-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaywright.ts
242 lines (223 loc) · 7.59 KB
/
playwright.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import fs from "fs";
import path from "path";
import type { XmtpEnv } from "@xmtp/node-sdk";
import {
chromium,
type Browser,
type BrowserContext,
type Page,
} from "playwright-chromium";
export class XmtpPlaywright {
private browser: Browser | null = null;
private page: Page | null = null;
private isHeadless: boolean = true;
private env: XmtpEnv = "local";
private walletKey: string = "";
private encryptionKey: string = "";
constructor(headless: boolean = true, env: XmtpEnv | null = null) {
this.isHeadless =
process.env.GITHUB_ACTIONS !== undefined ? true : headless;
this.env = env ?? (process.env.XMTP_ENV as XmtpEnv);
this.walletKey = process.env.WALLET_KEY_XMTP_CHAT as string;
this.encryptionKey = process.env.ENCRYPTION_KEY_XMTP_CHAT as string;
this.browser = null;
this.page = null;
}
/**
* Creates a DM with deeplink and checks for GM response
*/
async newDmWithDeeplink(address: string): Promise<boolean> {
const { page, browser } = await this.startPage(false, address);
try {
console.log("Creating DM with deeplink");
console.log("Sending message and waiting for GM response");
const response = await this.sendAndWaitForGm(page, "gm");
console.log("GM response:", response);
return response;
} catch (error) {
console.error("Could not find 'gm' message:", error);
await this.takeSnapshot(page, "before-finding-gm");
return false;
} finally {
if (browser) await browser.close();
}
}
/**
* Creates a group and checks for GM response
*/
async createGroupAndReceiveGm(
addresses: string[],
waitForMessage: boolean = true,
): Promise<void> {
const { page, browser } = await this.startPage(false);
try {
console.log("Filling addresses and creating group");
await this.fillAddressesAndCreate(page, addresses);
console.log("Sending message and waiting for GM response");
const response = await this.sendAndWaitForGm(page, "gm", waitForMessage);
if (!response) {
throw new Error("Failed to receive GM response");
}
} catch (error) {
console.error("Error in createGroupAndReceiveGm:", error);
await this.takeSnapshot(page, "before-finding-gm");
throw error;
} finally {
if (browser) await browser.close();
}
}
async readGroupMessages(
groupId: string,
messages: string[],
): Promise<boolean> {
const { page, browser } = await this.startPage(false);
try {
await page.goto(`https://xmtp.chat/group/${groupId}?env=${this.env}`);
await this.takeSnapshot(page, "before-reading-group-messages");
let allReceived = true;
for (const message of messages) {
// Wait for GM response with a longer timeout
const botMessage = await page.getByText(message);
const botMessageText = await botMessage.textContent();
if (botMessageText !== message) {
allReceived = false;
}
}
return allReceived;
} finally {
if (browser) await browser.close();
}
}
/**
* Takes a screenshot and saves it to the logs directory
*/
async takeSnapshot(page: Page, name: string): Promise<void> {
const snapshotDir = path.join(process.cwd(), "./logs");
if (!fs.existsSync(snapshotDir)) {
fs.mkdirSync(snapshotDir, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const screenshotPath = path.join(snapshotDir, `${name}-${timestamp}.png`);
await page.screenshot({ path: screenshotPath, fullPage: true });
}
// Private helper methods
/**
* Fills addresses and creates a new conversation
*/
private async fillAddressesAndCreate(
page: Page,
addresses: string[],
): Promise<void> {
if (!page) {
throw new Error("Page is not initialized");
}
await page
.getByRole("main")
.getByRole("button", { name: "Create a new group" })
.click();
await page.getByRole("button", { name: "Members" }).click();
for (const address of addresses) {
await page.getByRole("textbox", { name: "Address" }).fill(address);
await page.getByRole("button", { name: "Add" }).click();
}
await page.getByRole("button", { name: "Create" }).click();
}
/**
* Sends a message and optionally waits for GM response
*/
private async sendAndWaitForGm(
page: Page,
message: string,
waitForMessage: boolean = true,
): Promise<boolean> {
try {
// Wait for GM response with a longer timeout
await page?.waitForTimeout(1000);
await page.getByRole("textbox", { name: "Type a message..." }).click();
await page.getByRole("textbox", { name: "Type a message..." }).fill("hi");
await page.getByRole("button", { name: "Send" }).click();
const hiMessage = await page.getByText("hi");
const hiMessageText = await hiMessage.textContent();
console.log("Hi message:", hiMessageText);
if (waitForMessage) {
// Wait for GM response with a longer timeout
await page?.waitForTimeout(3000);
const botMessage = await page.getByText("gm");
const botMessageText = await botMessage.textContent();
console.log("Bot message:", botMessageText);
return botMessageText === "gm";
} else {
return hiMessageText === "hi";
}
} catch (error) {
console.error("Error in sendAndWaitForGm:", error);
throw error;
}
}
/**
* Starts a new page with the specified options
*/
private async startPage(
defaultUser: boolean = false,
address: string = "",
): Promise<{ browser: Browser; page: Page }> {
this.browser = await chromium.launch({
headless: this.isHeadless,
slowMo: this.isHeadless ? 0 : 100,
});
const context: BrowserContext = await this.browser.newContext(
this.isHeadless
? {
viewport: { width: 1920, height: 1080 },
deviceScaleFactor: 1,
}
: {},
);
this.page = await context.newPage();
await this.setLocalStorage(
this.page,
defaultUser ? this.walletKey : "",
defaultUser ? this.encryptionKey : "",
);
let url = "https://xmtp.chat/";
if (address) {
url = `https://xmtp.chat/dm/${address}?env=${this.env}`;
}
console.log("Navigating to:", url);
await this.page.goto(url);
await this.page.waitForTimeout(1000);
await this.page.getByText("Ephemeral", { exact: true }).click();
return { browser: this.browser, page: this.page };
}
/**
* Sets localStorage values for XMTP configuration
*/
private async setLocalStorage(
page: Page,
walletKey: string = "",
walletEncryptionKey: string = "",
): Promise<void> {
await page.addInitScript(
({ envValue, walletKey, walletEncryptionKey }) => {
if (walletKey !== "")
// @ts-expect-error Window localStorage access in browser context
window.localStorage.setItem("XMTP_EPHEMERAL_ACCOUNT_KEY", walletKey);
if (walletEncryptionKey !== "")
// @ts-expect-error Window localStorage access in browser context
window.localStorage.setItem(
"XMTP_ENCRYPTION_KEY",
walletEncryptionKey,
);
// @ts-expect-error Window localStorage access in browser context
window.localStorage.setItem("XMTP_NETWORK", envValue);
// @ts-expect-error Window localStorage access in browser context
window.localStorage.setItem("XMTP_USE_EPHEMERAL_ACCOUNT", "true");
},
{
envValue: this.env,
walletKey: walletKey,
walletEncryptionKey: walletEncryptionKey,
},
);
}
}