File size: 6,264 Bytes
fb38ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { FastifyBaseLogger } from "fastify";
import { BrowserLauncherOptions } from "../../../types/index.js";
import { ConfigurationError, ConfigurationField } from "../errors/launch-errors.js";

/**
 * Compares two Promise values by resolving them and checking if their serialized
 * representations are equal.
 * @param current - Current value or Promise<value>
 * @param next - Next value or Promise<value>
 * @returns Promise<boolean> - True if serialized values are equal
 */
export async function comparePromiseValues<T>(
  current: T | Promise<T>,
  next: T | Promise<T>,
): Promise<boolean> {
  try {
    const [currentValue, nextValue] = await Promise.all([
      Promise.resolve(current),
      Promise.resolve(next),
    ]);
    return JSON.stringify(currentValue) === JSON.stringify(nextValue);
  } catch (error) {
    // If either promise rejects, consider them not equal
    return false;
  }
}

/**
 * Validates a given launch configuration (not conclusive)
 */
export function validateLaunchConfig(config: BrowserLauncherOptions): void {
  // Validate dimensions
  if (config.dimensions) {
    if (config.dimensions.width <= 0 || config.dimensions.height <= 0) {
      throw new ConfigurationError(
        "Dimensions must be positive numbers",
        ConfigurationField.DIMENSIONS,
        config.dimensions,
      );
    }
    if (config.dimensions.width > 7680 || config.dimensions.height > 4320) {
      throw new ConfigurationError(
        "Dimensions are unreasonably large (max 7680x4320)",
        ConfigurationField.DIMENSIONS,
        config.dimensions,
      );
    }
  }

  // Validates proxy URL format
  if (config.options.proxyUrl) {
    try {
      new URL(config.options.proxyUrl);
    } catch {
      throw new ConfigurationError(
        `Invalid proxy URL format: ${config.options.proxyUrl}`,
        ConfigurationField.PROXY_URL,
        config.options.proxyUrl,
      );
    }
  }
}

/**
 * Validates and resolves the timezone configuration
 * @param logger - Fastify logger instance for warning messages
 * @param timezonePromise - Promise resolving to the timezone string
 * @param timeoutMs - Maximum time to wait for timezone resolution (default: 10000ms)
 * @returns Resolved and validated timezone string
 * @throws ConfigurationError if the timezone is invalid or cannot be resolved
 */
export async function validateTimezone(
  logger: FastifyBaseLogger,
  timezonePromise: Promise<string>,
  timeoutMs: number = 10000,
): Promise<string> {
  try {
    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(() => {
        reject(new Error(`Timezone validation timeout after ${timeoutMs}ms`));
      }, timeoutMs);
    });

    const timezone = await Promise.race([timezonePromise, timeoutPromise]);
    try {
      Intl.DateTimeFormat(undefined, { timeZone: timezone });
      return timezone;
    } catch (timezoneError) {
      throw new ConfigurationError(
        `Invalid timezone resolved: ${timezone}`,
        ConfigurationField.TIMEZONE,
        timezone,
      );
    }
  } catch (error) {
    if (error instanceof ConfigurationError) {
      throw error;
    }
    throw new ConfigurationError(
      `Failed to resolve timezone: ${error}`,
      ConfigurationField.TIMEZONE,
      undefined,
    );
  }
}

/**
 * Checks if two launch configurations are reusable
 * @param current - The current launch configuration
 * @param next - The next launch configuration
 * @returns True if the configurations are reusable, false otherwise
 */

export async function isSimilarConfig(
  current?: BrowserLauncherOptions,
  next?: BrowserLauncherOptions,
): Promise<boolean> {
  if (!current || !next) {
    return false;
  }

  // Start timezone comparison immediately (don't await yet)
  // This allows the Promise to resolve in parallel with our synchronous checks
  const timezoneComparisonPromise = comparePromiseValues(
    current.timezone || Promise.resolve(""),
    next.timezone || Promise.resolve(""),
  );

  const normalizeArgs = (args?: string[]) => (args || []).filter(Boolean).slice().sort();
  const normalizeExt = (ext?: string[]) => (ext || []).slice().sort();

  const currentHeadless = current.options?.headless ?? true;
  const nextHeadless = next.options?.headless ?? true;

  const currentProxy = current.options?.proxyUrl || "";
  const nextProxy = next.options?.proxyUrl || "";

  const currentArgs = normalizeArgs(current.options?.args);
  const nextArgs = normalizeArgs(next.options?.args);

  const currentExt = normalizeExt(current.extensions);
  const nextExt = normalizeExt(next.extensions);

  const currentBlockAds = current.blockAds ?? true;
  const nextBlockAds = next.blockAds ?? true;

  const currentUserAgent = current.userAgent || "";
  const nextUserAgent = next.userAgent || "";

  const currentUserDataDir = current.userDataDir || "";
  const nextUserDataDir = next.userDataDir || "";

  const currentSkipFingerprint = current.skipFingerprintInjection ?? false;
  const nextSkipFingerprint = next.skipFingerprintInjection ?? false;

  const currentWidth = current.dimensions?.width ?? 1920;
  const nextWidth = next.dimensions?.width ?? 1920;

  const currentHeight = current.dimensions?.height ?? 1080;
  const nextHeight = next.dimensions?.height ?? 1080;

  const {
    session: _s1,
    streaming: _w1,
    ...currentExtra
  } = (current.extra ?? {}) as Record<string, unknown>;
  const {
    session: _s2,
    streaming: _w2,
    ...nextExtra
  } = (next.extra ?? {}) as Record<string, unknown>;

  return (
    currentHeadless === nextHeadless &&
    currentProxy === nextProxy &&
    currentUserAgent === nextUserAgent &&
    currentUserDataDir === nextUserDataDir &&
    currentSkipFingerprint === nextSkipFingerprint &&
    currentWidth === nextWidth &&
    currentHeight === nextHeight &&
    currentBlockAds === nextBlockAds &&
    JSON.stringify(currentArgs) === JSON.stringify(nextArgs) &&
    JSON.stringify(currentExt) === JSON.stringify(nextExt) &&
    JSON.stringify(currentExtra) === JSON.stringify(nextExtra) &&
    JSON.stringify(current.userPreferences) === JSON.stringify(next.userPreferences) &&
    JSON.stringify(current.deviceConfig) === JSON.stringify(next.deviceConfig) &&
    (await timezoneComparisonPromise)
  );
}