@bigbinary/neeto-playwright-commons 5.0.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +1 -0
  2. package/index.d.ts +95 -22
  3. package/index.js +695 -313
  4. package/package.json +1 -1
package/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isPresent, keysToSnakeCase, isNotPresent, hyphenate, humanize, noop as noop$2, keysToCamelCase, truncate, isNotEmpty, _findBy, randomPick, findBy } from '@bigbinary/neeto-cist';
2
2
  import { faker } from '@faker-js/faker/locale/en';
3
3
  import * as fs from 'fs';
4
- import { readFileSync, writeFileSync, unlinkSync, mkdirSync, rmSync, existsSync, createWriteStream } from 'fs';
4
+ import { readFileSync, writeFileSync, unlinkSync } from 'fs';
5
5
  import { setTimeout as setTimeout$1 } from 'node:timers/promises';
6
6
  import os from 'os';
7
7
  import * as path from 'path';
@@ -9,7 +9,7 @@ import path__default from 'path';
9
9
  import { expect, test, chromium, defineConfig, devices } from '@playwright/test';
10
10
  import { stringify } from 'picoquery';
11
11
  import { getI18nInstance, initI18n } from 'playwright-i18next-fixture';
12
- import { isEmpty, mergeAll, curry, isNotNil, not, pluck, mergeDeepLeft } from 'ramda';
12
+ import { isEmpty, curry, isNotNil, not, pluck, mergeDeepLeft } from 'ramda';
13
13
  import { spawn, execSync, spawnSync } from 'child_process';
14
14
  import dayjs from 'dayjs';
15
15
  import { Redis } from 'ioredis';
@@ -26,6 +26,7 @@ import https from 'https';
26
26
  import { countries } from 'countries-list';
27
27
  import { parsePhoneNumberWithError } from 'libphonenumber-js';
28
28
  import { lock } from 'proper-lockfile';
29
+ import * as net from 'net';
29
30
  import dotenv from 'dotenv';
30
31
 
31
32
  const BASE_URL = "/api/v1";
@@ -1255,19 +1256,19 @@ const POLL_TIMEOUT_MS = 130_000;
1255
1256
  const cookieKey = (provider) => `pw:cookies:${provider}`;
1256
1257
  const lockKey = (provider) => `pw:lock:${provider}`;
1257
1258
  let cachedClient;
1258
- const log$2 = (msg) => console.log(`[cookieCache] ${msg}`);
1259
+ const log$1 = (msg) => console.log(`[cookieCache] ${msg}`);
1259
1260
  const getRedis = () => {
1260
1261
  if (cachedClient !== undefined)
1261
1262
  return cachedClient;
1262
1263
  const url = process.env.MINITEST_COORDINATOR;
1263
1264
  if (!url) {
1264
- log$2("MINITEST_COORDINATOR is not set — Redis unavailable, skipping cache");
1265
+ log$1("MINITEST_COORDINATOR is not set — Redis unavailable, skipping cache");
1265
1266
  cachedClient = null;
1266
1267
  return null;
1267
1268
  }
1268
- log$2(`Connecting to Redis at ${url}`);
1269
+ log$1(`Connecting to Redis at ${url}`);
1269
1270
  cachedClient = new Redis(url, { maxRetriesPerRequest: 2 });
1270
- cachedClient.on("error", err => log$2(`Redis error: ${err.message}`));
1271
+ cachedClient.on("error", err => log$1(`Redis error: ${err.message}`));
1271
1272
  return cachedClient;
1272
1273
  };
1273
1274
  const restoreCookies = async (redis, provider, context) => {
@@ -1276,11 +1277,11 @@ const restoreCookies = async (redis, provider, context) => {
1276
1277
  return false;
1277
1278
  try {
1278
1279
  await context.addCookies(JSON.parse(cached));
1279
- log$2(`Cache hit for "${provider}" — restoring cookies, skipping login`);
1280
+ log$1(`Cache hit for "${provider}" — restoring cookies, skipping login`);
1280
1281
  return true;
1281
1282
  }
1282
1283
  catch {
1283
- log$2(`Cache entry for "${provider}" is corrupt — falling back to login`);
1284
+ log$1(`Cache entry for "${provider}" is corrupt — falling back to login`);
1284
1285
  await redis.del(cookieKey(provider)).catch(noop$2);
1285
1286
  return false;
1286
1287
  }
@@ -1293,14 +1294,14 @@ const startLockRefresh = (redis, provider) => {
1293
1294
  .expire(lockKey(provider), LOCK_TTL_SECONDS)
1294
1295
  .then(success => {
1295
1296
  if (success)
1296
- log$2(`Refreshed lock TTL for "${provider}"`);
1297
+ log$1(`Refreshed lock TTL for "${provider}"`);
1297
1298
  })
1298
1299
  .catch(noop$2);
1299
1300
  }, LOCK_REFRESH_INTERVAL_MS);
1300
1301
  return () => clearInterval(interval);
1301
1302
  };
