File size: 8,814 Bytes
5448d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env node

import { spawn } from "node:child_process";
import { cpSync, existsSync, mkdirSync, readdirSync, renameSync } from "node:fs";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  resolveRuntimePorts,
  sanitizeColorEnv,
  spawnWithForwardedSignals,
  withRuntimePortEnv,
} from "../build/runtime-env.mjs";
import { bootstrapEnv } from "../build/bootstrap-env.mjs";

const mode = process.argv[2] === "start" ? "start" : "dev";
const cwd = process.cwd();
const appDir = join(cwd, "app");
const srcAppDir = join(cwd, "src", "app");
const appPage = join(appDir, "page.tsx");
const defaultBackupDir = join(cwd, "app.__qa_backup");
const backupDir = resolvePlaywrightAppBackupDir({
  cwd,
  baseBackupExists: existsSync(defaultBackupDir),
  appDirExists: existsSync(appDir),
});
const usingAlternativeBackupDir = backupDir !== defaultBackupDir;
const buildScript = join(cwd, "scripts", "build", "build-next-isolated.mjs");
const standaloneServer = join(cwd, testDistDir(), "standalone", "server.js");
const rootStaticDir = join(cwd, testDistDir(), "static");
const rootPublicDir = join(cwd, "public");
const standaloneStaticDir = join(cwd, testDistDir(), "standalone", ".next", "static");
const standalonePublicDir = join(cwd, testDistDir(), "standalone", "public");

let appDirMoved = false;

function testDistDir() {
  // Layer 1 moved the Next distDir default to .build/next; the Playwright
  // `start` runner must resolve the standalone server under the same dir.
  return process.env.NEXT_DIST_DIR || ".build/next";
}

function resolvePlaywrightDataDir({ cwd, env, pid = process.pid }) {
  if (typeof env.DATA_DIR === "string" && env.DATA_DIR.trim().length > 0) {
    return env.DATA_DIR;
  }

  return join(cwd, ".tmp", "playwright-data", String(pid));
}

export function resolvePlaywrightAppBackupDir({

  cwd,

  baseBackupExists,

  appDirExists,

  pid = process.pid,

  now = Date.now(),

}) {
  const baseBackupDir = join(cwd, "app.__qa_backup");
  if (!baseBackupExists || !appDirExists) {
    return baseBackupDir;
  }

  return join(cwd, `app.__qa_backup.${pid}.${now}`);
}

function shouldMoveAppDir() {
  return existsSync(appDir) && !existsSync(appPage) && existsSync(srcAppDir);
}

export function directoryHasEntries(dirPath) {
  try {
    return readdirSync(dirPath).length > 0;
  } catch {
    return false;
  }
}

export function standaloneAssetsNeedSync({

  standaloneServerPath,

  rootStaticDirPath,

  standaloneStaticDirPath,

}) {
  return (
    existsSync(standaloneServerPath) &&
    existsSync(rootStaticDirPath) &&
    !directoryHasEntries(standaloneStaticDirPath)
  );
}

export function syncStandaloneRuntimeAssets({

  standaloneServerPath,

  rootStaticDirPath,

  standaloneStaticDirPath,

  rootPublicDirPath,

  standalonePublicDirPath,

  log = console,

}) {
  if (!existsSync(standaloneServerPath)) return false;

  let changed = false;

  if (existsSync(rootPublicDirPath) && !directoryHasEntries(standalonePublicDirPath)) {
    cpSync(rootPublicDirPath, standalonePublicDirPath, {
      recursive: true,
      force: true,
    });
    changed = true;
  }

  if (existsSync(rootStaticDirPath) && !directoryHasEntries(standaloneStaticDirPath)) {
    mkdirSync(dirname(standaloneStaticDirPath), {
      recursive: true,
    });
    cpSync(rootStaticDirPath, standaloneStaticDirPath, {
      recursive: true,
      force: true,
    });
    changed = true;
  }

  if (changed) {
    log.log("[Playwright WebServer] Rehydrated standalone static/public assets");
  }

  return changed;
}

function prepareAppDir() {
  if (!shouldMoveAppDir()) return;

  if (usingAlternativeBackupDir) {
    console.warn(
      "[Playwright WebServer] Existing app.__qa_backup detected; using a per-run backup dir instead."
    );
  }

  renameSync(appDir, backupDir);
  appDirMoved = true;
  console.log("[Playwright WebServer] Temporarily moved app/ to app.__qa_backup");
}

function restoreAppDir() {
  if (!appDirMoved) return;
  if (!existsSync(backupDir) || existsSync(appDir)) return;

  renameSync(backupDir, appDir);
  console.log("[Playwright WebServer] Restored app/ directory");
}

