Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion configs/electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import typia from "@typia/unplugin/vite";
import { defineConfig } from "electron-vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { viteStaticCopy } from "vite-plugin-static-copy";
import { ipcValidators } from "./ipc-validators";

export default defineConfig({
main: {
plugins: [typia({ include: [/[/\\]main[/\\][^/\\]+[/\\]ipc\.ts$/], tsconfig: "configs/tsconfig.node.json" })],
plugins: [ipcValidators()],
build: {
outDir: "dist/main",
rollupOptions: {
Expand Down
212 changes: 212 additions & 0 deletions configs/ipc-validators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import { createHash, randomUUID, type Hash } from "node:crypto";
import { mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import ts from "typescript";
import typiaPackage from "typia/package.json" with { type: "json" };
import { transform } from "typia/lib/transform";
import { normalizePath, type Plugin } from "vite";

const ipcFile = /[/\\]main[/\\][^/\\]+[/\\]ipc\.ts$/;
const cacheVersion = ["ipc-validators-v1", ts.version, typiaPackage.version].join(":");
const queries = ["readFile", "fileExists", "directoryExists", "getDirectories", "readDirectory", "realpath"] as const;
type Query = typeof queries[number];
type ModuleKey = { source: string; key: string; watch: string[] };
type Snapshot = { version: string; reads: [string, string][]; modules: Record<string, ModuleKey> };
type Output = { code: string; map: { version: 3; sources: string[]; names: string[]; mappings: string } };
type Compilation = {
builder: ts.SemanticDiagnosticsBuilderProgram; program: ts.Program;
versions: Map<string, string>; common: Hash; watch: Set<string>;
};

function hash(text: string): string {
return createHash("sha256").update(text).digest("hex");
}

// Recheck the compiler's actual inputs on the next launch, including unsuccessful module lookups.
// A newly added declaration can change resolution even when every previously read file is identical.
function fingerprint(value: unknown): string {
return typeof value === "string" ? hash(value) : JSON.stringify(value) ?? "undefined";
}

function compilerSystem(reads: Map<string, string>): ts.System {
const system = { ...ts.sys };
for (const name of queries) {
const query = ts.sys[name];
if (query) Object.assign(system, { [name](...args: unknown[]) {
const value: unknown = Reflect.apply(query, ts.sys, args);
const call = JSON.stringify([name, ...args]), signature = fingerprint(value);
const previous = reads.get(call);
reads.set(call, previous === undefined || previous === signature ? signature : "changed during compilation");
return value;
} });
}
return system;
}

function previousBuild(path: string): Snapshot | undefined {
const text = ts.sys.readFile(path);
if (!text) return;
try {
const previous: Snapshot = JSON.parse(text);
if (previous.version === cacheVersion && previous.modules && previous.reads.every(([call, expected]) => {
const [name, ...args]: [Query, ...unknown[]] = JSON.parse(call);
const query = queries.includes(name) && ts.sys[name];
return query && fingerprint(Reflect.apply(query, ts.sys, args.map(arg => arg ?? undefined))) === expected;
})) return previous;
}
catch { /* Rebuild if the snapshot is incomplete. */ }
return undefined;
}

function compilation(root: string, inputs: Map<string, string>, system: ts.System): Compilation {
const config = join(root, "configs/tsconfig.node.json");
const lockfile = join(root, "pnpm-lock.yaml");
const manifest = join(root, "package.json");
const watch = new Set([lockfile, manifest]);
const parsed = ts.getParsedCommandLineOfConfigFile(config, {
composite: false, declaration: false, emitDeclarationOnly: false, noEmit: false,
sourceMap: true, inlineSources: true
}, { ...system, onUnRecoverableConfigFileDiagnostic: fail, readFile(path) {
watch.add(path);
return system.readFile(path);
} });
if (!parsed) throw new Error("Could not read " + config);
parsed.errors.forEach(fail);

const entries = parsed.fileNames.filter(path => ipcFile.test(path) || path.endsWith(".d.ts"));
const host = ts.createIncrementalCompilerHost(parsed.options, {
...system, readFile(path) {
const source = system.readFile(path);
return inputs.get(normalizePath(path)) ?? source;
}
});
const builder = ts.createSemanticDiagnosticsBuilderProgram([...new Set([...entries, ...inputs.keys()])], parsed.options, host);
const program = builder.getProgram();
const versions = new Map<string, string>();
const common = createHash("sha256").update(cacheVersion).update(JSON.stringify(parsed.options))
.update(system.readFile(lockfile) ?? "").update(system.readFile(manifest) ?? "");
for (const file of program.getSourceFiles()) {
const version = hash(file.text);
versions.set(file.fileName, version);
// Ambient declarations and module augmentations can change a type without an import edge.
if (file.isDeclarationFile || !ts.isExternalModule(file) || file.statements.some(ts.isModuleDeclaration)) {
common.update(JSON.stringify([file.fileName, version]));
if (!file.fileName.includes("/node_modules/")) watch.add(file.fileName);
}
}
return { builder, program, versions, common, watch };
}

function fail(diagnostic: Pick<ts.Diagnostic, "messageText">): never {
throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
}

function emit(project: Compilation, file: ts.SourceFile): Output {
let code: string | undefined, map: Output["map"] | undefined;
const result = project.program.emit(file, (path, text) => {
if (path.endsWith(".js.map")) {
map = JSON.parse(text) as Output["map"];
map.sources = [file.fileName];
}
if (path.endsWith(".js")) code = text.replace(/\/\/# sourceMappingURL=.*\s*$/, "");
}, undefined, false, { before: [transform(project.program, {}, { addDiagnostic: fail })] });
result.diagnostics.forEach(fail);
if (code === undefined || !map) throw new Error("Missing IPC validator output for " + file.fileName);
return { code, map };
}

function cached(path: string, key: string): Output | undefined {
const text = ts.sys.readFile(path);
if (!text) return;
try {
const entry = JSON.parse(text);
if (entry?.key === key && typeof entry.code === "string" && entry.map?.version === 3 &&
typeof entry.map.mappings === "string" && Array.isArray(entry.map.sources) && Array.isArray(entry.map.names)) {
return { code: entry.code, map: entry.map };
}
}
catch { /* Regenerate an incomplete cache entry. */ }
return undefined;
}

export function ipcValidators(): Plugin {
let root: string, directory: string, project: Compilation | undefined;
let previous: Snapshot | undefined, modules: Record<string, ModuleKey>;
let warn: (message: string) => void, canWrite = true;
const inputs = new Map<string, string>();
const reads = new Map<string, string>();
function save(path: string, value: unknown): void {
if (!canWrite) return;
const temporary = path + "." + randomUUID();
try {
mkdirSync(directory, { recursive: true });
writeFileSync(temporary, JSON.stringify(value));
renameSync(temporary, path);
}
catch (error) {
canWrite = false;
warn(`Could not save the IPC validator cache: ${error}`);
try {
rmSync(temporary, { force: true });
}
catch { /* The cache directory may be read-only. */ }
}
}
return {
name: "labloom-ipc-validators",
enforce: "pre",
configResolved(config) {
root = config.root;
directory = resolve(config.cacheDir, "labloom-ipc");
warn = message => config.logger.warn(message);
},
buildStart() {
previous = previousBuild(join(directory, "inputs.json"));
modules = {};
},
buildEnd(error) {
if (!error && project) save(join(directory, "inputs.json"), { version: cacheVersion, reads: [...reads], modules });
project = undefined;
previous = undefined;
inputs.clear();
reads.clear();
},
transform: {
filter: { id: { include: ipcFile, exclude: /[/\\]node_modules[/\\]/ }, code: /\btypia\b/ },
handler(code, id) {
const path = join(directory, basename(dirname(id)) + ".json");
const source = hash(code), known = previous?.modules[id];
if (known?.source === source && Array.isArray(known.watch)) {
const output = cached(path, known.key);
if (output) {
for (const dep of known.watch) this.addWatchFile(dep);
modules[id] = known;
return output;
}
}
// Normally all ten entries share one program. Honor earlier transforms of an entry too.
if (!project || project.program.getSourceFile(id)?.text !== code) {
inputs.set(id, code);
project = compilation(root, inputs, compilerSystem(reads));
}
const file = project.program.getSourceFile(id);
if (!file) throw new Error("Missing IPC source " + id);
const key = project.common.copy();
const watch = new Set(project.watch);
for (const dep of project.builder.getAllDependencies(file).toSorted()) {
key.update(JSON.stringify([dep, project.versions.get(dep)]));
if (!dep.includes("/node_modules/")) watch.add(dep);
}
for (const dep of watch) this.addWatchFile(dep);
const digest = key.digest("hex");
modules[id] = { key: digest, source, watch: [...watch] };
const hit = cached(path, digest);
if (hit) return hit;

const output = emit(project, file);
save(path, { key: digest, ...output });
return output;
}
}
};
}
2 changes: 1 addition & 1 deletion configs/tsconfig.node.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": ["electron.vite.config.*", "drizzle.config.ts", "feed.preview.ts", "../main/**/*", "../preload/**/*", "../shared/**/*", "../locales/*.json"],
"include": ["electron.vite.config.*", "ipc-validators.ts", "drizzle.config.ts", "feed.preview.ts", "../main/**/*", "../preload/**/*", "../shared/**/*", "../locales/*.json"],
"compilerOptions": {
"rootDir": "..",
"emitDeclarationOnly": true,
Expand Down
76 changes: 75 additions & 1 deletion locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,15 @@
"attribute-unsupported-builtin": "This page type does not support that built-in attribute.",
"attribute-invalid-detach": "Built-in attributes cannot be removed. An attribute cannot be written and removed together.",
"attribute-readonly": "This attribute is managed by its corresponding operation.",
"import-regular-file": "Choose a regular file.",
"import-pdf-only": "Only PDF files can create paper pages.",

"import-failed": "Some files could not be imported.",
"attachment-missing": "The attachment was not found.",
"attachment-owned": "An attachment can belong to only one file attribute on one page.",
"annotation-owned": "An annotation can belong to only one paper.",
"annotation-unavailable": "The annotation page is unavailable.",
"feed-body-forbidden": "A feed source page cannot contain body blocks.",
"page-body-forbidden": "This type of page cannot have a body.",
"page-missing": "The page was not found.",
"attribute-id-immutable": "The attribute identifier cannot be changed.",
"attribute-builtin-immutable": "Built-in attributes cannot be deleted or have their type changed.",
Expand Down Expand Up @@ -415,6 +419,75 @@
"feedView": "Feed Activity",
"targetDeleted": "Target has been deleted"
},
"reader": {
"pdf": "PDF reader",
"pdfFile": "PDF file",
"loading": "Loading…",
"noPdf": "No PDF",
"addPdf": "Add PDF",
"info": "Info",
"annotations": "Annotations",
"noAnnotations": "No annotations",
"annotationPage": "Page {{page}}",
"openAnnotation": "Open in tab",
"deleteAnnotation": "Delete",
"changeColor": "Change color",
"highlightActions": "Highlight actions",
"highlightColor": "{{color}} highlight",
"previousPage": "Previous page",
"nextPage": "Next page",
"pageNumber": "Page number",
"pageCount": "/ {{count}}",
"zoom": "Zoom",
"zoomOut": "Zoom out",
"zoomIn": "Zoom in",
"rotate": "Rotate page",
"find": "Find in PDF",
"clearFind": "Clear search",
"previousMatch": "Previous match",
"nextMatch": "Next match",
"matchCount": "{{current}}/{{total}}",
"noMatches": "No matches",
"noText": "No searchable text",
"scale": {
"auto": "Auto",
"page-actual": "Actual size",
"page-width": "Page width",
"page-fit": "Fit page"
}
},
"library": {
"scope": "Scope",
"all": "All Pages",
"search": "Search pages…",
"filter": "Filters",
"create": "New",
"emptyTrash": "Empty Recycle Bin",
"purgeResults": "Permanently Delete All Results",
"loading": "Loading…",
"empty": "No pages",
"count": "{{count}} pages",
"selected": "{{count}} items selected",

"type": "Type",
"paper": "Paper",
"editable": "Note",
"annotation": "Annotation",
"feed": "Feed",
"year": "Year",
"venue": "Journal",
"added": "Date Added",
"defaultColumns": "Restore Default Columns",
"width": "Resize {{name}}",
"panelWidth": "Resize item pane",
"tags": "Filter tags…",
"property": "Add a property condition",
"add": "Add condition",
"openFile": "Open in System Application",

"yes": "Yes",
"no": "No"
},
"pageAction": {
"open": "Open",
"openSide": "Open to the Side",
Expand Down Expand Up @@ -506,6 +579,7 @@
},
"property": {
"sourcePaper": "Source paper",
"sourcePaperDeleted": "Original paper deleted",
"none": "None",
"add": "Add property",
"search": "Search properties…",
Expand Down
Loading
Loading