From ce6e043985d0544b0a83416e02fbf0a1052cd2b7 Mon Sep 17 00:00:00 2001 From: Sachin Sharma Date: Sun, 19 Apr 2026 02:20:14 +0530 Subject: [PATCH] refactor(processors): dynamic-import mammoth, move to optionalDependencies Convert static `import * as mammoth from "mammoth"` to a lazy dynamic import with ERR_MODULE_NOT_FOUND detection. Move mammoth (2.3 MB) from dependencies to optionalDependencies. --- package.json | 2 +- pnpm-lock.yaml | 6 ++--- src/lib/processors/document/WordProcessor.ts | 23 ++++++++++++++++++-- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 47124b9d99..c35ba31d5c 100644 --- a/package.json +++ b/package.json @@ -236,7 +236,6 @@ "inquirer": "^13.3.0", "jose": "^6.1.3", "json-schema-to-zod": "^2.7.0", - "mammoth": "^1.11.0", "mediabunny": "^1.40.1", "music-metadata": "^11.11.2", "nanoid": "^5.1.5", @@ -273,6 +272,7 @@ "@picovoice/cobra-node": "^3.0.2", "bullmq": "^5.52.2", "exceljs": "^4.4.0", + "mammoth": "^1.11.0", "pdf-parse": "^2.4.5", "pdf-to-img": "^5.0.0", "@fastify/cors": "^11.2.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6f3cc0e2f4..2ab9b828be 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -161,9 +161,6 @@ importers: json-schema-to-zod: specifier: ^2.7.0 version: 2.8.0 - mammoth: - specifier: ^1.11.0 - version: 1.12.0 mediabunny: specifier: ^1.40.1 version: 1.40.1 @@ -448,6 +445,9 @@ importers: koa-bodyparser: specifier: ^4.4.1 version: 4.4.1 + mammoth: + specifier: ^1.11.0 + version: 1.12.0 pdf-parse: specifier: ^2.4.5 version: 2.4.5 diff --git a/src/lib/processors/document/WordProcessor.ts b/src/lib/processors/document/WordProcessor.ts index ff194d0326..4eb9ec3f11 100644 --- a/src/lib/processors/document/WordProcessor.ts +++ b/src/lib/processors/document/WordProcessor.ts @@ -32,8 +32,6 @@ * ``` */ -import * as mammoth from "mammoth"; - import { BaseFileProcessor } from "../base/BaseFileProcessor.js"; import type { FileInfo, @@ -44,6 +42,26 @@ import type { import { SIZE_LIMITS } from "../config/index.js"; import { FileErrorCode } from "../errors/index.js"; +let _mammoth: typeof import("mammoth") | null = null; +async function loadMammoth() { + if (_mammoth) { + return _mammoth; + } + try { + _mammoth = await import(/* @vite-ignore */ "mammoth"); + return _mammoth; + } catch (err) { + const e = err instanceof Error ? (err as NodeJS.ErrnoException) : null; + if (e?.code === "ERR_MODULE_NOT_FOUND" && e.message.includes("mammoth")) { + throw new Error( + 'Word document processing requires the "mammoth" package. Install it with:\n pnpm add mammoth', + { cause: err }, + ); + } + throw err; + } +} + // Re-export for consumers who import from this module // Import for local use @@ -266,6 +284,7 @@ export class WordProcessor extends BaseFileProcessor { const warnings: string[] = []; try { + const mammoth = await loadMammoth(); // Extract plain text const textResult = await mammoth.extractRawText({ buffer }); textContent = textResult.value;