Files
snapcad-studio/tests/unit/desktopBridge.test.ts
T
Enes Yakıştır 6769717276
Build and Push Docker Images / build (push) Canceled after 0s
Desktop Release / Build linux desktop (push) Canceled after 0s
Desktop Release / Build windows desktop (push) Canceled after 0s
Desktop Release / Attach packages to release (push) Canceled after 0s
CI / Typecheck and unit tests (push) Canceled after 0s
Desktop Release / Build macos desktop (push) Canceled after 0s
release: SnapCAD Studio 1.0.11 (Mimari BIM & Metraj Studyosu, IFC4 ihraci, canli guncelleme ilerlemesi, YakNet SSO iyilestirmesi)
2026-11-12 11:57:21 +03:00

257 lines
11 KiB
TypeScript

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
exportFiltersForFilename,
formatFriendlyUpdateError,
formatUpdateBytes,
formatUpdateTransferSummary,
getDesktopBridge,
isAllowedExternalUrl,
isDesktopRuntime,
isEditorOnlyMenuAction,
normalizeCloudApiPath,
parseMenuAction,
sanitizeDesktopTitle,
} from "../../apps/web/src/lib/desktopBridge";
import { SKF_CREATED_WITH_VERSION } from "../../apps/web/src/lib/skfProject";
import { SERVICE_WORKER_VERSION } from "../../apps/web/src/lib/serviceWorker";
import type { DesktopMenuAction, SnapCadDesktopBridge } from "../../apps/web/src/types/desktop";
describe("desktopBridge", () => {
it("sanitizes desktop window titles and formats dirty indicator", () => {
expect(sanitizeDesktopTitle(undefined, false)).toBe("SnapCAD Studio");
expect(sanitizeDesktopTitle("SnapCAD Studio", true)).toBe("* SnapCAD Studio");
expect(sanitizeDesktopTitle("Motor Braketi\n\r\t v2", false)).toBe("Motor Braketi v2 — SnapCAD Studio");
expect(sanitizeDesktopTitle("Motor Braketi", true)).toBe("* Motor Braketi — SnapCAD Studio");
expect(sanitizeDesktopTitle("Bileşen — SnapCAD Studio", false)).toBe("Bileşen — SnapCAD Studio");
expect(sanitizeDesktopTitle("A".repeat(200), false).length).toBeLessThanOrEqual(140);
});
it("validates desktop menu actions against allowlist", () => {
const samples: DesktopMenuAction[] = [
"file:open",
"file:save-as",
"file:export-stl",
"edit:make-component",
"edit:chamfer",
"view:zoom-extents",
"view:toggle-tray",
"view:style-blueprint",
"camera:isometric",
"camera:two-point",
"draw:shape-box",
"draw:sketch-extrude",
"tool:push-pull",
"tool:wall-opening",
"tool:physics-toggle",
"tray:entity-info",
"tray:outliner",
"window:settings",
"window:command-palette",
"window:keymap-classic",
"help:audit",
"help:tutorial",
];
for (const action of samples) {
expect(parseMenuAction(action)).toBe(action);
}
expect(parseMenuAction("file:delete-system32")).toBeNull();
expect(parseMenuAction(42)).toBeNull();
});
it("distinguishes global vs 3D-editor-only menu commands", () => {
expect(isEditorOnlyMenuAction("file:new")).toBe(false);
expect(isEditorOnlyMenuAction("file:open")).toBe(false);
expect(isEditorOnlyMenuAction("file:save-and-update")).toBe(false);
expect(isEditorOnlyMenuAction("file:dashboard")).toBe(false);
expect(parseMenuAction("file:save-and-update")).toBe("file:save-and-update");
expect(isEditorOnlyMenuAction("window:drawing")).toBe(false);
expect(isEditorOnlyMenuAction("window:classrooms")).toBe(false);
expect(isEditorOnlyMenuAction("window:shared")).toBe(false);
expect(isEditorOnlyMenuAction("window:command-palette")).toBe(false);
expect(isEditorOnlyMenuAction("window:a11y")).toBe(false);
expect(isEditorOnlyMenuAction("window:settings")).toBe(false);
expect(isEditorOnlyMenuAction("help:shortcuts")).toBe(false);
expect(isEditorOnlyMenuAction("file:export-stl")).toBe(true);
expect(isEditorOnlyMenuAction("edit:delete")).toBe(true);
expect(isEditorOnlyMenuAction("view:xray")).toBe(true);
expect(isEditorOnlyMenuAction("camera:isometric")).toBe(true);
expect(isEditorOnlyMenuAction("draw:shape-box")).toBe(true);
expect(isEditorOnlyMenuAction("tool:push-pull")).toBe(true);
expect(isEditorOnlyMenuAction("tool:physics-toggle")).toBe(true);
expect(isEditorOnlyMenuAction("tray:outliner")).toBe(true);
expect(isEditorOnlyMenuAction("window:workspace-settings")).toBe(true);
expect(isEditorOnlyMenuAction("help:audit")).toBe(true);
});
it("keeps native Electron menu items in parity with desktopBridge allowlist and renderer handlers", () => {
const repoRoot = path.resolve(__dirname, "../..");
const mainSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/main.cjs"), "utf8");
const pageSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/page.tsx"), "utf8");
const editorSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/components/SketchForgeEditor.tsx"), "utf8");
const menuBlockMatch = mainSource.match(/function buildNativeApplicationMenu\(\)[\s\S]*?^function setupDesktopIpc\(\)/m);
expect(menuBlockMatch).not.toBeNull();
const menuBlock = menuBlockMatch![0];
for (const label of ["Dosya", "Düzenle", "Görünüm", "Kamera", "Çizim", "Araçlar", "Pencere", "Stüdyolar", "Yardım"]) {
expect(menuBlock).toContain(`label: "${label}"`);
expect(menuBlock).not.toContain(`label: "&${label}"`);
}
const emittedActions = Array.from(menuBlock.matchAll(/sendMenuCommand\("([^"]+)"\)/g)).map((m) => m[1]);
expect(emittedActions.length).toBeGreaterThanOrEqual(90);
for (const action of emittedActions) {
expect(parseMenuAction(action), `parseMenuAction failed for ${action}`).toBe(action);
const handledInPage = pageSource.includes(`case "${action}":`);
const handledInEditor =
editorSource.includes(`case "${action}":`) ||
action.startsWith("draw:shape-") ||
action.startsWith("tray:");
expect(handledInPage || handledInEditor, `Unhandled native menu action: ${action}`).toBe(true);
}
});
it("normalizes and allowlists only relative SnapCAD cloud API paths", () => {
expect(normalizeCloudApiPath("/cloud-api.php")).toBe("/cloud-api.php");
expect(normalizeCloudApiPath(" /cloud-api.php?action=session ")).toBe("/cloud-api.php?action=session");
expect(normalizeCloudApiPath("https://snap.yakhub.com.tr/cloud-api.php?action=session")).toBeNull();
expect(normalizeCloudApiPath("//evil.example/cloud-api.php")).toBeNull();
expect(normalizeCloudApiPath("/login.php")).toBeNull();
expect(normalizeCloudApiPath("/cloud-api.php.evil")).toBeNull();
expect(normalizeCloudApiPath("")).toBeNull();
});
it("formats updater transport errors into readable Turkish copy", () => {
expect(formatFriendlyUpdateError("")).toBe("Güncelleme denetlenemedi.");
expect(formatFriendlyUpdateError("HttpError: 404 Not Found latest.yml")).toContain("henüz yeni bir masaüstü kurulum paketi yayınlanmadı");
expect(formatFriendlyUpdateError("net::ERR_NETWORK")).toContain("İnternet bağlantınızı kontrol edin");
expect(formatFriendlyUpdateError("Özel sunucu mesajı")).toBe("Özel sunucu mesajı");
});
it("formats live update download byte sizes and transfer summaries", () => {
expect(formatUpdateBytes(0)).toBe("0 B");
expect(formatUpdateBytes(512 * 1024)).toBe("512 KB");
expect(formatUpdateBytes(25.4 * 1024 * 1024)).toBe("25.4 MB");
expect(formatUpdateTransferSummary(null)).toBe("");
expect(
formatUpdateTransferSummary({
transferred: 12 * 1024 * 1024,
total: 0,
bytesPerSecond: 0,
}),
).toBe("12.0 MB indirildi");
expect(
formatUpdateTransferSummary({
currentVersion: "1.0.10",
latestVersion: "1.0.11",
updateAvailable: true,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
status: "downloading",
progressPercent: 45,
transferred: 45 * 1024 * 1024,
total: 100 * 1024 * 1024,
bytesPerSecond: 5.2 * 1024 * 1024,
}),
).toBe("45.0 MB / 100.0 MB • 5.2 MB/sn");
});
it("keeps desktop update safeguard and auth sync IPC channels in parity", () => {
const repoRoot = path.resolve(__dirname, "../..");
const mainSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/main.cjs"), "utf8");
const preloadSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/preload.cjs"), "utf8");
const pageSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/page.tsx"), "utf8");
const requiredChannels = [
"snapcad:get-auth-state-sync",
"snapcad:get-auth-state",
"snapcad:open-update-progress",
"snapcad:set-active-work-state",
"snapcad:prepare-before-update",
"snapcad:prepare-before-update-result",
"snapcad:confirm-update-after-save",
"snapcad:cancel-pending-update-install",
];
for (const channel of requiredChannels) {
expect(mainSource, `Missing in main.cjs: ${channel}`).toContain(channel);
expect(preloadSource, `Missing in preload.cjs: ${channel}`).toContain(channel);
}
expect(pageSource).toContain(`case "file:save-and-update":`);
});
it("allows only http and https external URLs", () => {
expect(isAllowedExternalUrl("https://snap.yakhub.com.tr")).toBe(true);
expect(isAllowedExternalUrl("http://127.0.0.1:62158")).toBe(true);
expect(isAllowedExternalUrl("file:///C:/Windows/System32/cmd.exe")).toBe(false);
expect(isAllowedExternalUrl("javascript:alert(1)")).toBe(false);
expect(isAllowedExternalUrl("")).toBe(false);
});
it("selects appropriate Electron file filters by extension", () => {
expect(exportFiltersForFilename("parca.stl")[0].extensions).toEqual(["stl"]);
expect(exportFiltersForFilename("govde.STEP")[0].extensions).toEqual(["step", "stp"]);
expect(exportFiltersForFilename("proje.skf")[0].extensions).toEqual(["skf"]);
expect(exportFiltersForFilename("bilinmeyen.bin")[0].extensions).toEqual(["*"]);
});
it("detects web vs injected Electron preload bridges cleanly", () => {
const globalObj = globalThis as unknown as { window?: Partial<Window> };
const prevWindow = globalObj.window;
try {
globalObj.window = undefined;
expect(isDesktopRuntime()).toBe(false);
expect(getDesktopBridge()).toBeNull();
const mockBridge: SnapCadDesktopBridge = {
isDesktop: true,
getVersion: async () => "1.0.10",
checkForUpdates: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
installUpdate: async () => ({
currentVersion: "1.0.10",
latestVersion: null,
updateAvailable: false,
downloaded: false,
checkedAt: "2026-01-01T00:00:00.000Z",
}),
};
globalObj.window = { snapcadDesktop: mockBridge };
expect(isDesktopRuntime()).toBe(true);
expect(getDesktopBridge()).toBe(mockBridge);
globalObj.window = { sketchforgeDesktop: mockBridge };
expect(isDesktopRuntime()).toBe(true);
expect(getDesktopBridge()).toBe(mockBridge);
} finally {
globalObj.window = prevWindow as Window | undefined;
}
});
it("keeps app version synchronized across package.json, lockfile, SKF metadata, and SW", () => {
const repoRoot = path.resolve(__dirname, "../..");
const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")) as { version: string };
const lock = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8")) as {
version: string;
packages: Record<string, { version?: string }>;
};
const swSource = fs.readFileSync(path.join(repoRoot, "apps/web/public/sw.js"), "utf8");
expect(pkg.version).toBe("1.0.11");
expect(lock.version).toBe(pkg.version);
expect(lock.packages[""]?.version).toBe(pkg.version);
expect(SKF_CREATED_WITH_VERSION).toBe(pkg.version);
expect(swSource).toContain(`const CACHE_NAME = "snapcad-v${SERVICE_WORKER_VERSION}"`);
});
});