@bigbinary/neeto-playwright-commons 6.0.0 → 6.0.1-beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +1 -1
  2. package/index.d.ts +9 -3
  3. package/index.js +1854 -1829
  4. package/package.json +2 -2
package/index.js CHANGED
@@ -1,19 +1,19 @@
1
- import { isPresent, keysToSnakeCase, isNotPresent, hyphenate, humanize, noop as noop$2, keysToCamelCase, truncate, isNotEmpty, _findBy, randomPick, findBy } from '@bigbinary/neeto-cist';
2
- import { faker } from '@faker-js/faker/locale/en';
1
+ import { isPresent, isNotPresent, hyphenate, humanize, noop as noop$2, keysToSnakeCase, keysToCamelCase, truncate, isNotEmpty, _findBy, randomPick, findBy } from '@bigbinary/neeto-cist';
2
+ import { spawn, execSync } from 'child_process';
3
3
  import * as fs from 'fs';
4
4
  import { readFileSync, writeFileSync, unlinkSync } from 'fs';
5
+ import { faker } from '@faker-js/faker/locale/en';
6
+ import { expect, test, chromium, defineConfig, devices } from '@playwright/test';
7
+ import { isEmpty, pluck, curry, isNotNil, not, mergeDeepLeft } from 'ramda';
8
+ import dayjs from 'dayjs';
9
+ import { getI18nInstance, initI18n } from 'playwright-i18next-fixture';
5
10
  import { setTimeout as setTimeout$1 } from 'node:timers/promises';
11
+ import { Redis } from 'ioredis';
12
+ import { TOTP } from 'otpauth';
6
13
  import os from 'os';
7
14
  import * as path from 'path';
8
15
  import path__default from 'path';
9
- import { expect, test, chromium, defineConfig, devices } from '@playwright/test';
10
16
  import { stringify } from 'picoquery';
11
- import { getI18nInstance, initI18n } from 'playwright-i18next-fixture';
12
- import { isEmpty, curry, isNotNil, not, pluck, mergeDeepLeft } from 'ramda';
13
- import { spawn, execSync } from 'child_process';
14
- import dayjs from 'dayjs';
15
- import { Redis } from 'ioredis';
16
- import { TOTP } from 'otpauth';
17
17
  import { randomFillSync, createPrivateKey, randomBytes, createHmac } from 'node:crypto';
18
18
  import { simpleParser } from 'mailparser';
19
19
  import { parse as parse$1 } from 'node-html-parser';
@@ -369,381 +369,284 @@ const DATE_FORMATS = {
369
369
  calendarDate: "YYYY-MM-DD",
370
370
  };
371
371
 
