@reopt-ai/data-contract 0.3.0 → 0.5.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/README.md +11 -4
- package/dist/{chunk-2LJ7JLDX.js → chunk-2LZBZXBF.js} +9 -3
- package/dist/chunk-2LZBZXBF.js.map +1 -0
- package/dist/{chunk-ATPS4UV6.cjs → chunk-4B4AY44F.cjs} +33 -7
- package/dist/chunk-4B4AY44F.cjs.map +1 -0
- package/dist/{chunk-J4VD3TLV.js → chunk-AHXPQQKO.js} +30 -4
- package/dist/chunk-AHXPQQKO.js.map +1 -0
- package/dist/{chunk-55IWO4S3.js → chunk-BCGR27G2.js} +123 -11
- package/dist/chunk-BCGR27G2.js.map +1 -0
- package/dist/{chunk-3A7WZ7L6.js → chunk-MFZEIH5Z.js} +5 -4
- package/dist/chunk-MFZEIH5Z.js.map +1 -0
- package/dist/{chunk-KXEQGD3E.cjs → chunk-OLSMH4RY.cjs} +9 -3
- package/dist/chunk-OLSMH4RY.cjs.map +1 -0
- package/dist/{chunk-I2T4HRBM.cjs → chunk-VQ2CD5MG.cjs} +131 -19
- package/dist/chunk-VQ2CD5MG.cjs.map +1 -0
- package/dist/{chunk-RDPPPFGO.cjs → chunk-XI3VP5DN.cjs} +5 -4
- package/dist/chunk-XI3VP5DN.cjs.map +1 -0
- package/dist/client.cjs +83 -43
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -2
- package/dist/client.d.ts +6 -2
- package/dist/client.js +45 -5
- package/dist/client.js.map +1 -1
- package/dist/control.cjs +14 -4
- package/dist/control.cjs.map +1 -1
- package/dist/control.d.cts +49 -7
- package/dist/control.d.ts +49 -7
- package/dist/control.js +15 -5
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/ingest.cjs +2 -2
- package/dist/ingest.d.cts +6 -6
- package/dist/ingest.d.ts +6 -6
- package/dist/ingest.js +1 -1
- package/dist/query.cjs +27 -3
- package/dist/query.cjs.map +1 -1
- package/dist/query.d.cts +302 -22
- package/dist/query.d.ts +302 -22
- package/dist/query.js +28 -4
- package/dist/report.cjs +85 -0
- package/dist/report.cjs.map +1 -0
- package/dist/report.d.cts +167 -0
- package/dist/report.d.ts +167 -0
- package/dist/report.js +85 -0
- package/dist/report.js.map +1 -0
- package/package.json +7 -2
- package/dist/chunk-2LJ7JLDX.js.map +0 -1
- package/dist/chunk-3A7WZ7L6.js.map +0 -1
- package/dist/chunk-55IWO4S3.js.map +0 -1
- package/dist/chunk-ATPS4UV6.cjs.map +0 -1
- package/dist/chunk-I2T4HRBM.cjs.map +0 -1
- package/dist/chunk-J4VD3TLV.js.map +0 -1
- package/dist/chunk-KXEQGD3E.cjs.map +0 -1
- package/dist/chunk-RDPPPFGO.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/control.ts"],"sourcesContent":["/**\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\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} as const;\n"],"mappings":";;;;;;;;AAgBA,SAAS,SAAS;AAIX,IAAM,sBAAsB;AAC5B,IAAM,iBAAiB;AASvB,IAAM,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAI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A,CAAK,OAAA,GAAU,GAAA;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,EAAA,CAAG,KAAA,EAAuC;AAC/C,IAAA,OACE,MAAA,WAAiB,cAAA,GAChB,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,IAAU,KAAA,GAAS,KAAA,CAAuC,eAAA,IAAmB,IAAA;AAAA,EAE/G;AACF,UAAA;ADtEA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,2aAAC","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-KXEQGD3E.cjs","sourcesContent":[null,"/**\n * `@reopt-ai/data-contract` — the wire contract between reopt-data and its\n * server-credential consumers (RFC-0023).\n *\n * Subpaths:\n * `@reopt-ai/data-contract` this module — version, shared primitives, errors\n * `@reopt-ai/data-contract/ingest` POST /api/track request + response schemas\n * `@reopt-ai/data-contract/query` POST /api/v1/query/* request + response schemas\n * `@reopt-ai/data-contract/control` provisioning request + response schemas\n * `@reopt-ai/data-contract/client` createDataClient() — typed fetch over all\n *\n * Only `/client` touches `fetch`; everything else is pure zod. The single\n * runtime dependency is zod, deliberately — consumers bundle this.\n */\nimport { z } from \"zod\";\n\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 */\nexport const CONTRACT_VERSION = \"0.3.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\n/**\n * A UTC calendar date. Windows are inclusive on both ends and are widened\n * server-side to `startDate T00:00:00Z` .. `endDate T23:59:59Z`.\n */\nexport const zDate = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/, \"expected YYYY-MM-DD (UTC)\");\n\n/** ISO-8601 instant, as produced by `Date#toISOString()`. */\nexport const zInstant = z.string().min(20);\n\n/**\n * Client credentials. The same pair authenticates both planes; what a given\n * client may reach is decided server-side by `Client.scopes`\n * (`\"ingest\"` / `\"query\"` / `\"provision\"`).\n */\nexport interface ClientCredentials {\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * Credentials are optional on the client itself because the provisioning\n * surface does not use them — it authenticates per call with a platform or\n * organization key. A caller that only provisions should not have to invent an\n * empty client id to satisfy a constructor.\n *\n * Reaching ingest or query without them fails with `credentials_missing`\n * rather than sending an unauthenticated request and reporting the 401 as a\n * server problem.\n */\nexport type OptionalClientCredentials = Partial<ClientCredentials>;\n\n/**\n * Every non-2xx response from either plane, plus the two failures the client\n * itself raises (`contract_mismatch`, `network_error`).\n */\nexport class DataApiError extends Error {\n /**\n * Brand for {@link DataApiError.is}. A bundler that inlines this module into\n * more than one entry point produces two distinct classes, and `instanceof`\n * silently stops matching — the brand survives that, and realm boundaries.\n */\n readonly isDataApiError = true as const;\n\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */\n readonly retryAfterMs?: number;\n /** zod issues for `validation_failed`, or the raw body when unparseable. */\n readonly details?: unknown;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n requestId?: string;\n retryAfterMs?: number;\n details?: unknown;\n }) {\n super(init.message);\n this.name = \"DataApiError\";\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId;\n this.retryAfterMs = init.retryAfterMs;\n this.details = init.details;\n }\n\n /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */\n get retryable(): boolean {\n return this.status === 429 || this.status >= 500;\n }\n\n /**\n * Prefer this over `instanceof` in a `catch`. It holds even when the class\n * has been duplicated — across CJS entry points, across bundler chunks, or\n * across realms — where `instanceof` quietly returns false.\n */\n static is(value: unknown): value is DataApiError {\n return (\n value instanceof DataApiError ||\n (typeof value === \"object\" && value !== null && (value as { isDataApiError?: unknown }).isDataApiError === true)\n );\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-RDPPPFGO.cjs","../src/ingest.ts"],"names":[],"mappings":"AAAA;ACWA,0BAAkB;AAGX,IAAM,qBAAA,EAAuB,CAAC,eAAA,EAAiB,aAAA,EAAe,aAAa,CAAA;AAG3E,IAAM,wBAAA,EAA0B,KAAA;AAEvC,IAAM,qBAAA,EAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3B,OAAA,EAAS,MAAA,CAAE,IAAA,CAAK,CAAA;AAAA;AAAA,EAEhB,SAAA,EAAW,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,CAAA,CAAE,WAAA,CAAY;AAC1C,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,SAAA,EAAW,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,GAAA,CAAI,GAAG,CAAA,CAAE,EAAA,CAAG,MAAA,CAAE,MAAA,CAAO,CAAC,CAAA,CAAE,QAAA,CAAS;AACzD,CAAC,CAAA,CACA,MAAA,CAAO,CAAC,IAAA,EAAA,GAAS,CAAC,oBAAA,CAAqB,QAAA,CAAS,IAAA,CAAK,IAAa,CAAA,EA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/data-contract/dist/chunk-RDPPPFGO.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\";\n\n/** Event names the pipeline reserves for its own session bookkeeping. */\nexport const RESERVED_EVENT_NAMES = [\"session_start\", \"session_end\", \"screen_view\"] as const;\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 idempotency key: it becomes the\n * `RawEvent` primary key, scoped to the project. Re-sending the same\n * eventId is 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\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"]}
|