```typescript
export function flatten(items: readonly unknown[], depth?: number): unknown[] {
    if (typeof depth !== 'number' || !Number.isFinite(depth) || depth < 0) {
        throw new Error('Depth must be a non-negative integer or Infinity.');
    }

    const result: unknown[] = [];
    const stack: [unknown, number][] = items.map((item, index) => ([item, depth]));

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

    return result;
}
```