1302
1303
  const pollForCookies = async (redis, provider, context) => {
1303
- log$2(`"${provider}" lock held by another shard — waiting for cached cookies`);
1304
+ log$1(`"${provider}" lock held by another shard — waiting for cached cookies`);
1304
1305
  const controller = new AbortController();
1305
1306
  const { signal } = controller;
1306
1307
  const timeout = setTimeout$1(POLL_TIMEOUT_MS, undefined, { signal }).then(() => {
@@ -1326,11 +1327,11 @@ const pollForCookies = async (redis, provider, context) => {
1326
1327
  const cacheCookies = async (redis, provider, context, allowedDomains) => {
1327
1328
  const cookies = (await context.cookies()).filter(({ domain }) => allowedDomains.some(d => domain.includes(d)));
1328
1329
  if (cookies.length === 0) {
1329
- log$2(`No cookies found for "${provider}" after login — skipping cache`);
1330
+ log$1(`No cookies found for "${provider}" after login — skipping cache`);
1330
1331
  return;
1331
1332
  }
1332
1333
  await redis.set(cookieKey(provider), JSON.stringify(cookies), "EX", COOKIES_TTL_SECONDS);
1333
- log$2(`Cached ${cookies.length} cookies for "${provider}" (TTL: ${COOKIES_TTL_SECONDS}s)`);
1334
+ log$1(`Cached ${cookies.length} cookies for "${provider}" (TTL: ${COOKIES_TTL_SECONDS}s)`);
1334
1335
  };
1335
1336
  const withCookieCache = async (provider, context, login, allowedDomains) => {
1336
1337
  const redis = getRedis();
@@ -1349,7 +1350,7 @@ const withCookieCache = async (provider, context, login, allowedDomains) => {
1349
1350
  // lock released without cookies being set; retry lock acquisition
1350
1351
  continue;
1351
1352
  }
1352
- log$2(`Lock acquired for "${provider}" — running full login`);
1353
+ log$1(`Lock acquired for "${provider}" — running full login`);
1353
1354
  const stopLockRefresh = startLockRefresh(redis, provider);
1354
1355
  try {
1355
1356
  await login();
@@ -1738,20 +1739,10 @@ class OrganizationPage {
1738
1739
  appName: `neeto${product}`,
1739
1740
  shouldSignupViaApi,
1740
1741
  });
1741
- await this.neetoPlaywrightUtilities.waitForPageLoad({
1742
- customPageContext: this.page,
1743
- });
1744
- const userCredentials = readFileSyncIfExists();
1745
- await this.page.context().storageState({ path: STORAGE_STATE });
1746
- const mergedCredentials = mergeAll([
1747
- readFileSyncIfExists(),
1748
- userCredentials,
1749
- ]);
1750
- writeDataToFile(JSON.stringify(mergedCredentials, null, 2));
1751
- updateCredentials({ key: "isLoggedIn", value: "true" });
1752
- updateCredentials({
1753
- key: "baseUrl",
1754
- value: baseURLGenerator(product),
1742
+ await this.neetoPlaywrightUtilities.waitForPageLoad();
1743
+ await saveStorageState(this.page, {
1744
+ isLoggedIn: "true",
1745
+ baseUrl: baseURLGenerator(product),
1755
1746
  });
1756
1747
  };
1757
1748
  updateSubdomainIfExists = async (appName) => {
@@ -2042,11 +2033,7 @@ const login = async ({ page, loginPath = "/", }) => {
2042
2033
  if (shouldSkipSetupAndTeardown() || !IS_DEV_ENV)
2043
2034
  return;
2044
2035
  await authenticateUser({ page, loginPath });
2045
- const userCredentials = readFileSyncIfExists();
2046
- await page.context().storageState({ path: STORAGE_STATE });
2047
- const mergedCredentials = mergeAll([readFileSyncIfExists(), userCredentials]);
2048
- writeDataToFile(JSON.stringify(mergedCredentials, null, 2));
2049
- updateCredentials({ key: "isLoggedIn", value: "true" });
2036
+ await saveStorageState(page, { isLoggedIn: "true" });
2050
2037
  };
2051
2038
 
2052
2039
  const REVIEW_APP_WAKE_TIMEOUT = 10 * 60_000;
@@ -2113,11 +2100,7 @@ const loginToReviewApp = async ({ page, loginPath = "/login", }) => {
2113
2100
  return;
2114
2101
  await waitForReviewApp();
2115
2102
  await authenticateUser({ page, loginPath });
2116
- const userCredentials = readFileSyncIfExists();
2117
- await page.context().storageState({ path: STORAGE_STATE });
2118
- const mergedCredentials = mergeAll([readFileSyncIfExists(), userCredentials]);
2119
- writeDataToFile(JSON.stringify(mergedCredentials, null, 2));
2120
- updateCredentials({ key: "isLoggedIn", value: "true" });
2103
+ await saveStorageState(page, { isLoggedIn: "true" });
2121
2104
  };
2122
2105
  const reviewAppOrganizationOptions = ({ subdomain = CREDENTIALS.subdomainName, loginPath = "/login", } = {}) => IS_REVIEW_ENV
2123
2106
  ? {
@@ -2171,6 +2154,16 @@ const updateCredentials = ({ key, value }) => {
2171
2154
  data["user"][key] = value;
2172
2155
  return writeDataToFile(JSON.stringify(data));
2173
2156
  };
2157
+ const saveStorageState = async (page, credentials = {}) => {
2158
+ const { user = {} } = readFileSyncIfExists();
2159
+ await page.context().storageState({ path: STORAGE_STATE });
2160
+ const csrfTokenLocator = page.locator("[name='csrf-token']");
2161
+ const csrfToken = (await csrfTokenLocator.getAttribute("content")) ?? "";
2162
+ return writeDataToFile(JSON.stringify({
2163
+ ...readFileSyncIfExists(),
2164
+ user: { ...user, ...credentials, csrfToken },
2165
+ }, null, 2));
2166
+ };
2174
2167
  const removeCredentialFile = () => {
2175
2168
  try {
2176
2169
  fs.existsSync(STORAGE_STATE) && fs.unlinkSync(STORAGE_STATE);
@@ -2832,9 +2825,12 @@ class CustomCommands {
2832
2825
  this.t = getI18nInstance().t;
2833
2826
  }
2834
2827
  initializeCsrfToken = async () => {
2835
- this.csrfToken = await this.page
2836
- .locator("[name='csrf-token']")
2837
- .getAttribute("content");
2828
+ this.csrfToken =
2829
+ this.page.url() === "about:blank"
2830
+ ? getGlobalUserState()?.csrfToken
2831
+ : await this.page
2832
+ .locator("[name='csrf-token']")
2833
+ .getAttribute("content");
2838
2834
  return this.csrfToken;
2839
2835
  };
2840
2836
  blockExternalResources = (page = this.page) => Promise.all(THIRD_PARTY_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())));
@@ -3873,11 +3869,6 @@ class ColorPickerUtils {
3873
3869
 
3874
3870
  const commands = {
3875
3871
  neetoPlaywrightUtilities: ({ page, request, baseURL }, use) => use(new CustomCommands(page, request, baseURL)),
3876
- page: async ({ page }, use) => {
3877
- await page.goto("/");
3878
- await page.waitForLoadState();
3879
- await use(page);
3880
- },
3881
3872
  mailerUtils: async ({ neetoPlaywrightUtilities }, use) => {
3882
3873
  const mailerUtils = new MailerUtils(neetoPlaywrightUtilities);
3883
3874
  await use(mailerUtils);
@@ -6508,19 +6499,12 @@ class CustomDomainPage {
6508
6499
  }, { timeout: 60_000, intervals: [1_000, 2_000, 5_000] })
6509
6500
  .toBe(true);
6510
6501
  };
6511
- saveCustomDomainState = async () => {
6512
- const { user } = readFileSyncIfExists();
6513
- await this.loginPage.context().storageState({ path: STORAGE_STATE });
6514
- const mergedCredentials = mergeAll([readFileSyncIfExists(), { user }]);
6515
- writeDataToFile(JSON.stringify(mergedCredentials, null, 2));
6516
- updateCredentials({ key: "baseUrl", value: this.customDomainURL });
6517
- updateCredentials({
6518
- key: "domain",
6519
- value: (this.isEdgeCertificateDomain() &&
6520
- CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX) ||
6521
- CUSTOM_DOMAIN_SUFFIX,
6522
- });
6523
- };
6502
+ saveCustomDomainState = async () => await saveStorageState(this.loginPage, {
6503
+ baseUrl: this.customDomainURL,
6504
+ domain: (this.isEdgeCertificateDomain() &&
6505
+ CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX) ||
6506
+ CUSTOM_DOMAIN_SUFFIX,
6507
+ });
6524
6508
  // Edge-certificate domains are already confirmed routable by waitForTrustedSSL.
6525
6509
  waitForDomainPropagation = async () => {
6526
6510
  // eslint-disable-next-line playwright/no-wait-for-timeout
@@ -10366,7 +10350,7 @@ const httpCheck = async (url, timeout = 3000) => {
10366
10350
  };
10367
10351
 
10368
10352
  const DIR = "/tmp/neeto-auth-web";
10369
- const CONFIG$1 = {
10353
+ const CONFIG = {
10370
10354
  DIR,
10371
10355
  LOG: "/tmp/neeto-auth-server.log",
10372
10356
  PORT: 9000,
@@ -10390,15 +10374,15 @@ const CONFIG$1 = {
10390
10374
  USERS_LOCK_RETRIES: 400,
10391
10375
  USERS_LOCK_RETRY_INTERVAL_MS: 100,
10392
10376
  };
10393
- const SCRIPTS_DIR$1 = path.join(import.meta.dirname, "scripts", "neeto-auth");
10377
+ const SCRIPTS_DIR = path.join(import.meta.dirname, "scripts", "neeto-auth");
10394
10378
  const escapeRubyString = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
10395
- const buildEmailCaptureInitializer = (targetApp) => {
10396
- const template = fs.readFileSync(path.join(SCRIPTS_DIR$1, "playwright_email_capture.rb.template"), "utf-8");
10379
+ const buildEmailCaptureInitializer$1 = (targetApp) => {
10380
+ const template = fs.readFileSync(path.join(SCRIPTS_DIR, "playwright_email_capture.rb.template"), "utf-8");
10397
10381
  return template.replace("{{TARGET_APP}}", escapeRubyString(targetApp));
10398
10382
  };
10399
- const log$1 = (msg) => console.log(`[NeetoAuth] ${msg}`);
10400
- const isServerListening$1 = () => httpCheck(`http://localhost:${CONFIG$1.PORT}/`);
10401
- const pollUntil = async (check, timeoutMs, intervalMs) => {
10383
+ const log = (msg) => console.log(`[NeetoAuth] ${msg}`);
10384
+ const isServerListening = () => httpCheck(`http://localhost:${CONFIG.PORT}/`);
10385
+ const pollUntil$1 = async (check, timeoutMs, intervalMs) => {
10402
10386
  const deadline = Date.now() + timeoutMs;
10403
10387
  while (Date.now() < deadline) {
10404
10388
  if (await check())
@@ -10407,7 +10391,7 @@ const pollUntil = async (check, timeoutMs, intervalMs) => {
10407
10391
  }
10408
10392
  return false;
10409
10393
  };
10410
- const isProcessAlive = (pid) => {
10394
+ const isProcessAlive$1 = (pid) => {
10411
10395
  try {
10412
10396
  process.kill(pid, 0);
10413
10397
  return true;
@@ -10422,8 +10406,8 @@ const listPids = (lsofArgs) => (spawnSync("lsof", ["-t", ...lsofArgs], { encodin
10422
10406
  .filter(pid => Number.isInteger(pid) && pid > 0);
10423
10407
  // "-i" reads the argument as a port, "-sTCP:LISTEN" drops httpCheck's client sockets.
10424
10408
  const listServerPids = (port) => listPids(["-i", `tcp:${port}`, "-sTCP:LISTEN"]).filter(pid => pid !== process.pid);
10425
- const readServerLog = () => fs.existsSync(CONFIG$1.LOG)
10426
- ? fs.readFileSync(CONFIG$1.LOG, "utf-8")
10409
+ const readServerLog = () => fs.existsSync(CONFIG.LOG)
10410
+ ? fs.readFileSync(CONFIG.LOG, "utf-8")
10427
10411
  : "<no log file>";
10428
10412
  class NeetoAuthServer {
10429
10413
  process = null;
@@ -10440,20 +10424,20 @@ class NeetoAuthServer {
10440
10424
  };
10441
10425
  }
10442
10426
  get userMarkerPath() {
10443
- return path.join(CONFIG$1.USERS_DIR, String(process.pid));
10427
+ return path.join(CONFIG.USERS_DIR, String(process.pid));
10444
10428
  }
10445
10429
  registerAsUser = () => {
10446
- fs.mkdirSync(CONFIG$1.USERS_DIR, { recursive: true });
10430
+ fs.mkdirSync(CONFIG.USERS_DIR, { recursive: true });
10447
10431
  fs.writeFileSync(this.userMarkerPath, "");
10448
10432
  };
10449
10433
  // Deletes dead markers instead of skipping them: a reused pid would read as alive.
10450
10434
  listLiveUsers = () => {
10451
- if (!fs.existsSync(CONFIG$1.USERS_DIR))
10435
+ if (!fs.existsSync(CONFIG.USERS_DIR))
10452
10436
  return [];
10453
- return fs.readdirSync(CONFIG$1.USERS_DIR).filter(pid => {
10454
- if (isProcessAlive(Number(pid)))
10437
+ return fs.readdirSync(CONFIG.USERS_DIR).filter(pid => {
10438
+ if (isProcessAlive$1(Number(pid)))
10455
10439
  return true;
10456
- fs.rmSync(path.join(CONFIG$1.USERS_DIR, pid), { force: true });
10440
+ fs.rmSync(path.join(CONFIG.USERS_DIR, pid), { force: true });
10457
10441
  return false;
10458
10442
  });
10459
10443
  };
@@ -10465,32 +10449,32 @@ class NeetoAuthServer {
10465
10449
  // Already gone.
10466
10450
  }
10467
10451
  });
10468
- waitUntilDirIsFree = () => pollUntil(() => listPids(["+D", CONFIG$1.DIR]).length === 0, CONFIG$1.DIR_RELEASE_TIMEOUT_MS, CONFIG$1.DIR_RELEASE_POLL_MS);
10452
+ waitUntilDirIsFree = () => pollUntil$1(() => listPids(["+D", CONFIG.DIR]).length === 0, CONFIG.DIR_RELEASE_TIMEOUT_MS, CONFIG.DIR_RELEASE_POLL_MS);
10469
10453
  killServerOnPort = async () => {
10470
- this.killPids(listServerPids(CONFIG$1.PORT), "SIGKILL");
10454
+ this.killPids(listServerPids(CONFIG.PORT), "SIGKILL");
10471
10455
  await setTimeout$1(1000);
10472
10456
  };
10473
10457
  acquireSetupLock = async () => {
10474
10458
  try {
10475
- return await lock(CONFIG$1.DIR, {
10476
- lockfilePath: CONFIG$1.SETUP_LOCK,
10459
+ return await lock(CONFIG.DIR, {
10460
+ lockfilePath: CONFIG.SETUP_LOCK,
10477
10461
  realpath: false,
10478
- stale: CONFIG$1.SETUP_LOCK_STALE_MS,
10479
- update: CONFIG$1.SETUP_LOCK_UPDATE_MS,
10462
+ stale: CONFIG.SETUP_LOCK_STALE_MS,
10463
+ update: CONFIG.SETUP_LOCK_UPDATE_MS,
10480
10464
  retries: {
10481
- retries: CONFIG$1.SETUP_LOCK_RETRIES,
10482
- minTimeout: CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS,
10483
- maxTimeout: CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS,
10465
+ retries: CONFIG.SETUP_LOCK_RETRIES,
10466
+ minTimeout: CONFIG.SETUP_LOCK_RETRY_INTERVAL_MS,
10467
+ maxTimeout: CONFIG.SETUP_LOCK_RETRY_INTERVAL_MS,
10484
10468
  },
10485
- onCompromised: error => log$1(`Setup lock was compromised: ${error.message}`),
10469
+ onCompromised: error => log(`Setup lock was compromised: ${error.message}`),
10486
10470
  });
10487
10471
  }
10488
10472
  catch (error) {
10489
10473
  if (error.code !== "ELOCKED")
10490
10474
  throw error;
10491
- throw new Error(`[NeetoAuth] Waited ${(CONFIG$1.SETUP_LOCK_RETRIES * CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS) /
10475
+ throw new Error(`[NeetoAuth] Waited ${(CONFIG.SETUP_LOCK_RETRIES * CONFIG.SETUP_LOCK_RETRY_INTERVAL_MS) /
10492
10476
  60_000} minutes for another worker to finish the neeto-auth-web setup, and it ` +
10493
- `still holds ${CONFIG$1.SETUP_LOCK}. Delete that file if no setup is running.`);
10477
+ `still holds ${CONFIG.SETUP_LOCK}. Delete that file if no setup is running.`);
10494
10478
  }
10495
10479
  };
10496
10480
  withSetupLock = async (fn) => {
@@ -10505,16 +10489,16 @@ class NeetoAuthServer {
10505
10489
  };
10506
10490
  // Separate from the setup lock: the fast path must not queue behind a setup.
10507
10491
  withUsersLock = async (fn) => {
10508
- const release = await lock(CONFIG$1.USERS_DIR, {
10509
- lockfilePath: CONFIG$1.USERS_LOCK,
10492
+ const release = await lock(CONFIG.USERS_DIR, {
10493
+ lockfilePath: CONFIG.USERS_LOCK,
10510
10494
  realpath: false,
10511
- stale: CONFIG$1.USERS_LOCK_STALE_MS,
10495
+ stale: CONFIG.USERS_LOCK_STALE_MS,
10512
10496
  retries: {
10513
- retries: CONFIG$1.USERS_LOCK_RETRIES,
10514
- minTimeout: CONFIG$1.USERS_LOCK_RETRY_INTERVAL_MS,
10515
- maxTimeout: CONFIG$1.USERS_LOCK_RETRY_INTERVAL_MS,
10497
+ retries: CONFIG.USERS_LOCK_RETRIES,
10498
+ minTimeout: CONFIG.USERS_LOCK_RETRY_INTERVAL_MS,
10499
+ maxTimeout: CONFIG.USERS_LOCK_RETRY_INTERVAL_MS,
10516
10500
  },
10517
- onCompromised: error => log$1(`Users lock was compromised: ${error.message}`),
10501
+ onCompromised: error => log(`Users lock was compromised: ${error.message}`),
10518
10502
  });
10519
10503
  try {
10520
10504
  return await fn();
@@ -10524,33 +10508,33 @@ class NeetoAuthServer {
10524
10508
  }
10525
10509
  };
10526
10510
  ensureSetup = async () => {
10527
- if (fs.existsSync(CONFIG$1.SETUP_COMPLETE_MARKER)) {
10528
- log$1("Already set up, skipping.");
10511
+ if (fs.existsSync(CONFIG.SETUP_COMPLETE_MARKER)) {
10512
+ log("Already set up, skipping.");
10529
10513
  return;
10530
10514
  }
10531
10515
  const githubToken = await getGithubToken();
10532
- if (fs.existsSync(CONFIG$1.DIR)) {
10516
+ if (fs.existsSync(CONFIG.DIR)) {
10533
10517
  // We hold the setup lock and the port is free, so anything using this directory is an orphan.
10534
- log$1("Found an incomplete previous setup — killing any lingering " +
10518
+ log("Found an incomplete previous setup — killing any lingering " +
10535
10519
  "process using it and cleaning up before retrying.");
10536
- this.killPids(listPids(["+D", CONFIG$1.DIR]), "SIGKILL");
10520
+ this.killPids(listPids(["+D", CONFIG.DIR]), "SIGKILL");
10537
10521
  await this.waitUntilDirIsFree();
10538
- fs.rmSync(CONFIG$1.DIR, { recursive: true, force: true });
10522
+ fs.rmSync(CONFIG.DIR, { recursive: true, force: true });
10539
10523
  }
10540
- log$1("Running first-time setup...");
10524
+ log("Running first-time setup...");
10541
10525
  try {
10542
10526
  await this.runSetupScript(githubToken);
10543
- fs.writeFileSync(CONFIG$1.SETUP_COMPLETE_MARKER, "");
10527
+ fs.writeFileSync(CONFIG.SETUP_COMPLETE_MARKER, "");
10544
10528
  }
10545
10529
  catch {
10546
10530
  throw new Error("[NeetoAuth] First-time setup failed. Check the output above for details.");
10547
10531
  }
10548
- log$1("Setup complete.");
10532
+ log("Setup complete.");
10549
10533
  };
10550
10534
  // Async, not execSync: a blocked event loop stops proper-lockfile refreshing the lock.
10551
10535
  runSetupScript = (githubToken) => new Promise((resolve, reject) => {
10552
- const setupScript = path.join(SCRIPTS_DIR$1, "setup.sh");
10553
- const child = spawn("bash", [setupScript, CONFIG$1.DIR], {
10536
+ const setupScript = path.join(SCRIPTS_DIR, "setup.sh");
10537
+ const child = spawn("bash", [setupScript, CONFIG.DIR], {
10554
10538
  stdio: "inherit",
10555
10539
  env: { ...this.serverEnv, GITHUB_TOKEN: githubToken },
10556
10540
  });
@@ -10559,52 +10543,52 @@ class NeetoAuthServer {
10559
10543
  ? resolve()
10560
10544
  : reject(new Error(`setup.sh exited with code ${code}`)));
10561
10545
  });
10562
- waitForServer = async (timeoutMs = CONFIG$1.MAX_WAIT_MS) => {
10563
- const started = await pollUntil(() => {
10546
+ waitForServer = async (timeoutMs = CONFIG.MAX_WAIT_MS) => {
10547
+ const started = await pollUntil$1(() => {
10564
10548
  if (this.process !== null && this.process.exitCode !== null) {
10565
10549
  throw new Error(`[NeetoAuth] Server process exited unexpectedly with code ${this.process.exitCode}.\nLog:\n${readServerLog()}`);
10566
10550
  }
10567
- return isServerListening$1();
10568
- }, timeoutMs, CONFIG$1.WAIT_FOR_SERVER_POLL_MS);
10551
+ return isServerListening();
10552
+ }, timeoutMs, CONFIG.WAIT_FOR_SERVER_POLL_MS);
10569
10553
  if (started)
10570
10554
  return;
10571
10555
  throw new Error(`[NeetoAuth] Server did not start within ${timeoutMs / 1000}s.\nLog:\n${readServerLog()}`);
10572
10556
  };
10573
10557
  spawnServer = async () => {
10574
10558
  // Nothing can be using a server that does not exist yet, so these are from a previous run.
10575
- fs.rmSync(CONFIG$1.USERS_DIR, { recursive: true, force: true });
10559
+ fs.rmSync(CONFIG.USERS_DIR, { recursive: true, force: true });
10576
10560
  // Puma refuses to start over a pidfile it thinks is alive; the port is already confirmed free, so this one is stale.
10577
- fs.rmSync(CONFIG$1.SERVER_PID_FILE, { force: true });
10578
- log$1("Starting server...");
10579
- const logStream = fs.createWriteStream(CONFIG$1.LOG);
10561
+ fs.rmSync(CONFIG.SERVER_PID_FILE, { force: true });
10562
+ log("Starting server...");
10563
+ const logStream = fs.createWriteStream(CONFIG.LOG);
10580
10564
  this.process = spawn("bundle", [
10581
10565
  "exec",
10582
10566
  "rails",
10583
10567
  "server",
10584
10568
  "-p",
10585
- CONFIG$1.PORT.toString(),
10569
+ CONFIG.PORT.toString(),
10586
10570
  "-b",
10587
10571
  "0.0.0.0",
10588
10572
  ], {
10589
- cwd: CONFIG$1.DIR,
10573
+ cwd: CONFIG.DIR,
10590
10574
  stdio: ["ignore", "pipe", "pipe"],
10591
10575
  env: this.serverEnv,
10592
10576
  });
10593
10577
  this.process.stdout?.pipe(logStream);
10594
10578
  this.process.stderr?.pipe(logStream);
10595
10579
  await this.waitForServer();
10596
- log$1("Server ready.");
10580
+ log("Server ready.");
10597
10581
  };
10598
10582
  injectEmailCaptureInitializer = () => {
10599
- fs.writeFileSync(CONFIG$1.EMAIL_INIT, buildEmailCaptureInitializer(this.targetApp));
10583
+ fs.writeFileSync(CONFIG.EMAIL_INIT, buildEmailCaptureInitializer$1(this.targetApp));
10600
10584
  };
10601
10585
  isRunningForCurrentApp = () => {
10602
- if (!fs.existsSync(CONFIG$1.EMAIL_INIT))
10586
+ if (!fs.existsSync(CONFIG.EMAIL_INIT))
10603
10587
  return false;
10604
- const currentContent = fs.readFileSync(CONFIG$1.EMAIL_INIT, "utf-8");
10605
- return currentContent === buildEmailCaptureInitializer(this.targetApp);
10588
+ const currentContent = fs.readFileSync(CONFIG.EMAIL_INIT, "utf-8");
10589
+ return currentContent === buildEmailCaptureInitializer$1(this.targetApp);
10606
10590
  };
10607
- isServingCurrentApp = async () => (await isServerListening$1()) && this.isRunningForCurrentApp();
10591
+ isServingCurrentApp = async () => (await isServerListening()) && this.isRunningForCurrentApp();
10608
10592
  start = async () => {
10609
10593
  if (IS_STAGING_ENV)
10610
10594
  return;
@@ -10616,17 +10600,17 @@ class NeetoAuthServer {
10616
10600
  return true;
10617
10601
  });
10618
10602
  if (adopted) {
10619
- log$1("Server already running for this app.");
10603
+ log("Server already running for this app.");
10620
10604
  return;
10621
10605
  }
10622
10606
  await this.withSetupLock(async () => {
10623
10607
  // Re-check: another worker may have finished setup while we waited for the lock.
10624
10608
  if (await this.isServingCurrentApp()) {
10625
- log$1("Server already running for this app.");
10609
+ log("Server already running for this app.");
10626
10610
  return;
10627
10611
  }
10628
- if (await isServerListening$1()) {
10629
- log$1("Server running for a different app — restarting...");
10612
+ if (await isServerListening()) {
10613
+ log("Server running for a different app — restarting...");
10630
10614
  await this.killServerOnPort();
10631
10615
  }
10632
10616
  await this.ensureSetup();
@@ -10642,19 +10626,19 @@ class NeetoAuthServer {
10642
10626
  await this.withUsersLock(async () => {
10643
10627
  fs.rmSync(this.userMarkerPath, { force: true });
10644
10628
  if (this.listLiveUsers().length > 0) {
10645
- log$1("Other workers still using the server — leaving it running.");
10629
+ log("Other workers still using the server — leaving it running.");
10646
10630
  return;
10647
10631
  }
10648
10632
  if (!this.isRunningForCurrentApp()) {
10649
- log$1("Server on the port is serving another app — leaving it running.");
10633
+ log("Server on the port is serving another app — leaving it running.");
10650
10634
  this.process = null;
10651
10635
  return;
10652
10636
  }
10653
- log$1("Stopping server...");
10654
- const pids = listServerPids(CONFIG$1.PORT);
10637
+ log("Stopping server...");
10638
+ const pids = listServerPids(CONFIG.PORT);
10655
10639
  this.killPids(pids, "SIGTERM");
10656
- await Promise.all(pids.map(pid => pollUntil(() => !isProcessAlive(pid), CONFIG$1.PROCESS_EXIT_TIMEOUT_MS, CONFIG$1.PROCESS_EXIT_POLL_MS)));
10657
- this.killPids(listServerPids(CONFIG$1.PORT), "SIGKILL"); // Any stragglers.
10640
+ await Promise.all(pids.map(pid => pollUntil$1(() => !isProcessAlive$1(pid), CONFIG.PROCESS_EXIT_TIMEOUT_MS, CONFIG.PROCESS_EXIT_POLL_MS)));
10641
+ this.killPids(listServerPids(CONFIG.PORT), "SIGKILL"); // Any stragglers.
10658
10642
  // A start() that failed before binding leaves a child the sweep cannot see.
10659
10643
  this.process?.kill("SIGKILL");
10660
10644
  this.process = null;
@@ -10662,231 +10646,629 @@ class NeetoAuthServer {
10662
10646
  };
10663
10647
  }
10664
10648
 
10665
- const CONFIG = {
10666
- DIR: "/tmp/neeto-chat-widget",
10667
- LOG: "/tmp/neeto-chat-widget.log",
10668
- PORT: 8081,
10669
- MAX_WAIT_MS: 180_000,
10670
- LOCK_RETRY_MS: 500,
10671
- SERVER_POLL_INTERVAL_MS: 3000,
10672
- WEBPACK_DEV_FILE: "/tmp/neeto-chat-widget/webpack.dev.js",
10673
- LOCK_DIR: "/tmp/neeto-chat-widget.lock",
10674
- STATE_FILE: "/tmp/neeto-chat-widget.state.json",
10675
- };
10676
- const DEFAULT_STATE = { pid: null, refCount: 0 };
10677
- const WIDGET_BASE_URL = `http://localhost:${CONFIG.PORT}`;
10678
- const SCRIPTS_DIR = path.join(import.meta.dirname, "scripts", "neeto-chat-widget");
10679
- const log = (msg) => console.log(`[NeetoChatWidget] ${msg}`);
10680
- const isServerListening = () => httpCheck(`${WIDGET_BASE_URL}/main.js`);
10681
- class NeetoChatWidget {
10682
- process = null;
10683
- hasLease = false;
10684
- logStream = null;
10685
- get serverEnv() {
10686
- return { ...process.env };
10687
- }
10688
- withLock = async (fn) => {
10689
- while (true) {
10690
- try {
10691
- mkdirSync(CONFIG.LOCK_DIR);
10692
- break;
10693
- }
10694
- catch (error) {
10695
- const nodeError = error;
10696
- if (nodeError.code !== "EEXIST")
10697
- throw error;
10698
- await setTimeout$1(CONFIG.LOCK_RETRY_MS);
10699
- }
10700
- }
10701
- try {
10702
- return await Promise.resolve(fn());
10703
- }
10704
- finally {
10705
- rmSync(CONFIG.LOCK_DIR, { force: true, recursive: true });
10649
+ const EMAIL_CAPTURE_TEMPLATE = path.join(import.meta.dirname, "scripts", "neeto-auth", "playwright_email_capture.rb.template");
10650
+ const TEMPLATE_REDIS_URL = "redis://localhost:6379/1";
10651
+ // The Redis the app under test reads OTPs from; locally, bin/launch derives it from the app's port.
10652
+ const appRedisUrl = () => {
10653
+ if (process.env.REDIS_URL)
10654
+ return process.env.REDIS_URL;
10655
+ const appPort = Number(requireEnv("RAILS_SERVER_PORT"));
10656
+ return `redis://localhost:${appPort - 3000}/${appPort % 10}`;
10657
+ };
10658
+ const buildEmailCaptureInitializer = (targetApp) => {
10659
+ const template = fs.readFileSync(EMAIL_CAPTURE_TEMPLATE, "utf-8");
10660
+ if (!template.includes(TEMPLATE_REDIS_URL)) {
10661
+ throw new Error(`The email capture template no longer writes to ${TEMPLATE_REDIS_URL}; update buildEmailCaptureInitializer.`);
10662
+ }
10663
+ return template
10664
+ .replace(TEMPLATE_REDIS_URL, appRedisUrl())
10665
+ .replace("{{TARGET_APP}}", targetApp.replace(/[\\"]/g, "\\$&"));
10666
+ };
10667
+
10668
+ // Synced into every product by neeto-commons-backend.
10669
+ const SETUP_SCRIPT_PATH = ".neetoci/scripts/playwright/setup_local_servers.sh";
10670
+ // Started by ProductServer when nothing listens on `port`; `start` runs from the repo root.
10671
+ const LOCAL_SERVER_SERVICES = {
10672
+ opensearch: {
10673
+ port: 9200,
10674
+ start: "s=.neetoci/scripts/playwright/setup_opensearch.sh; bash $s setup && bash $s start",
10675
+ },
10676
+ };
10677
+ // Ports match each product's .dev_launch; Redis databases avoid 0 to 3, which the app under test uses.
10678
+ const LOCAL_SERVER_PRODUCTS = {
10679
+ auth: {
10680
+ port: 9000,
10681
+ redisDb: 10,
10682
+ initializers: [
10683
+ {
10684
+ path: "config/initializers/playwright_email_capture.rb",
10685
+ build: buildEmailCaptureInitializer,
10686
+ },
10687
+ ],
10688
+ },
10689
+ desk: { port: 8910, redisDb: 11 },
10690
+ chat: { port: 8970, redisDb: 12, services: ["opensearch"] }, // Chat reindexes conversations in OpenSearch during requests.
10691
+ form: { port: 8890, redisDb: 13 },
10692
+ planner: { port: 8830, redisDb: 14 },
10693
+ };
10694
+ // The Redis port to use when REDIS_URL isn't set. Locally, REDIS_URL is usually not set.
10695
+ const DEFAULT_REDIS_PORT = 6379;
10696
+ const MAX_WAIT_MS = 120_000;
10697
+ const WAIT_FOR_SERVER_POLL_MS = 3000;
10698
+ const PROCESS_EXIT_TIMEOUT_MS = 10_000;
10699
+ const PROCESS_EXIT_POLL_MS = 500;
10700
+ const PORT_CHECK_TIMEOUT_MS = 1000;
10701
+ const SERVER_LOG_TAIL_LINES = 200;
10702
+ const SETUP_LOCK = {
10703
+ stale: 30_000,
10704
+ update: 10_000,
10705
+ retries: { retries: 480, minTimeout: 1000, maxTimeout: 1000 },
10706
+ };
10707
+ // The widget's lock is held only briefly once it runs, so waiters retry quickly, as NeetoChatWidget's lock did.
10708
+ const WIDGET_LOCK = {
10709
+ stale: 30_000,
10710
+ update: 10_000,
10711
+ retries: { retries: 960, minTimeout: 500, maxTimeout: 500 },
10712
+ };
10713
+ const USERS_LOCK = {
10714
+ stale: 30_000,
10715
+ retries: { retries: 400, minTimeout: 100, maxTimeout: 100 },
10716
+ };
10717
+ const buildPaths = (repo) => {
10718
+ const dir = `/tmp/${repo}`;
10719
+ return {
10720
+ DIR: dir,
10721
+ LOG: `${dir}.log`,
10722
+ SETUP_LOG: `${dir}-setup.log`,
10723
+ IDENTITY_FILE: `${dir}.identity`,
10724
+ STATE_FILE: `${dir}.state.json`,
10725
+ PREPARED_MARKER: path.join(dir, ".local_server_prepared"),
10726
+ DATABASE_MARKER: path.join(dir, ".local_server_database"),
10727
+ SETUP_LOCK_FILE: `${dir}-setup.lock`,
10728
+ SERVER_PID_FILE: path.join(dir, "tmp", "pids", "server.pid"),
10729
+ USERS_DIR: `${dir}-users`,
10730
+ USERS_LOCK_FILE: `${dir}-users.lock`,
10731
+ };
10732
+ };
10733
+ const CHAT_WIDGET_REPO = "neeto-chat-widget";
10734
+ const CHAT_WIDGET_URL = "http://localhost:8081";
10735
+ const CHAT_WIDGET_PATHS = buildPaths(CHAT_WIDGET_REPO);
10736
+ // Not a Rails product, so WidgetServer runs it instead of ProductServer.
10737
+ const CHAT_WIDGET = {
10738
+ name: "chatWidget",
10739
+ paths: CHAT_WIDGET_PATHS,
10740
+ webpackDevFile: path.join(CHAT_WIDGET_PATHS.DIR, "webpack.dev.js"),
10741
+ setupScript: path.join(import.meta.dirname, "scripts", CHAT_WIDGET_REPO, "setup.sh"),
10742
+ baseUrl: CHAT_WIDGET_URL,
10743
+ readyUrl: `${CHAT_WIDGET_URL}/main.js`,
10744
+ maxWaitMs: 180_000,
10745
+ };
10746
+
10747
+ // The product's root is the nearest folder above the working directory that has the setup script.
10748
+ const findRepoRoot = () => {
10749
+ let dir = process.cwd();
10750
+ while (!fs.existsSync(path.join(dir, SETUP_SCRIPT_PATH))) {
10751
+ const parent = path.dirname(dir);
10752
+ if (parent === dir) {
10753
+ throw new Error(`[LocalServer] Couldn't find ${SETUP_SCRIPT_PATH} above ${process.cwd()}. Sync the common files from neeto-commons-backend.`);
10706
10754
  }
10707
- };
10708
- parseState = (raw) => {
10709
- if (!raw || typeof raw !== "object")
10710
- return DEFAULT_STATE;
10711
- const state = raw;
10712
- const pid = typeof state.pid === "number" ? state.pid : null;
10713
- const refCount = typeof state.refCount === "number" && state.refCount > 0
10714
- ? state.refCount
10715
- : 0;
10716
- return { pid, refCount };
10717
- };
10718
- readState = () => {
10719
- if (!existsSync(CONFIG.STATE_FILE))
10720
- return DEFAULT_STATE;
10721
- try {
10722
- return this.parseState(JSON.parse(readFileSync(CONFIG.STATE_FILE, "utf-8")));
10755
+ dir = parent;
10756
+ }
10757
+ return dir;
10758
+ };
10759
+ const pollUntil = async ({ check, timeoutMs, intervalMs, }) => {
10760
+ const deadline = Date.now() + timeoutMs;
10761
+ while (Date.now() < deadline) {
10762
+ if (await check())
10763
+ return true;
10764
+ await setTimeout$1(intervalMs);
10765
+ }
10766
+ return false;
10767
+ };
10768
+ const isProcessAlive = (pid) => {
10769
+ try {
10770
+ process.kill(pid, 0);
10771
+ return true;
10772
+ }
10773
+ catch {
10774
+ return false;
10775
+ }
10776
+ };
10777
+ const killPid = (pid, signal) => {
10778
+ if (pid === null)
10779
+ return;
10780
+ try {
10781
+ process.kill(pid, signal);
10782
+ }
10783
+ catch {
10784
+ // Already gone.
10785
+ }
10786
+ };
10787
+ // SIGTERM, then SIGKILL if it outlives the wait; a group signal also stops the process's children.
10788
+ const stopProcess = async (pid, { isGroup = false } = {}) => {
10789
+ const target = isGroup ? -pid : pid;
10790
+ killPid(target, "SIGTERM");
10791
+ await pollUntil({
10792
+ check: () => !isProcessAlive(pid),
10793
+ timeoutMs: PROCESS_EXIT_TIMEOUT_MS,
10794
+ intervalMs: PROCESS_EXIT_POLL_MS,
10795
+ });
10796
+ isProcessAlive(pid) && killPid(target, "SIGKILL");
10797
+ };
10798
+ const isPortInUse = (port) => new Promise(resolve => {
10799
+ const socket = net.connect({ port, host: "127.0.0.1" });
10800
+ socket.setTimeout(PORT_CHECK_TIMEOUT_MS);
10801
+ socket.once("connect", () => {
10802
+ socket.destroy();
10803
+ resolve(true);
10804
+ });
10805
+ socket.once("timeout", () => {
10806
+ socket.destroy();
10807
+ resolve(false);
10808
+ });
10809
+ socket.once("error", () => resolve(false));
10810
+ });
10811
+ const tail = (file, lines = 40) => fs.existsSync(file)
10812
+ ? fs.readFileSync(file, "utf-8").split("\n").slice(-lines).join("\n")
10813
+ : "<no log file>";
10814
+ // The child gets its own copy of the log's descriptor, so ours is closed right away.
10815
+ const spawnWithLog = ({ command, args, logFile, append = false, ...options }) => {
10816
+ const logFd = fs.openSync(logFile, append ? "a" : "w");
10817
+ try {
10818
+ return spawn(command, args, {
10819
+ ...options,
10820
+ stdio: ["ignore", logFd, logFd],
10821
+ });
10822
+ }
10823
+ finally {
10824
+ fs.closeSync(logFd);
10825
+ }
10826
+ };
10827
+ // Detached, so the server outlives the worker that started it; it's stopped again if it never becomes ready.
10828
+ const spawnUntilReady = async ({ label, isReady, timeoutMs, ...spawnOptions }) => {
10829
+ const child = spawnWithLog({ ...spawnOptions, detached: true });
10830
+ child.unref();
10831
+ const { pid = null } = child;
10832
+ const lastLines = () => `Last lines of ${spawnOptions.logFile}:\n${tail(spawnOptions.logFile, SERVER_LOG_TAIL_LINES)}`;
10833
+ try {
10834
+ const isStarted = await pollUntil({
10835
+ check: () => {
10836
+ if (child.exitCode !== null) {
10837
+ throw new Error(`${label} Server process exited unexpectedly with code ${child.exitCode}.\n${lastLines()}`);
10838
+ }
10839
+ return isReady();
10840
+ },
10841
+ timeoutMs,
10842
+ intervalMs: WAIT_FOR_SERVER_POLL_MS,
10843
+ });
10844
+ if (!isStarted) {
10845
+ throw new Error(`${label} Server did not start within ${timeoutMs / 1000}s.\n${lastLines()}`);
10723
10846
  }
10724
- catch {
10725
- return DEFAULT_STATE;
10847
+ }
10848
+ catch (startError) {
10849
+ pid !== null && (await stopProcess(pid, { isGroup: true }));
10850
+ throw startError;
10851
+ }
10852
+ return pid;
10853
+ };
10854
+ // Each worker using a server leaves a file named after its pid, so a worker that dies without stop() doesn't keep the server alive.
10855
+ const registerUser = (usersDir) => {
10856
+ fs.mkdirSync(usersDir, { recursive: true });
10857
+ fs.writeFileSync(path.join(usersDir, String(process.pid)), "");
10858
+ };
10859
+ // Returns whether other live workers still use the server; dead markers are deleted, not skipped, as a reused pid would read as alive.
10860
+ const unregisterUser = (usersDir) => {
10861
+ fs.rmSync(path.join(usersDir, String(process.pid)), { force: true });
10862
+ if (!fs.existsSync(usersDir))
10863
+ return false;
10864
+ const liveUsers = fs.readdirSync(usersDir).filter(pid => {
10865
+ if (isProcessAlive(Number(pid)))
10866
+ return true;
10867
+ fs.rmSync(path.join(usersDir, pid), { force: true });
10868
+ return false;
10869
+ });
10870
+ return liveUsers.length > 0;
10871
+ };
10872
+ // Async, not execSync: a blocked event loop stops proper-lockfile refreshing the lock.
10873
+ const runWithLog = (label, options) => new Promise((resolve, reject) => {
10874
+ const child = spawnWithLog({ append: true, ...options });
10875
+ child.on("error", reject);
10876
+ child.on("exit", code => code === 0
10877
+ ? resolve()
10878
+ : reject(new Error(`${label} exited with code ${code}. Last lines of ${options.logFile}:\n${tail(options.logFile)}`)));
10879
+ });
10880
+ const buildLockOptions = ({ lockfilePath, options, onCompromised, }) => ({
10881
+ ...options,
10882
+ lockfilePath,
10883
+ realpath: false,
10884
+ onCompromised,
10885
+ });
10886
+ // A compromised lock is already released; rethrowing on release would mask fn()'s error.
10887
+ const withLock = async (acquire, fn) => {
10888
+ const release = await acquire;
10889
+ try {
10890
+ return await fn();
10891
+ }
10892
+ finally {
10893
+ await release().catch(() => { });
10894
+ }
10895
+ };
10896
+ // allSettled, so a failure doesn't leave the other steps half done.
10897
+ const settleAll = async (steps) => {
10898
+ const results = await Promise.allSettled(steps);
10899
+ const failure = results.find(result => result.status === "rejected");
10900
+ if (failure)
10901
+ throw failure.reason;
10902
+ };
10903
+
10904
+ // Runs one product from its main branch, like NeetoAuthServer; the last worker to stop it shuts it down.
10905
+ class ProductServer {
10906
+ product;
10907
+ repo;
10908
+ paths;
10909
+ serverUrl;
10910
+ targetApp;
10911
+ builtInitializerFiles = null;
10912
+ constructor(product, appName) {
10913
+ this.targetApp = appName ? STATUS_TEXTS.appName(appName) : null;
10914
+ if (this.targetApp === null && (product.initializers ?? []).length > 0) {
10915
+ throw new Error(`[LocalServer:${product.name}] Needs the app under test's name, e.g. new LocalServer("${product.name}", "Cal").`);
10726
10916
  }
10917
+ this.product = product;
10918
+ this.repo = `neeto-${product.name}-web`; // Same naming as setup_local_servers.sh.
10919
+ this.paths = buildPaths(this.repo);
10920
+ this.serverUrl = `http://localhost:${product.port}/`;
10921
+ }
10922
+ // Built on first use, so a run where start() does nothing never reads the env they need.
10923
+ get initializerFiles() {
10924
+ const { targetApp } = this;
10925
+ this.builtInitializerFiles ??=
10926
+ targetApp === null
10927
+ ? []
10928
+ : (this.product.initializers ?? []).map(initializer => [
10929
+ initializer.path,
10930
+ initializer.build(targetApp),
10931
+ ]);
10932
+ return this.builtInitializerFiles;
10933
+ }
10934
+ // Only the initializers differ by app, so other apps can share a product that has none.
10935
+ get identity() {
10936
+ return JSON.stringify(this.initializerFiles);
10937
+ }
10938
+ log = (msg) => console.log(`[LocalServer:${this.product.name}] ${msg}`);
10939
+ error = (msg) => new Error(`[LocalServer:${this.product.name}] ${msg}`);
10940
+ // Undefined drops the app under test's value from the child's environment.
10941
+ get serverEnv() {
10942
+ const { redisDb } = this.product;
10943
+ const database = `${this.repo.replace(/-/g, "_")}_playwright`;
10944
+ const redisUrl = new URL(process.env.REDIS_URL ?? `redis://localhost:${DEFAULT_REDIS_PORT}`);
10945
+ redisUrl.pathname = `/${redisDb}`;
10946
+ const databaseUrl = new URL(process.env.DATABASE_URL ?? "postgresql://127.0.0.1");
10947
+ databaseUrl.pathname = `/${database}`;
10948
+ return {
10949
+ ...process.env,
10950
+ BUNDLE_PATH: undefined,
10951
+ BUNDLE_GEMFILE: undefined,
10952
+ BUNDLE_APP_CONFIG: undefined,
10953
+ PORT: undefined,
10954
+ // It makes layouts load prebuilt asset packs, which these servers don't have.
10955
+ PLAYWRIGHT_RUN: undefined,
10956
+ RAILS_ENV: "development",
10957
+ POSTGRES_USER: process.env.POSTGRES_USER ?? process.env.USER ?? "postgres",
10958
+ DATABASE_URL: databaseUrl.toString(),
10959
+ REDIS_URL: redisUrl.toString(),
10960
+ REDIS_DB: String(redisDb),
10961
+ };
10962
+ }
10963
+ // Puma's pid file, as NeetoCI's image has no lsof.
10964
+ ownServerPid = () => {
10965
+ if (!fs.existsSync(this.paths.SERVER_PID_FILE))
10966
+ return null;
10967
+ const pid = Number(fs.readFileSync(this.paths.SERVER_PID_FILE, "utf-8"));
10968
+ return Number.isInteger(pid) && pid > 0 && isProcessAlive(pid) ? pid : null;
10727
10969
  };
10728
- writeState = (state) => {
10729
- writeFileSync(CONFIG.STATE_FILE, JSON.stringify(state));
10730
- };
10731
- clearState = () => {
10732
- existsSync(CONFIG.STATE_FILE) && rmSync(CONFIG.STATE_FILE, { force: true });
10970
+ lockOptions = ({ label, ...lockOptions }) => buildLockOptions({
10971
+ ...lockOptions,
10972
+ onCompromised: error => this.log(`${label} lock was compromised: ${error.message}`),
10973
+ });
10974
+ withSetupLock = (fn) => {
10975
+ const { DIR, SETUP_LOCK_FILE } = this.paths;
10976
+ const acquire = lock(DIR, this.lockOptions({
10977
+ lockfilePath: SETUP_LOCK_FILE,
10978
+ options: SETUP_LOCK,
10979
+ label: "Setup",
10980
+ })).catch(error => {
10981
+ if (error.code !== "ELOCKED")
10982
+ throw error;
10983
+ const { retries, minTimeout } = SETUP_LOCK.retries;
10984
+ throw this.error(`Waited ${(retries * minTimeout) / 60_000} minutes for another worker to finish the ${this.repo} setup, and it still holds ${SETUP_LOCK_FILE}. Delete that file if no setup is running.`);
10985
+ });
10986
+ return withLock(acquire, fn);
10733
10987
  };
10734
- getLogContent = () => existsSync(CONFIG.LOG)
10735
- ? readFileSync(CONFIG.LOG, "utf-8")
10736
- : "<no log file>";
10988
+ // Separate from the setup lock: the fast path must not queue behind a setup.
10989
+ withUsersLock = (fn) => withLock(lock(this.paths.USERS_DIR, this.lockOptions({
10990
+ lockfilePath: this.paths.USERS_LOCK_FILE,
10991
+ options: USERS_LOCK,
10992
+ label: "Users",
10993
+ })), fn);
10994
+ // Not the test's output: thousands of schema lines hold up the CI job.
10995
+ runLogged = ({ label, bashArgs, isDetached = false, }) => runWithLog(`[LocalServer:${this.product.name}] ${label}`, {
10996
+ command: "bash",
10997
+ args: bashArgs,
10998
+ logFile: this.paths.SETUP_LOG,
10999
+ cwd: findRepoRoot(),
11000
+ detached: isDetached,
11001
+ env: this.serverEnv,
11002
+ });
11003
+ // The script mints a GitHub token itself, only when it has to reach GitHub.
11004
+ runSetupScript = (mode) => this.runLogged({
11005
+ label: `setup_local_servers.sh ${mode}`,
11006
+ bashArgs: [SETUP_SCRIPT_PATH, mode, this.product.name],
11007
+ });
10737
11008
  ensureSetup = async () => {
10738
- if (existsSync(CONFIG.WEBPACK_DEV_FILE)) {
10739
- this.patchWebpackPublicPath();
10740
- log("Already set up, skipping.");
10741
- return;
10742
- }
10743
- existsSync(CONFIG.DIR) &&
10744
- rmSync(CONFIG.DIR, { force: true, recursive: true });
10745
- const githubToken = await getGithubToken();
10746
- const setupScript = path.join(SCRIPTS_DIR, "setup.sh");
10747
- log("Running first-time setup...");
10748
- try {
10749
- execSync(`bash "${setupScript}" "${CONFIG.DIR}"`, {
10750
- stdio: "inherit",
10751
- env: { ...this.serverEnv, GITHUB_TOKEN: githubToken },
10752
- });
11009
+ if (!fs.existsSync(this.paths.PREPARED_MARKER)) {
11010
+ if (fs.existsSync(this.paths.DIR)) {
11011
+ // We hold the setup lock, so a server still running from this folder is an orphan.
11012
+ this.log("Found an incomplete previous setup — stopping its server and cleaning up before retrying.");
11013
+ killPid(this.ownServerPid(), "SIGKILL");
11014
+ }
11015
+ this.log("Preparing the checkout...");
11016
+ await this.runSetupScript("prepare");
10753
11017
  }
10754
- catch {
10755
- throw new Error("[NeetoChatWidget] First-time setup failed. Check the output above for details.");
11018
+ if (!fs.existsSync(this.paths.DATABASE_MARKER)) {
11019
+ this.log("Setting up the database...");
11020
+ await this.runSetupScript("database");
11021
+ fs.writeFileSync(this.paths.DATABASE_MARKER, "");
10756
11022
  }
10757
- this.patchWebpackPublicPath();
10758
- log("Setup complete.");
10759
11023
  };
10760
- patchWebpackPublicPath = () => {
10761
- if (!existsSync(CONFIG.WEBPACK_DEV_FILE)) {
10762
- throw new Error(`[NeetoChatWidget] Missing webpack config at ${CONFIG.WEBPACK_DEV_FILE}`);
10763
- }
10764
- const fileContent = readFileSync(CONFIG.WEBPACK_DEV_FILE, "utf-8");
10765
- const targetPublicPath = `publicPath: "${WIDGET_BASE_URL}/"`;
10766
- if (fileContent.includes(targetPublicPath))
11024
+ // One lock per service, as several products on a machine can need the same one; services are left running.
11025
+ ensureServices = () => settleAll((this.product.services ?? []).map(service => {
11026
+ const { port, start } = LOCAL_SERVER_SERVICES[service];
11027
+ const target = `/tmp/local-server-${service}`;
11028
+ return withLock(lock(target, this.lockOptions({
11029
+ lockfilePath: `${target}.lock`,
11030
+ options: SETUP_LOCK,
11031
+ label: service,
11032
+ })), async () => {
11033
+ if (await isPortInUse(port))
11034
+ return;
11035
+ // Locally a developer runs their own, as the start commands target NeetoCI's machines.
11036
+ if (!IS_CI) {
11037
+ throw this.error(`Needs ${service} on port ${port}. Start it, then run the tests again.`);
11038
+ }
11039
+ this.log(`Starting ${service}...`);
11040
+ // Detached, so the service outlives the worker that started it.
11041
+ await this.runLogged({
11042
+ label: `${service} start`,
11043
+ bashArgs: ["-c", start],
11044
+ isDetached: true,
11045
+ });
11046
+ });
11047
+ }));
11048
+ // bin/launch sets REDIS_URL only for the app's own Rails process, so locally the products usually fall back to this Redis.
11049
+ ensureRedis = async () => {
11050
+ if (process.env.REDIS_URL || (await isPortInUse(DEFAULT_REDIS_PORT))) {
10767
11051
  return;
10768
- const oldConfig = ` devServer: {\n contentBase: "./src",\n allowedHosts: [".lvh.me"],\n },\n`;
10769
- const newConfig = ` devServer: {\n contentBase: "./src",\n allowedHosts: [".lvh.me"],\n publicPath: "${WIDGET_BASE_URL}/",\n },\n output: {\n publicPath: "${WIDGET_BASE_URL}/",\n },\n`;
10770
- if (!fileContent.includes(oldConfig)) {
10771
- throw new Error("[NeetoChatWidget] Unable to patch webpack.dev.js for local widget serving.");
10772
11052
  }
10773
- writeFileSync(CONFIG.WEBPACK_DEV_FILE, fileContent.replace(oldConfig, newConfig));
11053
+ throw this.error(`Needs Redis on port ${DEFAULT_REDIS_PORT}, as REDIS_URL isn't set. Start it, or set REDIS_URL, then run the tests again.`);
10774
11054
  };
10775
- closeLogStream = () => {
10776
- if (this.logStream) {
10777
- this.logStream.end();
10778
- this.logStream = null;
10779
- }
10780
- };
10781
- waitForProcessExit = async (pid) => {
10782
- const deadline = Date.now() + 10_000;
10783
- while (Date.now() < deadline) {
10784
- try {
10785
- process.kill(pid, 0);
10786
- await setTimeout$1(500);
10787
- }
10788
- catch {
11055
+ spawnServer = async () => {
11056
+ // Users and the pid file left by a previous run.
11057
+ fs.rmSync(this.paths.USERS_DIR, { recursive: true, force: true });
11058
+ fs.rmSync(this.paths.SERVER_PID_FILE, { force: true });
11059
+ this.initializerFiles.forEach(([file, content]) => fs.writeFileSync(path.join(this.paths.DIR, file), content));
11060
+ this.log("Starting server...");
11061
+ await spawnUntilReady({
11062
+ label: `[LocalServer:${this.product.name}]`,
11063
+ isReady: () => httpCheck(this.serverUrl),
11064
+ timeoutMs: MAX_WAIT_MS,
11065
+ command: "bundle",
11066
+ args: [
11067
+ "exec",
11068
+ "rails",
11069
+ "server",
11070
+ "-p",
11071
+ this.product.port.toString(),
11072
+ "-b",
11073
+ "0.0.0.0",
11074
+ ],
11075
+ logFile: this.paths.LOG,
11076
+ cwd: this.paths.DIR,
11077
+ env: this.serverEnv,
11078
+ });
11079
+ this.log(`Server ready (${fs.readFileSync(this.paths.PREPARED_MARKER, "utf-8").trim()}).`);
11080
+ };
11081
+ isRunningForCurrentApp = () => fs.existsSync(this.paths.IDENTITY_FILE) &&
11082
+ fs.readFileSync(this.paths.IDENTITY_FILE, "utf-8") === this.identity;
11083
+ // Checking and registering under one lock stops us adopting a doomed server.
11084
+ tryAdopt = () => this.withUsersLock(async () => {
11085
+ const isServing = this.isRunningForCurrentApp() &&
11086
+ this.ownServerPid() !== null &&
11087
+ (await httpCheck(this.serverUrl));
11088
+ if (!isServing)
11089
+ return false;
11090
+ registerUser(this.paths.USERS_DIR);
11091
+ this.log("Server already running for this app.");
11092
+ return true;
11093
+ });
11094
+ start = async () => {
11095
+ if (!IS_DEV_ENV || (await this.tryAdopt()))
11096
+ return;
11097
+ await this.withSetupLock(async () => {
11098
+ // Another worker may have started it while we waited.
11099
+ if (await this.tryAdopt())
10789
11100
  return;
11101
+ if (await isPortInUse(this.product.port)) {
11102
+ this.log("Server running for a different app — restarting...");
11103
+ const pid = this.ownServerPid();
11104
+ // Unlike NeetoAuthServer, never kills a server it didn't start.
11105
+ if (pid === null) {
11106
+ throw this.error(`Port ${this.product.port} is in use by another process. Stop it so the ${this.repo} server can start.`);
11107
+ }
11108
+ await stopProcess(pid);
10790
11109
  }
10791
- }
11110
+ // First, as the database setup needs Redis too.
11111
+ await this.ensureRedis();
11112
+ // Settled together, so a failed service doesn't release the setup lock while setup is still running.
11113
+ await settleAll([this.ensureSetup(), this.ensureServices()]);
11114
+ await this.spawnServer();
11115
+ // Together, so another worker's stop() never sees it without users.
11116
+ await this.withUsersLock(() => {
11117
+ fs.writeFileSync(this.paths.IDENTITY_FILE, this.identity);
11118
+ registerUser(this.paths.USERS_DIR);
11119
+ });
11120
+ });
10792
11121
  };
10793
- killServer = (pid) => {
10794
- if (!pid)
11122
+ stop = async () => {
11123
+ if (!IS_DEV_ENV)
10795
11124
  return;
11125
+ const { USERS_DIR, IDENTITY_FILE } = this.paths;
11126
+ // The kill stays inside the lock, or a worker could adopt the server in between.
11127
+ await this.withUsersLock(async () => {
11128
+ if (unregisterUser(USERS_DIR)) {
11129
+ this.log("Other workers still using the server — leaving it running.");
11130
+ return;
11131
+ }
11132
+ if (this.isRunningForCurrentApp()) {
11133
+ this.log("Stopping server...");
11134
+ const pid = this.ownServerPid();
11135
+ pid !== null && (await stopProcess(pid));
11136
+ fs.rmSync(IDENTITY_FILE, { force: true });
11137
+ }
11138
+ else {
11139
+ this.log("Server on the port is serving another app — leaving it running.");
11140
+ }
11141
+ });
11142
+ };
11143
+ }
11144
+
11145
+ const { name, paths, webpackDevFile, setupScript, baseUrl, readyUrl, maxWaitMs, } = CHAT_WIDGET;
11146
+ // Runs neeto-chat-widget's webpack dev server, as it isn't a Rails product; workers share it like ProductServer.
11147
+ class WidgetServer {
11148
+ log = (msg) => console.log(`[LocalServer:${name}] ${msg}`);
11149
+ error = (msg) => new Error(`[LocalServer:${name}] ${msg}`);
11150
+ isServing = () => httpCheck(readyUrl);
11151
+ // The pid of the server we started; null for a dead one, a missing file or a widget the developer started, so only ours gets stopped.
11152
+ readPid = () => {
10796
11153
  try {
10797
- process.kill(pid, "SIGTERM");
11154
+ const { pid } = JSON.parse(fs.readFileSync(paths.STATE_FILE, "utf-8"));
11155
+ return typeof pid === "number" && isProcessAlive(pid) ? pid : null;
10798
11156
  }
10799
11157
  catch {
10800
- // process may already be gone
11158
+ return null;
10801
11159
  }
10802
11160
  };
10803
- killProcessOnWidgetPort = async () => {
10804
- try {
10805
- execSync(`lsof -ti tcp:${CONFIG.PORT} | xargs kill -9`, {
10806
- stdio: "ignore",
10807
- });
10808
- await setTimeout$1(1000);
10809
- }
10810
- catch {
10811
- // No process on that port — nothing to kill.
11161
+ withLock = (fn) => withLock(lock(paths.DIR, buildLockOptions({
11162
+ lockfilePath: paths.SETUP_LOCK_FILE,
11163
+ options: WIDGET_LOCK,
11164
+ onCompromised: lockError => this.log(`Lock was compromised: ${lockError.message}`),
11165
+ })), fn);
11166
+ // Webpack's dev server must serve its bundle from localhost, not the page's host.
11167
+ patchWebpackPublicPath = () => {
11168
+ const content = fs.readFileSync(webpackDevFile, "utf-8");
11169
+ const publicPath = `publicPath: "${baseUrl}/"`;
11170
+ if (content.includes(publicPath))
11171
+ return;
11172
+ const oldConfig = ` devServer: {\n contentBase: "./src",\n allowedHosts: [".lvh.me"],\n },\n`;
11173
+ const newConfig = ` devServer: {\n contentBase: "./src",\n allowedHosts: [".lvh.me"],\n ${publicPath},\n },\n output: {\n ${publicPath},\n },\n`;
11174
+ if (!content.includes(oldConfig)) {
11175
+ throw this.error(`Unable to patch ${webpackDevFile} for local serving.`);
10812
11176
  }
11177
+ fs.writeFileSync(webpackDevFile, content.replace(oldConfig, newConfig));
10813
11178
  };
10814
- waitForServer = async (timeoutMs = CONFIG.MAX_WAIT_MS) => {
10815
- const startTime = Date.now();
10816
- while (Date.now() - startTime < timeoutMs) {
10817
- if (this.process !== null && this.process.exitCode !== null) {
10818
- throw new Error(`[NeetoChatWidget] Server process exited unexpectedly with code ${this.process.exitCode}.\nLog:\n${this.getLogContent()}`);
10819
- }
10820
- if (await isServerListening())
10821
- return;
10822
- await setTimeout$1(CONFIG.SERVER_POLL_INTERVAL_MS);
11179
+ ensureSetup = async () => {
11180
+ if (!fs.existsSync(webpackDevFile)) {
11181
+ this.log("Running first-time setup...");
11182
+ const [githubToken] = await Promise.all([
11183
+ getGithubToken(),
11184
+ fs.promises.rm(paths.DIR, { force: true, recursive: true }),
11185
+ ]);
11186
+ await runWithLog(`[LocalServer:${name}] setup.sh`, {
11187
+ command: "bash",
11188
+ args: [setupScript, paths.DIR],
11189
+ logFile: paths.SETUP_LOG,
11190
+ env: { ...process.env, GITHUB_TOKEN: githubToken },
11191
+ });
10823
11192
  }
10824
- throw new Error(`[NeetoChatWidget] Widget did not start within ${timeoutMs / 1000}s.\nLog:\n${this.getLogContent()}`);
11193
+ this.patchWebpackPublicPath();
11194
+ };
11195
+ launch = async () => {
11196
+ await this.ensureSetup();
11197
+ // Users left by a previous run.
11198
+ fs.rmSync(paths.USERS_DIR, { recursive: true, force: true });
11199
+ this.log("Starting server...");
11200
+ const pid = await spawnUntilReady({
11201
+ label: `[LocalServer:${name}]`,
11202
+ isReady: this.isServing,
11203
+ timeoutMs: maxWaitMs,
11204
+ command: "yarn",
11205
+ args: ["start"],
11206
+ logFile: paths.LOG,
11207
+ cwd: paths.DIR,
11208
+ });
11209
+ fs.writeFileSync(paths.STATE_FILE, JSON.stringify({ pid }));
11210
+ this.log("Server ready.");
10825
11211
  };
10826
11212
  start = async () => {
10827
11213
  if (IS_STAGING_ENV)
10828
11214
  return;
10829
11215
  await this.withLock(async () => {
10830
- const state = this.readState();
10831
- if (await isServerListening()) {
10832
- this.hasLease = true;
10833
- this.writeState({ ...state, refCount: state.refCount + 1 });
10834
- log("Server already running.");
10835
- return;
11216
+ if (await this.isServing()) {
11217
+ this.log("Server already running.");
10836
11218
  }
10837
- await this.ensureSetup();
10838
- log("Starting server...");
10839
- this.logStream = createWriteStream(CONFIG.LOG);
10840
- this.process = spawn("yarn", ["start"], {
10841
- cwd: CONFIG.DIR,
10842
- stdio: ["ignore", "pipe", "pipe"],
10843
- });
10844
- this.process.stdout?.pipe(this.logStream);
10845
- this.process.stderr?.pipe(this.logStream);
10846
- try {
10847
- await this.waitForServer();
11219
+ else {
11220
+ await this.launch();
10848
11221
  }
10849
- catch (error) {
10850
- const pid = this.process?.pid;
10851
- this.killServer(pid);
10852
- pid && (await this.waitForProcessExit(pid));
10853
- (await isServerListening()) && (await this.killProcessOnWidgetPort());
10854
- this.process = null;
10855
- this.closeLogStream();
10856
- throw error;
10857
- }
10858
- this.hasLease = true;
10859
- this.writeState({
10860
- pid: this.process.pid ?? null,
10861
- refCount: state.refCount + 1,
10862
- });
10863
- log("Server ready.");
11222
+ registerUser(paths.USERS_DIR);
10864
11223
  });
10865
11224
  };
10866
11225
  stop = async () => {
10867
- if (IS_STAGING_ENV || !this.hasLease)
11226
+ if (IS_STAGING_ENV)
10868
11227
  return;
10869
11228
  await this.withLock(async () => {
10870
- const state = this.readState();
10871
- const nextRefCount = Math.max(state.refCount - 1, 0);
10872
- this.hasLease = false;
10873
- if (nextRefCount > 0) {
10874
- this.writeState({ ...state, refCount: nextRefCount });
11229
+ if (unregisterUser(paths.USERS_DIR)) {
11230
+ this.log("Other workers still using the server — leaving it running.");
10875
11231
  return;
10876
11232
  }
10877
- if (state.pid) {
10878
- log("Stopping server...");
10879
- this.killServer(state.pid);
10880
- await this.waitForProcessExit(state.pid);
10881
- (await isServerListening()) && (await this.killProcessOnWidgetPort());
11233
+ const pid = this.readPid();
11234
+ if (pid !== null) {
11235
+ this.log("Stopping server...");
11236
+ // A group signal, so webpack stops with yarn.
11237
+ await stopProcess(pid, { isGroup: true });
10882
11238
  }
10883
- this.process = null;
10884
- this.closeLogStream();
10885
- this.clearState();
11239
+ fs.rmSync(paths.STATE_FILE, { force: true });
10886
11240
  });
10887
11241
  };
10888
11242
  }
10889
11243
 
11244
+ // new LocalServer("auth", "Cal"), or a list of names and other products' settings; the app name is needed only for auth.
11245
+ class LocalServer {
11246
+ servers;
11247
+ constructor(targets, appName) {
11248
+ const servers = new Map();
11249
+ [targets].flat().forEach(target => {
11250
+ if (target === CHAT_WIDGET.name) {
11251
+ servers.set(target, new WidgetServer());
11252
+ return;
11253
+ }
11254
+ const product = typeof target === "string"
11255
+ ? { name: target, ...LOCAL_SERVER_PRODUCTS[target] }
11256
+ : target;
11257
+ servers.set(product.name, new ProductServer(product, appName));
11258
+ });
11259
+ this.servers = [...servers.values()];
11260
+ }
11261
+ start = () => settleAll(this.servers.map(server => server.start()));
11262
+ stop = () => settleAll(this.servers.map(server => server.stop()));
11263
+ }
11264
+
11265
+ // Kept for existing fixtures; new code can use new LocalServer("chatWidget").
11266
+ class NeetoChatWidget {
11267
+ server = new LocalServer("chatWidget");
11268
+ start = () => this.server.start();
11269
+ stop = () => this.server.stop();
11270
+ }
11271
+
10890
11272
  const NEETO_EMAIL_DELIVERY_TESTING_BASE_URL = "/neeto_email_delivery/api/v1/testing";
10891
11273
  class NeetoEmailDeliveryApi {
10892
11274
  neetoPlaywrightUtilities;
@@ -11340,4 +11722,4 @@ class InboundEmailApis {
11340
11722
  };
11341
11723
  }
11342
11724
 
11343
- export { ACME_SUBDOMAIN, ACTIONS, ADMIN_PANEL_SELECTORS, ALL_RESOURCES, ANALYTICS_RESOURCES, API_ROUTES, APP_RESOURCES, AUDIT_LOGS_SELECTORS, AuditLogsPage, BASE_URL, CALENDAR_LABELS, CERTIFICATE_LIMIT_EXCEEDED_MESSAGE, CERTIFICATE_LIMIT_EXCEEDED_REGEXP, CERTIFICATE_PROVISION_FAILED_MESSAGE, CERTIFICATE_PROVISION_FAILED_REGEXP, CHANGELOG_WIDGET_SELECTORS, CHAT_WIDGET_SELECTORS, CHAT_WIDGET_TEXTS, COLOR, COMMON_SELECTORS, COMMON_TEXTS, COMMUNITY_TEXTS, CREDENTIALS, CURRENT_TIME_RANGES, CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX, CUSTOM_DOMAIN_SELECTORS, CUSTOM_DOMAIN_SUFFIX, ColorPickerUtils, CustomCommands, CustomDomainApi, CustomDomainPage, DATE_FORMATS, DATE_PICKER_SELECTORS, DATE_RANGES, DATE_TEXTS, DEFAULT_TIMEZONE_ID, DEFAULT_WEBHOOKS_RESPONSE_TEXT, DESCRIPTION_EDITOR_TEXTS, EDITOR_VERIFY_TEXT_COLOR, EMBED_SELECTORS, EMOJI_LABEL, EMPTY_STORAGE_STATE, ENGAGE_TEXTS, ENVIRONMENT, EXAMPLE_URL, EXPANDED_FONT_SIZE, EXPORT_FILE_TYPES, EditorPage, EmailDeliveryUtils, EmbedBase, FILE_FORMATS, FONTS_RESOURCES, FONT_SIZE_SELECTORS, FROM_EMAIL_ENV_KEYS, GLOBAL_TRANSLATIONS_PATTERN, GOOGLE_ANALYTICS_SELECTORS, GOOGLE_CALENDAR_DATE_FORMAT, GOOGLE_LOGIN_SELECTORS, GOOGLE_LOGIN_TEXTS, GOOGLE_SHEETS_SELECTORS, GooglePage, HELP_CENTER_ROUTES, HELP_CENTER_SELECTORS, HelpAndProfilePage, INTEGRATIONS_TEXTS, INTEGRATION_SELECTORS, IPRestrictionsPage, IP_RESTRICTIONS_SELECTORS, IS_CI, IS_DEV_CI, IS_DEV_ENV, IS_PLAYWRIGHT_RUN, IS_REVIEW_ENV, IS_STAGING_ENV, IS_WEBKIT, ImageUploader, InboundEmailApis, IntegrationBase, IpRestrictionsApi, KEYBOARD_SHORTCUTS_SELECTORS, KEYBOARD_SHORTCUT_TEST_CASES, LIST_MODIFIER_SELECTORS, LIST_MODIFIER_TAGS, LOGIN_DEFAULTS, LOGIN_SELECTORS, LOGIN_STRATEGIES, LOGIN_TIMEOUT, MAILPIT_BASE_URL, MAILPIT_DOMAIN_NAME, MICROSOFT_LOGIN_SELECTORS, MICROSOFT_LOGIN_TEXTS, MailerUtils, MailpitApi, MicrosoftPage, NEETO_AUTH_BASE_URL, NEETO_EDITOR_SELECTORS, NEETO_FILTERS_SELECTORS, NEETO_IMAGE_UPLOADER_SELECTORS, NEETO_ROUTES, NEETO_SEO_SELECTORS, NEETO_TEXT_MODIFIER_SELECTORS, NeetoAuthServer, NeetoChatWidget, NeetoEmailDeliveryApi, NeetoTowerApi, ONBOARDING_SELECTORS, ORGANIZATION_TEXTS, OTP_EMAIL_PATTERN, OTP_FETCH_TIMEOUT, OrganizationPage, PAST_TIME_RANGES, PHONE_NUMBER_FORMATS, PLURAL, PROFILE_LINKS, PROFILE_SECTION_SELECTORS, PROJECT_NAMES, PROJECT_TRANSLATIONS_PATH, REVIEW_APP_CUSTOM_DOMAIN_SUFFIX, ROUTES, RailsEmailApiClient, RailsEmailUtils, SIGNUP_SELECTORS, SINGULAR, SLACK_DATA_QA_SELECTORS, SLACK_DEFAULT_CHANNEL, SLACK_SELECTORS, SLACK_WEB_TEXTS, STATUS_TEXTS, STORAGE_STATE, SecurityApi, SidebarSection, SlackApi, SlackPage, SmsApi, SmsUtils, TABLE_SELECTORS, TAB_SELECTORS, TEXT_MODIFIER_ROLES, TEXT_MODIFIER_SELECTORS, TEXT_MODIFIER_TAGS, THANK_YOU_SELECTORS, THEMES_SELECTORS, THEMES_TEXTS, THIRD_PARTY_RESOURCES, THIRD_PARTY_ROUTES, TIME_RANGES, TOASTR_MESSAGES, TRAEFIK_NOT_FOUND_TEXT, TWILIO_SELECTORS, ThankYouApi, ThankYouPage, TwilioApi, USER_AGENTS, WebhookSiteApi, ZAPIER_LIMIT_EXHAUSTED_MESSAGE, ZAPIER_SELECTORS, ZAPIER_TEST_EMAIL, ZAPIER_WEB_TEXTS, ZapierPage, authenticateUser, baseURLGenerator, basicHTMLContent, clearCredentials, commands, cpuThrottlingUsingCDP, createOrganizationViaApi, createOrganizationViaRake, currencyUtils, dataQa, decodeQRCodeFromFile, definePlaywrightConfig, exampleEmail, executeWithThrottledResources, extractSubdomainFromError, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };
11725
+ export { ACME_SUBDOMAIN, ACTIONS, ADMIN_PANEL_SELECTORS, ALL_RESOURCES, ANALYTICS_RESOURCES, API_ROUTES, APP_RESOURCES, AUDIT_LOGS_SELECTORS, AuditLogsPage, BASE_URL, CALENDAR_LABELS, CERTIFICATE_LIMIT_EXCEEDED_MESSAGE, CERTIFICATE_LIMIT_EXCEEDED_REGEXP, CERTIFICATE_PROVISION_FAILED_MESSAGE, CERTIFICATE_PROVISION_FAILED_REGEXP, CHANGELOG_WIDGET_SELECTORS, CHAT_WIDGET_SELECTORS, CHAT_WIDGET_TEXTS, COLOR, COMMON_SELECTORS, COMMON_TEXTS, COMMUNITY_TEXTS, CREDENTIALS, CURRENT_TIME_RANGES, CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX, CUSTOM_DOMAIN_SELECTORS, CUSTOM_DOMAIN_SUFFIX, ColorPickerUtils, CustomCommands, CustomDomainApi, CustomDomainPage, DATE_FORMATS, DATE_PICKER_SELECTORS, DATE_RANGES, DATE_TEXTS, DEFAULT_TIMEZONE_ID, DEFAULT_WEBHOOKS_RESPONSE_TEXT, DESCRIPTION_EDITOR_TEXTS, EDITOR_VERIFY_TEXT_COLOR, EMBED_SELECTORS, EMOJI_LABEL, EMPTY_STORAGE_STATE, ENGAGE_TEXTS, ENVIRONMENT, EXAMPLE_URL, EXPANDED_FONT_SIZE, EXPORT_FILE_TYPES, EditorPage, EmailDeliveryUtils, EmbedBase, FILE_FORMATS, FONTS_RESOURCES, FONT_SIZE_SELECTORS, FROM_EMAIL_ENV_KEYS, GLOBAL_TRANSLATIONS_PATTERN, GOOGLE_ANALYTICS_SELECTORS, GOOGLE_CALENDAR_DATE_FORMAT, GOOGLE_LOGIN_SELECTORS, GOOGLE_LOGIN_TEXTS, GOOGLE_SHEETS_SELECTORS, GooglePage, HELP_CENTER_ROUTES, HELP_CENTER_SELECTORS, HelpAndProfilePage, INTEGRATIONS_TEXTS, INTEGRATION_SELECTORS, IPRestrictionsPage, IP_RESTRICTIONS_SELECTORS, IS_CI, IS_DEV_CI, IS_DEV_ENV, IS_PLAYWRIGHT_RUN, IS_REVIEW_ENV, IS_STAGING_ENV, IS_WEBKIT, ImageUploader, InboundEmailApis, IntegrationBase, IpRestrictionsApi, KEYBOARD_SHORTCUTS_SELECTORS, KEYBOARD_SHORTCUT_TEST_CASES, LIST_MODIFIER_SELECTORS, LIST_MODIFIER_TAGS, LOGIN_DEFAULTS, LOGIN_SELECTORS, LOGIN_STRATEGIES, LOGIN_TIMEOUT, LocalServer, MAILPIT_BASE_URL, MAILPIT_DOMAIN_NAME, MICROSOFT_LOGIN_SELECTORS, MICROSOFT_LOGIN_TEXTS, MailerUtils, MailpitApi, MicrosoftPage, NEETO_AUTH_BASE_URL, NEETO_EDITOR_SELECTORS, NEETO_FILTERS_SELECTORS, NEETO_IMAGE_UPLOADER_SELECTORS, NEETO_ROUTES, NEETO_SEO_SELECTORS, NEETO_TEXT_MODIFIER_SELECTORS, NeetoAuthServer, NeetoChatWidget, NeetoEmailDeliveryApi, NeetoTowerApi, ONBOARDING_SELECTORS, ORGANIZATION_TEXTS, OTP_EMAIL_PATTERN, OTP_FETCH_TIMEOUT, OrganizationPage, PAST_TIME_RANGES, PHONE_NUMBER_FORMATS, PLURAL, PROFILE_LINKS, PROFILE_SECTION_SELECTORS, PROJECT_NAMES, PROJECT_TRANSLATIONS_PATH, REVIEW_APP_CUSTOM_DOMAIN_SUFFIX, ROUTES, RailsEmailApiClient, RailsEmailUtils, SIGNUP_SELECTORS, SINGULAR, SLACK_DATA_QA_SELECTORS, SLACK_DEFAULT_CHANNEL, SLACK_SELECTORS, SLACK_WEB_TEXTS, STATUS_TEXTS, STORAGE_STATE, SecurityApi, SidebarSection, SlackApi, SlackPage, SmsApi, SmsUtils, TABLE_SELECTORS, TAB_SELECTORS, TEXT_MODIFIER_ROLES, TEXT_MODIFIER_SELECTORS, TEXT_MODIFIER_TAGS, THANK_YOU_SELECTORS, THEMES_SELECTORS, THEMES_TEXTS, THIRD_PARTY_RESOURCES, THIRD_PARTY_ROUTES, TIME_RANGES, TOASTR_MESSAGES, TRAEFIK_NOT_FOUND_TEXT, TWILIO_SELECTORS, ThankYouApi, ThankYouPage, TwilioApi, USER_AGENTS, WebhookSiteApi, ZAPIER_LIMIT_EXHAUSTED_MESSAGE, ZAPIER_SELECTORS, ZAPIER_TEST_EMAIL, ZAPIER_WEB_TEXTS, ZapierPage, authenticateUser, baseURLGenerator, basicHTMLContent, clearCredentials, commands, cpuThrottlingUsingCDP, createOrganizationViaApi, createOrganizationViaRake, currencyUtils, dataQa, decodeQRCodeFromFile, definePlaywrightConfig, exampleEmail, executeWithThrottledResources, extractSubdomainFromError, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, saveStorageState, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };