@bigbinary/neeto-playwright-commons 6.1.4 → 7.0.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.
package/index.js CHANGED
@@ -1,36 +1,43 @@
1
- import { isPresent, isNotPresent, hyphenate, humanize, noop as noop$2, keysToSnakeCase, keysToCamelCase, truncate, isNotEmpty, _findBy, randomPick, findBy } from '@bigbinary/neeto-cist';
1
+ import fs$1, { existsSync, globSync } from 'node:fs';
2
+ import { isPresent, isNotPresent, hyphenate, humanize, noop, keysToSnakeCase, keysToCamelCase, truncate, isNotEmpty, _findBy, randomPick, findBy } from '@bigbinary/neeto-cist';
2
3
  import { spawn, execSync } from 'child_process';
3
4
  import * as fs from 'fs';
4
- import { readFileSync, writeFileSync, unlinkSync } from 'fs';
5
+ import { readFileSync, writeFileSync, rmSync } from 'fs';
5
6
  import { faker } from '@faker-js/faker/locale/en';
6
7
  import { expect, test, chromium, defineConfig, devices } from '@playwright/test';
7
8
  import { isEmpty, pluck, curry, isNotNil, not, mergeDeepLeft, uniq, mergeDeepRight, uniqBy, sortBy } from 'ramda';
8
9
  import dayjs from 'dayjs';
9
- import { getI18nInstance, initI18n } from 'playwright-i18next-fixture';
10
- import { setTimeout as setTimeout$1 } from 'node:timers/promises';
10
+ import { createInstance } from 'i18next';
11
+ import { setTimeout } from 'node:timers/promises';
11
12
  import { Redis } from 'ioredis';
12
13
  import { TOTP } from 'otpauth';
13
14
  import os from 'os';
14
15
  import * as path from 'path';
15
16
  import path__default from 'path';
16
17
  import { stringify } from 'picoquery';
17
- import { randomFillSync, createPrivateKey, randomBytes, createHmac } from 'node:crypto';
18
+ import { randomFillSync, randomUUID, createPrivateKey, randomBytes, createHmac } from 'node:crypto';
18
19
  import { simpleParser } from 'mailparser';
19
- import { parse as parse$1 } from 'node-html-parser';
20
+ import { parse } from 'node-html-parser';
20
21
  import { Jimp } from 'jimp';
21
22
  import jsQRModule from 'jsqr';
22
23
  import { execFileSync } from 'node:child_process';
23
- import fs$1, { globSync } from 'node:fs';
24
24
  import path$1 from 'node:path';
25
25
  import { load } from 'js-yaml';
26
26
  import timezone from 'dayjs/plugin/timezone.js';
27
27
  import utc from 'dayjs/plugin/utc.js';
28
- import https from 'https';
28
+ import { createAppAuth } from '@octokit/auth-app';
29
+ import { Octokit } from '@octokit/core';
29
30
  import { countries } from 'countries-list';
30
31
  import { parsePhoneNumberWithError } from 'libphonenumber-js';
31
32
  import { lock } from 'proper-lockfile';
32
33
  import * as net from 'net';
33
- import dotenv from 'dotenv';
34
+
35
+ process.env.TEST_ENV ??= "development";
36
+ for (const suffix of [process.env.TEST_ENV, "local"]) {
37
+ const path = `./e2e/config/.env.${suffix}`;
38
+ if (existsSync(path))
39
+ process.loadEnvFile(path);
40
+ }
34
41
 
35
42
  const BASE_URL = "/api/v1";
36
43
  const NEETO_AUTH_BASE_URL = (subdomain = "app") => `https://${subdomain}.neetoauth.net`;
@@ -425,19 +432,11 @@ const isStagingOrganizationExpired = (subdomainName) => {
425
432
  return now.diff(createdAt, "day") >= getStagingOrganizationTtlInDays();
426
433
  };
427
434
 
428
- const formatEnvList = (names) => {
429
- const last = names[names.length - 1];
430
- const rest = names.slice(0, -1);
431
- if (rest.length === 0)
432
- return last;
433
- if (rest.length === 1)
434
- return `${rest[0]} and ${last}`;
435
- return `${rest.join(", ")}, and ${last}`;
436
- };
435
+ const envListFormat = new Intl.ListFormat("en", { type: "conjunction" });
437
436
  const missingEnvMessage = (names) => {
438
437
  const noun = names.length === 1 ? "ENV variable" : "ENV variables";
439
438
  const verb = names.length === 1 ? "is" : "are";
440
- return `${noun} ${formatEnvList(names)} ${verb} not set`;
439
+ return `${noun} ${envListFormat.format(names)} ${verb} not set`;
441
440
  };
