common.js
1 /** 2 * Shared utilities for CLI adapters. 3 */ 4 import { ArgumentError } from '@jackwener/opencli/errors'; 5 /** 6 * Clamp a numeric value to [min, max]. 7 * Matches the signature of lodash.clamp and Rust's clamp. 8 */ 9 export function clamp(value, min, max) { 10 return Math.max(min, Math.min(value, max)); 11 } 12 export function clampInt(raw, fallback, min, max) { 13 const parsed = Number(raw); 14 if (!Number.isFinite(parsed)) { 15 return fallback; 16 } 17 return clamp(Math.floor(parsed), min, max); 18 } 19 export function normalizeNumericId(value, label, example) { 20 const normalized = String(value ?? '').trim(); 21 if (!/^\d+$/.test(normalized)) { 22 throw new ArgumentError(`${label} must be a numeric ID`, `Pass a numeric ${label}, for example: ${example}`); 23 } 24 return normalized; 25 } 26 export function requireNonEmptyQuery(value, label = 'query') { 27 const normalized = String(value ?? '').trim(); 28 if (!normalized) { 29 throw new ArgumentError(`${label} cannot be empty`); 30 } 31 return normalized; 32 }