```ts
/** Truncate a string to the specified limit, replacing the last three characters with an ellipsis if necessary. */
export function truncate(text: string, limit: number): string {
  if (!Number.isInteger(limit) || limit < 3) {
    throw new Error('limit must be an integer of at least 3');
  }
  if (text.length <= limit) {
    return text;
  }
  const keep = limit - 3;
  return text.slice(0, keep) + '...';
}
```