@bigbinary/neeto-playwright-commons 4.10.0 → 4.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.d.ts +24 -14
  2. package/index.js +1603 -50
  3. package/package.json +2 -1
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isPresent, keysToSnakeCase, hyphenate, humanize, noop as noop$2, isNotPresent, keysToCamelCase, findBy, dynamicArray, truncate, isNotEmpty, _findBy, isNotEqualDeep, randomPick } from '@bigbinary/neeto-cist';
1
+ import { isPresent, keysToSnakeCase, hyphenate, humanize, noop as noop$2, isNotPresent, keysToCamelCase, dynamicArray, findBy, truncate, isNotEmpty, _findBy, isNotEqualDeep, randomPick } from '@bigbinary/neeto-cist';
2
2
  import { faker } from '@faker-js/faker/locale/en';
3
3
  import * as fs from 'fs';
4
4
  import { readFileSync, writeFileSync, unlinkSync, mkdirSync, rmSync, existsSync, createWriteStream } from 'fs';
@@ -19,6 +19,7 @@ import { parse as parse$1 } from 'node-html-parser';
19
19
  import { Jimp } from 'jimp';
20
20
  import jsQRModule from 'jsqr';
21
21
  import { globSync } from 'node:fs';
22
+ import { createPrivateKey } from 'node:crypto';
22
23
  import customParseFormat from 'dayjs/plugin/customParseFormat.js';
23
24
  import timezone from 'dayjs/plugin/timezone.js';
24
25
  import utc from 'dayjs/plugin/utc.js';
