```ts
/**
 * Flattens a nested array up to a specified depth.
 *
 * @param items - The array to flatten.
 * @param depth - The maximum depth to flatten. Defaults to Infinity.
 * @returns A new flattened array.
 */
export function flatten(items: readonly unknown[], depth?: number): unknown[] {
  if (depth === undefined) depth = Infinity;
  if (typeof depth !== 'number' || depth < 0 && depth !== Infinity) {
    throw new Error('Depth must be a non-negative integer or Infinity');
  }

  const result: unknown[] = [];
  const stack: { item: unknown; currentDepth: number }[] = items.map(item => ({ item, currentDepth: 1 }));

  while (stack.length > 0) {
    const { item, currentDepth } = stack.pop()!;
    if (Array.isArray(item) && currentDepth <= depth) {
      stack.push(...item.map(subItem => ({ item: subItem, currentDepth: currentDepth + 1 })));
    } else {
      result.unshift(item);
    }
  }

  return result;
}
```