| 20 | } |
| 21 | |
| 22 | export function parseSourceValue( |
| 23 | definition: SourceValueDefinition, |
| 24 | value: unknown, |
| 25 | sourceLabel: string, |
| 26 | rawKey: string, |
| 27 | ): unknown { |
| 28 | if (definition.multiple) { |
| 29 | const rawValues = Array.isArray(value) ? value : [value]; |
| 30 | return rawValues.map((entry) => |
| 31 | parseSourceValue( |
| 32 | { |
| 33 | ...definition, |
| 34 | multiple: false, |
| 35 | }, |
| 36 | entry, |
| 37 | sourceLabel, |
| 38 | rawKey, |
| 39 | ), |
| 40 | ); |
| 41 | } |
| 42 | |
| 43 | if (definition.type === 'boolean') { |
| 44 | return parseBooleanValue(value, sourceLabel, rawKey); |
| 45 | } |
| 46 | if (definition.type === 'booleanOrString') { |
| 47 | if (typeof value === 'boolean') return value; |
| 48 | if (typeof value === 'string' && parseBooleanLiteral(value) !== undefined) { |
| 49 | return parseBooleanLiteral(value); |
| 50 | } |
| 51 | if (typeof value === 'string' && value.trim().length > 0) return value; |
| 52 | throw new AppError( |
| 53 | 'INVALID_ARGS', |
| 54 | `Invalid value for "${rawKey}" in ${sourceLabel}. Expected boolean or non-empty string.`, |
| 55 | ); |
| 56 | } |
| 57 | if (definition.type === 'string') { |
| 58 | if (typeof value === 'string' && value.trim().length > 0) return value; |
| 59 | throw new AppError( |
| 60 | 'INVALID_ARGS', |
| 61 | `Invalid value for "${rawKey}" in ${sourceLabel}. Expected non-empty string.`, |
| 62 | ); |
| 63 | } |
| 64 | if (definition.type === 'enum') { |
| 65 | if (definition.setValue !== undefined) { |
| 66 | return parseEnumSetValue(definition, value, sourceLabel, rawKey); |
| 67 | } |
| 68 | if (typeof value !== 'string' || !definition.enumValues?.includes(value)) { |
| 69 | throw new AppError( |
| 70 | 'INVALID_ARGS', |
| 71 | `Invalid value for "${rawKey}" in ${sourceLabel}. Expected one of: ${definition.enumValues?.join(', ')}.`, |
| 72 | ); |
| 73 | } |
| 74 | return value; |
| 75 | } |
| 76 | const parsed = |
| 77 | typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : Number.NaN; |
| 78 | if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) { |
| 79 | throw new AppError( |