File size: 11,165 Bytes
062a991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { chromium } from "playwright";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";

const root = process.cwd();
const baseURL = process.env.BASE_URL || "http://127.0.0.1:3103";
const sqlitePath = process.env.LINKEDIN_SQLITE_PATH;
const outDir = path.join(root, "test-results", "public-main-flow");

await mkdir(outDir, { recursive: true });

async function record(result, exitCode = 0) {
  const payload = {
    generatedAt: new Date().toISOString(),
    baseURL,
    ...result,
  };
  await writeFile(path.join(outDir, "results.json"), JSON.stringify(payload, null, 2));
  console.log(JSON.stringify(payload, null, 2));
  if (exitCode) process.exitCode = exitCode;
}

async function dbVerification({ email, postText, commentText, messageText }) {
  if (!sqlitePath) return { blocked: true, reason: "LINKEDIN_SQLITE_PATH is required for direct database trace verification." };
  const database = new DatabaseSync(sqlitePath, { readOnly: true });
  try {
    const user = database.prepare("select id, email, username, email_verified_at is not null as verified from users where email = ?").get(email);
    if (!user) return { blocked: true, reason: "Registered user was not found in SQLite." };
    const counts = database.prepare(`
      select
        (select count(*) from posts where author_id = ? and content = ?) as posts,
        (select count(*) from comments where author_id = ? and content = ?) as comments,
        (select count(*) from post_likes where user_id = ?) as likes,
        (select count(*) from saved_jobs where user_id = ?) as saved_jobs,
        (select count(*) from job_applications where applicant_id = ?) as job_applications,
        (select count(*) from connections where requester_id = ?) as connection_requests,
        (select count(*) from messages where sender_id = ? and body = ?) as messages
    `).get(user.id, postText, user.id, commentText, user.id, user.id, user.id, user.id, user.id, messageText);
    return { blocked: false, user, counts };
  } finally {
    database.close();
  }
}

