```ts
/**
 * Returns a new array with nested arrays flattened up to depth levels, defaulting to every level.
 * A string is a value, never something to iterate into, no matter how deep it appears.
 * A depth of 0 returns a copy of the input unchanged. The input must not be mutated.
 * Throws an Error unless depth is a non-negative integer or Infinity.
 *
 * @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 (!Number.isInteger(depth) || depth < 0) throw new Error("Depth must be a non-negative integer or Infinity");

  const result: unknown[] = [];

  const stack: [unknown[], number][] = [[items, depth]];

  while (stack.length > 0) {
    const [currentItems, currentDepth] = stack.pop()!;
    for (const item of currentItems) {
      if (Array.isArray(item) && currentDepth > 0) {
        stack.push([item, currentDepth - 1]);
      } else {
        result.push(item);
      }
    }
  }

  return result;
}
```