@reopt-ai/data-contract 0.6.2 → 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 (55) hide show
  1. package/dist/{chunk-FMOKJTQD.js → chunk-7W33YGRO.js} +2 -2
  2. package/dist/chunk-7W33YGRO.js.map +1 -0
  3. package/dist/{chunk-AOS53KAV.cjs → chunk-F2RNXJGO.cjs} +2 -2
  4. package/dist/{chunk-AOS53KAV.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-FQSCQSMP.cjs → chunk-L3JPDRVG.cjs} +3 -3
  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-ZCKVMUIQ.js → chunk-PSUINLW7.js} +2 -2
  14. package/dist/{chunk-ZCKVMUIQ.js.map → chunk-PSUINLW7.js.map} +1 -1
  15. package/dist/{chunk-DUJSYMYY.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-BA52YA7N.cjs → chunk-ZI6A3WQP.cjs} +4 -4
  21. package/dist/{chunk-BA52YA7N.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.d.cts +6 -6
  30. package/dist/control.d.ts +6 -6
  31. package/dist/control.js +4 -4
  32. package/dist/identity.cjs +3 -3
  33. package/dist/identity.d.cts +3 -3
  34. package/dist/identity.d.ts +3 -3
  35. package/dist/identity.js +2 -2
  36. package/dist/index.cjs +3 -3
  37. package/dist/index.d.cts +7 -7
  38. package/dist/index.d.ts +7 -7
  39. package/dist/index.js +2 -2
  40. package/dist/ingest.cjs +4 -4
  41. package/dist/ingest.d.cts +6 -6
  42. package/dist/ingest.d.ts +6 -6
  43. package/dist/ingest.js +3 -3
  44. package/dist/query.cjs +4 -4
  45. package/dist/query.d.cts +5 -5
  46. package/dist/query.d.ts +5 -5
  47. package/dist/query.js +3 -3
  48. package/dist/{version-BANKB6Og.d.ts → version-DJ2Grb_N.d.cts} +1 -1
  49. package/dist/{version-BANKB6Og.d.cts → version-DJ2Grb_N.d.ts} +1 -1
  50. package/package.json +1 -1
  51. package/dist/chunk-FMOKJTQD.js.map +0 -1
  52. package/dist/chunk-FQSCQSMP.cjs.map +0 -1
  53. /package/dist/{chunk-IY4MXH35.js.map → chunk-L4KBQAOO.js.map} +0 -0
  54. /package/dist/{chunk-L3WJGIKD.js.map → chunk-NJ4JKNBX.js.map} +0 -0
  55. /package/dist/{chunk-DUJSYMYY.js.map → chunk-RU26QFM2.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  DEVICE_ID_HEADER
3
- } from "./chunk-ZCKVMUIQ.js";
3
+ } from "./chunk-PSUINLW7.js";
4
4
 
5
5
  // src/identity.ts
6
6
  var SESSION_ID_HEADER = "reopt-session-id";
@@ -157,4 +157,4 @@ export {
157
157
  signSessionToken,
158
158
  verifySessionToken
159
159
  };
160
- //# sourceMappingURL=chunk-FMOKJTQD.js.map
160
+ //# sourceMappingURL=chunk-7W33YGRO.js.map
@@ -0,0 +1 @@
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/**\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":";;;;;AAoCO,IAAM,oBAAoB;AAG1B,IAAM,2BAA2B,CAAC,kBAAkB,iBAAiB;AAMrE,IAAM,yBAAyB,MAAM,KAAK,KAAK;AAG/C,IAAM,2BAA2B;AAExC,IAAM,gBAAgB;AAOtB,SAAS,WAAW,UAA0B;AAC5C,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,SAAO,SAAS,QAAQ,mBAAmB,GAAG;AAChD;AAUO,SAAS,iBAAiB,UAA0B;AACzD,SAAO,GAAG,aAAa,GAAG,WAAW,QAAQ,CAAC;AAChD;AAGO,SAAS,kBAAkB,UAA0B;AAC1D,SAAO,GAAG,aAAa,GAAG,WAAW,QAAQ,CAAC;AAChD;AAsCO,IAAM,sBAAsB;AAE5B,SAAS,kBAAkB,OAAiC;AACjE,SAAO,OAAO,UAAU,YAAY,oBAAoB,KAAK,KAAK;AACpE;AAOA,SAAS,OAAO,KAAqB;AACnC,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,KAAK,IAAI,GAAG,SAAS;AACtE,QAAI;AACF,YAAM,OAAO,mBAAmB,IAAI;AACpC,UAAI,SAAS,KAAM;AACnB,aAAO;AAAA,IACT,QAAQ;AACN;AAAA,IACF;AACA,QAAI,KAAK,WAAW,GAAG,EAAG;AAAA,EAC5B;AACA,SAAO;AACT;AASO,SAAS,kBAAkB,KAA0D;AAC1F,MAAI,CAAC,IAA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AAI,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AACtE;AAEA,eAAe,QAAQ,QAAoC;AACzD,SAAO,OAAO,OAAO,UAAU,OAAO,QAAQ,OAAO,MAAM,GAAG,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;AAClH;AAGA,eAAsB,iBAAiB,QAAgB,WAAoC;AACzF,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,8CAA8C;AAC3E,QAAM,YAAY,MAAM,OAAO,OAAO,KAAK,QAAQ,MAAM,QAAQ,MAAM,GAAG,QAAQ,OAAO,SAAS,CAAC;AACnG,SAAO,UAAU,SAAS;AAC5B;AAOA,eAAsB,mBAAmB,QAAgB,YAAiD;AACxG,MAAI,CAAC,UAAU,CAAC,WAAY,QAAO;AACnC,QAAM,WAAW,MAAM,iBAAiB,QAAQ,WAAW,EAAE;AAC7D,MAAI,SAAS,WAAW,WAAW,MAAM,OAAQ,QAAO;AACxD,MAAI,OAAO;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,5 +1,5 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/version.ts
2
- var CONTRACT_VERSION = "0.6.2";
2
+ var CONTRACT_VERSION = "0.6.3";
3
3
  var CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
4
4
  var CLIENT_ID_HEADER = "reopt-client-id";
5
5
  var CLIENT_SECRET_HEADER = "reopt-client-secret";
@@ -16,4 +16,4 @@ var REQUEST_ID_HEADER = "x-request-id";
16
16
 
17
17
 
18
18
  exports.CONTRACT_VERSION = CONTRACT_VERSION; exports.CONTRACT_VERSION_HEADER = CONTRACT_VERSION_HEADER; exports.CLIENT_ID_HEADER = CLIENT_ID_HEADER; exports.CLIENT_SECRET_HEADER = CLIENT_SECRET_HEADER; exports.WRITE_KEY_HEADER = WRITE_KEY_HEADER; exports.DEVICE_ID_HEADER = DEVICE_ID_HEADER; exports.REQUEST_ID_HEADER = REQUEST_ID_HEADER;
19
- //# sourceMappingURL=chunk-AOS53KAV.cjs.map
19
+ //# sourceMappingURL=chunk-F2RNXJGO.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-AOS53KAV.cjs","../src/version.ts"],"names":[],"mappings":"AAAA;ACgBO,IAAM,iBAAA,EAAmB,OAAA;AAGzB,IAAM,wBAAA,EAA0B,0BAAA;AAGhC,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,qBAAA,EAAuB,qBAAA;AAC7B,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,kBAAA,EAAoB,cAAA;ADlBjC;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,kVAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-AOS53KAV.cjs","sourcesContent":[null,"/**\n * Wire version and header names — the part of the contract every party\n * needs and none of them should pay zod for. Both `.` and `./identity`\n * re-export these; browser bundles import them through `./identity` so the\n * schema modules stay out of the client graph.\n */\n\n/**\n * Contract version. Bumped on any breaking change to a schema in this package.\n * The server echoes the version it was built against in `x-reopt-contract-version`;\n * `createDataClient` surfaces a mismatch rather than guessing.\n *\n * Must equal the package version (`package-identity.test.ts` enforces it), so\n * every publish is a wire bump: consumers that check for exact equality —\n * every SDK — must upgrade in lockstep with the server.\n */\nexport const CONTRACT_VERSION = \"0.6.2\";\n\n/** Response header carrying the server's contract version. */\nexport const CONTRACT_VERSION_HEADER = \"x-reopt-contract-version\";\n\n/** Request header names shared by the ingest and query planes. */\nexport const CLIENT_ID_HEADER = \"reopt-client-id\";\nexport const CLIENT_SECRET_HEADER = \"reopt-client-secret\";\nexport const WRITE_KEY_HEADER = \"reopt-write-key\";\nexport const DEVICE_ID_HEADER = \"reopt-device-id\";\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n"]}
1
+ {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-F2RNXJGO.cjs","../src/version.ts"],"names":[],"mappings":"AAAA;ACgBO,IAAM,iBAAA,EAAmB,OAAA;AAGzB,IAAM,wBAAA,EAA0B,0BAAA;AAGhC,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,qBAAA,EAAuB,qBAAA;AAC7B,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,iBAAA,EAAmB,iBAAA;AACzB,IAAM,kBAAA,EAAoB,cAAA;ADlBjC;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,kVAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-F2RNXJGO.cjs","sourcesContent":[null,"/**\n * Wire version and header names — the part of the contract every party\n * needs and none of them should pay zod for. Both `.` and `./identity`\n * re-export these; browser bundles import them through `./identity` so the\n * schema modules stay out of the client graph.\n */\n\n/**\n * Contract version. Bumped on any breaking change to a schema in this package.\n * The server echoes the version it was built against in `x-reopt-contract-version`;\n * `createDataClient` surfaces a mismatch rather than guessing.\n *\n * Must equal the package version (`package-identity.test.ts` enforces it), so\n * every publish is a wire bump: consumers that check for exact equality —\n * every SDK — must upgrade in lockstep with the server.\n */\nexport const CONTRACT_VERSION = \"0.6.3\";\n\n/** Response header carrying the server's contract version. */\nexport const CONTRACT_VERSION_HEADER = \"x-reopt-contract-version\";\n\n/** Request header names shared by the ingest and query planes. */\nexport const CLIENT_ID_HEADER = \"reopt-client-id\";\nexport const CLIENT_SECRET_HEADER = \"reopt-client-secret\";\nexport const WRITE_KEY_HEADER = \"reopt-write-key\";\nexport const DEVICE_ID_HEADER = \"reopt-device-id\";\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n"]}
@@ -50,4 +50,4 @@ export {
50
50
  zInstant,
51
51
  DataApiError
52
52
  };
53
- //# sourceMappingURL=chunk-33BCA2LH.js.map
53
+ //# sourceMappingURL=chunk-JCEWUSUM.js.map
@@ -1 +1 @@
1
- {"version":3,"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;\n /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */\n readonly retryAfterMs?: number;\n /** zod issues for `validation_failed`, or the raw body when unparseable. */\n readonly details?: unknown;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n requestId?: string;\n retryAfterMs?: number;\n details?: unknown;\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":";AAiBA,SAAS,SAAS;AAgBX,IAAM,QAAQ,EAClB,OAAO,EACP,MAAM,uBAAuB,qBAAqB,EAClD,OAAO,oBAAoB,qBAAqB;AAEnD,SAAS,mBAAmB,OAAwB;AAClD,MAAI,CAAC,sBAAsB,KAAK,KAAK,EAAG,QAAO;AAC/C,QAAM,CAAC,MAAM,OAAO,GAAG,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI,MAAM;AACtD,QAAM,UAAU,IAAI,KAAK,KAAK,IAAI,MAAO,QAAS,GAAG,GAAI,CAAC;AAC1D,SAAO,QAAQ,eAAe,MAAM,QAAQ,QAAQ,YAAY,MAAM,QAAS,KAAK,QAAQ,WAAW,MAAM;AAC/G;AAGO,IAAM,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE;AA4BlC,IAAM,eAAN,MAAM,sBAAqB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7B,iBAAiB;AAAA,EAEjB;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAOT;AACD,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,OAAO,KAAK;AACjB,SAAK,YAAY,KAAK;AACtB,SAAK,eAAe,KAAK;AACzB,SAAK,UAAU,KAAK;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,YAAqB;AACvB,WAAO,KAAK,WAAW,OAAO,KAAK,UAAU;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,GAAG,OAAuC;AAC/C,WACE,iBAAiB,iBAChB,OAAO,UAAU,YAAY,UAAU,QAAS,MAAuC,mBAAmB;AAAA,EAE/G;AACF;","names":[]}
1
+ {"version":3,"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":";AAiBA,SAAS,SAAS;AAgBX,IAAM,QAAQ,EAClB,OAAO,EACP,MAAM,uBAAuB,qBAAqB,EAClD,OAAO,oBAAoB,qBAAqB;AAEnD,SAAS,mBAAmB,OAAwB;AAClD,MAAI,CAAC,sBAAsB,KAAK,KAAK,EAAG,QAAO;AAC/C,QAAM,CAAC,MAAM,OAAO,GAAG,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI,MAAM;AACtD,QAAM,UAAU,IAAI,KAAK,KAAK,IAAI,MAAO,QAAS,GAAG,GAAI,CAAC;AAC1D,SAAO,QAAQ,eAAe,MAAM,QAAQ,QAAQ,YAAY,MAAM,QAAS,KAAK,QAAQ,WAAW,MAAM;AAC/G;AAGO,IAAM,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE;AA4BlC,IAAM,eAAN,MAAM,sBAAqB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM7B,iBAAiB;AAAA,EAEjB;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAOT;AACD,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,OAAO,KAAK;AACjB,SAAK,YAAY,KAAK;AACtB,SAAK,eAAe,KAAK;AACzB,SAAK,UAAU,KAAK;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,YAAqB;AACvB,WAAO,KAAK,WAAW,OAAO,KAAK,UAAU;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,GAAG,OAAuC;AAC/C,WACE,iBAAiB,iBAChB,OAAO,UAAU,YAAY,UAAU,QAAS,MAAuC,mBAAmB;AAAA,EAE/G;AACF;","names":[]}
@@ -1,10 +1,10 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkAOS53KAVcjs = require('./chunk-AOS53KAV.cjs');
3
+ var _chunkF2RNXJGOcjs = require('./chunk-F2RNXJGO.cjs');
4
4
 
5
5
  // src/identity.ts
6
6
  var SESSION_ID_HEADER = "reopt-session-id";
7
- var IDENTITY_REQUEST_HEADERS = [_chunkAOS53KAVcjs.DEVICE_ID_HEADER, SESSION_ID_HEADER];
7
+ var IDENTITY_REQUEST_HEADERS = [_chunkF2RNXJGOcjs.DEVICE_ID_HEADER, SESSION_ID_HEADER];
8
8
  var COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;
9
9
  var OPT_OUT_CONSENT_CATEGORY = "analytics";
10
10
  var COOKIE_PREFIX = "reopt_";
@@ -157,4 +157,4 @@ async function verifySessionToken(secret, credential) {
157
157
 
158
158
 
159
159
  exports.SESSION_ID_HEADER = SESSION_ID_HEADER; exports.IDENTITY_REQUEST_HEADERS = IDENTITY_REQUEST_HEADERS; exports.COOKIE_MAX_AGE_SECONDS = COOKIE_MAX_AGE_SECONDS; exports.OPT_OUT_CONSENT_CATEGORY = OPT_OUT_CONSENT_CATEGORY; exports.deviceCookieName = deviceCookieName; exports.consentCookieName = consentCookieName; exports.IDENTITY_ID_PATTERN = IDENTITY_ID_PATTERN; exports.isValidIdentityId = isValidIdentityId; exports.parseDeviceCookie = parseDeviceCookie; exports.serializeDeviceCookie = serializeDeviceCookie; exports.parseConsentCookie = parseConsentCookie; exports.serializeConsentCookie = serializeConsentCookie; exports.isOptedOut = isOptedOut; exports.SESSION_HEADER_SEPARATOR = SESSION_HEADER_SEPARATOR; exports.formatSessionHeader = formatSessionHeader; exports.parseSessionHeader = parseSessionHeader; exports.signSessionToken = signSessionToken; exports.verifySessionToken = verifySessionToken;
160
- //# sourceMappingURL=chunk-FQSCQSMP.cjs.map
160
+ //# sourceMappingURL=chunk-L3JPDRVG.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-L3JPDRVG.cjs","../src/identity.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACgCO,IAAM,kBAAA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AA;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;AD3KU;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-L3JPDRVG.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/**\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"]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  zTimezone
3
- } from "./chunk-L3WJGIKD.js";
3
+ } from "./chunk-NJ4JKNBX.js";
4
4
  import {
5
5
  zInstant
6
- } from "./chunk-33BCA2LH.js";
6
+ } from "./chunk-JCEWUSUM.js";
7
7
 
8
8
  // src/control.ts
9
9
  import { z } from "zod";
@@ -201,4 +201,4 @@ export {
201
201
  zControlError,
202
202
  CONTROL_API_PATHS
203
203
  };
204
- //# sourceMappingURL=chunk-IY4MXH35.js.map
204
+ //# sourceMappingURL=chunk-L4KBQAOO.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  zDate,
3
3
  zInstant
4
- } from "./chunk-33BCA2LH.js";
4
+ } from "./chunk-JCEWUSUM.js";
5
5
 
6
6
  // src/query.ts
7
7
  import { z } from "zod";
@@ -358,4 +358,4 @@ export {
358
358
  zQueryError,
359
359
  QUERY_API_PATHS
360
360
  };
