spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / mods / telemetry / hooks / entries / checked-value / checked-value.ts
74 lines · 2.0 KBRaw
1import { CHOICE_TOKEN } from '../choice-token'
2import { CHOICES_LIMIT } from '../choices-limit'
3import { isRecord } from '../is-record'
4import type { Method } from '../method'
5import { refusal } from '../refusal'
6
7/**
8 * One property's value as it goes into the metadata: a finite number, a
9 * boolean, or a Choice's value chosen from its token list.
10 *
11 * A bare string is refused: free text never reaches the row.
12 *
13 * @param key the property's key, named in a refusal
14 * @param value what the caller passed under it
15 * @param method the method the property was passed to, named in a refusal
16 * @returns the value as stored: the boolean or finite number unchanged, or the
17 * chosen member when value is a Choice
18 */
19export function checkedValue(
20 key: string,
21 value: unknown,
22 method: Method = 'log',
23): string | number | boolean {
24 if (typeof value === 'boolean') {
25 return value
26 }
27
28 if (typeof value === 'number') {
29 if (Number.isFinite(value)) {
30 return value
31 }
32
33 throw refusal(`props.${key}: a number is finite`, method)
34 }
35
36 if (typeof value === 'string') {
37 throw refusal(
38 `props.${key}: free text is refused; a string is a Choice, ` +
39 `{ value, of: [...] }`,
40 method,
41 )
42 }
43
44 if (!isRecord(value) || !Array.isArray(value.of)) {
45 throw refusal(
46 `props.${key}: a value is a finite number, a boolean, or a Choice, ` +
47 `{ value, of: [...] }`,
48 method,
49 )
50 }
51
52 const members = value.of
53 const chosen = value.value
54
55 const isTokenList =
56 members.length > 0 &&
57 members.length <= CHOICES_LIMIT &&
58 members.every(
59 member => typeof member === 'string' && CHOICE_TOKEN.test(member),
60 )
61
62 if (!isTokenList) {
63 throw refusal(
64 `props.${key}.of: a list of 1 to ${CHOICES_LIMIT} ` + `lowercase tokens`,
65 method,
66 )
67 }
68
69 if (typeof chosen !== 'string' || !members.includes(chosen)) {
70 throw refusal(`props.${key}.value: one of the members of \`of\``, method)
71 }
72
73 return chosen
74}