Files

198 lines
7.9 KiB
JavaScript
Raw Permalink Normal View History

#!/usr/bin/env node
"use strict";
const { loginViaAuthForm } = require('./lib/browser-auth-login');
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { chromium } = require("playwright");
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|| ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"]
.find((candidate) => fs.existsSync(candidate));
function fileUrl(localPath) {
return `file://${localPath}`;
}
function localMdDocumentId(relativePath) {
return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}
function documentUrl(root, relativePath) {
const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
url.searchParams.set("sourceKind", "local_folder");
url.searchParams.set("rootUri", fileUrl(root));
url.searchParams.set("treeView", "filetree");
return url.toString();
}
function writeWorkspaceManifest(root, ownerId) {
const metadataDir = path.join(root, ".mnote");
fs.mkdirSync(metadataDir, { recursive: true });
fs.writeFileSync(
path.join(metadataDir, "workspace.json"),
`${JSON.stringify({
workspaceId: `local-ws:${ownerId}:task506`,
ownerId,
createdAt: new Date().toISOString(),
capabilities: ["local_files", "markdown_edit", "asset_upload"],
}, null, 2)}\n`,
"utf8",
);
}
async function quickLogin(page) {
// 7-76 P0: 标准表单登录(无测试快速登录按钮)
const base =
(typeof BASE_URL !== "undefined" && BASE_URL) ||
(typeof baseUrl !== "undefined" && baseUrl) ||
process.env.MNOTE_UI_BASE_URL ||
"http://127.0.0.1:3000";
const timeout =
(typeof UI_TIMEOUT_MS !== "undefined" && UI_TIMEOUT_MS) ||
(typeof TIMEOUT !== "undefined" && TIMEOUT) ||
30_000;
if (!String(page.url() || "").includes("/auth")) {
await page.goto(String(base).replace(/\/+$/, "") + "/auth", {
waitUntil: "commit",
timeout,
});
}
await loginViaAuthForm(page, {
baseUrl: base,
timeoutMs: timeout,
gotoAuth: false,
});
await page
.waitForURL((url) => !String(url).includes("/auth"), { timeout })
.catch(() => {});
}
async function openDocument(page, root, relativePath) {
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
}
async function waitForDeletedHomeFallback(page, documentId) {
await page.waitForFunction(
(expectedDocumentId) => {
const url = new URL(window.location.href);
const panelText = document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "";
return url.pathname === "/"
&& url.searchParams.get("missingPage") === expectedDocumentId
&& (url.searchParams.get("routeGuard") === "local_markdown_deleted"
|| url.searchParams.get("routeGuard") === "local_markdown_not_found")
&& !panelText.includes("文件冲突");
},
documentId,
{ timeout: UI_TIMEOUT_MS },
);
return await page.evaluate(() => ({
url: window.location.href,
missingPage: new URL(window.location.href).searchParams.get("missingPage") || "",
routeGuard: new URL(window.location.href).searchParams.get("routeGuard") || "",
panelText: document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
? window.__mnoteDebugDocumentSessions.snapshot()
: null,
}));
}
async function waitForExternalMoveHomeFallback(page, documentId) {
await page.waitForFunction(
(expectedDocumentId) => {
const url = new URL(window.location.href);
const panelText = document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "";
return url.pathname === "/"
&& url.searchParams.get("missingPage") === expectedDocumentId
&& (url.searchParams.get("routeGuard") === "local_markdown_deleted"
|| url.searchParams.get("routeGuard") === "local_markdown_not_found")
&& !panelText.includes("文件冲突");
},
documentId,
{ timeout: UI_TIMEOUT_MS },
);
return await page.evaluate(() => ({
url: window.location.href,
missingPage: new URL(window.location.href).searchParams.get("missingPage") || "",
routeGuard: new URL(window.location.href).searchParams.get("routeGuard") || "",
panelText: document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
? window.__mnoteDebugDocumentSessions.snapshot()
: null,
}));
}
async function main() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task506-lifecycle-"));
const deleteRelativePath = "DeleteMe.md";
const moveRelativePath = "MoveMe.md";
writeWorkspaceManifest(root, "mnote-e2e");
fs.writeFileSync(path.join(root, deleteRelativePath), "# Delete Me\n\n保留删除 buffer\n", "utf8");
fs.writeFileSync(path.join(root, moveRelativePath), "# Move Me\n\n保留移动 buffer\n", "utf8");
const browser = await chromium.launch({
headless: process.env.HEADFUL !== "1",
executablePath: CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext({
viewport: { width: 1366, height: 900 },
extraHTTPHeaders: {
"x-mnote-actor-id": "mnote-e2e",
"x-mnote-actor-type": "user",
},
});
const page = await context.newPage();
try {
await quickLogin(page);
await openDocument(page, root, deleteRelativePath);
fs.rmSync(path.join(root, deleteRelativePath));
const deletedState = await waitForDeletedHomeFallback(page, localMdDocumentId(deleteRelativePath));
await openDocument(page, root, moveRelativePath);
fs.renameSync(path.join(root, moveRelativePath), path.join(root, "Moved.md"));
const movedState = await waitForExternalMoveHomeFallback(page, localMdDocumentId(moveRelativePath));
console.log(JSON.stringify({
ok: true,
root,
states: [
{ step: "external-delete", deletedState },
{ step: "external-rename-as-deleted", movedState },
],
}, null, 2));
} catch (error) {
const diagnostics = await page.evaluate(() => ({
url: location.href,
status: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-status") || "",
statusError: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-error") || "",
editorText: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "",
panelText: document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
? window.__mnoteDebugDocumentSessions.snapshot()
: null,
})).catch((diagnosticsError) => ({ diagnosticsError: String(diagnosticsError) }));
console.error(JSON.stringify({ ok: false, root, diagnostics, error: String(error && error.stack || error) }, null, 2));
process.exitCode = 1;
} finally {
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
main().catch((error) => {
console.error(error && error.stack ? error.stack : error);
process.exit(1);
});