示例工程 32-deep-links-file-association
32-deep-links-file-association/demo-02-file-check/file.ts
type WorkFile = { title: string; body: string };
const MAX_SIZE = 64 * 1024;
function validatePath(filePath: string): string | null {
if (filePath.length === 0 || filePath.length > 260) return "BAD_PATH";
if (filePath.includes("\0")) return "BAD_PATH";
if (!filePath.toLowerCase().endsWith(".xwrt")) return "BAD_EXTENSION";
return null;
}
function validateSize(size: number): string | null {
if (!Number.isFinite(size) || size <= 0) return "BAD_SIZE";
if (size > MAX_SIZE) return "BAD_SIZE";
return null;
}
function parseContent(text: string): WorkFile | string {
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
return "BAD_CONTENT";
}
if (typeof raw !== "object" || raw === null) return "BAD_CONTENT";
const { title, body } = raw as { title?: unknown; body?: unknown };
if (
typeof title !== "string" ||
title.length === 0 ||
title.length > 80 ||
typeof body !== "string" ||
body.length === 0 ||
body.length > 4000
) {
return "BAD_CONTENT";
}
return { title, body };
}
const checks = [
validatePath("welcome.xwrt"),
validatePath("notes.txt"),
validatePath("bad\0.xwrt"),
validateSize(160),
validateSize(0),
validateSize(MAX_SIZE + 1),
parseContent('{"title":"Hello","body":"World"}'),
parseContent('{"title":"","body":"x"}'),
parseContent("not-json"),
];
const content = parseContent('{"title":"Hello","body":"World"}');
console.log(
JSON.stringify({
evt: "smoke",
ok:
checks[0] === null &&
checks[1] === "BAD_EXTENSION" &&
checks[2] === "BAD_PATH" &&
checks[3] === null &&
checks[4] === "BAD_SIZE" &&
checks[5] === "BAD_SIZE" &&
checks[6] !== "BAD_CONTENT" &&
checks[7] === "BAD_CONTENT" &&
checks[8] === "BAD_CONTENT" &&
typeof content === "object" &&
content.title === "Hello",
checks,
content,
}),
);