@@ -712,7 +713,6 @@ class SlackApi {
712
713
  fetchMessages = (channelId, unixTimestamp) => this.apiRequest("history", { channel: channelId, oldest: unixTimestamp });
713
714
  createChannel = (channelName) => this.apiRequest("create", { name: channelName });
714
715
  addUser = (channelId, userId) => this.apiRequest("invite", { channel: channelId, users: userId });
715
- listChannels = () => this.apiRequest("list", { exclude_archived: 1, limit: 1000 });
716
716
  archiveChannel = (channelId) => this.apiRequest("archive", { channel: channelId });
717
717
  mockChannelDeleted = (channelId) => this.neetoPlaywrightUtilities.apiRequest({
718
718
  url: "/neeto_slack/api/v1/testing/webhooks",
@@ -1516,7 +1516,7 @@ const SLACK_SELECTORS = {
1516
1516
  loginEmail: dataQa("login_email"),
1517
1517
  loginPassword: dataQa("login_password"),
1518
1518
  signInButton: dataQa("signin_button"),
1519
- teamPicketButtonContent: dataQa("team-picker-button-content"),
1519
+ teamPicketButtonContent: dataQa("oauth-team-picker-button-content"),
1520
1520
  redirectOpenInBrowser: dataQa("ssb_redirect_open_in_browser"),
1521
1521
  workspaceActionsButton: dataQa("workspace_actions_button"),
1522
1522
  teamMenuTrigger: dataQa("team-menu-trigger"),
@@ -5038,10 +5038,10 @@ var Hook = { Collection };
5038
5038
  // pkg/dist-src/defaults.js
5039
5039
 
5040
5040
  // pkg/dist-src/version.js
5041
- var VERSION$3 = "0.0.0-development";
5041
+ var VERSION$7 = "0.0.0-development";
5042
5042
 
5043
5043
  // pkg/dist-src/defaults.js
5044
- var userAgent = `octokit-endpoint.js/${VERSION$3} ${getUserAgent()}`;
5044
+ var userAgent = `octokit-endpoint.js/${VERSION$7} ${getUserAgent()}`;
5045
5045
  var DEFAULTS = {
5046
5046
  method: "GET",
5047
5047
  baseUrl: "https://api.github.com",
@@ -5746,12 +5746,12 @@ class RequestError extends Error {
5746
5746
  // pkg/dist-src/index.js
5747
5747
 
5748
5748
  // pkg/dist-src/version.js
5749
- var VERSION$2 = "10.0.8";
5749
+ var VERSION$6 = "10.0.8";
5750
5750
 
5751
5751
  // pkg/dist-src/defaults.js
5752
5752
  var defaults_default = {
5753
5753
  headers: {
5754
- "user-agent": `octokit-request.js/${VERSION$2} ${getUserAgent()}`
5754
+ "user-agent": `octokit-request.js/${VERSION$6} ${getUserAgent()}`
5755
5755
  }
5756
5756
  };
5757
5757
 
@@ -5936,7 +5936,7 @@ var request = withDefaults$1(endpoint, defaults_default);
5936
5936
  // pkg/dist-src/index.js
5937
5937
 
5938
5938
  // pkg/dist-src/version.js
5939
- var VERSION$1 = "0.0.0-development";
5939
+ var VERSION$5 = "0.0.0-development";
5940
5940
 
5941
5941
  // pkg/dist-src/error.js
5942
5942
  function _buildMessageForResponseErrors(data) {
@@ -6038,7 +6038,7 @@ function withDefaults(request2, newDefaults) {
6038
6038
  // pkg/dist-src/index.js
6039
6039
  withDefaults(request, {
6040
6040
  headers: {
6041
- "user-agent": `octokit-graphql.js/${VERSION$1} ${getUserAgent()}`
6041
+ "user-agent": `octokit-graphql.js/${VERSION$5} ${getUserAgent()}`
6042
6042
  },
6043
6043
  method: "POST",
6044
6044
  url: "/graphql"
@@ -6057,7 +6057,7 @@ var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);
6057
6057
  var isJWT = jwtRE.test.bind(jwtRE);
6058
6058
 
6059
6059
  // pkg/dist-src/auth.js
6060
- async function auth(token) {
6060
+ async function auth$4(token) {
6061
6061
  const isApp = isJWT(token);
6062
6062
  const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_");
6063
6063
  const isUserToServer = token.startsWith("ghu_");
@@ -6078,7 +6078,7 @@ function withAuthorizationPrefix(token) {
6078
6078
  }
6079
6079
 
6080
6080
  // pkg/dist-src/hook.js
6081
- async function hook(token, request, route, parameters) {
6081
+ async function hook$4(token, request, route, parameters) {
6082
6082
  const endpoint = request.endpoint.merge(
6083
6083
  route,
6084
6084
  parameters
@@ -6098,12 +6098,12 @@ var createTokenAuth = function createTokenAuth2(token) {
6098
6098
  );
6099
6099
  }
6100
6100
  token = token.replace(/^(token|bearer) +/i, "");
6101
- return Object.assign(auth.bind(null, token), {
6102
- hook: hook.bind(null, token)
6101
+ return Object.assign(auth$4.bind(null, token), {
6102
+ hook: hook$4.bind(null, token)
6103
6103
  });
6104
6104
  };
6105
6105
 
6106
- const VERSION = "7.0.6";
6106
+ const VERSION$4 = "7.0.6";
6107
6107
 
6108
6108
  const noop = () => {
6109
6109
  };
@@ -6124,9 +6124,9 @@ function createLogger(logger = {}) {
6124
6124
  }
6125
6125
  return logger;
6126
6126
  }
6127
- const userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;
6127
+ const userAgentTrail = `octokit-core.js/${VERSION$4} ${getUserAgent()}`;
6128
6128
  class Octokit {
6129
- static VERSION = VERSION;
6129
+ static VERSION = VERSION$4;
6130
6130
  static defaults(defaults) {
6131
6131
  const OctokitWithDefaults = class extends this {
6132
6132
  constructor(...args) {
@@ -6238,17 +6238,1579 @@ class Octokit {
6238
6238
  auth;
6239
6239
  }
6240
6240
 
6241
+ // pkg/dist-src/version.js
6242
+ function requestToOAuthBaseUrl$1(request) {
6243
+ const endpointDefaults = request.endpoint.DEFAULTS;
6244
+ return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
6245
+ }
6246
+ async function oauthRequest$1(request, route, parameters) {
6247
+ const withOAuthParameters = {
6248
+ baseUrl: requestToOAuthBaseUrl$1(request),
6249
+ headers: {
6250
+ accept: "application/json"
6251
+ },
6252
+ ...parameters
6253
+ };
6254
+ const response = await request(route, withOAuthParameters);
6255
+ if ("error" in response.data) {
6256
+ const error = new RequestError(
6257
+ `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`,
6258
+ 400,
6259
+ {
6260
+ request: request.endpoint.merge(
6261
+ route,
6262
+ withOAuthParameters
6263
+ )
6264
+ }
6265
+ );
6266
+ error.response = response;
6267
+ throw error;
6268
+ }
6269
+ return response;
6270
+ }
6271
+ async function createDeviceCode(options) {
6272
+ const request$1 = options.request || request;
6273
+ const parameters = {
6274
+ client_id: options.clientId
6275
+ };
6276
+ if ("scopes" in options && Array.isArray(options.scopes)) {
6277
+ parameters.scope = options.scopes.join(" ");
6278
+ }
6279
+ return oauthRequest$1(request$1, "POST /login/device/code", parameters);
6280
+ }
6281
+ async function exchangeDeviceCode(options) {
6282
+ const request$1 = options.request || request;
6283
+ const response = await oauthRequest$1(
6284
+ request$1,
6285
+ "POST /login/oauth/access_token",
6286
+ {
6287
+ client_id: options.clientId,
6288
+ device_code: options.code,
6289
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
6290
+ }
6291
+ );
6292
+ const authentication = {
6293
+ clientType: options.clientType,
6294
+ clientId: options.clientId,
6295
+ token: response.data.access_token,
6296
+ scopes: response.data.scope.split(/\s+/).filter(Boolean)
6297
+ };
6298
+ if ("clientSecret" in options) {
6299
+ authentication.clientSecret = options.clientSecret;
6300
+ }
6301
+ if (options.clientType === "github-app") {
6302
+ if ("refresh_token" in response.data) {
6303
+ const apiTimeInMs = new Date(response.headers.date).getTime();
6304
+ authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp2(
6305
+ apiTimeInMs,
6306
+ response.data.expires_in
6307
+ ), authentication.refreshTokenExpiresAt = toTimestamp2(
6308
+ apiTimeInMs,
6309
+ response.data.refresh_token_expires_in
6310
+ );
6311
+ }
6312
+ delete authentication.scopes;
6313
+ }
6314
+ return { ...response, authentication };
6315
+ }
6316
+ function toTimestamp2(apiTimeInMs, expirationInSeconds) {
6317
+ return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
6318
+ }
6319
+
6320
+ // pkg/dist-src/index.js
6321
+ async function getOAuthAccessToken(state, options) {
6322
+ const cachedAuthentication = getCachedAuthentication(state, options.auth);
6323
+ if (cachedAuthentication) return cachedAuthentication;
6324
+ const { data: verification } = await createDeviceCode({
6325
+ clientType: state.clientType,
6326
+ clientId: state.clientId,
6327
+ request: options.request || state.request,
6328
+ // @ts-expect-error the extra code to make TS happy is not worth it
6329
+ scopes: options.auth.scopes || state.scopes
6330
+ });
6331
+ await state.onVerification(verification);
6332
+ const authentication = await waitForAccessToken(
6333
+ options.request || state.request,
6334
+ state.clientId,
6335
+ state.clientType,
6336
+ verification
6337
+ );
6338
+ state.authentication = authentication;
6339
+ return authentication;
6340
+ }
6341
+ function getCachedAuthentication(state, auth2) {
6342
+ if (auth2.refresh === true) return false;
6343
+ if (!state.authentication) return false;
6344
+ if (state.clientType === "github-app") {
6345
+ return state.authentication;
6346
+ }
6347
+ const authentication = state.authentication;
6348
+ const newScope = ("scopes" in auth2 && auth2.scopes || state.scopes).join(
6349
+ " "
6350
+ );
6351
+ const currentScope = authentication.scopes.join(" ");
6352
+ return newScope === currentScope ? authentication : false;
6353
+ }
6354
+ async function wait(seconds) {
6355
+ await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
6356
+ }
6357
+ async function waitForAccessToken(request, clientId, clientType, verification) {
6358
+ try {
6359
+ const options = {
6360
+ clientId,
6361
+ request,
6362
+ code: verification.device_code
6363
+ };
6364
+ const { authentication } = clientType === "oauth-app" ? await exchangeDeviceCode({
6365
+ ...options,
6366
+ clientType: "oauth-app"
6367
+ }) : await exchangeDeviceCode({
6368
+ ...options,
6369
+ clientType: "github-app"
6370
+ });
6371
+ return {
6372
+ type: "token",
6373
+ tokenType: "oauth",
6374
+ ...authentication
6375
+ };
6376
+ } catch (error) {
6377
+ if (!error.response) throw error;
6378
+ const errorType = error.response.data.error;
6379
+ if (errorType === "authorization_pending") {
6380
+ await wait(verification.interval);
6381
+ return waitForAccessToken(request, clientId, clientType, verification);
6382
+ }
6383
+ if (errorType === "slow_down") {
6384
+ await wait(verification.interval + 7);
6385
+ return waitForAccessToken(request, clientId, clientType, verification);
6386
+ }
6387
+ throw error;
6388
+ }
6389
+ }
6390
+
6391
+ // pkg/dist-src/auth.js
6392
+ async function auth$3(state, authOptions) {
6393
+ return getOAuthAccessToken(state, {
6394
+ auth: authOptions
6395
+ });
6396
+ }
6397
+
6398
+ // pkg/dist-src/hook.js
6399
+ async function hook$3(state, request, route, parameters) {
6400
+ let endpoint = request.endpoint.merge(
6401
+ route,
6402
+ parameters
6403
+ );
6404
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
6405
+ return request(endpoint);
6406
+ }
6407
+ const { token } = await getOAuthAccessToken(state, {
6408
+ request,
6409
+ auth: { type: "oauth" }
6410
+ });
6411
+ endpoint.headers.authorization = `token ${token}`;
6412
+ return request(endpoint);
6413
+ }
6414
+
6415
+ // pkg/dist-src/version.js
6416
+ var VERSION$3 = "0.0.0-development";
6417
+
6418
+ // pkg/dist-src/index.js
6419
+ function createOAuthDeviceAuth(options) {
6420
+ const requestWithDefaults = options.request || request.defaults({
6421
+ headers: {
6422
+ "user-agent": `octokit-auth-oauth-device.js/${VERSION$3} ${getUserAgent()}`
6423
+ }
6424
+ });
6425
+ const { request: request$1 = requestWithDefaults, ...otherOptions } = options;
6426
+ const state = options.clientType === "github-app" ? {
6427
+ ...otherOptions,
6428
+ clientType: "github-app",
6429
+ request: request$1
6430
+ } : {
6431
+ ...otherOptions,
6432
+ clientType: "oauth-app",
6433
+ request: request$1,
6434
+ scopes: options.scopes || []
6435
+ };
6436
+ if (!options.clientId) {
6437
+ throw new Error(
6438
+ '[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'
6439
+ );
6440
+ }
6441
+ if (!options.onVerification) {
6442
+ throw new Error(
6443
+ '[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'
6444
+ );
6445
+ }
6446
+ return Object.assign(auth$3.bind(null, state), {
6447
+ hook: hook$3.bind(null, state)
6448
+ });
6449
+ }
6450
+
6451
+ // pkg/dist-src/version.js
6452
+ function requestToOAuthBaseUrl(request) {
6453
+ const endpointDefaults = request.endpoint.DEFAULTS;
6454
+ return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
6455
+ }
6456
+ async function oauthRequest(request, route, parameters) {
6457
+ const withOAuthParameters = {
6458
+ baseUrl: requestToOAuthBaseUrl(request),
6459
+ headers: {
6460
+ accept: "application/json"
6461
+ },
6462
+ ...parameters
6463
+ };
6464
+ const response = await request(route, withOAuthParameters);
6465
+ if ("error" in response.data) {
6466
+ const error = new RequestError(
6467
+ `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`,
6468
+ 400,
6469
+ {
6470
+ request: request.endpoint.merge(
6471
+ route,
6472
+ withOAuthParameters
6473
+ )
6474
+ }
6475
+ );
6476
+ error.response = response;
6477
+ throw error;
6478
+ }
6479
+ return response;
6480
+ }
6481
+ async function exchangeWebFlowCode(options) {
6482
+ const request$1 = options.request || request;
6483
+ const response = await oauthRequest(
6484
+ request$1,
6485
+ "POST /login/oauth/access_token",
6486
+ {
6487
+ client_id: options.clientId,
6488
+ client_secret: options.clientSecret,
6489
+ code: options.code,
6490
+ redirect_uri: options.redirectUrl
6491
+ }
6492
+ );
6493
+ const authentication = {
6494
+ clientType: options.clientType,
6495
+ clientId: options.clientId,
6496
+ clientSecret: options.clientSecret,
6497
+ token: response.data.access_token,
6498
+ scopes: response.data.scope.split(/\s+/).filter(Boolean)
6499
+ };
6500
+ if (options.clientType === "github-app") {
6501
+ if ("refresh_token" in response.data) {
6502
+ const apiTimeInMs = new Date(response.headers.date).getTime();
6503
+ authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(
6504
+ apiTimeInMs,
6505
+ response.data.expires_in
6506
+ ), authentication.refreshTokenExpiresAt = toTimestamp(
6507
+ apiTimeInMs,
6508
+ response.data.refresh_token_expires_in
6509
+ );
6510
+ }
6511
+ delete authentication.scopes;
6512
+ }
6513
+ return { ...response, authentication };
6514
+ }
6515
+ function toTimestamp(apiTimeInMs, expirationInSeconds) {
6516
+ return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
6517
+ }
6518
+ async function checkToken(options) {
6519
+ const request$1 = options.request || request;
6520
+ const response = await request$1("POST /applications/{client_id}/token", {
6521
+ headers: {
6522
+ authorization: `basic ${btoa(
6523
+ `${options.clientId}:${options.clientSecret}`
6524
+ )}`
6525
+ },
6526
+ client_id: options.clientId,
6527
+ access_token: options.token
6528
+ });
6529
+ const authentication = {
6530
+ clientType: options.clientType,
6531
+ clientId: options.clientId,
6532
+ clientSecret: options.clientSecret,
6533
+ token: options.token,
6534
+ scopes: response.data.scopes
6535
+ };
6536
+ if (response.data.expires_at)
6537
+ authentication.expiresAt = response.data.expires_at;
6538
+ if (options.clientType === "github-app") {
6539
+ delete authentication.scopes;
6540
+ }
6541
+ return { ...response, authentication };
6542
+ }
6543
+ async function refreshToken(options) {
6544
+ const request$1 = options.request || request;
6545
+ const response = await oauthRequest(
6546
+ request$1,
6547
+ "POST /login/oauth/access_token",
6548
+ {
6549
+ client_id: options.clientId,
6550
+ client_secret: options.clientSecret,
6551
+ grant_type: "refresh_token",
6552
+ refresh_token: options.refreshToken
6553
+ }
6554
+ );
6555
+ const apiTimeInMs = new Date(response.headers.date).getTime();
6556
+ const authentication = {
6557
+ clientType: "github-app",
6558
+ clientId: options.clientId,
6559
+ clientSecret: options.clientSecret,
6560
+ token: response.data.access_token,
6561
+ refreshToken: response.data.refresh_token,
6562
+ expiresAt: toTimestamp3(apiTimeInMs, response.data.expires_in),
6563
+ refreshTokenExpiresAt: toTimestamp3(
6564
+ apiTimeInMs,
6565
+ response.data.refresh_token_expires_in
6566
+ )
6567
+ };
6568
+ return { ...response, authentication };
6569
+ }
6570
+ function toTimestamp3(apiTimeInMs, expirationInSeconds) {
6571
+ return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString();
6572
+ }
6573
+ async function resetToken(options) {
6574
+ const request$1 = options.request || request;
6575
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
6576
+ const response = await request$1(
6577
+ "PATCH /applications/{client_id}/token",
6578
+ {
6579
+ headers: {
6580
+ authorization: `basic ${auth}`
6581
+ },
6582
+ client_id: options.clientId,
6583
+ access_token: options.token
6584
+ }
6585
+ );
6586
+ const authentication = {
6587
+ clientType: options.clientType,
6588
+ clientId: options.clientId,
6589
+ clientSecret: options.clientSecret,
6590
+ token: response.data.token,
6591
+ scopes: response.data.scopes
6592
+ };
6593
+ if (response.data.expires_at)
6594
+ authentication.expiresAt = response.data.expires_at;
6595
+ if (options.clientType === "github-app") {
6596
+ delete authentication.scopes;
6597
+ }
6598
+ return { ...response, authentication };
6599
+ }
6600
+ async function deleteToken(options) {
6601
+ const request$1 = options.request || request;
6602
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
6603
+ return request$1(
6604
+ "DELETE /applications/{client_id}/token",
6605
+ {
6606
+ headers: {
6607
+ authorization: `basic ${auth}`
6608
+ },
6609
+ client_id: options.clientId,
6610
+ access_token: options.token
6611
+ }
6612
+ );
6613
+ }
6614
+ async function deleteAuthorization(options) {
6615
+ const request$1 = options.request || request;
6616
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
6617
+ return request$1(
6618
+ "DELETE /applications/{client_id}/grant",
6619
+ {
6620
+ headers: {
6621
+ authorization: `basic ${auth}`
6622
+ },
6623
+ client_id: options.clientId,
6624
+ access_token: options.token
6625
+ }
6626
+ );
6627
+ }
6628
+
6629
+ // pkg/dist-src/index.js
6630
+
6631
+ // pkg/dist-src/version.js
6632
+ var VERSION$2 = "0.0.0-development";
6633
+ async function getAuthentication(state) {
6634
+ if ("code" in state.strategyOptions) {
6635
+ const { authentication } = await exchangeWebFlowCode({
6636
+ clientId: state.clientId,
6637
+ clientSecret: state.clientSecret,
6638
+ clientType: state.clientType,
6639
+ onTokenCreated: state.onTokenCreated,
6640
+ ...state.strategyOptions,
6641
+ request: state.request
6642
+ });
6643
+ return {
6644
+ type: "token",
6645
+ tokenType: "oauth",
6646
+ ...authentication
6647
+ };
6648
+ }
6649
+ if ("onVerification" in state.strategyOptions) {
6650
+ const deviceAuth = createOAuthDeviceAuth({
6651
+ clientType: state.clientType,
6652
+ clientId: state.clientId,
6653
+ onTokenCreated: state.onTokenCreated,
6654
+ ...state.strategyOptions,
6655
+ request: state.request
6656
+ });
6657
+ const authentication = await deviceAuth({
6658
+ type: "oauth"
6659
+ });
6660
+ return {
6661
+ clientSecret: state.clientSecret,
6662
+ ...authentication
6663
+ };
6664
+ }
6665
+ if ("token" in state.strategyOptions) {
6666
+ return {
6667
+ type: "token",
6668
+ tokenType: "oauth",
6669
+ clientId: state.clientId,
6670
+ clientSecret: state.clientSecret,
6671
+ clientType: state.clientType,
6672
+ onTokenCreated: state.onTokenCreated,
6673
+ ...state.strategyOptions
6674
+ };
6675
+ }
6676
+ throw new Error("[@octokit/auth-oauth-user] Invalid strategy options");
6677
+ }
6678
+ async function auth$2(state, options = {}) {
6679
+ if (!state.authentication) {
6680
+ state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state);
6681
+ }
6682
+ if (state.authentication.invalid) {
6683
+ throw new Error("[@octokit/auth-oauth-user] Token is invalid");
6684
+ }
6685
+ const currentAuthentication = state.authentication;
6686
+ if ("expiresAt" in currentAuthentication) {
6687
+ if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < /* @__PURE__ */ new Date()) {
6688
+ const { authentication } = await refreshToken({
6689
+ clientId: state.clientId,
6690
+ clientSecret: state.clientSecret,
6691
+ refreshToken: currentAuthentication.refreshToken,
6692
+ request: state.request
6693
+ });
6694
+ state.authentication = {
6695
+ tokenType: "oauth",
6696
+ type: "token",
6697
+ ...authentication
6698
+ };
6699
+ }
6700
+ }
6701
+ if (options.type === "refresh") {
6702
+ if (state.clientType === "oauth-app") {
6703
+ throw new Error(
6704
+ "[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"
6705
+ );
6706
+ }
6707
+ if (!currentAuthentication.hasOwnProperty("expiresAt")) {
6708
+ throw new Error("[@octokit/auth-oauth-user] Refresh token missing");
6709
+ }
6710
+ await state.onTokenCreated?.(state.authentication, {
6711
+ type: options.type
6712
+ });
6713
+ }
6714
+ if (options.type === "check" || options.type === "reset") {
6715
+ const method = options.type === "check" ? checkToken : resetToken;
6716
+ try {
6717
+ const { authentication } = await method({
6718
+ // @ts-expect-error making TS happy would require unnecessary code so no
6719
+ clientType: state.clientType,
6720
+ clientId: state.clientId,
6721
+ clientSecret: state.clientSecret,
6722
+ token: state.authentication.token,
6723
+ request: state.request
6724
+ });
6725
+ state.authentication = {
6726
+ tokenType: "oauth",
6727
+ type: "token",
6728
+ // @ts-expect-error TBD
6729
+ ...authentication
6730
+ };
6731
+ if (options.type === "reset") {
6732
+ await state.onTokenCreated?.(state.authentication, {
6733
+ type: options.type
6734
+ });
6735
+ }
6736
+ return state.authentication;
6737
+ } catch (error) {
6738
+ if (error.status === 404) {
6739
+ error.message = "[@octokit/auth-oauth-user] Token is invalid";
6740
+ state.authentication.invalid = true;
6741
+ }
6742
+ throw error;
6743
+ }
6744
+ }
6745
+ if (options.type === "delete" || options.type === "deleteAuthorization") {
6746
+ const method = options.type === "delete" ? deleteToken : deleteAuthorization;
6747
+ try {
6748
+ await method({
6749
+ // @ts-expect-error making TS happy would require unnecessary code so no
6750
+ clientType: state.clientType,
6751
+ clientId: state.clientId,
6752
+ clientSecret: state.clientSecret,
6753
+ token: state.authentication.token,
6754
+ request: state.request
6755
+ });
6756
+ } catch (error) {
6757
+ if (error.status !== 404) throw error;
6758
+ }
6759
+ state.authentication.invalid = true;
6760
+ return state.authentication;
6761
+ }
6762
+ return state.authentication;
6763
+ }
6764
+
6765
+ // pkg/dist-src/requires-basic-auth.js
6766
+ var ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/;
6767
+ function requiresBasicAuth(url) {
6768
+ return url && ROUTES_REQUIRING_BASIC_AUTH.test(url);
6769
+ }
6770
+
6771
+ // pkg/dist-src/hook.js
6772
+ async function hook$2(state, request, route, parameters = {}) {
6773
+ const endpoint = request.endpoint.merge(
6774
+ route,
6775
+ parameters
6776
+ );
6777
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
6778
+ return request(endpoint);
6779
+ }
6780
+ if (requiresBasicAuth(endpoint.url)) {
6781
+ const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
6782
+ endpoint.headers.authorization = `basic ${credentials}`;
6783
+ return request(endpoint);
6784
+ }
6785
+ const { token } = state.clientType === "oauth-app" ? await auth$2({ ...state, request }) : await auth$2({ ...state, request });
6786
+ endpoint.headers.authorization = "token " + token;
6787
+ return request(endpoint);
6788
+ }
6789
+
6790
+ // pkg/dist-src/index.js
6791
+ function createOAuthUserAuth({
6792
+ clientId,
6793
+ clientSecret,
6794
+ clientType = "oauth-app",
6795
+ request: request$1 = request.defaults({
6796
+ headers: {
6797
+ "user-agent": `octokit-auth-oauth-app.js/${VERSION$2} ${getUserAgent()}`
6798
+ }
6799
+ }),
6800
+ onTokenCreated,
6801
+ ...strategyOptions
6802
+ }) {
6803
+ const state = Object.assign({
6804
+ clientType,
6805
+ clientId,
6806
+ clientSecret,
6807
+ onTokenCreated,
6808
+ strategyOptions,
6809
+ request: request$1
6810
+ });
6811
+ return Object.assign(auth$2.bind(null, state), {
6812
+ // @ts-expect-error not worth the extra code needed to appease TS
6813
+ hook: hook$2.bind(null, state)
6814
+ });
6815
+ }
6816
+ createOAuthUserAuth.VERSION = VERSION$2;
6817
+
6818
+ // pkg/dist-src/index.js
6819
+ async function auth$1(state, authOptions) {
6820
+ if (authOptions.type === "oauth-app") {
6821
+ return {
6822
+ type: "oauth-app",
6823
+ clientId: state.clientId,
6824
+ clientSecret: state.clientSecret,
6825
+ clientType: state.clientType,
6826
+ headers: {
6827
+ authorization: `basic ${btoa(
6828
+ `${state.clientId}:${state.clientSecret}`
6829
+ )}`
6830
+ }
6831
+ };
6832
+ }
6833
+ if ("factory" in authOptions) {
6834
+ const { type, ...options } = {
6835
+ ...authOptions,
6836
+ ...state
6837
+ };
6838
+ return authOptions.factory(options);
6839
+ }
6840
+ const common = {
6841
+ clientId: state.clientId,
6842
+ clientSecret: state.clientSecret,
6843
+ request: state.request,
6844
+ ...authOptions
6845
+ };
6846
+ const userAuth = state.clientType === "oauth-app" ? await createOAuthUserAuth({
6847
+ ...common,
6848
+ clientType: state.clientType
6849
+ }) : await createOAuthUserAuth({
6850
+ ...common,
6851
+ clientType: state.clientType
6852
+ });
6853
+ return userAuth();
6854
+ }
6855
+ async function hook$1(state, request2, route, parameters) {
6856
+ let endpoint = request2.endpoint.merge(
6857
+ route,
6858
+ parameters
6859
+ );
6860
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
6861
+ return request2(endpoint);
6862
+ }
6863
+ if (state.clientType === "github-app" && !requiresBasicAuth(endpoint.url)) {
6864
+ throw new Error(
6865
+ `[@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.`
6866
+ );
6867
+ }
6868
+ const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
6869
+ endpoint.headers.authorization = `basic ${credentials}`;
6870
+ try {
6871
+ return await request2(endpoint);
6872
+ } catch (error) {
6873
+ if (error.status !== 401) throw error;
6874
+ error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`;
6875
+ throw error;
6876
+ }
6877
+ }
6878
+
6879
+ // pkg/dist-src/version.js
6880
+ var VERSION$1 = "0.0.0-development";
6881
+ function createOAuthAppAuth(options) {
6882
+ const state = Object.assign(
6883
+ {
6884
+ request: request.defaults({
6885
+ headers: {
6886
+ "user-agent": `octokit-auth-oauth-app.js/${VERSION$1} ${getUserAgent()}`
6887
+ }
6888
+ }),
6889
+ clientType: "oauth-app"
6890
+ },
6891
+ options
6892
+ );
6893
+ return Object.assign(auth$1.bind(null, state), {
6894
+ hook: hook$1.bind(null, state)
6895
+ });
6896
+ }
6897
+
6898
+ // we don't @ts-check here because it chokes on atob and btoa which are available in all modern JS runtime environments
6899
+
6900
+ /**
6901
+ * @param {string} privateKey
6902
+ * @returns {boolean}
6903
+ */
6904
+ function isPkcs1(privateKey) {
6905
+ return privateKey.includes("-----BEGIN RSA PRIVATE KEY-----");
6906
+ }
6907
+
6908
+ /**
6909
+ * @param {string} privateKey
6910
+ * @returns {boolean}
6911
+ */
6912
+ function isOpenSsh(privateKey) {
6913
+ return privateKey.includes("-----BEGIN OPENSSH PRIVATE KEY-----");
6914
+ }
6915
+
6916
+ /**
6917
+ * @param {string} str
6918
+ * @returns {ArrayBuffer}
6919
+ */
6920
+ function string2ArrayBuffer(str) {
6921
+ const buf = new ArrayBuffer(str.length);
6922
+ const bufView = new Uint8Array(buf);
6923
+ for (let i = 0, strLen = str.length; i < strLen; i++) {
6924
+ bufView[i] = str.charCodeAt(i);
6925
+ }
6926
+ return buf;
6927
+ }
6928
+
6929
+ /**
6930
+ * @param {string} pem
6931
+ * @returns {ArrayBuffer}
6932
+ */
6933
+ function getDERfromPEM(pem) {
6934
+ const pemB64 = pem
6935
+ .trim()
6936
+ .split("\n")
6937
+ .slice(1, -1) // Remove the --- BEGIN / END PRIVATE KEY ---
6938
+ .join("");
6939
+
6940
+ const decoded = atob(pemB64);
6941
+ return string2ArrayBuffer(decoded);
6942
+ }
6943
+
6944
+ /**
6945
+ * @param {import('../internals').Header} header
6946
+ * @param {import('../internals').Payload} payload
6947
+ * @returns {string}
6948
+ */
6949
+ function getEncodedMessage(header, payload) {
6950
+ return `${base64encodeJSON(header)}.${base64encodeJSON(payload)}`;
6951
+ }
6952
+
6953
+ /**
6954
+ * @param {ArrayBuffer} buffer
6955
+ * @returns {string}
6956
+ */
6957
+ function base64encode(buffer) {
6958
+ var binary = "";
6959
+ var bytes = new Uint8Array(buffer);
6960
+ var len = bytes.byteLength;
6961
+ for (var i = 0; i < len; i++) {
6962
+ binary += String.fromCharCode(bytes[i]);
6963
+ }
6964
+
6965
+ return fromBase64(btoa(binary));
6966
+ }
6967
+
6968
+ /**
6969
+ * @param {string} base64
6970
+ * @returns {string}
6971
+ */
6972
+ function fromBase64(base64) {
6973
+ return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
6974
+ }
6975
+
6976
+ /**
6977
+ * @param {Record<string,unknown>} obj
6978
+ * @returns {string}
6979
+ */
6980
+ function base64encodeJSON(obj) {
6981
+ return fromBase64(btoa(JSON.stringify(obj)));
6982
+ }
6983
+
6984
+ const { subtle } = globalThis.crypto;
6985
+
6986
+ // no-op, unfortunately there is no way to transform from PKCS8 or OpenSSH to PKCS1 with WebCrypto
6987
+ function convertPrivateKey(privateKey) {
6988
+ return privateKey;
6989
+ }
6990
+
6991
+ // we don't @ts-check here because it chokes crypto which is a global API in modern JS runtime environments
6992
+
6993
+
6994
+ /**
6995
+ * @param {import('../internals').GetTokenOptions} options
6996
+ * @returns {Promise<string>}
6997
+ */
6998
+ async function getToken({ privateKey, payload }) {
6999
+ const convertedPrivateKey = convertPrivateKey(privateKey);
7000
+
7001
+ // WebCrypto only supports PKCS#8, unfortunately
7002
+ /* c8 ignore start */
7003
+ if (isPkcs1(convertedPrivateKey)) {
7004
+ throw new Error(
7005
+ "[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"
7006
+ );
7007
+ }
7008
+ /* c8 ignore stop */
7009
+
7010
+ // WebCrypto does not support OpenSSH, unfortunately
7011
+ if (isOpenSsh(convertedPrivateKey)) {
7012
+ throw new Error(
7013
+ "[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"
7014
+ );
7015
+ }
7016
+
7017
+ const algorithm = {
7018
+ name: "RSASSA-PKCS1-v1_5",
7019
+ hash: { name: "SHA-256" },
7020
+ };
7021
+
7022
+ /** @type {import('../internals').Header} */
7023
+ const header = { alg: "RS256", typ: "JWT" };
7024
+
7025
+ const privateKeyDER = getDERfromPEM(convertedPrivateKey);
7026
+ const importedKey = await subtle.importKey(
7027
+ "pkcs8",
7028
+ privateKeyDER,
7029
+ algorithm,
7030
+ false,
7031
+ ["sign"]
7032
+ );
7033
+
7034
+ const encodedMessage = getEncodedMessage(header, payload);
7035
+ const encodedMessageArrBuf = string2ArrayBuffer(encodedMessage);
7036
+
7037
+ const signatureArrBuf = await subtle.sign(
7038
+ algorithm.name,
7039
+ importedKey,
7040
+ encodedMessageArrBuf
7041
+ );
7042
+
7043
+ const encodedSignature = base64encode(signatureArrBuf);
7044
+
7045
+ return `${encodedMessage}.${encodedSignature}`;
7046
+ }
7047
+
7048
+ // @ts-check
7049
+
7050
+
7051
+ /**
7052
+ * @param {import(".").Options} options
7053
+ * @returns {Promise<import(".").Result>}
7054
+ */
7055
+ async function githubAppJwt({
7056
+ id,
7057
+ privateKey,
7058
+ now = Math.floor(Date.now() / 1000),
7059
+ }) {
7060
+ // Private keys are often times configured as environment variables, in which case line breaks are escaped using `\\n`.
7061
+ // Replace these here for convenience.
7062
+ const privateKeyWithNewlines = privateKey.replace(/\\n/g, '\n');
7063
+
7064
+ // When creating a JSON Web Token, it sets the "issued at time" (iat) to 30s
7065
+ // in the past as we have seen people running situations where the GitHub API
7066
+ // claimed the iat would be in future. It turned out the clocks on the
7067
+ // different machine were not in sync.
7068
+ const nowWithSafetyMargin = now - 30;
7069
+ const expiration = nowWithSafetyMargin + 60 * 10; // JWT expiration time (10 minute maximum)
7070
+
7071
+ const payload = {
7072
+ iat: nowWithSafetyMargin, // Issued at time
7073
+ exp: expiration,
7074
+ iss: id,
7075
+ };
7076
+
7077
+ const token = await getToken({
7078
+ privateKey: privateKeyWithNewlines,
7079
+ payload,
7080
+ });
7081
+
7082
+ return {
7083
+ appId: id,
7084
+ expiration,
7085
+ token,
7086
+ };
7087
+ }
7088
+
7089
+ /**
7090
+ * toad-cache
7091
+ *
7092
+ * @copyright 2024 Igor Savin <kibertoad@gmail.com>
7093
+ * @license MIT
7094
+ * @version 3.7.0
7095
+ */
7096
+ class LruObject {
7097
+ constructor(max = 1000, ttlInMsecs = 0) {
7098
+ if (isNaN(max) || max < 0) {
7099
+ throw new Error('Invalid max value')
7100
+ }
7101
+
7102
+ if (isNaN(ttlInMsecs) || ttlInMsecs < 0) {
7103
+ throw new Error('Invalid ttl value')
7104
+ }
7105
+
7106
+ this.first = null;
7107
+ this.items = Object.create(null);
7108
+ this.last = null;
7109
+ this.size = 0;
7110
+ this.max = max;
7111
+ this.ttl = ttlInMsecs;
7112
+ }
7113
+
7114
+ bumpLru(item) {
7115
+ if (this.last === item) {
7116
+ return // Item is already the last one, no need to bump
7117
+ }
7118
+
7119
+ const last = this.last;
7120
+ const next = item.next;
7121
+ const prev = item.prev;
7122
+
7123
+ if (this.first === item) {
7124
+ this.first = next;
7125
+ }
7126
+
7127
+ item.next = null;
7128
+ item.prev = last;
7129
+ last.next = item;
7130
+
7131
+ if (prev !== null) {
7132
+ prev.next = next;
7133
+ }
7134
+
7135
+ if (next !== null) {
7136
+ next.prev = prev;
7137
+ }
7138
+
7139
+ this.last = item;
7140
+ }
7141
+
7142
+ clear() {
7143
+ this.items = Object.create(null);
7144
+ this.first = null;
7145
+ this.last = null;
7146
+ this.size = 0;
7147
+ }
7148
+
7149
+ delete(key) {
7150
+ if (Object.prototype.hasOwnProperty.call(this.items, key)) {
7151
+ const item = this.items[key];
7152
+
7153
+ delete this.items[key];
7154
+ this.size--;
7155
+
7156
+ if (item.prev !== null) {
7157
+ item.prev.next = item.next;
7158
+ }
7159
+
7160
+ if (item.next !== null) {
7161
+ item.next.prev = item.prev;
7162
+ }
7163
+
7164
+ if (this.first === item) {
7165
+ this.first = item.next;
7166
+ }
7167
+
7168
+ if (this.last === item) {
7169
+ this.last = item.prev;
7170
+ }
7171
+ }
7172
+ }
7173
+
7174
+ deleteMany(keys) {
7175
+ for (var i = 0; i < keys.length; i++) {
7176
+ this.delete(keys[i]);
7177
+ }
7178
+ }
7179
+
7180
+ evict() {
7181
+ if (this.size > 0) {
7182
+ const item = this.first;
7183
+
7184
+ delete this.items[item.key];
7185
+
7186
+ if (--this.size === 0) {
7187
+ this.first = null;
7188
+ this.last = null;
7189
+ } else {
7190
+ this.first = item.next;
7191
+ this.first.prev = null;
7192
+ }
7193
+ }
7194
+ }
7195
+
7196
+ expiresAt(key) {
7197
+ if (Object.prototype.hasOwnProperty.call(this.items, key)) {
7198
+ return this.items[key].expiry
7199
+ }
7200
+ }
7201
+
7202
+ get(key) {
7203
+ if (Object.prototype.hasOwnProperty.call(this.items, key)) {
7204
+ const item = this.items[key];
7205
+
7206
+ // Item has already expired
7207
+ if (this.ttl > 0 && item.expiry <= Date.now()) {
7208
+ this.delete(key);
7209
+ return
7210
+ }
7211
+
7212
+ // Item is still fresh
7213
+ this.bumpLru(item);
7214
+ return item.value
7215
+ }
7216
+ }
7217
+
7218
+ getMany(keys) {
7219
+ const result = [];
7220
+
7221
+ for (var i = 0; i < keys.length; i++) {
7222
+ result.push(this.get(keys[i]));
7223
+ }
7224
+
7225
+ return result
7226
+ }
7227
+
7228
+ keys() {
7229
+ return Object.keys(this.items)
7230
+ }
7231
+
7232
+ set(key, value) {
7233
+ // Replace existing item
7234
+ if (Object.prototype.hasOwnProperty.call(this.items, key)) {
7235
+ const item = this.items[key];
7236
+ item.value = value;
7237
+
7238
+ item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
7239
+
7240
+ if (this.last !== item) {
7241
+ this.bumpLru(item);
7242
+ }
7243
+
7244
+ return
7245
+ }
7246
+
7247
+ // Add new item
7248
+ if (this.max > 0 && this.size === this.max) {
7249
+ this.evict();
7250
+ }
7251
+
7252
+ const item = {
7253
+ expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
7254
+ key: key,
7255
+ prev: this.last,
7256
+ next: null,
7257
+ value,
7258
+ };
7259
+ this.items[key] = item;
7260
+
7261
+ if (++this.size === 1) {
7262
+ this.first = item;
7263
+ } else {
7264
+ this.last.next = item;
7265
+ }
7266
+
7267
+ this.last = item;
7268
+ }
7269
+ }
7270
+
7271
+ // pkg/dist-src/index.js
7272
+ async function getAppAuthentication({
7273
+ appId,
7274
+ privateKey,
7275
+ timeDifference,
7276
+ createJwt
7277
+ }) {
7278
+ try {
7279
+ if (createJwt) {
7280
+ const { jwt, expiresAt } = await createJwt(appId, timeDifference);
7281
+ return {
7282
+ type: "app",
7283
+ token: jwt,
7284
+ appId,
7285
+ expiresAt
7286
+ };
7287
+ }
7288
+ const authOptions = {
7289
+ id: appId,
7290
+ privateKey
7291
+ };
7292
+ if (timeDifference) {
7293
+ Object.assign(authOptions, {
7294
+ now: Math.floor(Date.now() / 1e3) + timeDifference
7295
+ });
7296
+ }
7297
+ const appAuthentication = await githubAppJwt(authOptions);
7298
+ return {
7299
+ type: "app",
7300
+ token: appAuthentication.token,
7301
+ appId: appAuthentication.appId,
7302
+ expiresAt: new Date(appAuthentication.expiration * 1e3).toISOString()
7303
+ };
7304
+ } catch (error) {
7305
+ if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") {
7306
+ throw new Error(
7307
+ "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'"
7308
+ );
7309
+ } else {
7310
+ throw error;
7311
+ }
7312
+ }
7313
+ }
7314
+ function getCache() {
7315
+ return new LruObject(
7316
+ // cache max. 15000 tokens, that will use less than 10mb memory
7317
+ 15e3,
7318
+ // Cache for 1 minute less than GitHub expiry
7319
+ 1e3 * 60 * 59
7320
+ );
7321
+ }
7322
+ async function get(cache, options) {
7323
+ const cacheKey = optionsToCacheKey(options);
7324
+ const result = await cache.get(cacheKey);
7325
+ if (!result) {
7326
+ return;
7327
+ }
7328
+ const [
7329
+ token,
7330
+ createdAt,
7331
+ expiresAt,
7332
+ repositorySelection,
7333
+ permissionsString,
7334
+ singleFileName
7335
+ ] = result.split("|");
7336
+ const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => {
7337
+ if (/!$/.test(string)) {
7338
+ permissions2[string.slice(0, -1)] = "write";
7339
+ } else {
7340
+ permissions2[string] = "read";
7341
+ }
7342
+ return permissions2;
7343
+ }, {});
7344
+ return {
7345
+ token,
7346
+ createdAt,
7347
+ expiresAt,
7348
+ permissions,
7349
+ repositoryIds: options.repositoryIds,
7350
+ repositoryNames: options.repositoryNames,
7351
+ singleFileName,
7352
+ repositorySelection
7353
+ };
7354
+ }
7355
+ async function set(cache, options, data) {
7356
+ const key = optionsToCacheKey(options);
7357
+ const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(
7358
+ (name) => `${name}${data.permissions[name] === "write" ? "!" : ""}`
7359
+ ).join(",");
7360
+ const value = [
7361
+ data.token,
7362
+ data.createdAt,
7363
+ data.expiresAt,
7364
+ data.repositorySelection,
7365
+ permissionsString,
7366
+ data.singleFileName
7367
+ ].join("|");
7368
+ await cache.set(key, value);
7369
+ }
7370
+ function optionsToCacheKey({
7371
+ installationId,
7372
+ permissions = {},
7373
+ repositoryIds = [],
7374
+ repositoryNames = []
7375
+ }) {
7376
+ const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(",");
7377
+ const repositoryIdsString = repositoryIds.sort().join(",");
7378
+ const repositoryNamesString = repositoryNames.join(",");
7379
+ return [
7380
+ installationId,
7381
+ repositoryIdsString,
7382
+ repositoryNamesString,
7383
+ permissionsString
7384
+ ].filter(Boolean).join("|");
7385
+ }
7386
+
7387
+ // pkg/dist-src/to-token-authentication.js
7388
+ function toTokenAuthentication({
7389
+ installationId,
7390
+ token,
7391
+ createdAt,
7392
+ expiresAt,
7393
+ repositorySelection,
7394
+ permissions,
7395
+ repositoryIds,
7396
+ repositoryNames,
7397
+ singleFileName
7398
+ }) {
7399
+ return Object.assign(
7400
+ {
7401
+ type: "token",
7402
+ tokenType: "installation",
7403
+ token,
7404
+ installationId,
7405
+ permissions,
7406
+ createdAt,
7407
+ expiresAt,
7408
+ repositorySelection
7409
+ },
7410
+ repositoryIds ? { repositoryIds } : null,
7411
+ repositoryNames ? { repositoryNames } : null,
7412
+ singleFileName ? { singleFileName } : null
7413
+ );
7414
+ }
7415
+
7416
+ // pkg/dist-src/get-installation-authentication.js
7417
+ async function getInstallationAuthentication(state, options, customRequest) {
7418
+ const installationId = Number(options.installationId || state.installationId);
7419
+ if (!installationId) {
7420
+ throw new Error(
7421
+ "[@octokit/auth-app] installationId option is required for installation authentication."
7422
+ );
7423
+ }
7424
+ if (options.factory) {
7425
+ const { type, factory, oauthApp, ...factoryAuthOptions } = {
7426
+ ...state,
7427
+ ...options
7428
+ };
7429
+ return factory(factoryAuthOptions);
7430
+ }
7431
+ const request = customRequest || state.request;
7432
+ return getInstallationAuthenticationConcurrently(
7433
+ state,
7434
+ { ...options, installationId },
7435
+ request
7436
+ );
7437
+ }
7438
+ var pendingPromises = /* @__PURE__ */ new Map();
7439
+ function getInstallationAuthenticationConcurrently(state, options, request) {
7440
+ const cacheKey = optionsToCacheKey(options);
7441
+ if (pendingPromises.has(cacheKey)) {
7442
+ return pendingPromises.get(cacheKey);
7443
+ }
7444
+ const promise = getInstallationAuthenticationImpl(
7445
+ state,
7446
+ options,
7447
+ request
7448
+ ).finally(() => pendingPromises.delete(cacheKey));
7449
+ pendingPromises.set(cacheKey, promise);
7450
+ return promise;
7451
+ }
7452
+ async function getInstallationAuthenticationImpl(state, options, request) {
7453
+ if (!options.refresh) {
7454
+ const result = await get(state.cache, options);
7455
+ if (result) {
7456
+ const {
7457
+ token: token2,
7458
+ createdAt: createdAt2,
7459
+ expiresAt: expiresAt2,
7460
+ permissions: permissions2,
7461
+ repositoryIds: repositoryIds2,
7462
+ repositoryNames: repositoryNames2,
7463
+ singleFileName: singleFileName2,
7464
+ repositorySelection: repositorySelection2
7465
+ } = result;
7466
+ return toTokenAuthentication({
7467
+ installationId: options.installationId,
7468
+ token: token2,
7469
+ createdAt: createdAt2,
7470
+ expiresAt: expiresAt2,
7471
+ permissions: permissions2,
7472
+ repositorySelection: repositorySelection2,
7473
+ repositoryIds: repositoryIds2,
7474
+ repositoryNames: repositoryNames2,
7475
+ singleFileName: singleFileName2
7476
+ });
7477
+ }
7478
+ }
7479
+ const appAuthentication = await getAppAuthentication(state);
7480
+ const payload = {
7481
+ installation_id: options.installationId,
7482
+ mediaType: {
7483
+ previews: ["machine-man"]
7484
+ },
7485
+ headers: {
7486
+ authorization: `bearer ${appAuthentication.token}`
7487
+ }
7488
+ };
7489
+ if (options.repositoryIds) {
7490
+ Object.assign(payload, { repository_ids: options.repositoryIds });
7491
+ }
7492
+ if (options.repositoryNames) {
7493
+ Object.assign(payload, {
7494
+ repositories: options.repositoryNames
7495
+ });
7496
+ }
7497
+ if (options.permissions) {
7498
+ Object.assign(payload, { permissions: options.permissions });
7499
+ }
7500
+ const {
7501
+ data: {
7502
+ token,
7503
+ expires_at: expiresAt,
7504
+ repositories,
7505
+ permissions: permissionsOptional,
7506
+ repository_selection: repositorySelectionOptional,
7507
+ single_file: singleFileName
7508
+ }
7509
+ } = await request(
7510
+ "POST /app/installations/{installation_id}/access_tokens",
7511
+ payload
7512
+ );
7513
+ const permissions = permissionsOptional || {};
7514
+ const repositorySelection = repositorySelectionOptional || "all";
7515
+ const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0;
7516
+ const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0;
7517
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
7518
+ const cacheOptions = {
7519
+ token,
7520
+ createdAt,
7521
+ expiresAt,
7522
+ repositorySelection,
7523
+ permissions};
7524
+ if (singleFileName) {
7525
+ Object.assign(payload, { singleFileName });
7526
+ }
7527
+ await set(state.cache, options, cacheOptions);
7528
+ const cacheData = {
7529
+ installationId: options.installationId,
7530
+ token,
7531
+ createdAt,
7532
+ expiresAt,
7533
+ repositorySelection,
7534
+ permissions,
7535
+ repositoryIds,
7536
+ repositoryNames
7537
+ };
7538
+ if (singleFileName) {
7539
+ Object.assign(cacheData, { singleFileName });
7540
+ }
7541
+ return toTokenAuthentication(cacheData);
7542
+ }
7543
+
7544
+ // pkg/dist-src/auth.js
7545
+ async function auth(state, authOptions) {
7546
+ switch (authOptions.type) {
7547
+ case "app":
7548
+ return getAppAuthentication(state);
7549
+ case "oauth-app":
7550
+ return state.oauthApp({ type: "oauth-app" });
7551
+ case "installation":
7552
+ return getInstallationAuthentication(state, {
7553
+ ...authOptions,
7554
+ type: "installation"
7555
+ });
7556
+ case "oauth-user":
7557
+ return state.oauthApp(authOptions);
7558
+ default:
7559
+ throw new Error(`Invalid auth type: ${authOptions.type}`);
7560
+ }
7561
+ }
7562
+
7563
+ // pkg/dist-src/requires-app-auth.js
7564
+ var PATHS = [
7565
+ "/app",
7566
+ "/app/hook/config",
7567
+ "/app/hook/deliveries",
7568
+ "/app/hook/deliveries/{delivery_id}",
7569
+ "/app/hook/deliveries/{delivery_id}/attempts",
7570
+ "/app/installations",
7571
+ "/app/installations/{installation_id}",
7572
+ "/app/installations/{installation_id}/access_tokens",
7573
+ "/app/installations/{installation_id}/suspended",
7574
+ "/app/installation-requests",
7575
+ "/marketplace_listing/accounts/{account_id}",
7576
+ "/marketplace_listing/plan",
7577
+ "/marketplace_listing/plans",
7578
+ "/marketplace_listing/plans/{plan_id}/accounts",
7579
+ "/marketplace_listing/stubbed/accounts/{account_id}",
7580
+ "/marketplace_listing/stubbed/plan",
7581
+ "/marketplace_listing/stubbed/plans",
7582
+ "/marketplace_listing/stubbed/plans/{plan_id}/accounts",
7583
+ "/orgs/{org}/installation",
7584
+ "/repos/{owner}/{repo}/installation",
7585
+ "/users/{username}/installation",
7586
+ "/enterprises/{enterprise}/installation"
7587
+ ];
7588
+ function routeMatcher(paths) {
7589
+ const regexes = paths.map(
7590
+ (p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/")
7591
+ );
7592
+ const regex = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})$`;
7593
+ return new RegExp(regex, "i");
7594
+ }
7595
+ var REGEX = routeMatcher(PATHS);
7596
+ function requiresAppAuth(url) {
7597
+ return !!url && REGEX.test(url.split("?")[0]);
7598
+ }
7599
+
7600
+ // pkg/dist-src/hook.js
7601
+ var FIVE_SECONDS_IN_MS = 5 * 1e3;
7602
+ function isNotTimeSkewError(error) {
7603
+ return !(error.message.match(
7604
+ /'Expiration time' claim \('exp'\) is too far in the future/
7605
+ ) || error.message.match(
7606
+ /'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/
7607
+ ) || error.message.match(
7608
+ /'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/
7609
+ ));
7610
+ }
7611
+ async function hook(state, request, route, parameters) {
7612
+ const endpoint = request.endpoint.merge(route, parameters);
7613
+ const url = endpoint.url;
7614
+ if (/\/login\/oauth\/access_token$/.test(url)) {
7615
+ return request(endpoint);
7616
+ }
7617
+ if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
7618
+ const { token: token2 } = await getAppAuthentication(state);
7619
+ endpoint.headers.authorization = `bearer ${token2}`;
7620
+ let response;
7621
+ try {
7622
+ response = await request(endpoint);
7623
+ } catch (error) {
7624
+ if (isNotTimeSkewError(error)) {
7625
+ throw error;
7626
+ }
7627
+ if (typeof error.response.headers.date === "undefined") {
7628
+ throw error;
7629
+ }
7630
+ const diff = Math.floor(
7631
+ (Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3
7632
+ );
7633
+ state.log.warn(error.message);
7634
+ state.log.warn(
7635
+ `[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`
7636
+ );
7637
+ const { token: token3 } = await getAppAuthentication({
7638
+ ...state,
7639
+ timeDifference: diff
7640
+ });
7641
+ endpoint.headers.authorization = `bearer ${token3}`;
7642
+ return request(endpoint);
7643
+ }
7644
+ return response;
7645
+ }
7646
+ if (requiresBasicAuth(url)) {
7647
+ const authentication = await state.oauthApp({ type: "oauth-app" });
7648
+ endpoint.headers.authorization = authentication.headers.authorization;
7649
+ return request(endpoint);
7650
+ }
7651
+ const { token, createdAt } = await getInstallationAuthentication(
7652
+ state,
7653
+ // @ts-expect-error TBD
7654
+ {},
7655
+ request.defaults({ baseUrl: endpoint.baseUrl })
7656
+ );
7657
+ endpoint.headers.authorization = `token ${token}`;
7658
+ return sendRequestWithRetries(
7659
+ state,
7660
+ request,
7661
+ endpoint,
7662
+ createdAt
7663
+ );
7664
+ }
7665
+ async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
7666
+ const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt);
7667
+ try {
7668
+ return await request(options);
7669
+ } catch (error) {
7670
+ if (error.status !== 401) {
7671
+ throw error;
7672
+ }
7673
+ if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
7674
+ if (retries > 0) {
7675
+ 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`;
7676
+ }
7677
+ throw error;
7678
+ }
7679
+ ++retries;
7680
+ const awaitTime = retries * 1e3;
7681
+ state.log.warn(
7682
+ `[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)`
7683
+ );
7684
+ await new Promise((resolve) => setTimeout(resolve, awaitTime));
7685
+ return sendRequestWithRetries(state, request, options, createdAt, retries);
7686
+ }
7687
+ }
7688
+
7689
+ // pkg/dist-src/version.js
7690
+ var VERSION = "8.2.0";
7691
+ function createAppAuth(options) {
7692
+ if (!options.appId) {
7693
+ throw new Error("[@octokit/auth-app] appId option is required");
7694
+ }
7695
+ if (!options.privateKey && !options.createJwt) {
7696
+ throw new Error("[@octokit/auth-app] privateKey option is required");
7697
+ } else if (options.privateKey && options.createJwt) {
7698
+ throw new Error(
7699
+ "[@octokit/auth-app] privateKey and createJwt options are mutually exclusive"
7700
+ );
7701
+ }
7702
+ if ("installationId" in options && !options.installationId) {
7703
+ throw new Error(
7704
+ "[@octokit/auth-app] installationId is set to a falsy value"
7705
+ );
7706
+ }
7707
+ const log = options.log || {};
7708
+ if (typeof log.warn !== "function") {
7709
+ log.warn = console.warn.bind(console);
7710
+ }
7711
+ const request$1 = options.request || request.defaults({
7712
+ headers: {
7713
+ "user-agent": `octokit-auth-app.js/${VERSION} ${getUserAgent()}`
7714
+ }
7715
+ });
7716
+ const state = Object.assign(
7717
+ {
7718
+ request: request$1,
7719
+ cache: getCache()
7720
+ },
7721
+ options,
7722
+ options.installationId ? { installationId: Number(options.installationId) } : {},
7723
+ {
7724
+ log,
7725
+ oauthApp: createOAuthAppAuth({
7726
+ clientType: "github-app",
7727
+ clientId: options.clientId || "",
7728
+ clientSecret: options.clientSecret || "",
7729
+ request: request$1
7730
+ })
7731
+ }
7732
+ );
7733
+ return Object.assign(auth.bind(null, state), {
7734
+ hook: hook.bind(null, state)
7735
+ });
7736
+ }
7737
+
7738
+ const PEM_PATTERN = /(-----BEGIN [A-Z ]+-----)([\s\S]*?)(-----END [A-Z ]+-----)/;
7739
+ const PEM_LINE_LENGTH = 64;
7740
+ const GITHUB_BOT_ENV_VARIABLES = [
7741
+ "GITHUB_BOT_APP_ID",
7742
+ "GITHUB_BOT_PRIVATE_KEY",
7743
+ "GITHUB_BOT_INSTALLATION_ID",
7744
+ ];
7745
+ let cachedAppAuth;
7746
+ // Secret stores hold the key with \n escapes, with spaces, or base64-encoded.
7747
+ const readPrivateKey = (rawKey) => {
7748
+ const unescaped = rawKey.replace(/\\n/g, "\n");
7749
+ const decoded = unescaped.includes("-----BEGIN")
7750
+ ? unescaped
7751
+ : Buffer.from(rawKey.replace(/\s/g, ""), "base64").toString("utf-8");
7752
+ const pem = decoded.match(PEM_PATTERN);
7753
+ if (!pem) {
7754
+ throw new Error("ENV variable GITHUB_BOT_PRIVATE_KEY is not a PEM key or a base64 encoded PEM key");
7755
+ }
7756
+ const [, begin, body, end] = pem;
7757
+ const lines = body.replace(/\s/g, "").match(new RegExp(`.{1,${PEM_LINE_LENGTH}}`, "g")) ??
7758
+ [];
7759
+ return [begin, ...lines, end, ""].join("\n");
7760
+ };
7761
+ // The auth client holds the token cache, so it must be reused across calls.
7762
+ const getAppAuth = () => {
7763
+ if (cachedAppAuth)
7764
+ return cachedAppAuth;
7765
+ const appId = process.env.GITHUB_BOT_APP_ID;
7766
+ const privateKey = process.env.GITHUB_BOT_PRIVATE_KEY;
7767
+ const installationId = process.env.GITHUB_BOT_INSTALLATION_ID;
7768
+ if (!appId || !privateKey || !installationId) {
7769
+ throw new Error("ENV variables GITHUB_BOT_APP_ID, GITHUB_BOT_PRIVATE_KEY and GITHUB_BOT_INSTALLATION_ID are not properly configured. Set all three, or set only GITHUB_TOKEN");
7770
+ }
7771
+ // createAppAuth needs a PKCS#8 key, and the bundled JWT signer does not convert the PKCS#1 key that GitHub issues.
7772
+ const privateKeyPkcs8 = createPrivateKey(readPrivateKey(privateKey)).export({
7773
+ type: "pkcs8",
7774
+ format: "pem",
7775
+ });
7776
+ cachedAppAuth = createAppAuth({
7777
+ appId: appId.trim(),
7778
+ privateKey: privateKeyPkcs8,
7779
+ installationId: installationId.trim(),
7780
+ });
7781
+ return cachedAppAuth;
7782
+ };
7783
+ const getGithubToken = async ({ forceRefresh = false, } = {}) => {
7784
+ const isGithubBotConfigured = GITHUB_BOT_ENV_VARIABLES.some(name => process.env[name]);
7785
+ const githubToken = process.env.GITHUB_TOKEN;
7786
+ if (!isGithubBotConfigured && githubToken)
7787
+ return githubToken;
7788
+ const { token } = await getAppAuth()({
7789
+ type: "installation",
7790
+ refresh: forceRefresh,
7791
+ });
7792
+ return token;
7793
+ };
7794
+
6241
7795
  const issueStatusCache = new Map();
6242
- let octokit;
6243
- const getOctokit = () => (octokit ??= new Octokit({ auth: process.env.GITHUB_TOKEN }));
6244
7796
  const fetchIsIssueOpen = async (owner, repo, issueNumber) => {
6245
- const { data } = await getOctokit().request("GET /repos/{owner}/{repo}/issues/{issue_number}", {
7797
+ const requestIssue = (auth) => new Octokit({ auth }).request("GET /repos/{owner}/{repo}/issues/{issue_number}", {
6246
7798
  owner,
6247
7799
  repo,
6248
7800
  issue_number: issueNumber,
6249
7801
  headers: { "X-GitHub-Api-Version": "2022-11-28" },
6250
7802
  });
6251
- return data.state === "open";
7803
+ try {
7804
+ const { data } = await requestIssue(await getGithubToken());
7805
+ return data.state === "open";
7806
+ }
7807
+ catch (error) {
7808
+ // 401 means the cached token was revoked — mint a fresh one and retry once.
7809
+ if (error.status !== 401)
7810
+ throw error;
7811
+ const { data } = await requestIssue(await getGithubToken({ forceRefresh: true }));
7812
+ return data.state === "open";
7813
+ }
6252
7814
  };
6253
7815
  const isIssueOpen = (issueLink) => {
6254
7816
  const [owner, repo, ...rest] = (issueLink.split(/[?#]/)[0].split("github.com/").at(-1) ?? "")
@@ -6405,27 +7967,25 @@ class HelpAndProfilePage {
6405
7967
  });
6406
7968
  };
6407
7969
  openAppSwitcherAndVerify = async () => {
6408
- const productName = "CRM";
7970
+ const productName = "Cal";
6409
7971
  const searchQueryPartial = productName.slice(0, 1).toLowerCase();
6410
7972
  const searchQueryFull = productName.toLowerCase();
6411
7973
  await test.step("1: Verify hovering over app switcher opens the app switcher drawer", () => expect(async () => {
6412
7974
  await this.openHelpCenter();
6413
7975
  await this.page.getByTestId(COMMON_SELECTORS.appSwitcherButton).hover();
6414
7976
  await expect(this.page.getByTestId(COMMON_SELECTORS.appSwitcherWrapper)).toBeVisible();
6415
- }).toPass({ timeout: 45_000 }));
7977
+ await this.neetoPlaywrightUtilities.waitForPageLoad();
7978
+ }).toPass({ timeout: 60_000 }));
6416
7979
  await test.step("2: Verify search functionality", async () => {
6417
- const crm = this.page.getByTestId(COMMON_SELECTORS.appLink(productName));
6418
- const course = this.page.getByTestId(COMMON_SELECTORS.appLink("Course"));
7980
+ const cal = this.page.getByTestId(COMMON_SELECTORS.appLink(productName));
7981
+ const chat = this.page.getByTestId(COMMON_SELECTORS.appLink("Chat"));
6419
7982
  const searchInput = this.page.getByTestId(COMMON_SELECTORS.productSwitcherSearchInput);
6420
7983
  await searchInput.fill(faker.word.words(3));
6421
7984
  await expect(this.page.getByTestId(COMMON_SELECTORS.noAppsFoundTitle)).toBeVisible();
6422
7985
  await searchInput.fill(searchQueryPartial);
6423
- await Promise.all([crm, course].map(app => expect(app).toBeVisible()));
7986
+ await Promise.all([cal, chat].map(app => expect(app).toBeVisible()));
6424
7987
  await searchInput.fill(searchQueryFull);
6425
- await Promise.all([
6426
- expect(crm).toBeVisible(),
6427
- expect(course).toBeHidden(),
6428
- ]);
7988
+ await Promise.all([expect(cal).toBeVisible(), expect(chat).toBeHidden()]);
6429
7989
  });
6430
7990
  };
6431
7991
  verifyLogout = async () => {
@@ -7168,12 +8728,6 @@ class SlackPage extends IntegrationBase {
7168
8728
  await nextButton.click();
7169
8729
  await this.slackWebappPageDataQa(SLACK_DATA_QA_SELECTORS.inviteToWorkspaceSkipButton).click();
7170
8730
  };
7171
- archiveChannelViaAPI = async (name) => {
7172
- const response = await this.slackApi.listChannels();
7173
- const { channels } = (await response?.json());
7174
- const channel = findBy({ name }, channels);
7175
- channel?.id && (await this.slackApi.archiveChannel(channel.id));
7176
- };
7177
8731
  }
7178
8732
 
7179
8733
  class WebhooksPage {
@@ -9775,11 +11329,11 @@ class TagsPage {
9775
11329
  }
9776
11330
 
9777
11331
  const USER_AGENTS = {
9778
- windows: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
9779
- mac: "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
9780
- iPhone: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/133.0.6943.120 Mobile/15E148 Safari/604.1",
9781
- iPad: "Mozilla/5.0 (iPad; CPU OS 18_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/121.0.6167.171 Mobile/15E148 Safari/604.1",
9782
- android: "Mozilla/5.0 (Linux; Android 15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.6943.137 Mobile Safari/537.36",
11332
+ windows: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36",
11333
+ mac: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36",
11334
+ iPhone: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/154.0.8037.55 Mobile/15E148 Safari/604.1",
11335
+ iPad: "Mozilla/5.0 (iPad; CPU OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/154.0.8037.55 Mobile/15E148 Safari/604.1",
11336
+ android: "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Mobile Safari/537.36",
9783
11337
  };
9784
11338
 
9785
11339
  const networkConditions = {
@@ -10717,9 +12271,7 @@ class NeetoAuthServer {
10717
12271
  log$1("Already set up, skipping.");
10718
12272
  return;
10719
12273
  }
10720
- if (!process.env.GITHUB_TOKEN) {
10721
- throw new Error("[NeetoAuth] GITHUB_TOKEN is not set. Cannot clone neeto-auth-web.");
10722
- }
12274
+ const githubToken = await getGithubToken();
10723
12275
  if (fs.existsSync(CONFIG$1.DIR)) {
10724
12276
  // We hold the setup lock and the port is free, so anything using this directory is an orphan.
10725
12277
  log$1("Found an incomplete previous setup — killing any lingering " +
@@ -10730,7 +12282,7 @@ class NeetoAuthServer {
10730
12282
  }
10731
12283
  log$1("Running first-time setup...");
10732
12284
  try {
10733
- await this.runSetupScript();
12285
+ await this.runSetupScript(githubToken);
10734
12286
  fs.writeFileSync(CONFIG$1.SETUP_COMPLETE_MARKER, "");
10735
12287
  }
10736
12288
  catch {
@@ -10739,11 +12291,11 @@ class NeetoAuthServer {
10739
12291
  log$1("Setup complete.");
10740
12292
  };
10741
12293
  // Async, not execSync: a blocked event loop stops proper-lockfile refreshing the lock.
10742
- runSetupScript = () => new Promise((resolve, reject) => {
12294
+ runSetupScript = (githubToken) => new Promise((resolve, reject) => {
10743
12295
  const setupScript = path.join(SCRIPTS_DIR$1, "setup.sh");
10744
12296
  const child = spawn("bash", [setupScript, CONFIG$1.DIR], {
10745
12297
  stdio: "inherit",
10746
- env: this.serverEnv,
12298
+ env: { ...this.serverEnv, GITHUB_TOKEN: githubToken },
10747
12299
  });
10748
12300
  child.on("error", reject);
10749
12301
  child.on("exit", code => code === 0
@@ -10934,7 +12486,7 @@ class NeetoChatWidget {
10934
12486
  getLogContent = () => existsSync(CONFIG.LOG)
10935
12487
  ? readFileSync(CONFIG.LOG, "utf-8")
10936
12488
  : "<no log file>";
10937
- ensureSetup = () => {
12489
+ ensureSetup = async () => {
10938
12490
  if (existsSync(CONFIG.WEBPACK_DEV_FILE)) {
10939
12491
  this.patchWebpackPublicPath();
10940
12492
  log("Already set up, skipping.");
@@ -10942,12 +12494,13 @@ class NeetoChatWidget {
10942
12494
  }
10943
12495
  existsSync(CONFIG.DIR) &&
10944
12496
  rmSync(CONFIG.DIR, { force: true, recursive: true });
12497
+ const githubToken = await getGithubToken();
10945
12498
  const setupScript = path.join(SCRIPTS_DIR, "setup.sh");
10946
12499
  log("Running first-time setup...");
10947
12500
  try {
10948
12501
  execSync(`bash "${setupScript}" "${CONFIG.DIR}"`, {
10949
12502
  stdio: "inherit",
10950
- env: this.serverEnv,
12503
+ env: { ...this.serverEnv, GITHUB_TOKEN: githubToken },
10951
12504
  });
10952
12505
  }
10953
12506
  catch {
@@ -11033,7 +12586,7 @@ class NeetoChatWidget {
11033
12586
  log("Server already running.");
11034
12587
  return;
11035
12588
  }
11036
- this.ensureSetup();
12589
+ await this.ensureSetup();
11037
12590
  log("Starting server...");
11038
12591
  this.logStream = createWriteStream(CONFIG.LOG);
11039
12592
  this.process = spawn("yarn", ["start"], {
@@ -11528,4 +13081,4 @@ class InboundEmailApis {
11528
13081
  };
11529
13082
  }
11530
13083
 
11531
- export { ACTIONS, ADMIN_PANEL_SELECTORS, ALL_RESOURCES, ANALYTICS_RESOURCES, API_KEYS_SELECTORS, API_ROUTES, APP_RESOURCES, AUDIT_LOGS_SELECTORS, ApiKeysApi, ApiKeysPage, ApiKeysPageV2, 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_SELECTORS, CUSTOM_DOMAIN_SUFFIX, ColorPickerUtils, CustomCommands, CustomCommandsV2, 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, HelpAndProfilePageV2, INTEGRATIONS_TEXTS, INTEGRATION_SELECTORS, IPRestrictionsPage, IP_RESTRICTIONS_SELECTORS, IS_CI, IS_DEV_CI, IS_DEV_ENV, IS_MAILPIT_ENABLED, IS_PLAYWRIGHT_RUN, IS_REVIEW_ENV, IS_SHADCN_UI, IS_STAGING_ENV, IS_WEBKIT, ImageUploader, InboundEmailApis, IntegrationBase, IpRestrictionsApi, KEYBOARD_SHORTCUTS_SELECTORS, KEYBOARD_SHORTCUT_TEST_CASES, LIST_MODIFIER_SELECTORS, LIST_MODIFIER_TAGS, LOGIN_DEFAULTS, LOGIN_SELECTORS, LOGIN_STRATEGIES, LOGIN_TIMEOUT, MAILPIT_BASE_URL, MAILPIT_DOMAIN_NAME, MEMBER_FORM_SELECTORS, MEMBER_SELECTORS, MEMBER_TEXTS, MERGE_TAGS_SELECTORS, MICROSOFT_LOGIN_SELECTORS, MICROSOFT_LOGIN_TEXTS, MailerUtils, MailpitApi, Member, MemberApis, MicrosoftPage, NEETO_AUTH_BASE_URL, NEETO_EDITOR_SELECTORS, NEETO_FILTERS_SELECTORS, NEETO_IMAGE_UPLOADER_SELECTORS, NEETO_ROUTES, NEETO_SEO_SELECTORS, NEETO_TEXT_MODIFIER_SELECTORS, NeetoAuthServer, NeetoChatWidget, NeetoEmailDeliveryApi, NeetoTowerApi, ONBOARDING_SELECTORS, ORGANIZATION_TEXTS, OTP_EMAIL_PATTERN, OTP_FETCH_TIMEOUT, OrganizationPage, PAST_TIME_RANGES, PHONE_NUMBER_FORMATS, PLURAL, PRODUCT_ROLES_ROUTE_MAP, PROFILE_LINKS, PROFILE_SECTION_SELECTORS, PROJECT_NAMES, PROJECT_TRANSLATIONS_PATH, ROLES_SELECTORS, ROUTES, RailsEmailApiClient, RailsEmailUtils, RoleApis, RolesPage, RolesPageV2, 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, TAGS_SELECTORS, TEAM_MEMBER_TEXTS, 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, TWILIO_SELECTORS, TagsApi, TagsPage, TeamMembers, TeamMembersV2, ThankYouApi, ThankYouPage, TwilioApi, USER_AGENTS, WEBHOOK_SELECTORS, WebhookSiteApi, WebhooksPage, ZAPIER_LIMIT_EXHAUSTED_MESSAGE, ZAPIER_SELECTORS, ZAPIER_TEST_EMAIL, ZAPIER_TEST_EMAIL_V2, ZAPIER_WEB_TEXTS, ZapierPage, authenticateUser, baseURLGenerator, basicHTMLContent, clearCredentials, commands, cpuThrottlingUsingCDP, createOrganizationViaApi, createOrganizationViaRake, currencyUtils, dataQa, decodeQRCodeFromFile, definePlaywrightConfig, exampleEmail, executeWithThrottledResources, extractSubdomainFromError, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getDirname, getFormattedPhoneNumber, getFullUrl, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, reviewAppBaseURL, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };
13084
+ export { ACTIONS, ADMIN_PANEL_SELECTORS, ALL_RESOURCES, ANALYTICS_RESOURCES, API_KEYS_SELECTORS, API_ROUTES, APP_RESOURCES, AUDIT_LOGS_SELECTORS, ApiKeysApi, ApiKeysPage, ApiKeysPageV2, 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_SELECTORS, CUSTOM_DOMAIN_SUFFIX, ColorPickerUtils, CustomCommands, CustomCommandsV2, 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, HelpAndProfilePageV2, INTEGRATIONS_TEXTS, INTEGRATION_SELECTORS, IPRestrictionsPage, IP_RESTRICTIONS_SELECTORS, IS_CI, IS_DEV_CI, IS_DEV_ENV, IS_MAILPIT_ENABLED, IS_PLAYWRIGHT_RUN, IS_REVIEW_ENV, IS_SHADCN_UI, IS_STAGING_ENV, IS_WEBKIT, ImageUploader, InboundEmailApis, IntegrationBase, IpRestrictionsApi, KEYBOARD_SHORTCUTS_SELECTORS, KEYBOARD_SHORTCUT_TEST_CASES, LIST_MODIFIER_SELECTORS, LIST_MODIFIER_TAGS, LOGIN_DEFAULTS, LOGIN_SELECTORS, LOGIN_STRATEGIES, LOGIN_TIMEOUT, MAILPIT_BASE_URL, MAILPIT_DOMAIN_NAME, MEMBER_FORM_SELECTORS, MEMBER_SELECTORS, MEMBER_TEXTS, MERGE_TAGS_SELECTORS, MICROSOFT_LOGIN_SELECTORS, MICROSOFT_LOGIN_TEXTS, MailerUtils, MailpitApi, Member, MemberApis, MicrosoftPage, NEETO_AUTH_BASE_URL, NEETO_EDITOR_SELECTORS, NEETO_FILTERS_SELECTORS, NEETO_IMAGE_UPLOADER_SELECTORS, NEETO_ROUTES, NEETO_SEO_SELECTORS, NEETO_TEXT_MODIFIER_SELECTORS, NeetoAuthServer, NeetoChatWidget, NeetoEmailDeliveryApi, NeetoTowerApi, ONBOARDING_SELECTORS, ORGANIZATION_TEXTS, OTP_EMAIL_PATTERN, OTP_FETCH_TIMEOUT, OrganizationPage, PAST_TIME_RANGES, PHONE_NUMBER_FORMATS, PLURAL, PRODUCT_ROLES_ROUTE_MAP, PROFILE_LINKS, PROFILE_SECTION_SELECTORS, PROJECT_NAMES, PROJECT_TRANSLATIONS_PATH, ROLES_SELECTORS, ROUTES, RailsEmailApiClient, RailsEmailUtils, RoleApis, RolesPage, RolesPageV2, 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, TAGS_SELECTORS, TEAM_MEMBER_TEXTS, 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, TWILIO_SELECTORS, TagsApi, TagsPage, TeamMembers, TeamMembersV2, ThankYouApi, ThankYouPage, TwilioApi, USER_AGENTS, WEBHOOK_SELECTORS, WebhookSiteApi, WebhooksPage, ZAPIER_LIMIT_EXHAUSTED_MESSAGE, ZAPIER_SELECTORS, ZAPIER_TEST_EMAIL, ZAPIER_TEST_EMAIL_V2, ZAPIER_WEB_TEXTS, ZapierPage, authenticateUser, baseURLGenerator, basicHTMLContent, clearCredentials, commands, cpuThrottlingUsingCDP, createOrganizationViaApi, createOrganizationViaRake, currencyUtils, dataQa, decodeQRCodeFromFile, definePlaywrightConfig, exampleEmail, executeWithThrottledResources, extractSubdomainFromError, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getDirname, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, reviewAppBaseURL, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };