#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix more `any` types in frontend code (#7818)
James Brunton5c525c445549
diff --git a/frontend/editor/src/core/components/viewer/ActiveDocumentContext.tsx b/frontend/editor/src/core/components/viewer/ActiveDocumentContext.tsxindex 07c035593c..3cc90ec18a 100644--- a/frontend/editor/src/core/components/viewer/ActiveDocumentContext.tsx+++ b/frontend/editor/src/core/components/viewer/ActiveDocumentContext.tsx@@ -41,8 +41,8 @@ export function ActiveDocumentProvider({// Subscribe to document changes (only if not already subscribed)if (!unsubscribeRef.current && docManagerApi.onDocumentOpened) {- unsubscribeRef.current = docManagerApi.onDocumentOpened((event: any) => {- const docId = event?.documentId || event?.id || event?.document?.id;+ unsubscribeRef.current = docManagerApi.onDocumentOpened((event) => {+ const docId = event.id;if (docId && docId !== documentIdRef.current) {documentIdRef.current = docId;setDocumentId(docId);diff --git a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsxindex ee8863ac5f..d60cae1ef1 100644--- a/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/AttachmentSidebar.tsx@@ -185,11 +185,9 @@ export const AttachmentSidebar = ({continue;}return Array.isArray(result) ? result : [];- } catch (error: any) {+ } catch (error) {const message =- typeof error?.message === "string"- ? error.message.toLowerCase()- : "";+ error instanceof Error ? error.message.toLowerCase() : "";const notReady =message.includes("document") &&message.includes("not") &&@@ -250,7 +248,7 @@ export const AttachmentSidebar = ({const handleDownload = (attachment: PdfAttachmentObject,- event: React.MouseEvent,+ event: React.SyntheticEvent,) => {event.stopPropagation();attachmentActions.downloadAttachment(attachment);@@ -296,7 +294,7 @@ export const AttachmentSidebar = ({onKeyDown={(event) => {if (event.key === "Enter" || event.key === " ") {event.preventDefault();- handleDownload(attachment, event as any);+ handleDownload(attachment, event);}}}>diff --git a/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx b/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsxindex 9c92730077..5b98926e27 100644--- a/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx@@ -34,6 +34,12 @@ interface BookmarkSidebarProps {type BookmarkNode = PdfBookmarkObject & { id: string };+interface BookmarkPayload {+ title: string;+ pageNumber: number;+ children: BookmarkPayload[];+}+type BookmarkCacheStatus = "idle" | "loading" | "success" | "error";interface BookmarkCacheEntry {@@ -249,11 +255,9 @@ export const BookmarkSidebar = ({continue;}return Array.isArray(result) ? result : [];- } catch (error: any) {+ } catch (error) {const message =- typeof error?.message === "string"- ? error.message.toLowerCase()- : "";+ error instanceof Error ? error.message.toLowerCase() : "";const notReady =message.includes("document") &&message.includes("not") &&@@ -377,13 +381,7 @@ export const BookmarkSidebar = ({try {// Convert existing PDF bookmarks (from embedpdf) to the backend's// payload shape, then append the new one.- const toPayload = (- b: PdfBookmarkObject,- ): {- title: string;- pageNumber: number;- children: any[];- } => ({+ const toPayload = (b: PdfBookmarkObject): BookmarkPayload => ({title: b.title ?? "",pageNumber: resolvePageNumber(b) ?? 1,children: (b.children ?? []).map(toPayload),@@ -521,7 +519,7 @@ export const BookmarkSidebar = ({const handleBookmarkClick = (bookmark: PdfBookmarkObject,- event: React.MouseEvent,+ event: React.SyntheticEvent,) => {const target = bookmark.target;if (target?.type === "action") {@@ -605,7 +603,7 @@ export const BookmarkSidebar = ({? (event) => {if (event.key === "Enter" || event.key === " ") {event.preventDefault();- handleBookmarkClick(node, event as any);+ handleBookmarkClick(node, event);}}: undefineddiff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsxindex 9045d3a35c..7a9eeb3bcb 100644--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx@@ -28,6 +28,7 @@ import {PdfAnnotationReplyType,type PdfAnnotationObject,type PdfTextAnnoObject,+ type Rect,} from "@embedpdf/models";import { useCommentAuthor } from "@app/contexts/CommentAuthorContext";import { useViewer } from "@app/contexts/ViewerContext";@@ -637,7 +638,7 @@ export function CommentsSidebar({);const handleSendReply = useCallback(- (pageIndex: number, parentId: string, parentRect: any) => {+ (pageIndex: number, parentId: string, parentRect: Rect | undefined) => {const key = `${pageIndex}_${parentId}_reply`;const text = replyDrafts[key]?.trim();if (!text || !provides?.createAnnotation) return;diff --git a/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx b/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsxindex 520417afd0..35383a56a3 100644--- a/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx+++ b/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx@@ -33,8 +33,8 @@ export function DocumentReadyWrapper({// Subscribe to document changesconst docManagerApi = plugin.provides?.();if (docManagerApi?.onDocumentOpened) {- const unsubscribe = docManagerApi.onDocumentOpened((event: any) => {- const docId = event?.documentId || event?.id || event?.document?.id;+ const unsubscribe = docManagerApi.onDocumentOpened((event) => {+ const docId = event.id;if (docId) {setActiveDocumentId(docId);}diff --git a/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx b/frontend/editor/src/core/components/viewer/PanAPIBridge.tsxindex 772af6d5ac..625645fe2c 100644--- a/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx@@ -54,11 +54,9 @@ function PanAPIBridgeInner({ documentId }: { documentId: string }) {},makePanDefault: () => {// v2.5.0: makePanDefault may not exist, enable pan as fallback- if (- "makePanDefault" in currentPan &&- typeof (currentPan as any).makePanDefault === "function"- ) {- (currentPan as any).makePanDefault();+ const withDefault = currentPan as { makePanDefault?: () => void };+ if (typeof withDefault.makePanDefault === "function") {+ withDefault.makePanDefault();} else {currentPan.enablePan();}diff --git a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsxindex c860e074d0..2276e9ded0 100644--- a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx@@ -55,7 +55,12 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {// Synchronize manual redaction color with EmbedPDF// Manual redaction uses the 'redact' annotation tool internallyuseEffect(() => {- const annotationApi = annotationProvides as any;+ const annotationApi = annotationProvides as {+ setToolDefaults?: (+ toolId: string,+ patch: Record<string, unknown>,+ ) => void;+ } | null;if (annotationApi?.setToolDefaults) {annotationApi.setToolDefaults("redact", {type: PdfAnnotationSubtype.REDACT,diff --git a/frontend/editor/src/core/components/viewer/SearchAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SearchAPIBridge.tsxindex 5c62692a7c..43419eab81 100644--- a/frontend/editor/src/core/components/viewer/SearchAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/SearchAPIBridge.tsx@@ -59,7 +59,7 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {if (!search) return;subscriptionRef.current =- search.onSearchResultStateChange?.((state: any) => {+ search.onSearchResultStateChange?.((state) => {if (!state) return;const newState = {@@ -137,11 +137,13 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {currentSearch.startSearch();const results = await currentSearch.searchAllPages(query);return results;- } catch (error: any) {+ } catch (error) {// Handle abort errors gracefully - these occur when searches overlap+ const abortLike = error as { type?: unknown; message?: unknown };if (- error?.type === "abort" ||- error?.message?.includes("abort")+ abortLike.type === "abort" ||+ (typeof abortLike.message === "string" &&+ abortLike.message.includes("abort"))) {// Silently handle abort - this is expected when user types quicklyreturn null;diff --git a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsxindex 3efb250de1..91bbe1dc7d 100644--- a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx@@ -136,7 +136,7 @@ export function SelectionAPIBridge() {api: buildApi(),});- const unsubChange = selection.onSelectionChange((event: any) => {+ const unsubChange = selection.onSelectionChange((event) => {const hasText = !!event?.selection;hasSelectionRef.current = hasText;diff --git a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsxindex 5cb4b3e59b..c478af89d5 100644--- a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx+++ b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx@@ -573,7 +573,7 @@ export function useViewerWorkbenchBarButtons(if (isFormFillActive) {handleBackToTools();} else {- handleToolSelect("formFill" as any);+ handleToolSelect("formFill");}}}disabled={disabled}diff --git a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx b/frontend/editor/src/core/contexts/AppConfigContext.test.tsxindex 93c860d823..35a313fa44 100644--- a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx+++ b/frontend/editor/src/core/contexts/AppConfigContext.test.tsx@@ -10,6 +10,10 @@ import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { ReactNode } from "react";+// The mocks below supply only the fields the code under test reads; cast the+// partial to apiClient.get's real resolved type (per-platform: axios or Tauri).+type GetResponse = Awaited<ReturnType<typeof apiClient.get>>;+// Mock apiClientvi.mock("@app/services/apiClient");@@ -43,7 +47,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValueOnce({status: 200,data: mockConfig,- } as any);+ } as GetResponse);const { result } = renderHook(() => useAppConfig(), { wrapper });@@ -181,7 +185,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValueOnce({status: 200,data: initialConfig,- } as any);+ } as GetResponse);const { result } = renderHook(() => useAppConfig(), { wrapper });@@ -193,7 +197,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValueOnce({status: 200,data: updatedConfig,- } as any);+ } as GetResponse);// Trigger jwt-available event wrapped in actawait act(async () => {@@ -218,7 +222,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValue({status: 200,data: mockConfig,- } as any);+ } as GetResponse);const { result } = renderHook(() => useAppConfig(), { wrapper });@@ -242,7 +246,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValue({status: 200,data: mockConfig,- } as any);+ } as GetResponse);const { result } = renderHook(() => useAppConfig(), { wrapper });@@ -399,7 +403,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValue({status: 200,data: { enableLogin: false },- } as any);+ } as GetResponse);const client = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -510,7 +514,7 @@ describe("AppConfigContext", () => {vi.mocked(apiClient.get).mockResolvedValueOnce({status: 200,data: mockConfig,- } as any);+ } as GetResponse);renderHook(() => useAppConfig(), { wrapper });diff --git a/frontend/editor/src/core/contexts/FileManagerContext.tsx b/frontend/editor/src/core/contexts/FileManagerContext.tsxindex 338a910508..2a63294c83 100644--- a/frontend/editor/src/core/contexts/FileManagerContext.tsx+++ b/frontend/editor/src/core/contexts/FileManagerContext.tsx@@ -443,7 +443,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({`/api/v1/storage/files/${fileToRemove.remoteStorageId}/shares/self`,{suppressErrorToast: true,- } as any,+ },);await refreshRecentFiles();alert({@@ -475,7 +475,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({try {await apiClient.delete(`/api/v1/storage/files/${fileToRemove.remoteStorageId}`,- { suppressErrorToast: true } as any,+ { suppressErrorToast: true },);} catch (error) {console.error("Failed to delete file from server:", error);@@ -1002,7 +1002,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({responseType: "blob",suppressErrorToast: true,skipAuthRedirect: true,- } as any,+ },);const contentType = readResponseHeader(response.headers,diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsxindex 17585ae7e8..1a559ea19e 100644--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx@@ -185,7 +185,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({responseType: "blob",suppressErrorToast: true,skipAuthRedirect: true,- } as any,+ },);const contentType = readResponseHeader(response.headers, "content-type");const disposition = readResponseHeader(@@ -206,7 +206,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({responseType: "blob",suppressErrorToast: true,skipAuthRedirect: true,- } as any,+ },);const contentType = readResponseHeader(response.headers, "content-type");const disposition = readResponseHeader(diff --git a/frontend/editor/src/core/hooks/useAuditFilters.ts b/frontend/editor/src/core/hooks/useAuditFilters.tsindex b67d1d7422..ecf2107d75 100644--- a/frontend/editor/src/core/hooks/useAuditFilters.ts+++ b/frontend/editor/src/core/hooks/useAuditFilters.ts@@ -38,7 +38,10 @@ export function useAuditFilters(}}, [loginEnabled]);- const handleFilterChange = (key: keyof AuditFilters, value: any) => {+ const handleFilterChange = <K extends keyof AuditFilters>(+ key: K,+ value: AuditFilters[K],+ ) => {setFilters((prev) => ({ ...prev, [key]: value }));};diff --git a/frontend/editor/src/core/hooks/useCookieConsent.ts b/frontend/editor/src/core/hooks/useCookieConsent.tsindex b4b0296f05..660485f2d5 100644--- a/frontend/editor/src/core/hooks/useCookieConsent.ts+++ b/frontend/editor/src/core/hooks/useCookieConsent.ts@@ -13,12 +13,12 @@ import { getCookieConsentOverrides } from "@app/extensions/cookieConsentConfig";declare global {interface Window {CookieConsent?: {- run: (config: any) => void;+ run: (config: Record<string, unknown>) => void;show: (show?: boolean) => void;hide: () => void;showPreferences: () => void;hidePreferences: () => void;- getCookie: (name?: string) => any;+ getCookie: (name?: string) => unknown;acceptedCategory: (category: string) => boolean;acceptedService: (serviceName: string, category: string) => boolean;};diff --git a/frontend/editor/src/core/hooks/useFileManager.ts b/frontend/editor/src/core/hooks/useFileManager.tsindex 4393a22d61..0b9da5d4da 100644--- a/frontend/editor/src/core/hooks/useFileManager.ts+++ b/frontend/editor/src/core/hooks/useFileManager.ts@@ -122,7 +122,7 @@ export const useFileManager = () => {{suppressErrorToast: true,skipAuthRedirect: true,- } as any,+ },);const serverFiles = Array.isArray(response.data) ? response.data : [];const serverStubs: StirlingFileStub[] = [];@@ -252,7 +252,7 @@ export const useFileManager = () => {>("/api/v1/storage/share-links/accessed", {suppressErrorToast: true,skipAuthRedirect: true,- } as any);+ });const sharedLinks = Array.isArray(sharedResponse.data)? sharedResponse.data: [];diff --git a/frontend/editor/src/core/hooks/useLoginRequired.ts b/frontend/editor/src/core/hooks/useLoginRequired.tsindex a775b9e8c5..90159f7b25 100644--- a/frontend/editor/src/core/hooks/useLoginRequired.ts+++ b/frontend/editor/src/core/hooks/useLoginRequired.ts@@ -42,8 +42,8 @@ export function useLoginRequired() {* Wrap an async handler to check login state before executing*/const withLoginCheck = useCallback(- <T extends (...args: any[]) => Promise<any>>(handler: T): T => {- return (async (...args: any[]) => {+ <T extends (...args: never[]) => Promise<unknown>>(handler: T): T => {+ return (async (...args: Parameters<T>) => {if (!validateLoginEnabled()) {return;}@@ -71,11 +71,11 @@ export function useLoginRequired() {* Wrap fetch function to skip API call when login disabled*/const withLoginCheckForFetch = useCallback(- <T extends (...args: any[]) => Promise<any>>(+ <T extends (...args: never[]) => Promise<unknown>>(fetchHandler: T,skipWhenDisabled: boolean = true,): T => {- return (async (...args: any[]) => {+ return (async (...args: Parameters<T>) => {if (!loginEnabled && skipWhenDisabled) {// Skip fetch when login disabled - component will use default/empty valuesreturn;diff --git a/frontend/editor/src/core/hooks/useMobileTransferSession.ts b/frontend/editor/src/core/hooks/useMobileTransferSession.tsindex 12da03af6f..bee78e717b 100644--- a/frontend/editor/src/core/hooks/useMobileTransferSession.ts+++ b/frontend/editor/src/core/hooks/useMobileTransferSession.ts@@ -13,11 +13,15 @@ import apiClient from "@app/services/apiClient";* at a time, via `onFileReceived`.*/+interface MobileScannerFile {+ filename: string;+ contentType?: string;+}+// Generate a cryptographically secure UUID v4-like session IDfunction generateSessionId(): string {// Use Web Crypto API for cryptographically secure random values- const cryptoObj =- typeof crypto !== "undefined" ? crypto : (window as any).crypto;+ const cryptoObj = typeof crypto !== "undefined" ? crypto : window.crypto;if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {const bytes = new Uint8Array(16);@@ -144,7 +148,7 @@ export function useMobileTransferSession({// Download only files we haven't processed yetconst newFiles = files.filter(- (f: any) => !processedFiles.current.has(f.filename),+ (f: MobileScannerFile) => !processedFiles.current.has(f.filename),);if (newFiles.length === 0) return;diff --git a/frontend/editor/src/core/hooks/useOs.ts b/frontend/editor/src/core/hooks/useOs.tsindex bb24c049f7..6d563ac04b 100644--- a/frontend/editor/src/core/hooks/useOs.ts+++ b/frontend/editor/src/core/hooks/useOs.ts@@ -1,5 +1,13 @@import { useEffect, useState } from "react";+interface UserAgentData {+ getHighEntropyValues(hints: string[]): Promise<{+ platform?: string;+ architecture?: string;+ bitness?: string;+ }>;+}+export type OS =| "windows"| "mac"@@ -39,7 +47,9 @@ export function useOs(): OS {let detected: OS = parseUA(navigator.userAgent);// Try Client Hints for better platform + architecture- const uaData = (navigator as any).userAgentData;+ const uaData = (+ navigator as Navigator & { userAgentData?: UserAgentData }+ ).userAgentData;if (uaData?.getHighEntropyValues) {try {const { platform, architecture, bitness } =diff --git a/frontend/editor/src/core/hooks/usePDFProcessor.ts b/frontend/editor/src/core/hooks/usePDFProcessor.tsindex 57b5388df4..e57df82384 100644--- a/frontend/editor/src/core/hooks/usePDFProcessor.ts+++ b/frontend/editor/src/core/hooks/usePDFProcessor.ts@@ -1,4 +1,5 @@import { useState, useCallback } from "react";+import type { PDFDocumentProxy } from "pdfjs-dist";import { PDFDocument, PDFPage } from "@app/types/pageEditor";import { pdfWorkerManager } from "@app/services/pdfWorkerManager";import { createQuickKey } from "@app/types/fileContext";@@ -46,7 +47,7 @@ export function usePDFProcessor() {// Internal function to generate thumbnail from already-opened PDFconst generateThumbnailFromPDF = useCallback(async (- pdf: any,+ pdf: PDFDocumentProxy,pageNumber: number,scale: number = 0.5,): Promise<string> => {@@ -62,7 +63,7 @@ export function usePDFProcessor() {throw new Error("Could not get canvas context");}- await page.render({ canvasContext: context, viewport }).promise;+ await page.render({ canvasContext: context, viewport, canvas }).promise;return canvas.toDataURL();},[],diff --git a/frontend/editor/src/core/hooks/usePdfSignatureDetection.ts b/frontend/editor/src/core/hooks/usePdfSignatureDetection.tsindex 0cfe016192..363ecbdcfa 100644--- a/frontend/editor/src/core/hooks/usePdfSignatureDetection.ts+++ b/frontend/editor/src/core/hooks/usePdfSignatureDetection.ts@@ -36,14 +36,16 @@ export const usePdfSignatureDetection = (intent: "display",});- annotations.forEach((annotation: any) => {- if (- annotation.subtype === "Widget" &&- annotation.fieldType === "Sig"- ) {- foundSignature = true;- }- });+ annotations.forEach(+ (annotation: { subtype?: string; fieldType?: string }) => {+ if (+ annotation.subtype === "Widget" &&+ annotation.fieldType === "Sig"+ ) {+ foundSignature = true;+ }+ },+ );if (foundSignature) break;}diff --git a/frontend/editor/src/core/hooks/useSuggestedTools.ts b/frontend/editor/src/core/hooks/useSuggestedTools.tsindex 5deb5d3a0d..d96cab3eeb 100644--- a/frontend/editor/src/core/hooks/useSuggestedTools.ts+++ b/frontend/editor/src/core/hooks/useSuggestedTools.ts@@ -14,7 +14,7 @@ import TextFieldsIcon from "@mui/icons-material/TextFields";export interface SuggestedTool {id: ToolId;title: string;- icon: React.ComponentType<any>;+ icon: React.ComponentType;href: string;onClick: (e: React.MouseEvent) => void;}diff --git a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts b/frontend/editor/src/core/hooks/useThumbnailGeneration.tsindex 495faf3456..13710acc1b 100644--- a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts+++ b/frontend/editor/src/core/hooks/useThumbnailGeneration.ts@@ -1,5 +1,8 @@import { useCallback } from "react";-import { thumbnailGenerationService } from "@app/services/thumbnailGenerationService";+import {+ thumbnailGenerationService,+ type ThumbnailResult,+} from "@app/services/thumbnailGenerationService";import { createQuickKey } from "@app/types/fileContext";import { FileId } from "@app/types/file";@@ -149,7 +152,7 @@ export function useThumbnailGeneration() {onProgress?: (progress: {completed: number;total: number;- thumbnails: any[];+ thumbnails: ThumbnailResult[];}) => void,) => {return thumbnailGenerationService.generateThumbnails(diff --git a/frontend/editor/src/core/hooks/useToolParameters.ts b/frontend/editor/src/core/hooks/useToolParameters.tsindex 0692940ee5..71d4b83fec 100644--- a/frontend/editor/src/core/hooks/useToolParameters.ts+++ b/frontend/editor/src/core/hooks/useToolParameters.ts@@ -4,14 +4,14 @@import { useCallback, useMemo } from "react";-type ToolParameterValues = Record<string, any>;+type ToolParameterValues = Record<string, unknown>;/*** Register tool parameters and get current values*/export function useToolParameters(_toolName: string,- _parameters: Record<string, any>,+ _parameters: Record<string, unknown>,): [ToolParameterValues, (updates: Partial<ToolParameterValues>) => void] {// Return empty values and noop updaterconst currentValues = useMemo(() => ({}), []);@@ -23,10 +23,10 @@ export function useToolParameters(/*** Hook for managing a single tool parameter*/-export function useToolParameter<T = any>(+export function useToolParameter<T = unknown>(toolName: string,paramName: string,- definition: any,+ definition: unknown,): [T, (value: T) => void] {const [allParams, updateParams] = useToolParameters(toolName, {[paramName]: definition,diff --git a/frontend/editor/src/core/services/pdfiumService.ts b/frontend/editor/src/core/services/pdfiumService.tsindex e5f5b1d0a8..01ecbbca10 100644--- a/frontend/editor/src/core/services/pdfiumService.ts+++ b/frontend/editor/src/core/services/pdfiumService.ts@@ -24,7 +24,7 @@ import {} from "@app/services/wasmPrecompiler";import type { FormField, WidgetCoordinates } from "@app/tools/formFill/types";-interface ExtendedPdfiumRuntime {+export interface ExtendedPdfiumRuntime {HEAPU8: Uint8Array;HEAPF32: Float32Array;}diff --git a/frontend/editor/src/core/services/thumbnailGenerationService.ts b/frontend/editor/src/core/services/thumbnailGenerationService.tsindex 0112f507e4..e653361566 100644--- a/frontend/editor/src/core/services/thumbnailGenerationService.ts+++ b/frontend/editor/src/core/services/thumbnailGenerationService.ts@@ -9,7 +9,7 @@ import {} from "@app/services/pdfiumService";import { renderPdfiumPageDataUrl } from "@app/utils/pdfiumPageRender";-interface ThumbnailResult {+export interface ThumbnailResult {pageNumber: number;thumbnail: string;success: boolean;diff --git a/frontend/editor/src/core/types/pageEditor.ts b/frontend/editor/src/core/types/pageEditor.tsindex bb87a5eb74..573eb8c964 100644--- a/frontend/editor/src/core/types/pageEditor.ts+++ b/frontend/editor/src/core/types/pageEditor.ts@@ -37,7 +37,7 @@ export interface PageOperation {pageIds: string[];timestamp: number;status: "pending" | "applied" | "failed";- data?: any;+ data?: unknown;metadata?: {rotation?: number;fromPosition?: number;diff --git a/frontend/editor/src/core/utils/automationConverter.test.ts b/frontend/editor/src/core/utils/automationConverter.test.tsindex d61d61f08e..9b6e21b7b0 100644--- a/frontend/editor/src/core/utils/automationConverter.test.ts+++ b/frontend/editor/src/core/utils/automationConverter.test.ts@@ -35,7 +35,7 @@ const registry = {// Dynamic endpoint — endpoint depends on parameters.convert: {operationConfig: {- endpoint: (params: Record<string, any>) =>+ endpoint: (params: Record<string, string>) =>`/api/v1/convert/${params.fromExtension}-to-${params.toExtension}`,},},@@ -130,7 +130,7 @@ describe("automationConverter", () => {compress: {operationConfig: {endpoint: "/api/v1/misc/compress-pdf",- toApiParams: (p: Record<string, any>) => ({+ toApiParams: (p: Record<string, string>) => ({optimizeLevel: p.compressionLevel,}),},@@ -250,7 +250,7 @@ describe("automationConverter", () => {compress: {operationConfig: {endpoint: "/api/v1/misc/compress-pdf",- toApiParams: (p: Record<string, any>) => ({+ toApiParams: (p: Record<string, string>) => ({optimizeLevel: p.compressionLevel,}),},@@ -278,7 +278,7 @@ describe("automationConverter", () => {...registry,splitLike: {operationConfig: {- endpoint: (p: Record<string, any>) =>+ endpoint: (p: Record<string, string>) =>p.method === "size"? "/api/v1/general/split-by-size": "/api/v1/general/split-pages",diff --git a/frontend/editor/src/core/utils/automationConverter.ts b/frontend/editor/src/core/utils/automationConverter.tsindex 05acbed8a6..5d647b6f35 100644--- a/frontend/editor/src/core/utils/automationConverter.ts+++ b/frontend/editor/src/core/utils/automationConverter.ts@@ -30,7 +30,7 @@ interface FolderScanningPipeline {icon?: string;pipeline: Array<{operation: string;- parameters: Record<string, any>;+ parameters: Record<string, unknown>;}>;_examples: {outputDir: string;@@ -191,7 +191,7 @@ function buildEndpointToToolIdMap(*/function findDynamicEndpointMatch(targetEndpoint: string,- parameters: Record<string, any>,+ parameters: Record<string, unknown>,toolRegistry: Partial<ToolRegistry>,): ToolId | undefined {for (const [toolId, entry] of Object.entries(toolRegistry)) {@@ -253,7 +253,8 @@ export function parseFolderScanningConfig(`Invalid folder scanning config: pipeline[${index}].operation must be a non-empty string`,);}- const rawParameters = (stepObj.parameters as Record<string, any>) || {};+ const rawParameters =+ (stepObj.parameters as Record<string, unknown>) || {};// Strip the export-time marker so the imported automation runs cleanly.const { fileInput: _fileInput, ...parameters } = rawParameters;@@ -337,7 +338,7 @@ export function parseAutomationConfigJson(`Invalid automation config: operations[${index}].operation must be a non-empty string`,);}- const parameters = (opObj.parameters as Record<string, any>) || {};+ const parameters = (opObj.parameters as Record<string, unknown>) || {};if (!isToolIdInRegistry(operation, toolRegistry)) {unresolved.push(operation);}diff --git a/frontend/editor/src/core/utils/automationExecutor.ts b/frontend/editor/src/core/utils/automationExecutor.tsindex 7855bc25e7..329e0a38bf 100644--- a/frontend/editor/src/core/utils/automationExecutor.ts+++ b/frontend/editor/src/core/utils/automationExecutor.ts@@ -11,10 +11,12 @@ import {} from "@app/hooks/tools/shared/toolOperationTypes";import { zipFileService } from "@app/services/zipFileService";import { processResponse } from "@app/utils/toolResponseProcessor";+import { extractErrorMessage } from "@app/utils/toolErrorHandler";+import { type AutomationConfig } from "@app/types/automation";export const processMultiFileResponse = async (responseData: Blob,- responseHeaders: any,+ responseHeaders: Record<string, unknown>,files: File[],filePrefix: string,preserveBackendFilename?: boolean,@@ -202,10 +204,10 @@ export const executeToolOperationWithPrefix = async (filePrefix,);}- } catch (error: any) {+ } catch (error) {console.error(`❌ ${operationName} failed:`, error);throw new Error(- `${operationName} operation failed: ${error.response?.data || error.message}`,+ `${operationName} operation failed: ${extractErrorMessage(error)}`,{cause: error,},@@ -217,7 +219,7 @@ export const executeToolOperationWithPrefix = async (* Execute an entire automation sequence*/export const executeAutomationSequence = async (- automation: any,+ automation: AutomationConfig,initialFiles: File[],toolRegistry: ToolRegistry,onStepStart?: (stepIndex: number, operationName: string) => void,@@ -260,9 +262,9 @@ export const executeAutomationSequence = async ();currentFiles = resultFiles;onStepComplete?.(i, resultFiles);- } catch (error: any) {+ } catch (error) {console.error(`❌ Step ${i + 1} failed:`, error);- onStepError?.(i, error.message);+ onStepError?.(i, error instanceof Error ? error.message : String(error));throw error;}}diff --git a/frontend/editor/src/core/utils/automationFileProcessor.ts b/frontend/editor/src/core/utils/automationFileProcessor.tsindex 6ff5a558be..ee2670063c 100644--- a/frontend/editor/src/core/utils/automationFileProcessor.ts+++ b/frontend/editor/src/core/utils/automationFileProcessor.ts@@ -6,6 +6,7 @@ import apiClient from "@app/services/apiClient";import { zipFileService } from "@app/services/zipFileService";import { ResourceManager } from "@app/utils/resourceManager";import { AUTOMATION_CONSTANTS } from "@app/constants/automation";+import { extractErrorMessage } from "@app/utils/toolErrorHandler";export interface AutomationProcessingOptions {timeout?: number;@@ -121,13 +122,11 @@ export class AutomationFileProcessor {files: [resultFile],errors: [],};- } catch (error: any) {+ } catch (error) {return {success: false,files: [],- errors: [- `Automation step failed: ${error.response?.data || error.message}`,- ],+ errors: [`Automation step failed: ${extractErrorMessage(error)}`],};}}@@ -158,13 +157,11 @@ export class AutomationFileProcessor {// Multi-file responses are typically ZIP filesreturn await this.extractAutomationZipFiles(response.data);- } catch (error: any) {+ } catch (error) {return {success: false,files: [],- errors: [- `Automation step failed: ${error.response?.data || error.message}`,- ],+ errors: [`Automation step failed: ${extractErrorMessage(error)}`],};}}@@ -173,7 +170,7 @@ export class AutomationFileProcessor {* Build form data for automation tool operations*/static buildAutomationFormData(- parameters: Record<string, any>,+ parameters: Record<string, unknown>,files: File | File[],fileFieldName: string = "fileInput",): FormData {@@ -186,12 +183,15 @@ export class AutomationFileProcessor {formData.append(fileFieldName, files);}- // Add parameters+ // Add parameters. FormData coerces non-Blob values to strings; do it+ // explicitly so the value type is honest.Object.entries(parameters).forEach(([key, value]) => {if (Array.isArray(value)) {- value.forEach((item) => formData.append(key, item));+ value.forEach((item) =>+ formData.append(key, item instanceof Blob ? item : String(item)),+ );} else if (value !== undefined && value !== null) {- formData.append(key, value);+ formData.append(key, value instanceof Blob ? value : String(value));}});diff --git a/frontend/editor/src/core/utils/convertUtils.test.ts b/frontend/editor/src/core/utils/convertUtils.test.tsindex a596e72258..a538e62939 100644--- a/frontend/editor/src/core/utils/convertUtils.test.ts+++ b/frontend/editor/src/core/utils/convertUtils.test.ts@@ -310,13 +310,25 @@ describe("convertUtils", () => {test("should handle null and undefined inputs gracefully", () => {// Note: TypeScript prevents these, but test runtime behavior for robustness// The current implementation handles these gracefully by returning falsy values- expect(getEndpointName(null as any, null as any)).toBe("");- expect(getEndpointUrl(undefined as any, undefined as any)).toBe("");- expect(isConversionSupported(null as any, null as any)).toBe(false);+ expect(+ getEndpointName(null as unknown as string, null as unknown as string),+ ).toBe("");+ expect(+ getEndpointUrl(+ undefined as unknown as string,+ undefined as unknown as string,+ ),+ ).toBe("");+ expect(+ isConversionSupported(+ null as unknown as string,+ null as unknown as string,+ ),+ ).toBe(false);// isImageFormat will throw because it calls toLowerCase() on null/undefined- expect(() => isImageFormat(null as any)).toThrow();- expect(() => isImageFormat(undefined as any)).toThrow();+ expect(() => isImageFormat(null as unknown as string)).toThrow();+ expect(() => isImageFormat(undefined as unknown as string)).toThrow();});test("should handle special characters in file extensions", () => {diff --git a/frontend/editor/src/core/utils/downloadUtils.ts b/frontend/editor/src/core/utils/downloadUtils.tsindex 0f25935b38..0aa0e9ee1d 100644--- a/frontend/editor/src/core/utils/downloadUtils.ts+++ b/frontend/editor/src/core/utils/downloadUtils.ts@@ -154,7 +154,7 @@ export function downloadTextAsFile(* @param data - Data to serialize and download* @param filename - Filename for the download*/-export function downloadJsonAsFile(data: any, filename: string): void {+export function downloadJsonAsFile(data: unknown, filename: string): void {const content = JSON.stringify(data, null, 2);downloadTextAsFile(content, filename, "application/json");}diff --git a/frontend/editor/src/core/utils/fileResponseUtils.ts b/frontend/editor/src/core/utils/fileResponseUtils.tsindex 35b640e86b..8f27d03a21 100644--- a/frontend/editor/src/core/utils/fileResponseUtils.ts+++ b/frontend/editor/src/core/utils/fileResponseUtils.ts@@ -35,12 +35,15 @@ export const getFilenameFromHeaders = (* @returns File object*/export const createFileFromApiResponse = (- responseData: any,- headers: any,+ responseData: BlobPart,+ headers: Record<string, unknown> | null | undefined,fallbackFilename: string,): File => {- const contentType = headers?.["content-type"] || "application/octet-stream";- const contentDisposition = headers?.["content-disposition"] || "";+ const contentType =+ (headers?.["content-type"] as string | undefined) ||+ "application/octet-stream";+ const contentDisposition =+ (headers?.["content-disposition"] as string | undefined) || "";const filename =getFilenameFromHeaders(contentDisposition) || fallbackFilename;diff --git a/frontend/editor/src/core/utils/fsAccessCapability.ts b/frontend/editor/src/core/utils/fsAccessCapability.tsindex 884968fdf6..d32505b584 100644--- a/frontend/editor/src/core/utils/fsAccessCapability.ts+++ b/frontend/editor/src/core/utils/fsAccessCapability.ts@@ -10,19 +10,19 @@/** True when the browser can pick a directory and read files from it. */export const canReadLocalFolder: boolean =typeof window !== "undefined" &&- typeof (window as any).showDirectoryPicker === "function";+ typeof window.showDirectoryPicker === "function";/** True when the browser supports writing files (createWritable). Requires Chrome/Edge. */export const canWriteLocalFolder: boolean =canReadLocalFolder &&typeof FileSystemFileHandle !== "undefined" &&- typeof (FileSystemFileHandle.prototype as any).createWritable === "function";+ typeof FileSystemFileHandle.prototype.createWritable === "function";/** True when the browser supports permission querying across sessions (queryPermission). */export const canPersistFsPermission: boolean =canReadLocalFolder &&typeof FileSystemHandle !== "undefined" &&- typeof (FileSystemHandle.prototype as any).queryPermission === "function";+ typeof FileSystemHandle.prototype.queryPermission === "function";export const FS_READ_UNSUPPORTED_MSG ="Your browser does not support the File System Access API. Use Chrome or Edge.";diff --git a/frontend/editor/src/core/utils/pdfiumBitmapUtils.ts b/frontend/editor/src/core/utils/pdfiumBitmapUtils.tsindex a73babb5f4..870c8c3b1d 100644--- a/frontend/editor/src/core/utils/pdfiumBitmapUtils.ts+++ b/frontend/editor/src/core/utils/pdfiumBitmapUtils.ts@@ -10,6 +10,7 @@* copy the result into the WASM heap with a single `HEAPU8.set()`.*/import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import type { ExtendedPdfiumRuntime } from "@app/services/pdfiumService";/** FPDF_ANNOT_LINK */export const FPDF_ANNOT_LINK = 4;@@ -56,14 +57,14 @@ export function copyRgbaToBgraHeap(bgra[i + 2] = rgba[i]; // Rbgra[i + 3] = rgba[i + 3]; // A}- new Uint8Array((m.pdfium.wasmExports as any).memory.buffer).set(+ (m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8.set(bgra,bufferPtr,);} else {// Stride has padding — swizzle + copy row by rowconst rowBuf = new Uint8Array(rowBytes);- const heap = new Uint8Array((m.pdfium.wasmExports as any).memory.buffer);+ const heap = (m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8;for (let y = 0; y < height; y++) {const srcRowStart = y * rowBytes;for (let x = 0; x < rowBytes; x += 4) {diff --git a/frontend/editor/src/core/utils/pdfiumPageRender.ts b/frontend/editor/src/core/utils/pdfiumPageRender.tsindex 1235653405..bbe222fa1b 100644--- a/frontend/editor/src/core/utils/pdfiumPageRender.ts+++ b/frontend/editor/src/core/utils/pdfiumPageRender.ts@@ -6,7 +6,10 @@* per-page thumbnail service (thumbnailGenerationService.ts) so the pixel-* copy + white-background logic lives in one place.*/-import { getPdfiumModule } from "@app/services/pdfiumService";+import {+ getPdfiumModule,+ type ExtendedPdfiumRuntime,+} from "@app/services/pdfiumService";/** FPDF_ANNOT (0x01) | FPDF_LCD_TEXT (0x10). */const PDFIUM_RENDER_FLAGS = 0x01 | 0x10;@@ -43,7 +46,7 @@ export async function renderPdfiumPageDataUrl(const rawW = m.FPDF_GetPageWidthF(pagePtr);const rawH = m.FPDF_GetPageHeightF(pagePtr);// Returns 0–3 for 0°/90°/180°/270° CW.- const pageRotQuarters = (m as any).FPDFPage_GetRotation(pagePtr) | 0;+ const pageRotQuarters = m.FPDFPage_GetRotation(pagePtr) | 0;const isQuarterTurn = pageRotQuarters === 1 || pageRotQuarters === 3;@@ -72,7 +75,7 @@ export async function renderPdfiumPageDataUrl(const bufferPtr = m.FPDFBitmap_GetBuffer(bitmapPtr);const stride = m.FPDFBitmap_GetStride(bitmapPtr);- const heap = new Uint8Array((m.pdfium.wasmExports as any).memory.buffer);+ const heap = (m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8;const pixels = new Uint8ClampedArray(w * h * 4);// @embedpdf/pdfium WASM stores pixels in RGBA byte order (not BGRA),@@ -112,7 +115,7 @@ export async function readPdfiumPageMetadata(try {const width = m.FPDF_GetPageWidthF(pagePtr);const height = m.FPDF_GetPageHeightF(pagePtr);- const rotation = (((m as any).FPDFPage_GetRotation(pagePtr) | 0) & 3) * 90;+ const rotation = ((m.FPDFPage_GetRotation(pagePtr) | 0) & 3) * 90;return { width, height, rotation };} finally {m.FPDF_ClosePage(pagePtr);diff --git a/frontend/editor/src/core/utils/signatureFlattening.ts b/frontend/editor/src/core/utils/signatureFlattening.tsindex a6200f52f2..289662deac 100644--- a/frontend/editor/src/core/utils/signatureFlattening.ts+++ b/frontend/editor/src/core/utils/signatureFlattening.ts@@ -29,6 +29,38 @@ interface MinimalFileContextSelectors {getFile: (id: FileId) => StirlingFile | undefined;}+/**+ * The subset of EmbedPDF's annotation payload this flattener reads. EmbedPDF+ * types `getPageAnnotations` as `any[]`; geometry and image fields vary by+ * annotation source, so each accessor path is optional.+ */+interface AnnotationRect {+ origin?: { x?: number; y?: number };+ size?: { width?: number; height?: number };+ x?: number;+ y?: number;+ left?: number;+ top?: number;+ width?: number;+ height?: number;+}++interface SignatureAnnotation {+ id: string;+ rect?: AnnotationRect;+ bounds?: AnnotationRect;+ rectangle?: AnnotationRect;+ position?: AnnotationRect;+ imageSrc?: unknown;+ imageData?: unknown;+ appearance?: unknown;+ stampData?: unknown;+ contents?: unknown;+ data?: unknown;+ customData?: unknown;+ asset?: unknown;+}+interface SignatureFlatteningOptions {signatureApiRef: React.RefObject<SignatureAPI | null>;getImageData: (id: string) => string | undefined;@@ -62,7 +94,10 @@ export async function flattenSignatures(try {// Step 1: Extract all annotations from EmbedPDF before export- const allAnnotations: Array<{ pageIndex: number; annotations: any[] }> = [];+ const allAnnotations: Array<{+ pageIndex: number;+ annotations: SignatureAnnotation[];+ }> = [];if (signatureApiRef?.current) {const scrollState = getScrollState();@@ -209,7 +244,7 @@ export async function flattenSignatures(type SignatureAnnotationsByPage = Array<{pageIndex: number;- annotations: any[];+ annotations: SignatureAnnotation[];}>;function extractImageDataUrl(@@ -238,7 +273,7 @@ function extractImageDataUrl(}function getAnnotationImageData(- annotation: any,+ annotation: SignatureAnnotation,getImageData: (id: string) => string | undefined,): string | undefined {// EmbedPDF can replace fields such as imageData/appearance with an internaldiff --git a/frontend/editor/src/core/utils/toolErrorHandler.ts b/frontend/editor/src/core/utils/toolErrorHandler.tsindex d023fdc788..020283135b 100644--- a/frontend/editor/src/core/utils/toolErrorHandler.ts+++ b/frontend/editor/src/core/utils/toolErrorHandler.ts@@ -2,16 +2,24 @@* Standardized error handling utilities for tool operations*/+import axios from "axios";import { normalizeAxiosErrorData } from "@app/services/errorUtils";/**- * Default error extractor that follows the standard pattern+ * Default error extractor that follows the standard pattern.+ *+ * The desktop Tauri HTTP client tags its errors with `isAxiosError`, so+ * {@link axios.isAxiosError} recognises both real and Tauri-shaped errors.*/-export const extractErrorMessage = (error: any): string => {- if (error.response?.data && typeof error.response.data === "string") {+export const extractErrorMessage = (error: unknown): string => {+ if (+ axios.isAxiosError(error) &&+ typeof error.response?.data === "string" &&+ error.response.data.length > 0+ ) {return error.response.data;}- if (error.message) {+ if (error instanceof Error && error.message) {return error.message;}return "There was an error processing your request.";@@ -23,11 +31,15 @@ export const extractErrorMessage = (error: any): string => {* @returns Error handler function that follows the standard pattern*/export const createStandardErrorHandler = (fallbackMessage: string) => {- return (error: any): string => {- if (error.response?.data && typeof error.response.data === "string") {+ return (error: unknown): string => {+ if (+ axios.isAxiosError(error) &&+ typeof error.response?.data === "string" &&+ error.response.data.length > 0+ ) {return error.response.data;}- if (error.message) {+ if (error instanceof Error && error.message) {return error.message;}return fallbackMessage;@@ -39,13 +51,14 @@ export const createStandardErrorHandler = (fallbackMessage: string) => {* and marks them in the UI. Returns true if IDs were found and handled, false otherwise.*/export const handle422Error = async (- error: any,+ error: unknown,markFileError: (fileId: string) => void,): Promise<boolean> => {- const status = error?.response?.status;- if (typeof status !== "number" || status !== 422) return false;+ if (!axios.isAxiosError(error) || error.response?.status !== 422) {+ return false;+ }- const payload = error?.response?.data;+ const payload = error.response?.data;let parsed: unknown = payload;if (typeof payload === "string") {@@ -98,11 +111,12 @@ export const handle422Error = async (* @returns Error message string*/export const handlePasswordError = async (- error: any,+ error: unknown,incorrectPasswordMessage: string,fallbackMessage: string,): Promise<string> => {- const status = error?.response?.status;+ const axiosError = axios.isAxiosError(error) ? error : undefined;+ const status = axiosError?.response?.status;// Handle specific error cases with user-friendly messages// Backend returns 400 with PdfPasswordException for incorrect/missing PDF passwords@@ -110,7 +124,7 @@ export const handlePasswordError = async (return incorrectPasswordMessage;}if (status === 400) {- const data = error?.response?.data;+ const data = axiosError?.response?.data;// ProblemDetail JSON has type "/errors/pdf-password", blob needs parsingconst isPasswordError = await (async () => {if (data instanceof Blob) {@@ -121,7 +135,7 @@ export const handlePasswordError = async (return false;}}- const type = data?.type ?? "";+ const type = (data as { type?: string })?.type ?? "";return type.includes("pdf-password");})();if (isPasswordError) {@@ -129,14 +143,13 @@ export const handlePasswordError = async (}}- // For other errors, try to extract the message- const normalizedData = await normalizeAxiosErrorData(error?.response?.data);- const errorWithNormalizedData = {- ...error,- response: {- ...error?.response,- data: normalizedData,- },- };- return extractErrorMessage(errorWithNormalizedData) || fallbackMessage;+ // For other errors, prefer the normalized response body (a blob is parsed to+ // text/JSON), else fall back to the error's own message.+ const normalizedData = await normalizeAxiosErrorData(+ axiosError?.response?.data,+ );+ if (typeof normalizedData === "string" && normalizedData.length > 0) {+ return normalizedData;+ }+ return extractErrorMessage(error) || fallbackMessage;};diff --git a/frontend/editor/src/core/utils/toolResponseProcessor.ts b/frontend/editor/src/core/utils/toolResponseProcessor.tsindex e36a93ecb5..0b569215bc 100644--- a/frontend/editor/src/core/utils/toolResponseProcessor.ts+++ b/frontend/editor/src/core/utils/toolResponseProcessor.ts@@ -18,7 +18,7 @@ export async function processResponse(originalFiles: File[],filePrefix?: string,responseHandler?: ResponseHandler,- responseHeaders?: Record<string, any>,+ responseHeaders?: Record<string, unknown>,): Promise<File[]> {if (responseHandler) {const out = await responseHandler(blob, originalFiles);@@ -28,12 +28,14 @@ export async function processResponse(// Check if we should use the backend-provided filename from headers// Only when responseHeaders are explicitly provided (indicating the operation requested this)if (responseHeaders) {- const contentDisposition = responseHeaders["content-disposition"];+ const contentDisposition = responseHeaders["content-disposition"] as+ | string+ | undefined;const backendFilename = getFilenameFromHeaders(contentDisposition);if (backendFilename) {const type =blob.type ||- responseHeaders["content-type"] ||+ (responseHeaders["content-type"] as string | undefined) ||"application/octet-stream";return [new File([blob], backendFilename, { type })];}diff --git a/frontend/editor/src/global.d.ts b/frontend/editor/src/global.d.tsindex 6b38e511b4..5060a47b24 100644--- a/frontend/editor/src/global.d.ts+++ b/frontend/editor/src/global.d.ts@@ -23,6 +23,28 @@ declare global {STIRLING_PDF_API_BASE_URL?: string;endpointAvailabilityService?: unknown;pdfjsLib?: typeof import("pdfjs-dist");+ /**+ * File System Access API directory picker. Not in the DOM lib; present in+ * Chromium and Firefox, absent in older Safari, so callers feature-detect.+ */+ showDirectoryPicker?: (options?: {+ id?: string;+ mode?: "read" | "readwrite";+ startIn?: FileSystemHandle | string;+ }) => Promise<FileSystemDirectoryHandle>;+ }++ /**+ * Non-standard permission methods on File System Access handles (Chromium+ * only; absent in Firefox/Safari). Optional so callers must feature-detect.+ */+ interface FileSystemHandle {+ queryPermission?: (descriptor?: {+ mode?: "read" | "readwrite";+ }) => Promise<PermissionState>;+ requestPermission?: (descriptor?: {+ mode?: "read" | "readwrite";+ }) => Promise<PermissionState>;}}diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsxindex 2276e1aa82..8747fe0dfe 100644--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx+++ b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx@@ -482,13 +482,11 @@ export function WatchedFolderManagementModal({variant="tertiary"onClick={async () => {try {- const handle = await (- window as unknown as {- showDirectoryPicker: (options?: {- mode?: "read" | "readwrite";- }) => Promise<FileSystemDirectoryHandle>;- }- ).showDirectoryPicker({ mode: "read" });+ const handle =+ await window.showDirectoryPicker?.({+ mode: "read",+ });+ if (!handle) return;pendingInputDirHandle.current = handle;setInputDirName(handle.name);} catch {@@ -580,13 +578,12 @@ export function WatchedFolderManagementModal({disabled={!canWriteLocalFolder}onClick={async () => {try {- const handle = await (- window as unknown as {- showDirectoryPicker: (options?: {- mode?: "read" | "readwrite";- }) => Promise<FileSystemDirectoryHandle>;- }- ).showDirectoryPicker({ mode: "readwrite" });+ const handle = await window.showDirectoryPicker?.(+ {+ mode: "readwrite",+ },+ );+ if (!handle) return;pendingDirHandle.current = handle;setOutputDirName(handle.name);} catch {diff --git a/frontend/oxlint.config.ts b/frontend/oxlint.config.tsindex c8c7ce711c..a52050bd7b 100644--- a/frontend/oxlint.config.ts+++ b/frontend/oxlint.config.ts@@ -75,12 +75,21 @@ const modernGlobals: OxlintGlobals = {// Folders not yet conformant to the stricter no-explicit-any ruleconst noExplicitAnyExcludes = ["editor/src/core/components/shared/config/configSections/*.{js,mjs,jsx,ts,tsx}",- "editor/src/core/components/viewer/*.{js,mjs,jsx,ts,tsx}",- "editor/src/core/contexts/*.{js,mjs,jsx,ts,tsx}",- "editor/src/core/hooks/*.{js,mjs,jsx,ts,tsx}",+ "editor/src/core/components/viewer/layerUtils.ts",+ "editor/src/core/components/viewer/SignatureAPIBridge.tsx",+ "editor/src/core/components/viewer/HistoryAPIBridge.tsx",+ "editor/src/core/components/viewer/TextSelectionHandler.tsx",+ "editor/src/core/components/viewer/RulerOverlay.tsx",+ "editor/src/core/components/viewer/viewerTypes.ts",+ "editor/src/core/components/viewer/EmbedPdfViewer.tsx",+ "editor/src/core/components/viewer/RedactionSelectionMenu.tsx",+ "editor/src/core/contexts/ToolWorkflowContext.tsx","editor/src/core/tools/annotate/useAnnotationSelection.ts",- "editor/src/core/types/*.{js,mjs,jsx,ts,tsx}",- "editor/src/core/utils/*.{js,mjs,jsx,ts,tsx}",+ "editor/src/core/types/fileContext.ts",+ "editor/src/core/types/fileIdSafety.d.ts",+ "editor/src/core/types/automation.ts",+ "editor/src/core/types/tool.ts",+ "editor/src/core/utils/settingsPendingHelper.ts",];export default defineConfig({