async function main() {
  const stamp = Date.now();
  const email = process.env.TEST_PUBLIC_EMAIL || `linkedin.public.e2e.${stamp}@example.test`;
  const username = `e2e${String(stamp).slice(-10)}`;
  const password = process.env.TEST_PUBLIC_PASSWORD || "LinkedInPublic123";
  const postText = `Public main flow post ${stamp}`;
  const commentText = `Public main flow comment ${stamp}`;
  const messageText = `Public main flow message ${stamp}`;
  const steps = [];
  const apiEvents = [];
  const assetErrors = [];
  const runtimeErrors = [];

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1366, height: 900 }, colorScheme: "light" });
  await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
  const page = await context.newPage();

  page.on("pageerror", (error) => {
    runtimeErrors.push({ type: "pageerror", message: error.message });
  });
  page.on("console", (message) => {
    if (message.type() === "error") runtimeErrors.push({ type: "console", message: message.text() });
  });
  page.on("requestfailed", (request) => {
    const url = request.url();
    if (url.startsWith(baseURL) && new URL(url).pathname.startsWith("/_next/static/")) {
      assetErrors.push({ path: new URL(url).pathname, failure: request.failure()?.errorText ?? "request_failed" });
    }
  });

  page.on("response", async (response) => {
    const url = response.url();
    if (!url.startsWith(baseURL)) return;
    const pathname = new URL(url).pathname;
    if (pathname.startsWith("/_next/static/") && response.status() >= 400) {
      assetErrors.push({ path: pathname, status: response.status() });
    }
    if (!pathname.startsWith("/api/")) return;
    const event = { method: response.request().method(), path: pathname, status: response.status() };
    try {
      const body = await response.json();
      if (body?.post?.id) event.postId = body.post.id;
      if (body?.comment?.id) event.commentId = body.comment.id;
      if (body?.application?.id) event.applicationId = body.application.id;
      if (body?.savedJob?.jobId) event.savedJobId = body.savedJob.jobId;
      if (body?.connection?.id) event.connectionId = body.connection.id;
      if (body?.message?.id) event.messageId = body.message.id;
      if (body?.code) event.code = body.code;
      if (body?.error) event.error = body.error;
    } catch {}
    apiEvents.push(event);
  });

  try {
    await page.goto(`${baseURL}/public-register`, { waitUntil: "networkidle" });
    await page.getByLabel("Email").fill(email);
    await page.getByRole("button", { name: "Send code" }).click();
    await page.locator("[data-auth-verification-status][data-state=\"success\"]").waitFor({ timeout: 10000 });
    await page.locator("[data-auth-code]").fill(process.env.PUBLIC_CLONE_AUTH_LOCAL_DEV_CODE || "123456");
    await page.getByRole("button", { name: "Verify" }).click();
    await page.waitForFunction(() => !document.querySelector("[data-auth-create-account]")?.disabled, null, { timeout: 10000 });
    await page.getByLabel("Full name").fill("LinkedIn Public E2E");
    await page.getByLabel("Username").fill(username);
    await page.getByLabel("Password").fill(password);
    await page.locator("[data-auth-create-account]").click();
    await page.waitForURL(/\/feed$/, { timeout: 10000 });
    await page.getByRole("button", { name: /Start a post/i }).waitFor({ timeout: 10000 });
    steps.push({ step: "public-register", result: "created_session", email, username });

    await context.clearCookies();
    await page.goto(`${baseURL}/login`, { waitUntil: "domcontentloaded", timeout: 15000 });
    await page.getByRole("heading", { name: "Sign in" }).waitFor({ timeout: 10000 });
    await page.getByLabel("Email").fill(email);
    await page.getByLabel("Password").fill(password);
    await page.getByRole("button", { name: "Sign in" }).click();
    await page.waitForURL(/\/feed$/, { timeout: 10000 });
    await page.getByRole("button", { name: /Start a post/i }).waitFor({ timeout: 10000 });
    steps.push({ step: "login", result: "signed_in_session_restored" });

    await page.getByRole("button", { name: /Start a post/i }).click();
    await page.getByPlaceholder(/Share an idea/i).fill(postText);
    await page.getByRole("button", { name: "Post", exact: true }).click();
    await page.getByText(postText).waitFor({ timeout: 10000 });
    steps.push({ step: "feed-post", result: "posted" });

    const createdPost = page.locator("article.post-card").filter({ hasText: postText }).first();
    await createdPost.getByRole("button", { name: /Like/i }).click();
    await createdPost.getByRole("button", { name: "Comment", exact: true }).click();
    await createdPost.getByPlaceholder(/Add a comment/i).fill(commentText);
    await createdPost.getByRole("button", { name: "Post", exact: true }).click();
    await createdPost.getByText(commentText).waitFor({ timeout: 10000 });
    steps.push({ step: "feed-actions", result: "liked_and_commented" });

    await page.goto(`${baseURL}/jobs`, { waitUntil: "networkidle" });
    await page.locator(".job-detail").getByRole("button", { name: /^Save$/ }).click();
    await page.locator(".job-detail").getByRole("button", { name: /Saved/i }).waitFor({ timeout: 10000 });
    await page.locator(".job-detail").getByRole("button", { name: /Easy Apply/i }).click();
    await page.getByRole("dialog", { name: /Apply to/i }).waitFor({ timeout: 10000 });
    await page.getByRole("button", { name: "Submit application" }).click();
    await page.locator(".job-detail").getByRole("button", { name: /Applied/i }).waitFor({ timeout: 10000 });
    steps.push({ step: "jobs", result: "saved_and_applied" });

    await page.goto(`${baseURL}/my-network`, { waitUntil: "networkidle" });
    await page.getByText("People you may know").waitFor({ timeout: 10000 });
    const connectButton = page.locator(".person-card").getByRole("button", { name: /Connect/i }).first();
    if (await connectButton.isVisible().catch(() => false)) {
      await connectButton.click();
      await page.locator(".person-card").getByRole("button", { name: /Pending/i }).first().waitFor({ timeout: 10000 });
      steps.push({ step: "network", result: "connection_requested" });
    } else {
      steps.push({ step: "network", result: "no_connectable_suggestions" });
    }

    await page.goto(`${baseURL}/messages`, { waitUntil: "networkidle" });
    await page.getByPlaceholder(/Write a message/i).fill(messageText);
    await page.getByRole("button", { name: /Send/i }).click();
    await page.getByText(messageText).waitFor({ timeout: 10000 });
    steps.push({ step: "messages", result: "sent" });

    await page.goto(`${baseURL}/search?q=Product`, { waitUntil: "networkidle" });
    await page.getByText(/Results for/i).waitFor({ timeout: 10000 });
    steps.push({ step: "search", result: "results_visible" });

    await page.goto(`${baseURL}/premium`, { waitUntil: "networkidle" });
    await page.locator(".premium-trust").getByText("Stripe Test Mode", { exact: true }).waitFor({ timeout: 10000 });
    steps.push({ step: "premium", result: "test_mode_guardrail_visible" });

    const body = await page.locator("body").innerText();
    if (body.includes("Something went wrong")) throw new Error("Global error boundary is visible after main flow.");
    if (body.includes("Loading LinkedIn")) throw new Error("Application is still stuck on the loading boundary.");
    if (assetErrors.length) throw new Error(`Static asset failures detected: ${JSON.stringify(assetErrors)}`);
    if (runtimeErrors.length) throw new Error(`Browser runtime errors detected: ${JSON.stringify(runtimeErrors)}`);
    await page.screenshot({ path: path.join(outDir, "final.png"), fullPage: true, animations: "disabled" });
    await context.tracing.stop({ path: path.join(outDir, "trace.zip") });

    const db = await dbVerification({ email, postText, commentText, messageText });
    if (db.blocked) {
      await record({ blocked: true, steps, apiEvents, assetErrors, runtimeErrors, db }, 2);
      return;
    }
    const missing = Object.entries(db.counts).filter(([, value]) => Number(value) < 1).map(([key]) => key);
    if (missing.length) throw new Error(`Database verification missing rows for: ${missing.join(", ")}`);
    await record({ blocked: false, steps, apiEvents, assetErrors, runtimeErrors, db, artifacts: { screenshot: path.join(outDir, "final.png"), trace: path.join(outDir, "trace.zip") } });
  } catch (error) {
    await page.screenshot({ path: path.join(outDir, "failure.png"), fullPage: true, animations: "disabled" }).catch(() => {});
    await context.tracing.stop({ path: path.join(outDir, "trace.zip") }).catch(() => {});
    await record({ blocked: true, steps, apiEvents, assetErrors, runtimeErrors, reason: error instanceof Error ? error.message : "unknown", artifacts: { screenshot: path.join(outDir, "failure.png"), trace: path.join(outDir, "trace.zip") } }, 2);
  } finally {
    await browser.close();
  }
}

await main();