442
441
  /**
443
442
  * Reads the named environment variables. Aborts the running test when any
@@ -639,8 +638,9 @@ const IP_RESTRICTIONS_SELECTORS = {
639
638
  ipRangeDeleteBtn: "allowed-ip-range-delete-button",
640
639
  ipStartInpError: "ip-start-input-error",
641
640
  ipEndInpError: "ip-end-input-error",
642
- typeSelectError: "type-select-error",
643
- addressTypeSelect: "address-type-select-field",
641
+ typeSelectError: "address-type-select-error",
642
+ addressTypeSelect: "address-type-select-input",
643
+ addressTypeSelectContainer: "address-type-select-container",
644
644
  resetButton: "ip-restriction-reset-btn",
645
645
  };
646
646
  const AUDIT_LOGS_SELECTORS = {
@@ -998,7 +998,7 @@ const EMBED_SELECTORS = {
998
998
  colorPickerTarget: "color-picker-target",
999
999
  colorpickerEditableInput: "colorpicker-editable-input",
1000
1000
  colorpickerEditableInputTextbox: "colorpicker-editable-input-textbox",
1001
- showIconCheckbox: "show-icon-checkbox",
1001
+ showIconCheckbox: "show-icon-checkbox-input",
1002
1002
  elementIdInput: "element-id-input-field",
1003
1003
  previewElementPopupButton: "preview-element-popup-button",
1004
1004
  embedSelector: (type) => `embed-selector-card-${hyphenate(type)}`,
@@ -1328,6 +1328,22 @@ const KEYBOARD_SHORTCUTS_SELECTORS = {
1328
1328
  hotKeyItem: "hotkey-item",
1329
1329
  };
1330
1330
 
1331
+ let storedI18n;
1332
+ const initI18n = async ({ plugins, options, }) => {
1333
+ if (!storedI18n?.isInitialized) {
1334
+ const instance = createInstance();
1335
+ plugins.forEach(plugin => instance.use(plugin));
1336
+ await instance.init(options);
1337
+ storedI18n = instance;
1338
+ }
1339
+ return storedI18n;
1340
+ };
1341
+ const getI18nInstance = () => {
1342
+ if (!storedI18n)
1343
+ throw new Error("No i18n instance initialized");
1344
+ return storedI18n;
1345
+ };
1346
+
1331
1347
  class IntegrationBase {
1332
1348
  page;
1333
1349
  neetoPlaywrightUtilities;
@@ -1443,12 +1459,12 @@ const restoreCookies = async (redis, provider, context) => {
1443
1459
  }
1444
1460
  catch {
1445
1461
  log(`Cache entry for "${provider}" is corrupt — falling back to login`);
1446
- await redis.del(cookieKey(provider)).catch(noop$2);
1462
+ await redis.del(cookieKey(provider)).catch(noop);
1447
1463
  return false;
1448
1464
  }
1449
1465
  };
1450
1466
  const acquireLock = (redis, provider) => redis.set(lockKey(provider), "1", "EX", LOCK_TTL_SECONDS, "NX");
1451
- const releaseLock = (redis, provider) => redis.del(lockKey(provider)).catch(noop$2);
1467
+ const releaseLock = (redis, provider) => redis.del(lockKey(provider)).catch(noop);
1452
1468
  const startLockRefresh = (redis, provider) => {
1453
1469
  const interval = setInterval(() => {
1454
1470
  redis
@@ -1457,7 +1473,7 @@ const startLockRefresh = (redis, provider) => {
1457
1473
  if (success)
1458
1474
  log(`Refreshed lock TTL for "${provider}"`);
1459
1475
  })
1460
- .catch(noop$2);
1476
+ .catch(noop);
1461
1477
  }, LOCK_REFRESH_INTERVAL_MS);
1462
1478
  return () => clearInterval(interval);
1463
1479
  };
@@ -1465,12 +1481,12 @@ const pollForCookies = async (redis, provider, context) => {
1465
1481
  log(`"${provider}" lock held by another shard — waiting for cached cookies`);
1466
1482
  const controller = new AbortController();
1467
1483
  const { signal } = controller;
1468
- const timeout = setTimeout$1(POLL_TIMEOUT_MS, undefined, { signal }).then(() => {
1484
+ const timeout = setTimeout(POLL_TIMEOUT_MS, undefined, { signal }).then(() => {
1469
1485
  failTest(`[cookieCache] Timed out waiting for "${provider}" cookies from another shard`);
1470
1486
  });
1471
1487
  const poll = async () => {
1472
1488
  while (true) {
1473
- await setTimeout$1(POLL_INTERVAL_MS, undefined, { signal });
1489
+ await setTimeout(POLL_INTERVAL_MS, undefined, { signal });
1474
1490
  if (await restoreCookies(redis, provider, context))
1475
1491
  return true;
1476
1492
  signal.throwIfAborted();
@@ -1541,6 +1557,29 @@ const initializeTotp = ({ issuer, secret, }) => {
1541
1557
  secret,
1542
1558
  });
1543
1559
  };
1560
+ const fillTotpWhenReady = async ({ codeInput, totp, submitButton, successLocators = [], hideCodeInput = true, }) => {
1561
+ const generateToken = () => totp.generate({ timestamp: Date.now() + 5_000 });
1562
+ const locatorsToHide = hideCodeInput
1563
+ ? [codeInput, ...successLocators]
1564
+ : successLocators;
1565
+ let previousToken;
1566
+ await expect(async () => {
1567
+ if (!hideCodeInput || !(await codeInput.isHidden())) {
1568
+ let token = generateToken();
1569
+ if (token === previousToken) {
1570
+ await setTimeout(totp.remaining({ timestamp: Date.now() + 5_000 }) + 500);
1571
+ token = generateToken();
1572
+ }
1573
+ if (!hideCodeInput || !(await codeInput.isHidden())) {
1574
+ previousToken = token;
1575
+ await codeInput.fill(token);
1576
+ expect(totp.validate({ token })).not.toBeNull();
1577
+ await submitButton?.click();
1578
+ }
1579
+ }
1580
+ await Promise.all(locatorsToHide.map(locator => expect(locator).toBeHidden({ timeout: 20_000 })));
1581
+ }).toPass({ timeout: 2 * 60_000, intervals: [5_000] });
1582
+ };
1544
1583
 
1545
1584
  class GooglePage extends IntegrationBase {
1546
1585
  totp;
@@ -1634,31 +1673,14 @@ class GooglePage extends IntegrationBase {
1634
1673
  }, ["google.com"]);
1635
1674
  };
1636
1675
  enterTotpCode = async () => {
1637
- let previousToken = null;
1638
1676
  const codeInput = this.page.getByLabel(GOOGLE_LOGIN_TEXTS.enterCode);
1639
1677
  await expect(codeInput).toBeVisible({ timeout: 20_000 });
1640
- await expect(async () => {
1641
- let totpToken = this.totp.generate({ timestamp: Date.now() });
1642
- if (totpToken === previousToken) {
1643
- const remainingTime = this.totp.remaining({ timestamp: Date.now() });
1644
- // Wait for the remaining time plus a small buffer to ensure new token is generated
1645
- // eslint-disable-next-line playwright/no-wait-for-timeout
1646
- await this.page.waitForTimeout(remainingTime + 500);
1647
- totpToken = this.totp.generate({ timestamp: Date.now() });
1648
- }
1649
- previousToken = totpToken;
1650
- if (await codeInput.isHidden())
1651
- return;
1652
- await codeInput.fill(totpToken);
1653
- expect(this.totp.validate({ token: totpToken })).not.toBeNull();
1654
- await this.page.locator(GOOGLE_LOGIN_SELECTORS.totpNext).click();
1655
- await Promise.all([
1656
- expect(codeInput).toBeHidden({ timeout: 20_000 }),
1657
- expect(this.page.getByText(GOOGLE_LOGIN_TEXTS.wrongCode)).toBeHidden({
1658
- timeout: 20_000,
1659
- }),
1660
- ]);
1661
- }).toPass({ timeout: 2 * 60 * 1000 });
1678
+ await fillTotpWhenReady({
1679
+ codeInput,
1680
+ totp: this.totp,
1681
+ submitButton: this.page.locator(GOOGLE_LOGIN_SELECTORS.totpNext),
1682
+ successLocators: [this.page.getByText(GOOGLE_LOGIN_TEXTS.wrongCode)],
1683
+ });
1662
1684
  };
1663
1685
  logoutFromGoogle = async () => {
1664
1686
  if (IS_DEV_ENV)
@@ -1945,32 +1967,19 @@ class OrganizationPage {
1945
1967
  }).toPass({ timeout: loginTimeout });
1946
1968
  };
1947
1969
  enterTotpCode = async () => {
1948
- let previousToken = null;
1949
1970
  const totp = initializeTotp({
1950
1971
  issuer: "Neeto",
1951
1972
  secret: process.env.PLAYWRIGHT_PRODUCTION_2FA_SECRET_KEY,
1952
1973
  });
1953
1974
  const codeInput = this.page.getByTestId(LOGIN_SELECTORS.authenticatorAppOtpInput);
1954
1975
  await expect(codeInput).toBeVisible({ timeout: 20_000 });
1955
- await expect(async () => {
1956
- let totpToken = totp.generate({ timestamp: Date.now() });
1957
- if (totpToken === previousToken) {
1958
- const remainingTime = totp.remaining({ timestamp: Date.now() });
1959
- // Wait for the remaining time plus a small buffer to ensure new token is generated
1960
- // eslint-disable-next-line playwright/no-wait-for-timeout
1961
- await this.page.waitForTimeout(remainingTime + 500);
1962
- totpToken = totp.generate({ timestamp: Date.now() });
1963
- }
1964
- previousToken = totpToken;
1965
- if (await codeInput.isHidden())
1966
- return;
1967
- await codeInput.fill(totpToken);
1968
- expect(totp.validate({ token: totpToken })).not.toBeNull();
1969
- await Promise.all([
1970
- expect(codeInput).toBeHidden({ timeout: 10_000 }),
1971
- expect(this.page.getByTestId(LOGIN_SELECTORS.enterOtpInputError)).toBeHidden({ timeout: 10_000 }),
1972
- ]);
1973
- }).toPass({ timeout: LOGIN_TIMEOUT });
1976
+ await fillTotpWhenReady({
1977
+ codeInput,
1978
+ totp,
1979
+ successLocators: [
1980
+ this.page.getByTestId(LOGIN_SELECTORS.enterOtpInputError),
1981
+ ],
1982
+ });
1974
1983
  };
1975
1984
  loginStrategies = {
1976
1985
  [LOGIN_STRATEGIES.oliver]: () => this.loginAsOliver(),
@@ -2284,7 +2293,7 @@ class CustomCommands {
2284
2293
  return await callback();
2285
2294
  }
2286
2295
  const timeToWaitInSecs = iteration > 3 ? 10 : Math.pow(2, iteration);
2287
- await setTimeout$1(timeToWaitInSecs * 1000);
2296
+ await setTimeout(timeToWaitInSecs * 1000);
2288
2297
  return await this.recursiveMethod(callback, condition, timeout, startTime, iteration + 1);
2289
2298
  };
2290
2299
  executeRecursively = async ({ callback, condition, timeout = 5000, }) => {
@@ -2306,16 +2315,11 @@ class CustomCommands {
2306
2315
  await expect(filteredToastLocator).toContainText(isEmpty(message) ? TOAST_DEFAULT_MESSAGE : message, { timeout });
2307
2316
  if (!closeAfterVerification)
2308
2317
  return;
2309
- const toastCloseButton = filteredToastLocator.getByTestId(COMMON_SELECTORS.toastCloseButton);
2310
- const buttonHandle = await toastCloseButton.elementHandle();
2311
- if (buttonHandle) {
2312
- await customPageContext.evaluate(button => {
2313
- button.dispatchEvent(new Event("click", { bubbles: true }));
2314
- }, buttonHandle);
2315
- await expect(toastCloseButton).toBeHidden({
2316
- timeout: toastCloseTimeout,
2317
- });
2318
- }
2318
+ const toastCloseBtn = filteredToastLocator.getByTestId(COMMON_SELECTORS.toastCloseButton);
2319
+ await toastCloseBtn.dispatchEvent("click", {}, {
2320
+ timeout: toastCloseTimeout,
2321
+ });
2322
+ await expect(toastCloseBtn).toBeHidden({ timeout: toastCloseTimeout });
2319
2323
  };
2320
2324
  waitForPageLoad = async ({ visibilityTimeout = 35_000, customPageContext = this.page, waitForOption = "serial", } = {}) => {
2321
2325
  await customPageContext.waitForLoadState();
@@ -2800,7 +2804,7 @@ const saveStorageState = async (page, credentials = {}) => {
2800
2804
  };
2801
2805
  const removeCredentialFile = () => {
2802
2806
  try {
2803
- fs.existsSync(STORAGE_STATE) && fs.unlinkSync(STORAGE_STATE);
2807
+ fs.rmSync(STORAGE_STATE, { force: true });
2804
2808
  }
2805
2809
  catch (error) {
2806
2810
  console.log(error);
@@ -3018,6 +3022,9 @@ class MailpitApi {
3018
3022
  };
3019
3023
  }
3020
3024
 
3025
+ const latestRailsEmail = (emails) => emails.reduce((latest, current) => !latest || new Date(current.receivedAt) > new Date(latest.receivedAt)
3026
+ ? current
3027
+ : latest, null);
3021
3028
  class RailsEmailApiClient {
3022
3029
  port = process.env.RAILS_SERVER_PORT;
3023
3030
  subdomain = process.env.SUBDOMAIN ?? "spinkart";
@@ -3067,12 +3074,7 @@ class RailsEmailApiClient {
3067
3074
  const data = await this.fetchJson(`${this.emailsEndpoint}${query}`);
3068
3075
  return data?.map(this.convertRawEmail) ?? [];
3069
3076
  };
3070
- getLatestEmail = async (searchParams) => {
3071
- const emails = await this.listEmails(searchParams);
3072
- return emails.reduce((latest, curr) => !latest || new Date(curr.receivedAt) > new Date(latest.receivedAt)
3073
- ? curr
3074
- : latest, null);
3075
- };
3077
+ getLatestEmail = async (searchParams) => latestRailsEmail(await this.listEmails(searchParams));
3076
3078
  clearEmails = () => this.fetchJson(this.emailsEndpoint, {
3077
3079
  method: "DELETE",
3078
3080
  });
@@ -3320,8 +3322,6 @@ class RailsEmailUtils {
3320
3322
  this.railsEmailClient = new RailsEmailApiClient();
3321
3323
  }
3322
3324
  convertRailsEmailToFormattedList = (railsEmail) => {
3323
- if (!railsEmail)
3324
- return null;
3325
3325
  const LINK_REGEX = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])/g;
3326
3326
  const CODE_REGEX = /(?<![#/])\b\d{4,}\b/g;
3327
3327
  const htmlBody = railsEmail.htmlBody || "";
@@ -3353,7 +3353,7 @@ class RailsEmailUtils {
3353
3353
  links: extractMatches(textBody, LINK_REGEX),
3354
3354
  codes: extractMatches(textBody, CODE_REGEX),
3355
3355
  },
3356
- id: `${railsEmail.receivedAt}-${Math.random().toString(36).substring(2, 9)}`,
3356
+ id: randomUUID(),
3357
3357
  from: parseEmailAddress(railsEmail.from),
3358
3358
  to: parseEmailAddress(railsEmail.to),
3359
3359
  cc: parseEmailAddress(railsEmail.cc),
@@ -3384,36 +3384,28 @@ class RailsEmailUtils {
3384
3384
  ...messageSearchCriteria,
3385
3385
  receivedAfter: receivedAfter.toISOString(),
3386
3386
  });
3387
- return emails
3388
- .map(email => this.convertRailsEmailToFormattedList(email))
3389
- .filter((email) => email !== null);
3387
+ return emails.map(this.convertRailsEmailToFormattedList);
3390
3388
  };
3391
- findMessage = async (messageSearchCriteria = {}, { timeout = 10_000, receivedAfter = new Date(new Date().valueOf() - 60 * 60 * 1000), expectedEmailCount = 1, } = {}, shouldThrowErrorOnTimeout = true) => {
3392
- const email = (await this.neetoPlaywrightUtilities.executeRecursively({
3393
- callback: async () => {
3394
- const railsEmail = await this.railsEmailClient.getLatestEmail({
3395
- ...messageSearchCriteria,
3396
- receivedAfter: receivedAfter.toISOString(),
3397
- });
3398
- if (!railsEmail)
3399
- return null;
3400
- return this.convertRailsEmailToFormattedList(railsEmail);
3401
- },
3389
+ waitForLatestEmail = async (searchParams, expectedEmailCount, timeout) => {
3390
+ let emails = [];
3391
+ const latestEmail = (await this.neetoPlaywrightUtilities.executeRecursively({
3392
+ callback: () => latestRailsEmail(emails),
3402
3393
  condition: async () => {
3403
- const emails = await this.railsEmailClient.listEmails({
3404
- ...messageSearchCriteria,
3405
- receivedAfter: receivedAfter.toISOString(),
3406
- });
3394
+ emails = await this.railsEmailClient.listEmails(searchParams);
3407
3395
  return emails.length >= expectedEmailCount;
3408
3396
  },
3409
3397
  timeout,
3410
3398
  }));
3399
+ return latestEmail || null;
3400
+ };
3401
+ findMessage = async (messageSearchCriteria = {}, { timeout = 10_000, receivedAfter = new Date(new Date().valueOf() - 60 * 60 * 1000), expectedEmailCount = 1, } = {}, shouldThrowErrorOnTimeout = true) => {
3402
+ const email = await this.waitForLatestEmail({ ...messageSearchCriteria, receivedAfter: receivedAfter.toISOString() }, expectedEmailCount, timeout);
3411
3403
  if (!email) {
3412
3404
  if (shouldThrowErrorOnTimeout && expectedEmailCount > 0)
3413
3405
  failTest("Timed out waiting for matching message");
3414
3406
  return {};
3415
3407
  }
3416
- return email;
3408
+ return this.convertRailsEmailToFormattedList(email);
3417
3409
  };
3418
3410
  getLatestMessageId = async (subject, { timeout = 10_000, receivedAfter = new Date(new Date().valueOf() - 60 * 1000), } = {}) => {
3419
3411
  const email = await this.findMessage({ subject }, { timeout, receivedAfter }, false);
@@ -3422,70 +3414,34 @@ class RailsEmailUtils {
3422
3414
  return email.messageId.replace(/^<|>$/g, "");
3423
3415
  };
3424
3416
  findOtpFromEmail = async ({ email, subjectSubstring = OTP_EMAIL_PATTERN, timeout = 10_000, receivedAfter = new Date(), expectedEmailCount = 1, }) => {
3425
- const otp = await this.neetoPlaywrightUtilities.executeRecursively({
3426
- callback: async () => {
3427
- const railsEmail = await this.railsEmailClient.getLatestEmail({
3428
- to: email,
3429
- subject: subjectSubstring,
3430
- receivedAfter: receivedAfter.toISOString(),
3431
- });
3432
- if (!railsEmail)
3433
- return null;
3434
- const formattedEmail = this.convertRailsEmailToFormattedList(railsEmail);
3435
- if (!formattedEmail)
3436
- return null;
3437
- return formattedEmail.html.codes?.[0] || formattedEmail.text.codes?.[0];
3438
- },
3439
- condition: async () => {
3440
- const emails = await this.railsEmailClient.listEmails({
3441
- to: email,
3442
- subject: subjectSubstring,
3443
- receivedAfter: receivedAfter.toISOString(),
3444
- });
3445
- return emails.length >= expectedEmailCount;
3446
- },
3447
- timeout,
3448
- });
3449
- return otp || undefined;
3417
+ const railsEmail = await this.waitForLatestEmail({
3418
+ to: email,
3419
+ subject: subjectSubstring,
3420
+ receivedAfter: receivedAfter.toISOString(),
3421
+ }, expectedEmailCount, timeout);
3422
+ if (!railsEmail)
3423
+ return undefined;
3424
+ const { html, text } = this.convertRailsEmailToFormattedList(railsEmail);
3425
+ return html.codes?.[0] || text.codes?.[0];
3450
3426
  };
3451
3427
  getEmailAttachment = async ({ name, type }, messageSearchCriteria = {}, { receivedAfter = new Date(new Date().valueOf() - 60 * 60 * 1000), expectedEmailCount = 1, timeout = 10_000, } = {}, shouldThrowErrorOnTimeout = true) => {
3452
- const attachmentDetails = (await this.neetoPlaywrightUtilities.executeRecursively({
3453
- callback: async () => {
3454
- const railsEmail = await this.railsEmailClient.getLatestEmail({
3455
- ...messageSearchCriteria,
3456
- receivedAfter: receivedAfter.toISOString(),
3457
- });
3458
- if (!railsEmail)
3459
- return null;
3460
- const attachment = railsEmail.attachments?.find(att => {
3461
- const matchesName = name ? att.name?.includes(name) : true;
3462
- const matchesType = type ? att.type?.startsWith(type) : true;
3463
- return matchesName && matchesType;
3464
- });
3465
- if (!attachment)
3466
- return null;
3467
- return {
3468
- filename: attachment.name,
3469
- type: attachment.type,
3470
- content: Buffer.from(attachment.content, "base64"),
3471
- contentType: attachment.type,
3472
- };
3473
- },
3474
- condition: async () => {
3475
- const emails = await this.railsEmailClient.listEmails({
3476
- ...messageSearchCriteria,
3477
- receivedAfter: receivedAfter.toISOString(),
3478
- });
3479
- return emails.length >= expectedEmailCount;
3480
- },
3481
- timeout,
3482
- }));
3483
- if (!attachmentDetails) {
3428
+ const railsEmail = await this.waitForLatestEmail({ ...messageSearchCriteria, receivedAfter: receivedAfter.toISOString() }, expectedEmailCount, timeout);
3429
+ const attachment = railsEmail?.attachments?.find(att => {
3430
+ const matchesName = name ? att.name?.includes(name) : true;
3431
+ const matchesType = type ? att.type?.startsWith(type) : true;
3432
+ return matchesName && matchesType;
3433
+ });
3434
+ if (!attachment) {
3484
3435
  if (shouldThrowErrorOnTimeout)
3485
3436
  failTest("Timed out waiting for matching message or attachment not found");
3486
3437
  return undefined;
3487
3438
  }
3488
- return attachmentDetails;
3439
+ return {
3440
+ filename: attachment.name,
3441
+ type: attachment.type,
3442
+ content: Buffer.from(attachment.content, "base64"),
3443
+ contentType: attachment.type,
3444
+ };
3489
3445
  };
3490
3446
  }
3491
3447
 
@@ -3523,7 +3479,7 @@ class MailerUtils {
3523
3479
  const wrappedHtml = /<html[\s>]/i.test(emailBody)
3524
3480
  ? emailBody.replace(/\sxmlns="[^"]+"/g, "")
3525
3481
  : basicHTMLContent(emailBody);
3526
- const root = parse$1(wrappedHtml, { comment: false });
3482
+ const root = parse(wrappedHtml, { comment: false });
3527
3483
  const textBody = root.querySelector("body")?.text.trim() || "";
3528
3484
  const text = { body: textBody, ...contentRecognitions };
3529
3485
  return { html, text };
@@ -3961,6 +3917,15 @@ const listFormatter = ({ value, format, lng, options, }) => {
3961
3917
  const items = newValue.toString().split(",");
3962
3918
  return formatter.format(items);
3963
3919
  };
3920
+ const interpolationFormatter = {
3921
+ type: "formatter",
3922
+ format: (value, format, lng, options) => {
3923
+ if (LIST_FORMATS.includes(format ?? "")) {
3924
+ return listFormatter({ value, format, lng, options });
3925
+ }
3926
+ return lowerCaseDynamicTextFormatter(value, format);
3927
+ },
3928
+ };
3964
3929
 
3965
3930
  const sentenceCase = (value) => value.charAt(0).toLocaleUpperCase() + value.slice(1);
3966
3931
  const sentenceCaseProcessor = {
@@ -4206,30 +4171,24 @@ const i18nFixture = {
4206
4171
  const options = {
4207
4172
  debug: false,
4208
4173
  fallbackLng: ENGLISH_LOCALE,
4174
+ returnEmptyString: true,
4209
4175
  resources,
4210
4176
  interpolation: {
4211
4177
  defaultVariables: { taxonomies },
4212
4178
  escapeValue: false,
4213
4179
  skipOnVariables: false,
4214
4180
  alwaysFormat: true,
4215
- format: (value, format, lng, options) => {
4216
- let newValue = value;
4217
- if (LIST_FORMATS.includes(format ?? "")) {
4218
- newValue = listFormatter({
4219
- value: newValue,
4220
- format,
4221
- lng,
4222
- options,
4223
- });
4224
- return newValue;
4225
- }
4226
- return lowerCaseDynamicTextFormatter(newValue, format);
4227
- },
4228
4181
  },
4229
4182
  postProcess: ["removeTagsProcessor", "sentenceCaseProcessor"],
4230
4183
  };
4231
- const plugins = [removeTagsProcessor, sentenceCaseProcessor];
4232
- const i18nInitialized = await initI18n({ plugins, options, cache: true });
4184
+ const i18nInitialized = await initI18n({
4185
+ plugins: [
4186
+ interpolationFormatter,
4187
+ removeTagsProcessor,
4188
+ sentenceCaseProcessor,
4189
+ ],
4190
+ options,
4191
+ });
4233
4192
  await use(i18nInitialized);
4234
4193
  },
4235
4194
  { auto: true, scope: "worker", box: true },
@@ -4369,7 +4328,7 @@ class EmbedBase {
4369
4328
  }
4370
4329
  await this.embedTestPage.close();
4371
4330
  await this.context.close();
4372
- unlinkSync(this.filePath);
4331
+ rmSync(this.filePath, { force: true });
4373
4332
  };
4374
4333
  clickOnPopupButton = async (popUpButtonSelectorOptions) => {
4375
4334
  const popUpButton = this.embedTestPage.getByRole(this.embedTestPageType === "floatingPopup" ? "button" : "link", popUpButtonSelectorOptions);
@@ -5020,14 +4979,13 @@ class MicrosoftPage extends IntegrationBase {
5020
4979
  name: MICROSOFT_LOGIN_TEXTS.verify,
5021
4980
  });
5022
4981
  await this.page.waitForLoadState("load", { timeout: 25_000 });
5023
- await expect(async () => {
5024
- const token = this.totp.generate({ timestamp: Date.now() + 5_000 });
5025
- await this.page.getByLabel(MICROSOFT_LOGIN_TEXTS.enterCode).fill(token);
5026
- expect(this.totp.validate({ token })).not.toBeNull();
5027
- await verifyBtn.click();
5028
- await expect(this.page.getByRole("alert")).toBeHidden();
5029
- await expect(verifyBtn).toBeHidden();
5030
- }).toPass({ timeout: 60 * 1000, intervals: [10_000] });
4982
+ await fillTotpWhenReady({
4983
+ codeInput: this.page.getByLabel(MICROSOFT_LOGIN_TEXTS.enterCode),
4984
+ totp: this.totp,
4985
+ submitButton: verifyBtn,
4986
+ successLocators: [this.page.getByRole("alert"), verifyBtn],
4987
+ hideCodeInput: false,
4988
+ });
5031
4989
  };
5032
4990
  staySignedIn = async () => {
5033
4991
  await this.page.waitForLoadState("load", { timeout: 25_000 });
@@ -5413,28 +5371,16 @@ class ZapierPage extends IntegrationBase {
5413
5371
  .waitFor({ timeout: 25_000 });
5414
5372
  };
5415
5373
  enterTotpCode = async () => {
5416
- let previousToken = null;
5417
5374
  const codeInput = this.zapierWebPage.locator(ZAPIER_SELECTORS.authenticationCode);
5418
5375
  await expect(codeInput).toBeVisible({ timeout: 20_000 });
5419
- await expect(async () => {
5420
- let totpToken = this.totp.generate({ timestamp: Date.now() });
5421
- if (totpToken === previousToken) {
5422
- const remainingTime = this.totp.remaining({ timestamp: Date.now() });
5423
- // Wait for the remaining time plus a small buffer to ensure new token is generated
5424
- // eslint-disable-next-line playwright/no-wait-for-timeout
5425
- await this.zapierWebPage.waitForTimeout(remainingTime + 500);
5426
- totpToken = this.totp.generate({ timestamp: Date.now() });
5427
- }
5428
- previousToken = totpToken;
5429
- if (await codeInput.isHidden())
5430
- return;
5431
- await codeInput.fill(totpToken);
5432
- expect(this.totp.validate({ token: totpToken })).not.toBeNull();
5433
- await this.zapierWebPage
5434
- .getByRole("button", { name: ZAPIER_WEB_TEXTS.confirm, exact: true })
5435
- .click();
5436
- await expect(codeInput).toBeHidden({ timeout: 20_000 });
5437
- }).toPass({ timeout: 2 * 60 * 1000 });
5376
+ await fillTotpWhenReady({
5377
+ codeInput,
5378
+ totp: this.totp,
5379
+ submitButton: this.zapierWebPage.getByRole("button", {
5380
+ name: ZAPIER_WEB_TEXTS.confirm,
5381
+ exact: true,
5382
+ }),
5383
+ });
5438
5384
  };
5439
5385
  logoutFromZapier = async () => {
5440
5386
  await this.zapierWebPage.goto(THIRD_PARTY_ROUTES.zapier.logOut, {
@@ -5511,6 +5457,8 @@ const DESCRIPTION_EDITOR_TEXTS = {
5511
5457
  linkTag: "a",
5512
5458
  link: "Link",
5513
5459
  cannedResponseHeader: "Canned responses",
5460
+ // Seeded record name (desk, chat), not UI copy, so it doesn't follow the locale.
5461
+ seededCannedResponseName: "Feedback",
5514
5462
  paragraphOption: "paragraph",
5515
5463
  search: "Search",
5516
5464
  emoji: "Emoji",
@@ -6048,9 +5996,9 @@ class EditorPage {
6048
5996
  await expect(this.page.getByTestId(COMMON_SELECTORS.paneHeader)).toContainText(DESCRIPTION_EDITOR_TEXTS.cannedResponseHeader);
6049
5997
  await this.page
6050
5998
  .getByTestId(NEETO_EDITOR_SELECTORS.cannedResponseSelectContainer)
6051
- .fill(this.t("neetoRules.labels.feedback"));
5999
+ .fill(DESCRIPTION_EDITOR_TEXTS.seededCannedResponseName);
6052
6000
  await this.page
6053
- .getByTestId(COMMON_SELECTORS.selectOption(this.t("neetoRules.labels.feedback")))
6001
+ .getByTestId(COMMON_SELECTORS.selectOption(DESCRIPTION_EDITOR_TEXTS.seededCannedResponseName))
6054
6002
  .click();
6055
6003
  await this.page.getByTestId(NEETO_EDITOR_SELECTORS.applyButton).click();
6056
6004
  await this.neetoPlaywrightUtilities.verifyToast({
@@ -6694,19 +6642,22 @@ class CustomDomainPage {
6694
6642
  };
6695
6643
  isEdgeCertificateDomain = () => !!CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX &&
6696
6644
  this.customDomainURL.endsWith(`.${CUSTOM_DOMAIN_EDGE_CERTIFICATE_SUFFIX}`);
6697
- isCustomDomainRouted = () => new Promise(resolve => {
6698
- https
6699
- .get(this.customDomainURL, { rejectUnauthorized: true }, res => {
6700
- res.resume();
6701
- // Traefik answers a plain-text 404 until an edge-certificate domain's route is loaded.
6702
- const isTraefikNotFound = res.statusCode === 404 &&
6703
- !!res.headers["content-type"]?.startsWith("text/plain");
6704
- resolve(!this.isEdgeCertificateDomain() || !isTraefikNotFound);
6705
- })
6706
- .on("error", () => {
6707
- resolve(false);
6708
- });
6709
- });
6645
+ isCustomDomainRouted = async () => {
6646
+ try {
6647
+ const response = await fetch(this.customDomainURL, {
6648
+ redirect: "manual",
6649
+ signal: AbortSignal.timeout(10_000),
6650
+ });
6651
+ await response.body?.cancel();
6652
+ // Traefik answers a plain-text 404 until the edge-certificate route is loaded.
6653
+ const isTraefikNotFound = response.status === 404 &&
6654
+ response.headers.get("content-type")?.startsWith("text/plain");
6655
+ return !this.isEdgeCertificateDomain() || !isTraefikNotFound;
6656
+ }
6657
+ catch {
6658
+ return false;
6659
+ }
6660
+ };
6710
6661
  // A new edge-certificate route flaps between routed and 404 before it settles.
6711
6662
  waitForTrustedSSL = () => {
6712
6663
  const requiredRoutedResponses = this.isEdgeCertificateDomain() ? 3 : 1;
@@ -6897,7 +6848,7 @@ class IPRestrictionsPage {
6897
6848
  .fill(type);
6898
6849
  await this.page.keyboard.press("Enter");
6899
6850
  await expect(this.page
6900
- .getByTestId(COMMON_SELECTORS.customSelectValueContainer("type"))
6851
+ .getByTestId(IP_RESTRICTIONS_SELECTORS.addressTypeSelectContainer)
6901
6852
  // eslint-disable-next-line playwright/no-nth-methods
6902
6853
  .nth(index)).toContainText(type);
6903
6854
  };
@@ -7496,24 +7447,31 @@ const cpuThrottlingUsingCDP = ({ cdpSession, rate = 1.25, }) => cdpSession.send(
7496
7447
  const executeWithThrottledResources = async ({ code: emulatedCode, kind = "both", networkCondition, cpuThrottlingRate, cdpSession, }) => {
7497
7448
  const shouldApplyNetworkThrottling = kind === "network" || kind === "both";
7498
7449
  const shouldApplyCPUThrottling = kind === "cpu" || kind === "both";
7499
- if (shouldApplyNetworkThrottling) {
7500
- await networkThrottlingUsingCDP({
7501
- cdpSession,
7502
- emulateNetworkConditionsParameters: networkCondition,
7503
- });
7450
+ try {
7451
+ if (shouldApplyNetworkThrottling) {
7452
+ await networkThrottlingUsingCDP({
7453
+ cdpSession,
7454
+ emulateNetworkConditionsParameters: networkCondition,
7455
+ });
7456
+ }
7457
+ if (shouldApplyCPUThrottling) {
7458
+ await cpuThrottlingUsingCDP({
7459
+ cdpSession,
7460
+ rate: cpuThrottlingRate,
7461
+ });
7462
+ }
7463
+ await emulatedCode();
7504
7464
  }
7505
- else if (shouldApplyCPUThrottling) {
7506
- await cpuThrottlingUsingCDP({
7507
- cdpSession,
7508
- rate: cpuThrottlingRate,
7509
- });
7465
+ finally {
7466
+ // allSettled so a closed CDP session can't replace the error from `code`.
7467
+ await Promise.allSettled([
7468
+ networkThrottlingUsingCDP({
7469
+ cdpSession,
7470
+ emulateNetworkConditionsParameters: networkConditions["No Throttling"],
7471
+ }),
7472
+ cpuThrottlingUsingCDP({ cdpSession, rate: 1 }),
7473
+ ]);
7510
7474
  }
7511
- await emulatedCode();
7512
- await networkThrottlingUsingCDP({
7513
- cdpSession,
7514
- emulateNetworkConditionsParameters: networkConditions["No Throttling"],
7515
- });
7516
- await cpuThrottlingUsingCDP({ cdpSession, rate: 1 });
7517
7475
  };
7518
7476
 
7519
7477
  const openFilterPane = async (page) => {
@@ -7575,2963 +7533,121 @@ const currencyUtils = {
7575
7533
  currencyFormat,
7576
7534
  };
7577
7535
 
7578
- function getUserAgent() {
7579
- if (typeof navigator === "object" && "userAgent" in navigator) {
7580
- return navigator.userAgent;
7581
- }
7582
-
7583
- if (typeof process === "object" && process.version !== undefined) {
7584
- return `Node.js/${process.version.substr(1)} (${process.platform}; ${
7585
- process.arch
7586
- })`;
7587
- }
7588
-
7589
- return "<environment undetectable>";
7590
- }
7591
-
7592
- // pkg/dist-src/defaults.js
7593
-
7594
- // pkg/dist-src/version.js
7595
- var VERSION$7 = "0.0.0-development";
7596
-
7597
- // pkg/dist-src/defaults.js
7598
- var userAgent = `octokit-endpoint.js/${VERSION$7} ${getUserAgent()}`;
7599
- var DEFAULTS = {
7600
- method: "GET",
7601
- baseUrl: "https://api.github.com",
7602
- headers: {
7603
- accept: "application/vnd.github.v3+json",
7604
- "user-agent": userAgent
7605
- },
7606
- mediaType: {
7607
- format: ""
7608
- }
7536
+ const PEM_PATTERN = /(-----BEGIN [A-Z ]+-----)([\s\S]*?)(-----END [A-Z ]+-----)/;
7537
+ const PEM_LINE_LENGTH = 64;
7538
+ const GITHUB_BOT_ENV_VARS = [
7539
+ "GITHUB_BOT_APP_ID",
7540
+ "GITHUB_BOT_PRIVATE_KEY",
7541
+ "GITHUB_BOT_INSTALLATION_ID",
7542
+ ];
7543
+ let cachedAppAuth;
7544
+ // Secret stores hold the key with \n escapes, with spaces, or base64-encoded.
7545
+ const readPrivateKey = (rawKey) => {
7546
+ const unescaped = rawKey.replace(/\\n/g, "\n");
7547
+ const decoded = unescaped.includes("-----BEGIN")
7548
+ ? unescaped
7549
+ : Buffer.from(rawKey.replace(/\s/g, ""), "base64").toString("utf-8");
7550
+ const pem = decoded.match(PEM_PATTERN);
7551
+ if (!pem)
7552
+ failTest("ENV variable GITHUB_BOT_PRIVATE_KEY is not a PEM key or a base64 encoded PEM key");
7553
+ const [, begin, body, end] = pem;
7554
+ const lines = body.replace(/\s/g, "").match(new RegExp(`.{1,${PEM_LINE_LENGTH}}`, "g")) ??
7555
+ [];
7556
+ return [begin, ...lines, end, ""].join("\n");
7557
+ };
7558
+ // The auth client holds the token cache, so it must be reused across calls.
7559
+ const getAppAuth = () => {
7560
+ if (cachedAppAuth)
7561
+ return cachedAppAuth;
7562
+ const missing = GITHUB_BOT_ENV_VARS.filter(name => isNotPresent(process.env[name]));
7563
+ if (missing.length > 0)
7564
+ failTest(`ENV variables ${missing.join(", ")} are not set. Set all of ${GITHUB_BOT_ENV_VARS.join(", ")}, or set only GITHUB_TOKEN`);
7565
+ const appId = process.env.GITHUB_BOT_APP_ID;
7566
+ const privateKey = process.env.GITHUB_BOT_PRIVATE_KEY;
7567
+ const installationId = process.env.GITHUB_BOT_INSTALLATION_ID;
7568
+ // createAppAuth needs a PKCS#8 key, and the bundled JWT signer does not convert the PKCS#1 key that GitHub issues.
7569
+ const privateKeyPkcs8 = createPrivateKey(readPrivateKey(privateKey)).export({
7570
+ type: "pkcs8",
7571
+ format: "pem",
7572
+ });
7573
+ cachedAppAuth = createAppAuth({
7574
+ appId: appId.trim(),
7575
+ privateKey: privateKeyPkcs8,
7576
+ installationId: installationId.trim(),
7577
+ });
7578
+ return cachedAppAuth;
7579
+ };
7580
+ const getGithubToken = async ({ forceRefresh = false, } = {}) => {
7581
+ const isGithubBotConfigured = GITHUB_BOT_ENV_VARS.some(name => process.env[name]);
7582
+ const githubToken = process.env.GITHUB_TOKEN;
7583
+ if (!isGithubBotConfigured && githubToken)
7584
+ return githubToken;
7585
+ const { token } = await getAppAuth()({
7586
+ type: "installation",
7587
+ refresh: forceRefresh,
7588
+ });
7589
+ return token;
7609
7590
  };
7610
7591
 
7611
- // pkg/dist-src/util/lowercase-keys.js
7612
- function lowercaseKeys(object) {
7613
- if (!object) {
7614
- return {};
7615
- }
7616
- return Object.keys(object).reduce((newObj, key) => {
7617
- newObj[key.toLowerCase()] = object[key];
7618
- return newObj;
7619
- }, {});
7620
- }
7621
-
7622
- // pkg/dist-src/util/is-plain-object.js
7623
- function isPlainObject$1(value) {
7624
- if (typeof value !== "object" || value === null) return false;
7625
- if (Object.prototype.toString.call(value) !== "[object Object]") return false;
7626
- const proto = Object.getPrototypeOf(value);
7627
- if (proto === null) return true;
7628
- const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
7629
- return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
7630
- }
7631
-
7632
- // pkg/dist-src/util/merge-deep.js
7633
- function mergeDeep(defaults, options) {
7634
- const result = Object.assign({}, defaults);
7635
- Object.keys(options).forEach((key) => {
7636
- if (isPlainObject$1(options[key])) {
7637
- if (!(key in defaults)) Object.assign(result, { [key]: options[key] });
7638
- else result[key] = mergeDeep(defaults[key], options[key]);
7639
- } else {
7640
- Object.assign(result, { [key]: options[key] });
7641
- }
7642
- });
7643
- return result;
7644
- }
7645
-
7646
- // pkg/dist-src/util/remove-undefined-properties.js
7647
- function removeUndefinedProperties(obj) {
7648
- for (const key in obj) {
7649
- if (obj[key] === void 0) {
7650
- delete obj[key];
7651
- }
7652
- }
7653
- return obj;
7654
- }
7655
-
7656
- // pkg/dist-src/merge.js
7657
- function merge(defaults, route, options) {
7658
- if (typeof route === "string") {
7659
- let [method, url] = route.split(" ");
7660
- options = Object.assign(url ? { method, url } : { url: method }, options);
7661
- } else {
7662
- options = Object.assign({}, route);
7663
- }
7664
- options.headers = lowercaseKeys(options.headers);
7665
- removeUndefinedProperties(options);
7666
- removeUndefinedProperties(options.headers);
7667
- const mergedOptions = mergeDeep(defaults || {}, options);
7668
- if (options.url === "/graphql") {
7669
- if (defaults && defaults.mediaType.previews?.length) {
7670
- mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
7671
- (preview) => !mergedOptions.mediaType.previews.includes(preview)
7672
- ).concat(mergedOptions.mediaType.previews);
7673
- }
7674
- mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
7675
- }
7676
- return mergedOptions;
7677
- }
7678
-
7679
- // pkg/dist-src/util/add-query-parameters.js
7680
- function addQueryParameters(url, parameters) {
7681
- const separator = /\?/.test(url) ? "&" : "?";
7682
- const names = Object.keys(parameters);
7683
- if (names.length === 0) {
7684
- return url;
7685
- }
7686
- return url + separator + names.map((name) => {
7687
- if (name === "q") {
7688
- return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
7592
+ const issueStatusCache = new Map();
7593
+ const fetchIsIssueOpen = async (owner, repo, issueNumber) => {
7594
+ const requestIssue = (auth) => new Octokit({ auth }).request("GET /repos/{owner}/{repo}/issues/{issue_number}", {
7595
+ owner,
7596
+ repo,
7597
+ issue_number: issueNumber,
7598
+ headers: { "X-GitHub-Api-Version": "2022-11-28" },
7599
+ });
7600
+ try {
7601
+ const { data } = await requestIssue(await getGithubToken());
7602
+ return data.state === "open";
7689
7603
  }
7690
- return `${name}=${encodeURIComponent(parameters[name])}`;
7691
- }).join("&");
7692
- }
7693
-
7694
- // pkg/dist-src/util/extract-url-variable-names.js
7695
- var urlVariableRegex = /\{[^{}}]+\}/g;
7696
- function removeNonChars(variableName) {
7697
- return variableName.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g, "").split(/,/);
7698
- }
7699
- function extractUrlVariableNames(url) {
7700
- const matches = url.match(urlVariableRegex);
7701
- if (!matches) {
7702
- return [];
7703
- }
7704
- return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
7705
- }
7706
-
7707
- // pkg/dist-src/util/omit.js
7708
- function omit(object, keysToOmit) {
7709
- const result = { __proto__: null };
7710
- for (const key of Object.keys(object)) {
7711
- if (keysToOmit.indexOf(key) === -1) {
7712
- result[key] = object[key];
7604
+ catch (error) {
7605
+ // 401 means the cached token was revoked — mint a fresh one and retry once.
7606
+ if (error.status !== 401)
7607
+ throw error;
7608
+ const { data } = await requestIssue(await getGithubToken({ forceRefresh: true }));
7609
+ return data.state === "open";
7713
7610
  }
7714
- }
7715
- return result;
7716
- }
7611
+ };
7612
+ const isIssueOpen = (issueLink) => {
7613
+ const [owner, repo, ...rest] = (issueLink.split(/[?#]/)[0].split("github.com/").at(-1) ?? "")
7614
+ .split("/")
7615
+ .filter(Boolean);
7616
+ const issueNumber = Number(rest.at(-1));
7617
+ if (!owner || !repo || !Number.isInteger(issueNumber))
7618
+ failTest(`[isGithubIssueOpen] Invalid GitHub issue link: ${issueLink}`);
7619
+ const cacheKey = `${owner}/${repo}#${issueNumber}`;
7620
+ const cachedStatus = issueStatusCache.get(cacheKey);
7621
+ if (cachedStatus)
7622
+ return cachedStatus;
7623
+ const status = fetchIsIssueOpen(owner, repo, issueNumber);
7624
+ issueStatusCache.set(cacheKey, status);
7625
+ status.catch(() => issueStatusCache.delete(cacheKey));
7626
+ return status;
7627
+ };
7628
+ const isGithubIssueOpen = async (issueLinks) => {
7629
+ const issueStatuses = await Promise.all(issueLinks.map(isIssueOpen));
7630
+ return issueStatuses.some(Boolean);
7631
+ };
7717
7632
 
7718
- // pkg/dist-src/util/url-template.js
7719
- function encodeReserved(str) {
7720
- return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
7721
- if (!/%[0-9A-Fa-f]/.test(part)) {
7722
- part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
7723
- }
7724
- return part;
7725
- }).join("");
7726
- }
7727
- function encodeUnreserved(str) {
7728
- return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
7729
- return "%" + c.charCodeAt(0).toString(16).toUpperCase();
7730
- });
7731
- }
7732
- function encodeValue(operator, value, key) {
7733
- value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
7734
- if (key) {
7735
- return encodeUnreserved(key) + "=" + value;
7736
- } else {
7737
- return value;
7738
- }
7739
- }
7740
- function isDefined(value) {
7741
- return value !== void 0 && value !== null;
7742
- }
7743
- function isKeyOperator(operator) {
7744
- return operator === ";" || operator === "&" || operator === "?";
7745
- }
7746
- function getValues(context, operator, key, modifier) {
7747
- var value = context[key], result = [];
7748
- if (isDefined(value) && value !== "") {
7749
- if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
7750
- value = value.toString();
7751
- if (modifier && modifier !== "*") {
7752
- value = value.substring(0, parseInt(modifier, 10));
7753
- }
7754
- result.push(
7755
- encodeValue(operator, value, isKeyOperator(operator) ? key : "")
7756
- );
7757
- } else {
7758
- if (modifier === "*") {
7759
- if (Array.isArray(value)) {
7760
- value.filter(isDefined).forEach(function(value2) {
7761
- result.push(
7762
- encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
7763
- );
7764
- });
7765
- } else {
7766
- Object.keys(value).forEach(function(k) {
7767
- if (isDefined(value[k])) {
7768
- result.push(encodeValue(operator, value[k], k));
7769
- }
7770
- });
7771
- }
7772
- } else {
7773
- const tmp = [];
7774
- if (Array.isArray(value)) {
7775
- value.filter(isDefined).forEach(function(value2) {
7776
- tmp.push(encodeValue(operator, value2));
7777
- });
7778
- } else {
7779
- Object.keys(value).forEach(function(k) {
7780
- if (isDefined(value[k])) {
7781
- tmp.push(encodeUnreserved(k));
7782
- tmp.push(encodeValue(operator, value[k].toString()));
7783
- }
7784
- });
7785
- }
7786
- if (isKeyOperator(operator)) {
7787
- result.push(encodeUnreserved(key) + "=" + tmp.join(","));
7788
- } else if (tmp.length !== 0) {
7789
- result.push(tmp.join(","));
7790
- }
7791
- }
7792
- }
7793
- } else {
7794
- if (operator === ";") {
7795
- if (isDefined(value)) {
7796
- result.push(encodeUnreserved(key));
7797
- }
7798
- } else if (value === "" && (operator === "&" || operator === "?")) {
7799
- result.push(encodeUnreserved(key) + "=");
7800
- } else if (value === "") {
7801
- result.push("");
7802
- }
7803
- }
7804
- return result;
7805
- }
7806
- function parseUrl(template) {
7807
- return {
7808
- expand: expand.bind(null, template)
7809
- };
7810
- }
7811
- function expand(template, context) {
7812
- var operators = ["+", "#", ".", "/", ";", "?", "&"];
7813
- template = template.replace(
7814
- /\{([^\{\}]+)\}|([^\{\}]+)/g,
7815
- function(_, expression, literal) {
7816
- if (expression) {
7817
- let operator = "";
7818
- const values = [];
7819
- if (operators.indexOf(expression.charAt(0)) !== -1) {
7820
- operator = expression.charAt(0);
7821
- expression = expression.substr(1);
7822
- }
7823
- expression.split(/,/g).forEach(function(variable) {
7824
- var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
7825
- values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
7826
- });
7827
- if (operator && operator !== "+") {
7828
- var separator = ",";
7829
- if (operator === "?") {
7830
- separator = "&";
7831
- } else if (operator !== "#") {
7832
- separator = operator;
7833
- }
7834
- return (values.length !== 0 ? operator : "") + values.join(separator);
7835
- } else {
7836
- return values.join(",");
7837
- }
7838
- } else {
7839
- return encodeReserved(literal);
7840
- }
7841
- }
7842
- );
7843
- if (template === "/") {
7844
- return template;
7845
- } else {
7846
- return template.replace(/\/$/, "");
7847
- }
7848
- }
7849
-
7850
- // pkg/dist-src/parse.js
7851
- function parse(options) {
7852
- let method = options.method.toUpperCase();
7853
- let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
7854
- let headers = Object.assign({}, options.headers);
7855
- let body;
7856
- let parameters = omit(options, [
7857
- "method",
7858
- "baseUrl",
7859
- "url",
7860
- "headers",
7861
- "request",
7862
- "mediaType"
7863
- ]);
7864
- const urlVariableNames = extractUrlVariableNames(url);
7865
- url = parseUrl(url).expand(parameters);
7866
- if (!/^http/.test(url)) {
7867
- url = options.baseUrl + url;
7868
- }
7869
- const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
7870
- const remainingParameters = omit(parameters, omittedParameters);
7871
- const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
7872
- if (!isBinaryRequest) {
7873
- if (options.mediaType.format) {
7874
- headers.accept = headers.accept.split(/,/).map(
7875
- (format) => format.replace(
7876
- /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
7877
- `application/vnd$1$2.${options.mediaType.format}`
7878
- )
7879
- ).join(",");
7880
- }
7881
- if (url.endsWith("/graphql")) {
7882
- if (options.mediaType.previews?.length) {
7883
- const previewsFromAcceptHeader = headers.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g) || [];
7884
- headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
7885
- const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
7886
- return `application/vnd.github.${preview}-preview${format}`;
7887
- }).join(",");
7888
- }
7889
- }
7890
- }
7891
- if (["GET", "HEAD"].includes(method)) {
7892
- url = addQueryParameters(url, remainingParameters);
7893
- } else {
7894
- if ("data" in remainingParameters) {
7895
- body = remainingParameters.data;
7896
- } else {
7897
- if (Object.keys(remainingParameters).length) {
7898
- body = remainingParameters;
7899
- }
7900
- }
7901
- }
7902
- if (!headers["content-type"] && typeof body !== "undefined") {
7903
- headers["content-type"] = "application/json; charset=utf-8";
7904
- }
7905
- if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
7906
- body = "";
7907
- }
7908
- return Object.assign(
7909
- { method, url, headers },
7910
- typeof body !== "undefined" ? { body } : null,
7911
- options.request ? { request: options.request } : null
7912
- );
7913
- }
7914
-
7915
- // pkg/dist-src/endpoint-with-defaults.js
7916
- function endpointWithDefaults(defaults, route, options) {
7917
- return parse(merge(defaults, route, options));
7918
- }
7919
-
7920
- // pkg/dist-src/with-defaults.js
7921
- function withDefaults$2(oldDefaults, newDefaults) {
7922
- const DEFAULTS2 = merge(oldDefaults, newDefaults);
7923
- const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
7924
- return Object.assign(endpoint2, {
7925
- DEFAULTS: DEFAULTS2,
7926
- defaults: withDefaults$2.bind(null, DEFAULTS2),
7927
- merge: merge.bind(null, DEFAULTS2),
7928
- parse
7929
- });
7930
- }
7931
-
7932
- // pkg/dist-src/index.js
7933
- var endpoint = withDefaults$2(null, DEFAULTS);
7934
-
7935
- var fastContentTypeParse = {};
7936
-
7937
- var hasRequiredFastContentTypeParse;
7938
-
7939
- function requireFastContentTypeParse () {
7940
- if (hasRequiredFastContentTypeParse) return fastContentTypeParse;
7941
- hasRequiredFastContentTypeParse = 1;
7942
-
7943
- const NullObject = function NullObject () { };
7944
- NullObject.prototype = Object.create(null);
7945
-
7946
- /**
7947
- * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
7948
- *
7949
- * parameter = token "=" ( token / quoted-string )
7950
- * token = 1*tchar
7951
- * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
7952
- * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
7953
- * / DIGIT / ALPHA
7954
- * ; any VCHAR, except delimiters
7955
- * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
7956
- * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
7957
- * obs-text = %x80-FF
7958
- * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
7959
- */
7960
- const paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
7961
-
7962
- /**
7963
- * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
7964
- *
7965
- * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
7966
- * obs-text = %x80-FF
7967
- */
7968
- const quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
7969
-
7970
- /**
7971
- * RegExp to match type in RFC 7231 sec 3.1.1.1
7972
- *
7973
- * media-type = type "/" subtype
7974
- * type = token
7975
- * subtype = token
7976
- */
7977
- const mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u;
7978
-
7979
- // default ContentType to prevent repeated object creation
7980
- const defaultContentType = { type: '', parameters: new NullObject() };
7981
- Object.freeze(defaultContentType.parameters);
7982
- Object.freeze(defaultContentType);
7983
-
7984
- /**
7985
- * Parse media type to object.
7986
- *
7987
- * @param {string|object} header
7988
- * @return {Object}
7989
- * @public
7990
- */
7991
-
7992
- function parse (header) {
7993
- if (typeof header !== 'string') {
7994
- throw new TypeError('argument header is required and must be a string')
7995
- }
7996
-
7997
- let index = header.indexOf(';');
7998
- const type = index !== -1
7999
- ? header.slice(0, index).trim()
8000
- : header.trim();
8001
-
8002
- if (mediaTypeRE.test(type) === false) {
8003
- throw new TypeError('invalid media type')
8004
- }
8005
-
8006
- const result = {
8007
- type: type.toLowerCase(),
8008
- parameters: new NullObject()
8009
- };
8010
-
8011
- // parse parameters
8012
- if (index === -1) {
8013
- return result
8014
- }
8015
-
8016
- let key;
8017
- let match;
8018
- let value;
8019
-
8020
- paramRE.lastIndex = index;
8021
-
8022
- while ((match = paramRE.exec(header))) {
8023
- if (match.index !== index) {
8024
- throw new TypeError('invalid parameter format')
8025
- }
8026
-
8027
- index += match[0].length;
8028
- key = match[1].toLowerCase();
8029
- value = match[2];
8030
-
8031
- if (value[0] === '"') {
8032
- // remove quotes and escapes
8033
- value = value
8034
- .slice(1, value.length - 1);
8035
-
8036
- quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'));
8037
- }
8038
-
8039
- result.parameters[key] = value;
8040
- }
8041
-
8042
- if (index !== header.length) {
8043
- throw new TypeError('invalid parameter format')
8044
- }
8045
-
8046
- return result
8047
- }
8048
-
8049
- function safeParse (header) {
8050
- if (typeof header !== 'string') {
8051
- return defaultContentType
8052
- }
8053
-
8054
- let index = header.indexOf(';');
8055
- const type = index !== -1
8056
- ? header.slice(0, index).trim()
8057
- : header.trim();
8058
-
8059
- if (mediaTypeRE.test(type) === false) {
8060
- return defaultContentType
8061
- }
8062
-
8063
- const result = {
8064
- type: type.toLowerCase(),
8065
- parameters: new NullObject()
8066
- };
8067
-
8068
- // parse parameters
8069
- if (index === -1) {
8070
- return result
8071
- }
8072
-
8073
- let key;
8074
- let match;
8075
- let value;
8076
-
8077
- paramRE.lastIndex = index;
8078
-
8079
- while ((match = paramRE.exec(header))) {
8080
- if (match.index !== index) {
8081
- return defaultContentType
8082
- }
8083
-
8084
- index += match[0].length;
8085
- key = match[1].toLowerCase();
8086
- value = match[2];
8087
-
8088
- if (value[0] === '"') {
8089
- // remove quotes and escapes
8090
- value = value
8091
- .slice(1, value.length - 1);
8092
-
8093
- quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'));
8094
- }
8095
-
8096
- result.parameters[key] = value;
8097
- }
8098
-
8099
- if (index !== header.length) {
8100
- return defaultContentType
8101
- }
8102
-
8103
- return result
8104
- }
8105
-
8106
- fastContentTypeParse.default = { parse, safeParse };
8107
- fastContentTypeParse.parse = parse;
8108
- fastContentTypeParse.safeParse = safeParse;
8109
- fastContentTypeParse.defaultContentType = defaultContentType;
8110
- return fastContentTypeParse;
8111
- }
8112
-
8113
- var fastContentTypeParseExports = requireFastContentTypeParse();
8114
-
8115
- const intRegex = /^-?\d+$/;
8116
- const noiseValue = /^-?\d+n+$/; // Noise - strings that match the custom format before being converted to it
8117
- const originalStringify = JSON.stringify;
8118
- const originalParse = JSON.parse;
8119
- const customFormat = /^-?\d+n$/;
8120
-
8121
- const bigIntsStringify = /([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g;
8122
- const noiseStringify =
8123
- /([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g;
8124
-
8125
- /** @typedef {(key: string, value: any, context?: { source: string }) => any} Reviver */
8126
-
8127
- /**
8128
- * Function to serialize value to a JSON string.
8129
- * Converts BigInt values to a custom format (strings with digits and "n" at the end) and then converts them to proper big integers in a JSON string.
8130
- * @param {*} value - The value to convert to a JSON string.
8131
- * @param {(Function|Array<string>|null)} [replacer] - A function that alters the behavior of the stringification process, or an array of strings to indicate properties to exclude.
8132
- * @param {(string|number)} [space] - A string or number to specify indentation or pretty-printing.
8133
- * @returns {string} The JSON string representation.
8134
- */
8135
- const JSONStringify = (value, replacer, space) => {
8136
- if ("rawJSON" in JSON) {
8137
- return originalStringify(
8138
- value,
8139
- (key, value) => {
8140
- if (typeof value === "bigint") return JSON.rawJSON(value.toString());
8141
-
8142
- if (Array.isArray(replacer) && replacer.includes(key)) return value;
8143
-
8144
- return value;
8145
- },
8146
- space,
8147
- );
8148
- }
8149
-
8150
- if (!value) return originalStringify(value, replacer, space);
8151
-
8152
- const convertedToCustomJSON = originalStringify(
8153
- value,
8154
- (key, value) => {
8155
- const isNoise =
8156
- typeof value === "string" && Boolean(value.match(noiseValue));
8157
-
8158
- if (isNoise) return value.toString() + "n"; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing
8159
-
8160
- if (typeof value === "bigint") return value.toString() + "n";
8161
-
8162
- if (Array.isArray(replacer) && replacer.includes(key)) return value;
8163
-
8164
- return value;
8165
- },
8166
- space,
8167
- );
8168
- const processedJSON = convertedToCustomJSON.replace(
8169
- bigIntsStringify,
8170
- "$1$2$3",
8171
- ); // Delete one "n" off the end of every BigInt value
8172
- const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); // Remove one "n" off the end of every noisy string
8173
-
8174
- return denoisedJSON;
8175
- };
8176
-
8177
- /**
8178
- * Support for JSON.parse's context.source feature detection.
8179
- * @type {boolean}
8180
- */
8181
- const isContextSourceSupported = () =>
8182
- JSON.parse("1", (_, __, context) => !!context && context.source === "1");
8183
-
8184
- /**
8185
- * Convert marked big numbers to BigInt
8186
- * @type {Reviver}
8187
- */
8188
- const convertMarkedBigIntsReviver = (key, value, context, userReviver) => {
8189
- const isCustomFormatBigInt =
8190
- typeof value === "string" && value.match(customFormat);
8191
- if (isCustomFormatBigInt) return BigInt(value.slice(0, -1));
8192
-
8193
- const isNoiseValue = typeof value === "string" && value.match(noiseValue);
8194
- if (isNoiseValue) return value.slice(0, -1);
8195
-
8196
- return value;
8197
- };
8198
-
8199
- /**
8200
- * Faster (2x) and simpler function to parse JSON.
8201
- * Based on JSON.parse's context.source feature, which is not universally available now.
8202
- * Does not support the legacy custom format, used in the first version of this library.
8203
- */
8204
- const JSONParseV2 = (text, reviver) => {
8205
- return JSON.parse(text, (key, value, context) => {
8206
- const isBigNumber =
8207
- typeof value === "number" &&
8208
- (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER);
8209
- const isInt = context && intRegex.test(context.source);
8210
- const isBigInt = isBigNumber && isInt;
8211
-
8212
- if (isBigInt) return BigInt(context.source);
8213
-
8214
- return value;
8215
- });
8216
- };
8217
-
8218
- const MAX_INT = Number.MAX_SAFE_INTEGER.toString();
8219
- const MAX_DIGITS = MAX_INT.length;
8220
- const stringsOrLargeNumbers =
8221
- /"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g;
8222
- const noiseValueWithQuotes = /^"-?\d+n+"$/; // Noise - strings that match the custom format before being converted to it
8223
-
8224
- /**
8225
- * Function to parse JSON.
8226
- * If JSON has number values greater than Number.MAX_SAFE_INTEGER, we convert those values to a custom format, then parse them to BigInt values.
8227
- * Other types of values are not affected and parsed as native JSON.parse() would parse them.
8228
- */
8229
- const JSONParse = (text, reviver) => {
8230
- if (!text) return originalParse(text, reviver);
8231
-
8232
- if (isContextSourceSupported()) return JSONParseV2(text); // Shortcut to a faster (2x) and simpler version
8233
-
8234
- // Find and mark big numbers with "n"
8235
- const serializedData = text.replace(
8236
- stringsOrLargeNumbers,
8237
- (text, digits, fractional, exponential) => {
8238
- const isString = text[0] === '"';
8239
- const isNoise = isString && Boolean(text.match(noiseValueWithQuotes));
8240
-
8241
- if (isNoise) return text.substring(0, text.length - 1) + 'n"'; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing
8242
-
8243
- const isFractionalOrExponential = fractional || exponential;
8244
- const isLessThanMaxSafeInt =
8245
- digits &&
8246
- (digits.length < MAX_DIGITS ||
8247
- (digits.length === MAX_DIGITS && digits <= MAX_INT)); // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison
8248
-
8249
- if (isString || isFractionalOrExponential || isLessThanMaxSafeInt)
8250
- return text;
8251
-
8252
- return '"' + text + 'n"';
8253
- },
8254
- );
8255
-
8256
- return originalParse(serializedData, (key, value, context) =>
8257
- convertMarkedBigIntsReviver(key, value),
8258
- );
8259
- };
8260
-
8261
- class RequestError extends Error {
8262
- name;
8263
- /**
8264
- * http status code
8265
- */
8266
- status;
8267
- /**
8268
- * Request options that lead to the error.
8269
- */
8270
- request;
8271
- /**
8272
- * Response object if a response was received
8273
- */
8274
- response;
8275
- constructor(message, statusCode, options) {
8276
- super(message, { cause: options.cause });
8277
- this.name = "HttpError";
8278
- this.status = Number.parseInt(statusCode);
8279
- if (Number.isNaN(this.status)) {
8280
- this.status = 0;
8281
- }
8282
- /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */
8283
- if ("response" in options) {
8284
- this.response = options.response;
8285
- }
8286
- const requestCopy = Object.assign({}, options.request);
8287
- if (options.request.headers.authorization) {
8288
- requestCopy.headers = Object.assign({}, options.request.headers, {
8289
- authorization: options.request.headers.authorization.replace(
8290
- /(?<! ) .*$/,
8291
- " [REDACTED]"
8292
- )
8293
- });
8294
- }
8295
- requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
8296
- this.request = requestCopy;
8297
- }
8298
- }
8299
-
8300
- // pkg/dist-src/index.js
8301
-
8302
- // pkg/dist-src/version.js
8303
- var VERSION$6 = "10.0.8";
8304
-
8305
- // pkg/dist-src/defaults.js
8306
- var defaults_default = {
8307
- headers: {
8308
- "user-agent": `octokit-request.js/${VERSION$6} ${getUserAgent()}`
8309
- }
8310
- };
8311
-
8312
- // pkg/dist-src/is-plain-object.js
8313
- function isPlainObject(value) {
8314
- if (typeof value !== "object" || value === null) return false;
8315
- if (Object.prototype.toString.call(value) !== "[object Object]") return false;
8316
- const proto = Object.getPrototypeOf(value);
8317
- if (proto === null) return true;
8318
- const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
8319
- return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
8320
- }
8321
- var noop$1 = () => "";
8322
- async function fetchWrapper(requestOptions) {
8323
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
8324
- if (!fetch) {
8325
- throw new Error(
8326
- "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing"
8327
- );
8328
- }
8329
- const log = requestOptions.request?.log || console;
8330
- const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;
8331
- const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body;
8332
- const requestHeaders = Object.fromEntries(
8333
- Object.entries(requestOptions.headers).map(([name, value]) => [
8334
- name,
8335
- String(value)
8336
- ])
8337
- );
8338
- let fetchResponse;
8339
- try {
8340
- fetchResponse = await fetch(requestOptions.url, {
8341
- method: requestOptions.method,
8342
- body,
8343
- redirect: requestOptions.request?.redirect,
8344
- headers: requestHeaders,
8345
- signal: requestOptions.request?.signal,
8346
- // duplex must be set if request.body is ReadableStream or Async Iterables.
8347
- // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.
8348
- ...requestOptions.body && { duplex: "half" }
8349
- });
8350
- } catch (error) {
8351
- let message = "Unknown Error";
8352
- if (error instanceof Error) {
8353
- if (error.name === "AbortError") {
8354
- error.status = 500;
8355
- throw error;
8356
- }
8357
- message = error.message;
8358
- if (error.name === "TypeError" && "cause" in error) {
8359
- if (error.cause instanceof Error) {
8360
- message = error.cause.message;
8361
- } else if (typeof error.cause === "string") {
8362
- message = error.cause;
8363
- }
8364
- }
8365
- }
8366
- const requestError = new RequestError(message, 500, {
8367
- request: requestOptions
8368
- });
8369
- requestError.cause = error;
8370
- throw requestError;
8371
- }
8372
- const status = fetchResponse.status;
8373
- const url = fetchResponse.url;
8374
- const responseHeaders = {};
8375
- for (const [key, value] of fetchResponse.headers) {
8376
- responseHeaders[key] = value;
8377
- }
8378
- const octokitResponse = {
8379
- url,
8380
- status,
8381
- headers: responseHeaders,
8382
- data: ""
8383
- };
8384
- if ("deprecation" in responseHeaders) {
8385
- const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/);
8386
- const deprecationLink = matches && matches.pop();
8387
- log.warn(
8388
- `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
8389
- );
8390
- }
8391
- if (status === 204 || status === 205) {
8392
- return octokitResponse;
8393
- }
8394
- if (requestOptions.method === "HEAD") {
8395
- if (status < 400) {
8396
- return octokitResponse;
8397
- }
8398
- throw new RequestError(fetchResponse.statusText, status, {
8399
- response: octokitResponse,
8400
- request: requestOptions
8401
- });
8402
- }
8403
- if (status === 304) {
8404
- octokitResponse.data = await getResponseData(fetchResponse);
8405
- throw new RequestError("Not modified", status, {
8406
- response: octokitResponse,
8407
- request: requestOptions
8408
- });
8409
- }
8410
- if (status >= 400) {
8411
- octokitResponse.data = await getResponseData(fetchResponse);
8412
- throw new RequestError(toErrorMessage(octokitResponse.data), status, {
8413
- response: octokitResponse,
8414
- request: requestOptions
8415
- });
8416
- }
8417
- octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;
8418
- return octokitResponse;
8419
- }
8420
- async function getResponseData(response) {
8421
- const contentType = response.headers.get("content-type");
8422
- if (!contentType) {
8423
- return response.text().catch(noop$1);
8424
- }
8425
- const mimetype = fastContentTypeParseExports.safeParse(contentType);
8426
- if (isJSONResponse(mimetype)) {
8427
- let text = "";
8428
- try {
8429
- text = await response.text();
8430
- return JSONParse(text);
8431
- } catch (err) {
8432
- return text;
8433
- }
8434
- } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") {
8435
- return response.text().catch(noop$1);
8436
- } else {
8437
- return response.arrayBuffer().catch(
8438
- /* v8 ignore next -- @preserve */
8439
- () => new ArrayBuffer(0)
8440
- );
8441
- }
8442
- }
8443
- function isJSONResponse(mimetype) {
8444
- return mimetype.type === "application/json" || mimetype.type === "application/scim+json";
8445
- }
8446
- function toErrorMessage(data) {
8447
- if (typeof data === "string") {
8448
- return data;
8449
- }
8450
- if (data instanceof ArrayBuffer) {
8451
- return "Unknown error";
8452
- }
8453
- if ("message" in data) {
8454
- const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : "";
8455
- return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`;
8456
- }
8457
- return `Unknown error: ${JSON.stringify(data)}`;
8458
- }
8459
-
8460
- // pkg/dist-src/with-defaults.js
8461
- function withDefaults$1(oldEndpoint, newDefaults) {
8462
- const endpoint2 = oldEndpoint.defaults(newDefaults);
8463
- const newApi = function(route, parameters) {
8464
- const endpointOptions = endpoint2.merge(route, parameters);
8465
- if (!endpointOptions.request || !endpointOptions.request.hook) {
8466
- return fetchWrapper(endpoint2.parse(endpointOptions));
8467
- }
8468
- const request2 = (route2, parameters2) => {
8469
- return fetchWrapper(
8470
- endpoint2.parse(endpoint2.merge(route2, parameters2))
8471
- );
8472
- };
8473
- Object.assign(request2, {
8474
- endpoint: endpoint2,
8475
- defaults: withDefaults$1.bind(null, endpoint2)
8476
- });
8477
- return endpointOptions.request.hook(request2, endpointOptions);
8478
- };
8479
- return Object.assign(newApi, {
8480
- endpoint: endpoint2,
8481
- defaults: withDefaults$1.bind(null, endpoint2)
8482
- });
8483
- }
8484
-
8485
- // pkg/dist-src/index.js
8486
- var request = withDefaults$1(endpoint, defaults_default);
8487
- /* v8 ignore next -- @preserve */
8488
- /* v8 ignore else -- @preserve */
8489
-
8490
- // pkg/dist-src/version.js
8491
- function requestToOAuthBaseUrl$1(request) {
8492
- const endpointDefaults = request.endpoint.DEFAULTS;
8493
- return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
8494
- }
8495
- async function oauthRequest$1(request, route, parameters) {
8496
- const withOAuthParameters = {
8497
- baseUrl: requestToOAuthBaseUrl$1(request),
8498
- headers: {
8499
- accept: "application/json"
8500
- },
8501
- ...parameters
8502
- };
8503
- const response = await request(route, withOAuthParameters);
8504
- if ("error" in response.data) {
8505
- const error = new RequestError(
8506
- `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`,
8507
- 400,
8508
- {
8509
- request: request.endpoint.merge(
8510
- route,
8511
- withOAuthParameters
8512
- )
8513
- }
8514
- );
8515
- error.response = response;
8516
- throw error;
8517
- }
8518
- return response;
8519
- }
8520
- async function createDeviceCode(options) {
8521
- const request$1 = options.request || request;
8522
- const parameters = {
8523
- client_id: options.clientId
8524
- };
8525
- if ("scopes" in options && Array.isArray(options.scopes)) {
8526
- parameters.scope = options.scopes.join(" ");
8527
- }
8528
- return oauthRequest$1(request$1, "POST /login/device/code", parameters);
8529
- }
8530
- async function exchangeDeviceCode(options) {
8531
- const request$1 = options.request || request;
8532
- const response = await oauthRequest$1(
8533
- request$1,
8534
- "POST /login/oauth/access_token",
8535
- {
8536
- client_id: options.clientId,
8537
- device_code: options.code,
8538
- grant_type: "urn:ietf:params:oauth:grant-type:device_code"
8539
- }
8540
- );
8541
- const authentication = {
8542
- clientType: options.clientType,
8543
- clientId: options.clientId,
8544
- token: response.data.access_token,
8545
- scopes: response.data.scope.split(/\s+/).filter(Boolean)
8546
- };
8547
- if ("clientSecret" in options) {
8548
- authentication.clientSecret = options.clientSecret;
8549
- }
8550
- if (options.clientType === "github-app") {
8551
- if ("refresh_token" in response.data) {
8552
- const apiTimeInMs = new Date(response.headers.date).getTime();
8553
- authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp2(
8554
- apiTimeInMs,
8555
- response.data.expires_in
8556
- ), authentication.refreshTokenExpiresAt = toTimestamp2(
8557
- apiTimeInMs,
8558
- response.data.refresh_token_expires_in
8559
- );
8560
- }
8561
- delete authentication.scopes;
8562
- }
8563
- return { ...response, authentication };
8564
- }
8565
- function toTimestamp2(apiTimeInMs, expirationInSeconds) {
8566
- return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
8567
- }
8568
-
8569
- // pkg/dist-src/index.js
8570
- async function getOAuthAccessToken(state, options) {
8571
- const cachedAuthentication = getCachedAuthentication(state, options.auth);
8572
- if (cachedAuthentication) return cachedAuthentication;
8573
- const { data: verification } = await createDeviceCode({
8574
- clientType: state.clientType,
8575
- clientId: state.clientId,
8576
- request: options.request || state.request,
8577
- // @ts-expect-error the extra code to make TS happy is not worth it
8578
- scopes: options.auth.scopes || state.scopes
8579
- });
8580
- await state.onVerification(verification);
8581
- const authentication = await waitForAccessToken(
8582
- options.request || state.request,
8583
- state.clientId,
8584
- state.clientType,
8585
- verification
8586
- );
8587
- state.authentication = authentication;
8588
- return authentication;
8589
- }
8590
- function getCachedAuthentication(state, auth2) {
8591
- if (auth2.refresh === true) return false;
8592
- if (!state.authentication) return false;
8593
- if (state.clientType === "github-app") {
8594
- return state.authentication;
8595
- }
8596
- const authentication = state.authentication;
8597
- const newScope = ("scopes" in auth2 && auth2.scopes || state.scopes).join(
8598
- " "
8599
- );
8600
- const currentScope = authentication.scopes.join(" ");
8601
- return newScope === currentScope ? authentication : false;
8602
- }
8603
- async function wait(seconds) {
8604
- await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
8605
- }
8606
- async function waitForAccessToken(request, clientId, clientType, verification) {
8607
- try {
8608
- const options = {
8609
- clientId,
8610
- request,
8611
- code: verification.device_code
8612
- };
8613
- const { authentication } = clientType === "oauth-app" ? await exchangeDeviceCode({
8614
- ...options,
8615
- clientType: "oauth-app"
8616
- }) : await exchangeDeviceCode({
8617
- ...options,
8618
- clientType: "github-app"
8619
- });
8620
- return {
8621
- type: "token",
8622
- tokenType: "oauth",
8623
- ...authentication
8624
- };
8625
- } catch (error) {
8626
- if (!error.response) throw error;
8627
- const errorType = error.response.data.error;
8628
- if (errorType === "authorization_pending") {
8629
- await wait(verification.interval);
8630
- return waitForAccessToken(request, clientId, clientType, verification);
8631
- }
8632
- if (errorType === "slow_down") {
8633
- await wait(verification.interval + 7);
8634
- return waitForAccessToken(request, clientId, clientType, verification);
8635
- }
8636
- throw error;
8637
- }
8638
- }
8639
-
8640
- // pkg/dist-src/auth.js
8641
- async function auth$4(state, authOptions) {
8642
- return getOAuthAccessToken(state, {
8643
- auth: authOptions
8644
- });
8645
- }
8646
-
8647
- // pkg/dist-src/hook.js
8648
- async function hook$4(state, request, route, parameters) {
8649
- let endpoint = request.endpoint.merge(
8650
- route,
8651
- parameters
8652
- );
8653
- if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
8654
- return request(endpoint);
8655
- }
8656
- const { token } = await getOAuthAccessToken(state, {
8657
- request,
8658
- auth: { type: "oauth" }
8659
- });
8660
- endpoint.headers.authorization = `token ${token}`;
8661
- return request(endpoint);
8662
- }
8663
-
8664
- // pkg/dist-src/version.js
8665
- var VERSION$5 = "0.0.0-development";
8666
-
8667
- // pkg/dist-src/index.js
8668
- function createOAuthDeviceAuth(options) {
8669
- const requestWithDefaults = options.request || request.defaults({
8670
- headers: {
8671
- "user-agent": `octokit-auth-oauth-device.js/${VERSION$5} ${getUserAgent()}`
8672
- }
8673
- });
8674
- const { request: request$1 = requestWithDefaults, ...otherOptions } = options;
8675
- const state = options.clientType === "github-app" ? {
8676
- ...otherOptions,
8677
- clientType: "github-app",
8678
- request: request$1
8679
- } : {
8680
- ...otherOptions,
8681
- clientType: "oauth-app",
8682
- request: request$1,
8683
- scopes: options.scopes || []
8684
- };
8685
- if (!options.clientId) {
8686
- throw new Error(
8687
- '[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'
8688
- );
8689
- }
8690
- if (!options.onVerification) {
8691
- throw new Error(
8692
- '[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'
8693
- );
8694
- }
8695
- return Object.assign(auth$4.bind(null, state), {
8696
- hook: hook$4.bind(null, state)
8697
- });
8698
- }
8699
-
8700
- // pkg/dist-src/version.js
8701
- function requestToOAuthBaseUrl(request) {
8702
- const endpointDefaults = request.endpoint.DEFAULTS;
8703
- return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
8704
- }
8705
- async function oauthRequest(request, route, parameters) {
8706
- const withOAuthParameters = {
8707
- baseUrl: requestToOAuthBaseUrl(request),
8708
- headers: {
8709
- accept: "application/json"
8710
- },
8711
- ...parameters
8712
- };
8713
- const response = await request(route, withOAuthParameters);
8714
- if ("error" in response.data) {
8715
- const error = new RequestError(
8716
- `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`,
8717
- 400,
8718
- {
8719
- request: request.endpoint.merge(
8720
- route,
8721
- withOAuthParameters
8722
- )
8723
- }
8724
- );
8725
- error.response = response;
8726
- throw error;
8727
- }
8728
- return response;
8729
- }
8730
- async function exchangeWebFlowCode(options) {
8731
- const request$1 = options.request || request;
8732
- const response = await oauthRequest(
8733
- request$1,
8734
- "POST /login/oauth/access_token",
8735
- {
8736
- client_id: options.clientId,
8737
- client_secret: options.clientSecret,
8738
- code: options.code,
8739
- redirect_uri: options.redirectUrl
8740
- }
8741
- );
8742
- const authentication = {
8743
- clientType: options.clientType,
8744
- clientId: options.clientId,
8745
- clientSecret: options.clientSecret,
8746
- token: response.data.access_token,
8747
- scopes: response.data.scope.split(/\s+/).filter(Boolean)
8748
- };
8749
- if (options.clientType === "github-app") {
8750
- if ("refresh_token" in response.data) {
8751
- const apiTimeInMs = new Date(response.headers.date).getTime();
8752
- authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(
8753
- apiTimeInMs,
8754
- response.data.expires_in
8755
- ), authentication.refreshTokenExpiresAt = toTimestamp(
8756
- apiTimeInMs,
8757
- response.data.refresh_token_expires_in
8758
- );
8759
- }
8760
- delete authentication.scopes;
8761
- }
8762
- return { ...response, authentication };
8763
- }
8764
- function toTimestamp(apiTimeInMs, expirationInSeconds) {
8765
- return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
8766
- }
8767
- async function checkToken(options) {
8768
- const request$1 = options.request || request;
8769
- const response = await request$1("POST /applications/{client_id}/token", {
8770
- headers: {
8771
- authorization: `basic ${btoa(
8772
- `${options.clientId}:${options.clientSecret}`
8773
- )}`
8774
- },
8775
- client_id: options.clientId,
8776
- access_token: options.token
8777
- });
8778
- const authentication = {
8779
- clientType: options.clientType,
8780
- clientId: options.clientId,
8781
- clientSecret: options.clientSecret,
8782
- token: options.token,
8783
- scopes: response.data.scopes
8784
- };
8785
- if (response.data.expires_at)
8786
- authentication.expiresAt = response.data.expires_at;
8787
- if (options.clientType === "github-app") {
8788
- delete authentication.scopes;
8789
- }
8790
- return { ...response, authentication };
8791
- }
8792
- async function refreshToken(options) {
8793
- const request$1 = options.request || request;
8794
- const response = await oauthRequest(
8795
- request$1,
8796
- "POST /login/oauth/access_token",
8797
- {
8798
- client_id: options.clientId,
8799
- client_secret: options.clientSecret,
8800
- grant_type: "refresh_token",
8801
- refresh_token: options.refreshToken
8802
- }
8803
- );
8804
- const apiTimeInMs = new Date(response.headers.date).getTime();
8805
- const authentication = {
8806
- clientType: "github-app",
8807
- clientId: options.clientId,
8808
- clientSecret: options.clientSecret,
8809
- token: response.data.access_token,
8810
- refreshToken: response.data.refresh_token,
8811
- expiresAt: toTimestamp3(apiTimeInMs, response.data.expires_in),
8812
- refreshTokenExpiresAt: toTimestamp3(
8813
- apiTimeInMs,
8814
- response.data.refresh_token_expires_in
8815
- )
8816
- };
8817
- return { ...response, authentication };
8818
- }
8819
- function toTimestamp3(apiTimeInMs, expirationInSeconds) {
8820
- return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
8821
- }
8822
- async function resetToken(options) {
8823
- const request$1 = options.request || request;
8824
- const auth = btoa(`${options.clientId}:${options.clientSecret}`);
8825
- const response = await request$1(
8826
- "PATCH /applications/{client_id}/token",
8827
- {
8828
- headers: {
8829
- authorization: `basic ${auth}`
8830
- },
8831
- client_id: options.clientId,
8832
- access_token: options.token
8833
- }
8834
- );
8835
- const authentication = {
8836
- clientType: options.clientType,
8837
- clientId: options.clientId,
8838
- clientSecret: options.clientSecret,
8839
- token: response.data.token,
8840
- scopes: response.data.scopes
8841
- };
8842
- if (response.data.expires_at)
8843
- authentication.expiresAt = response.data.expires_at;
8844
- if (options.clientType === "github-app") {
8845
- delete authentication.scopes;
8846
- }
8847
- return { ...response, authentication };
8848
- }
8849
- async function deleteToken(options) {
8850
- const request$1 = options.request || request;
8851
- const auth = btoa(`${options.clientId}:${options.clientSecret}`);
8852
- return request$1(
8853
- "DELETE /applications/{client_id}/token",
8854
- {
8855
- headers: {
8856
- authorization: `basic ${auth}`
8857
- },
8858
- client_id: options.clientId,
8859
- access_token: options.token
8860
- }
8861
- );
8862
- }
8863
- async function deleteAuthorization(options) {
8864
- const request$1 = options.request || request;
8865
- const auth = btoa(`${options.clientId}:${options.clientSecret}`);
8866
- return request$1(
8867
- "DELETE /applications/{client_id}/grant",
8868
- {
8869
- headers: {
8870
- authorization: `basic ${auth}`
8871
- },
8872
- client_id: options.clientId,
8873
- access_token: options.token
8874
- }
8875
- );
8876
- }
8877
-
8878
- // pkg/dist-src/index.js
8879
-
8880
- // pkg/dist-src/version.js
8881
- var VERSION$4 = "0.0.0-development";
8882
- async function getAuthentication(state) {
8883
- if ("code" in state.strategyOptions) {
8884
- const { authentication } = await exchangeWebFlowCode({
8885
- clientId: state.clientId,
8886
- clientSecret: state.clientSecret,
8887
- clientType: state.clientType,
8888
- onTokenCreated: state.onTokenCreated,
8889
- ...state.strategyOptions,
8890
- request: state.request
8891
- });
8892
- return {
8893
- type: "token",
8894
- tokenType: "oauth",
8895
- ...authentication
8896
- };
8897
- }
8898
- if ("onVerification" in state.strategyOptions) {
8899
- const deviceAuth = createOAuthDeviceAuth({
8900
- clientType: state.clientType,
8901
- clientId: state.clientId,
8902
- onTokenCreated: state.onTokenCreated,
8903
- ...state.strategyOptions,
8904
- request: state.request
8905
- });
8906
- const authentication = await deviceAuth({
8907
- type: "oauth"
8908
- });
8909
- return {
8910
- clientSecret: state.clientSecret,
8911
- ...authentication
8912
- };
8913
- }
8914
- if ("token" in state.strategyOptions) {
8915
- return {
8916
- type: "token",
8917
- tokenType: "oauth",
8918
- clientId: state.clientId,
8919
- clientSecret: state.clientSecret,
8920
- clientType: state.clientType,
8921
- onTokenCreated: state.onTokenCreated,
8922
- ...state.strategyOptions
8923
- };
8924
- }
8925
- throw new Error("[@octokit/auth-oauth-user] Invalid strategy options");
8926
- }
8927
- async function auth$3(state, options = {}) {
8928
- if (!state.authentication) {
8929
- state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state);
8930
- }
8931
- if (state.authentication.invalid) {
8932
- throw new Error("[@octokit/auth-oauth-user] Token is invalid");
8933
- }
8934
- const currentAuthentication = state.authentication;
8935
- if ("expiresAt" in currentAuthentication) {
8936
- if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < /* @__PURE__ */ new Date()) {
8937
- const { authentication } = await refreshToken({
8938
- clientId: state.clientId,
8939
- clientSecret: state.clientSecret,
8940
- refreshToken: currentAuthentication.refreshToken,
8941
- request: state.request
8942
- });
8943
- state.authentication = {
8944
- tokenType: "oauth",
8945
- type: "token",
8946
- ...authentication
8947
- };
8948
- }
8949
- }
8950
- if (options.type === "refresh") {
8951
- if (state.clientType === "oauth-app") {
8952
- throw new Error(
8953
- "[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"
8954
- );
8955
- }
8956
- if (!currentAuthentication.hasOwnProperty("expiresAt")) {
8957
- throw new Error("[@octokit/auth-oauth-user] Refresh token missing");
8958
- }
8959
- await state.onTokenCreated?.(state.authentication, {
8960
- type: options.type
8961
- });
8962
- }
8963
- if (options.type === "check" || options.type === "reset") {
8964
- const method = options.type === "check" ? checkToken : resetToken;
8965
- try {
8966
- const { authentication } = await method({
8967
- // @ts-expect-error making TS happy would require unnecessary code so no
8968
- clientType: state.clientType,
8969
- clientId: state.clientId,
8970
- clientSecret: state.clientSecret,
8971
- token: state.authentication.token,
8972
- request: state.request
8973
- });
8974
- state.authentication = {
8975
- tokenType: "oauth",
8976
- type: "token",
8977
- // @ts-expect-error TBD
8978
- ...authentication
8979
- };
8980
- if (options.type === "reset") {
8981
- await state.onTokenCreated?.(state.authentication, {
8982
- type: options.type
8983
- });
8984
- }
8985
- return state.authentication;
8986
- } catch (error) {
8987
- if (error.status === 404) {
8988
- error.message = "[@octokit/auth-oauth-user] Token is invalid";
8989
- state.authentication.invalid = true;
8990
- }
8991
- throw error;
8992
- }
8993
- }
8994
- if (options.type === "delete" || options.type === "deleteAuthorization") {
8995
- const method = options.type === "delete" ? deleteToken : deleteAuthorization;
8996
- try {
8997
- await method({
8998
- // @ts-expect-error making TS happy would require unnecessary code so no
8999
- clientType: state.clientType,
9000
- clientId: state.clientId,
9001
- clientSecret: state.clientSecret,
9002
- token: state.authentication.token,
9003
- request: state.request
9004
- });
9005
- } catch (error) {
9006
- if (error.status !== 404) throw error;
9007
- }
9008
- state.authentication.invalid = true;
9009
- return state.authentication;
9010
- }
9011
- return state.authentication;
9012
- }
9013
-
9014
- // pkg/dist-src/requires-basic-auth.js
9015
- var ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/;
9016
- function requiresBasicAuth(url) {
9017
- return url && ROUTES_REQUIRING_BASIC_AUTH.test(url);
9018
- }
9019
-
9020
- // pkg/dist-src/hook.js
9021
- async function hook$3(state, request, route, parameters = {}) {
9022
- const endpoint = request.endpoint.merge(
9023
- route,
9024
- parameters
9025
- );
9026
- if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
9027
- return request(endpoint);
9028
- }
9029
- if (requiresBasicAuth(endpoint.url)) {
9030
- const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
9031
- endpoint.headers.authorization = `basic ${credentials}`;
9032
- return request(endpoint);
9033
- }
9034
- const { token } = state.clientType === "oauth-app" ? await auth$3({ ...state, request }) : await auth$3({ ...state, request });
9035
- endpoint.headers.authorization = "token " + token;
9036
- return request(endpoint);
9037
- }
9038
-
9039
- // pkg/dist-src/index.js
9040
- function createOAuthUserAuth({
9041
- clientId,
9042
- clientSecret,
9043
- clientType = "oauth-app",
9044
- request: request$1 = request.defaults({
9045
- headers: {
9046
- "user-agent": `octokit-auth-oauth-app.js/${VERSION$4} ${getUserAgent()}`
9047
- }
9048
- }),
9049
- onTokenCreated,
9050
- ...strategyOptions
9051
- }) {
9052
- const state = Object.assign({
9053
- clientType,
9054
- clientId,
9055
- clientSecret,
9056
- onTokenCreated,
9057
- strategyOptions,
9058
- request: request$1
9059
- });
9060
- return Object.assign(auth$3.bind(null, state), {
9061
- // @ts-expect-error not worth the extra code needed to appease TS
9062
- hook: hook$3.bind(null, state)
9063
- });
9064
- }
9065
- createOAuthUserAuth.VERSION = VERSION$4;
9066
-
9067
- // pkg/dist-src/index.js
9068
- async function auth$2(state, authOptions) {
9069
- if (authOptions.type === "oauth-app") {
9070
- return {
9071
- type: "oauth-app",
9072
- clientId: state.clientId,
9073
- clientSecret: state.clientSecret,
9074
- clientType: state.clientType,
9075
- headers: {
9076
- authorization: `basic ${btoa(
9077
- `${state.clientId}:${state.clientSecret}`
9078
- )}`
9079
- }
9080
- };
9081
- }
9082
- if ("factory" in authOptions) {
9083
- const { type, ...options } = {
9084
- ...authOptions,
9085
- ...state
9086
- };
9087
- return authOptions.factory(options);
9088
- }
9089
- const common = {
9090
- clientId: state.clientId,
9091
- clientSecret: state.clientSecret,
9092
- request: state.request,
9093
- ...authOptions
9094
- };
9095
- const userAuth = state.clientType === "oauth-app" ? await createOAuthUserAuth({
9096
- ...common,
9097
- clientType: state.clientType
9098
- }) : await createOAuthUserAuth({
9099
- ...common,
9100
- clientType: state.clientType
9101
- });
9102
- return userAuth();
9103
- }
9104
- async function hook$2(state, request2, route, parameters) {
9105
- let endpoint = request2.endpoint.merge(
9106
- route,
9107
- parameters
9108
- );
9109
- if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
9110
- return request2(endpoint);
9111
- }
9112
- if (state.clientType === "github-app" && !requiresBasicAuth(endpoint.url)) {
9113
- throw new Error(
9114
- `[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`
9115
- );
9116
- }
9117
- const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
9118
- endpoint.headers.authorization = `basic ${credentials}`;
9119
- try {
9120
- return await request2(endpoint);
9121
- } catch (error) {
9122
- if (error.status !== 401) throw error;
9123
- error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`;
9124
- throw error;
9125
- }
9126
- }
9127
-
9128
- // pkg/dist-src/version.js
9129
- var VERSION$3 = "0.0.0-development";
9130
- function createOAuthAppAuth(options) {
9131
- const state = Object.assign(
9132
- {
9133
- request: request.defaults({
9134
- headers: {
9135
- "user-agent": `octokit-auth-oauth-app.js/${VERSION$3} ${getUserAgent()}`
9136
- }
9137
- }),
9138
- clientType: "oauth-app"
9139
- },
9140
- options
9141
- );
9142
- return Object.assign(auth$2.bind(null, state), {
9143
- hook: hook$2.bind(null, state)
9144
- });
9145
- }
9146
-
9147
- // we don't @ts-check here because it chokes on atob and btoa which are available in all modern JS runtime environments
9148
-
9149
- /**
9150
- * @param {string} privateKey
9151
- * @returns {boolean}
9152
- */
9153
- function isPkcs1(privateKey) {
9154
- return privateKey.includes("-----BEGIN RSA PRIVATE KEY-----");
9155
- }
9156
-
9157
- /**
9158
- * @param {string} privateKey
9159
- * @returns {boolean}
9160
- */
9161
- function isOpenSsh(privateKey) {
9162
- return privateKey.includes("-----BEGIN OPENSSH PRIVATE KEY-----");
9163
- }
9164
-
9165
- /**
9166
- * @param {string} str
9167
- * @returns {ArrayBuffer}
9168
- */
9169
- function string2ArrayBuffer(str) {
9170
- const buf = new ArrayBuffer(str.length);
9171
- const bufView = new Uint8Array(buf);
9172
- for (let i = 0, strLen = str.length; i < strLen; i++) {
9173
- bufView[i] = str.charCodeAt(i);
9174
- }
9175
- return buf;
9176
- }
9177
-
9178
- /**
9179
- * @param {string} pem
9180
- * @returns {ArrayBuffer}
9181
- */
9182
- function getDERfromPEM(pem) {
9183
- const pemB64 = pem
9184
- .trim()
9185
- .split("\n")
9186
- .slice(1, -1) // Remove the --- BEGIN / END PRIVATE KEY ---
9187
- .join("");
9188
-
9189
- const decoded = atob(pemB64);
9190
- return string2ArrayBuffer(decoded);
9191
- }
9192
-
9193
- /**
9194
- * @param {import('../internals').Header} header
9195
- * @param {import('../internals').Payload} payload
9196
- * @returns {string}
9197
- */
9198
- function getEncodedMessage(header, payload) {
9199
- return `${base64encodeJSON(header)}.${base64encodeJSON(payload)}`;
9200
- }
9201
-
9202
- /**
9203
- * @param {ArrayBuffer} buffer
9204
- * @returns {string}
9205
- */
9206
- function base64encode(buffer) {
9207
- var binary = "";
9208
- var bytes = new Uint8Array(buffer);
9209
- var len = bytes.byteLength;
9210
- for (var i = 0; i < len; i++) {
9211
- binary += String.fromCharCode(bytes[i]);
9212
- }
9213
-
9214
- return fromBase64(btoa(binary));
9215
- }
9216
-
9217
- /**
9218
- * @param {string} base64
9219
- * @returns {string}
9220
- */
9221
- function fromBase64(base64) {
9222
- return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
9223
- }
9224
-
9225
- /**
9226
- * @param {Record<string,unknown>} obj
9227
- * @returns {string}
9228
- */
9229
- function base64encodeJSON(obj) {
9230
- return fromBase64(btoa(JSON.stringify(obj)));
9231
- }
9232
-
9233
- const { subtle } = globalThis.crypto;
9234
-
9235
- // no-op, unfortunately there is no way to transform from PKCS8 or OpenSSH to PKCS1 with WebCrypto
9236
- function convertPrivateKey(privateKey) {
9237
- return privateKey;
9238
- }
9239
-
9240
- // we don't @ts-check here because it chokes crypto which is a global API in modern JS runtime environments
9241
-
9242
-
9243
- /**
9244
- * @param {import('../internals').GetTokenOptions} options
9245
- * @returns {Promise<string>}
9246
- */
9247
- async function getToken({ privateKey, payload }) {
9248
- const convertedPrivateKey = convertPrivateKey(privateKey);
9249
-
9250
- // WebCrypto only supports PKCS#8, unfortunately
9251
- /* c8 ignore start */
9252
- if (isPkcs1(convertedPrivateKey)) {
9253
- throw new Error(
9254
- "[universal-github-app-jwt] Private Key is in PKCS#1 format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats"
9255
- );
9256
- }
9257
- /* c8 ignore stop */
9258
-
9259
- // WebCrypto does not support OpenSSH, unfortunately
9260
- if (isOpenSsh(convertedPrivateKey)) {
9261
- throw new Error(
9262
- "[universal-github-app-jwt] Private Key is in OpenSSH format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats"
9263
- );
9264
- }
9265
-
9266
- const algorithm = {
9267
- name: "RSASSA-PKCS1-v1_5",
9268
- hash: { name: "SHA-256" },
9269
- };
9270
-
9271
- /** @type {import('../internals').Header} */
9272
- const header = { alg: "RS256", typ: "JWT" };
9273
-
9274
- const privateKeyDER = getDERfromPEM(convertedPrivateKey);
9275
- const importedKey = await subtle.importKey(
9276
- "pkcs8",
9277
- privateKeyDER,
9278
- algorithm,
9279
- false,
9280
- ["sign"]
9281
- );
9282
-
9283
- const encodedMessage = getEncodedMessage(header, payload);
9284
- const encodedMessageArrBuf = string2ArrayBuffer(encodedMessage);
9285
-
9286
- const signatureArrBuf = await subtle.sign(
9287
- algorithm.name,
9288
- importedKey,
9289
- encodedMessageArrBuf
9290
- );
9291
-
9292
- const encodedSignature = base64encode(signatureArrBuf);
9293
-
9294
- return `${encodedMessage}.${encodedSignature}`;
9295
- }
9296
-
9297
- // @ts-check
9298
-
9299
-
9300
- /**
9301
- * @param {import(".").Options} options
9302
- * @returns {Promise<import(".").Result>}
9303
- */
9304
- async function githubAppJwt({
9305
- id,
9306
- privateKey,
9307
- now = Math.floor(Date.now() / 1000),
9308
- }) {
9309
- // Private keys are often times configured as environment variables, in which case line breaks are escaped using `\\n`.
9310
- // Replace these here for convenience.
9311
- const privateKeyWithNewlines = privateKey.replace(/\\n/g, '\n');
9312
-
9313
- // When creating a JSON Web Token, it sets the "issued at time" (iat) to 30s
9314
- // in the past as we have seen people running situations where the GitHub API
9315
- // claimed the iat would be in future. It turned out the clocks on the
9316
- // different machine were not in sync.
9317
- const nowWithSafetyMargin = now - 30;
9318
- const expiration = nowWithSafetyMargin + 60 * 10; // JWT expiration time (10 minute maximum)
9319
-
9320
- const payload = {
9321
- iat: nowWithSafetyMargin, // Issued at time
9322
- exp: expiration,
9323
- iss: id,
9324
- };
9325
-
9326
- const token = await getToken({
9327
- privateKey: privateKeyWithNewlines,
9328
- payload,
9329
- });
9330
-
9331
- return {
9332
- appId: id,
9333
- expiration,
9334
- token,
9335
- };
9336
- }
9337
-
9338
- /**
9339
- * toad-cache
9340
- *
9341
- * @copyright 2024 Igor Savin <kibertoad@gmail.com>
9342
- * @license MIT
9343
- * @version 3.7.0
9344
- */
9345
- class LruObject {
9346
- constructor(max = 1000, ttlInMsecs = 0) {
9347
- if (isNaN(max) || max < 0) {
9348
- throw new Error('Invalid max value')
9349
- }
9350
-
9351
- if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
9352
- throw new Error('Invalid ttl value')
9353
- }
9354
-
9355
- this.first = null;
9356
- this.items = Object.create(null);
9357
- this.last = null;
9358
- this.size = 0;
9359
- this.max = max;
9360
- this.ttl = ttlInMsecs;
9361
- }
9362
-
9363
- bumpLru(item) {
9364
- if (this.last === item) {
9365
- return // Item is already the last one, no need to bump
9366
- }
9367
-
9368
- const last = this.last;
9369
- const next = item.next;
9370
- const prev = item.prev;
9371
-
9372
- if (this.first === item) {
9373
- this.first = next;
9374
- }
9375
-
9376
- item.next = null;
9377
- item.prev = last;
9378
- last.next = item;
9379
-
9380
- if (prev !== null) {
9381
- prev.next = next;
9382
- }
9383
-
9384
- if (next !== null) {
9385
- next.prev = prev;
9386
- }
9387
-
9388
- this.last = item;
9389
- }
9390
-
9391
- clear() {
9392
- this.items = Object.create(null);
9393
- this.first = null;
9394
- this.last = null;
9395
- this.size = 0;
9396
- }
9397
-
9398
- delete(key) {
9399
- if (Object.prototype.hasOwnProperty.call(this.items, key)) {
9400
- const item = this.items[key];
9401
-
9402
- delete this.items[key];
9403
- this.size--;
9404
-
9405
- if (item.prev !== null) {
9406
- item.prev.next = item.next;
9407
- }
9408
-
9409
- if (item.next !== null) {
9410
- item.next.prev = item.prev;
9411
- }
9412
-
9413
- if (this.first === item) {
9414
- this.first = item.next;
9415
- }
9416
-
9417
- if (this.last === item) {
9418
- this.last = item.prev;
9419
- }
9420
- }
9421
- }
9422
-
9423
- deleteMany(keys) {
9424
- for (var i = 0; i < keys.length; i++) {
9425
- this.delete(keys[i]);
9426
- }
9427
- }
9428
-
9429
- evict() {
9430
- if (this.size > 0) {
9431
- const item = this.first;
9432
-
9433
- delete this.items[item.key];
9434
-
9435
- if (--this.size === 0) {
9436
- this.first = null;
9437
- this.last = null;
9438
- } else {
9439
- this.first = item.next;
9440
- this.first.prev = null;
9441
- }
9442
- }
9443
- }
9444
-
9445
- expiresAt(key) {
9446
- if (Object.prototype.hasOwnProperty.call(this.items, key)) {
9447
- return this.items[key].expiry
9448
- }
9449
- }
9450
-
9451
- get(key) {
9452
- if (Object.prototype.hasOwnProperty.call(this.items, key)) {
9453
- const item = this.items[key];
9454
-
9455
- // Item has already expired
9456
- if (this.ttl > 0 && item.expiry <= Date.now()) {
9457
- this.delete(key);
9458
- return
9459
- }
9460
-
9461
- // Item is still fresh
9462
- this.bumpLru(item);
9463
- return item.value
9464
- }
9465
- }
9466
-
9467
- getMany(keys) {
9468
- const result = [];
9469
-
9470
- for (var i = 0; i < keys.length; i++) {
9471
- result.push(this.get(keys[i]));
9472
- }
9473
-
9474
- return result
9475
- }
9476
-
9477
- keys() {
9478
- return Object.keys(this.items)
9479
- }
9480
-
9481
- set(key, value) {
9482
- // Replace existing item
9483
- if (Object.prototype.hasOwnProperty.call(this.items, key)) {
9484
- const item = this.items[key];
9485
- item.value = value;
9486
-
9487
- item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
9488
-
9489
- if (this.last !== item) {
9490
- this.bumpLru(item);
9491
- }
9492
-
9493
- return
9494
- }
9495
-
9496
- // Add new item
9497
- if (this.max > 0 && this.size === this.max) {
9498
- this.evict();
9499
- }
9500
-
9501
- const item = {
9502
- expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
9503
- key: key,
9504
- prev: this.last,
9505
- next: null,
9506
- value,
9507
- };
9508
- this.items[key] = item;
9509
-
9510
- if (++this.size === 1) {
9511
- this.first = item;
9512
- } else {
9513
- this.last.next = item;
9514
- }
9515
-
9516
- this.last = item;
9517
- }
9518
- }
9519
-
9520
- // pkg/dist-src/index.js
9521
- async function getAppAuthentication({
9522
- appId,
9523
- privateKey,
9524
- timeDifference,
9525
- createJwt
9526
- }) {
9527
- try {
9528
- if (createJwt) {
9529
- const { jwt, expiresAt } = await createJwt(appId, timeDifference);
9530
- return {
9531
- type: "app",
9532
- token: jwt,
9533
- appId,
9534
- expiresAt
9535
- };
9536
- }
9537
- const authOptions = {
9538
- id: appId,
9539
- privateKey
9540
- };
9541
- if (timeDifference) {
9542
- Object.assign(authOptions, {
9543
- now: Math.floor(Date.now() / 1e3) + timeDifference
9544
- });
9545
- }
9546
- const appAuthentication = await githubAppJwt(authOptions);
9547
- return {
9548
- type: "app",
9549
- token: appAuthentication.token,
9550
- appId: appAuthentication.appId,
9551
- expiresAt: new Date(appAuthentication.expiration * 1e3).toISOString()
9552
- };
9553
- } catch (error) {
9554
- if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") {
9555
- throw new Error(
9556
- "The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"
9557
- );
9558
- } else {
9559
- throw error;
9560
- }
9561
- }
9562
- }
9563
- function getCache() {
9564
- return new LruObject(
9565
- // cache max. 15000 tokens, that will use less than 10mb memory
9566
- 15e3,
9567
- // Cache for 1 minute less than GitHub expiry
9568
- 1e3 * 60 * 59
9569
- );
9570
- }
9571
- async function get(cache, options) {
9572
- const cacheKey = optionsToCacheKey(options);
9573
- const result = await cache.get(cacheKey);
9574
- if (!result) {
9575
- return;
9576
- }
9577
- const [
9578
- token,
9579
- createdAt,
9580
- expiresAt,
9581
- repositorySelection,
9582
- permissionsString,
9583
- singleFileName
9584
- ] = result.split("|");
9585
- const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => {
9586
- if (/!$/.test(string)) {
9587
- permissions2[string.slice(0, -1)] = "write";
9588
- } else {
9589
- permissions2[string] = "read";
9590
- }
9591
- return permissions2;
9592
- }, {});
9593
- return {
9594
- token,
9595
- createdAt,
9596
- expiresAt,
9597
- permissions,
9598
- repositoryIds: options.repositoryIds,
9599
- repositoryNames: options.repositoryNames,
9600
- singleFileName,
9601
- repositorySelection
9602
- };
9603
- }
9604
- async function set(cache, options, data) {
9605
- const key = optionsToCacheKey(options);
9606
- const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(
9607
- (name) => `${name}${data.permissions[name] === "write" ? "!" : ""}`
9608
- ).join(",");
9609
- const value = [
9610
- data.token,
9611
- data.createdAt,
9612
- data.expiresAt,
9613
- data.repositorySelection,
9614
- permissionsString,
9615
- data.singleFileName
9616
- ].join("|");
9617
- await cache.set(key, value);
9618
- }
9619
- function optionsToCacheKey({
9620
- installationId,
9621
- permissions = {},
9622
- repositoryIds = [],
9623
- repositoryNames = []
9624
- }) {
9625
- const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(",");
9626
- const repositoryIdsString = repositoryIds.sort().join(",");
9627
- const repositoryNamesString = repositoryNames.join(",");
9628
- return [
9629
- installationId,
9630
- repositoryIdsString,
9631
- repositoryNamesString,
9632
- permissionsString
9633
- ].filter(Boolean).join("|");
9634
- }
9635
-
9636
- // pkg/dist-src/to-token-authentication.js
9637
- function toTokenAuthentication({
9638
- installationId,
9639
- token,
9640
- createdAt,
9641
- expiresAt,
9642
- repositorySelection,
9643
- permissions,
9644
- repositoryIds,
9645
- repositoryNames,
9646
- singleFileName
9647
- }) {
9648
- return Object.assign(
9649
- {
9650
- type: "token",
9651
- tokenType: "installation",
9652
- token,
9653
- installationId,
9654
- permissions,
9655
- createdAt,
9656
- expiresAt,
9657
- repositorySelection
9658
- },
9659
- repositoryIds ? { repositoryIds } : null,
9660
- repositoryNames ? { repositoryNames } : null,
9661
- singleFileName ? { singleFileName } : null
9662
- );
9663
- }
9664
-
9665
- // pkg/dist-src/get-installation-authentication.js
9666
- async function getInstallationAuthentication(state, options, customRequest) {
9667
- const installationId = Number(options.installationId || state.installationId);
9668
- if (!installationId) {
9669
- throw new Error(
9670
- "[@octokit/auth-app] installationId option is required for installation authentication."
9671
- );
9672
- }
9673
- if (options.factory) {
9674
- const { type, factory, oauthApp, ...factoryAuthOptions } = {
9675
- ...state,
9676
- ...options
9677
- };
9678
- return factory(factoryAuthOptions);
9679
- }
9680
- const request = customRequest || state.request;
9681
- return getInstallationAuthenticationConcurrently(
9682
- state,
9683
- { ...options, installationId },
9684
- request
9685
- );
9686
- }
9687
- var pendingPromises = /* @__PURE__ */ new Map();
9688
- function getInstallationAuthenticationConcurrently(state, options, request) {
9689
- const cacheKey = optionsToCacheKey(options);
9690
- if (pendingPromises.has(cacheKey)) {
9691
- return pendingPromises.get(cacheKey);
9692
- }
9693
- const promise = getInstallationAuthenticationImpl(
9694
- state,
9695
- options,
9696
- request
9697
- ).finally(() => pendingPromises.delete(cacheKey));
9698
- pendingPromises.set(cacheKey, promise);
9699
- return promise;
9700
- }
9701
- async function getInstallationAuthenticationImpl(state, options, request) {
9702
- if (!options.refresh) {
9703
- const result = await get(state.cache, options);
9704
- if (result) {
9705
- const {
9706
- token: token2,
9707
- createdAt: createdAt2,
9708
- expiresAt: expiresAt2,
9709
- permissions: permissions2,
9710
- repositoryIds: repositoryIds2,
9711
- repositoryNames: repositoryNames2,
9712
- singleFileName: singleFileName2,
9713
- repositorySelection: repositorySelection2
9714
- } = result;
9715
- return toTokenAuthentication({
9716
- installationId: options.installationId,
9717
- token: token2,
9718
- createdAt: createdAt2,
9719
- expiresAt: expiresAt2,
9720
- permissions: permissions2,
9721
- repositorySelection: repositorySelection2,
9722
- repositoryIds: repositoryIds2,
9723
- repositoryNames: repositoryNames2,
9724
- singleFileName: singleFileName2
9725
- });
9726
- }
9727
- }
9728
- const appAuthentication = await getAppAuthentication(state);
9729
- const payload = {
9730
- installation_id: options.installationId,
9731
- mediaType: {
9732
- previews: ["machine-man"]
9733
- },
9734
- headers: {
9735
- authorization: `bearer ${appAuthentication.token}`
9736
- }
9737
- };
9738
- if (options.repositoryIds) {
9739
- Object.assign(payload, { repository_ids: options.repositoryIds });
9740
- }
9741
- if (options.repositoryNames) {
9742
- Object.assign(payload, {
9743
- repositories: options.repositoryNames
9744
- });
9745
- }
9746
- if (options.permissions) {
9747
- Object.assign(payload, { permissions: options.permissions });
9748
- }
9749
- const {
9750
- data: {
9751
- token,
9752
- expires_at: expiresAt,
9753
- repositories,
9754
- permissions: permissionsOptional,
9755
- repository_selection: repositorySelectionOptional,
9756
- single_file: singleFileName
9757
- }
9758
- } = await request(
9759
- "POST /app/installations/{installation_id}/access_tokens",
9760
- payload
9761
- );
9762
- const permissions = permissionsOptional || {};
9763
- const repositorySelection = repositorySelectionOptional || "all";
9764
- const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0;
9765
- const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0;
9766
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
9767
- const cacheOptions = {
9768
- token,
9769
- createdAt,
9770
- expiresAt,
9771
- repositorySelection,
9772
- permissions};
9773
- if (singleFileName) {
9774
- Object.assign(payload, { singleFileName });
9775
- }
9776
- await set(state.cache, options, cacheOptions);
9777
- const cacheData = {
9778
- installationId: options.installationId,
9779
- token,
9780
- createdAt,
9781
- expiresAt,
9782
- repositorySelection,
9783
- permissions,
9784
- repositoryIds,
9785
- repositoryNames
9786
- };
9787
- if (singleFileName) {
9788
- Object.assign(cacheData, { singleFileName });
9789
- }
9790
- return toTokenAuthentication(cacheData);
9791
- }
9792
-
9793
- // pkg/dist-src/auth.js
9794
- async function auth$1(state, authOptions) {
9795
- switch (authOptions.type) {
9796
- case "app":
9797
- return getAppAuthentication(state);
9798
- case "oauth-app":
9799
- return state.oauthApp({ type: "oauth-app" });
9800
- case "installation":
9801
- return getInstallationAuthentication(state, {
9802
- ...authOptions,
9803
- type: "installation"
9804
- });
9805
- case "oauth-user":
9806
- return state.oauthApp(authOptions);
9807
- default:
9808
- throw new Error(`Invalid auth type: ${authOptions.type}`);
9809
- }
9810
- }
9811
-
9812
- // pkg/dist-src/requires-app-auth.js
9813
- var PATHS = [
9814
- "/app",
9815
- "/app/hook/config",
9816
- "/app/hook/deliveries",
9817
- "/app/hook/deliveries/{delivery_id}",
9818
- "/app/hook/deliveries/{delivery_id}/attempts",
9819
- "/app/installations",
9820
- "/app/installations/{installation_id}",
9821
- "/app/installations/{installation_id}/access_tokens",
9822
- "/app/installations/{installation_id}/suspended",
9823
- "/app/installation-requests",
9824
- "/marketplace_listing/accounts/{account_id}",
9825
- "/marketplace_listing/plan",
9826
- "/marketplace_listing/plans",
9827
- "/marketplace_listing/plans/{plan_id}/accounts",
9828
- "/marketplace_listing/stubbed/accounts/{account_id}",
9829
- "/marketplace_listing/stubbed/plan",
9830
- "/marketplace_listing/stubbed/plans",
9831
- "/marketplace_listing/stubbed/plans/{plan_id}/accounts",
9832
- "/orgs/{org}/installation",
9833
- "/repos/{owner}/{repo}/installation",
9834
- "/users/{username}/installation",
9835
- "/enterprises/{enterprise}/installation"
9836
- ];
9837
- function routeMatcher(paths) {
9838
- const regexes = paths.map(
9839
- (p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/")
9840
- );
9841
- const regex = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})$`;
9842
- return new RegExp(regex, "i");
9843
- }
9844
- var REGEX = routeMatcher(PATHS);
9845
- function requiresAppAuth(url) {
9846
- return !!url && REGEX.test(url.split("?")[0]);
9847
- }
9848
-
9849
- // pkg/dist-src/hook.js
9850
- var FIVE_SECONDS_IN_MS = 5 * 1e3;
9851
- function isNotTimeSkewError(error) {
9852
- return !(error.message.match(
9853
- /'Expiration time' claim \('exp'\) is too far in the future/
9854
- ) || error.message.match(
9855
- /'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/
9856
- ) || error.message.match(
9857
- /'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/
9858
- ));
9859
- }
9860
- async function hook$1(state, request, route, parameters) {
9861
- const endpoint = request.endpoint.merge(route, parameters);
9862
- const url = endpoint.url;
9863
- if (/\/login\/oauth\/access_token$/.test(url)) {
9864
- return request(endpoint);
9865
- }
9866
- if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
9867
- const { token: token2 } = await getAppAuthentication(state);
9868
- endpoint.headers.authorization = `bearer ${token2}`;
9869
- let response;
9870
- try {
9871
- response = await request(endpoint);
9872
- } catch (error) {
9873
- if (isNotTimeSkewError(error)) {
9874
- throw error;
9875
- }
9876
- if (typeof error.response.headers.date === "undefined") {
9877
- throw error;
9878
- }
9879
- const diff = Math.floor(
9880
- (Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3
9881
- );
9882
- state.log.warn(error.message);
9883
- state.log.warn(
9884
- `[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`
9885
- );
9886
- const { token: token3 } = await getAppAuthentication({
9887
- ...state,
9888
- timeDifference: diff
9889
- });
9890
- endpoint.headers.authorization = `bearer ${token3}`;
9891
- return request(endpoint);
9892
- }
9893
- return response;
9894
- }
9895
- if (requiresBasicAuth(url)) {
9896
- const authentication = await state.oauthApp({ type: "oauth-app" });
9897
- endpoint.headers.authorization = authentication.headers.authorization;
9898
- return request(endpoint);
9899
- }
9900
- const { token, createdAt } = await getInstallationAuthentication(
9901
- state,
9902
- // @ts-expect-error TBD
9903
- {},
9904
- request.defaults({ baseUrl: endpoint.baseUrl })
9905
- );
9906
- endpoint.headers.authorization = `token ${token}`;
9907
- return sendRequestWithRetries(
9908
- state,
9909
- request,
9910
- endpoint,
9911
- createdAt
9912
- );
9913
- }
9914
- async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
9915
- const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt);
9916
- try {
9917
- return await request(options);
9918
- } catch (error) {
9919
- if (error.status !== 401) {
9920
- throw error;
9921
- }
9922
- if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
9923
- if (retries > 0) {
9924
- error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`;
9925
- }
9926
- throw error;
9927
- }
9928
- ++retries;
9929
- const awaitTime = retries * 1e3;
9930
- state.log.warn(
9931
- `[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)`
9932
- );
9933
- await new Promise((resolve) => setTimeout(resolve, awaitTime));
9934
- return sendRequestWithRetries(state, request, options, createdAt, retries);
9935
- }
9936
- }
9937
-
9938
- // pkg/dist-src/version.js
9939
- var VERSION$2 = "8.2.0";
9940
- function createAppAuth(options) {
9941
- if (!options.appId) {
9942
- throw new Error("[@octokit/auth-app] appId option is required");
9943
- }
9944
- if (!options.privateKey && !options.createJwt) {
9945
- throw new Error("[@octokit/auth-app] privateKey option is required");
9946
- } else if (options.privateKey && options.createJwt) {
9947
- throw new Error(
9948
- "[@octokit/auth-app] privateKey and createJwt options are mutually exclusive"
9949
- );
9950
- }
9951
- if ("installationId" in options && !options.installationId) {
9952
- throw new Error(
9953
- "[@octokit/auth-app] installationId is set to a falsy value"
9954
- );
9955
- }
9956
- const log = options.log || {};
9957
- if (typeof log.warn !== "function") {
9958
- log.warn = console.warn.bind(console);
9959
- }
9960
- const request$1 = options.request || request.defaults({
9961
- headers: {
9962
- "user-agent": `octokit-auth-app.js/${VERSION$2} ${getUserAgent()}`
9963
- }
9964
- });
9965
- const state = Object.assign(
9966
- {
9967
- request: request$1,
9968
- cache: getCache()
9969
- },
9970
- options,
9971
- options.installationId ? { installationId: Number(options.installationId) } : {},
9972
- {
9973
- log,
9974
- oauthApp: createOAuthAppAuth({
9975
- clientType: "github-app",
9976
- clientId: options.clientId || "",
9977
- clientSecret: options.clientSecret || "",
9978
- request: request$1
9979
- })
9980
- }
9981
- );
9982
- return Object.assign(auth$1.bind(null, state), {
9983
- hook: hook$1.bind(null, state)
9984
- });
9985
- }
9986
-
9987
- const PEM_PATTERN = /(-----BEGIN [A-Z ]+-----)([\s\S]*?)(-----END [A-Z ]+-----)/;
9988
- const PEM_LINE_LENGTH = 64;
9989
- const GITHUB_BOT_ENV_VARS = [
9990
- "GITHUB_BOT_APP_ID",
9991
- "GITHUB_BOT_PRIVATE_KEY",
9992
- "GITHUB_BOT_INSTALLATION_ID",
9993
- ];
9994
- let cachedAppAuth;
9995
- // Secret stores hold the key with \n escapes, with spaces, or base64-encoded.
9996
- const readPrivateKey = (rawKey) => {
9997
- const unescaped = rawKey.replace(/\\n/g, "\n");
9998
- const decoded = unescaped.includes("-----BEGIN")
9999
- ? unescaped
10000
- : Buffer.from(rawKey.replace(/\s/g, ""), "base64").toString("utf-8");
10001
- const pem = decoded.match(PEM_PATTERN);
10002
- if (!pem)
10003
- failTest("ENV variable GITHUB_BOT_PRIVATE_KEY is not a PEM key or a base64 encoded PEM key");
10004
- const [, begin, body, end] = pem;
10005
- const lines = body.replace(/\s/g, "").match(new RegExp(`.{1,${PEM_LINE_LENGTH}}`, "g")) ??
10006
- [];
10007
- return [begin, ...lines, end, ""].join("\n");
10008
- };
10009
- // The auth client holds the token cache, so it must be reused across calls.
10010
- const getAppAuth = () => {
10011
- if (cachedAppAuth)
10012
- return cachedAppAuth;
10013
- const missing = GITHUB_BOT_ENV_VARS.filter(name => isNotPresent(process.env[name]));
10014
- if (missing.length > 0)
10015
- failTest(`ENV variables ${missing.join(", ")} are not set. Set all of ${GITHUB_BOT_ENV_VARS.join(", ")}, or set only GITHUB_TOKEN`);
10016
- const appId = process.env.GITHUB_BOT_APP_ID;
10017
- const privateKey = process.env.GITHUB_BOT_PRIVATE_KEY;
10018
- const installationId = process.env.GITHUB_BOT_INSTALLATION_ID;
10019
- // createAppAuth needs a PKCS#8 key, and the bundled JWT signer does not convert the PKCS#1 key that GitHub issues.
10020
- const privateKeyPkcs8 = createPrivateKey(readPrivateKey(privateKey)).export({
10021
- type: "pkcs8",
10022
- format: "pem",
10023
- });
10024
- cachedAppAuth = createAppAuth({
10025
- appId: appId.trim(),
10026
- privateKey: privateKeyPkcs8,
10027
- installationId: installationId.trim(),
10028
- });
10029
- return cachedAppAuth;
10030
- };
10031
- const getGithubToken = async ({ forceRefresh = false, } = {}) => {
10032
- const isGithubBotConfigured = GITHUB_BOT_ENV_VARS.some(name => process.env[name]);
10033
- const githubToken = process.env.GITHUB_TOKEN;
10034
- if (!isGithubBotConfigured && githubToken)
10035
- return githubToken;
10036
- const { token } = await getAppAuth()({
10037
- type: "installation",
10038
- refresh: forceRefresh,
10039
- });
10040
- return token;
10041
- };
10042
-
10043
- // @ts-check
10044
-
10045
- function register(state, name, method, options) {
10046
- if (typeof method !== "function") {
10047
- throw new Error("method for before hook must be a function");
10048
- }
10049
-
10050
- if (!options) {
10051
- options = {};
10052
- }
10053
-
10054
- if (Array.isArray(name)) {
10055
- return name.reverse().reduce((callback, name) => {
10056
- return register.bind(null, state, name, callback, options);
10057
- }, method)();
10058
- }
10059
-
10060
- return Promise.resolve().then(() => {
10061
- if (!state.registry[name]) {
10062
- return method(options);
10063
- }
10064
-
10065
- return state.registry[name].reduce((method, registered) => {
10066
- return registered.hook.bind(null, method, options);
10067
- }, method)();
10068
- });
10069
- }
10070
-
10071
- // @ts-check
10072
-
10073
- function addHook(state, kind, name, hook) {
10074
- const orig = hook;
10075
- if (!state.registry[name]) {
10076
- state.registry[name] = [];
10077
- }
10078
-
10079
- if (kind === "before") {
10080
- hook = (method, options) => {
10081
- return Promise.resolve()
10082
- .then(orig.bind(null, options))
10083
- .then(method.bind(null, options));
10084
- };
10085
- }
10086
-
10087
- if (kind === "after") {
10088
- hook = (method, options) => {
10089
- let result;
10090
- return Promise.resolve()
10091
- .then(method.bind(null, options))
10092
- .then((result_) => {
10093
- result = result_;
10094
- return orig(result, options);
10095
- })
10096
- .then(() => {
10097
- return result;
10098
- });
10099
- };
10100
- }
10101
-
10102
- if (kind === "error") {
10103
- hook = (method, options) => {
10104
- return Promise.resolve()
10105
- .then(method.bind(null, options))
10106
- .catch((error) => {
10107
- return orig(error, options);
10108
- });
10109
- };
10110
- }
10111
-
10112
- state.registry[name].push({
10113
- hook: hook,
10114
- orig: orig,
10115
- });
10116
- }
10117
-
10118
- // @ts-check
10119
-
10120
- function removeHook(state, name, method) {
10121
- if (!state.registry[name]) {
10122
- return;
10123
- }
10124
-
10125
- const index = state.registry[name]
10126
- .map((registered) => {
10127
- return registered.orig;
10128
- })
10129
- .indexOf(method);
10130
-
10131
- if (index === -1) {
10132
- return;
10133
- }
10134
-
10135
- state.registry[name].splice(index, 1);
10136
- }
10137
-
10138
- // @ts-check
10139
-
10140
-
10141
- // bind with array of arguments: https://stackoverflow.com/a/21792913
10142
- const bind = Function.bind;
10143
- const bindable = bind.bind(bind);
10144
-
10145
- function bindApi(hook, state, name) {
10146
- const removeHookRef = bindable(removeHook, null).apply(
10147
- null,
10148
- [state]
10149
- );
10150
- hook.api = { remove: removeHookRef };
10151
- hook.remove = removeHookRef;
10152
- ["before", "error", "after", "wrap"].forEach((kind) => {
10153
- const args = [state, kind];
10154
- hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);
10155
- });
10156
- }
10157
-
10158
- function Collection() {
10159
- const state = {
10160
- registry: {},
10161
- };
10162
-
10163
- const hook = register.bind(null, state);
10164
- bindApi(hook, state);
10165
-
10166
- return hook;
10167
- }
10168
-
10169
- var Hook = { Collection };
10170
-
10171
- // pkg/dist-src/index.js
10172
-
10173
- // pkg/dist-src/version.js
10174
- var VERSION$1 = "0.0.0-development";
10175
-
10176
- // pkg/dist-src/error.js
10177
- function _buildMessageForResponseErrors(data) {
10178
- return `Request failed due to following response errors:
10179
- ` + data.errors.map((e) => ` - ${e.message}`).join("\n");
10180
- }
10181
- var GraphqlResponseError = class extends Error {
10182
- constructor(request2, headers, response) {
10183
- super(_buildMessageForResponseErrors(response));
10184
- this.request = request2;
10185
- this.headers = headers;
10186
- this.response = response;
10187
- this.errors = response.errors;
10188
- this.data = response.data;
10189
- if (Error.captureStackTrace) {
10190
- Error.captureStackTrace(this, this.constructor);
10191
- }
10192
- }
10193
- name = "GraphqlResponseError";
10194
- errors;
10195
- data;
10196
- };
10197
-
10198
- // pkg/dist-src/graphql.js
10199
- var NON_VARIABLE_OPTIONS = [
10200
- "method",
10201
- "baseUrl",
10202
- "url",
10203
- "headers",
10204
- "request",
10205
- "query",
10206
- "mediaType",
10207
- "operationName"
10208
- ];
10209
- var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
10210
- var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
10211
- function graphql(request2, query, options) {
10212
- if (options) {
10213
- if (typeof query === "string" && "query" in options) {
10214
- return Promise.reject(
10215
- new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
10216
- );
10217
- }
10218
- for (const key in options) {
10219
- if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
10220
- return Promise.reject(
10221
- new Error(
10222
- `[@octokit/graphql] "${key}" cannot be used as variable name`
10223
- )
10224
- );
10225
- }
10226
- }
10227
- const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
10228
- const requestOptions = Object.keys(
10229
- parsedOptions
10230
- ).reduce((result, key) => {
10231
- if (NON_VARIABLE_OPTIONS.includes(key)) {
10232
- result[key] = parsedOptions[key];
10233
- return result;
10234
- }
10235
- if (!result.variables) {
10236
- result.variables = {};
10237
- }
10238
- result.variables[key] = parsedOptions[key];
10239
- return result;
10240
- }, {});
10241
- const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
10242
- if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
10243
- requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
10244
- }
10245
- return request2(requestOptions).then((response) => {
10246
- if (response.data.errors) {
10247
- const headers = {};
10248
- for (const key of Object.keys(response.headers)) {
10249
- headers[key] = response.headers[key];
10250
- }
10251
- throw new GraphqlResponseError(
10252
- requestOptions,
10253
- headers,
10254
- response.data
10255
- );
10256
- }
10257
- return response.data.data;
10258
- });
10259
- }
10260
-
10261
- // pkg/dist-src/with-defaults.js
10262
- function withDefaults(request2, newDefaults) {
10263
- const newRequest = request2.defaults(newDefaults);
10264
- const newApi = (query, options) => {
10265
- return graphql(newRequest, query, options);
10266
- };
10267
- return Object.assign(newApi, {
10268
- defaults: withDefaults.bind(null, newRequest),
10269
- endpoint: newRequest.endpoint
10270
- });
10271
- }
10272
-
10273
- // pkg/dist-src/index.js
10274
- withDefaults(request, {
10275
- headers: {
10276
- "user-agent": `octokit-graphql.js/${VERSION$1} ${getUserAgent()}`
10277
- },
10278
- method: "POST",
10279
- url: "/graphql"
10280
- });
10281
- function withCustomRequest(customRequest) {
10282
- return withDefaults(customRequest, {
10283
- method: "POST",
10284
- url: "/graphql"
10285
- });
10286
- }
10287
-
10288
- // pkg/dist-src/is-jwt.js
10289
- var b64url = "(?:[a-zA-Z0-9_-]+)";
10290
- var sep = "\\.";
10291
- var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);
10292
- var isJWT = jwtRE.test.bind(jwtRE);
10293
-
10294
- // pkg/dist-src/auth.js
10295
- async function auth(token) {
10296
- const isApp = isJWT(token);
10297
- const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_");
10298
- const isUserToServer = token.startsWith("ghu_");
10299
- const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
10300
- return {
10301
- type: "token",
10302
- token,
10303
- tokenType
10304
- };
10305
- }
10306
-
10307
- // pkg/dist-src/with-authorization-prefix.js
10308
- function withAuthorizationPrefix(token) {
10309
- if (token.split(/\./).length === 3) {
10310
- return `bearer ${token}`;
10311
- }
10312
- return `token ${token}`;
10313
- }
10314
-
10315
- // pkg/dist-src/hook.js
10316
- async function hook(token, request, route, parameters) {
10317
- const endpoint = request.endpoint.merge(
10318
- route,
10319
- parameters
10320
- );
10321
- endpoint.headers.authorization = withAuthorizationPrefix(token);
10322
- return request(endpoint);
10323
- }
10324
-
10325
- // pkg/dist-src/index.js
10326
- var createTokenAuth = function createTokenAuth2(token) {
10327
- if (!token) {
10328
- throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
10329
- }
10330
- if (typeof token !== "string") {
10331
- throw new Error(
10332
- "[@octokit/auth-token] Token passed to createTokenAuth is not a string"
10333
- );
10334
- }
10335
- token = token.replace(/^(token|bearer) +/i, "");
10336
- return Object.assign(auth.bind(null, token), {
10337
- hook: hook.bind(null, token)
10338
- });
10339
- };
10340
-
10341
- const VERSION = "7.0.6";
10342
-
10343
- const noop = () => {
10344
- };
10345
- const consoleWarn = console.warn.bind(console);
10346
- const consoleError = console.error.bind(console);
10347
- function createLogger(logger = {}) {
10348
- if (typeof logger.debug !== "function") {
10349
- logger.debug = noop;
10350
- }
10351
- if (typeof logger.info !== "function") {
10352
- logger.info = noop;
10353
- }
10354
- if (typeof logger.warn !== "function") {
10355
- logger.warn = consoleWarn;
10356
- }
10357
- if (typeof logger.error !== "function") {
10358
- logger.error = consoleError;
10359
- }
10360
- return logger;
10361
- }
10362
- const userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;
10363
- class Octokit {
10364
- static VERSION = VERSION;
10365
- static defaults(defaults) {
10366
- const OctokitWithDefaults = class extends this {
10367
- constructor(...args) {
10368
- const options = args[0] || {};
10369
- if (typeof defaults === "function") {
10370
- super(defaults(options));
10371
- return;
10372
- }
10373
- super(
10374
- Object.assign(
10375
- {},
10376
- defaults,
10377
- options,
10378
- options.userAgent && defaults.userAgent ? {
10379
- userAgent: `${options.userAgent} ${defaults.userAgent}`
10380
- } : null
10381
- )
10382
- );
10383
- }
10384
- };
10385
- return OctokitWithDefaults;
10386
- }
10387
- static plugins = [];
10388
- /**
10389
- * Attach a plugin (or many) to your Octokit instance.
10390
- *
10391
- * @example
10392
- * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
10393
- */
10394
- static plugin(...newPlugins) {
10395
- const currentPlugins = this.plugins;
10396
- const NewOctokit = class extends this {
10397
- static plugins = currentPlugins.concat(
10398
- newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
10399
- );
10400
- };
10401
- return NewOctokit;
10402
- }
10403
- constructor(options = {}) {
10404
- const hook = new Hook.Collection();
10405
- const requestDefaults = {
10406
- baseUrl: request.endpoint.DEFAULTS.baseUrl,
10407
- headers: {},
10408
- request: Object.assign({}, options.request, {
10409
- // @ts-ignore internal usage only, no need to type
10410
- hook: hook.bind(null, "request")
10411
- }),
10412
- mediaType: {
10413
- previews: [],
10414
- format: ""
10415
- }
10416
- };
10417
- requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
10418
- if (options.baseUrl) {
10419
- requestDefaults.baseUrl = options.baseUrl;
10420
- }
10421
- if (options.previews) {
10422
- requestDefaults.mediaType.previews = options.previews;
10423
- }
10424
- if (options.timeZone) {
10425
- requestDefaults.headers["time-zone"] = options.timeZone;
10426
- }
10427
- this.request = request.defaults(requestDefaults);
10428
- this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
10429
- this.log = createLogger(options.log);
10430
- this.hook = hook;
10431
- if (!options.authStrategy) {
10432
- if (!options.auth) {
10433
- this.auth = async () => ({
10434
- type: "unauthenticated"
10435
- });
10436
- } else {
10437
- const auth = createTokenAuth(options.auth);
10438
- hook.wrap("request", auth.hook);
10439
- this.auth = auth;
10440
- }
10441
- } else {
10442
- const { authStrategy, ...otherOptions } = options;
10443
- const auth = authStrategy(
10444
- Object.assign(
10445
- {
10446
- request: this.request,
10447
- log: this.log,
10448
- // we pass the current octokit instance as well as its constructor options
10449
- // to allow for authentication strategies that return a new octokit instance
10450
- // that shares the same internal state as the current one. The original
10451
- // requirement for this was the "event-octokit" authentication strategy
10452
- // of https://github.com/probot/octokit-auth-probot.
10453
- octokit: this,
10454
- octokitOptions: otherOptions
10455
- },
10456
- options.auth
10457
- )
10458
- );
10459
- hook.wrap("request", auth.hook);
10460
- this.auth = auth;
10461
- }
10462
- const classConstructor = this.constructor;
10463
- for (let i = 0; i < classConstructor.plugins.length; ++i) {
10464
- Object.assign(this, classConstructor.plugins[i](this, options));
10465
- }
10466
- }
10467
- // assigned during constructor
10468
- request;
10469
- graphql;
10470
- log;
10471
- hook;
10472
- // TODO: type `octokit.auth` based on passed options.authStrategy
10473
- auth;
10474
- }
10475
-
10476
- const issueStatusCache = new Map();
10477
- const fetchIsIssueOpen = async (owner, repo, issueNumber) => {
10478
- const requestIssue = (auth) => new Octokit({ auth }).request("GET /repos/{owner}/{repo}/issues/{issue_number}", {
10479
- owner,
10480
- repo,
10481
- issue_number: issueNumber,
10482
- headers: { "X-GitHub-Api-Version": "2022-11-28" },
10483
- });
10484
- try {
10485
- const { data } = await requestIssue(await getGithubToken());
10486
- return data.state === "open";
10487
- }
10488
- catch (error) {
10489
- // 401 means the cached token was revoked — mint a fresh one and retry once.
10490
- if (error.status !== 401)
10491
- throw error;
10492
- const { data } = await requestIssue(await getGithubToken({ forceRefresh: true }));
10493
- return data.state === "open";
10494
- }
10495
- };
10496
- const isIssueOpen = (issueLink) => {
10497
- const [owner, repo, ...rest] = (issueLink.split(/[?#]/)[0].split("github.com/").at(-1) ?? "")
10498
- .split("/")
10499
- .filter(Boolean);
10500
- const issueNumber = Number(rest.at(-1));
10501
- if (!owner || !repo || !Number.isInteger(issueNumber))
10502
- failTest(`[isGithubIssueOpen] Invalid GitHub issue link: ${issueLink}`);
10503
- const cacheKey = `${owner}/${repo}#${issueNumber}`;
10504
- const cachedStatus = issueStatusCache.get(cacheKey);
10505
- if (cachedStatus)
10506
- return cachedStatus;
10507
- const status = fetchIsIssueOpen(owner, repo, issueNumber);
10508
- issueStatusCache.set(cacheKey, status);
10509
- status.catch(() => issueStatusCache.delete(cacheKey));
10510
- return status;
10511
- };
10512
- const isGithubIssueOpen = async (issueLinks) => {
10513
- const issueStatuses = await Promise.all(issueLinks.map(isIssueOpen));
10514
- return issueStatuses.some(Boolean);
10515
- };
10516
-
10517
- const simulateTypingWithDelay = async ({ field, value, delay = 500, }) => {
10518
- const minSliceLength = Math.max(3, Math.floor(value.length * 0.6));
10519
- const maxSliceLength = Math.max(4, Math.floor(value.length * 0.8));
10520
- const sliceLength = Math.floor(Math.random() * (maxSliceLength - minSliceLength + 1)) +
10521
- minSliceLength;
10522
- const maxBackspaceCount = Math.max(2, Math.min(4, Math.floor(sliceLength * 0.3)));
10523
- const backspaceCount = Math.floor(Math.random() * (maxBackspaceCount - 1)) + 2;
10524
- const textPart1 = value.slice(0, sliceLength);
10525
- const textPart2 = value.slice(sliceLength - backspaceCount);
10526
- await field.hover();
10527
- await field.click({ delay: Math.floor(Math.random() * delay) + 700 });
10528
- await field.pressSequentially(textPart1, {
10529
- delay: Math.floor(Math.random() * delay) + 400,
10530
- timeout: 30_000,
10531
- });
10532
- for (let i = 0; i < backspaceCount; i++) {
10533
- await field.press("Backspace", {
10534
- delay: Math.floor(Math.random() * 1000) + 300,
7633
+ const simulateTypingWithDelay = async ({ field, value, delay = 500, }) => {
7634
+ const minSliceLength = Math.max(3, Math.floor(value.length * 0.6));
7635
+ const maxSliceLength = Math.max(4, Math.floor(value.length * 0.8));
7636
+ const sliceLength = Math.floor(Math.random() * (maxSliceLength - minSliceLength + 1)) +
7637
+ minSliceLength;
7638
+ const maxBackspaceCount = Math.max(2, Math.min(4, Math.floor(sliceLength * 0.3)));
7639
+ const backspaceCount = Math.floor(Math.random() * (maxBackspaceCount - 1)) + 2;
7640
+ const textPart1 = value.slice(0, sliceLength);
7641
+ const textPart2 = value.slice(sliceLength - backspaceCount);
7642
+ await field.hover();
7643
+ await field.click({ delay: Math.floor(Math.random() * delay) + 700 });
7644
+ await field.pressSequentially(textPart1, {
7645
+ delay: Math.floor(Math.random() * delay) + 400,
7646
+ timeout: 30_000,
7647
+ });
7648
+ for (let i = 0; i < backspaceCount; i++) {
7649
+ await field.press("Backspace", {
7650
+ delay: Math.floor(Math.random() * 1000) + 300,
10535
7651
  });
10536
7652
  }
10537
7653
  await field.pressSequentially(textPart2, {
@@ -10701,6 +7817,18 @@ const httpCheck = async (url, timeout = 3000) => {
10701
7817
  }
10702
7818
  };
10703
7819
 
7820
+ // Let child projects select their own Yarn instead of inheriting the host's shim.
7821
+ const stripBerryBinFromEnv = () => {
7822
+ const { BERRY_BIN_FOLDER, ...env } = process.env;
7823
+ if (!BERRY_BIN_FOLDER || env.PATH === undefined)
7824
+ return env;
7825
+ return {
7826
+ ...env,
7827
+ PATH: env.PATH.split(path.delimiter)
7828
+ .filter(dir => dir !== BERRY_BIN_FOLDER)
7829
+ .join(path.delimiter),
7830
+ };
7831
+ };
10704
7832
  // The product's root is the nearest folder above the working directory that has the setup script.
10705
7833
  const findRepoRoot = () => {
10706
7834
  let dir = process.cwd();
@@ -10718,7 +7846,7 @@ const pollUntil = async ({ check, timeoutMs, intervalMs, }) => {
10718
7846
  while (Date.now() < deadline) {
10719
7847
  if (await check())
10720
7848
  return true;
10721
- await setTimeout$1(intervalMs);
7849
+ await setTimeout(intervalMs);
10722
7850
  }
10723
7851
  return false;
10724
7852
  };
@@ -10903,7 +8031,7 @@ class ProductServer {
10903
8031
  const databaseUrl = new URL(process.env.DATABASE_URL ?? "postgresql://127.0.0.1");
10904
8032
  databaseUrl.pathname = `/${database}`;
10905
8033
  return {
10906
- ...process.env,
8034
+ ...stripBerryBinFromEnv(),
10907
8035
  BUNDLE_PATH: undefined,
10908
8036
  BUNDLE_GEMFILE: undefined,
10909
8037
  BUNDLE_APP_CONFIG: undefined,
@@ -11100,15 +8228,6 @@ class ProductServer {
11100
8228
  }
11101
8229
 
11102
8230
  const { name, paths, webpackDevFile, setupScript, baseUrl, readyUrl, maxWaitMs, } = CHAT_WIDGET;
11103
- // A product on Yarn 4 puts its own yarn first on PATH for the scripts it runs, so it's dropped to let the widget use its own Yarn.
11104
- const widgetEnv = (extraEnv = {}) => {
11105
- const { BERRY_BIN_FOLDER, ...env } = process.env;
11106
- const PATH = (env.PATH ?? "")
11107
- .split(path.delimiter)
11108
- .filter(dir => !BERRY_BIN_FOLDER || dir !== BERRY_BIN_FOLDER)
11109
- .join(path.delimiter);
11110
- return { ...env, PATH, ...extraEnv };
11111
- };
11112
8231
  // Runs neeto-chat-widget's webpack dev server, as it isn't a Rails product; workers share it like ProductServer.
11113
8232
  class WidgetServer {
11114
8233
  log = (msg) => console.log(`[LocalServer:${name}] ${msg}`);
@@ -11154,7 +8273,7 @@ class WidgetServer {
11154
8273
  command: "bash",
11155
8274
  args: [setupScript, paths.DIR],
11156
8275
  logFile: paths.SETUP_LOG,
11157
- env: widgetEnv({ GITHUB_TOKEN: githubToken }),
8276
+ env: { ...stripBerryBinFromEnv(), GITHUB_TOKEN: githubToken },
11158
8277
  });
11159
8278
  fs.writeFileSync(paths.PREPARED_MARKER, "");
11160
8279
  }
@@ -11173,7 +8292,7 @@ class WidgetServer {
11173
8292
  args: ["start"],
11174
8293
  logFile: paths.LOG,
11175
8294
  cwd: paths.DIR,
11176
- env: widgetEnv(),
8295
+ env: stripBerryBinFromEnv(),
11177
8296
  });
11178
8297
  fs.writeFileSync(paths.STATE_FILE, JSON.stringify({ pid }));
11179
8298
  this.log("Server ready.");
@@ -11376,13 +8495,6 @@ const parseSpecPatterns = () => {
11376
8495
  };
11377
8496
 
11378
8497
  // @ts-check
11379
- const envBasePath = "./e2e/config/.env";
11380
- const envLocalPath = `${envBasePath}.local`;
11381
- const reporterPackageName = "@bigbinary/neeto-playwright-reporter";
11382
- process.env.TEST_ENV = process.env.TEST_ENV ?? ENVIRONMENT.development;
11383
- const loadEnv = (path) => dotenv.config({ path, quiet: true });
11384
- loadEnv(`${envBasePath}.${process.env.TEST_ENV}`);
11385
- fs.existsSync(envLocalPath) && loadEnv(envLocalPath);
11386
8498
  const playdashStagingConfig = {
11387
8499
  apiKey: process.env.PLAYDASH_STAGING_API_KEY,
11388
8500
  ciBuildId: process.env.NEETO_CI_JOB_ID,
@@ -11404,6 +8516,7 @@ const playdashProductionHealthConfig = {
11404
8516
  ciBuildId: process.env.NEETO_CI_JOB_ID,
11405
8517
  tags: process.env.TAG,
11406
8518
  };
8519
+ const reporterPackageName = "@bigbinary/neeto-playwright-reporter";
11407
8520
  const railsPort = process.env.RAILS_SERVER_PORT;
11408
8521
  const vitePort = process.env.VITE_PORT;
11409
8522
  const isPlaywrightRun = process.env.PLAYWRIGHT_RUN === "true";
@@ -11684,4 +8797,4 @@ class InboundEmailApis {
11684
8797
  };
11685
8798
  }
11686
8799
 
11687
- 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, 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, failTest, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, getRailsT, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, railsTFixture, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, saveStorageState, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };
8800
+ 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, 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, failTest, fillTotpWhenReady, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getI18nInstance, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, getRailsT, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, railsTFixture, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, saveStorageState, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };