@reopt-ai/data-contract 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-2LZBZXBF.js → chunk-33BCA2LH.js} +1 -15
- package/dist/chunk-33BCA2LH.js.map +1 -0
- package/dist/chunk-3EEANNYN.cjs +62 -0
- package/dist/chunk-3EEANNYN.cjs.map +1 -0
- package/dist/{chunk-MFZEIH5Z.js → chunk-5BRCHDS3.js} +22 -4
- package/dist/chunk-5BRCHDS3.js.map +1 -0
- package/dist/chunk-6ZJOC4NJ.js +111 -0
- package/dist/chunk-6ZJOC4NJ.js.map +1 -0
- package/dist/chunk-FP2X3PRK.js +62 -0
- package/dist/chunk-FP2X3PRK.js.map +1 -0
- package/dist/{chunk-VQ2CD5MG.cjs → chunk-FUGY5ANJ.cjs} +13 -13
- package/dist/{chunk-VQ2CD5MG.cjs.map → chunk-FUGY5ANJ.cjs.map} +1 -1
- package/dist/chunk-IXPP5K4I.js +19 -0
- package/dist/chunk-IXPP5K4I.js.map +1 -0
- package/dist/{chunk-AHXPQQKO.js → chunk-IY4MXH35.js} +3 -3
- package/dist/chunk-JHHCT3GA.cjs +19 -0
- package/dist/chunk-JHHCT3GA.cjs.map +1 -0
- package/dist/chunk-KRJPEMFD.cjs +111 -0
- package/dist/chunk-KRJPEMFD.cjs.map +1 -0
- package/dist/{chunk-BCGR27G2.js → chunk-L3WJGIKD.js} +2 -2
- package/dist/{chunk-4B4AY44F.cjs → chunk-LA5F5KR6.cjs} +6 -6
- package/dist/{chunk-4B4AY44F.cjs.map → chunk-LA5F5KR6.cjs.map} +1 -1
- package/dist/{chunk-XI3VP5DN.cjs → chunk-OGL3P7IH.cjs} +26 -8
- package/dist/chunk-OGL3P7IH.cjs.map +1 -0
- package/dist/{chunk-OLSMH4RY.cjs → chunk-YSAEOYPD.cjs} +2 -16
- package/dist/chunk-YSAEOYPD.cjs.map +1 -0
- package/dist/client.cjs +53 -49
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +2 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +9 -5
- package/dist/client.js.map +1 -1
- package/dist/control.cjs +5 -4
- package/dist/control.cjs.map +1 -1
- package/dist/control.d.cts +6 -6
- package/dist/control.d.ts +6 -6
- package/dist/control.js +4 -3
- package/dist/events.cjs +17 -0
- package/dist/events.cjs.map +1 -0
- package/dist/events.d.cts +59 -0
- package/dist/events.d.ts +59 -0
- package/dist/events.js +17 -0
- package/dist/events.js.map +1 -0
- package/dist/identity.cjs +47 -0
- package/dist/identity.cjs.map +1 -0
- package/dist/identity.d.cts +90 -0
- package/dist/identity.d.ts +90 -0
- package/dist/identity.js +47 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.cjs +4 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -15
- package/dist/index.d.ts +5 -15
- package/dist/index.js +7 -5
- package/dist/ingest.cjs +16 -2
- package/dist/ingest.cjs.map +1 -1
- package/dist/ingest.d.cts +12 -9
- package/dist/ingest.d.ts +12 -9
- package/dist/ingest.js +16 -2
- package/dist/query.cjs +4 -3
- package/dist/query.cjs.map +1 -1
- package/dist/query.d.cts +9 -8
- package/dist/query.d.ts +9 -8
- package/dist/query.js +3 -2
- package/dist/version-CC4_BBvq.d.cts +26 -0
- package/dist/version-CC4_BBvq.d.ts +26 -0
- package/package.json +13 -2
- package/dist/chunk-2LZBZXBF.js.map +0 -1
- package/dist/chunk-MFZEIH5Z.js.map +0 -1
- package/dist/chunk-OLSMH4RY.cjs.map +0 -1
- package/dist/chunk-XI3VP5DN.cjs.map +0 -1
- /package/dist/{chunk-AHXPQQKO.js.map → chunk-IY4MXH35.js.map} +0 -0
- /package/dist/{chunk-BCGR27G2.js.map → chunk-L3WJGIKD.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-VQ2CD5MG.cj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AA;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-VQ2CD5MG.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-FUGY5ANJ.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,IAAI,IAAA,CAAK,cAAA,CAAe,OAAA,EAAS,EAAE,QAAA,EAAU,MAAM,CAAC,CAAA;AACpD,IAAA,OAAO,IAAA;AAAA,EACT,E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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"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/version.ts
|
|
2
|
+
var CONTRACT_VERSION = "0.6.0";
|
|
3
|
+
var CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
|
|
4
|
+
var CLIENT_ID_HEADER = "reopt-client-id";
|
|
5
|
+
var CLIENT_SECRET_HEADER = "reopt-client-secret";
|
|
6
|
+
var WRITE_KEY_HEADER = "reopt-write-key";
|
|
7
|
+
var DEVICE_ID_HEADER = "reopt-device-id";
|
|
8
|
+
var REQUEST_ID_HEADER = "x-request-id";
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
CONTRACT_VERSION,
|
|
12
|
+
CONTRACT_VERSION_HEADER,
|
|
13
|
+
CLIENT_ID_HEADER,
|
|
14
|
+
CLIENT_SECRET_HEADER,
|
|
15
|
+
WRITE_KEY_HEADER,
|
|
16
|
+
DEVICE_ID_HEADER,
|
|
17
|
+
REQUEST_ID_HEADER
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=chunk-IXPP5K4I.js.map
|
|
@@ -0,0 +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.0\";\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,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
zTimezone
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-L3WJGIKD.js";
|
|
4
4
|
import {
|
|
5
5
|
zInstant
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-33BCA2LH.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-
|
|
204
|
+
//# sourceMappingURL=chunk-IY4MXH35.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/version.ts
|
|
2
|
+
var CONTRACT_VERSION = "0.6.0";
|
|
3
|
+
var CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
|
|
4
|
+
var CLIENT_ID_HEADER = "reopt-client-id";
|
|
5
|
+
var CLIENT_SECRET_HEADER = "reopt-client-secret";
|
|
6
|
+
var WRITE_KEY_HEADER = "reopt-write-key";
|
|
7
|
+
var DEVICE_ID_HEADER = "reopt-device-id";
|
|
8
|
+
var REQUEST_ID_HEADER = "x-request-id";
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
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-JHHCT3GA.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-JHHCT3GA.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-JHHCT3GA.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.0\";\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"]}
|
|
@@ -0,0 +1,111 @@
|
|
|
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
|
+
|
|
3
|
+
var _chunkJHHCT3GAcjs = require('./chunk-JHHCT3GA.cjs');
|
|
4
|
+
|
|
5
|
+
// src/identity.ts
|
|
6
|
+
var SESSION_ID_HEADER = "reopt-session-id";
|
|
7
|
+
var IDENTITY_REQUEST_HEADERS = [_chunkJHHCT3GAcjs.DEVICE_ID_HEADER, SESSION_ID_HEADER];
|
|
8
|
+
var COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;
|
|
9
|
+
var OPT_OUT_CONSENT_CATEGORY = "analytics";
|
|
10
|
+
var COOKIE_PREFIX = "reopt_";
|
|
11
|
+
function cookieSafe(writeKey) {
|
|
12
|
+
if (!writeKey) {
|
|
13
|
+
throw new Error("[reopt] writeKey is required to derive cookie names");
|
|
14
|
+
}
|
|
15
|
+
return writeKey.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
16
|
+
}
|
|
17
|
+
function deviceCookieName(writeKey) {
|
|
18
|
+
return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;
|
|
19
|
+
}
|
|
20
|
+
function consentCookieName(writeKey) {
|
|
21
|
+
return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;
|
|
22
|
+
}
|
|
23
|
+
var IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;
|
|
24
|
+
function isValidIdentityId(value) {
|
|
25
|
+
return typeof value === "string" && IDENTITY_ID_PATTERN.test(value);
|
|
26
|
+
}
|
|
27
|
+
function decode(raw) {
|
|
28
|
+
try {
|
|
29
|
+
return decodeURIComponent(raw);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
return raw;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function parseDeviceCookie(raw) {
|
|
35
|
+
if (!raw) return null;
|
|
36
|
+
const text = decode(raw.trim());
|
|
37
|
+
if (!text) return null;
|
|
38
|
+
if (!text.startsWith("{")) {
|
|
39
|
+
return isValidIdentityId(text) ? { deviceId: text } : null;
|
|
40
|
+
}
|
|
41
|
+
let parsed;
|
|
42
|
+
try {
|
|
43
|
+
parsed = JSON.parse(text);
|
|
44
|
+
} catch (e2) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
48
|
+
const candidate = parsed;
|
|
49
|
+
if (!isValidIdentityId(candidate.deviceId)) return null;
|
|
50
|
+
const state = { deviceId: candidate.deviceId };
|
|
51
|
+
if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;
|
|
52
|
+
if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;
|
|
53
|
+
return state;
|
|
54
|
+
}
|
|
55
|
+
function serializeDeviceCookie(state) {
|
|
56
|
+
if (!isValidIdentityId(state.deviceId)) {
|
|
57
|
+
throw new Error("[reopt] deviceId must be a non-empty string without control characters");
|
|
58
|
+
}
|
|
59
|
+
const envelope = { deviceId: state.deviceId };
|
|
60
|
+
if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;
|
|
61
|
+
if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;
|
|
62
|
+
return encodeURIComponent(JSON.stringify(envelope));
|
|
63
|
+
}
|
|
64
|
+
function parseConsentCookie(raw) {
|
|
65
|
+
if (!raw) return null;
|
|
66
|
+
const text = decode(raw.trim());
|
|
67
|
+
if (!text.startsWith("{")) return null;
|
|
68
|
+
let parsed;
|
|
69
|
+
try {
|
|
70
|
+
parsed = JSON.parse(text);
|
|
71
|
+
} catch (e3) {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
75
|
+
const state = {};
|
|
76
|
+
for (const [category, decision] of Object.entries(parsed)) {
|
|
77
|
+
if (typeof decision === "boolean" && isValidIdentityId(category)) {
|
|
78
|
+
state[category] = decision;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return state;
|
|
82
|
+
}
|
|
83
|
+
function serializeConsentCookie(state) {
|
|
84
|
+
const clean = {};
|
|
85
|
+
for (const [category, decision] of Object.entries(state)) {
|
|
86
|
+
if (typeof decision === "boolean" && isValidIdentityId(category)) {
|
|
87
|
+
clean[category] = decision;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return encodeURIComponent(JSON.stringify(clean));
|
|
91
|
+
}
|
|
92
|
+
function isOptedOut(consent) {
|
|
93
|
+
return _optionalChain([consent, 'optionalAccess', _ => _[OPT_OUT_CONSENT_CATEGORY]]) === false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
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;
|
|
111
|
+
//# sourceMappingURL=chunk-KRJPEMFD.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-KRJPEMFD.cjs","../src/identity.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACgCO,IAAM,kBAAA,EAAoB,kBAAA;AAG1B,IAAM,yBAAA,EAA2B,CAAC,kCAAA,EAAkB,iBAAiB,CAAA;AAMrE,IAAM,uBAAA,EAAyB,IAAA,EAAM,GAAA,EAAK,GAAA,EAAK,EAAA;AAG/C,IAAM,yBAAA,EAA2B,WAAA;AAExC,IAAM,cAAA,EAAgB,QAAA;AAOtB,SAAS,UAAA,CAAW,QAAA,EAA0B;AAC5C,EAAA,GAAA,CAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,qDAAqD,CAAA;AAAA,EACvE;AACA,EAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAChD;AAGO,SAAS,gBAAA,CAAiB,QAAA,EAA0B;AACzD,EAAA,OAAO,CAAA,EAAA;AACT;AAGgB;AACP,EAAA;AACT;AAsCa;AAEG;AACP,EAAA;AACT;AAES;AACH,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACF;AASgB;AACT,EAAA;AACC,EAAA;AACD,EAAA;AAEA,EAAA;AACH,IAAA;AACF,EAAA;AAEI,EAAA;AACA,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACI,EAAA;AAEE,EAAA;AACD,EAAA;AAEC,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAQgB;AACT,EAAA;AACG,IAAA;AACR,EAAA;AACM,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAOgB;AACT,EAAA;AACC,EAAA;AACD,EAAA;AAED,EAAA;AACA,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACI,EAAA;AAEE,EAAA;AACN,EAAA;AACM,IAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgB;AACR,EAAA;AACN,EAAA;AACM,IAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAQgB;AACP,EAAA;AACT;AD5HU;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-KRJPEMFD.cjs","sourcesContent":[null,"/**\n * `@reopt-ai/data-contract/identity` — the names and encodings that carry a\n * visitor's identity between the browser SDK, the server SDK, the Next.js\n * proxy and the ingest pipeline.\n *\n * Every one of those parties reads or writes the same cookies and headers.\n * None of them depends on another (ingest does not import the SDKs), so this\n * module is the only place a name may be spelled out. A party that hardcodes\n * `reopt_<key>_device` instead of calling `deviceCookieName()` fails silently:\n * the browser sets one cookie, the server looks for another, and every\n * visitor is counted as new. `packages/db/src/__tests__/redis-namespace.test.ts`\n * guards Redis key prefixes for exactly the same reason.\n *\n * Nothing here touches `document`, `fetch` or Node built-ins — it runs in\n * browsers, edge runtimes and Node alike.\n */\nimport { DEVICE_ID_HEADER } from \"./version.js\";\n\nexport {\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n WRITE_KEY_HEADER,\n} from \"./version.js\";\n\n/**\n * Request header carrying the browser's current session id. The browser SDK\n * adds it to same-origin requests so a server-side `track()` can land in the\n * session the user is actually in; the server SDK forwards it to ingest.\n *\n * Ingest treats it as a *hint*, never as authority — a browser can put any\n * value here.\n */\nexport const SESSION_ID_HEADER = \"reopt-session-id\";\n\n/** Every request header the identity protocol may carry, for CORS allow-lists. */\nexport const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER] as const;\n\n/**\n * 400 days — the longest lifetime Chrome will honour. Anything longer is\n * silently clamped to this, so asking for more only hides the real expiry.\n */\nexport const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;\n\n/** Consent category whose refusal means \"send nothing at all\". */\nexport const OPT_OUT_CONSENT_CATEGORY = \"analytics\";\n\nconst COOKIE_PREFIX = \"reopt_\";\n\n/**\n * Cookie names may not contain separators (`=`, `;`, `,`, whitespace) or\n * control characters. A write key is opaque to us, so anything outside the\n * safe set is folded to `_` — deterministically, so both ends agree.\n */\nfunction cookieSafe(writeKey: string): string {\n if (!writeKey) {\n throw new Error(\"[reopt] writeKey is required to derive cookie names\");\n }\n return writeKey.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/** `reopt_<writeKey>_device` — device id plus session/profile hints. */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. */\nexport function consentCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;\n}\n\n/** Everything the device cookie may carry. Only `deviceId` is required. */\nexport interface DeviceCookieState {\n deviceId: string;\n /** Current session, if the browser has one. */\n sessionId?: string;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string;\n}\n\n/** Per-category consent. `false` withdraws, `true` grants, absent = undecided. */\nexport type ConsentCookieState = Record<string, boolean>;\n\n/**\n * What the server hands the browser SDK so the first render already agrees\n * with the server about who the visitor is. Plain JSON — it crosses the\n * RSC → client component boundary as a prop.\n */\nexport interface ReoptBootstrap {\n /** From the device cookie (seeded by the proxy on first visit). */\n deviceId: string;\n /** Session hint, or `null` when the browser has not started one. */\n sessionId: string | null;\n /** Result of the server's `getProfileId` resolver, or `null`. */\n profileId: string | null;\n consent: ConsentCookieState;\n /** Server clock at render time, so a skewed device clock can be corrected. */\n serverTimeMs: number;\n}\n\n/**\n * Ids are opaque, but a cookie is attacker-controlled input (a sibling\n * subdomain can set one). The value ends up in an HTTP header, and\n * `Headers.set` throws on anything outside ISO-8859-1 — so a single odd\n * cookie would break every `fetch` the tracing patch touches. Only the URL\n * \"unreserved\" set is accepted; every id this SDK mints is a UUID.\n */\nexport const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;\n\nexport function isValidIdentityId(value: unknown): value is string {\n return typeof value === \"string\" && IDENTITY_ID_PATTERN.test(value);\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Reads a device cookie value. Accepts the JSON envelope written by\n * `serializeDeviceCookie` and, for cookies seeded before the envelope existed,\n * a bare device id. Returns `null` for anything else — a malformed cookie is\n * treated as absent, never as an error, so a corrupted value cannot take the\n * page down.\n */\nexport function parseDeviceCookie(raw: string | null | undefined): DeviceCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text) return null;\n\n if (!text.startsWith(\"{\")) {\n return isValidIdentityId(text) ? { deviceId: text } : null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const candidate = parsed as Record<string, unknown>;\n if (!isValidIdentityId(candidate.deviceId)) return null;\n\n const state: DeviceCookieState = { deviceId: candidate.deviceId };\n if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;\n if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;\n return state;\n}\n\n/**\n * Cookie values may not contain `;`, `,` or whitespace, and JSON contains\n * quotes and commas. The envelope is therefore URI-encoded; `parseDeviceCookie`\n * reverses it. Optional fields are omitted rather than written as `null` so\n * the cookie stays as small as the state it carries.\n */\nexport function serializeDeviceCookie(state: DeviceCookieState): string {\n if (!isValidIdentityId(state.deviceId)) {\n throw new Error(\"[reopt] deviceId must be a non-empty string without control characters\");\n }\n const envelope: DeviceCookieState = { deviceId: state.deviceId };\n if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;\n if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;\n return encodeURIComponent(JSON.stringify(envelope));\n}\n\n/**\n * Reads a consent cookie. Only boolean entries survive; anything else in the\n * object is dropped rather than failing the whole cookie, because one odd key\n * must not erase a user's recorded opt-out.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text.startsWith(\"{\")) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\n const state: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n state[category] = decision;\n }\n }\n return state;\n}\n\nexport function serializeConsentCookie(state: ConsentCookieState): string {\n const clean: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(state)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n clean[category] = decision;\n }\n }\n return encodeURIComponent(JSON.stringify(clean));\n}\n\n/**\n * \"Opted out\" means the visitor refused the `analytics` category. An absent\n * cookie or an undecided category is *not* an opt-out — it is the default\n * state of every first visit, and treating it as refusal would make consent\n * banners mandatory for every integration.\n */\nexport function isOptedOut(consent: ConsentCookieState | null | undefined): boolean {\n return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
zDate,
|
|
3
3
|
zInstant
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-33BCA2LH.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-
|
|
361
|
+
//# sourceMappingURL=chunk-L3WJGIKD.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkFUGY5ANJcjs = require('./chunk-FUGY5ANJ.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkYSAEOYPDcjs = require('./chunk-YSAEOYPD.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:
|
|
59
|
+
timezone: _chunkFUGY5ANJcjs.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:
|
|
115
|
+
purgingAt: _chunkYSAEOYPDcjs.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:
|
|
135
|
+
updatedAt: _chunkYSAEOYPDcjs.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-
|
|
204
|
+
//# sourceMappingURL=chunk-LA5F5KR6.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-4B4AY44F.cjs","../src/control.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACSA,0BAAkB;AAIX,IAAM,oBAAA,EAAsB,oBAAA;AAC5B,IAAM,eAAA,EAAiB,eAAA;AASvB,IAAM,YAAA,EAAc,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA;AAI7C,IAAM,yBAAA,EAA2B,MAAA,CAAE,MAAA,CAAO;AAAA,EAC/C,UAAA,EAAY,WAAA;AAAA,EACZ,IAAA,EAAM,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA;AAAA,EAC/B,IAAA,EAAM,MAAA,CACH,MAAA,CAAO,CAAA,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,cAAA,EAAgB,4CAA4C,CAAA,CAClE,QAAA,CAAS,CAAA;AAAA,EACZ,iBAAA,EAAmB,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC3D,kBAAA,EAAoB,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY,CAAA,CAAE,QAAA,CAAS;AAC9D,CAAC,CAAA;AAGM,IAAM,cAAA,EAAgB,MAAA,CAAE,MAAA,CAAO;AAAA,EACpC,EAAA,EAAI,MAAA,C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;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-4B4AY44F.cjs","sourcesContent":[null,"/**\n * `POST /api/v1/organizations` · `/api/v1/projects` and friends — the\n * provisioning contract.\n *\n * A project-scoped client credential cannot authenticate the creation of the\n * project it is scoped to, and an organization key cannot authenticate the\n * creation of its own organization. So provisioning runs on two credentials\n * above the client one: a platform key that creates organizations and writes\n * quotas, and an organization key that creates and deletes projects inside one\n * organization.\n *\n * Quota writes sit with the platform key on purpose. Organization keys are held\n * one-per-workspace by the caller and so have a wide exposure surface; a leaked\n * one that could raise its own limits would turn a credential leak into an\n * unbounded bill.\n */\nimport { z } from \"zod\";\nimport { zInstant } from \"./index.js\";\nimport { zTimezone } from \"./query.js\";\n\nexport const PLATFORM_KEY_HEADER = \"reopt-platform-key\";\nexport const ORG_KEY_HEADER = \"reopt-org-key\";\n\n/**\n * The caller's own id for the thing being provisioned.\n *\n * Preferred over an `Idempotency-Key` header because this domain has a real\n * natural key — the caller already has a stable id for the workspace or brand —\n * and a header would make the caller store a second one just to retry safely.\n */\nexport const zExternalId = z.string().min(1).max(191);\n\n// ─── Organizations ──────────────────────────────────────────────────────────\n\nexport const zCreateOrganizationInput = z.object({\n externalId: zExternalId,\n name: z.string().min(1).max(200),\n slug: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9-]+$/, \"lowercase letters, digits and hyphens only\")\n .optional(),\n monthlyEventQuota: z.number().int().nonnegative().optional(),\n monthlyCreditQuota: z.number().int().nonnegative().optional(),\n});\nexport type CreateOrganizationInput = z.input<typeof zCreateOrganizationInput>;\n\nexport const zOrganization = z.object({\n id: z.string(),\n externalId: zExternalId,\n name: z.string(),\n slug: z.string(),\n monthlyEventQuota: z.number().int(),\n monthlyCreditQuota: z.number().int(),\n});\n\nexport const zCreateOrganizationResponse = z.object({\n /** `false` when this externalId already had an organization. */\n created: z.boolean(),\n organization: zOrganization,\n /**\n * Plaintext, returned here and nowhere else.\n *\n * Absent when `created` is `false`: re-issuing on every retry would let a\n * retry quietly multiply live credentials. A caller that lost the key rotates\n * instead — see `POST /api/v1/organizations/{id}/keys`.\n */\n orgKey: z.string().optional(),\n});\nexport type CreateOrganizationResponse = z.infer<typeof zCreateOrganizationResponse>;\n\nexport const zRotateOrganizationKeyResponse = z.object({\n organizationId: z.string(),\n keyPrefix: z.string(),\n /** Plaintext, returned once. Every previously issued key is revoked immediately. */\n orgKey: z.string(),\n});\nexport type RotateOrganizationKeyResponse = z.infer<typeof zRotateOrganizationKeyResponse>;\n\nexport const zUpdateOrganizationQuotaInput = z\n .object({\n monthlyEventQuota: z.number().int().nonnegative().optional(),\n monthlyCreditQuota: z.number().int().nonnegative().optional(),\n })\n .refine((value) => value.monthlyEventQuota !== undefined || value.monthlyCreditQuota !== undefined, {\n message: \"at least one quota must be given\",\n });\nexport type UpdateOrganizationQuotaInput = z.input<typeof zUpdateOrganizationQuotaInput>;\n\nexport const zUpdateOrganizationQuotaResponse = z.object({ organization: zOrganization });\nexport type UpdateOrganizationQuotaResponse = z.infer<typeof zUpdateOrganizationQuotaResponse>;\n\n// ─── Projects ───────────────────────────────────────────────────────────────\n\nexport const zCreateProjectInput = z.object({\n externalId: zExternalId,\n name: z.string().min(1).max(200),\n domain: z.string().max(253).optional(),\n /** Becomes the project's default for every query that omits one. */\n timezone: zTimezone.optional(),\n retentionDays: z.number().int().min(1).max(3650).optional(),\n});\nexport type CreateProjectInput = z.input<typeof zCreateProjectInput>;\n\nexport const zProject = z.object({\n id: z.string(),\n externalId: zExternalId,\n organizationId: z.string(),\n name: z.string(),\n /** The applied value — `\"UTC\"` when none was given. */\n timezone: z.string(),\n retentionDays: z.number().int().nullable(),\n});\n\nexport const zCreateProjectResponse = z.object({\n created: z.boolean(),\n project: zProject,\n /**\n * Two credentials, not one. A key embedded in a browser bundle must not also\n * be able to read the project's analytics, so the browser write key and the\n * server secret are separate rows with different reach.\n */\n clients: z.object({\n browser: z.object({\n id: z.string(),\n /** Public by design, and recoverable — it ships in page source anyway. */\n writeKey: z.string(),\n scopes: z.array(z.string()),\n }),\n server: z.object({\n id: z.string(),\n /** Plaintext, returned once. Absent when `created` is `false`. */\n clientSecret: z.string().optional(),\n scopes: z.array(z.string()),\n }),\n }),\n});\nexport type CreateProjectResponse = z.infer<typeof zCreateProjectResponse>;\n\nexport const zRotateClientSecretResponse = z.object({\n projectId: z.string(),\n clientId: z.string(),\n /** Plaintext, returned once. The previous secret stops working immediately. */\n clientSecret: z.string(),\n});\nexport type RotateClientSecretResponse = z.infer<typeof zRotateClientSecretResponse>;\n\nexport const zDeleteProjectInput = z.object({\n /**\n * A field in the body rather than `?purge=true`. This deletes the project's\n * Postgres rows and every analytics row behind it, with no undo — and a query\n * parameter is far too easy to fire from shell history or a mis-copied URL.\n */\n purge: z.literal(true),\n /** Checked against the project on record; a mismatch is refused. */\n externalId: zExternalId,\n});\nexport type DeleteProjectInput = z.input<typeof zDeleteProjectInput>;\n\nexport const zDeleteProjectResponse = z.object({\n projectId: z.string(),\n /** Idempotent, but it still says which of the two happened. */\n purge: z.enum([\"queued\", \"already-absent\"]),\n /** When the purge was marked. Absent for `already-absent`. */\n purgingAt: zInstant.optional(),\n});\nexport type DeleteProjectResponse = z.infer<typeof zDeleteProjectResponse>;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n// ─── Event metadata ─────────────────────────────────────────────────────────\n\n/**\n * `PUT /api/v1/projects/{projectId}/events/{name}` — catalogue settings for\n * one event name. Provisioning calls it to mark `form.submitted` a conversion\n * and an operational probe `internal`; the call is idempotent so a retried\n * provisioning run is harmless.\n */\nexport const EVENT_META_STATUSES = [\"active\", \"deprecated\", \"archived\", \"internal\"] as const;\nexport const zEventMetaStatus = z.enum(EVENT_META_STATUSES);\nexport type EventMetaStatus = z.infer<typeof zEventMetaStatus>;\n\nexport const zEventName = z.string().min(1).max(200);\n\nexport const zUpsertEventMetaInput = z\n .object({\n conversion: z.boolean().optional(),\n /** `internal` events are left out of every metric unless a query opts in. */\n status: zEventMetaStatus.optional(),\n /** Property keys the hourly rollups break this event down by. */\n rollupProperties: z.array(z.string().min(1).max(200)).max(20).optional(),\n })\n .strict();\nexport type UpsertEventMetaInput = z.infer<typeof zUpsertEventMetaInput>;\n\nexport const zEventMetaResponse = z.object({\n projectId: z.string(),\n name: z.string(),\n conversion: z.boolean(),\n status: zEventMetaStatus,\n rollupProperties: z.array(z.string()),\n /** Fields this call actually changed; empty on a repeat. */\n changed: z.array(z.string()),\n updatedAt: zInstant,\n});\nexport type EventMetaResponse = z.infer<typeof zEventMetaResponse>;\n\nexport const CONTROL_ERROR_CODES = [\n /** 401 — missing or invalid platform key / organization key. */\n \"unauthorized\",\n /** 403 — the organization key belongs to a different organization. */\n \"organization_scope_mismatch\",\n /**\n * 409 — this externalId exists with a materially different configuration.\n * Only fields whose change alters results are compared (see the docs); a\n * renamed brand is not a conflict.\n */\n \"external_id_conflict\",\n /** 409 — the externalId in a delete body does not match the project's. */\n \"project_external_id_mismatch\",\n /** 404 — no such organization or project, on an endpoint that is not idempotent. */\n \"not_found\",\n /** 400 — input failed the schema. */\n \"validation_failed\",\n /** 429 — per-credential rate limit. */\n \"rate_limited\",\n /** 500 — unexpected server failure. */\n \"internal_error\",\n] as const;\nexport const zControlErrorCode = z.enum(CONTROL_ERROR_CODES);\nexport type ControlErrorCode = z.infer<typeof zControlErrorCode>;\n\nexport const zControlError = z.object({\n status: z.number().int(),\n code: zControlErrorCode,\n error: z.string(),\n message: z.string().optional(),\n errors: z.unknown().optional(),\n requestId: z.string().optional(),\n});\nexport type ControlError = z.infer<typeof zControlError>;\n\n/** Paths, so the client and the route handlers cannot drift apart. */\nexport const CONTROL_API_PATHS = {\n organizations: \"/api/v1/organizations\",\n organization: (id: string) => `/api/v1/organizations/${encodeURIComponent(id)}`,\n organizationKeys: (id: string) => `/api/v1/organizations/${encodeURIComponent(id)}/keys`,\n projects: \"/api/v1/projects\",\n project: (id: string) => `/api/v1/projects/${encodeURIComponent(id)}`,\n clientRotate: (projectId: string, clientId: string) =>\n `/api/v1/projects/${encodeURIComponent(projectId)}/clients/${encodeURIComponent(clientId)}/rotate`,\n projectEvent: (projectId: string, name: string) =>\n `/api/v1/projects/${encodeURIComponent(projectId)}/events/${encodeURIComponent(name)}`,\n} as const;\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-LA5F5KR6.cjs","../src/control.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACSA,0BAAkB;AAIX,IAAM,oBAAA,EAAsB,oBAAA;AAC5B,IAAM,eAAA,EAAiB,eAAA;AASvB,IAAM,YAAA,EAAc,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA;AAI7C,IAAM,yBAAA,EAA2B,MAAA,CAAE,MAAA,CAAO;AAAA,EAC/C,UAAA,EAAY,WAAA;AAAA,EACZ,IAAA,EAAM,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA;AAAA,EAC/B,IAAA,EAAM,MAAA,CACH,MAAA,CAAO,CAAA,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,cAAA,EAAgB,4CAA4C,CAAA,CAClE,QAAA,CAAS,CAAA;AAAA,EACZ,iBAAA,EAAmB,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC3D,kBAAA,EAAoB,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY,CAAA,CAAE,QAAA,CAAS;AAC9D,CAAC,CAAA;AAGM,IAAM,c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;AACA;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-LA5F5KR6.cjs","sourcesContent":[null,"/**\n * `POST /api/v1/organizations` · `/api/v1/projects` and friends — the\n * provisioning contract.\n *\n * A project-scoped client credential cannot authenticate the creation of the\n * project it is scoped to, and an organization key cannot authenticate the\n * creation of its own organization. So provisioning runs on two credentials\n * above the client one: a platform key that creates organizations and writes\n * quotas, and an organization key that creates and deletes projects inside one\n * organization.\n *\n * Quota writes sit with the platform key on purpose. Organization keys are held\n * one-per-workspace by the caller and so have a wide exposure surface; a leaked\n * one that could raise its own limits would turn a credential leak into an\n * unbounded bill.\n */\nimport { z } from \"zod\";\nimport { zInstant } from \"./index.js\";\nimport { zTimezone } from \"./query.js\";\n\nexport const PLATFORM_KEY_HEADER = \"reopt-platform-key\";\nexport const ORG_KEY_HEADER = \"reopt-org-key\";\n\n/**\n * The caller's own id for the thing being provisioned.\n *\n * Preferred over an `Idempotency-Key` header because this domain has a real\n * natural key — the caller already has a stable id for the workspace or brand —\n * and a header would make the caller store a second one just to retry safely.\n */\nexport const zExternalId = z.string().min(1).max(191);\n\n// ─── Organizations ──────────────────────────────────────────────────────────\n\nexport const zCreateOrganizationInput = z.object({\n externalId: zExternalId,\n name: z.string().min(1).max(200),\n slug: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9-]+$/, \"lowercase letters, digits and hyphens only\")\n .optional(),\n monthlyEventQuota: z.number().int().nonnegative().optional(),\n monthlyCreditQuota: z.number().int().nonnegative().optional(),\n});\nexport type CreateOrganizationInput = z.input<typeof zCreateOrganizationInput>;\n\nexport const zOrganization = z.object({\n id: z.string(),\n externalId: zExternalId,\n name: z.string(),\n slug: z.string(),\n monthlyEventQuota: z.number().int(),\n monthlyCreditQuota: z.number().int(),\n});\n\nexport const zCreateOrganizationResponse = z.object({\n /** `false` when this externalId already had an organization. */\n created: z.boolean(),\n organization: zOrganization,\n /**\n * Plaintext, returned here and nowhere else.\n *\n * Absent when `created` is `false`: re-issuing on every retry would let a\n * retry quietly multiply live credentials. A caller that lost the key rotates\n * instead — see `POST /api/v1/organizations/{id}/keys`.\n */\n orgKey: z.string().optional(),\n});\nexport type CreateOrganizationResponse = z.infer<typeof zCreateOrganizationResponse>;\n\nexport const zRotateOrganizationKeyResponse = z.object({\n organizationId: z.string(),\n keyPrefix: z.string(),\n /** Plaintext, returned once. Every previously issued key is revoked immediately. */\n orgKey: z.string(),\n});\nexport type RotateOrganizationKeyResponse = z.infer<typeof zRotateOrganizationKeyResponse>;\n\nexport const zUpdateOrganizationQuotaInput = z\n .object({\n monthlyEventQuota: z.number().int().nonnegative().optional(),\n monthlyCreditQuota: z.number().int().nonnegative().optional(),\n })\n .refine((value) => value.monthlyEventQuota !== undefined || value.monthlyCreditQuota !== undefined, {\n message: \"at least one quota must be given\",\n });\nexport type UpdateOrganizationQuotaInput = z.input<typeof zUpdateOrganizationQuotaInput>;\n\nexport const zUpdateOrganizationQuotaResponse = z.object({ organization: zOrganization });\nexport type UpdateOrganizationQuotaResponse = z.infer<typeof zUpdateOrganizationQuotaResponse>;\n\n// ─── Projects ───────────────────────────────────────────────────────────────\n\nexport const zCreateProjectInput = z.object({\n externalId: zExternalId,\n name: z.string().min(1).max(200),\n domain: z.string().max(253).optional(),\n /** Becomes the project's default for every query that omits one. */\n timezone: zTimezone.optional(),\n retentionDays: z.number().int().min(1).max(3650).optional(),\n});\nexport type CreateProjectInput = z.input<typeof zCreateProjectInput>;\n\nexport const zProject = z.object({\n id: z.string(),\n externalId: zExternalId,\n organizationId: z.string(),\n name: z.string(),\n /** The applied value — `\"UTC\"` when none was given. */\n timezone: z.string(),\n retentionDays: z.number().int().nullable(),\n});\n\nexport const zCreateProjectResponse = z.object({\n created: z.boolean(),\n project: zProject,\n /**\n * Two credentials, not one. A key embedded in a browser bundle must not also\n * be able to read the project's analytics, so the browser write key and the\n * server secret are separate rows with different reach.\n */\n clients: z.object({\n browser: z.object({\n id: z.string(),\n /** Public by design, and recoverable — it ships in page source anyway. */\n writeKey: z.string(),\n scopes: z.array(z.string()),\n }),\n server: z.object({\n id: z.string(),\n /** Plaintext, returned once. Absent when `created` is `false`. */\n clientSecret: z.string().optional(),\n scopes: z.array(z.string()),\n }),\n }),\n});\nexport type CreateProjectResponse = z.infer<typeof zCreateProjectResponse>;\n\nexport const zRotateClientSecretResponse = z.object({\n projectId: z.string(),\n clientId: z.string(),\n /** Plaintext, returned once. The previous secret stops working immediately. */\n clientSecret: z.string(),\n});\nexport type RotateClientSecretResponse = z.infer<typeof zRotateClientSecretResponse>;\n\nexport const zDeleteProjectInput = z.object({\n /**\n * A field in the body rather than `?purge=true`. This deletes the project's\n * Postgres rows and every analytics row behind it, with no undo — and a query\n * parameter is far too easy to fire from shell history or a mis-copied URL.\n */\n purge: z.literal(true),\n /** Checked against the project on record; a mismatch is refused. */\n externalId: zExternalId,\n});\nexport type DeleteProjectInput = z.input<typeof zDeleteProjectInput>;\n\nexport const zDeleteProjectResponse = z.object({\n projectId: z.string(),\n /** Idempotent, but it still says which of the two happened. */\n purge: z.enum([\"queued\", \"already-absent\"]),\n /** When the purge was marked. Absent for `already-absent`. */\n purgingAt: zInstant.optional(),\n});\nexport type DeleteProjectResponse = z.infer<typeof zDeleteProjectResponse>;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n// ─── Event metadata ─────────────────────────────────────────────────────────\n\n/**\n * `PUT /api/v1/projects/{projectId}/events/{name}` — catalogue settings for\n * one event name. Provisioning calls it to mark `form.submitted` a conversion\n * and an operational probe `internal`; the call is idempotent so a retried\n * provisioning run is harmless.\n */\nexport const EVENT_META_STATUSES = [\"active\", \"deprecated\", \"archived\", \"internal\"] as const;\nexport const zEventMetaStatus = z.enum(EVENT_META_STATUSES);\nexport type EventMetaStatus = z.infer<typeof zEventMetaStatus>;\n\nexport const zEventName = z.string().min(1).max(200);\n\nexport const zUpsertEventMetaInput = z\n .object({\n conversion: z.boolean().optional(),\n /** `internal` events are left out of every metric unless a query opts in. */\n status: zEventMetaStatus.optional(),\n /** Property keys the hourly rollups break this event down by. */\n rollupProperties: z.array(z.string().min(1).max(200)).max(20).optional(),\n })\n .strict();\nexport type UpsertEventMetaInput = z.infer<typeof zUpsertEventMetaInput>;\n\nexport const zEventMetaResponse = z.object({\n projectId: z.string(),\n name: z.string(),\n conversion: z.boolean(),\n status: zEventMetaStatus,\n rollupProperties: z.array(z.string()),\n /** Fields this call actually changed; empty on a repeat. */\n changed: z.array(z.string()),\n updatedAt: zInstant,\n});\nexport type EventMetaResponse = z.infer<typeof zEventMetaResponse>;\n\nexport const CONTROL_ERROR_CODES = [\n /** 401 — missing or invalid platform key / organization key. */\n \"unauthorized\",\n /** 403 — the organization key belongs to a different organization. */\n \"organization_scope_mismatch\",\n /**\n * 409 — this externalId exists with a materially different configuration.\n * Only fields whose change alters results are compared (see the docs); a\n * renamed brand is not a conflict.\n */\n \"external_id_conflict\",\n /** 409 — the externalId in a delete body does not match the project's. */\n \"project_external_id_mismatch\",\n /** 404 — no such organization or project, on an endpoint that is not idempotent. */\n \"not_found\",\n /** 400 — input failed the schema. */\n \"validation_failed\",\n /** 429 — per-credential rate limit. */\n \"rate_limited\",\n /** 500 — unexpected server failure. */\n \"internal_error\",\n] as const;\nexport const zControlErrorCode = z.enum(CONTROL_ERROR_CODES);\nexport type ControlErrorCode = z.infer<typeof zControlErrorCode>;\n\nexport const zControlError = z.object({\n status: z.number().int(),\n code: zControlErrorCode,\n error: z.string(),\n message: z.string().optional(),\n errors: z.unknown().optional(),\n requestId: z.string().optional(),\n});\nexport type ControlError = z.infer<typeof zControlError>;\n\n/** Paths, so the client and the route handlers cannot drift apart. */\nexport const CONTROL_API_PATHS = {\n organizations: \"/api/v1/organizations\",\n organization: (id: string) => `/api/v1/organizations/${encodeURIComponent(id)}`,\n organizationKeys: (id: string) => `/api/v1/organizations/${encodeURIComponent(id)}/keys`,\n projects: \"/api/v1/projects\",\n project: (id: string) => `/api/v1/projects/${encodeURIComponent(id)}`,\n clientRotate: (projectId: string, clientId: string) =>\n `/api/v1/projects/${encodeURIComponent(projectId)}/clients/${encodeURIComponent(clientId)}/rotate`,\n projectEvent: (projectId: string, name: string) =>\n `/api/v1/projects/${encodeURIComponent(projectId)}/events/${encodeURIComponent(name)}`,\n} as const;\n"]}
|
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunkKRJPEMFDcjs = require('./chunk-KRJPEMFD.cjs');
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
var _chunk3EEANNYNcjs = require('./chunk-3EEANNYN.cjs');
|
|
7
|
+
|
|
8
|
+
// src/ingest.ts
|
|
2
9
|
var _zod = require('zod');
|
|
3
|
-
var RESERVED_EVENT_NAMES = ["session_start", "session_end", "screen_view"];
|
|
4
10
|
var MAX_TRACK_PAYLOAD_BYTES = 512e3;
|
|
5
11
|
var zClientEventMetadata = {
|
|
6
12
|
/**
|
|
@@ -11,14 +17,27 @@ var zClientEventMetadata = {
|
|
|
11
17
|
*/
|
|
12
18
|
eventId: _zod.z.uuid(),
|
|
13
19
|
/** Event time, epoch milliseconds. */
|
|
14
|
-
timestamp: _zod.z.number().int().nonnegative()
|
|
20
|
+
timestamp: _zod.z.number().int().nonnegative(),
|
|
21
|
+
/**
|
|
22
|
+
* The browser device this event belongs to, for events a server records
|
|
23
|
+
* on a visitor's behalf (a form submission, an order). Lets one server
|
|
24
|
+
* batch carry events from many visitors — a forwarder cannot split its
|
|
25
|
+
* batches per device without breaking its failure model and its
|
|
26
|
+
* `accepted + duplicates + rejected === sent` invariant.
|
|
27
|
+
*
|
|
28
|
+
* Honoured in `server` mode only, where it takes precedence over the
|
|
29
|
+
* `reopt-device-id` request header. Ignored in `browser` mode: there the
|
|
30
|
+
* header is authoritative and a body field would be trivially forged.
|
|
31
|
+
* Same character set as every identity id.
|
|
32
|
+
*/
|
|
33
|
+
deviceId: _zod.z.string().regex(_chunkKRJPEMFDcjs.IDENTITY_ID_PATTERN, "expected an identity id").optional()
|
|
15
34
|
};
|
|
16
35
|
var zTrackPayload = _zod.z.object({
|
|
17
36
|
name: _zod.z.string().min(1).max(200),
|
|
18
37
|
properties: _zod.z.record(_zod.z.string(), _zod.z.unknown()).optional(),
|
|
19
38
|
profileId: _zod.z.string().max(500).or(_zod.z.number()).optional()
|
|
20
|
-
}).refine((data) => !RESERVED_EVENT_NAMES.includes(data.name), {
|
|
21
|
-
message: `Event name cannot be one of the reserved names: ${RESERVED_EVENT_NAMES.join(", ")}`,
|
|
39
|
+
}).refine((data) => !_chunk3EEANNYNcjs.RESERVED_EVENT_NAMES.includes(data.name), {
|
|
40
|
+
message: `Event name cannot be one of the reserved names: ${_chunk3EEANNYNcjs.RESERVED_EVENT_NAMES.join(", ")}`,
|
|
22
41
|
path: ["name"]
|
|
23
42
|
});
|
|
24
43
|
var zIdentifyPayload = _zod.z.object({
|
|
@@ -149,6 +168,5 @@ var zIngestError = _zod.z.object({
|
|
|
149
168
|
|
|
150
169
|
|
|
151
170
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
//# sourceMappingURL=chunk-XI3VP5DN.cjs.map
|
|
171
|
+
exports.MAX_TRACK_PAYLOAD_BYTES = MAX_TRACK_PAYLOAD_BYTES; exports.zTrackPayload = zTrackPayload; exports.zIdentifyPayload = zIdentifyPayload; exports.zIncrementPayload = zIncrementPayload; exports.zDecrementPayload = zDecrementPayload; exports.zTrackHandlerPayload = zTrackHandlerPayload; exports.INGEST_MODES = INGEST_MODES; exports.zIngestMode = zIngestMode; exports.INGEST_REJECTION_REASONS = INGEST_REJECTION_REASONS; exports.zIngestRejectionReason = zIngestRejectionReason; exports.zIngestRejection = zIngestRejection; exports.zIngestOkResponse = zIngestOkResponse; exports.zIngestAcceptedResponse = zIngestAcceptedResponse; exports.zIngestResponse = zIngestResponse; exports.reconcileIngestResponse = reconcileIngestResponse; exports.INGEST_ERROR_CODES = INGEST_ERROR_CODES; exports.zIngestErrorCode = zIngestErrorCode; exports.zIngestError = zIngestError;
|
|
172
|
+
//# sourceMappingURL=chunk-OGL3P7IH.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-OGL3P7IH.cjs","../src/ingest.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACIA,0BAAkB;AAgBX,IAAM,wBAAA,EAA0B,KAAA;AAEvC,IAAM,qBAAA,EAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO3B,OAAA,EAAS,MAAA,CAAE,IAAA,CAAK,CAAA;AAAA;AAAA,EAEhB,SAAA,EAAW,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaxC,QAAA,EAAU,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,KAAA,CAAM,qCAAA,EAAqB,yBAAyB,CAAA,CAAE,QAAA,CAAS;AACtF,CAAA;AAEO,IAAM,cAAA,EAAgB,MAAA,CAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA;AAAA,EAC/B,UAAA,EAAY,MAAA,CAAE,MAAA,CAAO,MAAA,CAAE,MAAA,CAAO,CAAA,EAAG,MAAA,CAAE,OAAA,CAAQ,CAAC,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EACvD,SAA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A;AAAA;AAEA,EAAA;AACF;AACyD;AAGpB;AACZ,EAAA;AACjB,EAAA;AACU,EAAA;AACa,EAAA;AAAA;AAEA,EAAA;AACE,EAAA;AAChC;AD1F6F;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-OGL3P7IH.cjs","sourcesContent":[null,"/**\n * `POST /api/track` — the ingest contract.\n *\n * The request shape is shared by both credential modes. The *response* shape\n * is where server-ingest differs: it reports per-event rejections instead of\n * failing a whole batch, because a forwarder that stalls on one malformed row\n * stops forwarding forever.\n *\n * Absorbed from the former internal `@reopt/ingest-contract`; that package is\n * now a deprecated re-export of this module.\n */\nimport { z } from \"zod\";\nimport { IDENTITY_ID_PATTERN } from \"./identity.js\";\n\nexport {\n AUTO_EVENT_NAMES,\n AUTO_EVENT_PROPERTIES,\n AUTO_EVENT_ROLLUP_KEYS,\n RESERVED_EVENT_NAMES,\n SCROLL_DEPTH_BUCKETS,\n scrollDepthBucket,\n type AutoEventName,\n type ScrollDepthBucket,\n} from \"./events.js\";\nimport { RESERVED_EVENT_NAMES } from \"./events.js\";\n\n/** Hard cap enforced by the route before the body is even parsed. */\nexport const MAX_TRACK_PAYLOAD_BYTES = 512_000;\n\nconst zClientEventMetadata = {\n /**\n * Client-generated UUID. This is the project-scoped idempotency key stored as\n * `RawEvent.clientEventId`; the server uses a separate globally unique raw\n * event id internally. Re-sending the same eventId to the same project is\n * always safe and always reported as a duplicate.\n */\n eventId: z.uuid(),\n /** Event time, epoch milliseconds. */\n timestamp: z.number().int().nonnegative(),\n /**\n * The browser device this event belongs to, for events a server records\n * on a visitor's behalf (a form submission, an order). Lets one server\n * batch carry events from many visitors — a forwarder cannot split its\n * batches per device without breaking its failure model and its\n * `accepted + duplicates + rejected === sent` invariant.\n *\n * Honoured in `server` mode only, where it takes precedence over the\n * `reopt-device-id` request header. Ignored in `browser` mode: there the\n * header is authoritative and a body field would be trivially forged.\n * Same character set as every identity id.\n */\n deviceId: z.string().regex(IDENTITY_ID_PATTERN, \"expected an identity id\").optional(),\n};\n\nexport const zTrackPayload = z\n .object({\n name: z.string().min(1).max(200),\n properties: z.record(z.string(), z.unknown()).optional(),\n profileId: z.string().max(500).or(z.number()).optional(),\n })\n .refine((data) => !RESERVED_EVENT_NAMES.includes(data.name as never), {\n message: `Event name cannot be one of the reserved names: ${RESERVED_EVENT_NAMES.join(\", \")}`,\n path: [\"name\"],\n });\n\nexport const zIdentifyPayload = z.object({\n profileId: z.string().min(1).max(500).or(z.number()),\n firstName: z.string().max(200).optional(),\n lastName: z.string().max(200).optional(),\n email: z.email().max(320).optional(),\n avatar: z.url().max(2000).optional(),\n properties: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const zIncrementPayload = z.object({\n profileId: z.string().min(1).max(500).or(z.number()),\n property: z.string().min(1).max(200),\n value: z.number().positive().optional(),\n});\n\nexport const zDecrementPayload = z.object({\n profileId: z.string().min(1).max(500).or(z.number()),\n property: z.string().min(1).max(200),\n value: z.number().positive().optional(),\n});\n\nexport const zTrackHandlerPayload = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"track\"), payload: zTrackPayload, ...zClientEventMetadata }),\n z.object({ type: z.literal(\"identify\"), payload: zIdentifyPayload, ...zClientEventMetadata }),\n z.object({ type: z.literal(\"increment\"), payload: zIncrementPayload, ...zClientEventMetadata }),\n z.object({ type: z.literal(\"decrement\"), payload: zDecrementPayload, ...zClientEventMetadata }),\n]);\n\nexport type ITrackPayload = z.infer<typeof zTrackPayload>;\nexport type IIdentifyPayload = z.infer<typeof zIdentifyPayload>;\nexport type IIncrementPayload = z.infer<typeof zIncrementPayload>;\nexport type IDecrementPayload = z.infer<typeof zDecrementPayload>;\nexport type ITrackHandlerPayload = z.infer<typeof zTrackHandlerPayload>;\n\n// ─── Ingest mode ────────────────────────────────────────────────────────────\n\n/**\n * Decided by the credential presented, never by a header the caller sets:\n * `reopt-write-key` alone → `browser`, `reopt-client-id` + `reopt-client-secret`\n * → `server`. A separate mode header could disagree with the credential; this\n * cannot.\n *\n * `browser` keeps the 5-second click dedup and device-scoped sessions.\n * `server` drops both and relies solely on `eventId` idempotency — a server\n * batch legitimately contains the same event name many times within one second,\n * and its \"device\" is a process, not a person.\n */\nexport const INGEST_MODES = [\"browser\", \"server\"] as const;\nexport const zIngestMode = z.enum(INGEST_MODES);\nexport type IngestMode = z.infer<typeof zIngestMode>;\n\n// ─── Response ───────────────────────────────────────────────────────────────\n\n/**\n * Why a single event in a batch was dropped. These are permanent: re-sending\n * the same row produces the same rejection, so a forwarder should count it as\n * skipped and advance its cursor rather than retry.\n */\nexport const INGEST_REJECTION_REASONS = [\n /** Failed the zod schema (bad eventId, missing name, wrong types…). */\n \"validation_failed\",\n /** Used one of RESERVED_EVENT_NAMES. */\n \"reserved_name\",\n /** Another row earlier in the same batch already claimed this eventId. */\n \"duplicate_in_batch\",\n] as const;\nexport const zIngestRejectionReason = z.enum(INGEST_REJECTION_REASONS);\nexport type IngestRejectionReason = z.infer<typeof zIngestRejectionReason>;\n\nexport const zIngestRejection = z.object({\n /** May be absent or malformed on `validation_failed` — hence `string`, not `uuid`. */\n eventId: z.string(),\n /** Position in the submitted batch. The only reliable identifier when eventId itself is bad. */\n index: z.number().int().nonnegative(),\n reason: zIngestRejectionReason,\n message: z.string().optional(),\n});\nexport type IngestRejection = z.infer<typeof zIngestRejection>;\n\nconst ingestCounts = {\n /** Raw events newly persisted by this request. */\n accepted: z.number().int().nonnegative(),\n /**\n * Events the server already had. In `server` mode this is exactly the\n * eventId-idempotency count; in `browser` mode it also includes the\n * 5-second click dedup.\n */\n duplicates: z.number().int().nonnegative(),\n /** Always `[]` in `browser` mode, where a bad row fails the whole batch. */\n rejected: z.array(zIngestRejection),\n};\n\n/** 200 — accepted and handed to the materialize queue. */\nexport const zIngestOkResponse = z.object({\n status: z.literal(\"ok\"),\n requestId: z.string(),\n mode: zIngestMode,\n ...ingestCounts,\n queued: z.boolean(),\n});\n\n/**\n * 202 — raw events landed, but enqueueing the materialize task failed. No data\n * is lost: the `replay-unmaterialized` cron picks these up. A forwarder should\n * treat this as success and advance its cursor. Carries the same counts as 200\n * so the reconciliation below works here too.\n */\nexport const zIngestAcceptedResponse = z.object({\n status: z.literal(\"accepted\"),\n requestId: z.string(),\n mode: zIngestMode,\n ...ingestCounts,\n backgroundQueued: z.literal(false),\n replay: z.literal(\"unmaterialized-raw-events\"),\n});\n\nexport const zIngestResponse = z.discriminatedUnion(\"status\", [zIngestOkResponse, zIngestAcceptedResponse]);\n\nexport type IngestOkResponse = z.infer<typeof zIngestOkResponse>;\nexport type IngestAcceptedResponse = z.infer<typeof zIngestAcceptedResponse>;\nexport type IngestResponse = z.infer<typeof zIngestResponse>;\n\n/**\n * The reconciliation a forwarder runs on every 2xx:\n *\n * accepted + duplicates + rejected.length === events sent\n *\n * A mismatch means the server silently dropped something, which is exactly the\n * failure mode this contract exists to make impossible to miss.\n */\nexport function reconcileIngestResponse(response: IngestResponse, sentCount: number): boolean {\n return response.accepted + response.duplicates + response.rejected.length === sentCount;\n}\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n/**\n * Stable machine-readable codes. Branch on these, never on `error`/`message`,\n * which are prose and may be reworded.\n */\nexport const INGEST_ERROR_CODES = [\n /** 401 — unknown or mismatched credentials. Stop and alert; do not retry. */\n \"unauthorized\",\n /** 400 — body was not valid JSON. */\n \"invalid_json\",\n /** 400 — request exceeded MAX_TRACK_PAYLOAD_BYTES. Split the batch. */\n \"payload_too_large\",\n /** 400 — zero events submitted. */\n \"empty_batch\",\n /** 400 — batch contained a `type: \"alias\"` event, which is not supported. */\n \"alias_unsupported\",\n /** 400 — the project has no organization; it cannot be billed or quota-checked. */\n \"project_without_organization\",\n /** 400 — `browser` mode only: a row failed validation. `server` mode reports these in `rejected[]`. */\n \"validation_failed\",\n /** 429 — per-project request rate limit. `Retry-After` set. Pause this tick, keep the cursor. */\n \"rate_limited\",\n /** 429 — the organization's monthly event quota is exhausted. `Retry-After` set (capped at 1h). Alert: a human must raise the limit. */\n \"quota_exceeded\",\n /** 410 — the project is being deleted. Permanent; stop sending. */\n \"project_purging\",\n /** 500 — unexpected server failure. Back off and retry. */\n \"internal_error\",\n] as const;\nexport const zIngestErrorCode = z.enum(INGEST_ERROR_CODES);\nexport type IngestErrorCode = z.infer<typeof zIngestErrorCode>;\n\nexport const zIngestError = z.object({\n status: z.number().int(),\n code: zIngestErrorCode,\n error: z.string(),\n message: z.string().optional(),\n /** zod issues, when `code === \"validation_failed\"`. */\n errors: z.unknown().optional(),\n requestId: z.string().optional(),\n});\nexport type IngestError = z.infer<typeof zIngestError>;\n"]}
|