361
- //# sourceMappingURL=chunk-L3WJGIKD.js.map
361
+ //# sourceMappingURL=chunk-NJ4JKNBX.js.map
@@ -50,4 +50,4 @@ var DataApiError = (_class = class _DataApiError extends Error {
50
50
 
51
51
 
52
52
  exports.zDate = zDate; exports.zInstant = zInstant; exports.DataApiError = DataApiError;
53
- //# sourceMappingURL=chunk-YSAEOYPD.cjs.map
53
+ //# sourceMappingURL=chunk-ORNTN6AK.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-YSAEOYPD.cjs","../src/index.ts"],"names":[],"mappings":"AAAA;ACiBA,0BAAkB;AAgBX,IAAM,MAAA,EAAQ,MAAA,CAClB,MAAA,CAAO,CAAA,CACP,KAAA,CAAM,qBAAA,EAAuB,qBAAqB,CAAA,CAClD,MAAA,CAAO,kBAAA,EAAoB,qBAAqB,CAAA;AAEnD,SAAS,kBAAA,CAAmB,KAAA,EAAwB;AAClD,EAAA,GAAA,CAAI,CAAC,qBAAA,CAAsB,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AAC/C,EAAA,MAAM,CAAC,IAAA,EAAM,KAAA,EAAO,GAAG,EAAA,EAAI,KAAA,CAAM,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,MAAM,CAAA;AACtD,EAAA,MAAM,QAAA,EAAU,IAAI,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,IAAA,EAAO,MAAA,EAAS,CAAA,EAAG,GAAI,CAAC,CAAA;AAC1D,EAAA,OAAO,OAAA,CAAQ,cAAA,CAAe,EAAA,IAAM,KAAA,GAAQ,OAAA,CAAQ,WAAA,CAAY,EAAA,IAAM,MAAA,EAAS,EAAA,GAAK,OAAA,CAAQ,UAAA,CAAW,EAAA,IAAM,GAAA;AAC/G;AAGO,IAAM,SAAA,EAAW,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,EAAE,CAAA;AA4BlC,IAAM,aAAA,YAAN,MAAM,cAAA,QAAqB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAM7B,eAAA,EAAiB,KAAA;AAAA,EAEjB;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,WAAA,CAAY,IAAA,EAOT;AACD,IAAA,KAAA,CAAM,IAAA,CAAK,OAAO,qCAAA;AAClB,IAAA,IAAA,CAAK,KAAA,EAAO,cAAA;AACZ,IAAA,IAAA,CAAK,OAAA,EAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,KAAA,EAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,UAAA,EAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,aAAA,EAAe,IAAA,CAAK,YAAA;AACzB,IAAA,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,OAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,SAAA,CAAA,EAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,OAAA,IAAW,IAAA,GAAO,IAAA,CAAK,OAAA,GAAU,GAAA;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,EAAA,CAAG,KAAA,EAAuC;AAC/C,IAAA,OACE,MAAA,WAAiB,cAAA,GAChB,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,IAAU,KAAA,GAAS,KAAA,CAAuC,eAAA,IAAmB,IAAA;AAAA,EAE/G;AACF,UAAA;AD7EA;AACA;AACE;AACA;AACA;AACF,wFAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-YSAEOYPD.cjs","sourcesContent":[null,"/**\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;\n /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */\n readonly retryAfterMs?: number;\n /** zod issues for `validation_failed`, or the raw body when unparseable. */\n readonly details?: unknown;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n requestId?: string;\n retryAfterMs?: number;\n details?: unknown;\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"]}
1
+ {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-ORNTN6AK.cjs","../src/index.ts"],"names":[],"mappings":"AAAA;ACiBA,0BAAkB;AAgBX,IAAM,MAAA,EAAQ,MAAA,CAClB,MAAA,CAAO,CAAA,CACP,KAAA,CAAM,qBAAA,EAAuB,qBAAqB,CAAA,CAClD,MAAA,CAAO,kBAAA,EAAoB,qBAAqB,CAAA;AAEnD,SAAS,kBAAA,CAAmB,KAAA,EAAwB;AAClD,EAAA,GAAA,CA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vB,IAAA,OAAO,IAAA,CAAK,OAAA,IAAW,IAAA,GAAO,IAAA,CAAK,OAAA,GAAU,GAAA;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,EAAA,CAAG,KAAA,EAAuC;AAC/C,IAAA,OACE,MAAA,WAAiB,cAAA,GAChB,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,IAAU,KAAA,GAAS,KAAA,CAAuC,eAAA,IAAmB,IAAA;AAAA,EAE/G;AACF,UAAA;AD7EA;AACA;AACE;AACA;AACA;AACF,wFAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-ORNTN6AK.cjs","sourcesContent":[null,"/**\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"]}
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var CONTRACT_VERSION = "0.6.2";
2
+ var CONTRACT_VERSION = "0.6.3";
3
3
  var CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
4
4
  var CLIENT_ID_HEADER = "reopt-client-id";
5
5
  var CLIENT_SECRET_HEADER = "reopt-client-secret";
@@ -16,4 +16,4 @@ export {
16
16
  DEVICE_ID_HEADER,
17
17
  REQUEST_ID_HEADER
18
18
  };
19
- //# sourceMappingURL=chunk-ZCKVMUIQ.js.map
19
+ //# sourceMappingURL=chunk-PSUINLW7.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["/**\n * Wire version and header names — the part of the contract every party\n * needs and none of them should pay zod for. Both `.` and `./identity`\n * re-export these; browser bundles import them through `./identity` so the\n * schema modules stay out of the client graph.\n */\n\n/**\n * Contract version. Bumped on any breaking change to a schema in this package.\n * The server echoes the version it was built against in `x-reopt-contract-version`;\n * `createDataClient` surfaces a mismatch rather than guessing.\n *\n * Must equal the package version (`package-identity.test.ts` enforces it), so\n * every publish is a wire bump: consumers that check for exact equality —\n * every SDK — must upgrade in lockstep with the server.\n */\nexport const CONTRACT_VERSION = \"0.6.2\";\n\n/** Response header carrying the server's contract version. */\nexport const CONTRACT_VERSION_HEADER = \"x-reopt-contract-version\";\n\n/** Request header names shared by the ingest and query planes. */\nexport const CLIENT_ID_HEADER = \"reopt-client-id\";\nexport const CLIENT_SECRET_HEADER = \"reopt-client-secret\";\nexport const WRITE_KEY_HEADER = \"reopt-write-key\";\nexport const DEVICE_ID_HEADER = \"reopt-device-id\";\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n"],"mappings":";AAgBO,IAAM,mBAAmB;AAGzB,IAAM,0BAA0B;AAGhC,IAAM,mBAAmB;AACzB,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["/**\n * Wire version and header names — the part of the contract every party\n * needs and none of them should pay zod for. Both `.` and `./identity`\n * re-export these; browser bundles import them through `./identity` so the\n * schema modules stay out of the client graph.\n */\n\n/**\n * Contract version. Bumped on any breaking change to a schema in this package.\n * The server echoes the version it was built against in `x-reopt-contract-version`;\n * `createDataClient` surfaces a mismatch rather than guessing.\n *\n * Must equal the package version (`package-identity.test.ts` enforces it), so\n * every publish is a wire bump: consumers that check for exact equality —\n * every SDK — must upgrade in lockstep with the server.\n */\nexport const CONTRACT_VERSION = \"0.6.3\";\n\n/** Response header carrying the server's contract version. */\nexport const CONTRACT_VERSION_HEADER = \"x-reopt-contract-version\";\n\n/** Request header names shared by the ingest and query planes. */\nexport const CLIENT_ID_HEADER = \"reopt-client-id\";\nexport const CLIENT_SECRET_HEADER = \"reopt-client-secret\";\nexport const WRITE_KEY_HEADER = \"reopt-write-key\";\nexport const DEVICE_ID_HEADER = \"reopt-device-id\";\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n"],"mappings":";AAgBO,IAAM,mBAAmB;AAGzB,IAAM,0BAA0B;AAGhC,IAAM,mBAAmB;AACzB,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  IDENTITY_ID_PATTERN
3
- } from "./chunk-FMOKJTQD.js";
3
+ } from "./chunk-7W33YGRO.js";
4
4
  import {
5
5
  RESERVED_EVENT_NAMES
6
6
  } from "./chunk-FP2X3PRK.js";
@@ -176,4 +176,4 @@ export {
176
176
  zIngestErrorCode,
177
177
  zIngestError
178
178
  };
179
- //# sourceMappingURL=chunk-DUJSYMYY.js.map
179
+ //# sourceMappingURL=chunk-RU26QFM2.js.map
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkYSAEOYPDcjs = require('./chunk-YSAEOYPD.cjs');
4
+ var _chunkORNTN6AKcjs = require('./chunk-ORNTN6AK.cjs');
5
5
 
6
6
  // src/query.ts
7
7
  var _zod = require('zod');
