Files
anidev-design-system/tests/package.mjs
T

570 lines
21 KiB
JavaScript

import assert from "node:assert/strict";
import { readFile, readdir, cp, mkdir, mkdtemp } from "node:fs/promises";
import { createHash } from "node:crypto";
import http from "node:http";
import path from "node:path";
import { chromium } from "playwright";
const pkg = path.resolve("dist/package");
const metadata = JSON.parse(
await readFile(path.join(pkg, "package.json"), "utf8"),
);
const manifest = JSON.parse(
await readFile(path.join(pkg, "manifest.json"), "utf8"),
);
assert.equal(manifest.version, metadata.version);
assert.equal(
metadata.version,
JSON.parse(await readFile("package.json", "utf8")).version,
);
assert.equal(metadata.private, true);
for (const file of Object.keys(manifest.files).filter((file) =>
file.endsWith(".md"),
)) {
const markdown = await readFile(path.join(pkg, file), "utf8");
for (const [, link] of markdown.matchAll(/\]\(([^)]+)\)/g)) {
if (/^(https?:|#)/.test(link)) continue;
const target = path.resolve(pkg, path.dirname(file), link.split("#")[0]);
assert.ok(
target.startsWith(pkg + path.sep),
`Link escapes package: ${file}`,
);
await readFile(target);
}
}
for (const [file, hash] of Object.entries(manifest.files)) {
assert.equal(
createHash("sha256")
.update(await readFile(path.join(pkg, file)))
.digest("hex"),
hash,
file,
);
assert.ok(
!/^(playground|patterns\/demo-identity|prompts|\.research|node_modules)\//.test(
file,
),
file,
);
}
const api = await import(
new URL("../dist/package/runtime/index.js", import.meta.url)
);
assert.ok(api.iconNames.length >= 64);
assert.throws(() =>
api.validateNavigation([
{ id: "same", label: "A", icon: "dashboard" },
{ id: "same", label: "B", icon: "server" },
]),
);
assert.throws(() =>
api.validateNavigation([{ id: "bad", label: "A", icon: "missing" }]),
);
assert.throws(() =>
api.validateNavigation([
{
id: "bad",
label: "A",
icon: "server",
children: [{ id: "nested", label: "B", icon: "server", children: [] }],
},
]),
);
for (const file of Object.keys(manifest.files).filter((file) =>
/\.(css|js)$/.test(file),
)) {
const content = await readFile(path.join(pkg, file), "utf8");
const refs = [
...content.matchAll(
/(?:from\s*["']|import\s*["']|import\(["']|url\(["']?)(\.{1,2}\/[^"')\s]+)/g,
),
];
for (const [, ref] of refs)
await readFile(path.resolve(pkg, path.dirname(file), ref.split("?")[0]));
}
const skill = path.resolve("dist/skills/anidev-design-system");
const skillText = await readFile(path.join(skill, "SKILL.md"), "utf8");
for (const [, link] of skillText.matchAll(/\]\(([^)]+)\)/g)) {
const target = path.resolve(skill, link);
assert.ok(target.startsWith(skill + path.sep));
await readFile(target);
}
await mkdir("test-results", { recursive: true });
const consumer = await mkdtemp(path.resolve("test-results/consumer-"));
await cp("dist/starter", consumer, { recursive: true });
const original = JSON.parse(
await readFile(path.join(consumer, "api/navigation.json"), "utf8"),
);
let config = structuredClone(original),
configDelay = 0,
failMenu = false,
failPage = false;
let account = JSON.parse(
await readFile(path.join(consumer, "api/account.json"), "utf8"),
),
pageFailure = null,
menuFailure = null;
const pageDelays = {};
const mime = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
".json": "application/json",
".svg": "image/svg+xml",
};
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost"),
pathname = decodeURIComponent(url.pathname);
if (pathname === "/api/account.json") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(account));
return;
}
if (pageFailure && pathname.startsWith("/api/pages/")) {
res.writeHead(pageFailure.status, { "Content-Type": "application/json" });
res.end(JSON.stringify(pageFailure.body));
return;
}
if (pathname === "/api/navigation.json") {
if (menuFailure) {
res.writeHead(menuFailure.status, {
"Content-Type": "application/json",
});
res.end(JSON.stringify(menuFailure.body));
return;
}
const snapshot = JSON.stringify(config),
delay = configDelay;
if (failMenu) {
res.writeHead(503);
res.end();
return;
}
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(snapshot);
return;
}
if (failPage && pathname.startsWith("/api/pages/")) {
res.writeHead(503);
res.end();
return;
}
const file = path.resolve(
consumer,
"." + (pathname.endsWith("/") ? pathname + "index.html" : pathname),
);
if (!file.startsWith(consumer + path.sep)) throw Error();
const body = await readFile(file);
if (pageDelays[pathname])
await new Promise((resolve) => setTimeout(resolve, pageDelays[pathname]));
res.writeHead(200, {
"Content-Type": mime[path.extname(file)] || "application/octet-stream",
"Cache-Control": "no-store",
});
res.end(body);
} catch {
res.writeHead(404);
res.end();
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({
executablePath:
process.env.PLAYWRIGHT_EXECUTABLE_PATH ||
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
headless: true,
});
const page = await browser.newPage({
permissions: ["clipboard-read", "clipboard-write"],
});
const errors = [],
requests = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (r) => requests.push(r.url()));
await mkdir("references/integration", { recursive: true });
let passed = 0;
try {
for (const width of [1440, 768, 390]) {
await page.setViewportSize({ width, height: 900 });
await page.goto(origin);
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
for (const theme of ["light", "dark"]) {
if ((await page.locator("body").getAttribute("data-theme")) !== theme)
await page.locator("#theme-toggle").click();
assert.equal(
await page.locator("body").getAttribute("data-theme"),
theme,
);
await page.waitForTimeout(280);
await page.screenshot({
path: `references/integration/${theme}-${width}.png`,
fullPage: true,
});
assert.equal(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
true,
);
passed++;
}
const before = await page.locator(".main-column").boundingBox();
await page.locator(".dock-brand").click();
await page.waitForTimeout(280);
const after = await page.locator(".main-column").boundingBox();
assert.equal(before.x, after.x);
assert.equal(before.width, after.width);
assert.equal(
await page.locator(".main-column").evaluate((e) => e.inert),
true,
);
await page.locator('[data-nav-toggle="administration"]').click();
await page.locator('[data-nav-id="logs"]').click();
await page.locator("#page-title").filter({ hasText: "Логи" }).waitFor();
assert.equal(
await page.locator(".dock-brand").getAttribute("aria-expanded"),
"true",
);
await page.keyboard.press("Escape");
await page.locator("[data-copy-input]").click();
assert.equal(
await page.evaluate(() => navigator.clipboard.readText()),
"anidev-production",
);
await page.locator("[data-toast-dismiss]").click();
await page.locator(".search-select-trigger").click();
await page.locator('[role="combobox"]').fill("stag");
await page.keyboard.press("Enter");
assert.equal(
await page.locator('input[name="environment"]').inputValue(),
"staging",
);
passed++;
}
await page.setViewportSize({ width: 1440, height: 900 });
// Menu refresh preserves an available active leaf, focus, group and open Dock.
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="logs"]').focus();
config = structuredClone(original);
config.items[2].children[0].label = "Логи сервера";
await page.evaluate(() =>
document.querySelector("#refresh-navigation").click(),
);
await page
.locator('[data-nav-id="logs"]')
.filter({ hasText: "Логи сервера" })
.waitFor();
assert.equal(
await page.locator('[data-nav-id="logs"]').getAttribute("aria-current"),
"page",
);
assert.equal(
await page.evaluate(() => document.activeElement?.dataset.navId),
"logs",
);
assert.equal(
await page.locator(".dock-brand").getAttribute("aria-expanded"),
"true",
);
await page.waitForTimeout(280);
await page.screenshot({
path: "references/integration/dynamic-menu-dark.png",
});
await page.keyboard.press("Tab");
assert.equal(
await page
.locator(".dock-account")
.evaluate((e) => e === document.activeElement),
true,
);
await page.keyboard.press("Tab");
assert.equal(
await page
.locator(".dock-brand")
.evaluate((e) => e === document.activeElement),
true,
);
await page.keyboard.press("Shift+Tab");
assert.equal(
await page
.locator(".dock-account")
.evaluate((e) => e === document.activeElement),
true,
);
await page.keyboard.press("Shift+Tab");
assert.equal(
await page.evaluate(() => document.activeElement?.dataset.navId),
"logs",
);
await page.keyboard.press("Escape");
passed++;
config = { items: [original.items[1]], defaultPage: "projects" };
await page.locator("#refresh-navigation").click();
await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor();
assert.equal(await page.locator("[data-nav-id]").count(), 1);
assert.equal(new URL(page.url()).searchParams.get("page"), "projects");
passed++;
config = { items: [] };
await page.locator("#refresh-navigation").click();
await page
.locator("#page-title")
.filter({ hasText: "Нет доступных разделов" })
.waitFor();
assert.equal(await page.locator("#page-data").innerText(), "");
passed++;
config = structuredClone(original);
await page.locator("#refresh-navigation").click();
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
failMenu = true;
await page.locator("#refresh-navigation").click();
await page
.locator("#connection-status")
.filter({ hasText: "Не удалось" })
.waitFor();
assert.equal(await page.locator('[data-nav-id="overview"]').count(), 1);
await page.locator("[data-toast-dismiss]").click();
failMenu = false;
passed++;
config = {
items: [
{
id: "injected",
label: "<img src=x onerror=alert(1)>",
icon: "dashboard",
},
],
};
await page.locator("#refresh-navigation").click();
await page.locator('[data-nav-id="injected"]').waitFor();
assert.equal(await page.locator(".navigation img").count(), 0);
await page.locator('[data-error-status="404"]').waitFor();
passed++;
config = { items: [{ id: "bad", label: "Bad", icon: "unknown" }] };
await page.locator("#refresh-navigation").click();
await page
.locator("#connection-status")
.filter({ hasText: "Не удалось" })
.waitFor();
assert.equal(await page.locator('[data-nav-id="injected"]').count(), 1);
await page.locator("[data-toast-dismiss]").click();
passed++;
// A slow previous menu must not overwrite a newer response.
config = { items: [original.items[1]] };
configDelay = 500;
await page.locator("#refresh-navigation").click();
await page.waitForTimeout(80);
config = structuredClone(original);
configDelay = 0;
await page.locator("#refresh-navigation").click();
await page.locator('[data-nav-id="overview"]').waitFor();
await page.waitForTimeout(550);
assert.equal(await page.locator('[data-nav-id="overview"]').count(), 1);
passed++;
failPage = true;
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="projects"]').click();
await page.keyboard.press("Escape");
await page.locator('[data-error-status="503"]').waitFor();
failPage = false;
await page.getByRole("button", { name: "Повторить", exact: true }).click();
await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor();
passed++;
pageDelays["/api/pages/overview.json"] = 500;
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="overview"]').click();
if (
(await page
.locator('[data-nav-toggle="administration"]')
.getAttribute("aria-expanded")) !== "true"
)
await page.locator('[data-nav-toggle="administration"]').click();
await page.locator('[data-nav-id="logs"]').click();
await page.keyboard.press("Escape");
await page.locator("#page-title").filter({ hasText: "Логи" }).waitFor();
await page.waitForTimeout(550);
assert.equal(await page.locator("#page-title").innerText(), "Логи");
pageDelays["/api/pages/overview.json"] = 0;
passed++;
// Fixed account routes survive an empty service menu and reloads.
config = { items: [] };
await page.locator("#refresh-navigation").click();
await page
.locator("#page-title")
.filter({ hasText: "Нет доступных разделов" })
.waitFor();
await page.locator(".dock-brand").click();
await page.locator(".dock-account").click();
await page.locator('[data-account-page="account"]').click();
await page.keyboard.press("Escape");
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
assert.equal(await page.locator("[data-nav-id]").count(), 0);
await page
.getByRole("button", { name: "Настройки аккаунта", exact: true })
.click();
await page.locator('input[name="account-theme"][value="light"]').check();
assert.equal(await page.locator("body").getAttribute("data-theme"), "light");
await page.reload();
await page
.locator("#page-title")
.filter({ hasText: "Настройки аккаунта" })
.waitFor();
passed++;
// Normal service clicks still render after leaving a fixed account route.
config = structuredClone(original);
await page.locator("#refresh-navigation").click();
await page.locator('[data-nav-id="projects"]').waitFor();
assert.equal(
new URL(page.url()).searchParams.get("page"),
"account-settings",
);
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="projects"]').click();
await page.keyboard.press("Escape");
await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor();
passed++;
// Live ban: plain 403 is distinct from ACCOUNT_BANNED and never leaks HTML.
pageFailure = { status: 403, body: { error: { code: "FORBIDDEN" } } };
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="overview"]').click();
await page.keyboard.press("Escape");
await page.locator('[data-error-status="403"]').waitFor();
assert.equal(await page.locator(".error-page-reason").count(), 0);
passed++;
pageFailure = {
status: 403,
body: {
error: {
code: "ACCOUNT_BANNED",
reason: "<img src=x>\nПричина из API",
requestId: "req-test",
},
},
};
await page.locator(".dock-brand").click();
await page.locator('[data-nav-id="projects"]').click();
await page.keyboard.press("Escape");
await page.locator('[data-error-status="banned"]').waitFor();
assert.equal(await page.locator(".error-page-reason img").count(), 0);
assert.equal(
await page.locator(".error-page-reason p").innerText(),
"<img src=x>\nПричина из API",
);
assert.equal(await page.locator("[data-nav-id]").count(), 0);
assert.equal(await page.locator(".integration-form").isVisible(), false);
await page.locator('[data-error-action="account"]').click();
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
passed++;
// Server reports a ban at bootstrap; account/settings remain reachable.
pageFailure = null;
account = {
...account,
status: "banned",
banReason: "Блокировка на сервере",
};
await page.goto(origin + "/?page=logs");
await page.locator('[data-error-status="banned"]').waitFor();
assert.equal(await page.locator("[data-nav-id]").count(), 0);
await page.locator('[data-error-action="account"]').click();
await page
.getByRole("button", { name: "Настройки аккаунта", exact: true })
.click();
await page
.locator("#page-title")
.filter({ hasText: "Настройки аккаунта" })
.waitFor();
passed++;
account = { ...account, status: "active", banReason: null };
await page.goto(origin + "/?page=missing-page");
await page.locator('[data-error-status="404"]').waitFor();
await page.locator('[data-error-action="home"]').click();
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
passed++;
config = { items: [] };
await page.goto(origin + "/?page=logs");
await page.locator('[data-error-status="403"]').waitFor();
passed++;
config = structuredClone(original);
await page.goto(origin + "/?page=overview");
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
menuFailure = { status: 401, body: { error: { code: "UNAUTHENTICATED" } } };
await page.locator("#refresh-navigation").click();
await page.locator('[data-error-status="401"]').waitFor();
assert.equal(await page.locator("[data-nav-id]").count(), 0);
assert.equal(await page.locator(".resource-row").count(), 0);
passed++;
menuFailure = {
status: 403,
body: { error: { code: "ACCOUNT_BANNED", reason: "Изменение доступа" } },
};
await page.locator("#refresh-navigation").click();
await page.locator('[data-error-status="banned"]').waitFor();
await page.locator('[data-error-action="account"]').click();
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
passed++;
menuFailure = null;
// Core modules also work independently of the starter's host logic.
await page.goto(origin + "/?page=error-502");
await page.locator('[data-error-status="502"]').waitFor();
assert.equal(await page.locator(".error-page-code").innerText(), "502");
assert.equal(await page.locator(".integration-form").isVisible(), false);
passed++;
await page.evaluate(async () => {
const { createNotifier, mountCopyField, mountAccountMenu } =
await import("/anidev/runtime/index.js");
const toast = document.createElement("div");
document.body.append(toast);
const notify = createNotifier(toast);
notify("Before dispose", { duration: 0 });
notify.dispose();
notify("After dispose");
if (toast.matches(":popover-open"))
throw Error("Notifier survived dispose");
const root = document.createElement("div");
root.innerHTML =
'<input value="test"><button data-copy-input>copy</button>';
document.body.append(root);
Object.defineProperty(navigator.clipboard, "writeText", {
configurable: true,
value: () => Promise.reject(Error("denied")),
});
window.copyResult = null;
const cleanup = mountCopyField(root, {
notify: (message, options) => (window.copyResult = options.type),
});
root.querySelector("button").click();
await new Promise((resolve) => setTimeout(resolve, 0));
if (window.copyResult !== "error")
throw Error("Clipboard failure not reported");
cleanup();
root.remove();
toast.remove();
const accountRoot = document.createElement("div");
document.body.append(accountRoot);
const menu = mountAccountMenu(accountRoot, { onNavigate: () => {} }),
trigger = accountRoot.querySelector(".dock-account");
trigger.click();
if (!accountRoot.querySelector(".account-menu").matches(":popover-open"))
throw Error("Account menu did not open");
menu.dispose();
trigger.click();
if (accountRoot.querySelector(".account-menu").matches(":popover-open"))
throw Error("Account menu survived dispose");
accountRoot.remove();
});
passed++;
assert.ok(requests.every((url) => url.startsWith(origin + "/")));
assert.ok(
!requests.some((url) => /playground|demo-identity|frame\.js/.test(url)),
);
assert.deepEqual(errors, []);
console.log(
`Package integration: ${passed} checks passed; isolated consumer, dynamic API navigation, theme/layout, clipboard/search, errors/stale responses, cleanup, manifest/imports/skill links.`,
);
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}