Skip to content

Build your personal knowledge base with Trilium Notes

feat(build): ESM output option with code splitting for backend bundles

Elian Doran1fd0f284d17b
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index 590882a5fc..57136e6f01 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -20,7 +20,7 @@
* with every built-in Claude Code tool (file access, bash, …) disabled.
*/
-import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
+import type { Options as AgentOptions, query as queryFn, SDKAssistantMessage, SDKMessage, SDKUserMessage, SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
@@ -282,6 +282,7 @@ export class ClaudeAgentProvider implements LlmProvider {
})
};
+ const query = await loadQuery();
const response = query({
prompt: noInput,
options: {
@@ -377,6 +378,7 @@ export class ClaudeAgentProvider implements LlmProvider {
const toolIdsByBlockIndex = new Map<number, string>();
try {
+ const query = await loadQuery();
const response = query({
prompt,
options: {
@@ -541,6 +543,7 @@ export class ClaudeAgentProvider implements LlmProvider {
async generateTitle(firstMessage: string): Promise<string> {
try {
+ const query = await loadQuery();
const response = query({
prompt: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`,
options: {
@@ -937,3 +940,8 @@ function describeAgentError(error: unknown): string {
}
return text;
}
+
+// Dynamically imported so the agent SDK only loads when an agent chat actually runs.
+async function loadQuery(): Promise<typeof queryFn> {
+ return (await import("@anthropic-ai/claude-agent-sdk")).query;
+}
diff --git a/apps/server/src/services/ocr/processors/office_processor.ts b/apps/server/src/services/ocr/processors/office_processor.ts
index b6b37ce4a4..4680dd8039 100644
--- a/apps/server/src/services/ocr/processors/office_processor.ts
+++ b/apps/server/src/services/ocr/processors/office_processor.ts
@@ -1,6 +1,6 @@
import { OFFICE_FILE_TYPE_HINTS, OFFICE_MIME_TYPES } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
-import { OfficeParser, type OfficeParserConfig } from 'officeparser';
+import { type OfficeParserConfig } from 'officeparser';
import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';
import { FileProcessor } from './file_processor.js';
@@ -36,6 +36,8 @@ export class OfficeProcessor extends FileProcessor {
const fileType = OFFICE_FILE_TYPE_HINTS[mimeType];
const config = fileType ? { ...PARSER_CONFIG, fileType } : PARSER_CONFIG;
+ // Dynamically imported so officeparser only loads when an Office file is actually processed.
+ const { OfficeParser } = await import('officeparser');
const ast = await OfficeParser.parseOffice(buffer, config);
const trimmed = ast.toText().trim();
diff --git a/apps/server/src/services/ocr/processors/pdf_processor.ts b/apps/server/src/services/ocr/processors/pdf_processor.ts
index 3581e18e06..1ca486dc7e 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts
@@ -1,5 +1,3 @@
-import { extractText, getDocumentProxy } from 'unpdf';
-
import { getLog } from "@triliumnext/core";
import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';
import { FileProcessor } from './file_processor.js';
@@ -20,6 +18,8 @@ export class PDFProcessor extends FileProcessor {
async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {
getLog().info('Starting PDF text extraction...');
+ // Dynamically imported so unpdf only loads when a PDF is actually processed.
+ const { extractText, getDocumentProxy } = await import('unpdf');
const pdf = await getDocumentProxy(new Uint8Array(buffer));
const { totalPages, text } = await extractText(pdf, { mergePages: true });
const trimmed = text.trim();
diff --git a/scripts/build-utils.ts b/scripts/build-utils.ts
index 76c5d5d150..5a93f04d91 100644
--- a/scripts/build-utils.ts
+++ b/scripts/build-utils.ts
@@ -37,14 +37,20 @@ export default class BuildHelper {
}
/**
- * @param entryPoints source entry points to bundle into CJS.
+ * @param entryPoints source entry points to bundle.
* @param opts.importMetaUrlShim redirects `import.meta.url` to the bundle's own file so
* bundled ESM deps calling `createRequire(import.meta.url)` work in CJS output (defaults
* to `true`). Must be disabled for scripts that run in Electron's sandboxed renderer (e.g.
- * the desktop preload), where the injected `require("node:url")` banner throws.
+ * the desktop preload), where the injected `require("node:url")` banner throws. Ignored
+ * for ESM output, where `import.meta.url` needs no shim.
+ * @param opts.format output format (defaults to `"cjs"`). `"esm"` emits `.mjs` with code
+ * splitting: dynamic `import()` boundaries become separate chunks under `chunks/`, so
+ * V8 never parses or retains the source of a subsystem until it is first used. The
+ * desktop preload must stay `"cjs"` — Electron's sandboxed renderer cannot load ESM.
*/
- async buildBackend(entryPoints: string[], opts: { importMetaUrlShim?: boolean } = {}) {
- const { importMetaUrlShim = true } = opts;
+ async buildBackend(entryPoints: string[], opts: { importMetaUrlShim?: boolean; format?: "cjs" | "esm" } = {}) {
+ const { importMetaUrlShim = true, format = "cjs" } = opts;
+ const esm = format === "esm";
const result = await esbuild({
entryPoints: entryPoints.map(e => join(this.projectDir, e)),
tsconfig: join(this.projectDir, "tsconfig.app.json"),
@@ -52,9 +58,11 @@ export default class BuildHelper {
bundle: true,
outdir: this.outDir,
outExtension: {
- ".js": ".cjs"
+ ".js": esm ? ".mjs" : ".cjs"
},
- format: "cjs",
+ format,
+ splitting: esm,
+ chunkNames: "chunks/[name]-[hash]",
external: [
"electron",
"better-sqlite3",
@@ -80,7 +88,6 @@ export default class BuildHelper {
"@triliumnext/core/src/assets/*"
],
metafile: true,
- splitting: false,
loader: {
".css": "text",
".ejs": "text"
@@ -94,12 +101,28 @@ export default class BuildHelper {
// then throws `ERR_INVALID_ARG_VALUE`. Redirect it to the
// bundle's own file so createRequire()/`.resolve()` anchor at
// dist/ and can still locate sibling node_modules packages.
- ...(importMetaUrlShim && { "import.meta.url": "__bundleImportMetaUrl" }),
+ ...(importMetaUrlShim && !esm && { "import.meta.url": "__bundleImportMetaUrl" }),
},
- // The banner defines the redirect target above. It uses
+ // The CJS banner defines the redirect target above. It uses
// `require("node:url")`, which throws in Electron's sandboxed
// renderer, so it must be omitted for preload-style bundles.
- ...(importMetaUrlShim && {
+ // The ESM banner is the mirror image: bundled CJS deps reference
+ // `require`, `__filename` and `__dirname`, which do not exist in
+ // ESM, so each output file defines them from `import.meta.url`.
+ // esbuild's `__require` interop helper picks up the banner's
+ // `require` binding for external packages (better-sqlite3 etc.).
+ ...(esm ? {
+ banner: {
+ js: [
+ `import { createRequire as __bundleCreateRequire } from "node:module";`,
+ `import { fileURLToPath as __bundleFileURLToPath } from "node:url";`,
+ `import { dirname as __bundleDirname } from "node:path";`,
+ `const require = __bundleCreateRequire(import.meta.url);`,
+ `const __filename = __bundleFileURLToPath(import.meta.url);`,
+ `const __dirname = __bundleDirname(__filename);`
+ ].join("\n")
+ }
+ } : importMetaUrlShim && {
banner: {
js: `const __bundleImportMetaUrl = require("node:url").pathToFileURL(__filename).href;`
}