Validates that an event conforms to the expected shape.
(event: unknown)
| 89 | |
| 90 | /** Validates that an event conforms to the expected shape. */ |
| 91 | function validateEvent(event: unknown): event is TelemetryEvent { |
| 92 | if (typeof event !== 'object' || event === null || Array.isArray(event)) { |
| 93 | return false |
| 94 | } |
| 95 | const e = event as Record<string, unknown> |
| 96 | |
| 97 | // 'type' must be a non-empty string |
| 98 | if (typeof e.type !== 'string' || e.type.length === 0) return false |
| 99 | |
| 100 | // 'timestamp' must be a finite number |
| 101 | if (typeof e.timestamp !== 'number' || !Number.isFinite(e.timestamp)) return false |
| 102 | |
| 103 | // 'session_id' is required and must be a string (can be empty – the |
| 104 | // rate limiter will derive a key if needed, but the field must exist) |
| 105 | if (typeof e.session_id !== 'string') return false |
| 106 | |
| 107 | // Reject events that are unreasonably large (> 64 KB serialised) |
| 108 | if (JSON.stringify(e).length > 65_536) return false |
| 109 | |
| 110 | return true |
| 111 | } |
| 112 | |
| 113 | // Handle CORS preflight |
| 114 | export const onRequestOptions: PagesFunction<Env> = async () => { |