示例工程 09-typed-ipc-contracts
09-typed-ipc-contracts/app/.tsc/src/renderer.js
import "./styles.css";
const state = {
tab: "contract",
title: "IPC 契约笔记",
body: "请求与响应类型只定义一次,三端引用同一份 shared/ipc.ts。",
tags: "ipc, types",
notes: [],
response: null,
error: null,
report: null,
busy: false,
};
const tabs = [
{ id: "contract", label: "契约" },
{ id: "error", label: "错误" },
{ id: "cases", label: "校验用例" },
];
function escapeHtml(value) {
return value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
function json(value) {
return escapeHtml(JSON.stringify(value, null, 2));
}
function time(at) {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function contractTab() {
return `<div class="section">
<h2>请求 / 响应</h2>
<p class="hint">页面只能按 <code>CreateNoteReq</code> 传值;主进程第一行仍然要校验,因为 TS 管不到运行期。</p>
<div class="form">
<label>title<input id="title-input" data-testid="title-input" value="${escapeHtml(state.title)}" /></label>
<label>body<input id="body-input" data-testid="body-input" value="${escapeHtml(state.body)}" /></label>
<label>tags<input id="tags-input" data-testid="tags-input" value="${escapeHtml(state.tags)}" /></label>
</div>
<div class="row">
<button class="tab active" id="create-button" data-testid="create-button">创建笔记</button>
<button class="mini" id="bad-empty" data-testid="bad-empty">空标题</button>
<button class="mini" id="bad-tags" data-testid="bad-tags">6 个 tags</button>
<button class="mini" id="bad-extra" data-testid="bad-extra">未知字段</button>
</div>
<table class="table" data-testid="note-table">
<thead><tr><th>ID</th><th>标题</th><th>tags</th><th>创建时间</th></tr></thead>
<tbody>
${state.notes
.map((note) => `<tr data-testid="note-row">
<td><code>${note.id}</code></td>
<td>${escapeHtml(note.title)}</td>
<td>${note.tags.map((tag) => `<code>${escapeHtml(tag)}</code>`).join(" ")}</td>
<td><code>${time(note.createdAt)}</code></td>
</tr>`)
.join("")}
</tbody>
</table>
<div class="panel">
<div class="panel-label">最后一次响应</div>
<pre class="code" data-testid="response-json">${state.response ? json(state.response) : "(还没有请求)"}</pre>
</div>
</div>`;
}
function errorTab() {
const error = state.error;
const body = error
? `<div class="grid">
<div class="card"><div class="card-label">code</div><div class="card-value" data-testid="error-code">${escapeHtml(error.code)}</div></div>
<div class="card"><div class="card-label">requestId</div><div class="card-value small" data-testid="error-request-id">${escapeHtml(error.requestId)}</div></div>
<div class="card"><div class="card-label">detail</div><div class="card-value small" data-testid="error-detail">${escapeHtml(error.detail ?? "(无)")}</div></div>
<div class="card"><div class="card-label">stack</div><div class="card-value small" data-testid="error-stack">不在返回里</div></div>
</div>
<div class="panel">
<div class="panel-label">页面收到的完整对象</div>
<pre class="code" data-testid="error-json">${json(error)}</pre>
</div>
<p class="hint">错误对象只有 <code>code / message / detail / requestId</code>;主进程堆栈只写主进程日志。</p>`
: `<p class="hint">先在上一个页签点「空标题」或「未知字段」。</p>`;
return `<div class="section">
<h2>结构化错误</h2>
${body}
</div>`;
}
function casesTab() {
const report = state.report;
const body = report
? `<div class="row">
<span class="badge" data-testid="cases-summary">${report.passed} / ${report.total} 通过</span>
<span class="badge">失败 ${report.failed}</span>
</div>
<table class="table" data-testid="case-table">
<thead><tr><th>用例</th><th>期望</th><th>实际</th><th>结果</th></tr></thead>
<tbody>
${report.cases
.map((item) => `<tr data-testid="case-row">
<td>${escapeHtml(item.name)}</td>
<td><code>${escapeHtml(item.expected)}</code></td>
<td><code>${escapeHtml(item.actual)}</code></td>
<td>${item.ok ? "PASS" : "FAIL"}</td>
</tr>`)
.join("")}
</tbody>
</table>`
: `<p class="hint">点「运行校验用例」,主进程会用同一份 shared/ipc.ts 跑 10 条断言。</p>`;
return `<div class="section">
<h2>校验用例</h2>
<div class="row">
<button class="tab active" id="cases-button" data-testid="cases-button">运行校验用例</button>
</div>
${body}
</div>`;
}
function render() {
const root = document.querySelector("#app");
if (!root)
return;
const body = state.tab === "contract"
? contractTab()
: state.tab === "error"
? errorTab()
: casesTab();
root.innerHTML = `
<header class="header">
<div>
<h1 data-testid="app-title">类型安全 IPC 契约</h1>
<p class="subtitle">shared/ipc.ts · 手写校验 · 结构化错误</p>
</div>
<nav class="tabs">
${tabs
.map((tab) => `<button class="tab${state.tab === tab.id ? " active" : ""}" data-tab="${tab.id}" data-testid="tab-${tab.id}">${tab.label}</button>`)
.join("")}
</nav>
</header>
<main class="content">${body}</main>`;
for (const button of root.querySelectorAll("[data-tab]")) {
button.addEventListener("click", () => {
const tab = button.dataset.tab;
if (tab === "contract" || tab === "error" || tab === "cases") {
state.tab = tab;
render();
}
});
}
const readForm = () => {
const title = root.querySelector("#title-input");
const bodyInput = root.querySelector("#body-input");
const tags = root.querySelector("#tags-input");
state.title = title?.value ?? "";
state.body = bodyInput?.value ?? "";
state.tags = tags?.value ?? "";
return {
title: state.title,
body: state.body,
tags: state.tags
.split(",")
.map((tag) => tag.trim())
.filter(Boolean),
};
};
root.querySelector("#create-button")?.addEventListener("click", () => {
void create(readForm());
});
root.querySelector("#bad-empty")?.addEventListener("click", () => {
void create({ title: " ", body: "正文" });
});
root.querySelector("#bad-tags")?.addEventListener("click", () => {
void createRaw({
title: "tags 太多",
body: "正文",
tags: ["a", "b", "c", "d", "e", "f"],
});
});
root.querySelector("#bad-extra")?.addEventListener("click", () => {
void createRaw({ title: "未知字段", body: "正文", extra: true });
});
root.querySelector("#cases-button")?.addEventListener("click", () => {
void runCases();
});
}
async function create(req) {
if (state.busy)
return;
state.busy = true;
try {
const response = await window.api.createNote(req);
state.response = response;
if (response.ok) {
state.error = null;
await reloadNotes();
}
else {
state.error = response.error;
}
}
finally {
state.busy = false;
render();
}
}
async function createRaw(value) {
if (state.busy)
return;
state.busy = true;
try {
const response = await window.api.createNoteRaw(value);
state.response = response;
if (response.ok) {
state.error = null;
await reloadNotes();
}
else {
state.error = response.error;
}
}
finally {
state.busy = false;
render();
}
}
async function reloadNotes() {
const response = await window.api.listNotes({ limit: 10 });
if (response.ok)
state.notes = response.value.items;
}
async function runCases() {
const response = await window.api.runCases();
if (response.ok)
state.report = response.value;
render();
}
function boot() {
render();
window.__setTab = (tab) => {
state.tab = tab;
render();
};
window.__snapshot = () => ({
tab: state.tab,
notes: state.notes.length,
error: state.error?.code ?? null,
cases: state.report?.passed ?? 0,
});
window.__smoke = async () => {
await window.api.resetNotes();
state.notes = [];
state.response = null;
state.error = null;
const created = await window.api.createNote({
title: "IPC 契约笔记",
body: "请求与响应类型只定义一次,三端引用同一份 shared/ipc.ts。",
tags: ["ipc", "types"],
});
const empty = await window.api.createNote({ title: " ", body: "正文" });
const tooMany = await window.api.createNoteRaw({
title: "tags 太多",
body: "正文",
tags: ["a", "b", "c", "d", "e", "f"],
});
const unknown = await window.api.createNoteRaw({
title: "未知字段",
body: "正文",
extra: true,
});
const list = await window.api.listNotes({ limit: 5 });
const cases = await window.api.runCases();
state.response = created;
state.error = empty.ok ? null : empty.error;
state.notes = list.ok ? list.value.items : [];
state.report = cases.ok ? cases.value : null;
render();
return {
created: created.ok ? 1 : 0,
emptyTitle: empty.ok ? "OK" : empty.error.code,
tooManyTags: tooMany.ok ? "OK" : tooMany.error.code,
unknownField: unknown.ok ? "OK" : unknown.error.code,
listCount: list.ok ? list.value.items.length : 0,
casesFailed: cases.ok ? cases.value.failed : -1,
noStack: empty.ok ? false : !("stack" in empty.error),
};
};
}
boot();
//# sourceMappingURL=renderer.js.map