@reopt-ai/data-contract 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/client.cjs +228 -321
  2. package/dist/client.cjs.map +1 -1
  3. package/dist/client.d.cts +57 -71
  4. package/dist/client.d.cts.map +1 -0
  5. package/dist/client.d.ts +57 -71
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +228 -322
  8. package/dist/client.js.map +1 -1
  9. package/dist/control.cjs +158 -54
  10. package/dist/control.cjs.map +1 -1
  11. package/dist/control.d.cts +124 -140
  12. package/dist/control.d.cts.map +1 -0
  13. package/dist/control.d.ts +124 -140
  14. package/dist/control.d.ts.map +1 -0
  15. package/dist/control.js +134 -54
  16. package/dist/control.js.map +1 -1
  17. package/dist/events-BUIeU60t.d.cts +142 -0
  18. package/dist/events-BUIeU60t.d.cts.map +1 -0
  19. package/dist/events-BUIeU60t.d.ts +142 -0
  20. package/dist/events-BUIeU60t.d.ts.map +1 -0
  21. package/dist/events.cjs +110 -15
  22. package/dist/events.cjs.map +1 -1
  23. package/dist/events.d.cts +2 -59
  24. package/dist/events.d.ts +2 -59
  25. package/dist/events.js +101 -15
  26. package/dist/events.js.map +1 -1
  27. package/dist/identity.cjs +150 -55
  28. package/dist/identity.cjs.map +1 -1
  29. package/dist/identity.d.cts +21 -20
  30. package/dist/identity.d.cts.map +1 -0
  31. package/dist/identity.d.ts +21 -20
  32. package/dist/identity.d.ts.map +1 -0
  33. package/dist/identity.js +126 -56
  34. package/dist/identity.js.map +1 -1
  35. package/dist/index.cjs +46 -25
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +37 -54
  38. package/dist/index.d.cts.map +1 -0
  39. package/dist/index.d.ts +37 -54
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +36 -25
  42. package/dist/index.js.map +1 -1
  43. package/dist/ingest.cjs +152 -57
  44. package/dist/ingest.cjs.map +1 -1
  45. package/dist/ingest.d.cts +185 -196
  46. package/dist/ingest.d.cts.map +1 -0
  47. package/dist/ingest.d.ts +185 -196
  48. package/dist/ingest.d.ts.map +1 -0
  49. package/dist/ingest.js +126 -57
  50. package/dist/ingest.js.map +1 -1
  51. package/dist/query.cjs +284 -84
  52. package/dist/query.cjs.map +1 -1
  53. package/dist/query.d.cts +458 -471
  54. package/dist/query.d.cts.map +1 -0
  55. package/dist/query.d.ts +458 -471
  56. package/dist/query.d.ts.map +1 -0
  57. package/dist/query.js +245 -84
  58. package/dist/query.js.map +1 -1
  59. package/dist/report.cjs +104 -74
  60. package/dist/report.cjs.map +1 -1
  61. package/dist/report.d.cts +182 -136
  62. package/dist/report.d.cts.map +1 -0
  63. package/dist/report.d.ts +182 -136
  64. package/dist/report.d.ts.map +1 -0
  65. package/dist/report.js +93 -74
  66. package/dist/report.js.map +1 -1
  67. package/dist/version-B_0qb1_K.cjs +53 -0
  68. package/dist/version-B_0qb1_K.cjs.map +1 -0
  69. package/dist/version-C09Cyf4R.js +12 -0
  70. package/dist/version-C09Cyf4R.js.map +1 -0
  71. package/dist/{version-BANKB6Og.d.ts → version-CGujUGWd.d.cts} +5 -3
  72. package/dist/version-CGujUGWd.d.cts.map +1 -0
  73. package/dist/{version-BANKB6Og.d.cts → version-CGujUGWd.d.ts} +5 -3
  74. package/dist/version-CGujUGWd.d.ts.map +1 -0
  75. package/package.json +69 -28
  76. package/dist/chunk-33BCA2LH.js +0 -53
  77. package/dist/chunk-33BCA2LH.js.map +0 -1
  78. package/dist/chunk-3EEANNYN.cjs +0 -62
  79. package/dist/chunk-3EEANNYN.cjs.map +0 -1
  80. package/dist/chunk-AOS53KAV.cjs +0 -19
  81. package/dist/chunk-AOS53KAV.cjs.map +0 -1
  82. package/dist/chunk-BA52YA7N.cjs +0 -179
  83. package/dist/chunk-BA52YA7N.cjs.map +0 -1
  84. package/dist/chunk-DUJSYMYY.js +0 -179
  85. package/dist/chunk-DUJSYMYY.js.map +0 -1
  86. package/dist/chunk-FMOKJTQD.js +0 -160
  87. package/dist/chunk-FMOKJTQD.js.map +0 -1
  88. package/dist/chunk-FP2X3PRK.js +0 -62
  89. package/dist/chunk-FP2X3PRK.js.map +0 -1
  90. package/dist/chunk-FQSCQSMP.cjs +0 -160
  91. package/dist/chunk-FQSCQSMP.cjs.map +0 -1
  92. package/dist/chunk-FUGY5ANJ.cjs +0 -361
  93. package/dist/chunk-FUGY5ANJ.cjs.map +0 -1
  94. package/dist/chunk-IY4MXH35.js +0 -204
  95. package/dist/chunk-IY4MXH35.js.map +0 -1
  96. package/dist/chunk-L3WJGIKD.js +0 -361
  97. package/dist/chunk-L3WJGIKD.js.map +0 -1
  98. package/dist/chunk-LA5F5KR6.cjs +0 -204
  99. package/dist/chunk-LA5F5KR6.cjs.map +0 -1
  100. package/dist/chunk-YSAEOYPD.cjs +0 -53
  101. package/dist/chunk-YSAEOYPD.cjs.map +0 -1
  102. package/dist/chunk-ZCKVMUIQ.js +0 -19
  103. package/dist/chunk-ZCKVMUIQ.js.map +0 -1