@@ -26,7 +26,7 @@ var zQuerySource = _zod.z.enum(["rollup", "raw", "mixed"]);
26
26
  var zQueryMeta = _zod.z.object({
27
27
  projectId: _zod.z.string(),
28
28
  /** When the underlying computation actually ran. On a cache hit, when the cached value was computed. */
29
- computedAt: _chunkYSAEOYPDcjs.zInstant,
29
+ computedAt: _chunkORNTN6AKcjs.zInstant,
30
30
  /** Age of the returned computation, in seconds. `0` on a cache miss. */
31
31
  cacheAgeSeconds: _zod.z.number().int().nonnegative(),
32
32
  /**
@@ -80,8 +80,8 @@ var zEventPropertyFilter = _zod.z.object({
80
80
  });
81
81
  var zEventsTimeseriesInput = _zod.z.object({
82
82
  projectId: _zod.z.string().min(1),
83
- startDate: _chunkYSAEOYPDcjs.zDate,
84
- endDate: _chunkYSAEOYPDcjs.zDate,
83
+ startDate: _chunkORNTN6AKcjs.zDate,
84
+ endDate: _chunkORNTN6AKcjs.zDate,
85
85
  granularity: zGranularity.default("day"),
86
86
  /** Omit to count every event in the window. */
87
87
  eventName: _zod.z.string().min(1).max(200).optional(),
@@ -129,8 +129,8 @@ var zFunnelInput = _zod.z.object({
129
129
  projectId: _zod.z.string().min(1),
130
130
  /** Ordered event names. A user counts at step k if they reached at least step k. */
131
131
  steps: _zod.z.array(_zod.z.string().min(1).max(200)).min(2).max(10),
132
- startDate: _chunkYSAEOYPDcjs.zDate,
133
- endDate: _chunkYSAEOYPDcjs.zDate,
132
+ startDate: _chunkORNTN6AKcjs.zDate,
133
+ endDate: _chunkORNTN6AKcjs.zDate,
134
134
  /** Max seconds between the first and last step for a conversion to count. Default 24h. */
135
135
  windowSeconds: _zod.z.number().int().min(60).max(2592e3).default(86400),
136
136
  segmentId: _zod.z.string().min(1).optional(),
@@ -167,8 +167,8 @@ var zFunnelResponse = zQueryEnvelope(zFunnelData);
167
167
  var zRetentionInterval = _zod.z.enum(["day", "week", "month"]);
168
168
  var zRetentionInput = _zod.z.object({
169
169
  projectId: _zod.z.string().min(1),
170
- startDate: _chunkYSAEOYPDcjs.zDate,
171
- endDate: _chunkYSAEOYPDcjs.zDate,
170
+ startDate: _chunkORNTN6AKcjs.zDate,
171
+ endDate: _chunkORNTN6AKcjs.zDate,
172
172
  interval: zRetentionInterval.default("day"),
173
173
  periods: _zod.z.number().int().min(1).max(30).default(7),
174
174
  startEvent: _zod.z.string().min(1).max(200).optional(),
@@ -228,8 +228,8 @@ var zRetentionData = _zod.z.object({
228
228
  var zRetentionResponse = zQueryEnvelope(zRetentionData);
229
229
  var zTrafficOverviewInput = _zod.z.object({
230
230
  projectId: _zod.z.string().min(1),
231
- startDate: _chunkYSAEOYPDcjs.zDate,
232
- endDate: _chunkYSAEOYPDcjs.zDate,
231
+ startDate: _chunkORNTN6AKcjs.zDate,
232
+ endDate: _chunkORNTN6AKcjs.zDate,
233
233
  granularity: zGranularity.default("day"),
234
234
  timezone: zTimezone.optional()
235
235
  }).refine((input) => input.startDate <= input.endDate, {
@@ -255,8 +255,8 @@ var zTrafficOverviewResponse = zQueryEnvelope(zTrafficOverviewData);
255
255
  var zTrafficDimension = _zod.z.enum(["channel", "referrer", "utm"]);
256
256
  var zTrafficSourcesInput = _zod.z.object({
257
257
  projectId: _zod.z.string().min(1),
258
- startDate: _chunkYSAEOYPDcjs.zDate,
259
- endDate: _chunkYSAEOYPDcjs.zDate,
258
+ startDate: _chunkORNTN6AKcjs.zDate,
259
+ endDate: _chunkORNTN6AKcjs.zDate,
260
260
  /** `channel`: channel_type · `referrer`: referrer name+type · `utm`: source/medium/campaign. */
261
261
  dimension: zTrafficDimension,
262
262
  limit: _zod.z.number().int().min(1).max(100).default(10),
@@ -358,4 +358,4 @@ var QUERY_API_PATHS = {
358
358
 
359
359
 
360
360
  exports.zGranularity = zGranularity; exports.zTimezone = zTimezone; exports.isValidTimeZone = isValidTimeZone; exports.zChannelFilter = zChannelFilter; exports.zQuerySource = zQuerySource; exports.zQueryMeta = zQueryMeta; exports.zQueryEnvelope = zQueryEnvelope; exports.zTimeseriesBreakdown = zTimeseriesBreakdown; exports.zEventPropertyFilter = zEventPropertyFilter; exports.zEventsTimeseriesInput = zEventsTimeseriesInput; exports.zBucketStart = zBucketStart; exports.zTimeseriesPoint = zTimeseriesPoint; exports.zEventsTimeseriesData = zEventsTimeseriesData; exports.zEventsTimeseriesResponse = zEventsTimeseriesResponse; exports.zFunnelInput = zFunnelInput; exports.zFunnelStep = zFunnelStep; exports.zFunnelData = zFunnelData; exports.zFunnelResponse = zFunnelResponse; exports.zRetentionInterval = zRetentionInterval; exports.zRetentionInput = zRetentionInput; exports.zRetentionCell = zRetentionCell; exports.zRetentionData = zRetentionData; exports.zRetentionResponse = zRetentionResponse; exports.zTrafficOverviewInput = zTrafficOverviewInput; exports.zTrafficTotals = zTrafficTotals; exports.zTrafficSeriesPoint = zTrafficSeriesPoint; exports.zTrafficOverviewData = zTrafficOverviewData; exports.zTrafficOverviewResponse = zTrafficOverviewResponse; exports.zTrafficDimension = zTrafficDimension; exports.zTrafficSourcesInput = zTrafficSourcesInput; exports.zTrafficSourceRow = zTrafficSourceRow; exports.zTrafficSourcesData = zTrafficSourcesData; exports.zTrafficSourcesResponse = zTrafficSourcesResponse; exports.QUERY_ERROR_CODES = QUERY_ERROR_CODES; exports.zQueryErrorCode = zQueryErrorCode; exports.zQueryError = zQueryError; exports.QUERY_API_PATHS = QUERY_API_PATHS;
361
- //# sourceMappingURL=chunk-FUGY5ANJ.cjs.map
361
+ //#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MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA;AAAA,EACvB,IAAA,EAAM,eAAA;AAAA,EACN,KAAA,EAAO,MAAA,CAAE,MAAA,CAAO,CAAA;AAAA,EAChB,OAAA,EAAS,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC7B,MAAA,EAAQ,MAAA,CAAE,OAAA,CAAQ,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC7B,SAAA,EAAW,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS;AACjC,CAAC,CAAA;AAIM,IAAM,gBAAA,EAAkB;AAAA,EAC7B,gBAAA,EAAkB,iCAAA;AAAA,EAClB,MAAA,EAAQ,sBAAA;AAAA,EACR,SAAA,EAAW,yBAAA;AAAA,EACX,eAAA,EAAiB,gCAAA;AAAA,EACjB,cAAA,EAAgB;AAClB,CAAA;ADjJA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,opDAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-FUGY5ANJ.cjs","sourcesContent":[null,"/**\n * `POST /api/v1/query/*` — the read contract.\n *\n * Server credentials, project-scoped: the authenticated client's projectId must\n * equal the `projectId` in the body, or the request is refused. Reads are POSTs\n * because the inputs nest (funnel steps, channel filters) and would not survive\n * a query string; consumers cache on their own side, so HTTP cache semantics\n * buy nothing here.\n *\n * Response shapes mirror the existing dashboard computations exactly — this\n * plane re-exposes them, it does not add new math.\n */\nimport { z } from \"zod\";\nimport { zDate, zInstant } from \"./index.js\";\n\nexport { zDate, zInstant };\n\n/** Bucket width for a time series. */\nexport const zGranularity = z.enum([\"hour\", \"day\", \"week\", \"month\"]);\nexport type Granularity = z.infer<typeof zGranularity>;\n\n/**\n * IANA time zone name, e.g. `Asia/Seoul`. Decides two things at once: where a\n * calendar day starts, and therefore which bucket an event falls in.\n *\n * A Korean brand reading \"23 Aug: 120 visits\" means 23 Aug in Seoul. Computed\n * in UTC, that headline silently covers 23 Aug 09:00 through 24 Aug 09:00 —\n * wrong by nine hours in a way nothing on the page reveals.\n *\n * Validated against the runtime's own zone database rather than a regex, so an\n * unknown name fails here with a clear message instead of deep inside a query.\n */\nexport const zTimezone = z.string().min(1).max(64).refine(isValidTimeZone, { message: \"unknown IANA time zone\" });\n\nexport function isValidTimeZone(value: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Acquisition-channel filter. Every field is a set — an event matches when its\n * value is in the set; omitted fields do not constrain. Mirrors the dashboard's\n * `channelFilterSchema` field-for-field.\n */\nexport const zChannelFilter = z\n .object({\n referrerTypes: z.array(z.string()).optional(),\n channelTypes: z.array(z.string()).optional(),\n utmSources: z.array(z.string()).optional(),\n utmMediums: z.array(z.string()).optional(),\n utmCampaigns: z.array(z.string()).optional(),\n })\n .optional();\nexport type ChannelFilter = z.infer<typeof zChannelFilter>;\n\n// ─── Envelope ───────────────────────────────────────────────────────────────\n\n/**\n * Staleness is reported as two independent numbers, never as one sum, because\n * the two have different remedies: a stale cache resolves itself at the next\n * TTL, while ingest lag means the read model is genuinely behind and the right\n * response is an \"aggregating\" badge, not a refresh.\n */\nexport const zQuerySource = z.enum([\"rollup\", \"raw\", \"mixed\"]);\nexport type QuerySource = z.infer<typeof zQuerySource>;\n\nexport const zQueryMeta = z.object({\n projectId: z.string(),\n /** When the underlying computation actually ran. On a cache hit, when the cached value was computed. */\n computedAt: zInstant,\n /** Age of the returned computation, in seconds. `0` on a cache miss. */\n cacheAgeSeconds: z.number().int().nonnegative(),\n /**\n * How far behind live materialization was when the computation ran, in\n * seconds. `0` means no live event is pending; `null` means measurement\n * failed and must never be interpreted as fresh.\n *\n * Deliberately not `now - max(events.created_at)` — that conflates \"the\n * pipeline is behind\" with \"this project is quiet\", and grows without bound\n * on an idle project.\n */\n ingestLagSeconds: z.number().int().nonnegative().nullable(),\n /** Whether the freshness measurement itself succeeded. */\n ingestLagStatus: z.enum([\"known\", \"unknown\"]),\n /**\n * Pending events older than the live replay window. Kept separate so an old\n * permanently failing event neither pegs live lag nor disappears behind 0.\n * `null` means the measurement failed.\n */\n ingestDeadLetterCount: z.number().int().nonnegative().nullable(),\n cached: z.boolean(),\n /**\n * The time zone actually used to place bucket and window boundaries — the\n * resolved value, not the requested one. Read it rather than assuming the\n * request was honoured: when no zone is given anywhere it is `\"UTC\"`, and\n * that is exactly the case a consumer needs to notice.\n */\n timezone: z.string(),\n /**\n * Where the numbers came from. `rollup`: pre-aggregated hourly tables;\n * `raw`: a scan of the event/session tables; `mixed`: finished hours from\n * the rollup, the hour still in progress from raw. Diagnostic — the values\n * agree either way — but a consumer that expected `rollup` and sees `raw`\n * has asked for a combination the rollups cannot serve.\n */\n source: zQuerySource,\n requestId: z.string(),\n});\nexport type QueryMeta = z.infer<typeof zQueryMeta>;\n\n/** Every query response is `{ data, meta }`. */\nexport function zQueryEnvelope<T extends z.ZodTypeAny>(data: T) {\n return z.object({ data, meta: zQueryMeta });\n}\n\n// ─── events.timeseries ──────────────────────────────────────────────────────\n\n/**\n * v1 breaks down by `properties` JSON keys only. Built-in columns\n * (country / os / browser / utm_*) have a totals breakdown in the backend but\n * no *time series* variant, and this plane does not add new computations.\n */\nexport const zTimeseriesBreakdown = z.object({\n kind: z.literal(\"property\"),\n key: z.string().min(1).max(200),\n topN: z.number().int().min(1).max(100).default(5),\n});\nexport type TimeseriesBreakdown = z.infer<typeof zTimeseriesBreakdown>;\n\n/** Exact-match filter for a top-level event `properties` key. Multiple filters are ANDed. */\nexport const zEventPropertyFilter = z.object({\n key: z.string().min(1).max(200),\n operator: z.literal(\"eq\").default(\"eq\"),\n value: z.string().min(1).max(500),\n});\nexport type EventPropertyFilter = z.infer<typeof zEventPropertyFilter>;\n\nexport const zEventsTimeseriesInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n granularity: zGranularity.default(\"day\"),\n /** Omit to count every event in the window. */\n eventName: z.string().min(1).max(200).optional(),\n /** Exact matches against top-level `properties` keys. Every item must match. */\n propertyFilters: z.array(zEventPropertyFilter).max(10).optional(),\n breakdown: zTimeseriesBreakdown.optional(),\n /**\n * Cannot be combined with `breakdown` — the backend's breakdown time series\n * takes no segment. Sending both is refused with `unsupported_combination`\n * rather than silently ignoring one of them.\n */\n segmentId: z.string().min(1).optional(),\n /** Omit to fall back to the project's configured zone, then to UTC. */\n timezone: zTimezone.optional(),\n /**\n * Events whose catalogue status is `internal` (operational probes) are\n * left out by default. A probe that needs to find its own event sets this.\n */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type EventsTimeseriesInput = z.input<typeof zEventsTimeseriesInput>;\n\n/**\n * Bucket start as wall-clock time in `meta.timezone`, `YYYY-MM-DD HH:MM:SS`.\n *\n * Pinned rather than left to the backend, because a consumer keys its chart on\n * this string: an unspecified format is one where two backends, or two\n * granularities, can quietly disagree and produce two different keys for the\n * same bucket.\n *\n * It is wall time, not an instant — for `Asia/Seoul` a day bucket reads\n * `2026-08-24 00:00:00`, which is `2026-08-23T15:00:00Z`. Day, week and month\n * buckets always carry `00:00:00`, so slicing the first ten characters is a\n * safe way to get a date key.\n */\nexport const zBucketStart = z.string().regex(/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/, \"expected 'YYYY-MM-DD HH:MM:SS'\");\n\nexport const zTimeseriesPoint = z.object({\n date: zBucketStart,\n count: z.number().int().nonnegative(),\n});\nexport type TimeseriesPoint = z.infer<typeof zTimeseriesPoint>;\n\nexport const zEventsTimeseriesData = z.object({\n granularity: zGranularity,\n /** Zone the buckets were cut in. Mirrors `meta.timezone`. */\n timezone: z.string(),\n /** Total per bucket. Always present, with or without a breakdown. */\n series: z.array(zTimeseriesPoint),\n /** Present only when `breakdown` was requested: the top-N values, each with its own series. */\n breakdown: z\n .array(\n z.object({\n value: z.string(),\n points: z.array(zTimeseriesPoint),\n })\n )\n .optional(),\n});\nexport type EventsTimeseriesData = z.infer<typeof zEventsTimeseriesData>;\n\nexport const zEventsTimeseriesResponse = zQueryEnvelope(zEventsTimeseriesData);\nexport type EventsTimeseriesResponse = z.infer<typeof zEventsTimeseriesResponse>;\n\n// ─── funnel ─────────────────────────────────────────────────────────────────\n\nexport const zFunnelInput = z\n .object({\n projectId: z.string().min(1),\n /** Ordered event names. A user counts at step k if they reached at least step k. */\n steps: z.array(z.string().min(1).max(200)).min(2).max(10),\n startDate: zDate,\n endDate: zDate,\n /** Max seconds between the first and last step for a conversion to count. Default 24h. */\n windowSeconds: z.number().int().min(60).max(2_592_000).default(86_400),\n segmentId: z.string().min(1).optional(),\n channelFilter: zChannelFilter,\n /**\n * Decides where `startDate` / `endDate` fall. A funnel has no buckets, so\n * this only moves the window — but a nine-hour window shift changes who is\n * in the funnel.\n */\n timezone: zTimezone.optional(),\n /** Accepted for symmetry with events.timeseries; funnel steps are named explicitly, so nothing is filtered. */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type FunnelInput = z.input<typeof zFunnelInput>;\n\nexport const zFunnelStep = z.object({\n step: z.number().int().min(1),\n name: z.string(),\n users: z.number().int().nonnegative(),\n /** Percent of the previous step that reached this one. `100` for step 1. */\n conversionRate: z.number(),\n /** Percent of the previous step that did not. `0` for step 1. */\n dropoffRate: z.number(),\n dropoffUsers: z.number().int().nonnegative(),\n});\n\nexport const zFunnelData = z.object({\n steps: z.array(zFunnelStep),\n totalUsers: z.number().int().nonnegative(),\n /** Percent of step-1 users that reached the last step. */\n overallConversionRate: z.number(),\n});\nexport type FunnelData = z.infer<typeof zFunnelData>;\n\nexport const zFunnelResponse = zQueryEnvelope(zFunnelData);\nexport type FunnelResponse = z.infer<typeof zFunnelResponse>;\n\n// ─── retention ──────────────────────────────────────────────────────────────\n\nexport const zRetentionInterval = z.enum([\"day\", \"week\", \"month\"]);\n\nexport const zRetentionInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n interval: zRetentionInterval.default(\"day\"),\n periods: z.number().int().min(1).max(30).default(7),\n startEvent: z.string().min(1).max(200).optional(),\n returnEvent: z.string().min(1).max(200).optional(),\n /** `bounded`: returned in exactly period N. `unbounded`: returned in period N or later. */\n retentionType: z.enum([\"bounded\", \"unbounded\"]).default(\"bounded\"),\n /**\n * `first-ever` (default): the cohort is everyone whose true first activity\n * landed in the window, read from the first-seen aggregate. `startEvent`,\n * `segmentId` and `channelFilter` then constrain only the *returning* side.\n * `first-in-window`: the cohort is selected by scanning events in the window\n * with all filters applied. Slower, but filters apply to cohort selection.\n */\n cohortMode: z.enum([\"first-ever\", \"first-in-window\"]).default(\"first-ever\"),\n segmentId: z.string().min(1).optional(),\n channelFilter: zChannelFilter,\n /**\n * Decides where a cohort day starts, and so which period a return falls in.\n *\n * Honoured under both cohort modes. Note that a non-UTC zone makes\n * `first-ever` read raw events instead of its daily rollup — the rollup is\n * cut on UTC days and cannot be re-cut after the fact — so expect a slower\n * query in exchange for cohorts that match the reader's calendar.\n */\n timezone: zTimezone.optional(),\n /** Accepted for symmetry with events.timeseries; retention reads named or all-event activity and does not yet apply the internal filter. */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type RetentionInput = z.input<typeof zRetentionInput>;\n\nexport const zRetentionCell = z.object({\n /** `0` is the cohort's own period. */\n period: z.number().int().nonnegative(),\n users: z.number().int().nonnegative(),\n /** Percent of `cohortSize`. */\n rate: z.number(),\n});\n\nexport const zRetentionData = z.object({\n matrix: z.array(\n z.object({\n /** Cohort bucket start, same shape and zone as {@link zBucketStart}. */\n cohortDate: zBucketStart,\n cohortSize: z.number().int().nonnegative(),\n /** Length is `periods + 1`, index-aligned to `period`. */\n retention: z.array(zRetentionCell),\n })\n ),\n /** Unweighted mean rate per period across cohorts. */\n averageRetention: z.array(z.object({ period: z.number().int().nonnegative(), rate: z.number() })),\n interval: zRetentionInterval,\n periods: z.number().int(),\n retentionType: z.enum([\"bounded\", \"unbounded\"]),\n /** Zone the cohort days were cut in. Mirrors `meta.timezone`. */\n timezone: z.string(),\n});\nexport type RetentionData = z.infer<typeof zRetentionData>;\n\nexport const zRetentionResponse = zQueryEnvelope(zRetentionData);\nexport type RetentionResponse = z.infer<typeof zRetentionResponse>;\n\n// ─── traffic ────────────────────────────────────────────────────────────────\n\n/**\n * Session-level traffic for a brand site, served from the hourly rollups.\n * `newVisitors` counts sessions whose device was first seen inside them;\n * `returningVisitors` is the rest. Both are session counts, not people —\n * \"visitor\" is the vocabulary the dashboards already use.\n */\nexport const zTrafficOverviewInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n granularity: zGranularity.default(\"day\"),\n timezone: zTimezone.optional(),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type TrafficOverviewInput = z.input<typeof zTrafficOverviewInput>;\n\nexport const zTrafficTotals = z.object({\n sessions: z.number().int().nonnegative(),\n pageviews: z.number().int().nonnegative(),\n newVisitors: z.number().int().nonnegative(),\n returningVisitors: z.number().int().nonnegative(),\n /** Percent of sessions that bounced, two decimals. */\n bounceRate: z.number(),\n});\nexport type TrafficTotals = z.infer<typeof zTrafficTotals>;\n\nexport const zTrafficSeriesPoint = zTrafficTotals.extend({ date: zBucketStart });\n\nexport const zTrafficOverviewData = z.object({\n granularity: zGranularity,\n timezone: z.string(),\n totals: zTrafficTotals,\n series: z.array(zTrafficSeriesPoint),\n});\nexport type TrafficOverviewData = z.infer<typeof zTrafficOverviewData>;\nexport const zTrafficOverviewResponse = zQueryEnvelope(zTrafficOverviewData);\nexport type TrafficOverviewResponse = z.infer<typeof zTrafficOverviewResponse>;\n\nexport const zTrafficDimension = z.enum([\"channel\", \"referrer\", \"utm\"]);\nexport type TrafficDimension = z.infer<typeof zTrafficDimension>;\n\nexport const zTrafficSourcesInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n /** `channel`: channel_type · `referrer`: referrer name+type · `utm`: source/medium/campaign. */\n dimension: zTrafficDimension,\n limit: z.number().int().min(1).max(100).default(10),\n timezone: zTimezone.optional(),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type TrafficSourcesInput = z.input<typeof zTrafficSourcesInput>;\n\nexport const zTrafficSourceRow = zTrafficTotals.extend({\n /** Display key for the row: the channel, the referrer name, or `source / medium / campaign`. */\n key: z.string(),\n channelType: z.string().optional(),\n referrerName: z.string().optional(),\n referrerType: z.string().optional(),\n utmSource: z.string().optional(),\n utmMedium: z.string().optional(),\n utmCampaign: z.string().optional(),\n});\nexport type TrafficSourceRow = z.infer<typeof zTrafficSourceRow>;\n\nexport const zTrafficSourcesData = z.object({\n dimension: zTrafficDimension,\n timezone: z.string(),\n /** Ordered by sessions, descending. */\n rows: z.array(zTrafficSourceRow),\n});\nexport type TrafficSourcesData = z.infer<typeof zTrafficSourcesData>;\nexport const zTrafficSourcesResponse = zQueryEnvelope(zTrafficSourcesData);\nexport type TrafficSourcesResponse = z.infer<typeof zTrafficSourcesResponse>;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\nexport const QUERY_ERROR_CODES = [\n /** 401 — unknown or mismatched credentials. */\n \"unauthorized\",\n /** 403 — the credential's project is not the project asked about. */\n \"project_scope_mismatch\",\n /** 403 — the credential lacks the `query` scope. Provision a query-scoped client. */\n \"query_scope_missing\",\n /** 400 — input failed the schema. `errors` carries the zod issues. */\n \"validation_failed\",\n /** 400 — inputs are individually valid but cannot be served together (e.g. breakdown + segmentId). */\n \"unsupported_combination\",\n /** 410 — the project is being deleted. Permanent; stop asking. */\n \"project_purging\",\n /** 429 — per-credential query rate limit. `Retry-After` set. */\n \"rate_limited\",\n /** 504 — the analytics backend exceeded its statement timeout. Narrow the window. */\n \"query_timeout\",\n /** 500 — unexpected server failure. */\n \"internal_error\",\n] as const;\nexport const zQueryErrorCode = z.enum(QUERY_ERROR_CODES);\nexport type QueryErrorCode = z.infer<typeof zQueryErrorCode>;\n\nexport const zQueryError = z.object({\n status: z.number().int(),\n code: zQueryErrorCode,\n error: z.string(),\n message: z.string().optional(),\n errors: z.unknown().optional(),\n requestId: z.string().optional(),\n});\nexport type QueryError = z.infer<typeof zQueryError>;\n\n/** Paths, so the client and the route handlers cannot drift apart. */\nexport const QUERY_API_PATHS = {\n eventsTimeseries: \"/api/v1/query/events/timeseries\",\n funnel: \"/api/v1/query/funnel\",\n retention: \"/api/v1/query/retention\",\n trafficOverview: \"/api/v1/query/traffic/overview\",\n trafficSources: \"/api/v1/query/traffic/sources\",\n} as const;\n"]}
1
+ {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-XDH5QQYF.cjs","../src/query.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACOA,0BAAkB;AAMX,IAAM,aAAA,EAAe,MAAA,CAAE,IAAA,CAAK,CAAC,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,OAAO,CAAC,CAAA;AAc5D,IAAM,UAAA,EAAY,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,EAAE,CAAA,CAAE,MAAA,CAAO,eAAA,EAAiB,EAAE,OAAA,EAAS,yBAAyB,CAAC,CAAA;AAEzG,SAAS,eAAA,CAAgB,KAAA,EAAwB;AACtD,EAAA,IAAI;AACF,IAAA,I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ADjJA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,opDAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-XDH5QQYF.cjs","sourcesContent":[null,"/**\n * `POST /api/v1/query/*` — the read contract.\n *\n * Server credentials, project-scoped: the authenticated client's projectId must\n * equal the `projectId` in the body, or the request is refused. Reads are POSTs\n * because the inputs nest (funnel steps, channel filters) and would not survive\n * a query string; consumers cache on their own side, so HTTP cache semantics\n * buy nothing here.\n *\n * Response shapes mirror the existing dashboard computations exactly — this\n * plane re-exposes them, it does not add new math.\n */\nimport { z } from \"zod\";\nimport { zDate, zInstant } from \"./index.js\";\n\nexport { zDate, zInstant };\n\n/** Bucket width for a time series. */\nexport const zGranularity = z.enum([\"hour\", \"day\", \"week\", \"month\"]);\nexport type Granularity = z.infer<typeof zGranularity>;\n\n/**\n * IANA time zone name, e.g. `Asia/Seoul`. Decides two things at once: where a\n * calendar day starts, and therefore which bucket an event falls in.\n *\n * A Korean brand reading \"23 Aug: 120 visits\" means 23 Aug in Seoul. Computed\n * in UTC, that headline silently covers 23 Aug 09:00 through 24 Aug 09:00 —\n * wrong by nine hours in a way nothing on the page reveals.\n *\n * Validated against the runtime's own zone database rather than a regex, so an\n * unknown name fails here with a clear message instead of deep inside a query.\n */\nexport const zTimezone = z.string().min(1).max(64).refine(isValidTimeZone, { message: \"unknown IANA time zone\" });\n\nexport function isValidTimeZone(value: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Acquisition-channel filter. Every field is a set — an event matches when its\n * value is in the set; omitted fields do not constrain. Mirrors the dashboard's\n * `channelFilterSchema` field-for-field.\n */\nexport const zChannelFilter = z\n .object({\n referrerTypes: z.array(z.string()).optional(),\n channelTypes: z.array(z.string()).optional(),\n utmSources: z.array(z.string()).optional(),\n utmMediums: z.array(z.string()).optional(),\n utmCampaigns: z.array(z.string()).optional(),\n })\n .optional();\nexport type ChannelFilter = z.infer<typeof zChannelFilter>;\n\n// ─── Envelope ───────────────────────────────────────────────────────────────\n\n/**\n * Staleness is reported as two independent numbers, never as one sum, because\n * the two have different remedies: a stale cache resolves itself at the next\n * TTL, while ingest lag means the read model is genuinely behind and the right\n * response is an \"aggregating\" badge, not a refresh.\n */\nexport const zQuerySource = z.enum([\"rollup\", \"raw\", \"mixed\"]);\nexport type QuerySource = z.infer<typeof zQuerySource>;\n\nexport const zQueryMeta = z.object({\n projectId: z.string(),\n /** When the underlying computation actually ran. On a cache hit, when the cached value was computed. */\n computedAt: zInstant,\n /** Age of the returned computation, in seconds. `0` on a cache miss. */\n cacheAgeSeconds: z.number().int().nonnegative(),\n /**\n * How far behind live materialization was when the computation ran, in\n * seconds. `0` means no live event is pending; `null` means measurement\n * failed and must never be interpreted as fresh.\n *\n * Deliberately not `now - max(events.created_at)` — that conflates \"the\n * pipeline is behind\" with \"this project is quiet\", and grows without bound\n * on an idle project.\n */\n ingestLagSeconds: z.number().int().nonnegative().nullable(),\n /** Whether the freshness measurement itself succeeded. */\n ingestLagStatus: z.enum([\"known\", \"unknown\"]),\n /**\n * Pending events older than the live replay window. Kept separate so an old\n * permanently failing event neither pegs live lag nor disappears behind 0.\n * `null` means the measurement failed.\n */\n ingestDeadLetterCount: z.number().int().nonnegative().nullable(),\n cached: z.boolean(),\n /**\n * The time zone actually used to place bucket and window boundaries — the\n * resolved value, not the requested one. Read it rather than assuming the\n * request was honoured: when no zone is given anywhere it is `\"UTC\"`, and\n * that is exactly the case a consumer needs to notice.\n */\n timezone: z.string(),\n /**\n * Where the numbers came from. `rollup`: pre-aggregated hourly tables;\n * `raw`: a scan of the event/session tables; `mixed`: finished hours from\n * the rollup, the hour still in progress from raw. Diagnostic — the values\n * agree either way — but a consumer that expected `rollup` and sees `raw`\n * has asked for a combination the rollups cannot serve.\n */\n source: zQuerySource,\n requestId: z.string(),\n});\nexport type QueryMeta = z.infer<typeof zQueryMeta>;\n\n/** Every query response is `{ data, meta }`. */\nexport function zQueryEnvelope<T extends z.ZodTypeAny>(data: T) {\n return z.object({ data, meta: zQueryMeta });\n}\n\n// ─── events.timeseries ──────────────────────────────────────────────────────\n\n/**\n * v1 breaks down by `properties` JSON keys only. Built-in columns\n * (country / os / browser / utm_*) have a totals breakdown in the backend but\n * no *time series* variant, and this plane does not add new computations.\n */\nexport const zTimeseriesBreakdown = z.object({\n kind: z.literal(\"property\"),\n key: z.string().min(1).max(200),\n topN: z.number().int().min(1).max(100).default(5),\n});\nexport type TimeseriesBreakdown = z.infer<typeof zTimeseriesBreakdown>;\n\n/** Exact-match filter for a top-level event `properties` key. Multiple filters are ANDed. */\nexport const zEventPropertyFilter = z.object({\n key: z.string().min(1).max(200),\n operator: z.literal(\"eq\").default(\"eq\"),\n value: z.string().min(1).max(500),\n});\nexport type EventPropertyFilter = z.infer<typeof zEventPropertyFilter>;\n\nexport const zEventsTimeseriesInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n granularity: zGranularity.default(\"day\"),\n /** Omit to count every event in the window. */\n eventName: z.string().min(1).max(200).optional(),\n /** Exact matches against top-level `properties` keys. Every item must match. */\n propertyFilters: z.array(zEventPropertyFilter).max(10).optional(),\n breakdown: zTimeseriesBreakdown.optional(),\n /**\n * Cannot be combined with `breakdown` — the backend's breakdown time series\n * takes no segment. Sending both is refused with `unsupported_combination`\n * rather than silently ignoring one of them.\n */\n segmentId: z.string().min(1).optional(),\n /** Omit to fall back to the project's configured zone, then to UTC. */\n timezone: zTimezone.optional(),\n /**\n * Events whose catalogue status is `internal` (operational probes) are\n * left out by default. A probe that needs to find its own event sets this.\n */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type EventsTimeseriesInput = z.input<typeof zEventsTimeseriesInput>;\n\n/**\n * Bucket start as wall-clock time in `meta.timezone`, `YYYY-MM-DD HH:MM:SS`.\n *\n * Pinned rather than left to the backend, because a consumer keys its chart on\n * this string: an unspecified format is one where two backends, or two\n * granularities, can quietly disagree and produce two different keys for the\n * same bucket.\n *\n * It is wall time, not an instant — for `Asia/Seoul` a day bucket reads\n * `2026-08-24 00:00:00`, which is `2026-08-23T15:00:00Z`. Day, week and month\n * buckets always carry `00:00:00`, so slicing the first ten characters is a\n * safe way to get a date key.\n */\nexport const zBucketStart = z.string().regex(/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/, \"expected 'YYYY-MM-DD HH:MM:SS'\");\n\nexport const zTimeseriesPoint = z.object({\n date: zBucketStart,\n count: z.number().int().nonnegative(),\n});\nexport type TimeseriesPoint = z.infer<typeof zTimeseriesPoint>;\n\nexport const zEventsTimeseriesData = z.object({\n granularity: zGranularity,\n /** Zone the buckets were cut in. Mirrors `meta.timezone`. */\n timezone: z.string(),\n /** Total per bucket. Always present, with or without a breakdown. */\n series: z.array(zTimeseriesPoint),\n /** Present only when `breakdown` was requested: the top-N values, each with its own series. */\n breakdown: z\n .array(\n z.object({\n value: z.string(),\n points: z.array(zTimeseriesPoint),\n })\n )\n .optional(),\n});\nexport type EventsTimeseriesData = z.infer<typeof zEventsTimeseriesData>;\n\nexport const zEventsTimeseriesResponse = zQueryEnvelope(zEventsTimeseriesData);\nexport type EventsTimeseriesResponse = z.infer<typeof zEventsTimeseriesResponse>;\n\n// ─── funnel ─────────────────────────────────────────────────────────────────\n\nexport const zFunnelInput = z\n .object({\n projectId: z.string().min(1),\n /** Ordered event names. A user counts at step k if they reached at least step k. */\n steps: z.array(z.string().min(1).max(200)).min(2).max(10),\n startDate: zDate,\n endDate: zDate,\n /** Max seconds between the first and last step for a conversion to count. Default 24h. */\n windowSeconds: z.number().int().min(60).max(2_592_000).default(86_400),\n segmentId: z.string().min(1).optional(),\n channelFilter: zChannelFilter,\n /**\n * Decides where `startDate` / `endDate` fall. A funnel has no buckets, so\n * this only moves the window — but a nine-hour window shift changes who is\n * in the funnel.\n */\n timezone: zTimezone.optional(),\n /** Accepted for symmetry with events.timeseries; funnel steps are named explicitly, so nothing is filtered. */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type FunnelInput = z.input<typeof zFunnelInput>;\n\nexport const zFunnelStep = z.object({\n step: z.number().int().min(1),\n name: z.string(),\n users: z.number().int().nonnegative(),\n /** Percent of the previous step that reached this one. `100` for step 1. */\n conversionRate: z.number(),\n /** Percent of the previous step that did not. `0` for step 1. */\n dropoffRate: z.number(),\n dropoffUsers: z.number().int().nonnegative(),\n});\n\nexport const zFunnelData = z.object({\n steps: z.array(zFunnelStep),\n totalUsers: z.number().int().nonnegative(),\n /** Percent of step-1 users that reached the last step. */\n overallConversionRate: z.number(),\n});\nexport type FunnelData = z.infer<typeof zFunnelData>;\n\nexport const zFunnelResponse = zQueryEnvelope(zFunnelData);\nexport type FunnelResponse = z.infer<typeof zFunnelResponse>;\n\n// ─── retention ──────────────────────────────────────────────────────────────\n\nexport const zRetentionInterval = z.enum([\"day\", \"week\", \"month\"]);\n\nexport const zRetentionInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n interval: zRetentionInterval.default(\"day\"),\n periods: z.number().int().min(1).max(30).default(7),\n startEvent: z.string().min(1).max(200).optional(),\n returnEvent: z.string().min(1).max(200).optional(),\n /** `bounded`: returned in exactly period N. `unbounded`: returned in period N or later. */\n retentionType: z.enum([\"bounded\", \"unbounded\"]).default(\"bounded\"),\n /**\n * `first-ever` (default): the cohort is everyone whose true first activity\n * landed in the window, read from the first-seen aggregate. `startEvent`,\n * `segmentId` and `channelFilter` then constrain only the *returning* side.\n * `first-in-window`: the cohort is selected by scanning events in the window\n * with all filters applied. Slower, but filters apply to cohort selection.\n */\n cohortMode: z.enum([\"first-ever\", \"first-in-window\"]).default(\"first-ever\"),\n segmentId: z.string().min(1).optional(),\n channelFilter: zChannelFilter,\n /**\n * Decides where a cohort day starts, and so which period a return falls in.\n *\n * Honoured under both cohort modes. Note that a non-UTC zone makes\n * `first-ever` read raw events instead of its daily rollup — the rollup is\n * cut on UTC days and cannot be re-cut after the fact — so expect a slower\n * query in exchange for cohorts that match the reader's calendar.\n */\n timezone: zTimezone.optional(),\n /** Accepted for symmetry with events.timeseries; retention reads named or all-event activity and does not yet apply the internal filter. */\n includeInternal: z.boolean().default(false),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type RetentionInput = z.input<typeof zRetentionInput>;\n\nexport const zRetentionCell = z.object({\n /** `0` is the cohort's own period. */\n period: z.number().int().nonnegative(),\n users: z.number().int().nonnegative(),\n /** Percent of `cohortSize`. */\n rate: z.number(),\n});\n\nexport const zRetentionData = z.object({\n matrix: z.array(\n z.object({\n /** Cohort bucket start, same shape and zone as {@link zBucketStart}. */\n cohortDate: zBucketStart,\n cohortSize: z.number().int().nonnegative(),\n /** Length is `periods + 1`, index-aligned to `period`. */\n retention: z.array(zRetentionCell),\n })\n ),\n /** Unweighted mean rate per period across cohorts. */\n averageRetention: z.array(z.object({ period: z.number().int().nonnegative(), rate: z.number() })),\n interval: zRetentionInterval,\n periods: z.number().int(),\n retentionType: z.enum([\"bounded\", \"unbounded\"]),\n /** Zone the cohort days were cut in. Mirrors `meta.timezone`. */\n timezone: z.string(),\n});\nexport type RetentionData = z.infer<typeof zRetentionData>;\n\nexport const zRetentionResponse = zQueryEnvelope(zRetentionData);\nexport type RetentionResponse = z.infer<typeof zRetentionResponse>;\n\n// ─── traffic ────────────────────────────────────────────────────────────────\n\n/**\n * Session-level traffic for a brand site, served from the hourly rollups.\n * `newVisitors` counts sessions whose device was first seen inside them;\n * `returningVisitors` is the rest. Both are session counts, not people —\n * \"visitor\" is the vocabulary the dashboards already use.\n */\nexport const zTrafficOverviewInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n granularity: zGranularity.default(\"day\"),\n timezone: zTimezone.optional(),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type TrafficOverviewInput = z.input<typeof zTrafficOverviewInput>;\n\nexport const zTrafficTotals = z.object({\n sessions: z.number().int().nonnegative(),\n pageviews: z.number().int().nonnegative(),\n newVisitors: z.number().int().nonnegative(),\n returningVisitors: z.number().int().nonnegative(),\n /** Percent of sessions that bounced, two decimals. */\n bounceRate: z.number(),\n});\nexport type TrafficTotals = z.infer<typeof zTrafficTotals>;\n\nexport const zTrafficSeriesPoint = zTrafficTotals.extend({ date: zBucketStart });\n\nexport const zTrafficOverviewData = z.object({\n granularity: zGranularity,\n timezone: z.string(),\n totals: zTrafficTotals,\n series: z.array(zTrafficSeriesPoint),\n});\nexport type TrafficOverviewData = z.infer<typeof zTrafficOverviewData>;\nexport const zTrafficOverviewResponse = zQueryEnvelope(zTrafficOverviewData);\nexport type TrafficOverviewResponse = z.infer<typeof zTrafficOverviewResponse>;\n\nexport const zTrafficDimension = z.enum([\"channel\", \"referrer\", \"utm\"]);\nexport type TrafficDimension = z.infer<typeof zTrafficDimension>;\n\nexport const zTrafficSourcesInput = z\n .object({\n projectId: z.string().min(1),\n startDate: zDate,\n endDate: zDate,\n /** `channel`: channel_type · `referrer`: referrer name+type · `utm`: source/medium/campaign. */\n dimension: zTrafficDimension,\n limit: z.number().int().min(1).max(100).default(10),\n timezone: zTimezone.optional(),\n })\n .refine((input) => input.startDate <= input.endDate, {\n message: \"endDate must be on or after startDate\",\n path: [\"endDate\"],\n });\nexport type TrafficSourcesInput = z.input<typeof zTrafficSourcesInput>;\n\nexport const zTrafficSourceRow = zTrafficTotals.extend({\n /** Display key for the row: the channel, the referrer name, or `source / medium / campaign`. */\n key: z.string(),\n channelType: z.string().optional(),\n referrerName: z.string().optional(),\n referrerType: z.string().optional(),\n utmSource: z.string().optional(),\n utmMedium: z.string().optional(),\n utmCampaign: z.string().optional(),\n});\nexport type TrafficSourceRow = z.infer<typeof zTrafficSourceRow>;\n\nexport const zTrafficSourcesData = z.object({\n dimension: zTrafficDimension,\n timezone: z.string(),\n /** Ordered by sessions, descending. */\n rows: z.array(zTrafficSourceRow),\n});\nexport type TrafficSourcesData = z.infer<typeof zTrafficSourcesData>;\nexport const zTrafficSourcesResponse = zQueryEnvelope(zTrafficSourcesData);\nexport type TrafficSourcesResponse = z.infer<typeof zTrafficSourcesResponse>;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\nexport const QUERY_ERROR_CODES = [\n /** 401 — unknown or mismatched credentials. */\n \"unauthorized\",\n /** 403 — the credential's project is not the project asked about. */\n \"project_scope_mismatch\",\n /** 403 — the credential lacks the `query` scope. Provision a query-scoped client. */\n \"query_scope_missing\",\n /** 400 — input failed the schema. `errors` carries the zod issues. */\n \"validation_failed\",\n /** 400 — inputs are individually valid but cannot be served together (e.g. breakdown + segmentId). */\n \"unsupported_combination\",\n /** 410 — the project is being deleted. Permanent; stop asking. */\n \"project_purging\",\n /** 429 — per-credential query rate limit. `Retry-After` set. */\n \"rate_limited\",\n /** 504 — the analytics backend exceeded its statement timeout. Narrow the window. */\n \"query_timeout\",\n /** 500 — unexpected server failure. */\n \"internal_error\",\n] as const;\nexport const zQueryErrorCode = z.enum(QUERY_ERROR_CODES);\nexport type QueryErrorCode = z.infer<typeof zQueryErrorCode>;\n\nexport const zQueryError = z.object({\n status: z.number().int(),\n code: zQueryErrorCode,\n error: z.string(),\n message: z.string().optional(),\n errors: z.unknown().optional(),\n requestId: z.string().optional(),\n});\nexport type QueryError = z.infer<typeof zQueryError>;\n\n/** Paths, so the client and the route handlers cannot drift apart. */\nexport const QUERY_API_PATHS = {\n eventsTimeseries: \"/api/v1/query/events/timeseries\",\n funnel: \"/api/v1/query/funnel\",\n retention: \"/api/v1/query/retention\",\n trafficOverview: \"/api/v1/query/traffic/overview\",\n trafficSources: \"/api/v1/query/traffic/sources\",\n} as const;\n"]}
@@ -1,9 +1,9 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkFUGY5ANJcjs = require('./chunk-FUGY5ANJ.cjs');
3
+ var _chunkXDH5QQYFcjs = require('./chunk-XDH5QQYF.cjs');
4
4
 
5
5
 
6
- var _chunkYSAEOYPDcjs = require('./chunk-YSAEOYPD.cjs');
6
+ var _chunkORNTN6AKcjs = require('./chunk-ORNTN6AK.cjs');
7
7
 
8
8
  // src/control.ts
9
9
  var _zod = require('zod');
@@ -56,7 +56,7 @@ var zCreateProjectInput = _zod.z.object({
56
56
  name: _zod.z.string().min(1).max(200),
57
57
  domain: _zod.z.string().max(253).optional(),
58
58
  /** Becomes the project's default for every query that omits one. */
59
- timezone: _chunkFUGY5ANJcjs.zTimezone.optional(),
59
+ timezone: _chunkXDH5QQYFcjs.zTimezone.optional(),
60
60
  retentionDays: _zod.z.number().int().min(1).max(3650).optional()
61
61
  });
62
62
  var zProject = _zod.z.object({
@@ -112,7 +112,7 @@ var zDeleteProjectResponse = _zod.z.object({
112
112
  /** Idempotent, but it still says which of the two happened. */
113
113
  purge: _zod.z.enum(["queued", "already-absent"]),
114
114
  /** When the purge was marked. Absent for `already-absent`. */
115
- purgingAt: _chunkYSAEOYPDcjs.zInstant.optional()
115
+ purgingAt: _chunkORNTN6AKcjs.zInstant.optional()
116
116
  });
117
117
  var EVENT_META_STATUSES = ["active", "deprecated", "archived", "internal"];
118
118
  var zEventMetaStatus = _zod.z.enum(EVENT_META_STATUSES);
@@ -132,7 +132,7 @@ var zEventMetaResponse = _zod.z.object({
132
132
  rollupProperties: _zod.z.array(_zod.z.string()),
133
133
  /** Fields this call actually changed; empty on a repeat. */
134
134
  changed: _zod.z.array(_zod.z.string()),
135
- updatedAt: _chunkYSAEOYPDcjs.zInstant
135
+ updatedAt: _chunkORNTN6AKcjs.zInstant
136
136
  });
137
137
  var CONTROL_ERROR_CODES = [
138
138
  /** 401 — missing or invalid platform key / organization key. */
@@ -201,4 +201,4 @@ var CONTROL_API_PATHS = {
201
201
 
202
202
 
203
203
  exports.PLATFORM_KEY_HEADER = PLATFORM_KEY_HEADER; exports.ORG_KEY_HEADER = ORG_KEY_HEADER; exports.zExternalId = zExternalId; exports.zCreateOrganizationInput = zCreateOrganizationInput; exports.zOrganization = zOrganization; exports.zCreateOrganizationResponse = zCreateOrganizationResponse; exports.zRotateOrganizationKeyResponse = zRotateOrganizationKeyResponse; exports.zUpdateOrganizationQuotaInput = zUpdateOrganizationQuotaInput; exports.zUpdateOrganizationQuotaResponse = zUpdateOrganizationQuotaResponse; exports.zCreateProjectInput = zCreateProjectInput; exports.zProject = zProject; exports.zCreateProjectResponse = zCreateProjectResponse; exports.zRotateClientSecretResponse = zRotateClientSecretResponse; exports.zDeleteProjectInput = zDeleteProjectInput; exports.zDeleteProjectResponse = zDeleteProjectResponse; exports.EVENT_META_STATUSES = EVENT_META_STATUSES; exports.zEventMetaStatus = zEventMetaStatus; exports.zEventName = zEventName; exports.zUpsertEventMetaInput = zUpsertEventMetaInput; exports.zEventMetaResponse = zEventMetaResponse; exports.CONTROL_ERROR_CODES = CONTROL_ERROR_CODES; exports.zControlErrorCode = zControlErrorCode; exports.zControlError = zControlError; exports.CONTROL_API_PATHS = CONTROL_API_PATHS;
204
- //# sourceMappingURL=chunk-LA5F5KR6.cjs.map
204
+ //# sourceMappingURL=chunk-YCTGHWTP.cjs.map