const playwrightDataDir = resolvePlaywrightDataDir({
  cwd,
  env: process.env,
});
const bootstrapEnvVars = bootstrapEnv({
  quiet: true,
  dataDirOverride: playwrightDataDir,
});
const runtimePorts = resolveRuntimePorts(bootstrapEnvVars);
const bootstrapMode = process.env.OMNIROUTE_E2E_BOOTSTRAP_MODE || "auth";
const playwrightPassword =
  process.env.OMNIROUTE_E2E_PASSWORD || process.env.INITIAL_PASSWORD || "omniroute-e2e-password";
const testServerEnv = {
  ...sanitizeColorEnv(bootstrapEnvVars),
  ...sanitizeColorEnv(process.env),
  NODE_ENV: mode === "start" ? "production" : "development",
  DATA_DIR: playwrightDataDir,
  NEXT_PUBLIC_OMNIROUTE_E2E_MODE: process.env.NEXT_PUBLIC_OMNIROUTE_E2E_MODE || "1",
  OMNIROUTE_DISABLE_BACKGROUND_SERVICES:
    process.env.OMNIROUTE_DISABLE_BACKGROUND_SERVICES || "true",
  OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK: process.env.OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK || "true",
  OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK: process.env.OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK || "true",
  OMNIROUTE_HIDE_HEALTHCHECK_LOGS: process.env.OMNIROUTE_HIDE_HEALTHCHECK_LOGS || "true",
  ...(bootstrapMode === "open"
    ? {
        INITIAL_PASSWORD: "",
        OMNIROUTE_E2E_PASSWORD: "",
        OMNIROUTE_API_KEY: "",
      }
    : {
        INITIAL_PASSWORD: playwrightPassword,
        OMNIROUTE_E2E_PASSWORD: playwrightPassword,
      }),
  ...(process.env.OMNIROUTE_USE_TURBOPACK
    ? {
        OMNIROUTE_USE_TURBOPACK: process.env.OMNIROUTE_USE_TURBOPACK,
      }
    : {}),
};

export function shouldUseWebpackForPlaywrightDev({ mode, env }) {
  return mode === "dev" && env.OMNIROUTE_USE_TURBOPACK !== "1";
}

function runChild(command, args, env) {
  return new Promise((resolve) => {
    const child = spawn(command, args, {
      stdio: "inherit",
      env,
    });

    const forward = (signal) => {
      if (!child.killed) child.kill(signal);
    };

    process.on("SIGINT", forward);
    process.on("SIGTERM", forward);

    child.on("exit", (code, signal) => {
      process.off("SIGINT", forward);
      process.off("SIGTERM", forward);
      resolve({ code: code ?? 1, signal: signal ?? null });
    });
  });
}

async function runBuildForStart() {
  if (mode !== "start") return;
  if (process.env.OMNIROUTE_PLAYWRIGHT_SKIP_BUILD === "1") return;
  console.log("[Playwright WebServer] Building fresh standalone app for this run...");

  const buildEnv = withRuntimePortEnv(testServerEnv, runtimePorts);
  const result = await runChild(process.execPath, [buildScript], buildEnv);

  if (result.signal) {
    process.kill(process.pid, result.signal);
    return;
  }

  if (result.code !== 0) {
    process.exit(result.code);
  }
}

export async function main() {
  process.on("exit", restoreAppDir);
  process.on("uncaughtException", (error) => {
    restoreAppDir();
    throw error;
  });

  prepareAppDir();
  await runBuildForStart();

  if (mode === "start") {
    if (existsSync(standaloneServer)) {
      syncStandaloneRuntimeAssets({
        standaloneServerPath: standaloneServer,
        rootStaticDirPath: rootStaticDir,
        standaloneStaticDirPath: standaloneStaticDir,
        rootPublicDirPath: rootPublicDir,
        standalonePublicDirPath: standalonePublicDir,
      });

      spawnWithForwardedSignals(process.execPath, [standaloneServer], {
        stdio: "inherit",
        env: {
          ...withRuntimePortEnv(testServerEnv, runtimePorts),
          PORT: String(runtimePorts.dashboardPort),
          HOSTNAME: process.env.HOSTNAME || "127.0.0.1",
        },
      });
      return;
    }

    const args = [
      "./node_modules/next/dist/bin/next",
      "start",
      "--port",
      String(runtimePorts.dashboardPort),
    ];

    spawnWithForwardedSignals(process.execPath, args, {
      stdio: "inherit",
      env: withRuntimePortEnv(testServerEnv, runtimePorts),
    });
    return;
  }

  const args = [
    "./node_modules/next/dist/bin/next",
    mode,
    "--port",
    String(runtimePorts.dashboardPort),
  ];

  if (shouldUseWebpackForPlaywrightDev({ mode, env: testServerEnv })) {
    args.splice(2, 0, "--webpack");
  }

  spawnWithForwardedSignals(process.execPath, args, {
    stdio: "inherit",
    env: withRuntimePortEnv(testServerEnv, runtimePorts),
  });
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  await main();
}