package/dist/identity.js CHANGED
@@ -1,57 +1,127 @@
1
- import {
2
- COOKIE_MAX_AGE_SECONDS,
3
- IDENTITY_ID_PATTERN,
4
- IDENTITY_REQUEST_HEADERS,
5
- OPT_OUT_CONSENT_CATEGORY,
6
- SESSION_HEADER_SEPARATOR,
7
- SESSION_ID_HEADER,
8
- consentCookieName,
9
- deviceCookieName,
10
- formatSessionHeader,
11
- isOptedOut,
12
- isValidIdentityId,
13
- parseConsentCookie,
14
- parseDeviceCookie,
15
- parseSessionHeader,
16
- serializeConsentCookie,
17
- serializeDeviceCookie,
18
- signSessionToken,
19
- verifySessionToken
20
- } from "./chunk-FMOKJTQD.js";
21
- import {
22
- CLIENT_ID_HEADER,
23
- CLIENT_SECRET_HEADER,
24
- CONTRACT_VERSION,
25
- CONTRACT_VERSION_HEADER,
26
- DEVICE_ID_HEADER,
27
- REQUEST_ID_HEADER,
28
- WRITE_KEY_HEADER
29
- } from "./chunk-ZCKVMUIQ.js";
30
- export {
31
- CLIENT_ID_HEADER,
32
- CLIENT_SECRET_HEADER,
33
- CONTRACT_VERSION,
34
- CONTRACT_VERSION_HEADER,
35
- COOKIE_MAX_AGE_SECONDS,
36
- DEVICE_ID_HEADER,
37
- IDENTITY_ID_PATTERN,
38
- IDENTITY_REQUEST_HEADERS,
39
- OPT_OUT_CONSENT_CATEGORY,
40
- REQUEST_ID_HEADER,
41
- SESSION_HEADER_SEPARATOR,
42
- SESSION_ID_HEADER,
43
- WRITE_KEY_HEADER,
44
- consentCookieName,
45
- deviceCookieName,
46
- formatSessionHeader,
47
- isOptedOut,
48
- isValidIdentityId,
49
- parseConsentCookie,
50
- parseDeviceCookie,
51
- parseSessionHeader,
52
- serializeConsentCookie,
53
- serializeDeviceCookie,
54
- signSessionToken,
55
- verifySessionToken
56
- };
1
+ import { a as DEVICE_ID_HEADER, i as CONTRACT_VERSION_HEADER, n as CLIENT_SECRET_HEADER, o as REQUEST_ID_HEADER, r as CONTRACT_VERSION, s as WRITE_KEY_HEADER, t as CLIENT_ID_HEADER } from "./version-C09Cyf4R.js";
2
+ //#region src/identity.ts
3
+ const SESSION_ID_HEADER = "reopt-session-id";
4
+ const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER];
5
+ const COOKIE_MAX_AGE_SECONDS = 3456e4;
6
+ const OPT_OUT_CONSENT_CATEGORY = "analytics";
7
+ const COOKIE_PREFIX = "reopt_";
8
+ function cookieSafe(writeKey) {
9
+ if (!writeKey) throw new Error("[reopt] writeKey is required to derive cookie names");
10
+ return writeKey.replace(/[^A-Za-z0-9_-]/g, "_");
11
+ }
12
+ function deviceCookieName(writeKey) {
13
+ return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;
14
+ }
15
+ function consentCookieName(writeKey) {
16
+ return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;
17
+ }
18
+ const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;
19
+ function isValidIdentityId(value) {
20
+ return typeof value === "string" && IDENTITY_ID_PATTERN.test(value);
21
+ }
22
+ function decode(raw) {
23
+ let text = raw;
24
+ for (let round = 0; round < 3 && /%[0-9A-Fa-f]{2}/.test(text); round++) {
25
+ try {
26
+ const next = decodeURIComponent(text);
27
+ if (next === text) break;
28
+ text = next;
29
+ } catch {
30
+ break;
31
+ }
32
+ if (text.startsWith("{")) break;
33
+ }
34
+ return text;
35
+ }
36
+ function parseDeviceCookie(raw) {
37
+ if (!raw) return null;
38
+ const text = decode(raw.trim());
39
+ if (!text) return null;
40
+ if (!text.startsWith("{")) return isValidIdentityId(text) ? { deviceId: text } : null;
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(text);
44
+ } catch {
45
+ return null;
46
+ }
47
+ if (typeof parsed !== "object" || parsed === null) return null;
48
+ const candidate = parsed;
49
+ if (!isValidIdentityId(candidate.deviceId)) return null;
50
+ const state = { deviceId: candidate.deviceId };
51
+ if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;
52
+ if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;
53
+ return state;
54
+ }
55
+ function serializeDeviceCookie(state) {
56
+ if (!isValidIdentityId(state.deviceId)) throw new Error("[reopt] deviceId must be a non-empty string without control characters");
57
+ const envelope = { deviceId: state.deviceId };
58
+ if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;
59
+ if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;
60
+ return encodeURIComponent(JSON.stringify(envelope));
61
+ }
62
+ function parseConsentCookie(raw) {
63
+ if (!raw) return null;
64
+ const text = decode(raw.trim());
65
+ if (!text.startsWith("{")) return null;
66
+ let parsed;
67
+ try {
68
+ parsed = JSON.parse(text);
69
+ } catch {
70
+ return null;
71
+ }
72
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
73
+ const state = {};
74
+ for (const [category, decision] of Object.entries(parsed)) if (typeof decision === "boolean" && isValidIdentityId(category)) state[category] = decision;
75
+ return state;
76
+ }
77
+ function serializeConsentCookie(state) {
78
+ const clean = {};
79
+ for (const [category, decision] of Object.entries(state)) if (typeof decision === "boolean" && isValidIdentityId(category)) clean[category] = decision;
80
+ return encodeURIComponent(JSON.stringify(clean));
81
+ }
82
+ function isOptedOut(consent) {
83
+ return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;
84
+ }
85
+ const SESSION_HEADER_SEPARATOR = ".";
86
+ function formatSessionHeader(credential) {
87
+ return `${credential.id}.${credential.token}`;
88
+ }
89
+ function parseSessionHeader(value) {
90
+ if (!value) return null;
91
+ const at = value.lastIndexOf(".");
92
+ if (at <= 0 || at === value.length - 1) return null;
93
+ const id = value.slice(0, at);
94
+ const token = value.slice(at + 1);
95
+ return isValidIdentityId(id) && /^[A-Za-z0-9_-]{43}$/.test(token) ? {
96
+ id,
97
+ token
98
+ } : null;
99
+ }
100
+ const encoder = new TextEncoder();
101
+ function base64url(bytes) {
102
+ let binary = "";
103
+ for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
104
+ return (typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
105
+ }
106
+ async function hmacKey(secret) {
107
+ return crypto.subtle.importKey("raw", encoder.encode(secret), {
108
+ name: "HMAC",
109
+ hash: "SHA-256"
110
+ }, false, ["sign"]);
111
+ }
112
+ async function signSessionToken(secret, sessionId) {
113
+ if (!secret) throw new Error("[reopt] a session signing secret is required");
114
+ return base64url(await crypto.subtle.sign("HMAC", await hmacKey(secret), encoder.encode(sessionId)));
115
+ }
116
+ async function verifySessionToken(secret, credential) {
117
+ if (!secret || !credential) return false;
118
+ const expected = await signSessionToken(secret, credential.id);
119
+ if (expected.length !== credential.token.length) return false;
120
+ let diff = 0;
121
+ for (let index = 0; index < expected.length; index++) diff |= expected.charCodeAt(index) ^ credential.token.charCodeAt(index);
122
+ return diff === 0;
123
+ }
124
+ //#endregion
125
+ export { CLIENT_ID_HEADER, CLIENT_SECRET_HEADER, CONTRACT_VERSION, CONTRACT_VERSION_HEADER, COOKIE_MAX_AGE_SECONDS, DEVICE_ID_HEADER, IDENTITY_ID_PATTERN, IDENTITY_REQUEST_HEADERS, OPT_OUT_CONSENT_CATEGORY, REQUEST_ID_HEADER, SESSION_HEADER_SEPARATOR, SESSION_ID_HEADER, WRITE_KEY_HEADER, consentCookieName, deviceCookieName, formatSessionHeader, isOptedOut, isValidIdentityId, parseConsentCookie, parseDeviceCookie, parseSessionHeader, serializeConsentCookie, serializeDeviceCookie, signSessionToken, verifySessionToken };
126
+
57
127
  //# sourceMappingURL=identity.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"file":"identity.js","names":[],"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/**\n * `reopt_<writeKey>_device` — device id plus session/profile hints.\n *\n * The write key is **sanitized**: any character outside `[A-Za-z0-9_-]`\n * becomes `_` (see `cookieSafe`), so do not derive prefix/suffix pieces by\n * probing this with a marker character — the marker is folded too. Always\n * call this with the real write key and compare whole names.\n */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. Same sanitizing as `deviceCookieName`. */\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 | undefined;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string | undefined;\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\n/**\n * Decodes the envelope. Tolerates one extra layer (`%257B…`) — a cookie\n * setter that encodes an already-encoded value is a mistake we have shipped\n * once, and a visitor's identity should survive it rather than be reminted.\n */\nfunction decode(raw: string): string {\n let text = raw;\n for (let round = 0; round < 3 && /%[0-9A-Fa-f]{2}/.test(text); round++) {\n try {\n const next = decodeURIComponent(text);\n if (next === text) break;\n text = next;\n } catch {\n break;\n }\n if (text.startsWith(\"{\")) break;\n }\n return text;\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":"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"}
package/dist/index.cjs CHANGED
@@ -1,27 +1,48 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_version = require("./version-B_0qb1_K.cjs");
3
+ let zod = require("zod");
4
+ //#region src/index.ts
5
+ const zDate = zod.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD").refine(isRealCalendarDate, "date does not exist");
6
+ function isRealCalendarDate(value) {
7
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
8
+ const [year, month, day] = value.split("-").map(Number);
9
+ const instant = new Date(Date.UTC(year, month - 1, day));
10
+ return instant.getUTCFullYear() === year && instant.getUTCMonth() === month - 1 && instant.getUTCDate() === day;
11
+ }
12
+ const zInstant = zod.z.string().min(20);
13
+ var DataApiError = class DataApiError extends Error {
14
+ isDataApiError = true;
15
+ status;
16
+ code;
17
+ requestId;
18
+ retryAfterMs;
19
+ details;
20
+ constructor(init) {
21
+ super(init.message);
22
+ this.name = "DataApiError";
23
+ this.status = init.status;
24
+ this.code = init.code;
25
+ this.requestId = init.requestId;
26
+ this.retryAfterMs = init.retryAfterMs;
27
+ this.details = init.details;
28
+ }
29
+ get retryable() {
30
+ return this.status === 429 || this.status >= 500;
31
+ }
32
+ static is(value) {
33
+ return value instanceof DataApiError || typeof value === "object" && value !== null && value.isDataApiError === true;
34
+ }
35
+ };
36
+ //#endregion
37
+ exports.CLIENT_ID_HEADER = require_version.CLIENT_ID_HEADER;
38
+ exports.CLIENT_SECRET_HEADER = require_version.CLIENT_SECRET_HEADER;
39
+ exports.CONTRACT_VERSION = require_version.CONTRACT_VERSION;
40
+ exports.CONTRACT_VERSION_HEADER = require_version.CONTRACT_VERSION_HEADER;
41
+ exports.DEVICE_ID_HEADER = require_version.DEVICE_ID_HEADER;
42
+ exports.DataApiError = DataApiError;
43
+ exports.REQUEST_ID_HEADER = require_version.REQUEST_ID_HEADER;
44
+ exports.WRITE_KEY_HEADER = require_version.WRITE_KEY_HEADER;
45
+ exports.zDate = zDate;
46
+ exports.zInstant = zInstant;
2
47
 
3
-
4
-
5
- var _chunkYSAEOYPDcjs = require('./chunk-YSAEOYPD.cjs');
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
- var _chunkAOS53KAVcjs = require('./chunk-AOS53KAV.cjs');
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
- exports.CLIENT_ID_HEADER = _chunkAOS53KAVcjs.CLIENT_ID_HEADER; exports.CLIENT_SECRET_HEADER = _chunkAOS53KAVcjs.CLIENT_SECRET_HEADER; exports.CONTRACT_VERSION = _chunkAOS53KAVcjs.CONTRACT_VERSION; exports.CONTRACT_VERSION_HEADER = _chunkAOS53KAVcjs.CONTRACT_VERSION_HEADER; exports.DEVICE_ID_HEADER = _chunkAOS53KAVcjs.DEVICE_ID_HEADER; exports.DataApiError = _chunkYSAEOYPDcjs.DataApiError; exports.REQUEST_ID_HEADER = _chunkAOS53KAVcjs.REQUEST_ID_HEADER; exports.WRITE_KEY_HEADER = _chunkAOS53KAVcjs.WRITE_KEY_HEADER; exports.zDate = _chunkYSAEOYPDcjs.zDate; exports.zInstant = _chunkYSAEOYPDcjs.zInstant;
27
48
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,+lBAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/index.cjs"}
1
+ {"version":3,"file":"index.cjs","names":["z"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reopt-ai/data-contract` — the wire contract between reopt-data and its\n * server-credential consumers (RFC-0023).\n *\n * Subpaths:\n * `@reopt-ai/data-contract` this module — version, shared primitives, errors\n * `@reopt-ai/data-contract/ingest` POST /api/track request + response schemas\n * `@reopt-ai/data-contract/query` POST /api/v1/query/* request + response schemas\n * `@reopt-ai/data-contract/control` provisioning request + response schemas\n * `@reopt-ai/data-contract/client` createDataClient() — typed fetch over all\n * `@reopt-ai/data-contract/events` event names + property keys (no zod)\n * `@reopt-ai/data-contract/identity` cookie/header names and encodings shared by\n * the SDKs, the Next.js proxy and ingest\n *\n * Only `/client` touches `fetch`; everything else is pure zod. The single\n * runtime dependency is zod, deliberately — consumers bundle this.\n */\nimport { z } from \"zod\";\n\nexport {\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n WRITE_KEY_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n} from \"./version.js\";\n\n/**\n * A real calendar date. The query's resolved IANA zone decides which instants\n * its inclusive day covers.\n */\nexport const zDate = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, \"expected YYYY-MM-DD\")\n .refine(isRealCalendarDate, \"date does not exist\");\n\nfunction isRealCalendarDate(value: string): boolean {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return false;\n const [year, month, day] = value.split(\"-\").map(Number);\n const instant = new Date(Date.UTC(year!, month! - 1, day!));\n return instant.getUTCFullYear() === year && instant.getUTCMonth() === month! - 1 && instant.getUTCDate() === day;\n}\n\n/** ISO-8601 instant, as produced by `Date#toISOString()`. */\nexport const zInstant = z.string().min(20);\n\n/**\n * Client credentials. The same pair authenticates both planes; what a given\n * client may reach is decided server-side by `Client.scopes`\n * (`\"ingest\"` / `\"query\"` / `\"provision\"`).\n */\nexport interface ClientCredentials {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Credentials are optional on the client itself because the provisioning\n * surface does not use them — it authenticates per call with a platform or\n * organization key. A caller that only provisions should not have to invent an\n * empty client id to satisfy a constructor.\n *\n * Reaching ingest or query without them fails with `credentials_missing`\n * rather than sending an unauthenticated request and reporting the 401 as a\n * server problem.\n */\nexport type OptionalClientCredentials = Partial<ClientCredentials>;\n\n/**\n * Every non-2xx response from either plane, plus the two failures the client\n * itself raises (`contract_mismatch`, `network_error`).\n */\nexport class DataApiError extends Error {\n /**\n * Brand for {@link DataApiError.is}. A bundler that inlines this module into\n * more than one entry point produces two distinct classes, and `instanceof`\n * silently stops matching — the brand survives that, and realm boundaries.\n */\n readonly isDataApiError = true as const;\n\n readonly status: number;\n readonly code: string;\n readonly requestId?: string | undefined;\n /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */\n readonly retryAfterMs?: number | undefined;\n /** zod issues for `validation_failed`, or the raw body when unparseable. */\n readonly details?: unknown | undefined;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n requestId?: string | undefined;\n retryAfterMs?: number | undefined;\n details?: unknown | undefined;\n }) {\n super(init.message);\n this.name = \"DataApiError\";\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId;\n this.retryAfterMs = init.retryAfterMs;\n this.details = init.details;\n }\n\n /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */\n get retryable(): boolean {\n return this.status === 429 || this.status >= 500;\n }\n\n /**\n * Prefer this over `instanceof` in a `catch`. It holds even when the class\n * has been duplicated — across CJS entry points, across bundler chunks, or\n * across realms — where `instanceof` quietly returns false.\n */\n static is(value: unknown): value is DataApiError {\n return (\n value instanceof DataApiError ||\n (typeof value === \"object\" && value !== null && (value as { isDataApiError?: unknown }).isDataApiError === true)\n );\n }\n}\n"],"mappings":";;;;AAiCA,MAAa,QAAQA,IAAAA,EAClB,OAAO,CAAC,CACR,MAAM,uBAAuB,qBAAqB,CAAC,CACnD,OAAO,oBAAoB,qBAAqB;AAEnD,SAAS,mBAAmB,OAAwB;CAClD,IAAI,CAAC,sBAAsB,KAAK,KAAK,GAAG,OAAO;CAC/C,MAAM,CAAC,MAAM,OAAO,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CACtD,MAAM,UAAU,IAAI,KAAK,KAAK,IAAI,MAAO,QAAS,GAAG,GAAI,CAAC;CAC1D,OAAO,QAAQ,eAAe,MAAM,QAAQ,QAAQ,YAAY,MAAM,QAAS,KAAK,QAAQ,WAAW,MAAM;AAC/G;AAGA,MAAa,WAAWA,IAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE;AA4BzC,IAAa,eAAb,MAAa,qBAAqB,MAAM;CAMtC,iBAA0B;CAE1B;CACA;CACA;CAEA;CAEA;CAEA,YAAY,MAOT;EACD,MAAM,KAAK,OAAO;EAClB,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;EACjB,KAAK,YAAY,KAAK;EACtB,KAAK,eAAe,KAAK;EACzB,KAAK,UAAU,KAAK;CACtB;CAGA,IAAI,YAAqB;EACvB,OAAO,KAAK,WAAW,OAAO,KAAK,UAAU;CAC/C;CAOA,OAAO,GAAG,OAAuC;EAC/C,OACE,iBAAiB,gBAChB,OAAO,UAAU,YAAY,UAAU,QAAS,MAAuC,mBAAmB;CAE/G;AACF"}
package/dist/index.d.cts CHANGED
@@ -1,24 +1,6 @@
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-BANKB6Og.cjs';
3
-
4
- /**
5
- * `@reopt-ai/data-contract` — the wire contract between reopt-data and its
6
- * server-credential consumers (RFC-0023).
7
- *
8
- * Subpaths:
9
- * `@reopt-ai/data-contract` this module — version, shared primitives, errors
10
- * `@reopt-ai/data-contract/ingest` POST /api/track request + response schemas
11
- * `@reopt-ai/data-contract/query` POST /api/v1/query/* request + response schemas
12
- * `@reopt-ai/data-contract/control` provisioning request + response schemas
13
- * `@reopt-ai/data-contract/client` createDataClient() — typed fetch over all
14
- * `@reopt-ai/data-contract/events` event names + property keys (no zod)
15
- * `@reopt-ai/data-contract/identity` cookie/header names and encodings shared by
16
- * the SDKs, the Next.js proxy and ingest
17
- *
18
- * Only `/client` touches `fetch`; everything else is pure zod. The single
19
- * runtime dependency is zod, deliberately — consumers bundle this.
20
- */
21
-
1
+ import { a as DEVICE_ID_HEADER, i as CONTRACT_VERSION_HEADER, n as CLIENT_SECRET_HEADER, o as REQUEST_ID_HEADER, r as CONTRACT_VERSION, s as WRITE_KEY_HEADER, t as CLIENT_ID_HEADER } from "./version-CGujUGWd.cjs";
2
+ import { z } from "zod";
3
+ //#region src/index.d.ts
22
4
  /**
23
5
  * A real calendar date. The query's resolved IANA zone decides which instants
24
6
  * its inclusive day covers.
@@ -32,8 +14,8 @@ declare const zInstant: z.ZodString;
32
14
  * (`"ingest"` / `"query"` / `"provision"`).
33
15
  */
34
16
  interface ClientCredentials {
35
- clientId: string;
36
- clientSecret: string;
17
+ clientId: string;
18
+ clientSecret: string;
37
19
  }
38
20
  /**
39
21
  * Credentials are optional on the client itself because the provisioning
@@ -51,35 +33,36 @@ type OptionalClientCredentials = Partial<ClientCredentials>;
51
33
  * itself raises (`contract_mismatch`, `network_error`).
52
34
  */
53
35
  declare class DataApiError extends Error {
54
- /**
55
- * Brand for {@link DataApiError.is}. A bundler that inlines this module into
56
- * more than one entry point produces two distinct classes, and `instanceof`
57
- * silently stops matching — the brand survives that, and realm boundaries.
58
- */
59
- readonly isDataApiError: true;
60
- readonly status: number;
61
- readonly code: string;
62
- readonly requestId?: string;
63
- /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */
64
- readonly retryAfterMs?: number;
65
- /** zod issues for `validation_failed`, or the raw body when unparseable. */
66
- readonly details?: unknown;
67
- constructor(init: {
68
- message: string;
69
- status: number;
70
- code: string;
71
- requestId?: string;
72
- retryAfterMs?: number;
73
- details?: unknown;
74
- });
75
- /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */
76
- get retryable(): boolean;
77
- /**
78
- * Prefer this over `instanceof` in a `catch`. It holds even when the class
79
- * has been duplicated — across CJS entry points, across bundler chunks, or
80
- * across realms — where `instanceof` quietly returns false.
81
- */
82
- static is(value: unknown): value is DataApiError;
36
+ /**
37
+ * Brand for {@link DataApiError.is}. A bundler that inlines this module into
38
+ * more than one entry point produces two distinct classes, and `instanceof`
39
+ * silently stops matching — the brand survives that, and realm boundaries.
40
+ */
41
+ readonly isDataApiError: true;
42
+ readonly status: number;
43
+ readonly code: string;
44
+ readonly requestId?: string | undefined;
45
+ /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */
46
+ readonly retryAfterMs?: number | undefined;
47
+ /** zod issues for `validation_failed`, or the raw body when unparseable. */
48
+ readonly details?: unknown | undefined;
49
+ constructor(init: {
50
+ message: string;
51
+ status: number;
52
+ code: string;
53
+ requestId?: string | undefined;
54
+ retryAfterMs?: number | undefined;
55
+ details?: unknown | undefined;
56
+ });
57
+ /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */
58
+ get retryable(): boolean;
59
+ /**
60
+ * Prefer this over `instanceof` in a `catch`. It holds even when the class
61
+ * has been duplicated — across CJS entry points, across bundler chunks, or
62
+ * across realms — where `instanceof` quietly returns false.
63
+ */
64
+ static is(value: unknown): value is DataApiError;
83
65
  }
84
-
85
- export { type ClientCredentials, DataApiError, type OptionalClientCredentials, zDate, zInstant };
66
+ //#endregion
67
+ export { CLIENT_ID_HEADER, CLIENT_SECRET_HEADER, CONTRACT_VERSION, CONTRACT_VERSION_HEADER, ClientCredentials, DEVICE_ID_HEADER, DataApiError, OptionalClientCredentials, REQUEST_ID_HEADER, WRITE_KEY_HEADER, zDate, zInstant };
68
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;cAiCa,OAAK,EAAA;;cAaL,UAAQ,EAAA;;;;;;UAOJ;EACf;EACA;;;;;;;;;;;;KAaU,4BAA4B,QAAQ;;;;;cAMnC,qBAAqB;;;;;;WAMvB;WAEA;WACA;WACA;;WAEA;;WAEA;EAEG,YAAA;IACV;IACA;IACA;IACA;IACA;IACA;;;MAYE;;;;;;SASG,GAAG,iBAAiB,SAAS"}
package/dist/index.d.ts CHANGED
@@ -1,24 +1,6 @@
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-BANKB6Og.js';
3
-
4
- /**
5
- * `@reopt-ai/data-contract` — the wire contract between reopt-data and its
6
- * server-credential consumers (RFC-0023).
7
- *
8
- * Subpaths:
9
- * `@reopt-ai/data-contract` this module — version, shared primitives, errors
10
- * `@reopt-ai/data-contract/ingest` POST /api/track request + response schemas
11
- * `@reopt-ai/data-contract/query` POST /api/v1/query/* request + response schemas
12
- * `@reopt-ai/data-contract/control` provisioning request + response schemas
13
- * `@reopt-ai/data-contract/client` createDataClient() — typed fetch over all
14
- * `@reopt-ai/data-contract/events` event names + property keys (no zod)
15
- * `@reopt-ai/data-contract/identity` cookie/header names and encodings shared by
16
- * the SDKs, the Next.js proxy and ingest
17
- *
18
- * Only `/client` touches `fetch`; everything else is pure zod. The single
19
- * runtime dependency is zod, deliberately — consumers bundle this.
20
- */
21
-
1
+ import { a as DEVICE_ID_HEADER, i as CONTRACT_VERSION_HEADER, n as CLIENT_SECRET_HEADER, o as REQUEST_ID_HEADER, r as CONTRACT_VERSION, s as WRITE_KEY_HEADER, t as CLIENT_ID_HEADER } from "./version-CGujUGWd.js";
2
+ import { z } from "zod";
3
+ //#region src/index.d.ts
22
4
  /**
23
5
  * A real calendar date. The query's resolved IANA zone decides which instants
24
6
  * its inclusive day covers.
@@ -32,8 +14,8 @@ declare const zInstant: z.ZodString;
32
14
  * (`"ingest"` / `"query"` / `"provision"`).
33
15
  */
34
16
  interface ClientCredentials {
35
- clientId: string;
36
- clientSecret: string;
17
+ clientId: string;
18
+ clientSecret: string;
37
19
  }
38
20
  /**
39
21
  * Credentials are optional on the client itself because the provisioning
@@ -51,35 +33,36 @@ type OptionalClientCredentials = Partial<ClientCredentials>;
51
33
  * itself raises (`contract_mismatch`, `network_error`).
52
34
  */
53
35
  declare class DataApiError extends Error {
54
- /**
55
- * Brand for {@link DataApiError.is}. A bundler that inlines this module into
56
- * more than one entry point produces two distinct classes, and `instanceof`
57
- * silently stops matching — the brand survives that, and realm boundaries.
58
- */
59
- readonly isDataApiError: true;
60
- readonly status: number;
61
- readonly code: string;
62
- readonly requestId?: string;
63
- /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */
64
- readonly retryAfterMs?: number;
65
- /** zod issues for `validation_failed`, or the raw body when unparseable. */
66
- readonly details?: unknown;
67
- constructor(init: {
68
- message: string;
69
- status: number;
70
- code: string;
71
- requestId?: string;
72
- retryAfterMs?: number;
73
- details?: unknown;
74
- });
75
- /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */
76
- get retryable(): boolean;
77
- /**
78
- * Prefer this over `instanceof` in a `catch`. It holds even when the class
79
- * has been duplicated — across CJS entry points, across bundler chunks, or
80
- * across realms — where `instanceof` quietly returns false.
81
- */
82
- static is(value: unknown): value is DataApiError;
36
+ /**
37
+ * Brand for {@link DataApiError.is}. A bundler that inlines this module into
38
+ * more than one entry point produces two distinct classes, and `instanceof`
39
+ * silently stops matching — the brand survives that, and realm boundaries.
40
+ */
41
+ readonly isDataApiError: true;
42
+ readonly status: number;
43
+ readonly code: string;
44
+ readonly requestId?: string | undefined;
45
+ /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */
46
+ readonly retryAfterMs?: number | undefined;
47
+ /** zod issues for `validation_failed`, or the raw body when unparseable. */
48
+ readonly details?: unknown | undefined;
49
+ constructor(init: {
50
+ message: string;
51
+ status: number;
52
+ code: string;
53
+ requestId?: string | undefined;
54
+ retryAfterMs?: number | undefined;
55
+ details?: unknown | undefined;
56
+ });
57
+ /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */
58
+ get retryable(): boolean;
59
+ /**
60
+ * Prefer this over `instanceof` in a `catch`. It holds even when the class
61
+ * has been duplicated — across CJS entry points, across bundler chunks, or
62
+ * across realms — where `instanceof` quietly returns false.
63
+ */
64
+ static is(value: unknown): value is DataApiError;
83
65
  }
84
-
85
- export { type ClientCredentials, DataApiError, type OptionalClientCredentials, zDate, zInstant };
66
+ //#endregion
67
+ export { CLIENT_ID_HEADER, CLIENT_SECRET_HEADER, CONTRACT_VERSION, CONTRACT_VERSION_HEADER, ClientCredentials, DEVICE_ID_HEADER, DataApiError, OptionalClientCredentials, REQUEST_ID_HEADER, WRITE_KEY_HEADER, zDate, zInstant };
68
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;cAiCa,OAAK,EAAA;;cAaL,UAAQ,EAAA;;;;;;UAOJ;EACf;EACA;;;;;;;;;;;;KAaU,4BAA4B,QAAQ;;;;;cAMnC,qBAAqB;;;;;;WAMvB;WAEA;WACA;WACA;;WAEA;;WAEA;EAEG,YAAA;IACV;IACA;IACA;IACA;IACA;IACA;;;MAYE;;;;;;SASG,GAAG,iBAAiB,SAAS"}
package/dist/index.js CHANGED
@@ -1,27 +1,38 @@
1
- import {
2
- DataApiError,
3
- zDate,
4
- zInstant
5
- } from "./chunk-33BCA2LH.js";
6
- import {
7
- CLIENT_ID_HEADER,
8
- CLIENT_SECRET_HEADER,
9
- CONTRACT_VERSION,
10
- CONTRACT_VERSION_HEADER,
11
- DEVICE_ID_HEADER,
12
- REQUEST_ID_HEADER,
13
- WRITE_KEY_HEADER
14
- } from "./chunk-ZCKVMUIQ.js";
15
- export {
16
- CLIENT_ID_HEADER,
17
- CLIENT_SECRET_HEADER,
18
- CONTRACT_VERSION,
19
- CONTRACT_VERSION_HEADER,
20
- DEVICE_ID_HEADER,
21
- DataApiError,
22
- REQUEST_ID_HEADER,
23
- WRITE_KEY_HEADER,
24
- zDate,
25
- zInstant
1
+ import { a as DEVICE_ID_HEADER, i as CONTRACT_VERSION_HEADER, n as CLIENT_SECRET_HEADER, o as REQUEST_ID_HEADER, r as CONTRACT_VERSION, s as WRITE_KEY_HEADER, t as CLIENT_ID_HEADER } from "./version-C09Cyf4R.js";
2
+ import { z } from "zod";
3
+ //#region src/index.ts
4
+ const zDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD").refine(isRealCalendarDate, "date does not exist");
5
+ function isRealCalendarDate(value) {
6
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
7
+ const [year, month, day] = value.split("-").map(Number);
8
+ const instant = new Date(Date.UTC(year, month - 1, day));
9
+ return instant.getUTCFullYear() === year && instant.getUTCMonth() === month - 1 && instant.getUTCDate() === day;
10
+ }
11
+ const zInstant = z.string().min(20);
12
+ var DataApiError = class DataApiError extends Error {
13
+ isDataApiError = true;
14
+ status;
15
+ code;
16
+ requestId;
17
+ retryAfterMs;
18
+ details;
19
+ constructor(init) {
20
+ super(init.message);
21
+ this.name = "DataApiError";
22
+ this.status = init.status;
23
+ this.code = init.code;
24
+ this.requestId = init.requestId;
25
+ this.retryAfterMs = init.retryAfterMs;
26
+ this.details = init.details;
27
+ }
28
+ get retryable() {
29
+ return this.status === 429 || this.status >= 500;
30
+ }
31
+ static is(value) {
32
+ return value instanceof DataApiError || typeof value === "object" && value !== null && value.isDataApiError === true;
33
+ }
26
34
  };
35
+ //#endregion
36
+ export { CLIENT_ID_HEADER, CLIENT_SECRET_HEADER, CONTRACT_VERSION, CONTRACT_VERSION_HEADER, DEVICE_ID_HEADER, DataApiError, REQUEST_ID_HEADER, WRITE_KEY_HEADER, zDate, zInstant };
37
+
27
38
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reopt-ai/data-contract` — the wire contract between reopt-data and its\n * server-credential consumers (RFC-0023).\n *\n * Subpaths:\n * `@reopt-ai/data-contract` this module — version, shared primitives, errors\n * `@reopt-ai/data-contract/ingest` POST /api/track request + response schemas\n * `@reopt-ai/data-contract/query` POST /api/v1/query/* request + response schemas\n * `@reopt-ai/data-contract/control` provisioning request + response schemas\n * `@reopt-ai/data-contract/client` createDataClient() — typed fetch over all\n * `@reopt-ai/data-contract/events` event names + property keys (no zod)\n * `@reopt-ai/data-contract/identity` cookie/header names and encodings shared by\n * the SDKs, the Next.js proxy and ingest\n *\n * Only `/client` touches `fetch`; everything else is pure zod. The single\n * runtime dependency is zod, deliberately — consumers bundle this.\n */\nimport { z } from \"zod\";\n\nexport {\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n WRITE_KEY_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n} from \"./version.js\";\n\n/**\n * A real calendar date. The query's resolved IANA zone decides which instants\n * its inclusive day covers.\n */\nexport const zDate = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, \"expected YYYY-MM-DD\")\n .refine(isRealCalendarDate, \"date does not exist\");\n\nfunction isRealCalendarDate(value: string): boolean {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return false;\n const [year, month, day] = value.split(\"-\").map(Number);\n const instant = new Date(Date.UTC(year!, month! - 1, day!));\n return instant.getUTCFullYear() === year && instant.getUTCMonth() === month! - 1 && instant.getUTCDate() === day;\n}\n\n/** ISO-8601 instant, as produced by `Date#toISOString()`. */\nexport const zInstant = z.string().min(20);\n\n/**\n * Client credentials. The same pair authenticates both planes; what a given\n * client may reach is decided server-side by `Client.scopes`\n * (`\"ingest\"` / `\"query\"` / `\"provision\"`).\n */\nexport interface ClientCredentials {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Credentials are optional on the client itself because the provisioning\n * surface does not use them — it authenticates per call with a platform or\n * organization key. A caller that only provisions should not have to invent an\n * empty client id to satisfy a constructor.\n *\n * Reaching ingest or query without them fails with `credentials_missing`\n * rather than sending an unauthenticated request and reporting the 401 as a\n * server problem.\n */\nexport type OptionalClientCredentials = Partial<ClientCredentials>;\n\n/**\n * Every non-2xx response from either plane, plus the two failures the client\n * itself raises (`contract_mismatch`, `network_error`).\n */\nexport class DataApiError extends Error {\n /**\n * Brand for {@link DataApiError.is}. A bundler that inlines this module into\n * more than one entry point produces two distinct classes, and `instanceof`\n * silently stops matching — the brand survives that, and realm boundaries.\n */\n readonly isDataApiError = true as const;\n\n readonly status: number;\n readonly code: string;\n readonly requestId?: string | undefined;\n /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */\n readonly retryAfterMs?: number | undefined;\n /** zod issues for `validation_failed`, or the raw body when unparseable. */\n readonly details?: unknown | undefined;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n requestId?: string | undefined;\n retryAfterMs?: number | undefined;\n details?: unknown | undefined;\n }) {\n super(init.message);\n this.name = \"DataApiError\";\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId;\n this.retryAfterMs = init.retryAfterMs;\n this.details = init.details;\n }\n\n /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */\n get retryable(): boolean {\n return this.status === 429 || this.status >= 500;\n }\n\n /**\n * Prefer this over `instanceof` in a `catch`. It holds even when the class\n * has been duplicated — across CJS entry points, across bundler chunks, or\n * across realms — where `instanceof` quietly returns false.\n */\n static is(value: unknown): value is DataApiError {\n return (\n value instanceof DataApiError ||\n (typeof value === \"object\" && value !== null && (value as { isDataApiError?: unknown }).isDataApiError === true)\n );\n }\n}\n"],"mappings":";;;AAiCA,MAAa,QAAQ,EAClB,OAAO,CAAC,CACR,MAAM,uBAAuB,qBAAqB,CAAC,CACnD,OAAO,oBAAoB,qBAAqB;AAEnD,SAAS,mBAAmB,OAAwB;CAClD,IAAI,CAAC,sBAAsB,KAAK,KAAK,GAAG,OAAO;CAC/C,MAAM,CAAC,MAAM,OAAO,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CACtD,MAAM,UAAU,IAAI,KAAK,KAAK,IAAI,MAAO,QAAS,GAAG,GAAI,CAAC;CAC1D,OAAO,QAAQ,eAAe,MAAM,QAAQ,QAAQ,YAAY,MAAM,QAAS,KAAK,QAAQ,WAAW,MAAM;AAC/G;AAGA,MAAa,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE;AA4BzC,IAAa,eAAb,MAAa,qBAAqB,MAAM;CAMtC,iBAA0B;CAE1B;CACA;CACA;CAEA;CAEA;CAEA,YAAY,MAOT;EACD,MAAM,KAAK,OAAO;EAClB,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;EACjB,KAAK,YAAY,KAAK;EACtB,KAAK,eAAe,KAAK;EACzB,KAAK,UAAU,KAAK;CACtB;CAGA,IAAI,YAAqB;EACvB,OAAO,KAAK,WAAW,OAAO,KAAK,UAAU;CAC/C;CAOA,OAAO,GAAG,OAAuC;EAC/C,OACE,iBAAiB,gBAChB,OAAO,UAAU,YAAY,UAAU,QAAS,MAAuC,mBAAmB;CAE/G;AACF"}