372
- const EMPTY_SEARCH_RESULT = {
373
- messages: [],
374
- messagesCount: 0,
375
- };
376
- class MailpitApi {
377
- neetoPlaywrightUtilities;
378
- baseUrl;
379
- headers;
380
- constructor(neetoPlaywrightUtilities) {
381
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
382
- this.baseUrl = (process.env.MAILPIT_BASE_URL || MAILPIT_BASE_URL).replace(/\/+$/, "");
383
- const { MAILPIT_USERNAME, MAILPIT_PASSWORD } = process.env;
384
- this.headers =
385
- MAILPIT_USERNAME && MAILPIT_PASSWORD
386
- ? {
387
- Authorization: `Basic ${Buffer.from(`${MAILPIT_USERNAME}:${MAILPIT_PASSWORD}`).toString("base64")}`,
388
- }
389
- : {};
390
- }
391
- authorizeAndSetAccountId = async () => { };
392
- warnOnUnexpectedResponse = (endpoint, response) => {
393
- if (response.ok() || response.status() === 404)
394
- return;
395
- if (response.status() === 401) {
396
- console.warn(`Mailpit rejected the credentials for ${endpoint}. Set MAILPIT_USERNAME and MAILPIT_PASSWORD to the basic auth credentials of ${this.baseUrl}, otherwise every email lookup will time out.`);
397
- return;
398
- }
399
- console.warn(`Mailpit responded with ${response.status()} for ${endpoint}. Treating it as no result, so an email lookup may time out even though the email exists.`);
400
- };
401
- search = async ({ query, start = 0, limit = 50, tz = "UTC", }) => {
402
- const isSearch = Boolean(query);
403
- const endpoint = `/api/v1/${isSearch ? "search" : "messages"}`;
404
- const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, {
405
- params: isSearch
406
- ? { query: query, start, limit, tz }
407
- : { start, limit },
408
- headers: this.headers,
409
- failOnStatusCode: false,
410
- timeout: 15_000,
411
- });
412
- this.warnOnUnexpectedResponse(endpoint, response);
413
- if (!response.ok())
414
- return EMPTY_SEARCH_RESULT;
415
- const { messages, messages_count: messagesCount } = await response.json();
416
- return { messages: messages ?? [], messagesCount: messagesCount ?? 0 };
417
- };
418
- getMessage = async (id) => {
419
- const endpoint = `/api/v1/message/${id}`;
420
- const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, { headers: this.headers, failOnStatusCode: false, timeout: 15_000 });
421
- this.warnOnUnexpectedResponse(endpoint, response);
422
- return response.ok() ? await response.json() : null;
423
- };
424
- fetchRawMessage = async (id) => {
425
- const endpoint = `/api/v1/message/${id}/raw`;
426
- const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, { headers: this.headers, failOnStatusCode: false, timeout: 15_000 });
427
- this.warnOnUnexpectedResponse(endpoint, response);
428
- return response.ok() ? await response.body() : null;
429
- };
430
- deleteMessages = async (ids) => {
431
- if (!ids?.length)
432
- throw new Error("MailpitApi.deleteMessages requires a non-empty list of message IDs. Mailpit deletes every stored message when the list is empty, and the inbox is shared across neeto products.");
433
- await this.neetoPlaywrightUtilities.request.delete(`${this.baseUrl}/api/v1/messages`, {
434
- data: { IDs: ids },
435
- headers: this.headers,
436
- failOnStatusCode: false,
437
- timeout: 15_000,
438
- });
439
- };
440
- }
441
-
442
- class RailsEmailApiClient {
443
- port = process.env.RAILS_SERVER_PORT;
444
- subdomain = process.env.SUBDOMAIN ?? "spinkart";
445
- baseUrl = `http://${this.subdomain}.lvh.me:${this.port}`;
446
- emailsEndpoint = `${this.baseUrl}/api/v1/testing/emails`;
447
- constructor() { }
448
- convertRawEmail = (raw) => ({
449
- from: raw.from,
450
- to: raw.to,
451
- cc: raw.cc,
452
- bcc: raw.bcc,
453
- replyTo: raw.reply_to,
454
- subject: raw.subject,
455
- htmlBody: raw.html_body,
456
- textBody: raw.text_body,
457
- receivedAt: raw.received_at,
458
- ...(raw.message_id && { messageId: raw.message_id }),
459
- attachments: raw.attachments?.map(({ filename, mime_type, data }) => ({
460
- name: filename,
461
- type: mime_type,
462
- content: data,
463
- })),
464
- });
465
- buildQueryString = (params) => {
466
- if (!params)
467
- return "";
468
- const filtered = Object.fromEntries(Object.entries(keysToSnakeCase(params))
469
- .filter(([, v]) => v != null && v !== "")
470
- .map(([k, v]) => [k, String(v)]));
471
- const query = new URLSearchParams(filtered).toString();
472
- return query ? `?${query}` : "";
473
- };
474
- fetchJson = async (url, options) => {
475
- try {
476
- const res = await fetch(url, options);
477
- if (!res.ok)
478
- return null;
479
- return (await res.json());
480
- }
481
- catch (err) {
482
- console.error("API error:", err);
483
- return null;
484
- }
485
- };
486
- listEmails = async (searchParams) => {
487
- const query = this.buildQueryString(searchParams);
488
- const data = await this.fetchJson(`${this.emailsEndpoint}${query}`);
489
- return data?.map(this.convertRawEmail) ?? [];
490
- };
491
- getLatestEmail = async (searchParams) => {
492
- const emails = await this.listEmails(searchParams);
493
- return emails.reduce((latest, curr) => !latest || new Date(curr.receivedAt) > new Date(latest.receivedAt)
494
- ? curr
495
- : latest, null);
496
- };
497
- clearEmails = () => this.fetchJson(this.emailsEndpoint, {
498
- method: "DELETE",
499
- });
500
- clearStaleEmails = (receivedBefore) => this.fetchJson(`${this.emailsEndpoint}?received_before=${encodeURIComponent(receivedBefore)}`, { method: "DELETE" });
501
- }
502
-
503
- const SECURITY_BASE_URL = `/secure${BASE_URL}/configuration`;
504
- class SecurityApi {
505
- neetoPlaywrightUtilities;
506
- constructor(neetoPlaywrightUtilities) {
507
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
508
- }
509
- buildBody = (auth, value) => {
510
- switch (auth) {
511
- case "password":
512
- return {
513
- configuration: {
514
- auth: "basic",
515
- password: value || faker.internet.password(),
516
- },
517
- };
518
- case "invite":
519
- return { configuration: { auth: "invited" } };
520
- case "member":
521
- return { configuration: { auth: "session" } };
522
- case "email":
523
- return {
524
- configuration: {
525
- auth: "email",
526
- allowed_keywords: [value || faker.internet.domainName()],
527
- },
528
- };
529
- default:
530
- return { configuration: { auth: "no" } };
531
- }
372
+ const generateStagingData = (product = "invoice") => {
373
+ const jobCompletionIndex = process.env.JOB_COMPLETION_INDEX;
374
+ const dateTimeString = `${dayjs().format("DDMM-HHmm")}-${faker.string.alphanumeric({ length: 5, casing: "lower" })}`;
375
+ const timestamp = jobCompletionIndex
376
+ ? `${dateTimeString}-${jobCompletionIndex}`
377
+ : dateTimeString;
378
+ const firstName = IS_STAGING_ENV ? "André" : CREDENTIALS.firstName;
379
+ const lastName = IS_STAGING_ENV ? "O'Reilly" : CREDENTIALS.lastName;
380
+ const otpBypassKey = process.env.OTP_BYPASS_KEY;
381
+ const isGlobalSetup = !getGlobalUserState(); // For dev global setup staging data, we use the default subdomain `spinkart`.
382
+ const shouldKeepDefaultDataForDevEnv = isGlobalSetup && IS_DEV_ENV;
383
+ const stagingOrganization = shouldKeepDefaultDataForDevEnv
384
+ ? CREDENTIALS.subdomainName
385
+ : `cpt-${product}-${timestamp}`;
386
+ const email = shouldKeepDefaultDataForDevEnv
387
+ ? CREDENTIALS.email
388
+ : `cpt${otpBypassKey}+${product}+${timestamp}@bigbinary.com`;
389
+ return {
390
+ firstName,
391
+ lastName,
392
+ otp: 111111,
393
+ domain: IS_STAGING_ENV ? `neeto${product}.net` : `lvh.me`,
394
+ currentUserName: joinString(firstName, lastName),
395
+ businessName: stagingOrganization,
396
+ subdomainName: stagingOrganization,
397
+ email,
532
398
  };
533
- update = ({ ownerId, auth, value }) => this.neetoPlaywrightUtilities.apiRequest({
534
- body: this.buildBody(auth, value),
535
- url: SECURITY_BASE_URL,
536
- ...(ownerId && { params: keysToSnakeCase({ ownerId }) }),
537
- method: "put",
538
- });
539
- }
540
-
541
- const THANK_YOU_URL = "/neeto_thank_you/thank_you_configurations";
542
- class ThankYouApi {
543
- neetoPlaywrightUtilities;
544
- constructor(neetoPlaywrightUtilities) {
545
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
546
- }
547
- create = ({ entityId, title, }) => this.neetoPlaywrightUtilities.apiRequest({
548
- method: "post",
549
- body: { title, description: "" },
550
- url: THANK_YOU_URL,
551
- params: keysToSnakeCase({ entityId }),
552
- });
553
- fetch = ({ entityId }) => this.neetoPlaywrightUtilities.apiRequest({
554
- url: THANK_YOU_URL,
555
- params: keysToSnakeCase({ entityId }),
556
- });
557
- update = ({ thankYouPageId, entityId, }) => this.neetoPlaywrightUtilities.apiRequest({
558
- method: "put",
559
- url: `${THANK_YOU_URL}/${thankYouPageId}`,
560
- body: keysToSnakeCase({
561
- entityId,
562
- thankYouConfiguration: {
563
- id: thankYouPageId,
564
- kind: "redirect_to_url",
565
- passEventDetailsToRedirectUrl: false,
566
- redirectUrl: EXAMPLE_URL,
567
- },
568
- }),
569
- });
570
- }
571
-
572
- const formatEnvList = (names) => {
573
- const last = names[names.length - 1];
574
- const rest = names.slice(0, -1);
575
- if (rest.length === 0)
576
- return last;
577
- if (rest.length === 1)
578
- return `${rest[0]} and ${last}`;
579
- return `${rest.join(", ")}, and ${last}`;
580
399
  };
581
- const missingEnvMessage = (names) => {
582
- const noun = names.length === 1 ? "ENV variable" : "ENV variables";
583
- const verb = names.length === 1 ? "is" : "are";
584
- return `${noun} ${formatEnvList(names)} ${verb} not set`;
400
+ const DEFAULT_STAGING_ORGANIZATION_TTL_IN_DAYS = 3;
401
+ const getStagingOrganizationTtlInDays = () => {
402
+ const ttl = Number(process.env.STAGING_ORGANIZATION_TTL_IN_DAYS);
403
+ return Number.isFinite(ttl) && ttl > 0
404
+ ? ttl
405
+ : DEFAULT_STAGING_ORGANIZATION_TTL_IN_DAYS;
406
+ };
407
+ const isStagingOrganizationExpired = (subdomainName) => {
408
+ if (!subdomainName?.startsWith("cpt"))
409
+ return false;
410
+ const match = subdomainName.match(/-(\d{2})(\d{2})-(\d{2})(\d{2})-[a-z\d]{5}(?:-\d+)?$/);
411
+ if (!match)
412
+ return false;
413
+ const [, day, month, hour, minute] = match;
414
+ const now = dayjs();
415
+ // The subdomain timestamp does not include a year, so assume the current year.
416
+ // If that places the creation date in the future, it was created last year.
417
+ let createdAt = dayjs(`${now.year()}-${month}-${day}T${hour}:${minute}`);
418
+ if (!createdAt.isValid())
419
+ return false;
420
+ if (createdAt.isAfter(now))
421
+ createdAt = createdAt.subtract(1, "year");
422
+ return now.diff(createdAt, "day") >= getStagingOrganizationTtlInDays();
423
+ };
424
+
425
+ const formatEnvList = (names) => {
426
+ const last = names[names.length - 1];
427
+ const rest = names.slice(0, -1);
428
+ if (rest.length === 0)
429
+ return last;
430
+ if (rest.length === 1)
431
+ return `${rest[0]} and ${last}`;
432
+ return `${rest.join(", ")}, and ${last}`;
433
+ };
434
+ const missingEnvMessage = (names) => {
435
+ const noun = names.length === 1 ? "ENV variable" : "ENV variables";
436
+ const verb = names.length === 1 ? "is" : "are";
437
+ return `${noun} ${formatEnvList(names)} ${verb} not set`;
585
438
  };
586
439
  /**
587
- * Reads the named environment variables. Throws when any value is missing or
588
- * blank, listing only the names that failed. One name returns the string;
440
+ * Reads the named environment variables. Aborts the running test when any
441
+ * value is missing or blank, listing only the names that failed. Outside a
442
+ * test, throws an Error with that same message. One name returns the string;
589
443
  * several names return an object keyed by those names.
590
444
  */
591
445
  const requireEnv = (...names) => {
592
446
  const missing = names.filter(name => isNotPresent(process.env[name]));
593
447
  if (missing.length > 0)
594
- throw new Error(missingEnvMessage(missing));
448
+ failTest(missingEnvMessage(missing));
595
449
  if (names.length === 1)
596
450
  return process.env[names[0]];
597
451
  return Object.fromEntries(names.map(name => [name, process.env[name]]));
598
452
  };
599
453
 
600
- const NEETO_TOWER_BASE_URL = "https://ops.neetotower.com/";
601
- const DNS_RECORDS_BASE_URL = `${NEETO_TOWER_BASE_URL}api/v1/public/automation_tests/dns_records`;
602
- class NeetoTowerApi {
603
- neetoPlaywrightUtilities;
604
- apiKey;
605
- constructor(neetoPlaywrightUtilities) {
606
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
607
- this.apiKey = requireEnv("NEETO_TOWER_API_KEY");
608
- }
609
- apiRequest = ({ method, dnsDomainId = "", body, }) => this.neetoPlaywrightUtilities.apiRequest({
610
- url: `${DNS_RECORDS_BASE_URL}${dnsDomainId ? `/${dnsDomainId}` : ""}`,
611
- headers: { "X-API-KEY": this.apiKey },
612
- method,
613
- body,
614
- });
615
- createRecord = ({ hostname, value }) => this.apiRequest({
616
- method: "post",
617
- body: { name: hostname, type: "TXT", content: value },
618
- });
619
- getRecords = () => this.apiRequest({ method: "get" });
620
- deleteRecord = (dnsDomainId) => this.apiRequest({ method: "delete", dnsDomainId });
621
- }
622
-
623
- class SlackApi {
624
- neetoPlaywrightUtilities;
625
- botToken;
626
- constructor(neetoPlaywrightUtilities) {
627
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
628
- this.botToken = requireEnv("SLACK_BOT_TOKEN");
629
- }
630
- apiRequest = (endpoint, params) => this.neetoPlaywrightUtilities.apiRequest({
631
- url: `https://slack.com/api/conversations.${endpoint}`,
632
- headers: { Authorization: `Bearer ${this.botToken}` },
633
- params,
634
- });
635
- fetchMessages = (channelId, unixTimestamp) => this.apiRequest("history", { channel: channelId, oldest: unixTimestamp });
636
- createChannel = (channelName) => this.apiRequest("create", { name: channelName });
637
- addUser = (channelId, userId) => this.apiRequest("invite", { channel: channelId, users: userId });
638
- archiveChannel = (channelId) => this.apiRequest("archive", { channel: channelId });
639
- mockChannelDeleted = (channelId) => this.neetoPlaywrightUtilities.apiRequest({
640
- url: "/neeto_slack/api/v1/testing/webhooks",
641
- method: "post",
642
- data: keysToSnakeCase({
643
- eventType: "channel_deleted",
644
- notificationChannelId: channelId,
645
- }),
646
- });
647
- }
648
-
649
- class WebhookSiteApi {
650
- request;
651
- WEBHOOK_SITE_BASE_URL = "https://webhook.site/token";
652
- constructor(request) {
653
- this.request = request;
654
- }
655
- create = () => this.request.post(this.WEBHOOK_SITE_BASE_URL);
656
- fetch = (token) => this.request.get(`${this.WEBHOOK_SITE_BASE_URL}/${token}/request/latest`);
657
- configure = (tokenId, content = DEFAULT_WEBHOOKS_RESPONSE_TEXT) => this.request.put(`${THIRD_PARTY_ROUTES.webhooks.site}token/${tokenId}`, {
658
- data: keysToSnakeCase({ defaultContent: content }),
659
- });
660
- }
661
-
662
- class TwilioApi {
663
- neetoPlaywrightUtilities;
664
- authToken;
665
- sid;
666
- defaultPhoneSid;
667
- constructor(neetoPlaywrightUtilities) {
668
- this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
669
- const env = requireEnv("TWILIO_AUTH_TOKEN", "TWILIO_SID", "TWILIO_DEFAULT_PHONE_SID");
670
- this.authToken = env.TWILIO_AUTH_TOKEN;
671
- this.sid = env.TWILIO_SID;
672
- this.defaultPhoneSid = env.TWILIO_DEFAULT_PHONE_SID;
673
- }
674
- apiRequest = ({ endpoint, params, body, method = "get", }) => this.neetoPlaywrightUtilities.apiRequest({
675
- method,
676
- url: `/neeto_integrations/${endpoint}`,
677
- ...(params && { params }),
678
- ...(body && { body }),
679
- });
680
- fetch = ({ integrableId, integrableType }) => this.apiRequest({
681
- endpoint: "twilio/sms_configurations",
682
- ...(integrableId && {
683
- params: keysToSnakeCase({ integrableId, integrableType }),
684
- }),
685
- });
686
- disconnect = ({ integrableId, integrableType }) => this.apiRequest({
687
- method: "delete",
688
- endpoint: "disconnect",
689
- body: keysToSnakeCase({
690
- disconnect: { slug: "twilio" },
691
- ...(integrableId && { integrableId, integrableType }),
692
- }),
693
- });
694
- connect = ({ integrableId, integrableType }) => this.apiRequest({
695
- endpoint: "twilio/sms_configurations",
696
- method: "post",
697
- body: keysToSnakeCase({
698
- twilioAuthToken: this.authToken,
699
- twilioSid: this.sid,
700
- twilioPhoneNumberSid: this.defaultPhoneSid,
701
- ...(integrableId && { integrableId, integrableType }),
702
- }),
703
- });
704
- }
454
+ const generateRandomBypassEmail = () => `cpt${process.env.OTP_BYPASS_KEY}+${faker.number.int()}@bigbinary.com`;
455
+ const LOGIN_STRATEGIES = {
456
+ password: "password",
457
+ oliver: "oliver",
458
+ bypassOtp: "bypassOtp",
459
+ emailOtp: "emailOtp",
460
+ authenticatorApp: "authenticatorApp",
461
+ google: "google",
462
+ };
463
+ const LOGIN_TIMEOUT = 2 * 60 * 1000;
464
+ const OTP_FETCH_TIMEOUT = 4 * 60 * 1000;
465
+ const DEFAULTS_BY_ENV = {
466
+ [ENVIRONMENT.development]: {
467
+ via: LOGIN_STRATEGIES.password,
468
+ generateEmail: () => CREDENTIALS.email,
469
+ },
470
+ [ENVIRONMENT.staging]: {
471
+ via: LOGIN_STRATEGIES.bypassOtp,
472
+ generateEmail: generateRandomBypassEmail,
473
+ },
474
+ [ENVIRONMENT.review]: {
475
+ via: LOGIN_STRATEGIES.bypassOtp,
476
+ generateEmail: generateRandomBypassEmail,
477
+ },
478
+ };
479
+ const LOGIN_DEFAULTS = DEFAULTS_BY_ENV[process.env.TEST_ENV ?? ""] ??
480
+ DEFAULTS_BY_ENV[ENVIRONMENT.staging];
705
481
 
706
- const ADMIN_PANEL_SELECTORS = {
707
- settingsItemHeading: "settings-item-heading",
708
- settingsItemDescription: "settings-item-description",
709
- expiryDateInput: "expiry-date-input",
710
- goBackButton: "admin-panel-go-back-button",
482
+ const CHAT_WIDGET_TEXTS = {
483
+ newConversation: "Ask a question",
484
+ welcomeChatBubble: "Hi! I'm here to assist you with any questions you may have. What can I do for you?",
485
+ preChatQuestions: "Please fill in the form to start chatting.",
711
486
  };
712
- const CUSTOM_DOMAIN_SELECTORS = {
713
- addCustomDomainButton: "add-new-custom-domain-button",
714
- disabledAddCustomDomainButton: "add-custom-domain-button",
715
- customDomainItem: "custom-domain-item",
716
- customDomainInputField: "custom-domain-input-field",
717
- submitCustomDomainButton: "submit-custom-domain-button",
718
- customDomainValidateButton: "validate-domain-button",
719
- editCustomDomainButton: "edit-custom-domain-button",
720
- deleteCustomDomainButton: "delete-custom-domain-button",
721
- dropdownButton: "custom-domains-more-dropdown-button",
722
- activeTagContainer: "active-tag-container",
723
- nameInputError: "domain-name-input-error",
724
- strategyContinueButton: "custom-domain-strategy-continue-button",
725
- onlyAddRootRadio: "custom-domain-strategy-only-add-root-radio-input",
487
+ const INTEGRATIONS_TEXTS = {
488
+ connectHeader: (integration) => `Connect your ${integration} account`,
489
+ connectedHeader: (integration) => `${integration} is connected`,
726
490
  };
727
- const IP_RESTRICTIONS_SELECTORS = {
728
- enableIPRestrictionChk: "enable-ip-restriction-checkbox",
729
- saveChanges: "ip-restriction-save-changes",
730
- addIPRangeBtn: "add-allowed-ip-range-button",
731
- ipStartTextField: "ip-start-text-field",
732
- ipEndTextField: "ip-end-text-field",
733
- ipRangeDeleteBtn: "allowed-ip-range-delete-button",
734
- ipStartInpError: "ip-start-input-error",
735
- ipEndInpError: "ip-end-input-error",
736
- typeSelectError: "type-select-error",
737
- addressTypeSelect: "address-type-select-field",
738
- resetButton: "ip-restriction-reset-btn",
491
+ const SLACK_WEB_TEXTS = {
492
+ signOut: "Sign out",
493
+ allow: "Allow",
494
+ loadingThread: "Loading thread",
495
+ name: "Name",
496
+ deleteThisChannel: "Delete this channel",
497
+ permanentlyDeleteTheChannel: "Yes, permanently delete the channel",
498
+ deleteChannel: "Delete channel",
739
499
  };
740
- const AUDIT_LOGS_SELECTORS = {
741
- card: "audit-log-card",
742
- content: "audit-log-content",
743
- timestamp: "audit-log-timestamp",
744
- text: "audit-log-text",
500
+ const ZAPIER_WEB_TEXTS = {
501
+ editZap: "Edit Zap",
502
+ newSubmission: "New Submission",
503
+ sendOutboundEmail: "Send Outbound Email",
504
+ moreOptions: "More options",
505
+ reconnect: "Reconnect this authentication",
506
+ retestStep: "Retest step",
507
+ editThisZap: "Edit this Zap",
508
+ staging: "Staging",
509
+ create: "Create",
510
+ account: "Account",
511
+ email: "Email",
512
+ continue: "Continue",
513
+ statusLabel: "Status",
514
+ password: "Password",
515
+ editExistingDraft: "Edit existing draft",
516
+ signInTo: "Sign in to *",
517
+ reconnectBtn: "Reconnect",
518
+ testTrigger: "Test trigger",
519
+ editStep: "Edit step",
520
+ continueWithSelectedRecord: "Continue with selected record",
521
+ publish: "Publish",
522
+ delete: "Delete",
523
+ loading: "Loading",
524
+ subdomain: "Subdomain",
525
+ apiKey: "API key",
526
+ publishingZapHeading: "Preparing Zap to go live",
527
+ connectionListMenu: "Toggle connection list menu",
528
+ usageRegExp: "Usage resets in *",
529
+ trialEndsRegExp: "Trial ends on",
530
+ testCurrentlyInQueue: "Test currently in queue",
531
+ welcomeText: (zapierLoginEmail) => `Welcome back ${zapierLoginEmail}`,
532
+ connectStagingApp: (appName) => `Connect ${appName} Staging`,
533
+ zapierWorkflowTriggered: "Zapier Workflow Triggered",
534
+ startFreeWithEmail: "Start free with email",
535
+ appsByTitle: "Apps by title",
536
+ logIn: "Log in",
537
+ loginToYourAccount: "Log in to your account",
538
+ confirm: "Confirm",
539
+ deleteMessage: "Zapier API Keys are deleted successfully!",
745
540
  };
746
-
541
+ const TOASTR_MESSAGES = {
542
+ zapierApiKeyGenerated: "Zapier API key is generated successfully!",
543
+ };
544
+ const ZAPIER_LIMIT_EXHAUSTED_MESSAGE = "Zapier free task limit is exhausted. Test will be aborted";
545
+ const EMOJI_LABEL = "thumbs up";
546
+ const GOOGLE_CALENDAR_DATE_FORMAT = "YYYY/M/D";
547
+ const MICROSOFT_LOGIN_TEXTS = {
548
+ passwordInput: "Enter the password",
549
+ emailInput: "Enter your email",
550
+ enterCode: "Enter code",
551
+ verify: "Verify",
552
+ staySignedIn: "Stay signed in?",
553
+ signIn: "Sign in",
554
+ next: "Next",
555
+ enterPassword: "Enter password",
556
+ password: "Password",
557
+ permissionsRequested: "Permissions requested",
558
+ yes: "Yes",
559
+ remove: "Remove",
560
+ manageYourApplication: "Manage your application",
561
+ revokeConsent: "Revoke consent",
562
+ useVerificationCode: "Use a verification code",
563
+ successfullyRevokedConsent: "Successfully revoked consent",
564
+ };
565
+ const GOOGLE_LOGIN_TEXTS = {
566
+ googleAccount: "Google Account:",
567
+ connectYourGoogleAccount: "Connect your Google account",
568
+ signInWithGoogle: "Sign in with Google",
569
+ signInHeading: (appName) => new RegExp(`^(?:You['’]re signing back in to ${appName}\\.net|Sign in to ${appName}\\.net)$`, "i"),
570
+ stagingAppName: (appName) => `${appName} - Staging`,
571
+ continue: "Continue",
572
+ selectAll: "Select All",
573
+ appNotVerified: "Google hasn’t verified this app",
574
+ next: "Next",
575
+ showPassword: "Show password",
576
+ emailOrPhone: "Email or phone",
577
+ enterYourPassword: "Enter your password",
578
+ twoStepVerification: "2-Step Verification",
579
+ enterCode: "Enter code",
580
+ allow: "Allow",
581
+ signOut: "Sign out",
582
+ wrongCode: "Wrong code. Try again",
583
+ verificationCode: "verification code",
584
+ confirm: "Confirm",
585
+ cancel: "Cancel",
586
+ deleteConnections: "Delete all connections you",
587
+ noLongerConnected: "You’re no longer connected to",
588
+ backToSafety: "Back to safety",
589
+ neetoAutomation: "automation",
590
+ chooseAnAccount: "Choose an account",
591
+ };
592
+ const ENGAGE_TEXTS = { subscribe: "Subscribe" };
593
+ const COMMUNITY_TEXTS = { joinCommunity: "Join community" };
594
+ const STATUS_TEXTS = {
595
+ appName: (appName) => `Neeto${appName}`,
596
+ };
597
+ const COMMON_TEXTS = {
598
+ skipCleanup: "@SKIP_CLEANUP",
599
+ skipSetup: "@SKIP_SETUP",
600
+ };
601
+ const ORGANIZATION_TEXTS = {
602
+ subdomainAvailable: "Subdomain is available",
603
+ };
604
+ const THEMES_TEXTS = {
605
+ lightThemeClass: /neeto-ui-theme--light/,
606
+ darkThemeClass: /neeto-ui-theme--dark/,
607
+ };
608
+
609
+ const ADMIN_PANEL_SELECTORS = {
610
+ settingsItemHeading: "settings-item-heading",
611
+ settingsItemDescription: "settings-item-description",
612
+ expiryDateInput: "expiry-date-input",
613
+ goBackButton: "admin-panel-go-back-button",
614
+ };
615
+ const CUSTOM_DOMAIN_SELECTORS = {
616
+ addCustomDomainButton: "add-new-custom-domain-button",
617
+ disabledAddCustomDomainButton: "add-custom-domain-button",
618
+ customDomainItem: "custom-domain-item",
619
+ customDomainInputField: "custom-domain-input-field",
620
+ submitCustomDomainButton: "submit-custom-domain-button",
621
+ customDomainValidateButton: "validate-domain-button",
622
+ editCustomDomainButton: "edit-custom-domain-button",
623
+ deleteCustomDomainButton: "delete-custom-domain-button",
624
+ dropdownButton: "custom-domains-more-dropdown-button",
625
+ activeTagContainer: "active-tag-container",
626
+ nameInputError: "domain-name-input-error",
627
+ strategyContinueButton: "custom-domain-strategy-continue-button",
628
+ onlyAddRootRadio: "custom-domain-strategy-only-add-root-radio-input",
629
+ };
630
+ const IP_RESTRICTIONS_SELECTORS = {
631
+ enableIPRestrictionChk: "enable-ip-restriction-checkbox",
632
+ saveChanges: "ip-restriction-save-changes",
633
+ addIPRangeBtn: "add-allowed-ip-range-button",
634
+ ipStartTextField: "ip-start-text-field",
635
+ ipEndTextField: "ip-end-text-field",
636
+ ipRangeDeleteBtn: "allowed-ip-range-delete-button",
637
+ ipStartInpError: "ip-start-input-error",
638
+ ipEndInpError: "ip-end-input-error",
639
+ typeSelectError: "type-select-error",
640
+ addressTypeSelect: "address-type-select-field",
641
+ resetButton: "ip-restriction-reset-btn",
642
+ };
643
+ const AUDIT_LOGS_SELECTORS = {
644
+ card: "audit-log-card",
645
+ content: "audit-log-content",
646
+ timestamp: "audit-log-timestamp",
647
+ text: "audit-log-text",
648
+ };
649
+
747
650
  const COMMON_SELECTORS = {
748
651
  emailInputError: "email-input-error",
749
652
  nuiSelectInput: "nui-select-input",
@@ -960,211 +863,466 @@ const DATE_PICKER_SELECTORS = {
960
863
  selectedDateInCalendarClass: "ant-picker-cell-selected",
961
864
  };
962
865
 
963
- const generateStagingData = (product = "invoice") => {
964
- const jobCompletionIndex = process.env.JOB_COMPLETION_INDEX;
965
- const dateTimeString = `${dayjs().format("DDMM-HHmm")}-${faker.string.alphanumeric({ length: 5, casing: "lower" })}`;
966
- const timestamp = jobCompletionIndex
967
- ? `${dateTimeString}-${jobCompletionIndex}`
968
- : dateTimeString;
969
- const firstName = IS_STAGING_ENV ? "André" : CREDENTIALS.firstName;
970
- const lastName = IS_STAGING_ENV ? "O'Reilly" : CREDENTIALS.lastName;
971
- const otpBypassKey = process.env.OTP_BYPASS_KEY;
972
- const isGlobalSetup = !getGlobalUserState(); // For dev global setup staging data, we use the default subdomain `spinkart`.
973
- const shouldKeepDefaultDataForDevEnv = isGlobalSetup && IS_DEV_ENV;
974
- const stagingOrganization = shouldKeepDefaultDataForDevEnv
975
- ? CREDENTIALS.subdomainName
976
- : `cpt-${product}-${timestamp}`;
977
- const email = shouldKeepDefaultDataForDevEnv
978
- ? CREDENTIALS.email
979
- : `cpt${otpBypassKey}+${product}+${timestamp}@bigbinary.com`;
980
- return {
981
- firstName,
982
- lastName,
983
- otp: 111111,
984
- domain: IS_STAGING_ENV ? `neeto${product}.net` : `lvh.me`,
985
- currentUserName: joinString(firstName, lastName),
986
- businessName: stagingOrganization,
987
- subdomainName: stagingOrganization,
988
- email,
989
- };
866
+ const optionSelector = (option) => `neeto-editor-fixed-menu-${option}-option`;
867
+ const fixedMenuSelector = (selector) => `neeto-editor-fixed-menu-${selector}`;
868
+ const NEETO_EDITOR_SELECTORS = {
869
+ fontSize: optionSelector("font-size"),
870
+ fontSizeHeadingOptions: new RegExp(`^${optionSelector("font-size")}-h[1-5]$`),
871
+ boldOption: optionSelector("bold"),
872
+ italicOption: optionSelector("italic"),
873
+ underlineOption: optionSelector("underline"),
874
+ strikeOption: optionSelector("strike"),
875
+ codeBlockOption: optionSelector("code"),
876
+ highlightOption: optionSelector("highlight"),
877
+ textColorOption: optionSelector("text-color"),
878
+ emojiOption: optionSelector("emoji"),
879
+ emojiDropdownIcon: "emoji-dropdown-icon",
880
+ linkInput: fixedMenuSelector("link-option-input"),
881
+ linkSubmitButton: fixedMenuSelector("link-option-link-button"),
882
+ commandList: (index) => `neeto-editor-command-list-item-${index}`,
883
+ imageUploadUrlSubmitButton: "neeto-editor-media-upload-url-submit",
884
+ imageUploadUrlInputTextField: "neeto-editor-media-upload-url-input",
885
+ uploadInput: "neeto-editor-media-uploader-input",
886
+ editorMenuBarWrapper: fixedMenuSelector("wrapper"),
887
+ undoOption: optionSelector("undo"),
888
+ redoOption: optionSelector("redo"),
889
+ imageWrapper: "neeto-editor-image-wrapper",
890
+ contentField: "neeto-editor-content",
891
+ slashCommandsWrapper: "neeto-editor-slash-commands-wrapper",
892
+ addLinkButton: optionSelector("link"),
893
+ addLinkTextField: "neeto-editor-add-link-text-input",
894
+ addURLTextField: "neeto-editor-add-link-url-input",
895
+ submitLinkButton: "neeto-editor-add-link",
896
+ fixedMenuArrow: fixedMenuSelector("arrow"),
897
+ cannedResponseOption: optionSelector("canned-responses"),
898
+ cannedResponseSelectContainer: "select-a-canned-response-select-container",
899
+ fixedMenuWrapper: fixedMenuSelector("wrapper"),
900
+ moreMenuOption: optionSelector("more"),
901
+ linkOption: optionSelector("link"),
902
+ addLinkUrlInput: "neeto-editor-add-link-url-input",
903
+ addLinkDoneButton: "neeto-editor-add-link",
904
+ addLinkOpenInNewTabCheckbox: "neeto-editor-add-link-open-in-new-tab-switch",
905
+ linkPopoverEditButton: "neeto-editor-link-popover-edit",
906
+ editLinkSubmitButton: "neeto-editor-edit-link",
907
+ unlinkButton: "neeto-editor-link-popover-unlink",
908
+ editorAttachmentsButton: optionSelector("attachments"),
909
+ attachmentPreviewDeleteButton: "neeto-editor-preview-delete-button",
910
+ imageUploadOption: optionSelector("image-upload"),
911
+ imageUploadLinkInput: "neeto-editor-media-upload-url-input",
912
+ imageUploadButton: "neeto-editor-media-uploader-dnd",
913
+ imageUploadLinkSubmitButton: "neeto-editor-media-upload-url-submit",
914
+ applyButton: "apply-button",
915
+ videoEmbedOption: optionSelector("video-embed"),
916
+ videoEmbedInput: "neeto-editor-embed-input",
917
+ videoEmbedSubmit: "neeto-editor-embed-cancel",
918
+ videoWrapper: "neeto-editor-video-wrapper",
919
+ paragraphOption: fixedMenuSelector("font-size-option-body2"),
920
+ calloutOption: fixedMenuSelector("callout-option"),
921
+ attachmentPreview: "ne-attachments-wrapper",
922
+ attachmentActionsButton: "neeto-editor-attachment-actions",
923
+ imageUploadLinkButton: "neeto-editor-media-uploader-link-tab",
924
+ errorText: "neeto-editor-error-text",
925
+ content: "editor-content",
926
+ imageUploadDeleteButton: "neeto-editor-image-menu-Delete",
927
+ dynamicVariablesButton: "dynamic-variables-button",
928
+ emojiContainer: "neeto-editor-emoji-picker",
929
+ characterCount: "neeto-editor-character-count",
930
+ tableOption: optionSelector("table"),
931
+ tableCreateButton: "neeto-editor-fixed-menu-table-option-create-button",
932
+ videoUploadOption: optionSelector("video-upload"),
933
+ todoListOption: optionSelector("todoList"),
934
+ editorMenuWrapper: "neeto-editor-fixed-menu-wrapper",
935
+ dataEmojiType: (type) => `[data-emoji="${type}"]`,
936
+ //Use data-testid once https://github.com/neetozone/neeto-editor/issues/1651 is resolved
937
+ calloutContent: ".callout-content",
938
+ //Use data-testid once https://github.com/neetozone/neeto-editor/issues/1648 is resolved
939
+ calloutTypeOption: ".neeto-editor-callout-dropdown__type-option",
940
+ calloutTypeOptionV2: "callout-type-option",
941
+ editorMediaUploaderTab: "neeto-editor-media-uploader-local-tab",
942
+ dynamicVariableSelector: (variable) => `dynamic-variables-list-item-${joinHyphenCase(variable)}`,
943
+ dynamicVariableList: (variable) => `dynamic-variables-list-${hyphenate(variable)}`,
944
+ neetoEditorFixedMenuFontSize: "neeto-editor-fixed-menu-font-size-option",
945
+ highlightText: (textColorIndex) => `--neeto-editor-highlight-text-${textColorIndex}`,
946
+ highlightBg: (bgColorIndex) => `--neeto-editor-highlight-bg-${bgColorIndex}`,
947
+ neetoEditorHighlightTextColor: (textColorIndex) => `neeto-editor-highlight-text-color-dot-${textColorIndex}`,
948
+ neetoEditorHighlightBgColor: (bgColorIndex) => `neeto-editor-highlight-background-color-dot-${bgColorIndex}`,
949
+ highlightTextColorGrid: "neeto-editor-highlight-text-color-grid",
950
+ todoList: "[data-type='todoList']",
951
+ selectedText: ".selected-text",
952
+ commandListItem: (index) => `neeto-editor-command-list-item-${index}`,
953
+ itemBlockHeading: "neeto-editor-command-list-item-block-heading",
990
954
  };
991
- const DEFAULT_STAGING_ORGANIZATION_TTL_IN_DAYS = 3;
992
- const getStagingOrganizationTtlInDays = () => {
993
- const ttl = Number(process.env.STAGING_ORGANIZATION_TTL_IN_DAYS);
994
- return Number.isFinite(ttl) && ttl > 0
995
- ? ttl
996
- : DEFAULT_STAGING_ORGANIZATION_TTL_IN_DAYS;
955
+ const NEETO_TEXT_MODIFIER_SELECTORS = {
956
+ strike: optionSelector("strike"),
957
+ underline: optionSelector("underline"),
958
+ highlight: optionSelector("highlight"),
997
959
  };
998
- const isStagingOrganizationExpired = (subdomainName) => {
999
- if (!subdomainName?.startsWith("cpt"))
1000
- return false;
1001
- const match = subdomainName.match(/-(\d{2})(\d{2})-(\d{2})(\d{2})-[a-z\d]{5}(?:-\d+)?$/);
1002
- if (!match)
1003
- return false;
1004
- const [, day, month, hour, minute] = match;
1005
- const now = dayjs();
1006
- // The subdomain timestamp does not include a year, so assume the current year.
1007
- // If that places the creation date in the future, it was created last year.
1008
- let createdAt = dayjs(`${now.year()}-${month}-${day}T${hour}:${minute}`);
1009
- if (!createdAt.isValid())
1010
- return false;
1011
- if (createdAt.isAfter(now))
1012
- createdAt = createdAt.subtract(1, "year");
1013
- return now.diff(createdAt, "day") >= getStagingOrganizationTtlInDays();
960
+ const TEXT_MODIFIER_SELECTORS = {
961
+ bold: optionSelector("bold"),
962
+ italic: optionSelector("italic"),
963
+ code: optionSelector("code"),
964
+ blockquote: optionSelector("blockquote"),
965
+ codeBlock: optionSelector("codeBlock"),
1014
966
  };
1015
-
1016
- const generateRandomBypassEmail = () => `cpt${process.env.OTP_BYPASS_KEY}+${faker.number.int()}@bigbinary.com`;
1017
- const LOGIN_STRATEGIES = {
1018
- password: "password",
1019
- oliver: "oliver",
1020
- bypassOtp: "bypassOtp",
1021
- emailOtp: "emailOtp",
1022
- authenticatorApp: "authenticatorApp",
1023
- google: "google",
967
+ const LIST_MODIFIER_SELECTORS = {
968
+ bulletList: optionSelector("bulletList"),
969
+ orderedList: optionSelector("orderedList"),
1024
970
  };
1025
- const LOGIN_TIMEOUT = 2 * 60 * 1000;
1026
- const OTP_FETCH_TIMEOUT = 4 * 60 * 1000;
1027
- const DEFAULTS_BY_ENV = {
1028
- [ENVIRONMENT.development]: {
1029
- via: LOGIN_STRATEGIES.password,
1030
- generateEmail: () => CREDENTIALS.email,
1031
- },
1032
- [ENVIRONMENT.staging]: {
1033
- via: LOGIN_STRATEGIES.bypassOtp,
1034
- generateEmail: generateRandomBypassEmail,
1035
- },
1036
- [ENVIRONMENT.review]: {
1037
- via: LOGIN_STRATEGIES.bypassOtp,
1038
- generateEmail: generateRandomBypassEmail,
1039
- },
971
+ const FONT_SIZE_SELECTORS = {
972
+ h1: fixedMenuSelector("font-size-option-h1"),
973
+ h2: fixedMenuSelector("font-size-option-h2"),
974
+ h3: fixedMenuSelector("font-size-option-h3"),
975
+ h4: fixedMenuSelector("font-size-option-h4"),
976
+ h5: fixedMenuSelector("font-size-option-h5"),
1040
977
  };
1041
- const LOGIN_DEFAULTS = DEFAULTS_BY_ENV[process.env.TEST_ENV ?? ""] ??
1042
- DEFAULTS_BY_ENV[ENVIRONMENT.staging];
1043
978
 
1044
- const CHAT_WIDGET_TEXTS = {
1045
- newConversation: "Ask a question",
1046
- welcomeChatBubble: "Hi! I'm here to assist you with any questions you may have. What can I do for you?",
1047
- preChatQuestions: "Please fill in the form to start chatting.",
1048
- };
1049
- const INTEGRATIONS_TEXTS = {
1050
- connectHeader: (integration) => `Connect your ${integration} account`,
1051
- connectedHeader: (integration) => `${integration} is connected`,
979
+ const EMBED_SELECTORS = {
980
+ iframe: (appName) => `#${appName}-iframe`,
981
+ modal: (appName) => `#${appName}-modal`,
982
+ close: (appName) => `#close-${appName}`,
983
+ loader: (appName) => `#${appName}-loader`,
984
+ inlineHeightInput: "inline-height-input-field",
985
+ inlineWidthInput: "inline-width-input-field",
986
+ inlineElementIdInput: "inline-element-id-input-field",
987
+ codeBlock: "html-code-block",
988
+ previewTab: "preview-tab",
989
+ htmlTab: "html-tab",
990
+ buttonTextInput: "button-text-input-field",
991
+ buttonPositionSelectContainer: "button-position-select-field-select-container",
992
+ buttonPositionSelectMenu: "button-position-select-field-select-menu",
993
+ buttonColorLabel: "button-color-label",
994
+ buttonTextColorLabel: "button-text-color-label",
995
+ colorPickerTarget: "color-picker-target",
996
+ colorpickerEditableInput: "colorpicker-editable-input",
997
+ colorpickerEditableInputTextbox: "colorpicker-editable-input-textbox",
998
+ showIconCheckbox: "show-icon-checkbox",
999
+ elementIdInput: "element-id-input-field",
1000
+ previewElementPopupButton: "preview-element-popup-button",
1001
+ embedSelector: (type) => `embed-selector-card-${hyphenate(type)}`,
1002
+ backToEmbedSelectionButton: "back-to-embed-selection-button",
1052
1003
  };
1053
- const SLACK_WEB_TEXTS = {
1054
- signOut: "Sign out",
1055
- allow: "Allow",
1056
- loadingThread: "Loading thread",
1057
- name: "Name",
1058
- deleteThisChannel: "Delete this channel",
1059
- permanentlyDeleteTheChannel: "Yes, permanently delete the channel",
1060
- deleteChannel: "Delete channel",
1004
+
1005
+ const NEETO_FILTERS_SELECTORS = {
1006
+ emailSelectContainer: "email-select-container-wrapper",
1007
+ filterPaneHeading: "neeto-filters-pane-header",
1008
+ neetoFiltersEmailBlock: "neeto-filters-email-block",
1009
+ neetoFiltersRoleBlock: "neeto-filters-role-block",
1010
+ neetoFiltersBarClearButton: "neeto-filters-bar-clear-btn",
1011
+ neetoFiltersNameFilterField: "neeto-filters-name-filter",
1012
+ neetoFilterNameBlock: "neeto-filters-name-block",
1013
+ roleSelectContainer: "role-select-container-wrapper",
1014
+ filterButton: "neeto-filters-toggle-btn",
1015
+ filtersClearButton: "neeto-filters-clear-btn",
1016
+ filterDoneButton: "neeto-filters-done-btn",
1017
+ filteredMembersCount: "ntm-filtered-members-count",
1018
+ allMenubarBlock: "ntm-members-menubar-all-block",
1019
+ filtersEmailFilter: "neeto-filters-email-filter",
1020
+ paneModalCrossIcon: "neeto-filters-close-button",
1021
+ searchTermBlock: "neeto-filters-search-term-block",
1022
+ categoriesFilter: "neeto-filters-categories-filter",
1023
+ filtersSegmentName: "neeto-filters-segment-name",
1024
+ activeSelectContainer: "neeto-filters-status-filter",
1025
+ neetoFiltersFilter: (filterName) => `neeto-filters-${hyphenate(filterName)}-filter`,
1026
+ filtersTermBlock: (filterType = "search-term") => `neeto-filters-${hyphenate(filterType)}-block`,
1027
+ dateRange: (filterName) => `neeto-filters-${hyphenate(filterName)}-date-range`,
1028
+ segmentLabel: (label) => `neeto-filters-segment-block-${hyphenate(label)}`,
1061
1029
  };
1062
- const ZAPIER_WEB_TEXTS = {
1063
- editZap: "Edit Zap",
1064
- newSubmission: "New Submission",
1065
- sendOutboundEmail: "Send Outbound Email",
1066
- moreOptions: "More options",
1067
- reconnect: "Reconnect this authentication",
1068
- retestStep: "Retest step",
1069
- editThisZap: "Edit this Zap",
1070
- staging: "Staging",
1071
- create: "Create",
1072
- account: "Account",
1073
- email: "Email",
1074
- continue: "Continue",
1075
- statusLabel: "Status",
1076
- password: "Password",
1077
- editExistingDraft: "Edit existing draft",
1078
- signInTo: "Sign in to *",
1079
- reconnectBtn: "Reconnect",
1080
- testTrigger: "Test trigger",
1081
- editStep: "Edit step",
1082
- continueWithSelectedRecord: "Continue with selected record",
1083
- publish: "Publish",
1084
- delete: "Delete",
1085
- loading: "Loading",
1086
- subdomain: "Subdomain",
1087
- apiKey: "API key",
1088
- publishingZapHeading: "Preparing Zap to go live",
1089
- connectionListMenu: "Toggle connection list menu",
1090
- usageRegExp: "Usage resets in *",
1091
- trialEndsRegExp: "Trial ends on",
1092
- testCurrentlyInQueue: "Test currently in queue",
1093
- welcomeText: (zapierLoginEmail) => `Welcome back ${zapierLoginEmail}`,
1094
- connectStagingApp: (appName) => `Connect ${appName} Staging`,
1095
- zapierWorkflowTriggered: "Zapier Workflow Triggered",
1096
- startFreeWithEmail: "Start free with email",
1097
- appsByTitle: "Apps by title",
1098
- logIn: "Log in",
1099
- loginToYourAccount: "Log in to your account",
1100
- deleteMessage: "Zapier API Keys are deleted successfully!",
1030
+
1031
+ const HELP_CENTER_SELECTORS = {
1032
+ helpMenuBtn: "help-menu-button",
1033
+ helpButton: "help-button",
1034
+ documentationButton: "help-link-help-articles-button",
1035
+ keyboardShortcutButton: "help-link-keyboard-shortcut-button",
1036
+ chatButton: "help-link-live-chat-button",
1037
+ whatsNewButton: "help-link-engage-button",
1038
+ whatsNewWidgetInfo: "h1",
1039
+ whatsNewWidgetCloseButton: ".ne-widget-header__btn",
1040
+ keyboardShortcutPaneHeading: "keyboard-shortcuts-pane-title",
1041
+ keyboardShortcutPaneCrossIcon: "keyboard-shortcuts-pane-close-button",
1042
+ statusButton: "help-link-status-button",
1043
+ communityButton: "help-link-community-button",
1044
+ subscriptionPlan: "subscription-plan",
1101
1045
  };
1102
- const TOASTR_MESSAGES = {
1103
- zapierApiKeyGenerated: "Zapier API key is generated successfully!",
1046
+
1047
+ const NEETO_IMAGE_UPLOADER_SELECTORS = {
1048
+ libraryImageCard: "library-image-card",
1049
+ imageUploaderWrapper: "image-uploader-wrapper",
1050
+ browseText: "neeto-image-uploader-browse-text",
1051
+ fileInput: "neeto-image-uploader-file-input",
1052
+ uploadedImage: "uploaded-image",
1053
+ uploadNewAsset: "upload-new-asset",
1054
+ basicImageUploaderRemoveButton: "basic-image-uploader-remove-button",
1055
+ removeButton: "image-uploader-remove-button",
1056
+ openImageLibraryButton: "image-uploader-open-image-library-button",
1057
+ openAssetLibraryButton: "open-asset-library-button",
1058
+ imageEditorBackButton: "image-editor-back-button",
1059
+ aspectRatioWidthInput: "aspect-ratio-width-input",
1060
+ aspectRatioHeightInput: "aspect-ratio-height-input",
1061
+ cropSubmitButton: "neeto-image-uploader-crop-submit-button",
1062
+ restrictionMessage: "neeto-image-uploader-restriction-message",
1063
+ progressBar: "neeto-image-uploader-progress-bar",
1064
+ myImagesTab: "neeto-image-uploader-my-images-tab",
1065
+ unsplashTab: "neeto-image-uploader-unsplash-tab",
1066
+ nthLibraryImage: (index) => `niu-library-image-${index}`,
1067
+ nthUnsplashImage: (index) => `niu-unsplash-image-${index}`,
1068
+ unsplashSearchInput: "niu-unsplash-image-picker-search-input",
1069
+ imageEditorUploadedImage: "image-editor-uploaded-image",
1070
+ selectOriginalImageSwitch: "select-original-image-switch",
1071
+ lockAspectRatioSwitch: "lock-aspect-ratio-switch",
1072
+ widthInputField: "width-input-field",
1073
+ heightInputField: "height-input-field",
1104
1074
  };
1105
- const ZAPIER_LIMIT_EXHAUSTED_MESSAGE = "Zapier free task limit is exhausted. Test will be aborted";
1106
- const EMOJI_LABEL = "thumbs up";
1107
- const GOOGLE_CALENDAR_DATE_FORMAT = "YYYY/M/D";
1108
- const MICROSOFT_LOGIN_TEXTS = {
1109
- passwordInput: "Enter the password",
1110
- emailInput: "Enter your email",
1111
- enterCode: "Enter code",
1112
- verify: "Verify",
1113
- staySignedIn: "Stay signed in?",
1114
- signIn: "Sign in",
1115
- next: "Next",
1116
- enterPassword: "Enter password",
1117
- password: "Password",
1118
- permissionsRequested: "Permissions requested",
1119
- yes: "Yes",
1120
- remove: "Remove",
1121
- manageYourApplication: "Manage your application",
1122
- revokeConsent: "Revoke consent",
1123
- useVerificationCode: "Use a verification code",
1124
- successfullyRevokedConsent: "Successfully revoked consent",
1075
+
1076
+ const INTEGRATION_SELECTORS = {
1077
+ integrationCard: (integration) => `${integration}-integration-card`,
1078
+ connectButton: "connect-button",
1079
+ integrationStatusTag: "integration-status-tag",
1080
+ disconnectButton: "disconnect-button",
1081
+ manageButton: "manage-button",
1082
+ integrationConnectedTag: "integration-connected-tag",
1125
1083
  };
1126
- const GOOGLE_LOGIN_TEXTS = {
1127
- googleAccount: "Google Account:",
1128
- connectYourGoogleAccount: "Connect your Google account",
1129
- signInWithGoogle: "Sign in with Google",
1130
- signInHeading: (appName) => new RegExp(`^(?:You['’]re signing back in to ${appName}\\.net|Sign in to ${appName}\\.net)$`, "i"),
1131
- stagingAppName: (appName) => `${appName} - Staging`,
1132
- continue: "Continue",
1133
- selectAll: "Select All",
1134
- appNotVerified: "Google hasn’t verified this app",
1135
- next: "Next",
1136
- showPassword: "Show password",
1137
- emailOrPhone: "Email or phone",
1138
- enterYourPassword: "Enter your password",
1139
- twoStepVerification: "2-Step Verification",
1140
- enterCode: "Enter code",
1141
- allow: "Allow",
1142
- signOut: "Sign out",
1143
- wrongCode: "Wrong code. Try again",
1144
- verificationCode: "verification code",
1145
- confirm: "Confirm",
1146
- cancel: "Cancel",
1147
- deleteConnections: "Delete all connections you",
1148
- noLongerConnected: "You’re no longer connected to",
1149
- backToSafety: "Back to safety",
1150
- neetoAutomation: "automation",
1151
- chooseAnAccount: "Choose an account",
1084
+
1085
+ const GOOGLE_LOGIN_SELECTORS = {
1086
+ totpNext: "#totpNext",
1087
+ form: "form",
1088
+ totpChallengeSelector: '[data-challengeid="2"]',
1089
+ signOutFrameLocator: 'iframe[name="account"]',
1152
1090
  };
1153
- const ENGAGE_TEXTS = { subscribe: "Subscribe" };
1154
- const COMMUNITY_TEXTS = { joinCommunity: "Join community" };
1155
- const STATUS_TEXTS = {
1156
- appName: (appName) => `Neeto${appName}`,
1091
+ const GOOGLE_ANALYTICS_SELECTORS = {
1092
+ gaCode: "google-analytics-code-input-field",
1157
1093
  };
1158
- const COMMON_TEXTS = {
1159
- skipCleanup: "@SKIP_CLEANUP",
1160
- skipSetup: "@SKIP_SETUP",
1094
+ const GOOGLE_SHEETS_SELECTORS = {
1095
+ iframe: 'iframe[title="Content"]',
1161
1096
  };
1162
- const ORGANIZATION_TEXTS = {
1163
- subdomainAvailable: "Subdomain is available",
1097
+
1098
+ const MICROSOFT_LOGIN_SELECTORS = {
1099
+ acceptButton: '[data-report-event="Signin_Submit"]',
1100
+ cancelButton: 'input[type="button"]',
1101
+ signInProfileIcon: "#mectrl_headerPicture",
1102
+ emailInput: '[type="email"]',
1103
+ placeholder: ".placeholderInnerContainer",
1104
+ dropdownMenu: (appName) => `button[aria-label*='${appName}app']`,
1164
1105
  };
1165
- const THEMES_TEXTS = {
1166
- lightThemeClass: /neeto-ui-theme--light/,
1167
- darkThemeClass: /neeto-ui-theme--dark/,
1106
+
1107
+ const dataQa = (value) => `[data-qa='${value}']`;
1108
+ const SLACK_SELECTORS = {
1109
+ messageContainer: dataQa("message_container"),
1110
+ loginEmail: dataQa("login_email"),
1111
+ loginPassword: dataQa("login_password"),
1112
+ signInButton: dataQa("signin_button"),
1113
+ teamPicketButtonContent: dataQa("oauth-team-picker-button-content"),
1114
+ redirectOpenInBrowser: dataQa("ssb_redirect_open_in_browser"),
1115
+ workspaceActionsButton: dataQa("workspace_actions_button"),
1116
+ teamMenuTrigger: dataQa("team-menu-trigger"),
1117
+ menuItemButton: "menu_item_button",
1118
+ threadsFlexpane: "threads_flexpane",
1119
+ replyBar: "reply_bar",
1120
+ markdownElement: "bk_markdown_element",
1121
+ virtualListItem: "virtual-list-item",
1122
+ channelItems: '[role="treeitem"][data-qa="virtual-list-item"]',
1123
+ installButton: dataQa("oauth_submit_button"),
1124
+ };
1125
+ const SLACK_DATA_QA_SELECTORS = {
1126
+ sectionHeadingButton: "section_heading_button__channels",
1127
+ coachMarkCloseButton: "coachmark-close-button",
1128
+ messagePaneBannerCloseIcon: "message_pane_banner_close_icon",
1129
+ permissionBannerCloseIcon: "banner_close_btn",
1130
+ channelSectionSubmenuCreate: "channel_section_submenu_create",
1131
+ channelSectionMenuCreateChannel: "channel_section_menu__create_channel",
1132
+ skModalContent: "sk-modal-content",
1133
+ infiniteSpinner: "infinite-spinner",
1134
+ channelNameOptionsList: "channel-name-options-list",
1135
+ channelNameInput: "channel-name-input",
1136
+ createChannelNextButton: "create-channel-next-button",
1137
+ inviteToWorkspaceSkipButton: "invite_to_workspace_skip_button",
1138
+ menuItems: "menu_items",
1139
+ channelDetailsModal: "channel_details_modal",
1140
+ channelDetailsSettingsTab: "channel_details_settings_tab",
1141
+ };
1142
+
1143
+ const TWILIO_SELECTORS = {
1144
+ sidField: "sid-input-field",
1145
+ authTokenField: "auth-token-input-field",
1146
+ };
1147
+
1148
+ const ZAPIER_SELECTORS = {
1149
+ zapTriggerStep: (zapId) => `[data-testid='step-node-${zapId}']`,
1150
+ zapAccountSubstep: "[data-testid='substep-Account']",
1151
+ zapOpenSubstepContainer: "[data-testid='open-sub-step-container']",
1152
+ modal: "[data-testid='Modal']",
1153
+ spinner: "spinner",
1154
+ skeletonBlock: "[data-testid='SkeletonBlock']",
1155
+ accountsLoader: "[data-testid='accounts-loader']",
1156
+ floatingBox: "floating-box",
1157
+ connection: "[data-testid='Connection']",
1158
+ deleteConnectionModal: "[data-testid='DeleteAuthModal-root']",
1159
+ deleteConnectionDropdownButton: "[data-testid='connection-list-item-dropdown-item-Delete']",
1160
+ usageAmounts: "css=[class$=UsageBar__amounts]",
1161
+ universalSidebar: "[data-testid='universalSidebar']",
1162
+ sidebarFooter: "css=[class$=InAppSidebarFooter__footerWrapper]",
1163
+ contextualSideBar: "[data-testid='contextual-sidebar']",
1164
+ iconContainer: "[data-testid='iconContainer']",
1165
+ deleteApiButton: "delete-apikey-button",
1166
+ zapierSubLink: "zapier-sub-link",
1167
+ navbar: "top-nav-test-id",
1168
+ authTitle: "auth-title",
1169
+ publishButton: "publish-button-wrapper",
1170
+ panelFooter: "#details-panel-footer",
1171
+ zapToggle: "zap-toggle",
1172
+ stepBlock: `step-node-${process.env.ZAP_ID}`,
1173
+ universalTopbar: "universalTopbar",
1174
+ accountsMenu: "accounts-menu-summary",
1175
+ authenticationCode: "[id='2fa-code']",
1176
+ zapToggleCheckbox: "input[type='checkbox']",
1177
+ };
1178
+
1179
+ const LOGIN_SELECTORS = {
1180
+ appleAuthenticationButton: "apple-authentication-button",
1181
+ emailTextField: "login-email-text-field",
1182
+ loginAsOliverBtn: "login-as-oliver-btn",
1183
+ googleAuthenticationButton: "google-authentication-button",
1184
+ githubAuthenticationButton: "github-authentication-button",
1185
+ loginViaEmailButton: "login-via-email-button",
1186
+ passwordTextField: "login-password-text-field",
1187
+ rememberMeCheckBox: "login-remember-me-check-box",
1188
+ submitButton: "login-submit-button",
1189
+ twitterAuthenticationButton: "twitter-authentication-button",
1190
+ authenticatorAppOtpInput: "authenticator-app-otp-login-code-input",
1191
+ enterOtpInputError: "enter-otp-input-error",
1192
+ authenticatorAppLaterButton: "authenticator-app-promo-later-button",
1193
+ };
1194
+
1195
+ const ONBOARDING_SELECTORS = {
1196
+ welcomeTitle: "onboarding-welcome-title",
1197
+ welcomeDescription: "onboarding-welcome-description",
1198
+ getStartedBtn: "onboarding-welcome-button",
1199
+ doLaterBtn: "onboarding-do-later-button",
1200
+ helpBtn: "onboarding-help-button",
1201
+ continueBtn: "onboarding-continue-button",
1202
+ congratulationsTitle: "onboarding-congratulations-title",
1203
+ congratulationsDescription: "onboarding-congratulations-description",
1204
+ congratulationsBtn: "onboarding-congratulations-button",
1205
+ };
1206
+
1207
+ const PROFILE_SECTION_SELECTORS = {
1208
+ profileSectionButton: "profile-section",
1209
+ profilePopup: "profile-popup",
1210
+ profileExpandMenuBtn: "profile-expand-menu-button",
1211
+ profileMoreDropdownButton: "profile-more-dropdown-button",
1212
+ myProfileButton: "profile-my-profile-button",
1213
+ updateEmailMenuBtn: "update-email-menu-button",
1214
+ workspaceDisplay: "workspace-display",
1215
+ profileOrganizationSettingsButton: "profile-organization-settings-button",
1216
+ logoutButton: "profile-logout-button",
1217
+ neetoAuthLink: "ntm-visit-auth-button",
1218
+ profileSidebarCancelButton: "ntm-profile-cancel-button",
1219
+ profileAvatar: "profile-avatar",
1220
+ actionHeaderUserName: "floating-action-menu-header-user-name",
1221
+ actionHeaderUserEmail: "floating-action-menu-header-user-email",
1222
+ submitButton: "ntm-profile-submit-button",
1223
+ editBtn: "edit-basic-info-menu-button",
1224
+ firstNameTextField: "profile-first-name-text-field",
1225
+ lastNameTextField: "profile-last-name-text-field",
1226
+ manageBillingAndSubscriptionsButton: "manage-billing-subscriptions-menu-button",
1227
+ cancelButton: "profile-cancel-button",
1228
+ profileSubmitBtn: "profile-submit-button",
1229
+ editBasicInfoMenuBtn: "edit-basic-info-menu-button",
1230
+ editBasicInfoBtn: "edit-basic-info-button",
1231
+ phoneNumberTxtField: "profile-phonenumber-text-field",
1232
+ timezoneBtn: "timezone-selector-select-button",
1233
+ timezoneSearchBox: "timezone-selector-search-box",
1234
+ nameField: "profile-full-name-field",
1235
+ emailField: "profile-email-field",
1236
+ firstNameField: "profile-first-name-field",
1237
+ lastNameField: "profile-last-name-field",
1238
+ phoneNumberField: "profile-phone-number-field",
1239
+ countryField: "profile-country-field",
1240
+ timeZoneField: "profile-time-zone-field",
1241
+ timeFormatField: "profile-preferred-time-format-field",
1242
+ dateFormatField: "profile-preferred-date-format-field",
1243
+ firstNameInputError: "first-name-input-error",
1244
+ timeZoneSelect: "profile-time-zone-select",
1245
+ lastNameInputError: "last-name-input-error",
1246
+ phoneNumberInputError: "phone-number-input-error",
1247
+ imageUploadBtn: "profile-image-upload-button",
1248
+ profileImageDropdownButton: "profile-image-dropdown-button",
1249
+ imageRemoveBtn: "profile-image-remove-button",
1250
+ };
1251
+
1252
+ const NEETO_SEO_SELECTORS = {
1253
+ configureButton: "neeto-seo-configure-button",
1254
+ };
1255
+
1256
+ const SIGNUP_SELECTORS = {
1257
+ emailTextField: "signup-email-text-field",
1258
+ firstNameTextField: "signup-profile-first-name-text-field",
1259
+ lastNameTextField: "signup-profile-last-name-text-field",
1260
+ organizationNameTextField: "signup-organization-name-text-field",
1261
+ organizationSubmitButton: "signup-organization-submit-button",
1262
+ organizationSyncContainer: "organization-sync-container",
1263
+ otpTextBox: "otpinput-otp-number",
1264
+ profileSubmitButton: "signup-profile-submit-button",
1265
+ signupViaEmailButton: "signup-via-email-button",
1266
+ submitButton: "signup-email-submit-button",
1267
+ subdomainNameTextField: "signup-organization-subdomain-text-field",
1268
+ subdomainAvailabilityMsg: "subdomain-availability-message",
1269
+ subdomainError: "subdomain-input-error",
1270
+ tryFreeButton: "neeto-auth-signup-link",
1271
+ unregisteredEmailError: "unregistered-email-error",
1272
+ organization: (organizationName) => `${organizationName}-organization-item`,
1273
+ };
1274
+
1275
+ const TAB_SELECTORS = {
1276
+ configureTab: "configure-tab",
1277
+ buildTab: "build-tab",
1278
+ themeTab: "theme-tab",
1279
+ shareTab: "share-tab",
1280
+ submissionsTab: "submissions-tab",
1281
+ paymentsTab: "payments-tab",
1282
+ settingsTab: "settings-tab",
1283
+ };
1284
+
1285
+ const TABLE_SELECTORS = {
1286
+ freezeUnfreezeButton: "freeze-unfreeze-column-menu-button",
1287
+ ascendingButton: "ascending-column-menu-button",
1288
+ descendingButton: "descending-column-menu-button",
1289
+ hideButton: "hide-column-menu-button",
1290
+ columnHeaderTitle: (columnName) => `${hyphenate(columnName)}-header-title`,
1291
+ columnMenuButton: "column-menu-button",
1292
+ columnInfoIcon: "column-info-icon",
1293
+ columnMenuBtn: (action) => `${action}-column-menu-button`,
1294
+ moveColumnBtn: (position) => `move-column-${position}-menu-button`,
1295
+ };
1296
+
1297
+ const THEMES_SELECTORS = {
1298
+ colorPickerDropdownContainer: (colorHex) => `${colorHex}-dropdown-container`,
1299
+ baseThemeStyle: (styleType) => `theme-style-${hyphenate(styleType)}`,
1300
+ introPageThemeStyle: (styleType) => `intro-page-theme-style-${hyphenate(styleType)}`,
1301
+ themeSwitcherButton: "theme-switcher-button",
1302
+ themeSwitcherDarkButton: "theme-switcher-dark-button",
1303
+ };
1304
+
1305
+ const CHAT_WIDGET_SELECTORS = {
1306
+ iframe: "#neetochat-iframe",
1307
+ spinner: ".neeto-chat-widget-spinner",
1308
+ helpButton: "help-button",
1309
+ preChatEmailInput: "neeto-chat-widget-input",
1310
+ preChatSubmitButton: "neeto-chat-widget-pre-chat-submit-btn",
1311
+ chatBubble: "neeto-chat-widget-chat-message-bubble",
1312
+ closeChat: "neeto-chat-widget-close-btn",
1313
+ chatQuestionHeader: "chat-question-header",
1314
+ openChat: "neeto-chat-widget-open-btn",
1315
+ homeScreenSubtitle: "neeto-chat-widget-home-screen-subtitle",
1316
+ };
1317
+ const CHANGELOG_WIDGET_SELECTORS = {
1318
+ changelogWrapper: ".ne-widget__wrapper",
1319
+ closeButton: "ne-widget-close-btn",
1320
+ publicUrlLink: "ne-widget-public-url",
1321
+ };
1322
+ const KEYBOARD_SHORTCUTS_SELECTORS = {
1323
+ keyboardShortcutsPane: "keyboard-shortcuts-pane",
1324
+ closePaneButton: "keyboard-shortcuts-pane-close-button",
1325
+ hotKeyItem: "hotkey-item",
1168
1326
  };
1169
1327
 
1170
1328
  class IntegrationBase {
@@ -1305,7 +1463,7 @@ const pollForCookies = async (redis, provider, context) => {
1305
1463
  const controller = new AbortController();
1306
1464
  const { signal } = controller;
1307
1465
  const timeout = setTimeout$1(POLL_TIMEOUT_MS, undefined, { signal }).then(() => {
1308
- throw new Error(`[cookieCache] Timed out waiting for "${provider}" cookies from another shard`);
1466
+ failTest(`[cookieCache] Timed out waiting for "${provider}" cookies from another shard`);
1309
1467
  });
1310
1468
  const poll = async () => {
1311
1469
  while (true) {
@@ -1370,7 +1528,7 @@ const initializeTotp = ({ issuer, secret, }) => {
1370
1528
  if (IS_DEV_ENV)
1371
1529
  secret = "JBSWY3DPEHPK3PXP";
1372
1530
  else
1373
- throw new Error("Secret for TOTP generation is not defined.");
1531
+ failTest("Secret for TOTP generation is not defined.");
1374
1532
  }
1375
1533
  return new TOTP({
1376
1534
  issuer,
@@ -1600,9 +1758,8 @@ const createOrganizationViaRake = async ({ email, firstName, lastName, subdomain
1600
1758
  childProcess.on("error", reject);
1601
1759
  childProcess.on("close", resolve);
1602
1760
  });
1603
- if (exitCode !== 0) {
1604
- throw new Error(`Failed to create organization: ${stderr || stdout || `Exit code ${exitCode}`}`);
1605
- }
1761
+ if (exitCode !== 0)
1762
+ failTest(`Failed to create organization: ${stderr || stdout || `Exit code ${exitCode}`}`);
1606
1763
  return stdout.trim();
1607
1764
  };
1608
1765
  const createOrganizationViaApi = async ({ page, email, firstName, lastName, businessName, subdomainName, redirectUri, timeZone = DEFAULT_TIMEZONE_ID, }) => {
@@ -1624,9 +1781,8 @@ const createOrganizationViaApi = async ({ page, email, firstName, lastName, busi
1624
1781
  },
1625
1782
  timeout: 120_000,
1626
1783
  });
1627
- if (!response.ok()) {
1628
- throw new Error(`Quick organization setup failed with status ${response.status()}: ${await response.text()}`);
1629
- }
1784
+ if (!response.ok())
1785
+ failTest(`Quick organization setup failed with status ${response.status()}: ${await response.text()}`);
1630
1786
  // The OTT in the login URL expires in 150 seconds; navigate immediately.
1631
1787
  const { login_url: loginUrl } = await response.json();
1632
1788
  await page.goto(loginUrl, { timeout: 30_000 });
@@ -2019,1223 +2175,1076 @@ class OrganizationPage {
2019
2175
  };
2020
2176
  }
2021
2177
 
2022
- const authenticateUser = async ({ page, loginPath, email, }) => {
2023
- const organizationPage = new OrganizationPage(page, new CustomCommands(page, page.request));
2024
- await (email
2025
- ? organizationPage.login({ email, path: loginPath })
2026
- : organizationPage.login({
2027
- via: LOGIN_STRATEGIES.oliver,
2028
- path: loginPath,
2029
- }));
2030
- await expect(page.getByTestId(COMMON_SELECTORS.floatingActionMenuButton)).toBeVisible({ timeout: 60_000 });
2031
- };
2032
- const login = async ({ page, loginPath = "/", }) => {
2033
- if (shouldSkipSetupAndTeardown() || !IS_DEV_ENV)
2034
- return;
2035
- await authenticateUser({ page, loginPath });
2036
- await saveStorageState(page, { isLoggedIn: "true" });
2037
- };
2038
-
2039
- const REVIEW_APP_WAKE_TIMEOUT = 10 * 60_000;
2040
- const REVIEW_APP_POLL_INTERVAL = 10_000;
2041
- const REVIEW_APP_REQUEST_TIMEOUT = 20_000;
2042
- // The host is read on each call so that a product importing the package outside
2043
- // the review environment never trips the guard.
2044
- const reviewAppHost = () => requireEnv("REVIEW_APP_HOST");
2045
- const isReviewAppServing = async () => {
2046
- try {
2047
- const response = await fetch(`https://${reviewAppHost()}/?_hs=${Date.now()}`, {
2048
- headers: { Accept: "text/html", "X-Downtime-Poll": "1" },
2049
- redirect: "manual",
2050
- signal: AbortSignal.timeout(REVIEW_APP_REQUEST_TIMEOUT),
2051
- });
2052
- return response.status < 400 && !response.headers.has("x-neeto-downtime");
2053
- }
2054
- catch {
2055
- return false;
2056
- }
2057
- };
2058
- const wakeReviewApp = async () => {
2059
- try {
2060
- await fetch(`https://${reviewAppHost()}/`, {
2061
- headers: { Accept: "text/html" },
2062
- signal: AbortSignal.timeout(REVIEW_APP_REQUEST_TIMEOUT),
2063
- });
2064
- }
2065
- catch {
2066
- // The wake request is fire-and-forget; readiness is polled separately.
2067
- }
2068
- };
2069
- const reviewAppBaseURL = (subdomain = CREDENTIALS.subdomainName) => `https://${subdomain}.${reviewAppHost()}`;
2070
- const waitForReviewApp = () => {
2071
- const host = reviewAppHost();
2072
- return expect(async () => {
2073
- const isServing = await isReviewAppServing();
2074
- !isServing && (await wakeReviewApp());
2075
- expect(isServing, `Review app ${host} is not up yet`).toBe(true);
2076
- }).toPass({
2077
- timeout: REVIEW_APP_WAKE_TIMEOUT,
2078
- intervals: [REVIEW_APP_POLL_INTERVAL],
2079
- });
2080
- };
2081
- const initializeReviewAppCredentials = () => {
2082
- if (shouldSkipSetupAndTeardown())
2083
- return;
2084
- const { firstName, lastName, name, email, subdomainName } = CREDENTIALS;
2085
- writeDataToFile(JSON.stringify({
2086
- user: {
2087
- firstName,
2088
- lastName,
2089
- email,
2090
- subdomainName,
2091
- businessName: subdomainName,
2092
- currentUserName: name,
2093
- otp: 111111,
2094
- domain: reviewAppHost(),
2095
- },
2096
- }, null, 2));
2097
- };
2098
- const loginToReviewApp = async ({ page, loginPath = "/login", }) => {
2099
- if (shouldSkipSetupAndTeardown())
2100
- return;
2101
- await waitForReviewApp();
2102
- await authenticateUser({ page, loginPath });
2103
- await saveStorageState(page, { isLoggedIn: "true" });
2104
- };
2105
- const reviewAppOrganizationOptions = ({ subdomain = CREDENTIALS.subdomainName, loginPath = "/login", } = {}) => IS_REVIEW_ENV
2106
- ? {
2107
- baseURL: reviewAppBaseURL(subdomain),
2108
- storageState: async ({ browser, baseURL }, use) => {
2109
- const context = await browser.newContext({
2110
- ...EMPTY_STORAGE_STATE,
2111
- baseURL,
2112
- });
2113
- try {
2114
- await authenticateUser({
2115
- page: await context.newPage(),
2116
- loginPath,
2117
- });
2118
- await use(await context.storageState());
2119
- }
2120
- finally {
2121
- await context.close();
2122
- }
2123
- },
2124
- }
2125
- : {};
2126
-
2127
- const execCommand = (command) => execSync(command, { encoding: "utf8" }).trimEnd();
2128
- const joinString = (string1, string2, string3 = "", separator = " ") => {
2129
- if (string3 === "") {
2130
- return string1 + separator + string2;
2131
- }
2132
- return string1 + separator + string2 + separator + string3;
2133
- };
2134
- const readFileSyncIfExists = (path = STORAGE_STATE) => {
2135
- try {
2136
- return JSON.parse(fs.readFileSync(path, "utf8"));
2137
- }
2138
- catch {
2139
- return {};
2140
- }
2141
- };
2142
- const getGlobalUserState = () => readFileSyncIfExists()?.user;
2143
- const writeDataToFile = data => {
2144
- try {
2145
- fs.writeFileSync(STORAGE_STATE, data, "utf8");
2146
- }
2147
- catch (error) {
2148
- console.log(error);
2149
- }
2150
- return true;
2151
- };
2152
- const updateCredentials = ({ key, value }) => {
2153
- const data = readFileSyncIfExists();
2154
- data["user"][key] = value;
2155
- return writeDataToFile(JSON.stringify(data));
2156
- };
2157
- const saveStorageState = async (page, credentials = {}) => {
2158
- const { user = {} } = readFileSyncIfExists();
2159
- await page.context().storageState({ path: STORAGE_STATE });
2160
- const csrfTokenLocator = page.locator("[name='csrf-token']");
2161
- const csrfToken = (await csrfTokenLocator.getAttribute("content")) ?? "";
2162
- return writeDataToFile(JSON.stringify({
2163
- ...readFileSyncIfExists(),
2164
- user: { ...user, ...credentials, csrfToken },
2165
- }, null, 2));
2166
- };
2167
- const removeCredentialFile = () => {
2168
- try {
2169
- fs.existsSync(STORAGE_STATE) && fs.unlinkSync(STORAGE_STATE);
2170
- }
2171
- catch (error) {
2172
- console.log(error);
2173
- }
2174
- };
2175
- const clearCredentials = () => {
2176
- if (shouldSkipSetupAndTeardown())
2177
- return;
2178
- removeCredentialFile();
2178
+ const mimeTypeMap = {
2179
+ csv: "text/csv",
2180
+ avi: "video/x-msvideo",
2181
+ doc: "application/msword",
2182
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2183
+ flv: "video/x-flv",
2184
+ html: "text/html",
2185
+ mp3: "audio/mpeg",
2186
+ mp4: "video/mp4",
2187
+ mpg: "video/mpeg",
2188
+ pdf: "application/pdf",
2189
+ rtf: "application/rtf",
2190
+ txt: "text/plain",
2191
+ webm: "video/webm",
2192
+ xls: "application/vnd.ms-excel",
2193
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2194
+ wma: "audio/x-ms-wma",
2195
+ zip: "application/zip",
2196
+ jpg: "image/jpeg",
2197
+ jpeg: "image/jpeg",
2198
+ png: "image/png",
2199
+ gif: "image/gif",
2200
+ ico: "image/x-icon",
2201
+ svg: "image/svg+xml",
2179
2202
  };
2180
- const joinHyphenCase = (...args) => args.join(" ").replace(/\s+/g, "-").toLowerCase();
2181
- const skipTest = {
2182
- forDevelopmentEnv: () => test.skip(process.env.TEST_ENV === ENVIRONMENT.development),
2183
- forReviewEnv: () => test.skip(process.env.TEST_ENV === ENVIRONMENT.review),
2184
- forAllExceptStagingEnv: () => test.skip(process.env.TEST_ENV !== ENVIRONMENT.staging),
2185
- forNonNightlyRun: () => {
2186
- const currentBranch = execCommand("git rev-parse --abbrev-ref HEAD");
2187
- const isNightlyRun = currentBranch === "main" && IS_STAGING_ENV && IS_CI;
2188
- return test.skip(not(isNightlyRun), "Run test only in playwright-nightly");
2189
- },
2190
- ifNotWithinAllowedNightlyHours: ({ reason, allowedNightlyRunHours = [0, 6, 12, 18], }) => {
2191
- skipTest.forNonNightlyRun();
2192
- const currentDate = new Date();
2193
- const day = currentDate.getUTCDay();
2194
- const hour = currentDate.getUTCHours();
2195
- const isAllowedNightlyRun = 0 < day && day < 6 && allowedNightlyRunHours.includes(hour);
2196
- test.skip(not(isAllowedNightlyRun), `Nightly run is skipped due to ${reason}`);
2197
- },
2203
+ const serializeFileForBrowser = async (file) => {
2204
+ const buffer = await file.arrayBuffer();
2205
+ return {
2206
+ name: file.name,
2207
+ type: file.type,
2208
+ lastModified: file.lastModified,
2209
+ buffer: Array.from(new Uint8Array(buffer)),
2210
+ };
2198
2211
  };
2199
- const shouldSkipSetupAndTeardown = () => getGlobalUserState()?.isLoggedIn && process.env.SKIP_SETUP === "true";
2200
- const shouldSkipCustomDomainSetup = () => process.env.SETUP_CUSTOM_DOMAIN !== "true" || !IS_STAGING_ENV;
2201
- const baseURLGenerator = (product, customSubdomain) => {
2202
- const { subdomainName } = getGlobalUserState();
2203
- const subdomain = customSubdomain ?? subdomainName;
2204
- const railsPort = process.env.RAILS_SERVER_PORT;
2205
- if (IS_DEV_ENV)
2206
- return `http://${subdomain}.lvh.me:${railsPort}`;
2207
- if (IS_REVIEW_ENV)
2208
- return reviewAppBaseURL(subdomain);
2209
- return `https://${subdomain}.neeto${product.toLowerCase()}.net`;
2212
+ const generateRandomFile = ({ sizeInKB, fileType, fileName = `sample.${fileType}`, }) => {
2213
+ const mimeType = mimeTypeMap[fileType];
2214
+ const byteArray = randomFillSync(new Uint8Array(sizeInKB * 1024));
2215
+ const file = new File([byteArray], fileName, { type: mimeType });
2216
+ return { file, fileName };
2210
2217
  };
2211
- // trims and replaces multiple whitespace characters in a string with a single space
2212
- const squish = (text) => text.trim().replace(/\s+/g, " ");
2213
- const toCamelCase = (string) => string.toLowerCase().replace(/( \w)/g, letter => letter[1].toUpperCase());
2214
- const getByDataQA = curry((page, dataQa) => {
2215
- if (typeof dataQa === "string") {
2216
- return page.locator(`[data-qa='${dataQa}']`);
2217
- }
2218
- return page
2219
- .locator(`[data-qa='${dataQa[0]}']`)
2220
- .locator(`[data-qa='${dataQa[1]}']`);
2218
+ const readFileAsBrowserFile = ({ filePath, mimeType, }) => new File([readFileSync(filePath)], path__default.basename(filePath), {
2219
+ type: mimeType,
2221
2220
  });
2222
- const getListCount = async ({ page, countSelector, }) => {
2223
- const countText = await page.getByTestId(countSelector).textContent();
2224
- return Number(countText?.trim().split(" ")[0]);
2221
+
2222
+ const getImagePathAndName = (localImagePath) => {
2223
+ const imagePath = path__default.join(import.meta.dirname, localImagePath);
2224
+ const imageName = path__default.basename(localImagePath, path__default.extname(localImagePath));
2225
+ return { imagePath, imageName };
2225
2226
  };
2226
- const getGlobalUserProps = async (page) => (await page.evaluate(() => window.globalProps.user));
2227
- const createTextareaAndEvaluateCopiedText = async (page) => {
2228
- const textareaHandle = await page.evaluateHandle(() => {
2229
- const textarea = document.createElement("textarea");
2230
- Object.assign(textarea.style, {
2231
- position: "fixed",
2232
- top: "0",
2233
- left: "0",
2234
- opacity: "0",
2235
- pointerEvents: "none",
2236
- zIndex: "9999",
2237
- });
2238
- document.body.appendChild(textarea);
2239
- textarea.focus();
2240
- return textarea;
2241
- });
2242
- try {
2243
- await page.keyboard.press("ControlOrMeta+v");
2244
- return await page.evaluate(el => el.value, textareaHandle);
2227
+
2228
+ const TOAST_DEFAULT_MESSAGE = "👍";
2229
+ class CustomCommands {
2230
+ page;
2231
+ t;
2232
+ responses;
2233
+ request;
2234
+ baseURL;
2235
+ csrfToken;
2236
+ constructor(page, request, baseURL = process.env.BASE_URL) {
2237
+ this.page = page;
2238
+ this.responses = [];
2239
+ this.request = request;
2240
+ this.baseURL = baseURL;
2241
+ this.t = getI18nInstance().t;
2245
2242
  }
2246
- finally {
2247
- await textareaHandle.evaluate(el => el.remove());
2248
- await textareaHandle.dispose();
2249
- }
2250
- };
2251
- const getClipboardContent = async (page) => {
2252
- // Attempt 1: Native Clipboard API
2253
- const clipboardText = await page.evaluate(async () => {
2254
- if (!navigator.clipboard?.readText)
2255
- return null;
2256
- return await navigator.clipboard.readText();
2243
+ initializeCsrfToken = async () => {
2244
+ this.csrfToken =
2245
+ this.page.url() === "about:blank"
2246
+ ? getGlobalUserState()?.csrfToken
2247
+ : await this.page
2248
+ .locator("[name='csrf-token']")
2249
+ .getAttribute("content");
2250
+ return this.csrfToken;
2251
+ };
2252
+ blockExternalResources = (page = this.page) => Promise.all(THIRD_PARTY_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())));
2253
+ blockInternalResources = (page = this.page) => Promise.all(APP_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())));
2254
+ blockNonEssentialResourceTypes = (page = this.page) => page
2255
+ .context()
2256
+ .route("**/*", route => ["image", "stylesheet", "font"].includes(route.request().resourceType())
2257
+ ? route.abort()
2258
+ : route.fallback());
2259
+ blockAllResources = (page = this.page) => Promise.all([
2260
+ this.blockNonEssentialResourceTypes(page),
2261
+ ...ALL_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())),
2262
+ ]);
2263
+ waitForFloatingMenu = (customPageContext = this.page) => expect(customPageContext.getByTestId(COMMON_SELECTORS.floatingActionMenuButton)).toBeVisible({ timeout: 30_000 });
2264
+ interceptMultipleResponses = ({ responseUrl = "", responseStatus = 200, times = 1, baseUrl, customPageContext = this.page, timeout = 35_000, } = {}) => Promise.all([...new Array(times)].map(() => customPageContext.waitForResponse((response) => {
2265
+ if (response.request().resourceType() === "xhr" &&
2266
+ response.status() === responseStatus &&
2267
+ response.url().includes(responseUrl) &&
2268
+ response.url().startsWith(baseUrl ?? this.baseURL ?? "") &&
2269
+ !this.responses.includes(response.headers()?.["x-request-id"])) {
2270
+ this.responses.push(response.headers()?.["x-request-id"]);
2271
+ return true;
2272
+ }
2273
+ return false;
2274
+ }, { timeout })));
2275
+ recursiveMethod = async (callback, condition, timeout, startTime, iteration) => {
2276
+ if (Date.now() - timeout >= startTime) {
2277
+ await callback();
2278
+ return false;
2279
+ }
2280
+ else if (await condition()) {
2281
+ return await callback();
2282
+ }
2283
+ const timeToWaitInSecs = iteration > 3 ? 10 : Math.pow(2, iteration);
2284
+ await setTimeout$1(timeToWaitInSecs * 1000);
2285
+ return await this.recursiveMethod(callback, condition, timeout, startTime, iteration + 1);
2286
+ };
2287
+ executeRecursively = async ({ callback, condition, timeout = 5000, }) => {
2288
+ const startTime = Date.now();
2289
+ return await this.recursiveMethod(callback, condition, timeout, startTime, 1);
2290
+ };
2291
+ verifyToast = async ({ message = "", toastType = "success", closeAfterVerification = true, timeout = 10_000, toastCloseTimeout = 10_000, customPageContext = this.page, } = {}) => {
2292
+ const toastMessageLocator = customPageContext.getByTestId(COMMON_SELECTORS.toastMessage(toastType));
2293
+ // Some products are still on the v1 (neetoui) Toastr, which renders the thumbs up icon and close button outside the message container.
2294
+ const toastLocator = customPageContext
2295
+ .locator(COMMON_SELECTORS.neetoUiToastr)
2296
+ .filter({ has: toastMessageLocator })
2297
+ .or(toastMessageLocator);
2298
+ const filteredToastLocator = (isEmpty(message)
2299
+ ? toastLocator
2300
+ : toastLocator.filter({ hasText: message }))
2301
+ // eslint-disable-next-line playwright/no-nth-methods
2302
+ .first();
2303
+ await expect(filteredToastLocator).toContainText(isEmpty(message) ? TOAST_DEFAULT_MESSAGE : message, { timeout });
2304
+ if (!closeAfterVerification)
2305
+ return;
2306
+ const toastCloseButton = filteredToastLocator.getByTestId(COMMON_SELECTORS.toastCloseButton);
2307
+ const buttonHandle = await toastCloseButton.elementHandle();
2308
+ if (buttonHandle) {
2309
+ await customPageContext.evaluate(button => {
2310
+ button.dispatchEvent(new Event("click", { bubbles: true }));
2311
+ }, buttonHandle);
2312
+ await expect(toastCloseButton).toBeHidden({
2313
+ timeout: toastCloseTimeout,
2314
+ });
2315
+ }
2316
+ };
2317
+ waitForPageLoad = async ({ visibilityTimeout = 35_000, customPageContext = this.page, waitForOption = "serial", } = {}) => {
2318
+ await customPageContext.waitForLoadState();
2319
+ const loaders = [
2320
+ customPageContext.getByTestId(COMMON_SELECTORS.pageLoader),
2321
+ customPageContext.getByTestId(COMMON_SELECTORS.uiSpinner),
2322
+ ];
2323
+ if (waitForOption === "serial") {
2324
+ for (const loader of loaders) {
2325
+ await expect(loader).toHaveCount(0, { timeout: visibilityTimeout });
2326
+ }
2327
+ return;
2328
+ }
2329
+ await Promise.all(loaders.map(loader => expect(loader).toHaveCount(0, { timeout: visibilityTimeout })));
2330
+ };
2331
+ apiRequest = async ({ url, failOnStatusCode = true, headers: additionalHeaders, body: data, method = "get", params = {}, timeout = 30_000, ...otherOptions }) => {
2332
+ const csrfToken = this.csrfToken ?? (await this.initializeCsrfToken());
2333
+ const requestOptions = {
2334
+ failOnStatusCode,
2335
+ timeout,
2336
+ headers: {
2337
+ ...additionalHeaders,
2338
+ "accept-encoding": "gzip",
2339
+ "x-csrf-token": csrfToken ?? "",
2340
+ },
2341
+ data,
2342
+ ...otherOptions,
2343
+ };
2344
+ const formattedUrl = isEmpty(params)
2345
+ ? url
2346
+ : `${url}?${stringify(params, {
2347
+ nestingSyntax: "js",
2348
+ arrayRepeat: true,
2349
+ arrayRepeatSyntax: "bracket",
2350
+ })}`;
2351
+ return await this.request[method](formattedUrl, requestOptions);
2352
+ };
2353
+ selectOptionFromDropdown = async ({ label = "nui", value, page = this.page, options: { visibilityTimeout = 5_000, textAssertionTimeout = 5_000, retryTimeout = 60_000, } = {}, }) => {
2354
+ const menu = page.getByTestId(COMMON_SELECTORS.customDropDownMenu(label));
2355
+ const optionByName = menu.getByRole("option", { name: value, exact: true });
2356
+ const container = page.getByTestId(COMMON_SELECTORS.customSelectContainer(label));
2357
+ await expect(async () => {
2358
+ await container.click();
2359
+ await expect(menu).toBeVisible({ timeout: visibilityTimeout });
2360
+ await page.keyboard.type(value);
2361
+ const option = (await optionByName.count()) > 0
2362
+ ? optionByName
2363
+ : menu.getByText(value, { exact: true });
2364
+ await option.click();
2365
+ await expect(container).toContainText(value, {
2366
+ timeout: textAssertionTimeout,
2367
+ });
2368
+ }).toPass({ timeout: retryTimeout });
2369
+ };
2370
+ waitForSheetOpen = () => expect(this.page.getByTestId(COMMON_SELECTORS.sheetHeader)).toBeInViewport({
2371
+ timeout: 10_000,
2372
+ ratio: 1,
2257
2373
  });
2258
- if (isNotNil(clipboardText))
2259
- return clipboardText;
2260
- // Attempt 2: Keyboard paste fallback
2261
- return createTextareaAndEvaluateCopiedText(page);
2262
- };
2263
- const grantClipboardPermissions = async (context) => {
2264
- const isWebkit = context.browser()?.browserType().name() === "webkit";
2265
- // WebKit supports "clipboard-read" but rejects "clipboard-write".
2266
- await context.grantPermissions(isWebkit ? ["clipboard-read"] : ["clipboard-read", "clipboard-write"]);
2267
- };
2268
- const getFullUrl = (path) => shouldSkipCustomDomainSetup() ? path : `${process.env.BASE_URL}${path}`;
2269
- const globalShortcuts = (t) => [
2270
- {
2271
- description: t("neetoMolecules.keyboardShortcuts.global.openKeyboardShortcutsPane"),
2272
- sequence: "ctrl+/",
2273
- },
2274
- {
2275
- description: t("neetoMolecules.keyboardShortcuts.global.close"),
2276
- sequence: "esc",
2277
- },
2278
- {
2279
- description: t("neetoMolecules.keyboardShortcuts.global.submitForm"),
2280
- sequence: "ctrl+enter",
2281
- },
2282
- {
2283
- description: t("neetoMolecules.keyboardShortcuts.global.openProductSwitcher"),
2284
- sequence: "ctrl+u",
2285
- },
2286
- {
2287
- description: t("neetoMolecules.keyboardShortcuts.global.search"),
2288
- sequence: "ctrl+k",
2289
- },
2290
- ];
2291
- const generatePhoneNumber = () => `${"+91"} 9${faker.string.numeric(4)} ${faker.string.numeric(5)}`;
2292
- const initializeTestData = (product) => {
2293
- const credentials = generateStagingData(product.toLowerCase());
2294
- const baseURL = baseURLGenerator(product, credentials.subdomainName);
2295
- return { credentials, baseURL };
2296
- };
2297
- const imageRegex = (imageName) => {
2298
- const [baseName, extension] = imageName.split(".");
2299
- return new RegExp(`${baseName}.*\\.${extension}$`);
2300
- };
2301
- const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60 * 1000);
2302
- const exampleEmail = () => faker.internet.exampleEmail({
2303
- firstName: faker.string.alpha(1),
2304
- lastName: faker.string.alpha(1),
2305
- allowSpecialCharacters: false,
2306
- });
2307
-
2308
- const optionSelector = (option) => `neeto-editor-fixed-menu-${option}-option`;
2309
- const fixedMenuSelector = (selector) => `neeto-editor-fixed-menu-${selector}`;
2310
- const NEETO_EDITOR_SELECTORS = {
2311
- fontSize: optionSelector("font-size"),
2312
- fontSizeHeadingOptions: new RegExp(`^${optionSelector("font-size")}-h[1-5]$`),
2313
- boldOption: optionSelector("bold"),
2314
- italicOption: optionSelector("italic"),
2315
- underlineOption: optionSelector("underline"),
2316
- strikeOption: optionSelector("strike"),
2317
- codeBlockOption: optionSelector("code"),
2318
- highlightOption: optionSelector("highlight"),
2319
- textColorOption: optionSelector("text-color"),
2320
- emojiOption: optionSelector("emoji"),
2321
- emojiDropdownIcon: "emoji-dropdown-icon",
2322
- linkInput: fixedMenuSelector("link-option-input"),
2323
- linkSubmitButton: fixedMenuSelector("link-option-link-button"),
2324
- commandList: (index) => `neeto-editor-command-list-item-${index}`,
2325
- imageUploadUrlSubmitButton: "neeto-editor-media-upload-url-submit",
2326
- imageUploadUrlInputTextField: "neeto-editor-media-upload-url-input",
2327
- uploadInput: "neeto-editor-media-uploader-input",
2328
- editorMenuBarWrapper: fixedMenuSelector("wrapper"),
2329
- undoOption: optionSelector("undo"),
2330
- redoOption: optionSelector("redo"),
2331
- imageWrapper: "neeto-editor-image-wrapper",
2332
- contentField: "neeto-editor-content",
2333
- slashCommandsWrapper: "neeto-editor-slash-commands-wrapper",
2334
- addLinkButton: optionSelector("link"),
2335
- addLinkTextField: "neeto-editor-add-link-text-input",
2336
- addURLTextField: "neeto-editor-add-link-url-input",
2337
- submitLinkButton: "neeto-editor-add-link",
2338
- fixedMenuArrow: fixedMenuSelector("arrow"),
2339
- cannedResponseOption: optionSelector("canned-responses"),
2340
- cannedResponseSelectContainer: "select-a-canned-response-select-container",
2341
- fixedMenuWrapper: fixedMenuSelector("wrapper"),
2342
- moreMenuOption: optionSelector("more"),
2343
- linkOption: optionSelector("link"),
2344
- addLinkUrlInput: "neeto-editor-add-link-url-input",
2345
- addLinkDoneButton: "neeto-editor-add-link",
2346
- addLinkOpenInNewTabCheckbox: "neeto-editor-add-link-open-in-new-tab-switch",
2347
- linkPopoverEditButton: "neeto-editor-link-popover-edit",
2348
- editLinkSubmitButton: "neeto-editor-edit-link",
2349
- unlinkButton: "neeto-editor-link-popover-unlink",
2350
- editorAttachmentsButton: optionSelector("attachments"),
2351
- attachmentPreviewDeleteButton: "neeto-editor-preview-delete-button",
2352
- imageUploadOption: optionSelector("image-upload"),
2353
- imageUploadLinkInput: "neeto-editor-media-upload-url-input",
2354
- imageUploadButton: "neeto-editor-media-uploader-dnd",
2355
- imageUploadLinkSubmitButton: "neeto-editor-media-upload-url-submit",
2356
- applyButton: "apply-button",
2357
- videoEmbedOption: optionSelector("video-embed"),
2358
- videoEmbedInput: "neeto-editor-embed-input",
2359
- videoEmbedSubmit: "neeto-editor-embed-cancel",
2360
- videoWrapper: "neeto-editor-video-wrapper",
2361
- paragraphOption: fixedMenuSelector("font-size-option-body2"),
2362
- calloutOption: fixedMenuSelector("callout-option"),
2363
- attachmentPreview: "ne-attachments-wrapper",
2364
- attachmentActionsButton: "neeto-editor-attachment-actions",
2365
- imageUploadLinkButton: "neeto-editor-media-uploader-link-tab",
2366
- errorText: "neeto-editor-error-text",
2367
- content: "editor-content",
2368
- imageUploadDeleteButton: "neeto-editor-image-menu-Delete",
2369
- dynamicVariablesButton: "dynamic-variables-button",
2370
- emojiContainer: "neeto-editor-emoji-picker",
2371
- characterCount: "neeto-editor-character-count",
2372
- tableOption: optionSelector("table"),
2373
- tableCreateButton: "neeto-editor-fixed-menu-table-option-create-button",
2374
- videoUploadOption: optionSelector("video-upload"),
2375
- todoListOption: optionSelector("todoList"),
2376
- editorMenuWrapper: "neeto-editor-fixed-menu-wrapper",
2377
- dataEmojiType: (type) => `[data-emoji="${type}"]`,
2378
- //Use data-testid once https://github.com/neetozone/neeto-editor/issues/1651 is resolved
2379
- calloutContent: ".callout-content",
2380
- //Use data-testid once https://github.com/neetozone/neeto-editor/issues/1648 is resolved
2381
- calloutTypeOption: ".neeto-editor-callout-dropdown__type-option",
2382
- calloutTypeOptionV2: "callout-type-option",
2383
- editorMediaUploaderTab: "neeto-editor-media-uploader-local-tab",
2384
- dynamicVariableSelector: (variable) => `dynamic-variables-list-item-${joinHyphenCase(variable)}`,
2385
- dynamicVariableList: (variable) => `dynamic-variables-list-${hyphenate(variable)}`,
2386
- neetoEditorFixedMenuFontSize: "neeto-editor-fixed-menu-font-size-option",
2387
- highlightText: (textColorIndex) => `--neeto-editor-highlight-text-${textColorIndex}`,
2388
- highlightBg: (bgColorIndex) => `--neeto-editor-highlight-bg-${bgColorIndex}`,
2389
- neetoEditorHighlightTextColor: (textColorIndex) => `neeto-editor-highlight-text-color-dot-${textColorIndex}`,
2390
- neetoEditorHighlightBgColor: (bgColorIndex) => `neeto-editor-highlight-background-color-dot-${bgColorIndex}`,
2391
- highlightTextColorGrid: "neeto-editor-highlight-text-color-grid",
2392
- todoList: "[data-type='todoList']",
2393
- selectedText: ".selected-text",
2394
- commandListItem: (index) => `neeto-editor-command-list-item-${index}`,
2395
- itemBlockHeading: "neeto-editor-command-list-item-block-heading",
2396
- };
2397
- const NEETO_TEXT_MODIFIER_SELECTORS = {
2398
- strike: optionSelector("strike"),
2399
- underline: optionSelector("underline"),
2400
- highlight: optionSelector("highlight"),
2401
- };
2402
- const TEXT_MODIFIER_SELECTORS = {
2403
- bold: optionSelector("bold"),
2404
- italic: optionSelector("italic"),
2405
- code: optionSelector("code"),
2406
- blockquote: optionSelector("blockquote"),
2407
- codeBlock: optionSelector("codeBlock"),
2408
- };
2409
- const LIST_MODIFIER_SELECTORS = {
2410
- bulletList: optionSelector("bulletList"),
2411
- orderedList: optionSelector("orderedList"),
2412
- };
2413
- const FONT_SIZE_SELECTORS = {
2414
- h1: fixedMenuSelector("font-size-option-h1"),
2415
- h2: fixedMenuSelector("font-size-option-h2"),
2416
- h3: fixedMenuSelector("font-size-option-h3"),
2417
- h4: fixedMenuSelector("font-size-option-h4"),
2418
- h5: fixedMenuSelector("font-size-option-h5"),
2419
- };
2420
-
2421
- const EMBED_SELECTORS = {
2422
- iframe: (appName) => `#${appName}-iframe`,
2423
- modal: (appName) => `#${appName}-modal`,
2424
- close: (appName) => `#close-${appName}`,
2425
- loader: (appName) => `#${appName}-loader`,
2426
- inlineHeightInput: "inline-height-input-field",
2427
- inlineWidthInput: "inline-width-input-field",
2428
- inlineElementIdInput: "inline-element-id-input-field",
2429
- codeBlock: "html-code-block",
2430
- previewTab: "preview-tab",
2431
- htmlTab: "html-tab",
2432
- buttonTextInput: "button-text-input-field",
2433
- buttonPositionSelectContainer: "button-position-select-field-select-container",
2434
- buttonPositionSelectMenu: "button-position-select-field-select-menu",
2435
- buttonColorLabel: "button-color-label",
2436
- buttonTextColorLabel: "button-text-color-label",
2437
- colorPickerTarget: "color-picker-target",
2438
- colorpickerEditableInput: "colorpicker-editable-input",
2439
- colorpickerEditableInputTextbox: "colorpicker-editable-input-textbox",
2440
- showIconCheckbox: "show-icon-checkbox",
2441
- elementIdInput: "element-id-input-field",
2442
- previewElementPopupButton: "preview-element-popup-button",
2443
- embedSelector: (type) => `embed-selector-card-${hyphenate(type)}`,
2444
- backToEmbedSelectionButton: "back-to-embed-selection-button",
2445
- };
2446
-
2447
- const NEETO_FILTERS_SELECTORS = {
2448
- emailSelectContainer: "email-select-container-wrapper",
2449
- filterPaneHeading: "neeto-filters-pane-header",
2450
- neetoFiltersEmailBlock: "neeto-filters-email-block",
2451
- neetoFiltersRoleBlock: "neeto-filters-role-block",
2452
- neetoFiltersBarClearButton: "neeto-filters-bar-clear-btn",
2453
- neetoFiltersNameFilterField: "neeto-filters-name-filter",
2454
- neetoFilterNameBlock: "neeto-filters-name-block",
2455
- roleSelectContainer: "role-select-container-wrapper",
2456
- filterButton: "neeto-filters-toggle-btn",
2457
- filtersClearButton: "neeto-filters-clear-btn",
2458
- filterDoneButton: "neeto-filters-done-btn",
2459
- filteredMembersCount: "ntm-filtered-members-count",
2460
- allMenubarBlock: "ntm-members-menubar-all-block",
2461
- filtersEmailFilter: "neeto-filters-email-filter",
2462
- paneModalCrossIcon: "neeto-filters-close-button",
2463
- searchTermBlock: "neeto-filters-search-term-block",
2464
- categoriesFilter: "neeto-filters-categories-filter",
2465
- filtersSegmentName: "neeto-filters-segment-name",
2466
- activeSelectContainer: "neeto-filters-status-filter",
2467
- neetoFiltersFilter: (filterName) => `neeto-filters-${hyphenate(filterName)}-filter`,
2468
- filtersTermBlock: (filterType = "search-term") => `neeto-filters-${hyphenate(filterType)}-block`,
2469
- dateRange: (filterName) => `neeto-filters-${hyphenate(filterName)}-date-range`,
2470
- segmentLabel: (label) => `neeto-filters-segment-block-${hyphenate(label)}`,
2471
- };
2472
-
2473
- const HELP_CENTER_SELECTORS = {
2474
- helpMenuBtn: "help-menu-button",
2475
- helpButton: "help-button",
2476
- documentationButton: "help-link-help-articles-button",
2477
- keyboardShortcutButton: "help-link-keyboard-shortcut-button",
2478
- chatButton: "help-link-live-chat-button",
2479
- whatsNewButton: "help-link-engage-button",
2480
- whatsNewWidgetInfo: "h1",
2481
- whatsNewWidgetCloseButton: ".ne-widget-header__btn",
2482
- keyboardShortcutPaneHeading: "keyboard-shortcuts-pane-title",
2483
- keyboardShortcutPaneCrossIcon: "keyboard-shortcuts-pane-close-button",
2484
- statusButton: "help-link-status-button",
2485
- communityButton: "help-link-community-button",
2486
- subscriptionPlan: "subscription-plan",
2487
- };
2488
-
2489
- const NEETO_IMAGE_UPLOADER_SELECTORS = {
2490
- libraryImageCard: "library-image-card",
2491
- imageUploaderWrapper: "image-uploader-wrapper",
2492
- browseText: "neeto-image-uploader-browse-text",
2493
- fileInput: "neeto-image-uploader-file-input",
2494
- uploadedImage: "uploaded-image",
2495
- uploadNewAsset: "upload-new-asset",
2496
- basicImageUploaderRemoveButton: "basic-image-uploader-remove-button",
2497
- removeButton: "image-uploader-remove-button",
2498
- openImageLibraryButton: "image-uploader-open-image-library-button",
2499
- openAssetLibraryButton: "open-asset-library-button",
2500
- imageEditorBackButton: "image-editor-back-button",
2501
- aspectRatioWidthInput: "aspect-ratio-width-input",
2502
- aspectRatioHeightInput: "aspect-ratio-height-input",
2503
- cropSubmitButton: "neeto-image-uploader-crop-submit-button",
2504
- restrictionMessage: "neeto-image-uploader-restriction-message",
2505
- progressBar: "neeto-image-uploader-progress-bar",
2506
- myImagesTab: "neeto-image-uploader-my-images-tab",
2507
- unsplashTab: "neeto-image-uploader-unsplash-tab",
2508
- nthLibraryImage: (index) => `niu-library-image-${index}`,
2509
- nthUnsplashImage: (index) => `niu-unsplash-image-${index}`,
2510
- unsplashSearchInput: "niu-unsplash-image-picker-search-input",
2511
- imageEditorUploadedImage: "image-editor-uploaded-image",
2512
- selectOriginalImageSwitch: "select-original-image-switch",
2513
- lockAspectRatioSwitch: "lock-aspect-ratio-switch",
2514
- widthInputField: "width-input-field",
2515
- heightInputField: "height-input-field",
2516
- };
2517
-
2518
- const INTEGRATION_SELECTORS = {
2519
- integrationCard: (integration) => `${integration}-integration-card`,
2520
- connectButton: "connect-button",
2521
- integrationStatusTag: "integration-status-tag",
2522
- disconnectButton: "disconnect-button",
2523
- manageButton: "manage-button",
2524
- integrationConnectedTag: "integration-connected-tag",
2525
- };
2526
-
2527
- const GOOGLE_LOGIN_SELECTORS = {
2528
- totpNext: "#totpNext",
2529
- form: "form",
2530
- totpChallengeSelector: '[data-challengeid="2"]',
2531
- signOutFrameLocator: 'iframe[name="account"]',
2532
- };
2533
- const GOOGLE_ANALYTICS_SELECTORS = {
2534
- gaCode: "google-analytics-code-input-field",
2535
- };
2536
- const GOOGLE_SHEETS_SELECTORS = {
2537
- iframe: 'iframe[title="Content"]',
2538
- };
2539
-
2540
- const MICROSOFT_LOGIN_SELECTORS = {
2541
- acceptButton: '[data-report-event="Signin_Submit"]',
2542
- cancelButton: 'input[type="button"]',
2543
- signInProfileIcon: "#mectrl_headerPicture",
2544
- emailInput: '[type="email"]',
2545
- placeholder: ".placeholderInnerContainer",
2546
- dropdownMenu: (appName) => `button[aria-label*='${appName}app']`,
2547
- };
2548
-
2549
- const dataQa = (value) => `[data-qa='${value}']`;
2550
- const SLACK_SELECTORS = {
2551
- messageContainer: dataQa("message_container"),
2552
- loginEmail: dataQa("login_email"),
2553
- loginPassword: dataQa("login_password"),
2554
- signInButton: dataQa("signin_button"),
2555
- teamPicketButtonContent: dataQa("oauth-team-picker-button-content"),
2556
- redirectOpenInBrowser: dataQa("ssb_redirect_open_in_browser"),
2557
- workspaceActionsButton: dataQa("workspace_actions_button"),
2558
- teamMenuTrigger: dataQa("team-menu-trigger"),
2559
- menuItemButton: "menu_item_button",
2560
- threadsFlexpane: "threads_flexpane",
2561
- replyBar: "reply_bar",
2562
- markdownElement: "bk_markdown_element",
2563
- virtualListItem: "virtual-list-item",
2564
- channelItems: '[role="treeitem"][data-qa="virtual-list-item"]',
2565
- installButton: dataQa("oauth_submit_button"),
2566
- };
2567
- const SLACK_DATA_QA_SELECTORS = {
2568
- sectionHeadingButton: "section_heading_button__channels",
2569
- coachMarkCloseButton: "coachmark-close-button",
2570
- messagePaneBannerCloseIcon: "message_pane_banner_close_icon",
2571
- permissionBannerCloseIcon: "banner_close_btn",
2572
- channelSectionSubmenuCreate: "channel_section_submenu_create",
2573
- channelSectionMenuCreateChannel: "channel_section_menu__create_channel",
2574
- skModalContent: "sk-modal-content",
2575
- infiniteSpinner: "infinite-spinner",
2576
- channelNameOptionsList: "channel-name-options-list",
2577
- channelNameInput: "channel-name-input",
2578
- createChannelNextButton: "create-channel-next-button",
2579
- inviteToWorkspaceSkipButton: "invite_to_workspace_skip_button",
2580
- menuItems: "menu_items",
2581
- channelDetailsModal: "channel_details_modal",
2582
- channelDetailsSettingsTab: "channel_details_settings_tab",
2583
- };
2584
-
2585
- const TWILIO_SELECTORS = {
2586
- sidField: "sid-input-field",
2587
- authTokenField: "auth-token-input-field",
2588
- };
2589
-
2590
- const ZAPIER_SELECTORS = {
2591
- zapTriggerStep: (zapId) => `[data-testid='step-node-${zapId}']`,
2592
- zapAccountSubstep: "[data-testid='substep-Account']",
2593
- zapOpenSubstepContainer: "[data-testid='open-sub-step-container']",
2594
- modal: "[data-testid='Modal']",
2595
- spinner: "spinner",
2596
- skeletonBlock: "[data-testid='SkeletonBlock']",
2597
- accountsLoader: "[data-testid='accounts-loader']",
2598
- floatingBox: "floating-box",
2599
- connection: "[data-testid='Connection']",
2600
- deleteConnectionModal: "[data-testid='DeleteAuthModal-root']",
2601
- deleteConnectionDropdownButton: "[data-testid='connection-list-item-dropdown-item-Delete']",
2602
- usageAmounts: "css=[class$=UsageBar__amounts]",
2603
- universalSidebar: "[data-testid='universalSidebar']",
2604
- sidebarFooter: "css=[class$=InAppSidebarFooter__footerWrapper]",
2605
- contextualSideBar: "[data-testid='contextual-sidebar']",
2606
- iconContainer: "[data-testid='iconContainer']",
2607
- deleteApiButton: "delete-apikey-button",
2608
- zapierSubLink: "zapier-sub-link",
2609
- navbar: "top-nav-test-id",
2610
- authTitle: "auth-title",
2611
- publishButton: "publish-button-wrapper",
2612
- panelFooter: "#details-panel-footer",
2613
- zapToggle: "zap-toggle",
2614
- stepBlock: `step-node-${process.env.ZAP_ID}`,
2615
- universalTopbar: "universalTopbar",
2616
- accountsMenu: "accounts-menu-summary",
2617
- zapToggleCheckbox: "input[type='checkbox']",
2618
- };
2619
-
2620
- const LOGIN_SELECTORS = {
2621
- appleAuthenticationButton: "apple-authentication-button",
2622
- emailTextField: "login-email-text-field",
2623
- loginAsOliverBtn: "login-as-oliver-btn",
2624
- googleAuthenticationButton: "google-authentication-button",
2625
- githubAuthenticationButton: "github-authentication-button",
2626
- loginViaEmailButton: "login-via-email-button",
2627
- passwordTextField: "login-password-text-field",
2628
- rememberMeCheckBox: "login-remember-me-check-box",
2629
- submitButton: "login-submit-button",
2630
- twitterAuthenticationButton: "twitter-authentication-button",
2631
- authenticatorAppOtpInput: "authenticator-app-otp-login-code-input",
2632
- enterOtpInputError: "enter-otp-input-error",
2633
- authenticatorAppLaterButton: "authenticator-app-promo-later-button",
2634
- };
2374
+ waitForSheetClose = () => expect(this.page.getByTestId(COMMON_SELECTORS.sheetWrapper)).toHaveCount(0, { timeout: 10_000 });
2375
+ verifyFieldValue = values => {
2376
+ const verifyEachFieldValue = ({ field, value, }) => expect(this.page.getByTestId(field)).toHaveValue(value);
2377
+ return Array.isArray(values)
2378
+ ? Promise.all(values.map(value => verifyEachFieldValue(value)))
2379
+ : verifyEachFieldValue(values);
2380
+ };
2381
+ searchAndVerify = async ({ searchTerm, searchInputSelector = COMMON_SELECTORS.inputField, countSelector, countText, }) => {
2382
+ await this.page.getByTestId(searchInputSelector).clear();
2383
+ await this.page
2384
+ .getByTestId(searchInputSelector)
2385
+ .pressSequentially(searchTerm, { delay: 100 });
2386
+ await expect(this.page.locator(COMMON_SELECTORS.tableSpinner)).toBeHidden({
2387
+ timeout: 10_000,
2388
+ });
2389
+ await expect(this.page.getByTestId(NEETO_FILTERS_SELECTORS.searchTermBlock)).toBeVisible();
2390
+ await this.waitForPageLoad();
2391
+ await expect(this.page.getByRole("cell", { name: searchTerm })).toBeVisible();
2392
+ await expect(this.page.getByTestId(countSelector)).toContainText(countText);
2393
+ };
2394
+ uploadImage = async (localImagePath) => {
2395
+ const { imageName, imagePath } = getImagePathAndName(localImagePath);
2396
+ await this.page
2397
+ .getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.browseText)
2398
+ .click();
2399
+ await this.page
2400
+ .getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.fileInput)
2401
+ .setInputFiles(imagePath);
2402
+ await expect(this.page.getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.uploadedImage)).toHaveAttribute("src", new RegExp(imageName), { timeout: 20_000 });
2403
+ };
2404
+ uploadFileViaDispatch = async ({ fileNameWithType, assetsPath = "../../../e2e/assets/", dispatchEvent = "drop", droppableZone = this.page.getByTestId(COMMON_SELECTORS.fileUploadBody), }) => {
2405
+ const filePath = path__default.join(import.meta.dirname, `${assetsPath}/${fileNameWithType}`);
2406
+ const buffer = readFileSync(filePath).toString("base64");
2407
+ const dataTransfer = await droppableZone.evaluateHandle((_, { buffer, fileNameWithType }) => {
2408
+ const dataTransfer = new DataTransfer();
2409
+ const fileName = fileNameWithType.split("/")?.[1];
2410
+ const hexString = Uint8Array.from(atob(buffer), c => c.charCodeAt(0));
2411
+ const file = new File([hexString], fileName);
2412
+ dataTransfer.items.add(file);
2413
+ return dataTransfer;
2414
+ }, { buffer, fileNameWithType });
2415
+ await droppableZone.dispatchEvent(dispatchEvent, { dataTransfer });
2416
+ };
2417
+ hoverOnElement = (triggerElement, customPageContext = this.page) => expect(async () => {
2418
+ await triggerElement.hover();
2419
+ await expect(customPageContext.getByTestId(COMMON_SELECTORS.tooltip)).toBeVisible({ timeout: 3_000 });
2420
+ }).toPass({ timeout: 10_000 });
2421
+ verifyTooltip = async ({ triggerElement, content, customPageContext = this.page, }) => {
2422
+ await this.hoverOnElement(triggerElement, customPageContext);
2423
+ const resolvedContent = typeof content === "function" ? await content() : content;
2424
+ await expect(customPageContext.getByTestId(COMMON_SELECTORS.tooltip)).toContainText(resolvedContent);
2425
+ await this.hideTooltip(triggerElement, customPageContext);
2426
+ };
2427
+ verifyHelpPopover = async ({ triggerElement = this.page.getByTestId(COMMON_SELECTORS.helpPopoverButton), title, content, helpURL, customPageContext = this.page, }) => {
2428
+ await triggerElement.hover();
2429
+ const titleLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverTitle);
2430
+ const descLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverDesc);
2431
+ const linkLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverLinkButton);
2432
+ const popoverContentLocator = title
2433
+ ? titleLocator
2434
+ : content
2435
+ ? descLocator
2436
+ : linkLocator;
2437
+ title && (await expect(titleLocator).toHaveText(title));
2438
+ content && (await expect(descLocator).toContainText(content));
2439
+ helpURL &&
2440
+ (await Promise.all([
2441
+ this.assertHelpURLIsValid(helpURL),
2442
+ expect(linkLocator).toHaveAttribute("href", new RegExp(helpURL, "i")),
2443
+ ]));
2444
+ await this.hidePopoverContent(popoverContentLocator, customPageContext);
2445
+ };
2446
+ assertHelpURLIsValid = (helpURL) => expect(async () => {
2447
+ const response = await this.request.get(helpURL, { timeout: 15_000 });
2448
+ await expect(response).toBeOK();
2449
+ }).toPass({ timeout: 45_000, intervals: [3_000] });
2450
+ verifyHelpText = async (helpURL) => {
2451
+ const isNoDataTitleHidden = await this.page
2452
+ .getByTestId(COMMON_SELECTORS.noDataTitleV2)
2453
+ .isHidden();
2454
+ if (isNoDataTitleHidden)
2455
+ return;
2456
+ const helpLink = this.page
2457
+ .getByTestId(COMMON_SELECTORS.noDataHelpTextV2)
2458
+ .getByRole("link")
2459
+ .or(this.page
2460
+ .getByTestId(COMMON_SELECTORS.noDataDescriptionV2)
2461
+ .getByRole("link"));
2462
+ await Promise.all([
2463
+ this.assertHelpURLIsValid(helpURL),
2464
+ expect(helpLink).toHaveAttribute("href", new RegExp(helpURL, "i")),
2465
+ ]);
2466
+ };
2467
+ verifySearchTermBlock = async (searchTerm) => {
2468
+ const filtersSearchTermBlock = this.page.getByTestId(NEETO_FILTERS_SELECTORS.filtersTermBlock());
2469
+ if (searchTerm) {
2470
+ const textContent = await filtersSearchTermBlock?.textContent();
2471
+ textContent?.includes("..")
2472
+ ? await this.verifyTooltip({
2473
+ triggerElement: filtersSearchTermBlock,
2474
+ content: searchTerm,
2475
+ })
2476
+ : await expect(filtersSearchTermBlock).toContainText(searchTerm);
2477
+ }
2478
+ else {
2479
+ await expect(filtersSearchTermBlock).toBeHidden();
2480
+ }
2481
+ };
2482
+ saveChanges = ({ isPane = false, customPageContext = this.page, closeAfterVerification = true, toastMessage = "", } = {}) => {
2483
+ const pane = customPageContext.getByTestId(COMMON_SELECTORS.sheetWrapper);
2484
+ const baseLocator = isPane ? pane : customPageContext;
2485
+ return Promise.all([
2486
+ this.clickButtonAndAwaitLoad({
2487
+ locator: baseLocator.getByTestId(COMMON_SELECTORS.saveChangesButton),
2488
+ timeout: 10_000,
2489
+ }),
2490
+ // eslint-disable-next-line playwright/missing-playwright-await
2491
+ isPane && expect(pane).toBeHidden({ timeout: 10_000 }),
2492
+ this.verifyToast({
2493
+ closeAfterVerification,
2494
+ customPageContext,
2495
+ message: toastMessage,
2496
+ timeout: 20_000,
2497
+ }),
2498
+ ]);
2499
+ };
2500
+ hideTooltip = async (triggerElement, customPageContext = this.page) => {
2501
+ const boundingBox = await triggerElement.boundingBox();
2502
+ if (!boundingBox)
2503
+ failTest("Trigger element bounding box not found");
2504
+ const { x, y, width, height } = boundingBox;
2505
+ const moves = [
2506
+ [x + width + 10, y],
2507
+ [x, y + height + 10],
2508
+ [x - 10, y],
2509
+ [x, y - 10],
2510
+ ];
2511
+ const tooltip = customPageContext.getByTestId(COMMON_SELECTORS.tooltip);
2512
+ await expect(async () => {
2513
+ for (const [moveX, moveY] of moves) {
2514
+ await customPageContext.mouse.move(moveX, moveY);
2515
+ if ((await tooltip.count()) === 0)
2516
+ break;
2517
+ }
2518
+ await expect(tooltip).toHaveCount(0);
2519
+ }).toPass({ timeout: 30_000 });
2520
+ };
2521
+ hidePopoverContent = async (contentLocator, customPageContext = this.page) => {
2522
+ await customPageContext.mouse.move(0, 0);
2523
+ await expect(contentLocator).toBeHidden();
2524
+ };
2525
+ verifyBreadcrumbs = async (titlesAndRoutes) => {
2526
+ const header = this.page.getByTestId(COMMON_SELECTORS.breadcrumbHeader);
2527
+ const titles = pluck("title", titlesAndRoutes);
2528
+ const [last, ...links] = titlesAndRoutes.toReversed();
2529
+ await Promise.all([
2530
+ expect(header).toContainText(titles),
2531
+ expect(header).toHaveCount(titlesAndRoutes.length),
2532
+ expect(header.getByRole("link", { name: last?.title, exact: true })).toHaveAttribute("aria-disabled", "true"),
2533
+ ...links.map(({ title, route }) => expect(header.getByRole("link", { name: title, exact: true })).toHaveAttribute("href", route)),
2534
+ ]);
2535
+ };
2536
+ uploadFileViaDispatchV2 = async ({ droppableZone = this.page.getByTestId(COMMON_SELECTORS.fileUploadBody), dispatchEvent = "drop", timeout = 45_000, file, }) => {
2537
+ const serializedFile = await serializeFileForBrowser(file);
2538
+ const dataTransfer = await droppableZone.evaluateHandle((_, { name, type, buffer, lastModified }) => {
2539
+ const uint8Array = new Uint8Array(buffer);
2540
+ const file = new File([uint8Array], name, { type, lastModified });
2541
+ const dataTransfer = new DataTransfer();
2542
+ dataTransfer.items.add(file);
2543
+ return dataTransfer;
2544
+ }, serializedFile, { timeout });
2545
+ try {
2546
+ await droppableZone.dispatchEvent(dispatchEvent, { dataTransfer });
2547
+ }
2548
+ finally {
2549
+ await dataTransfer.dispose();
2550
+ }
2551
+ };
2552
+ verifyUnsavedChangesModal = async (shouldLeavePage = false) => {
2553
+ const alertBox = this.page.getByTestId(COMMON_SELECTORS.alertBox);
2554
+ await Promise.all([
2555
+ expect(this.page.getByTestId(COMMON_SELECTORS.alertModalMessage)
2556
+ // TODO: Use translation for this once https://github.com/neetozone/neeto-atoms/issues/423 is resolved
2557
+ ).toHaveText("Are you sure you want to leave? All unsaved changes will be lost."),
2558
+ expect(this.page.getByTestId(COMMON_SELECTORS.alertTitle)).toHaveText("You have unsaved changes"),
2559
+ ]);
2560
+ const actionButton = shouldLeavePage
2561
+ ? alertBox.getByTestId(COMMON_SELECTORS.alertCancelButton)
2562
+ : alertBox
2563
+ .getByTestId(COMMON_SELECTORS.dialogCloseButton)
2564
+ .or(alertBox.getByTestId(COMMON_SELECTORS.alertModalCrossIcon));
2565
+ await actionButton.click();
2566
+ await expect(alertBox).toBeHidden();
2567
+ };
2568
+ setSliderValue = async ({ parentLocator = this.page, valueAsPercent, startFromCenter = false, }) => {
2569
+ const sliderLocator = parentLocator.locator(COMMON_SELECTORS.slider);
2570
+ await expect(sliderLocator).toBeVisible();
2571
+ await sliderLocator.evaluate(node => node.scrollIntoView({ behavior: "instant", block: "center" }));
2572
+ const sliderBoundingBox = await sliderLocator.boundingBox();
2573
+ let targetX = sliderBoundingBox.width * valueAsPercent;
2574
+ if (startFromCenter)
2575
+ targetX = targetX / 2;
2576
+ let sliderSourceX = sliderBoundingBox.x;
2577
+ if (startFromCenter)
2578
+ sliderSourceX += sliderBoundingBox.width / 2;
2579
+ const sliderSourceY = sliderBoundingBox.y + sliderBoundingBox.height / 2;
2580
+ await this.page.mouse.move(sliderSourceX, sliderSourceY, { steps: 5 });
2581
+ await this.page.mouse.down();
2582
+ await this.page.mouse.move(sliderSourceX + targetX, sliderSourceY, {
2583
+ steps: 5,
2584
+ });
2585
+ await this.page.mouse.up();
2586
+ };
2587
+ assertCardDetails = ({ cardLocator, title, description, }) => Promise.all([
2588
+ expect(cardLocator.getByTestId(ADMIN_PANEL_SELECTORS.settingsItemHeading)).toHaveText(title),
2589
+ expect(cardLocator.getByTestId(ADMIN_PANEL_SELECTORS.settingsItemDescription)).toHaveText(description),
2590
+ expect(this.page.getByTestId(COMMON_SELECTORS.sidebarSubLink(title))).toHaveCSS("background-color", COLOR.transparent),
2591
+ ]);
2592
+ executeWithErrorHandling = async (asyncFn) => {
2593
+ try {
2594
+ const result = await asyncFn();
2595
+ return { success: true, result };
2596
+ }
2597
+ catch (error) {
2598
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
2599
+ return { success: false, error: errorInstance.message };
2600
+ }
2601
+ };
2602
+ clickButtonAndAwaitLoad = async ({ locator, timeout, }) => {
2603
+ await locator.click({ timeout });
2604
+ await expect(locator.getByTestId(COMMON_SELECTORS.uiSpinner)).toBeHidden({
2605
+ timeout: 35_000,
2606
+ });
2607
+ };
2608
+ toggleElement = ({ locator, shouldBeChecked = true }) => expect(async () => {
2609
+ // Callers often pass an atoms Switch's wrapper (`<prefix>-switch`); the checkable control is the nested `nui-switch-item`.
2610
+ const switchItem = locator.getByTestId(COMMON_SELECTORS.switchLabel);
2611
+ const target =
2612
+ // eslint-disable-next-line playwright/no-nth-methods
2613
+ (await switchItem.count()) > 0 ? switchItem.first() : locator;
2614
+ (await target.isChecked()) !== shouldBeChecked && (await target.click());
2615
+ await expect(target).toBeChecked({ checked: shouldBeChecked });
2616
+ }).toPass({ timeout: 15_000 });
2617
+ // Polls the editor's own state, which is what the next key press acts on.
2618
+ // The DOM selection is not proof: ProseMirror re-applies its stored
2619
+ // selection shortly after a programmatic focus, undoing an early collapse.
2620
+ waitForSelectionToCollapse = (timeout = 2_000) => expect
2621
+ .poll(() => this.page.evaluate(contentField => {
2622
+ const editor = document.activeElement?.closest(`[data-testid="${contentField}"]`)?.editor;
2623
+ if (!editor)
2624
+ return "no focused editor";
2625
+ const { selection } = editor.state;
2626
+ return selection.empty
2627
+ ? "collapsed"
2628
+ : `${selection.from}-${selection.to}`;
2629
+ }, NEETO_EDITOR_SELECTORS.contentField), {
2630
+ timeout,
2631
+ intervals: [50, 100, 250],
2632
+ message: "Editor selection did not collapse",
2633
+ })
2634
+ .toBe("collapsed");
2635
+ moveCursorAtBottom = async () => {
2636
+ const isMacOS = os.platform() === "darwin";
2637
+ const rightArrowKey = isMacOS ? "Meta+ArrowRight" : "End";
2638
+ const downArrowKey = isMacOS ? "Meta+ArrowDown" : "PageDown";
2639
+ await expect(async () => {
2640
+ await this.page.keyboard.press(rightArrowKey);
2641
+ await this.page.keyboard.press(rightArrowKey);
2642
+ await this.page.keyboard.press(downArrowKey);
2643
+ await this.waitForSelectionToCollapse();
2644
+ }).toPass({ timeout: 15_000 });
2645
+ await this.page.keyboard.press("Enter");
2646
+ };
2647
+ }
2635
2648
 
2636
- const ONBOARDING_SELECTORS = {
2637
- welcomeTitle: "onboarding-welcome-title",
2638
- welcomeDescription: "onboarding-welcome-description",
2639
- getStartedBtn: "onboarding-welcome-button",
2640
- doLaterBtn: "onboarding-do-later-button",
2641
- helpBtn: "onboarding-help-button",
2642
- continueBtn: "onboarding-continue-button",
2643
- congratulationsTitle: "onboarding-congratulations-title",
2644
- congratulationsDescription: "onboarding-congratulations-description",
2645
- congratulationsBtn: "onboarding-congratulations-button",
2649
+ const authenticateUser = async ({ page, loginPath, email, }) => {
2650
+ const organizationPage = new OrganizationPage(page, new CustomCommands(page, page.request));
2651
+ await (email
2652
+ ? organizationPage.login({ email, path: loginPath })
2653
+ : organizationPage.login({
2654
+ via: LOGIN_STRATEGIES.oliver,
2655
+ path: loginPath,
2656
+ }));
2657
+ await expect(page.getByTestId(COMMON_SELECTORS.floatingActionMenuButton)).toBeVisible({ timeout: 60_000 });
2646
2658
  };
2647
-
2648
- const PROFILE_SECTION_SELECTORS = {
2649
- profileSectionButton: "profile-section",
2650
- profilePopup: "profile-popup",
2651
- profileExpandMenuBtn: "profile-expand-menu-button",
2652
- profileMoreDropdownButton: "profile-more-dropdown-button",
2653
- myProfileButton: "profile-my-profile-button",
2654
- updateEmailMenuBtn: "update-email-menu-button",
2655
- workspaceDisplay: "workspace-display",
2656
- profileOrganizationSettingsButton: "profile-organization-settings-button",
2657
- logoutButton: "profile-logout-button",
2658
- neetoAuthLink: "ntm-visit-auth-button",
2659
- profileSidebarCancelButton: "ntm-profile-cancel-button",
2660
- profileAvatar: "profile-avatar",
2661
- actionHeaderUserName: "floating-action-menu-header-user-name",
2662
- actionHeaderUserEmail: "floating-action-menu-header-user-email",
2663
- submitButton: "ntm-profile-submit-button",
2664
- editBtn: "edit-basic-info-menu-button",
2665
- firstNameTextField: "profile-first-name-text-field",
2666
- lastNameTextField: "profile-last-name-text-field",
2667
- manageBillingAndSubscriptionsButton: "manage-billing-subscriptions-menu-button",
2668
- cancelButton: "profile-cancel-button",
2669
- profileSubmitBtn: "profile-submit-button",
2670
- editBasicInfoMenuBtn: "edit-basic-info-menu-button",
2671
- editBasicInfoBtn: "edit-basic-info-button",
2672
- phoneNumberTxtField: "profile-phonenumber-text-field",
2673
- timezoneBtn: "timezone-selector-select-button",
2674
- timezoneSearchBox: "timezone-selector-search-box",
2675
- nameField: "profile-full-name-field",
2676
- emailField: "profile-email-field",
2677
- firstNameField: "profile-first-name-field",
2678
- lastNameField: "profile-last-name-field",
2679
- phoneNumberField: "profile-phone-number-field",
2680
- countryField: "profile-country-field",
2681
- timeZoneField: "profile-time-zone-field",
2682
- timeFormatField: "profile-preferred-time-format-field",
2683
- dateFormatField: "profile-preferred-date-format-field",
2684
- firstNameInputError: "first-name-input-error",
2685
- timeZoneSelect: "profile-time-zone-select",
2686
- lastNameInputError: "last-name-input-error",
2687
- phoneNumberInputError: "phone-number-input-error",
2688
- imageUploadBtn: "profile-image-upload-button",
2689
- profileImageDropdownButton: "profile-image-dropdown-button",
2690
- imageRemoveBtn: "profile-image-remove-button",
2659
+ const login = async ({ page, loginPath = "/", }) => {
2660
+ if (shouldSkipSetupAndTeardown() || !IS_DEV_ENV)
2661
+ return;
2662
+ await authenticateUser({ page, loginPath });
2663
+ await saveStorageState(page, { isLoggedIn: "true" });
2691
2664
  };
2692
2665
 
2693
- const NEETO_SEO_SELECTORS = {
2694
- configureButton: "neeto-seo-configure-button",
2666
+ const REVIEW_APP_WAKE_TIMEOUT = 10 * 60_000;
2667
+ const REVIEW_APP_POLL_INTERVAL = 10_000;
2668
+ const REVIEW_APP_REQUEST_TIMEOUT = 20_000;
2669
+ // The host is read on each call so that a product importing the package outside
2670
+ // the review environment never trips the guard.
2671
+ const reviewAppHost = () => requireEnv("REVIEW_APP_HOST");
2672
+ const isReviewAppServing = async () => {
2673
+ try {
2674
+ const response = await fetch(`https://${reviewAppHost()}/?_hs=${Date.now()}`, {
2675
+ headers: { Accept: "text/html", "X-Downtime-Poll": "1" },
2676
+ redirect: "manual",
2677
+ signal: AbortSignal.timeout(REVIEW_APP_REQUEST_TIMEOUT),
2678
+ });
2679
+ return response.status < 400 && !response.headers.has("x-neeto-downtime");
2680
+ }
2681
+ catch {
2682
+ return false;
2683
+ }
2695
2684
  };
2696
-
2697
- const SIGNUP_SELECTORS = {
2698
- emailTextField: "signup-email-text-field",
2699
- firstNameTextField: "signup-profile-first-name-text-field",
2700
- lastNameTextField: "signup-profile-last-name-text-field",
2701
- organizationNameTextField: "signup-organization-name-text-field",
2702
- organizationSubmitButton: "signup-organization-submit-button",
2703
- organizationSyncContainer: "organization-sync-container",
2704
- otpTextBox: "otpinput-otp-number",
2705
- profileSubmitButton: "signup-profile-submit-button",
2706
- signupViaEmailButton: "signup-via-email-button",
2707
- submitButton: "signup-email-submit-button",
2708
- subdomainNameTextField: "signup-organization-subdomain-text-field",
2709
- subdomainAvailabilityMsg: "subdomain-availability-message",
2710
- subdomainError: "subdomain-input-error",
2711
- tryFreeButton: "neeto-auth-signup-link",
2712
- unregisteredEmailError: "unregistered-email-error",
2713
- organization: (organizationName) => `${organizationName}-organization-item`,
2685
+ const wakeReviewApp = async () => {
2686
+ try {
2687
+ await fetch(`https://${reviewAppHost()}/`, {
2688
+ headers: { Accept: "text/html" },
2689
+ signal: AbortSignal.timeout(REVIEW_APP_REQUEST_TIMEOUT),
2690
+ });
2691
+ }
2692
+ catch {
2693
+ // The wake request is fire-and-forget; readiness is polled separately.
2694
+ }
2714
2695
  };
2715
-
2716
- const TAB_SELECTORS = {
2717
- configureTab: "configure-tab",
2718
- buildTab: "build-tab",
2719
- themeTab: "theme-tab",
2720
- shareTab: "share-tab",
2721
- submissionsTab: "submissions-tab",
2722
- paymentsTab: "payments-tab",
2723
- settingsTab: "settings-tab",
2696
+ const reviewAppBaseURL = (subdomain = CREDENTIALS.subdomainName) => `https://${subdomain}.${reviewAppHost()}`;
2697
+ const waitForReviewApp = () => {
2698
+ const host = reviewAppHost();
2699
+ return expect(async () => {
2700
+ const isServing = await isReviewAppServing();
2701
+ !isServing && (await wakeReviewApp());
2702
+ expect(isServing, `Review app ${host} is not up yet`).toBe(true);
2703
+ }).toPass({
2704
+ timeout: REVIEW_APP_WAKE_TIMEOUT,
2705
+ intervals: [REVIEW_APP_POLL_INTERVAL],
2706
+ });
2724
2707
  };
2725
-
2726
- const TABLE_SELECTORS = {
2727
- freezeUnfreezeButton: "freeze-unfreeze-column-menu-button",
2728
- ascendingButton: "ascending-column-menu-button",
2729
- descendingButton: "descending-column-menu-button",
2730
- hideButton: "hide-column-menu-button",
2731
- columnHeaderTitle: (columnName) => `${hyphenate(columnName)}-header-title`,
2732
- columnMenuButton: "column-menu-button",
2733
- columnInfoIcon: "column-info-icon",
2734
- columnMenuBtn: (action) => `${action}-column-menu-button`,
2735
- moveColumnBtn: (position) => `move-column-${position}-menu-button`,
2708
+ const initializeReviewAppCredentials = () => {
2709
+ if (shouldSkipSetupAndTeardown())
2710
+ return;
2711
+ const { firstName, lastName, name, email, subdomainName } = CREDENTIALS;
2712
+ writeDataToFile(JSON.stringify({
2713
+ user: {
2714
+ firstName,
2715
+ lastName,
2716
+ email,
2717
+ subdomainName,
2718
+ businessName: subdomainName,
2719
+ currentUserName: name,
2720
+ otp: 111111,
2721
+ domain: reviewAppHost(),
2722
+ },
2723
+ }, null, 2));
2736
2724
  };
2737
-
2738
- const THEMES_SELECTORS = {
2739
- colorPickerDropdownContainer: (colorHex) => `${colorHex}-dropdown-container`,
2740
- baseThemeStyle: (styleType) => `theme-style-${hyphenate(styleType)}`,
2741
- introPageThemeStyle: (styleType) => `intro-page-theme-style-${hyphenate(styleType)}`,
2742
- themeSwitcherButton: "theme-switcher-button",
2743
- themeSwitcherDarkButton: "theme-switcher-dark-button",
2725
+ const loginToReviewApp = async ({ page, loginPath = "/login", }) => {
2726
+ if (shouldSkipSetupAndTeardown())
2727
+ return;
2728
+ await waitForReviewApp();
2729
+ await authenticateUser({ page, loginPath });
2730
+ await saveStorageState(page, { isLoggedIn: "true" });
2744
2731
  };
2732
+ const reviewAppOrganizationOptions = ({ subdomain = CREDENTIALS.subdomainName, loginPath = "/login", } = {}) => IS_REVIEW_ENV
2733
+ ? {
2734
+ baseURL: reviewAppBaseURL(subdomain),
2735
+ storageState: async ({ browser, baseURL }, use) => {
2736
+ const context = await browser.newContext({
2737
+ ...EMPTY_STORAGE_STATE,
2738
+ baseURL,
2739
+ });
2740
+ try {
2741
+ await authenticateUser({
2742
+ page: await context.newPage(),
2743
+ loginPath,
2744
+ });
2745
+ await use(await context.storageState());
2746
+ }
2747
+ finally {
2748
+ await context.close();
2749
+ }
2750
+ },
2751
+ }
2752
+ : {};
2745
2753
 
2746
- const CHAT_WIDGET_SELECTORS = {
2747
- iframe: "#neetochat-iframe",
2748
- spinner: ".neeto-chat-widget-spinner",
2749
- helpButton: "help-button",
2750
- preChatEmailInput: "neeto-chat-widget-input",
2751
- preChatSubmitButton: "neeto-chat-widget-pre-chat-submit-btn",
2752
- chatBubble: "neeto-chat-widget-chat-message-bubble",
2753
- closeChat: "neeto-chat-widget-close-btn",
2754
- chatQuestionHeader: "chat-question-header",
2755
- openChat: "neeto-chat-widget-open-btn",
2756
- homeScreenSubtitle: "neeto-chat-widget-home-screen-subtitle",
2757
- };
2758
- const CHANGELOG_WIDGET_SELECTORS = {
2759
- changelogWrapper: ".ne-widget__wrapper",
2760
- closeButton: "ne-widget-close-btn",
2761
- publicUrlLink: "ne-widget-public-url",
2762
- };
2763
- const KEYBOARD_SHORTCUTS_SELECTORS = {
2764
- keyboardShortcutsPane: "keyboard-shortcuts-pane",
2765
- closePaneButton: "keyboard-shortcuts-pane-close-button",
2766
- hotKeyItem: "hotkey-item",
2754
+ const execCommand = (command) => execSync(command, { encoding: "utf8" }).trimEnd();
2755
+ const joinString = (string1, string2, string3 = "", separator = " ") => {
2756
+ if (string3 === "") {
2757
+ return string1 + separator + string2;
2758
+ }
2759
+ return string1 + separator + string2 + separator + string3;
2767
2760
  };
2768
-
2769
- const mimeTypeMap = {
2770
- csv: "text/csv",
2771
- avi: "video/x-msvideo",
2772
- doc: "application/msword",
2773
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2774
- flv: "video/x-flv",
2775
- html: "text/html",
2776
- mp3: "audio/mpeg",
2777
- mp4: "video/mp4",
2778
- mpg: "video/mpeg",
2779
- pdf: "application/pdf",
2780
- rtf: "application/rtf",
2781
- txt: "text/plain",
2782
- webm: "video/webm",
2783
- xls: "application/vnd.ms-excel",
2784
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2785
- wma: "audio/x-ms-wma",
2786
- zip: "application/zip",
2787
- jpg: "image/jpeg",
2788
- jpeg: "image/jpeg",
2789
- png: "image/png",
2790
- gif: "image/gif",
2791
- ico: "image/x-icon",
2792
- svg: "image/svg+xml",
2761
+ const readFileSyncIfExists = (path = STORAGE_STATE) => {
2762
+ try {
2763
+ return JSON.parse(fs.readFileSync(path, "utf8"));
2764
+ }
2765
+ catch {
2766
+ return {};
2767
+ }
2793
2768
  };
2794
- const serializeFileForBrowser = async (file) => {
2795
- const buffer = await file.arrayBuffer();
2796
- return {
2797
- name: file.name,
2798
- type: file.type,
2799
- lastModified: file.lastModified,
2800
- buffer: Array.from(new Uint8Array(buffer)),
2801
- };
2769
+ const getGlobalUserState = () => readFileSyncIfExists()?.user;
2770
+ const writeDataToFile = data => {
2771
+ try {
2772
+ fs.writeFileSync(STORAGE_STATE, data, "utf8");
2773
+ }
2774
+ catch (error) {
2775
+ console.log(error);
2776
+ }
2777
+ return true;
2802
2778
  };
2803
- const generateRandomFile = ({ sizeInKB, fileType, fileName = `sample.${fileType}`, }) => {
2804
- const mimeType = mimeTypeMap[fileType];
2805
- const byteArray = randomFillSync(new Uint8Array(sizeInKB * 1024));
2806
- const file = new File([byteArray], fileName, { type: mimeType });
2807
- return { file, fileName };
2779
+ const updateCredentials = ({ key, value }) => {
2780
+ const data = readFileSyncIfExists();
2781
+ data["user"][key] = value;
2782
+ return writeDataToFile(JSON.stringify(data));
2808
2783
  };
2809
- const readFileAsBrowserFile = ({ filePath, mimeType, }) => new File([readFileSync(filePath)], path__default.basename(filePath), {
2810
- type: mimeType,
2811
- });
2812
-
2813
- const getImagePathAndName = (localImagePath) => {
2814
- const imagePath = path__default.join(import.meta.dirname, localImagePath);
2815
- const imageName = path__default.basename(localImagePath, path__default.extname(localImagePath));
2816
- return { imagePath, imageName };
2784
+ const saveStorageState = async (page, credentials = {}) => {
2785
+ const { user = {} } = readFileSyncIfExists();
2786
+ await page.context().storageState({ path: STORAGE_STATE });
2787
+ const csrfTokenLocator = page.locator("[name='csrf-token']");
2788
+ const csrfToken = (await csrfTokenLocator.getAttribute("content")) ?? "";
2789
+ return writeDataToFile(JSON.stringify({
2790
+ ...readFileSyncIfExists(),
2791
+ user: { ...user, ...credentials, csrfToken },
2792
+ }, null, 2));
2817
2793
  };
2818
-
2819
- const TOAST_DEFAULT_MESSAGE = "👍";
2820
- class CustomCommands {
2821
- page;
2822
- t;
2823
- responses;
2824
- request;
2825
- baseURL;
2826
- csrfToken;
2827
- constructor(page, request, baseURL = process.env.BASE_URL) {
2828
- this.page = page;
2829
- this.responses = [];
2830
- this.request = request;
2831
- this.baseURL = baseURL;
2832
- this.t = getI18nInstance().t;
2794
+ const removeCredentialFile = () => {
2795
+ try {
2796
+ fs.existsSync(STORAGE_STATE) && fs.unlinkSync(STORAGE_STATE);
2833
2797
  }
2834
- initializeCsrfToken = async () => {
2835
- this.csrfToken =
2836
- this.page.url() === "about:blank"
2837
- ? getGlobalUserState()?.csrfToken
2838
- : await this.page
2839
- .locator("[name='csrf-token']")
2840
- .getAttribute("content");
2841
- return this.csrfToken;
2842
- };
2843
- blockExternalResources = (page = this.page) => Promise.all(THIRD_PARTY_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())));
2844
- blockInternalResources = (page = this.page) => Promise.all(APP_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())));
2845
- blockNonEssentialResourceTypes = (page = this.page) => page
2846
- .context()
2847
- .route("**/*", route => ["image", "stylesheet", "font"].includes(route.request().resourceType())
2848
- ? route.abort()
2849
- : route.fallback());
2850
- blockAllResources = (page = this.page) => Promise.all([
2851
- this.blockNonEssentialResourceTypes(page),
2852
- ...ALL_RESOURCES.map(pattern => page.context().route(pattern, route => route.abort())),
2853
- ]);
2854
- waitForFloatingMenu = (customPageContext = this.page) => expect(customPageContext.getByTestId(COMMON_SELECTORS.floatingActionMenuButton)).toBeVisible({ timeout: 30_000 });
2855
- interceptMultipleResponses = ({ responseUrl = "", responseStatus = 200, times = 1, baseUrl, customPageContext = this.page, timeout = 35_000, } = {}) => Promise.all([...new Array(times)].map(() => customPageContext.waitForResponse((response) => {
2856
- if (response.request().resourceType() === "xhr" &&
2857
- response.status() === responseStatus &&
2858
- response.url().includes(responseUrl) &&
2859
- response.url().startsWith(baseUrl ?? this.baseURL ?? "") &&
2860
- !this.responses.includes(response.headers()?.["x-request-id"])) {
2861
- this.responses.push(response.headers()?.["x-request-id"]);
2862
- return true;
2863
- }
2864
- return false;
2865
- }, { timeout })));
2866
- recursiveMethod = async (callback, condition, timeout, startTime, iteration) => {
2867
- if (Date.now() - timeout >= startTime) {
2868
- await callback();
2869
- return false;
2870
- }
2871
- else if (await condition()) {
2872
- return await callback();
2873
- }
2874
- const timeToWaitInSecs = iteration > 3 ? 10 : Math.pow(2, iteration);
2875
- await setTimeout$1(timeToWaitInSecs * 1000);
2876
- return await this.recursiveMethod(callback, condition, timeout, startTime, iteration + 1);
2877
- };
2878
- executeRecursively = async ({ callback, condition, timeout = 5000, }) => {
2879
- const startTime = Date.now();
2880
- return await this.recursiveMethod(callback, condition, timeout, startTime, 1);
2881
- };
2882
- verifyToast = async ({ message = "", toastType = "success", closeAfterVerification = true, timeout = 10_000, toastCloseTimeout = 10_000, customPageContext = this.page, } = {}) => {
2883
- const toastMessageLocator = customPageContext.getByTestId(COMMON_SELECTORS.toastMessage(toastType));
2884
- // Some products are still on the v1 (neetoui) Toastr, which renders the thumbs up icon and close button outside the message container.
2885
- const toastLocator = customPageContext
2886
- .locator(COMMON_SELECTORS.neetoUiToastr)
2887
- .filter({ has: toastMessageLocator })
2888
- .or(toastMessageLocator);
2889
- const filteredToastLocator = (isEmpty(message)
2890
- ? toastLocator
2891
- : toastLocator.filter({ hasText: message }))
2892
- // eslint-disable-next-line playwright/no-nth-methods
2893
- .first();
2894
- await expect(filteredToastLocator).toContainText(isEmpty(message) ? TOAST_DEFAULT_MESSAGE : message, { timeout });
2895
- if (!closeAfterVerification)
2896
- return;
2897
- const toastCloseButton = filteredToastLocator.getByTestId(COMMON_SELECTORS.toastCloseButton);
2898
- const buttonHandle = await toastCloseButton.elementHandle();
2899
- if (buttonHandle) {
2900
- await customPageContext.evaluate(button => {
2901
- button.dispatchEvent(new Event("click", { bubbles: true }));
2902
- }, buttonHandle);
2903
- await expect(toastCloseButton).toBeHidden({
2904
- timeout: toastCloseTimeout,
2905
- });
2906
- }
2907
- };
2908
- waitForPageLoad = async ({ visibilityTimeout = 35_000, customPageContext = this.page, waitForOption = "serial", } = {}) => {
2909
- await customPageContext.waitForLoadState();
2910
- const loaders = [
2911
- customPageContext.getByTestId(COMMON_SELECTORS.pageLoader),
2912
- customPageContext.getByTestId(COMMON_SELECTORS.uiSpinner),
2913
- ];
2914
- if (waitForOption === "serial") {
2915
- for (const loader of loaders) {
2916
- await expect(loader).toHaveCount(0, { timeout: visibilityTimeout });
2917
- }
2918
- return;
2919
- }
2920
- await Promise.all(loaders.map(loader => expect(loader).toHaveCount(0, { timeout: visibilityTimeout })));
2921
- };
2922
- apiRequest = async ({ url, failOnStatusCode = true, headers: additionalHeaders, body: data, method = "get", params = {}, timeout = 30_000, ...otherOptions }) => {
2923
- const csrfToken = this.csrfToken ?? (await this.initializeCsrfToken());
2924
- const requestOptions = {
2925
- failOnStatusCode,
2926
- timeout,
2927
- headers: {
2928
- ...additionalHeaders,
2929
- "accept-encoding": "gzip",
2930
- "x-csrf-token": csrfToken ?? "",
2931
- },
2932
- data,
2933
- ...otherOptions,
2934
- };
2935
- const formattedUrl = isEmpty(params)
2936
- ? url
2937
- : `${url}?${stringify(params, {
2938
- nestingSyntax: "js",
2939
- arrayRepeat: true,
2940
- arrayRepeatSyntax: "bracket",
2941
- })}`;
2942
- return await this.request[method](formattedUrl, requestOptions);
2943
- };
2944
- selectOptionFromDropdown = async ({ label = "nui", value, page = this.page, options: { visibilityTimeout = 5_000, textAssertionTimeout = 5_000, retryTimeout = 60_000, } = {}, }) => {
2945
- const menu = page.getByTestId(COMMON_SELECTORS.customDropDownMenu(label));
2946
- const optionByName = menu.getByRole("option", { name: value, exact: true });
2947
- const container = page.getByTestId(COMMON_SELECTORS.customSelectContainer(label));
2948
- await expect(async () => {
2949
- await container.click();
2950
- await expect(menu).toBeVisible({ timeout: visibilityTimeout });
2951
- await page.keyboard.type(value);
2952
- const option = (await optionByName.count()) > 0
2953
- ? optionByName
2954
- : menu.getByText(value, { exact: true });
2955
- await option.click();
2956
- await expect(container).toContainText(value, {
2957
- timeout: textAssertionTimeout,
2958
- });
2959
- }).toPass({ timeout: retryTimeout });
2960
- };
2961
- waitForSheetOpen = () => expect(this.page.getByTestId(COMMON_SELECTORS.sheetHeader)).toBeInViewport({
2962
- timeout: 10_000,
2963
- ratio: 1,
2964
- });
2965
- waitForSheetClose = () => expect(this.page.getByTestId(COMMON_SELECTORS.sheetWrapper)).toHaveCount(0, { timeout: 10_000 });
2966
- verifyFieldValue = values => {
2967
- const verifyEachFieldValue = ({ field, value, }) => expect(this.page.getByTestId(field)).toHaveValue(value);
2968
- return Array.isArray(values)
2969
- ? Promise.all(values.map(value => verifyEachFieldValue(value)))
2970
- : verifyEachFieldValue(values);
2971
- };
2972
- searchAndVerify = async ({ searchTerm, searchInputSelector = COMMON_SELECTORS.inputField, countSelector, countText, }) => {
2973
- await this.page.getByTestId(searchInputSelector).clear();
2974
- await this.page
2975
- .getByTestId(searchInputSelector)
2976
- .pressSequentially(searchTerm, { delay: 100 });
2977
- await expect(this.page.locator(COMMON_SELECTORS.tableSpinner)).toBeHidden({
2978
- timeout: 10_000,
2798
+ catch (error) {
2799
+ console.log(error);
2800
+ }
2801
+ };
2802
+ const clearCredentials = () => {
2803
+ if (shouldSkipSetupAndTeardown())
2804
+ return;
2805
+ removeCredentialFile();
2806
+ };
2807
+ const joinHyphenCase = (...args) => args.join(" ").replace(/\s+/g, "-").toLowerCase();
2808
+ const skipTest = {
2809
+ forDevelopmentEnv: () => test.skip(process.env.TEST_ENV === ENVIRONMENT.development),
2810
+ forReviewEnv: () => test.skip(process.env.TEST_ENV === ENVIRONMENT.review),
2811
+ forAllExceptStagingEnv: () => test.skip(process.env.TEST_ENV !== ENVIRONMENT.staging),
2812
+ forNonNightlyRun: () => {
2813
+ const currentBranch = execCommand("git rev-parse --abbrev-ref HEAD");
2814
+ const isNightlyRun = currentBranch === "main" && IS_STAGING_ENV && IS_CI;
2815
+ return test.skip(not(isNightlyRun), "Run test only in playwright-nightly");
2816
+ },
2817
+ ifNotWithinAllowedNightlyHours: ({ reason, allowedNightlyRunHours = [0, 6, 12, 18], }) => {
2818
+ skipTest.forNonNightlyRun();
2819
+ const currentDate = new Date();
2820
+ const day = currentDate.getUTCDay();
2821
+ const hour = currentDate.getUTCHours();
2822
+ const isAllowedNightlyRun = 0 < day && day < 6 && allowedNightlyRunHours.includes(hour);
2823
+ test.skip(not(isAllowedNightlyRun), `Nightly run is skipped due to ${reason}`);
2824
+ },
2825
+ };
2826
+ const shouldSkipSetupAndTeardown = () => getGlobalUserState()?.isLoggedIn && process.env.SKIP_SETUP === "true";
2827
+ const shouldSkipCustomDomainSetup = () => process.env.SETUP_CUSTOM_DOMAIN !== "true" || !IS_STAGING_ENV;
2828
+ const baseURLGenerator = (product, customSubdomain) => {
2829
+ const { subdomainName } = getGlobalUserState();
2830
+ const subdomain = customSubdomain ?? subdomainName;
2831
+ const railsPort = process.env.RAILS_SERVER_PORT;
2832
+ if (IS_DEV_ENV)
2833
+ return `http://${subdomain}.lvh.me:${railsPort}`;
2834
+ if (IS_REVIEW_ENV)
2835
+ return reviewAppBaseURL(subdomain);
2836
+ return `https://${subdomain}.neeto${product.toLowerCase()}.net`;
2837
+ };
2838
+ // trims and replaces multiple whitespace characters in a string with a single space
2839
+ const squish = (text) => text.trim().replace(/\s+/g, " ");
2840
+ const toCamelCase = (string) => string.toLowerCase().replace(/( \w)/g, letter => letter[1].toUpperCase());
2841
+ const getByDataQA = curry((page, dataQa) => {
2842
+ if (typeof dataQa === "string") {
2843
+ return page.locator(`[data-qa='${dataQa}']`);
2844
+ }
2845
+ return page
2846
+ .locator(`[data-qa='${dataQa[0]}']`)
2847
+ .locator(`[data-qa='${dataQa[1]}']`);
2848
+ });
2849
+ const getListCount = async ({ page, countSelector, }) => {
2850
+ const countText = await page.getByTestId(countSelector).textContent();
2851
+ return Number(countText?.trim().split(" ")[0]);
2852
+ };
2853
+ const getGlobalUserProps = async (page) => (await page.evaluate(() => window.globalProps.user));
2854
+ const createTextareaAndEvaluateCopiedText = async (page) => {
2855
+ const textareaHandle = await page.evaluateHandle(() => {
2856
+ const textarea = document.createElement("textarea");
2857
+ Object.assign(textarea.style, {
2858
+ position: "fixed",
2859
+ top: "0",
2860
+ left: "0",
2861
+ opacity: "0",
2862
+ pointerEvents: "none",
2863
+ zIndex: "9999",
2979
2864
  });
2980
- await expect(this.page.getByTestId(NEETO_FILTERS_SELECTORS.searchTermBlock)).toBeVisible();
2981
- await this.waitForPageLoad();
2982
- await expect(this.page.getByRole("cell", { name: searchTerm })).toBeVisible();
2983
- await expect(this.page.getByTestId(countSelector)).toContainText(countText);
2984
- };
2985
- uploadImage = async (localImagePath) => {
2986
- const { imageName, imagePath } = getImagePathAndName(localImagePath);
2987
- await this.page
2988
- .getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.browseText)
2989
- .click();
2990
- await this.page
2991
- .getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.fileInput)
2992
- .setInputFiles(imagePath);
2993
- await expect(this.page.getByTestId(NEETO_IMAGE_UPLOADER_SELECTORS.uploadedImage)).toHaveAttribute("src", new RegExp(imageName), { timeout: 20_000 });
2994
- };
2995
- uploadFileViaDispatch = async ({ fileNameWithType, assetsPath = "../../../e2e/assets/", dispatchEvent = "drop", droppableZone = this.page.getByTestId(COMMON_SELECTORS.fileUploadBody), }) => {
2996
- const filePath = path__default.join(import.meta.dirname, `${assetsPath}/${fileNameWithType}`);
2997
- const buffer = readFileSync(filePath).toString("base64");
2998
- const dataTransfer = await droppableZone.evaluateHandle((_, { buffer, fileNameWithType }) => {
2999
- const dataTransfer = new DataTransfer();
3000
- const fileName = fileNameWithType.split("/")?.[1];
3001
- const hexString = Uint8Array.from(atob(buffer), c => c.charCodeAt(0));
3002
- const file = new File([hexString], fileName);
3003
- dataTransfer.items.add(file);
3004
- return dataTransfer;
3005
- }, { buffer, fileNameWithType });
3006
- await droppableZone.dispatchEvent(dispatchEvent, { dataTransfer });
3007
- };
3008
- hoverOnElement = (triggerElement, customPageContext = this.page) => expect(async () => {
3009
- await triggerElement.hover();
3010
- await expect(customPageContext.getByTestId(COMMON_SELECTORS.tooltip)).toBeVisible({ timeout: 3_000 });
3011
- }).toPass({ timeout: 10_000 });
3012
- verifyTooltip = async ({ triggerElement, content, customPageContext = this.page, }) => {
3013
- await this.hoverOnElement(triggerElement, customPageContext);
3014
- const resolvedContent = typeof content === "function" ? await content() : content;
3015
- await expect(customPageContext.getByTestId(COMMON_SELECTORS.tooltip)).toContainText(resolvedContent);
3016
- await this.hideTooltip(triggerElement, customPageContext);
3017
- };
3018
- verifyHelpPopover = async ({ triggerElement = this.page.getByTestId(COMMON_SELECTORS.helpPopoverButton), title, content, helpURL, customPageContext = this.page, }) => {
3019
- await triggerElement.hover();
3020
- const titleLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverTitle);
3021
- const descLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverDesc);
3022
- const linkLocator = customPageContext.getByTestId(COMMON_SELECTORS.helpPopoverLinkButton);
3023
- const popoverContentLocator = title
3024
- ? titleLocator
3025
- : content
3026
- ? descLocator
3027
- : linkLocator;
3028
- title && (await expect(titleLocator).toHaveText(title));
3029
- content && (await expect(descLocator).toContainText(content));
3030
- helpURL &&
3031
- (await Promise.all([
3032
- this.assertHelpURLIsValid(helpURL),
3033
- expect(linkLocator).toHaveAttribute("href", new RegExp(helpURL, "i")),
3034
- ]));
3035
- await this.hidePopoverContent(popoverContentLocator, customPageContext);
3036
- };
3037
- assertHelpURLIsValid = (helpURL) => expect(async () => {
3038
- const response = await this.request.get(helpURL, { timeout: 15_000 });
3039
- await expect(response).toBeOK();
3040
- }).toPass({ timeout: 45_000, intervals: [3_000] });
3041
- verifyHelpText = async (helpURL) => {
3042
- const isNoDataTitleHidden = await this.page
3043
- .getByTestId(COMMON_SELECTORS.noDataTitleV2)
3044
- .isHidden();
3045
- if (isNoDataTitleHidden)
3046
- return;
3047
- const helpLink = this.page
3048
- .getByTestId(COMMON_SELECTORS.noDataHelpTextV2)
3049
- .getByRole("link")
3050
- .or(this.page
3051
- .getByTestId(COMMON_SELECTORS.noDataDescriptionV2)
3052
- .getByRole("link"));
3053
- await Promise.all([
3054
- this.assertHelpURLIsValid(helpURL),
3055
- expect(helpLink).toHaveAttribute("href", new RegExp(helpURL, "i")),
3056
- ]);
3057
- };
3058
- verifySearchTermBlock = async (searchTerm) => {
3059
- const filtersSearchTermBlock = this.page.getByTestId(NEETO_FILTERS_SELECTORS.filtersTermBlock());
3060
- if (searchTerm) {
3061
- const textContent = await filtersSearchTermBlock?.textContent();
3062
- textContent?.includes("..")
3063
- ? await this.verifyTooltip({
3064
- triggerElement: filtersSearchTermBlock,
3065
- content: searchTerm,
3066
- })
3067
- : await expect(filtersSearchTermBlock).toContainText(searchTerm);
3068
- }
3069
- else {
3070
- await expect(filtersSearchTermBlock).toBeHidden();
3071
- }
3072
- };
3073
- saveChanges = ({ isPane = false, customPageContext = this.page, closeAfterVerification = true, toastMessage = "", } = {}) => {
3074
- const pane = customPageContext.getByTestId(COMMON_SELECTORS.sheetWrapper);
3075
- const baseLocator = isPane ? pane : customPageContext;
3076
- return Promise.all([
3077
- this.clickButtonAndAwaitLoad({
3078
- locator: baseLocator.getByTestId(COMMON_SELECTORS.saveChangesButton),
3079
- timeout: 10_000,
3080
- }),
3081
- // eslint-disable-next-line playwright/missing-playwright-await
3082
- isPane && expect(pane).toBeHidden({ timeout: 10_000 }),
3083
- this.verifyToast({
3084
- closeAfterVerification,
3085
- customPageContext,
3086
- message: toastMessage,
3087
- timeout: 20_000,
3088
- }),
3089
- ]);
3090
- };
3091
- hideTooltip = async (triggerElement, customPageContext = this.page) => {
3092
- const boundingBox = await triggerElement.boundingBox();
3093
- if (!boundingBox) {
3094
- throw new Error("Trigger element bounding box not found");
2865
+ document.body.appendChild(textarea);
2866
+ textarea.focus();
2867
+ return textarea;
2868
+ });
2869
+ try {
2870
+ await page.keyboard.press("ControlOrMeta+v");
2871
+ return await page.evaluate(el => el.value, textareaHandle);
2872
+ }
2873
+ finally {
2874
+ await textareaHandle.evaluate(el => el.remove());
2875
+ await textareaHandle.dispose();
2876
+ }
2877
+ };
2878
+ const getClipboardContent = async (page) => {
2879
+ // Attempt 1: Native Clipboard API
2880
+ const clipboardText = await page.evaluate(async () => {
2881
+ if (!navigator.clipboard?.readText)
2882
+ return null;
2883
+ return await navigator.clipboard.readText();
2884
+ });
2885
+ if (isNotNil(clipboardText))
2886
+ return clipboardText;
2887
+ // Attempt 2: Keyboard paste fallback
2888
+ return createTextareaAndEvaluateCopiedText(page);
2889
+ };
2890
+ const grantClipboardPermissions = async (context) => {
2891
+ const isWebkit = context.browser()?.browserType().name() === "webkit";
2892
+ // WebKit supports "clipboard-read" but rejects "clipboard-write".
2893
+ await context.grantPermissions(isWebkit ? ["clipboard-read"] : ["clipboard-read", "clipboard-write"]);
2894
+ };
2895
+ const getFullUrl = (path) => shouldSkipCustomDomainSetup() ? path : `${process.env.BASE_URL}${path}`;
2896
+ const globalShortcuts = (t) => [
2897
+ {
2898
+ description: t("neetoMolecules.keyboardShortcuts.global.openKeyboardShortcutsPane"),
2899
+ sequence: "ctrl+/",
2900
+ },
2901
+ {
2902
+ description: t("neetoMolecules.keyboardShortcuts.global.close"),
2903
+ sequence: "esc",
2904
+ },
2905
+ {
2906
+ description: t("neetoMolecules.keyboardShortcuts.global.submitForm"),
2907
+ sequence: "ctrl+enter",
2908
+ },
2909
+ {
2910
+ description: t("neetoMolecules.keyboardShortcuts.global.openProductSwitcher"),
2911
+ sequence: "ctrl+u",
2912
+ },
2913
+ {
2914
+ description: t("neetoMolecules.keyboardShortcuts.global.search"),
2915
+ sequence: "ctrl+k",
2916
+ },
2917
+ ];
2918
+ const generatePhoneNumber = () => `${"+91"} 9${faker.string.numeric(4)} ${faker.string.numeric(5)}`;
2919
+ const initializeTestData = (product) => {
2920
+ const credentials = generateStagingData(product.toLowerCase());
2921
+ const baseURL = baseURLGenerator(product, credentials.subdomainName);
2922
+ return { credentials, baseURL };
2923
+ };
2924
+ const imageRegex = (imageName) => {
2925
+ const [baseName, extension] = imageName.split(".");
2926
+ return new RegExp(`${baseName}.*\\.${extension}$`);
2927
+ };
2928
+ const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60 * 1000);
2929
+ const exampleEmail = () => faker.internet.exampleEmail({
2930
+ firstName: faker.string.alpha(1),
2931
+ lastName: faker.string.alpha(1),
2932
+ allowSpecialCharacters: false,
2933
+ });
2934
+ function failTest(message) {
2935
+ try {
2936
+ test.info();
2937
+ }
2938
+ catch {
2939
+ throw new Error(message);
2940
+ }
2941
+ return test.abort(message);
2942
+ }
2943
+
2944
+ const EMPTY_SEARCH_RESULT = {
2945
+ messages: [],
2946
+ messagesCount: 0,
2947
+ };
2948
+ class MailpitApi {
2949
+ neetoPlaywrightUtilities;
2950
+ baseUrl;
2951
+ headers;
2952
+ constructor(neetoPlaywrightUtilities) {
2953
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
2954
+ this.baseUrl = (process.env.MAILPIT_BASE_URL || MAILPIT_BASE_URL).replace(/\/+$/, "");
2955
+ const { MAILPIT_USERNAME, MAILPIT_PASSWORD } = process.env;
2956
+ this.headers =
2957
+ MAILPIT_USERNAME && MAILPIT_PASSWORD
2958
+ ? {
2959
+ Authorization: `Basic ${Buffer.from(`${MAILPIT_USERNAME}:${MAILPIT_PASSWORD}`).toString("base64")}`,
2960
+ }
2961
+ : {};
2962
+ }
2963
+ authorizeAndSetAccountId = async () => { };
2964
+ warnOnUnexpectedResponse = (endpoint, response) => {
2965
+ if (response.ok() || response.status() === 404)
2966
+ return;
2967
+ if (response.status() === 401) {
2968
+ console.warn(`Mailpit rejected the credentials for ${endpoint}. Set MAILPIT_USERNAME and MAILPIT_PASSWORD to the basic auth credentials of ${this.baseUrl}, otherwise every email lookup will time out.`);
2969
+ return;
3095
2970
  }
3096
- const { x, y, width, height } = boundingBox;
3097
- const moves = [
3098
- [x + width + 10, y],
3099
- [x, y + height + 10],
3100
- [x - 10, y],
3101
- [x, y - 10],
3102
- ];
3103
- const tooltip = customPageContext.getByTestId(COMMON_SELECTORS.tooltip);
3104
- await expect(async () => {
3105
- for (const [moveX, moveY] of moves) {
3106
- await customPageContext.mouse.move(moveX, moveY);
3107
- if ((await tooltip.count()) === 0)
3108
- break;
3109
- }
3110
- await expect(tooltip).toHaveCount(0);
3111
- }).toPass({ timeout: 30_000 });
3112
- };
3113
- hidePopoverContent = async (contentLocator, customPageContext = this.page) => {
3114
- await customPageContext.mouse.move(0, 0);
3115
- await expect(contentLocator).toBeHidden();
2971
+ console.warn(`Mailpit responded with ${response.status()} for ${endpoint}. Treating it as no result, so an email lookup may time out even though the email exists.`);
3116
2972
  };
3117
- verifyBreadcrumbs = async (titlesAndRoutes) => {
3118
- const header = this.page.getByTestId(COMMON_SELECTORS.breadcrumbHeader);
3119
- const titles = pluck("title", titlesAndRoutes);
3120
- const [last, ...links] = titlesAndRoutes.toReversed();
3121
- await Promise.all([
3122
- expect(header).toContainText(titles),
3123
- expect(header).toHaveCount(titlesAndRoutes.length),
3124
- expect(header.getByRole("link", { name: last?.title, exact: true })).toHaveAttribute("aria-disabled", "true"),
3125
- ...links.map(({ title, route }) => expect(header.getByRole("link", { name: title, exact: true })).toHaveAttribute("href", route)),
3126
- ]);
2973
+ search = async ({ query, start = 0, limit = 50, tz = "UTC", }) => {
2974
+ const isSearch = Boolean(query);
2975
+ const endpoint = `/api/v1/${isSearch ? "search" : "messages"}`;
2976
+ const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, {
2977
+ params: isSearch
2978
+ ? { query: query, start, limit, tz }
2979
+ : { start, limit },
2980
+ headers: this.headers,
2981
+ failOnStatusCode: false,
2982
+ timeout: 15_000,
2983
+ });
2984
+ this.warnOnUnexpectedResponse(endpoint, response);
2985
+ if (!response.ok())
2986
+ return EMPTY_SEARCH_RESULT;
2987
+ const { messages, messages_count: messagesCount } = await response.json();
2988
+ return { messages: messages ?? [], messagesCount: messagesCount ?? 0 };
3127
2989
  };
3128
- uploadFileViaDispatchV2 = async ({ droppableZone = this.page.getByTestId(COMMON_SELECTORS.fileUploadBody), dispatchEvent = "drop", timeout = 45_000, file, }) => {
3129
- const serializedFile = await serializeFileForBrowser(file);
3130
- const dataTransfer = await droppableZone.evaluateHandle((_, { name, type, buffer, lastModified }) => {
3131
- const uint8Array = new Uint8Array(buffer);
3132
- const file = new File([uint8Array], name, { type, lastModified });
3133
- const dataTransfer = new DataTransfer();
3134
- dataTransfer.items.add(file);
3135
- return dataTransfer;
3136
- }, serializedFile, { timeout });
3137
- try {
3138
- await droppableZone.dispatchEvent(dispatchEvent, { dataTransfer });
3139
- }
3140
- finally {
3141
- await dataTransfer.dispose();
3142
- }
2990
+ getMessage = async (id) => {
2991
+ const endpoint = `/api/v1/message/${id}`;
2992
+ const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, { headers: this.headers, failOnStatusCode: false, timeout: 15_000 });
2993
+ this.warnOnUnexpectedResponse(endpoint, response);
2994
+ return response.ok() ? await response.json() : null;
3143
2995
  };
3144
- verifyUnsavedChangesModal = async (shouldLeavePage = false) => {
3145
- const alertBox = this.page.getByTestId(COMMON_SELECTORS.alertBox);
3146
- await Promise.all([
3147
- expect(this.page.getByTestId(COMMON_SELECTORS.alertModalMessage)
3148
- // TODO: Use translation for this once https://github.com/neetozone/neeto-atoms/issues/423 is resolved
3149
- ).toHaveText("Are you sure you want to leave? All unsaved changes will be lost."),
3150
- expect(this.page.getByTestId(COMMON_SELECTORS.alertTitle)).toHaveText("You have unsaved changes"),
3151
- ]);
3152
- const actionButton = shouldLeavePage
3153
- ? alertBox.getByTestId(COMMON_SELECTORS.alertCancelButton)
3154
- : alertBox
3155
- .getByTestId(COMMON_SELECTORS.dialogCloseButton)
3156
- .or(alertBox.getByTestId(COMMON_SELECTORS.alertModalCrossIcon));
3157
- await actionButton.click();
3158
- await expect(alertBox).toBeHidden();
2996
+ fetchRawMessage = async (id) => {
2997
+ const endpoint = `/api/v1/message/${id}/raw`;
2998
+ const response = await this.neetoPlaywrightUtilities.request.get(`${this.baseUrl}${endpoint}`, { headers: this.headers, failOnStatusCode: false, timeout: 15_000 });
2999
+ this.warnOnUnexpectedResponse(endpoint, response);
3000
+ return response.ok() ? await response.body() : null;
3159
3001
  };
3160
- setSliderValue = async ({ parentLocator = this.page, valueAsPercent, startFromCenter = false, }) => {
3161
- const sliderLocator = parentLocator.locator(COMMON_SELECTORS.slider);
3162
- await expect(sliderLocator).toBeVisible();
3163
- await sliderLocator.evaluate(node => node.scrollIntoView({ behavior: "instant", block: "center" }));
3164
- const sliderBoundingBox = await sliderLocator.boundingBox();
3165
- let targetX = sliderBoundingBox.width * valueAsPercent;
3166
- if (startFromCenter)
3167
- targetX = targetX / 2;
3168
- let sliderSourceX = sliderBoundingBox.x;
3169
- if (startFromCenter)
3170
- sliderSourceX += sliderBoundingBox.width / 2;
3171
- const sliderSourceY = sliderBoundingBox.y + sliderBoundingBox.height / 2;
3172
- await this.page.mouse.move(sliderSourceX, sliderSourceY, { steps: 5 });
3173
- await this.page.mouse.down();
3174
- await this.page.mouse.move(sliderSourceX + targetX, sliderSourceY, {
3175
- steps: 5,
3002
+ deleteMessages = async (ids) => {
3003
+ if (!ids?.length)
3004
+ failTest("MailpitApi.deleteMessages requires a non-empty list of message IDs. Mailpit deletes every stored message when the list is empty, and the inbox is shared across neeto products.");
3005
+ await this.neetoPlaywrightUtilities.request.delete(`${this.baseUrl}/api/v1/messages`, {
3006
+ data: { IDs: ids },
3007
+ headers: this.headers,
3008
+ failOnStatusCode: false,
3009
+ timeout: 15_000,
3176
3010
  });
3177
- await this.page.mouse.up();
3178
3011
  };
3179
- assertCardDetails = ({ cardLocator, title, description, }) => Promise.all([
3180
- expect(cardLocator.getByTestId(ADMIN_PANEL_SELECTORS.settingsItemHeading)).toHaveText(title),
3181
- expect(cardLocator.getByTestId(ADMIN_PANEL_SELECTORS.settingsItemDescription)).toHaveText(description),
3182
- expect(this.page.getByTestId(COMMON_SELECTORS.sidebarSubLink(title))).toHaveCSS("background-color", COLOR.transparent),
3183
- ]);
3184
- executeWithErrorHandling = async (asyncFn) => {
3012
+ }
3013
+
3014
+ class RailsEmailApiClient {
3015
+ port = process.env.RAILS_SERVER_PORT;
3016
+ subdomain = process.env.SUBDOMAIN ?? "spinkart";
3017
+ baseUrl = `http://${this.subdomain}.lvh.me:${this.port}`;
3018
+ emailsEndpoint = `${this.baseUrl}/api/v1/testing/emails`;
3019
+ constructor() { }
3020
+ convertRawEmail = (raw) => ({
3021
+ from: raw.from,
3022
+ to: raw.to,
3023
+ cc: raw.cc,
3024
+ bcc: raw.bcc,
3025
+ replyTo: raw.reply_to,
3026
+ subject: raw.subject,
3027
+ htmlBody: raw.html_body,
3028
+ textBody: raw.text_body,
3029
+ receivedAt: raw.received_at,
3030
+ ...(raw.message_id && { messageId: raw.message_id }),
3031
+ attachments: raw.attachments?.map(({ filename, mime_type, data }) => ({
3032
+ name: filename,
3033
+ type: mime_type,
3034
+ content: data,
3035
+ })),
3036
+ });
3037
+ buildQueryString = (params) => {
3038
+ if (!params)
3039
+ return "";
3040
+ const filtered = Object.fromEntries(Object.entries(keysToSnakeCase(params))
3041
+ .filter(([, v]) => v != null && v !== "")
3042
+ .map(([k, v]) => [k, String(v)]));
3043
+ const query = new URLSearchParams(filtered).toString();
3044
+ return query ? `?${query}` : "";
3045
+ };
3046
+ fetchJson = async (url, options) => {
3185
3047
  try {
3186
- const result = await asyncFn();
3187
- return { success: true, result };
3048
+ const res = await fetch(url, options);
3049
+ if (!res.ok)
3050
+ return null;
3051
+ return (await res.json());
3188
3052
  }
3189
- catch (error) {
3190
- const errorInstance = error instanceof Error ? error : new Error(String(error));
3191
- return { success: false, error: errorInstance.message };
3053
+ catch (err) {
3054
+ console.error("API error:", err);
3055
+ return null;
3192
3056
  }
3193
3057
  };
3194
- clickButtonAndAwaitLoad = async ({ locator, timeout, }) => {
3195
- await locator.click({ timeout });
3196
- await expect(locator.getByTestId(COMMON_SELECTORS.uiSpinner)).toBeHidden({
3197
- timeout: 35_000,
3198
- });
3058
+ listEmails = async (searchParams) => {
3059
+ const query = this.buildQueryString(searchParams);
3060
+ const data = await this.fetchJson(`${this.emailsEndpoint}${query}`);
3061
+ return data?.map(this.convertRawEmail) ?? [];
3199
3062
  };
3200
- toggleElement = ({ locator, shouldBeChecked = true }) => expect(async () => {
3201
- // Callers often pass an atoms Switch's wrapper (`<prefix>-switch`); the checkable control is the nested `nui-switch-item`.
3202
- const switchItem = locator.getByTestId(COMMON_SELECTORS.switchLabel);
3203
- const target =
3204
- // eslint-disable-next-line playwright/no-nth-methods
3205
- (await switchItem.count()) > 0 ? switchItem.first() : locator;
3206
- (await target.isChecked()) !== shouldBeChecked && (await target.click());
3207
- await expect(target).toBeChecked({ checked: shouldBeChecked });
3208
- }).toPass({ timeout: 15_000 });
3209
- // Polls the editor's own state, which is what the next key press acts on.
3210
- // The DOM selection is not proof: ProseMirror re-applies its stored
3211
- // selection shortly after a programmatic focus, undoing an early collapse.
3212
- waitForSelectionToCollapse = (timeout = 2_000) => expect
3213
- .poll(() => this.page.evaluate(contentField => {
3214
- const editor = document.activeElement?.closest(`[data-testid="${contentField}"]`)?.editor;
3215
- if (!editor)
3216
- return "no focused editor";
3217
- const { selection } = editor.state;
3218
- return selection.empty
3219
- ? "collapsed"
3220
- : `${selection.from}-${selection.to}`;
3221
- }, NEETO_EDITOR_SELECTORS.contentField), {
3222
- timeout,
3223
- intervals: [50, 100, 250],
3224
- message: "Editor selection did not collapse",
3225
- })
3226
- .toBe("collapsed");
3227
- moveCursorAtBottom = async () => {
3228
- const isMacOS = os.platform() === "darwin";
3229
- const rightArrowKey = isMacOS ? "Meta+ArrowRight" : "End";
3230
- const downArrowKey = isMacOS ? "Meta+ArrowDown" : "PageDown";
3231
- await expect(async () => {
3232
- await this.page.keyboard.press(rightArrowKey);
3233
- await this.page.keyboard.press(rightArrowKey);
3234
- await this.page.keyboard.press(downArrowKey);
3235
- await this.waitForSelectionToCollapse();
3236
- }).toPass({ timeout: 15_000 });
3237
- await this.page.keyboard.press("Enter");
3063
+ getLatestEmail = async (searchParams) => {
3064
+ const emails = await this.listEmails(searchParams);
3065
+ return emails.reduce((latest, curr) => !latest || new Date(curr.receivedAt) > new Date(latest.receivedAt)
3066
+ ? curr
3067
+ : latest, null);
3068
+ };
3069
+ clearEmails = () => this.fetchJson(this.emailsEndpoint, {
3070
+ method: "DELETE",
3071
+ });
3072
+ clearStaleEmails = (receivedBefore) => this.fetchJson(`${this.emailsEndpoint}?received_before=${encodeURIComponent(receivedBefore)}`, { method: "DELETE" });
3073
+ }
3074
+
3075
+ const SECURITY_BASE_URL = `/secure${BASE_URL}/configuration`;
3076
+ class SecurityApi {
3077
+ neetoPlaywrightUtilities;
3078
+ constructor(neetoPlaywrightUtilities) {
3079
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
3080
+ }
3081
+ buildBody = (auth, value) => {
3082
+ switch (auth) {
3083
+ case "password":
3084
+ return {
3085
+ configuration: {
3086
+ auth: "basic",
3087
+ password: value || faker.internet.password(),
3088
+ },
3089
+ };
3090
+ case "invite":
3091
+ return { configuration: { auth: "invited" } };
3092
+ case "member":
3093
+ return { configuration: { auth: "session" } };
3094
+ case "email":
3095
+ return {
3096
+ configuration: {
3097
+ auth: "email",
3098
+ allowed_keywords: [value || faker.internet.domainName()],
3099
+ },
3100
+ };
3101
+ default:
3102
+ return { configuration: { auth: "no" } };
3103
+ }
3238
3104
  };
3105
+ update = ({ ownerId, auth, value }) => this.neetoPlaywrightUtilities.apiRequest({
3106
+ body: this.buildBody(auth, value),
3107
+ url: SECURITY_BASE_URL,
3108
+ ...(ownerId && { params: keysToSnakeCase({ ownerId }) }),
3109
+ method: "put",
3110
+ });
3111
+ }
3112
+
3113
+ const THANK_YOU_URL = "/neeto_thank_you/thank_you_configurations";
3114
+ class ThankYouApi {
3115
+ neetoPlaywrightUtilities;
3116
+ constructor(neetoPlaywrightUtilities) {
3117
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
3118
+ }
3119
+ create = ({ entityId, title, }) => this.neetoPlaywrightUtilities.apiRequest({
3120
+ method: "post",
3121
+ body: { title, description: "" },
3122
+ url: THANK_YOU_URL,
3123
+ params: keysToSnakeCase({ entityId }),
3124
+ });
3125
+ fetch = ({ entityId }) => this.neetoPlaywrightUtilities.apiRequest({
3126
+ url: THANK_YOU_URL,
3127
+ params: keysToSnakeCase({ entityId }),
3128
+ });
3129
+ update = ({ thankYouPageId, entityId, }) => this.neetoPlaywrightUtilities.apiRequest({
3130
+ method: "put",
3131
+ url: `${THANK_YOU_URL}/${thankYouPageId}`,
3132
+ body: keysToSnakeCase({
3133
+ entityId,
3134
+ thankYouConfiguration: {
3135
+ id: thankYouPageId,
3136
+ kind: "redirect_to_url",
3137
+ passEventDetailsToRedirectUrl: false,
3138
+ redirectUrl: EXAMPLE_URL,
3139
+ },
3140
+ }),
3141
+ });
3142
+ }
3143
+
3144
+ const NEETO_TOWER_BASE_URL = "https://ops.neetotower.com/";
3145
+ const DNS_RECORDS_BASE_URL = `${NEETO_TOWER_BASE_URL}api/v1/public/automation_tests/dns_records`;
3146
+ class NeetoTowerApi {
3147
+ neetoPlaywrightUtilities;
3148
+ apiKey;
3149
+ constructor(neetoPlaywrightUtilities) {
3150
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
3151
+ this.apiKey = requireEnv("NEETO_TOWER_API_KEY");
3152
+ }
3153
+ apiRequest = ({ method, dnsDomainId = "", body, }) => this.neetoPlaywrightUtilities.apiRequest({
3154
+ url: `${DNS_RECORDS_BASE_URL}${dnsDomainId ? `/${dnsDomainId}` : ""}`,
3155
+ headers: { "X-API-KEY": this.apiKey },
3156
+ method,
3157
+ body,
3158
+ });
3159
+ createRecord = ({ hostname, value }) => this.apiRequest({
3160
+ method: "post",
3161
+ body: { name: hostname, type: "TXT", content: value },
3162
+ });
3163
+ getRecords = () => this.apiRequest({ method: "get" });
3164
+ deleteRecord = (dnsDomainId) => this.apiRequest({ method: "delete", dnsDomainId });
3165
+ }
3166
+
3167
+ class SlackApi {
3168
+ neetoPlaywrightUtilities;
3169
+ botToken;
3170
+ constructor(neetoPlaywrightUtilities) {
3171
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
3172
+ this.botToken = requireEnv("SLACK_BOT_TOKEN");
3173
+ }
3174
+ apiRequest = (endpoint, params) => this.neetoPlaywrightUtilities.apiRequest({
3175
+ url: `https://slack.com/api/conversations.${endpoint}`,
3176
+ headers: { Authorization: `Bearer ${this.botToken}` },
3177
+ params,
3178
+ });
3179
+ fetchMessages = (channelId, unixTimestamp) => this.apiRequest("history", { channel: channelId, oldest: unixTimestamp });
3180
+ createChannel = (channelName) => this.apiRequest("create", { name: channelName });
3181
+ addUser = (channelId, userId) => this.apiRequest("invite", { channel: channelId, users: userId });
3182
+ archiveChannel = (channelId) => this.apiRequest("archive", { channel: channelId });
3183
+ mockChannelDeleted = (channelId) => this.neetoPlaywrightUtilities.apiRequest({
3184
+ url: "/neeto_slack/api/v1/testing/webhooks",
3185
+ method: "post",
3186
+ data: keysToSnakeCase({
3187
+ eventType: "channel_deleted",
3188
+ notificationChannelId: channelId,
3189
+ }),
3190
+ });
3191
+ }
3192
+
3193
+ class WebhookSiteApi {
3194
+ request;
3195
+ WEBHOOK_SITE_BASE_URL = "https://webhook.site/token";
3196
+ constructor(request) {
3197
+ this.request = request;
3198
+ }
3199
+ create = () => this.request.post(this.WEBHOOK_SITE_BASE_URL);
3200
+ fetch = (token) => this.request.get(`${this.WEBHOOK_SITE_BASE_URL}/${token}/request/latest`);
3201
+ configure = (tokenId, content = DEFAULT_WEBHOOKS_RESPONSE_TEXT) => this.request.put(`${THIRD_PARTY_ROUTES.webhooks.site}token/${tokenId}`, {
3202
+ data: keysToSnakeCase({ defaultContent: content }),
3203
+ });
3204
+ }
3205
+
3206
+ class TwilioApi {
3207
+ neetoPlaywrightUtilities;
3208
+ authToken;
3209
+ sid;
3210
+ defaultPhoneSid;
3211
+ constructor(neetoPlaywrightUtilities) {
3212
+ this.neetoPlaywrightUtilities = neetoPlaywrightUtilities;
3213
+ const env = requireEnv("TWILIO_AUTH_TOKEN", "TWILIO_SID", "TWILIO_DEFAULT_PHONE_SID");
3214
+ this.authToken = env.TWILIO_AUTH_TOKEN;
3215
+ this.sid = env.TWILIO_SID;
3216
+ this.defaultPhoneSid = env.TWILIO_DEFAULT_PHONE_SID;
3217
+ }
3218
+ apiRequest = ({ endpoint, params, body, method = "get", }) => this.neetoPlaywrightUtilities.apiRequest({
3219
+ method,
3220
+ url: `/neeto_integrations/${endpoint}`,
3221
+ ...(params && { params }),
3222
+ ...(body && { body }),
3223
+ });
3224
+ fetch = ({ integrableId, integrableType }) => this.apiRequest({
3225
+ endpoint: "twilio/sms_configurations",
3226
+ ...(integrableId && {
3227
+ params: keysToSnakeCase({ integrableId, integrableType }),
3228
+ }),
3229
+ });
3230
+ disconnect = ({ integrableId, integrableType }) => this.apiRequest({
3231
+ method: "delete",
3232
+ endpoint: "disconnect",
3233
+ body: keysToSnakeCase({
3234
+ disconnect: { slug: "twilio" },
3235
+ ...(integrableId && { integrableId, integrableType }),
3236
+ }),
3237
+ });
3238
+ connect = ({ integrableId, integrableType }) => this.apiRequest({
3239
+ endpoint: "twilio/sms_configurations",
3240
+ method: "post",
3241
+ body: keysToSnakeCase({
3242
+ twilioAuthToken: this.authToken,
3243
+ twilioSid: this.sid,
3244
+ twilioPhoneNumberSid: this.defaultPhoneSid,
3245
+ ...(integrableId && { integrableId, integrableType }),
3246
+ }),
3247
+ });
3239
3248
  }
3240
3249
 
3241
3250
  class Health {
@@ -3393,9 +3402,8 @@ class RailsEmailUtils {
3393
3402
  timeout,
3394
3403
  }));
3395
3404
  if (!email) {
3396
- if (shouldThrowErrorOnTimeout && expectedEmailCount > 0) {
3397
- throw new Error("Timed out waiting for matching message");
3398
- }
3405
+ if (shouldThrowErrorOnTimeout && expectedEmailCount > 0)
3406
+ failTest("Timed out waiting for matching message");
3399
3407
  return {};
3400
3408
  }
3401
3409
  return email;
@@ -3466,9 +3474,8 @@ class RailsEmailUtils {
3466
3474
  timeout,
3467
3475
  }));
3468
3476
  if (!attachmentDetails) {
3469
- if (shouldThrowErrorOnTimeout) {
3470
- throw new Error("Timed out waiting for matching message or attachment not found");
3471
- }
3477
+ if (shouldThrowErrorOnTimeout)
3478
+ failTest("Timed out waiting for matching message or attachment not found");
3472
3479
  return undefined;
3473
3480
  }
3474
3481
  return attachmentDetails;
@@ -3482,7 +3489,7 @@ const toMailpitSearchDate = (date) => new Date(date.valueOf() - MAILPIT_SEARCH_D
3482
3489
  .slice(0, 10)
3483
3490
  .replace(/-/g, "/");
3484
3491
  const toMailpitSearchTerm = (value) => `"${value.replace(/"/g, "")}"`;
3485
- const mailpitTimeoutError = (messageSearchCriteria, receivedAfter, expectedEmailCount) => new Error(`Timed out waiting for matching message. Searched Mailpit for ${JSON.stringify(messageSearchCriteria)} received after ${receivedAfter.toISOString()}, expecting at least ${expectedEmailCount}.`);
3492
+ const mailpitTimeoutMessage = (messageSearchCriteria, receivedAfter, expectedEmailCount) => `Timed out waiting for matching message. Searched Mailpit for ${JSON.stringify(messageSearchCriteria)} received after ${receivedAfter.toISOString()}, expecting at least ${expectedEmailCount}.`;
3486
3493
  class MailerUtils {
3487
3494
  neetoPlaywrightUtilities;
3488
3495
  mailpitApi;
@@ -3587,7 +3594,7 @@ class MailerUtils {
3587
3594
  };
3588
3595
  queryMailpitEmails = async (messageSearchCriteria, { receivedAfter = dateTimeOneHourAgo(), page = 1, itemsPerPage = 50, }) => {
3589
3596
  if (itemsPerPage > 100 || itemsPerPage < 1)
3590
- throw new Error("itemsPerPage should be in the range of 1-100");
3597
+ failTest("itemsPerPage should be in the range of 1-100");
3591
3598
  const { to, from } = messageSearchCriteria;
3592
3599
  const query = [
3593
3600
  ...(to ? [`to:${toMailpitSearchTerm(to)}`] : []),
@@ -3650,7 +3657,7 @@ class MailerUtils {
3650
3657
  const summaries = await this.pollForMailpitSummaries(messageSearchCriteria, { timeout, receivedAfter, expectedEmailCount });
3651
3658
  if (!summaries) {
3652
3659
  if (shouldThrowErrorOnTimeout)
3653
- throw mailpitTimeoutError(messageSearchCriteria, receivedAfter, expectedEmailCount);
3660
+ failTest(mailpitTimeoutMessage(messageSearchCriteria, receivedAfter, expectedEmailCount));
3654
3661
  return [];
3655
3662
  }
3656
3663
  return summaries.map(({ ID }) => ID);
@@ -3663,7 +3670,7 @@ class MailerUtils {
3663
3670
  const summaries = await this.pollForMailpitSummaries(messageSearchCriteria, { timeout, receivedAfter, expectedEmailCount });
3664
3671
  if (!summaries) {
3665
3672
  if (shouldThrowErrorOnTimeout)
3666
- throw mailpitTimeoutError(messageSearchCriteria, receivedAfter, expectedEmailCount);
3673
+ failTest(mailpitTimeoutMessage(messageSearchCriteria, receivedAfter, expectedEmailCount));
3667
3674
  return {};
3668
3675
  }
3669
3676
  const emails = await this.getEmails(summaries);
@@ -3707,7 +3714,7 @@ class MailerUtils {
3707
3714
  const { id } = await this.findMessage(messageSearchCriteria, { expectedEmailCount, receivedAfter, timeout }, shouldThrowErrorOnTimeout);
3708
3715
  const rawMessage = id ? await this.mailpitApi.fetchRawMessage(id) : null;
3709
3716
  if (!rawMessage)
3710
- throw new Error("No such attachment exists");
3717
+ failTest("No such attachment exists");
3711
3718
  const parsedEmail = await simpleParser(rawMessage);
3712
3719
  const attachments = parsedEmail.attachments;
3713
3720
  const attachment = attachments.find(att => {
@@ -3716,7 +3723,7 @@ class MailerUtils {
3716
3723
  return matchesName && matchesType;
3717
3724
  });
3718
3725
  if (!attachment)
3719
- throw new Error("No such attachment exists");
3726
+ failTest("No such attachment exists");
3720
3727
  return attachment;
3721
3728
  };
3722
3729
  }
@@ -3773,9 +3780,8 @@ class SmsApi {
3773
3780
  url: TESTING_SMS_PATH,
3774
3781
  params: keysToSnakeCase(searchParams),
3775
3782
  });
3776
- if (!response) {
3777
- throw new Error(`Received no response from GET ${TESTING_SMS_PATH}.`);
3778
- }
3783
+ if (!response)
3784
+ failTest(`Received no response from GET ${TESTING_SMS_PATH}.`);
3779
3785
  return keysToCamelCase(await response.json());
3780
3786
  };
3781
3787
  deleteSms = (receivedBefore) => this.neetoPlaywrightUtilities.apiRequest({
@@ -3818,15 +3824,13 @@ class SmsUtils {
3818
3824
  timeout,
3819
3825
  }));
3820
3826
  if (expectedSmsCount === 0) {
3821
- if (sms) {
3822
- throw new Error(`Expected no SMS matching ${JSON.stringify(searchParams)}, but received ${JSON.stringify(sms)}.`);
3823
- }
3827
+ if (sms)
3828
+ failTest(`Expected no SMS matching ${JSON.stringify(searchParams)}, but received ${JSON.stringify(sms)}.`);
3824
3829
  return {};
3825
3830
  }
3826
3831
  if (!sms) {
3827
- if (shouldThrowErrorOnTimeout) {
3828
- throw new Error(`Timed out waiting for SMS matching ${JSON.stringify(searchParams)}, expected at least ${expectedSmsCount}.`);
3829
- }
3832
+ if (shouldThrowErrorOnTimeout)
3833
+ failTest(`Timed out waiting for SMS matching ${JSON.stringify(searchParams)}, expected at least ${expectedSmsCount}.`);
3830
3834
  return {};
3831
3835
  }
3832
3836
  return sms;
@@ -5038,45 +5042,11 @@ class SlackPage extends IntegrationBase {
5038
5042
  };
5039
5043
  }
5040
5044
 
5041
- const simulateTypingWithDelay = async ({ field, value, delay = 500, }) => {
5042
- const minSliceLength = Math.max(3, Math.floor(value.length * 0.6));
5043
- const maxSliceLength = Math.max(4, Math.floor(value.length * 0.8));
5044
- const sliceLength = Math.floor(Math.random() * (maxSliceLength - minSliceLength + 1)) +
5045
- minSliceLength;
5046
- const maxBackspaceCount = Math.max(2, Math.min(4, Math.floor(sliceLength * 0.3)));
5047
- const backspaceCount = Math.floor(Math.random() * (maxBackspaceCount - 1)) + 2;
5048
- const textPart1 = value.slice(0, sliceLength);
5049
- const textPart2 = value.slice(sliceLength - backspaceCount);
5050
- await field.hover();
5051
- await field.click({ delay: Math.floor(Math.random() * delay) + 700 });
5052
- await field.pressSequentially(textPart1, {
5053
- delay: Math.floor(Math.random() * delay) + 400,
5054
- timeout: 30_000,
5055
- });
5056
- for (let i = 0; i < backspaceCount; i++) {
5057
- await field.press("Backspace", {
5058
- delay: Math.floor(Math.random() * 1000) + 300,
5059
- });
5060
- }
5061
- await field.pressSequentially(textPart2, {
5062
- delay: Math.floor(Math.random() * delay) + 700,
5063
- timeout: 45_000,
5064
- });
5065
- };
5066
- const simulateClickWithDelay = async ({ element, page, }) => {
5067
- const locatorBoundingBox = await element.boundingBox();
5068
- const clickX = locatorBoundingBox.x + locatorBoundingBox.width / 2 + 10;
5069
- const clickY = locatorBoundingBox.y + locatorBoundingBox.height / 2 - 10;
5070
- await element.hover();
5071
- await page.mouse.click(clickX, clickY, {
5072
- delay: Math.floor(Math.random() * 1000) + 1000,
5073
- });
5074
- };
5075
-
5076
5045
  class ZapierPage extends IntegrationBase {
5077
5046
  zapierWebPage;
5078
5047
  continueButton;
5079
5048
  mailerUtils;
5049
+ totp;
5080
5050
  zapId;
5081
5051
  zapierLoginEmail;
5082
5052
  zapierLoginPassword;
@@ -5093,11 +5063,15 @@ class ZapierPage extends IntegrationBase {
5093
5063
  neetoPlaywrightUtilities,
5094
5064
  integrationRouteIndex,
5095
5065
  });
5096
- const env = requireEnv("ZAPIER_LOGIN_EMAIL", "ZAPIER_LOGIN_PASSWORD", "ZAP_ID");
5066
+ const env = requireEnv("ZAPIER_LOGIN_EMAIL", "ZAPIER_LOGIN_PASSWORD", "ZAPIER_2FA_SECRET_KEY", "ZAP_ID");
5097
5067
  this.zapierLoginEmail = env.ZAPIER_LOGIN_EMAIL;
5098
5068
  this.zapierLoginPassword = env.ZAPIER_LOGIN_PASSWORD;
5099
5069
  this.zapId = env.ZAP_ID;
5100
5070
  this.mailerUtils = mailerUtils;
5071
+ this.totp = initializeTotp({
5072
+ issuer: "Zapier",
5073
+ secret: env.ZAPIER_2FA_SECRET_KEY,
5074
+ });
5101
5075
  }
5102
5076
  gotoZapEditor = async () => {
5103
5077
  await this.zapierWebPage.goto(THIRD_PARTY_ROUTES.zapier.zapEditor(this.zapId));
@@ -5208,27 +5182,46 @@ class ZapierPage extends IntegrationBase {
5208
5182
  await loginToYourAccountHeading.dblclick({
5209
5183
  delay: Math.floor(Math.random() * 1000) + 300,
5210
5184
  });
5211
- await simulateTypingWithDelay({
5212
- field: emailField,
5213
- value: this.zapierLoginEmail,
5214
- });
5215
- await simulateClickWithDelay({
5216
- element: this.continueButton,
5217
- page: zapierWebPage,
5185
+ await emailField.pressSequentially(this.zapierLoginEmail, {
5186
+ delay: 350,
5187
+ timeout: 25_000,
5218
5188
  });
5189
+ await this.continueButton.click({ delay: 550, timeout: 10_000 });
5219
5190
  await expect(zapierWebPage.getByText(ZAPIER_WEB_TEXTS.welcomeText(this.zapierLoginEmail))).toBeVisible({ timeout: 15_000 });
5220
- await simulateTypingWithDelay({
5221
- field: passwordField,
5222
- value: this.zapierLoginPassword,
5223
- });
5224
- await simulateClickWithDelay({
5225
- element: this.continueButton,
5226
- page: zapierWebPage,
5191
+ await passwordField.pressSequentially(this.zapierLoginPassword, {
5192
+ delay: 350,
5193
+ timeout: 25_000,
5227
5194
  });
5195
+ await this.continueButton.click({ delay: 550, timeout: 10_000 });
5196
+ await this.enterTotpCode();
5228
5197
  await this.zapierWebPage
5229
5198
  .getByTestId(ZAPIER_SELECTORS.accountsMenu)
5230
5199
  .waitFor({ timeout: 25_000 });
5231
5200
  };
5201
+ enterTotpCode = async () => {
5202
+ let previousToken = null;
5203
+ const codeInput = this.zapierWebPage.locator(ZAPIER_SELECTORS.authenticationCode);
5204
+ await expect(codeInput).toBeVisible({ timeout: 20_000 });
5205
+ await expect(async () => {
5206
+ let totpToken = this.totp.generate({ timestamp: Date.now() });
5207
+ if (totpToken === previousToken) {
5208
+ const remainingTime = this.totp.remaining({ timestamp: Date.now() });
5209
+ // Wait for the remaining time plus a small buffer to ensure new token is generated
5210
+ // eslint-disable-next-line playwright/no-wait-for-timeout
5211
+ await this.zapierWebPage.waitForTimeout(remainingTime + 500);
5212
+ totpToken = this.totp.generate({ timestamp: Date.now() });
5213
+ }
5214
+ previousToken = totpToken;
5215
+ if (await codeInput.isHidden())
5216
+ return;
5217
+ await codeInput.fill(totpToken);
5218
+ expect(this.totp.validate({ token: totpToken })).not.toBeNull();
5219
+ await this.zapierWebPage
5220
+ .getByRole("button", { name: ZAPIER_WEB_TEXTS.confirm, exact: true })
5221
+ .click();
5222
+ await expect(codeInput).toBeHidden({ timeout: 20_000 });
5223
+ }).toPass({ timeout: 2 * 60 * 1000 });
5224
+ };
5232
5225
  logoutFromZapier = async () => {
5233
5226
  await this.zapierWebPage.goto(THIRD_PARTY_ROUTES.zapier.logOut, {
5234
5227
  waitUntil: "commit",
@@ -9779,7 +9772,7 @@ function createAppAuth(options) {
9779
9772
 
9780
9773
  const PEM_PATTERN = /(-----BEGIN [A-Z ]+-----)([\s\S]*?)(-----END [A-Z ]+-----)/;
9781
9774
  const PEM_LINE_LENGTH = 64;
9782
- const GITHUB_BOT_ENV_VARIABLES = [
9775
+ const GITHUB_BOT_ENV_VARS = [
9783
9776
  "GITHUB_BOT_APP_ID",
9784
9777
  "GITHUB_BOT_PRIVATE_KEY",
9785
9778
  "GITHUB_BOT_INSTALLATION_ID",
@@ -9792,9 +9785,8 @@ const readPrivateKey = (rawKey) => {
9792
9785
  ? unescaped
9793
9786
  : Buffer.from(rawKey.replace(/\s/g, ""), "base64").toString("utf-8");
9794
9787
  const pem = decoded.match(PEM_PATTERN);
9795
- if (!pem) {
9796
- throw new Error("ENV variable GITHUB_BOT_PRIVATE_KEY is not a PEM key or a base64 encoded PEM key");
9797
- }
9788
+ if (!pem)
9789
+ failTest("ENV variable GITHUB_BOT_PRIVATE_KEY is not a PEM key or a base64 encoded PEM key");
9798
9790
  const [, begin, body, end] = pem;
9799
9791
  const lines = body.replace(/\s/g, "").match(new RegExp(`.{1,${PEM_LINE_LENGTH}}`, "g")) ??
9800
9792
  [];
@@ -9804,12 +9796,12 @@ const readPrivateKey = (rawKey) => {
9804
9796
  const getAppAuth = () => {
9805
9797
  if (cachedAppAuth)
9806
9798
  return cachedAppAuth;
9799
+ const missing = GITHUB_BOT_ENV_VARS.filter(name => isNotPresent(process.env[name]));
9800
+ if (missing.length > 0)
9801
+ failTest(`ENV variables ${missing.join(", ")} are not set. Set all of ${GITHUB_BOT_ENV_VARS.join(", ")}, or set only GITHUB_TOKEN`);
9807
9802
  const appId = process.env.GITHUB_BOT_APP_ID;
9808
9803
  const privateKey = process.env.GITHUB_BOT_PRIVATE_KEY;
9809
9804
  const installationId = process.env.GITHUB_BOT_INSTALLATION_ID;
9810
- if (!appId || !privateKey || !installationId) {
9811
- 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");
9812
- }
9813
9805
  // createAppAuth needs a PKCS#8 key, and the bundled JWT signer does not convert the PKCS#1 key that GitHub issues.
9814
9806
  const privateKeyPkcs8 = createPrivateKey(readPrivateKey(privateKey)).export({
9815
9807
  type: "pkcs8",
@@ -9823,7 +9815,7 @@ const getAppAuth = () => {
9823
9815
  return cachedAppAuth;
9824
9816
  };
9825
9817
  const getGithubToken = async ({ forceRefresh = false, } = {}) => {
9826
- const isGithubBotConfigured = GITHUB_BOT_ENV_VARIABLES.some(name => process.env[name]);
9818
+ const isGithubBotConfigured = GITHUB_BOT_ENV_VARS.some(name => process.env[name]);
9827
9819
  const githubToken = process.env.GITHUB_TOKEN;
9828
9820
  if (!isGithubBotConfigured && githubToken)
9829
9821
  return githubToken;
@@ -10292,9 +10284,8 @@ const isIssueOpen = (issueLink) => {
10292
10284
  .split("/")
10293
10285
  .filter(Boolean);
10294
10286
  const issueNumber = Number(rest.at(-1));
10295
- if (!owner || !repo || !Number.isInteger(issueNumber)) {
10296
- throw new Error(`[isGithubIssueOpen] Invalid GitHub issue link: ${issueLink}`);
10297
- }
10287
+ if (!owner || !repo || !Number.isInteger(issueNumber))
10288
+ failTest(`[isGithubIssueOpen] Invalid GitHub issue link: ${issueLink}`);
10298
10289
  const cacheKey = `${owner}/${repo}#${issueNumber}`;
10299
10290
  const cachedStatus = issueStatusCache.get(cacheKey);
10300
10291
  if (cachedStatus)
@@ -10309,6 +10300,41 @@ const isGithubIssueOpen = async (issueLinks) => {
10309
10300
  return issueStatuses.some(Boolean);
10310
10301
  };
10311
10302
 
10303
+ const simulateTypingWithDelay = async ({ field, value, delay = 500, }) => {
10304
+ const minSliceLength = Math.max(3, Math.floor(value.length * 0.6));
10305
+ const maxSliceLength = Math.max(4, Math.floor(value.length * 0.8));
10306
+ const sliceLength = Math.floor(Math.random() * (maxSliceLength - minSliceLength + 1)) +
10307
+ minSliceLength;
10308
+ const maxBackspaceCount = Math.max(2, Math.min(4, Math.floor(sliceLength * 0.3)));
10309
+ const backspaceCount = Math.floor(Math.random() * (maxBackspaceCount - 1)) + 2;
10310
+ const textPart1 = value.slice(0, sliceLength);
10311
+ const textPart2 = value.slice(sliceLength - backspaceCount);
10312
+ await field.hover();
10313
+ await field.click({ delay: Math.floor(Math.random() * delay) + 700 });
10314
+ await field.pressSequentially(textPart1, {
10315
+ delay: Math.floor(Math.random() * delay) + 400,
10316
+ timeout: 30_000,
10317
+ });
10318
+ for (let i = 0; i < backspaceCount; i++) {
10319
+ await field.press("Backspace", {
10320
+ delay: Math.floor(Math.random() * 1000) + 300,
10321
+ });
10322
+ }
10323
+ await field.pressSequentially(textPart2, {
10324
+ delay: Math.floor(Math.random() * delay) + 700,
10325
+ timeout: 45_000,
10326
+ });
10327
+ };
10328
+ const simulateClickWithDelay = async ({ element, page, }) => {
10329
+ const locatorBoundingBox = await element.boundingBox();
10330
+ const clickX = locatorBoundingBox.x + locatorBoundingBox.width / 2 + 10;
10331
+ const clickY = locatorBoundingBox.y + locatorBoundingBox.height / 2 - 10;
10332
+ await element.hover();
10333
+ await page.mouse.click(clickX, clickY, {
10334
+ delay: Math.floor(Math.random() * 1000) + 1000,
10335
+ });
10336
+ };
10337
+
10312
10338
  const phoneCodeToIsoMap = new Map(Object.entries(countries).flatMap(([isoCode, countryData]) => countryData?.phone?.map(phoneCode => [phoneCode, isoCode])));
10313
10339
  const getIsoCodeFromPhoneCode = (phoneCode) => {
10314
10340
  const numericCode = Number(phoneCode.replace(/^\+/, ""));
@@ -11059,9 +11085,8 @@ class EmailDeliveryUtils {
11059
11085
  callback: async () => lastResult?.exists ? (lastResult.email ?? null) : null,
11060
11086
  timeout,
11061
11087
  }));
11062
- if (!email && shouldThrowErrorOnTimeout) {
11063
- throw new Error(`Timed out waiting for ${provider} email matching subject "${subject}"`);
11064
- }
11088
+ if (!email && shouldThrowErrorOnTimeout)
11089
+ failTest(`Timed out waiting for ${provider} email matching subject "${subject}"`);
11065
11090
  return email;
11066
11091
  };
11067
11092
  }
@@ -11432,4 +11457,4 @@ class InboundEmailApis {
11432
11457
  };
11433
11458
  }
11434
11459
 
11435
- 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, filterUtils, fixedMenuSelector, generatePhoneNumber, generatePhoneNumberDetails, generateRandomBypassEmail, generateRandomFile, generateStagingData, getByDataQA, getClipboardContent, getFormattedPhoneNumber, getFullUrl, getGithubToken, getGlobalUserProps, getGlobalUserState, getImagePathAndName, getIsoCodeFromPhoneCode, getListCount, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, saveStorageState, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };
11460
+ 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, globalShortcuts, grantClipboardPermissions, hexToRGB, hexToRGBA, i18nFixture, imageRegex, initializeCredentials, initializeReviewAppCredentials, initializeTestData, initializeTotp, isGithubIssueOpen, isStagingOrganizationExpired, joinHyphenCase, joinString, login, loginToReviewApp, mailpitDomainName, minutesAgo, networkConditions, networkThrottlingUsingCDP, optionSelector, readFileAsBrowserFile, readFileSyncIfExists, removeCredentialFile, requireEnv, reviewAppBaseURL, reviewAppOrganizationOptions, saveStorageState, serializeFileForBrowser, shouldSkipCustomDomainSetup, shouldSkipSetupAndTeardown, simulateClickWithDelay, simulateTypingWithDelay, skipTest, squish, stealth as stealthTest, tableUtils, toCamelCase, updateCredentials, waitForReviewApp, warmup, withCookieCache, writeDataToFile };