SPB Git forge

spb/spb-cloud

Public
10commits 1branches 0releases
3.2 MBsize
maindefault branch
1 h agolast push
JavaScript 56.7% TypeScript 42.6%

chore: checkpoint v2 WIP before v3 redesign (2026-09-07)

Simon-Pierre Boucher committed 25 days ago (Sep 7, 2026) parent 2f468ea

102 changed files +9,863 −742

modified .gitignore +4 −0
@@ -28,3 +28,7 @@ Thumbs.db
28 28
29 29 # Claude
30 30 .claude/
31 +
32 +# Snapshots (26G, never commit)
33 +snapshots/
34 +*.tsbuildinfo
modified app/admin/backup/page.tsx +13 −3
@@ -2,16 +2,26 @@
2 2
3 3 import AppShell from "@/components/layout/AppShell";
4 4 import BackupPanel from "@/components/admin/BackupPanel";
5 +import SnapshotPanel from "@/components/admin/SnapshotPanel";
5 6
6 7 export default function BackupPage() {
7 8 return (
8 9 <AppShell>
9 − <div className="p-4 lg:p-6 space-y-6">
10 + <div className="p-4 lg:p-6 space-y-8">
10 11 <div>
11 − <h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Backups</h1>
12 + <h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Backups & Snapshots</h1>
12 13 <p className="text-sm text-gray-500 mt-1">Sauvegardez et restaurez vos données</p>
13 14 </div>
14 − <BackupPanel />
15 +
16 + {/* Daily snapshots — rolling 7-day window */}
17 + <div className="bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-2xl p-4 lg:p-6">
18 + <SnapshotPanel />
19 + </div>
20 +
21 + {/* Manual full/incremental backups */}
22 + <div className="bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-2xl p-4 lg:p-6">
23 + <BackupPanel />
24 + </div>
15 25 </div>
16 26 </AppShell>
17 27 );
modified app/api/admin/activity/route.ts +5 −1
@@ -16,5 +16,9 @@ export async function GET(request: NextRequest) {
16 16 prisma.activityLog.count(),
17 17 ]);
18 18
19 − return NextResponse.json({ activities, total });
19 + return NextResponse.json({
20 + activities,
21 + total,
22 + hasMore: offset + limit < total,
23 + });
20 24 }
added app/api/ai/agent/route.ts +682 −0
@@ -0,0 +1,682 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +import { deleteFile, loadFileData } from "@/lib/storage";
6 +import { logActivity } from "@/lib/activity";
7 +import Anthropic from "@anthropic-ai/sdk";
8 +
9 +const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
10 +const MODEL = "claude-opus-4-6";
11 +const MAX_ITERATIONS = 15;
12 +
13 +// ─── Tool definitions ─────────────────────────────────────────────────────────
14 +
15 +const TOOLS: Anthropic.Tool[] = [
16 + {
17 + name: "list_files",
18 + description:
19 + "Liste les fichiers dans un dossier. Si folderId est omis ou null, liste les fichiers à la racine.",
20 + input_schema: {
21 + type: "object" as const,
22 + properties: {
23 + folderId: {
24 + type: "string",
25 + description: "ID du dossier (omis ou null = racine)",
26 + },
27 + },
28 + required: [],
29 + },
30 + },
31 + {
32 + name: "list_folders",
33 + description:
34 + "Liste les sous-dossiers. Si parentId est omis ou null, liste les dossiers à la racine.",
35 + input_schema: {
36 + type: "object" as const,
37 + properties: {
38 + parentId: {
39 + type: "string",
40 + description: "ID du dossier parent (omis ou null = racine)",
41 + },
42 + },
43 + required: [],
44 + },
45 + },
46 + {
47 + name: "create_folder",
48 + description: "Crée un nouveau dossier.",
49 + input_schema: {
50 + type: "object" as const,
51 + properties: {
52 + name: {
53 + type: "string",
54 + description: "Nom du dossier à créer",
55 + },
56 + parentId: {
57 + type: "string",
58 + description: "ID du dossier parent (omis ou null = racine)",
59 + },
60 + },
61 + required: ["name"],
62 + },
63 + },
64 + {
65 + name: "rename_file",
66 + description: "Renomme un fichier.",
67 + input_schema: {
68 + type: "object" as const,
69 + properties: {
70 + fileId: {
71 + type: "string",
72 + description: "ID du fichier à renommer",
73 + },
74 + newName: {
75 + type: "string",
76 + description: "Nouveau nom du fichier (avec extension)",
77 + },
78 + },
79 + required: ["fileId", "newName"],
80 + },
81 + },
82 + {
83 + name: "move_file",
84 + description: "Déplace un fichier vers un autre dossier.",
85 + input_schema: {
86 + type: "object" as const,
87 + properties: {
88 + fileId: {
89 + type: "string",
90 + description: "ID du fichier à déplacer",
91 + },
92 + targetFolderId: {
93 + type: "string",
94 + description:
95 + "ID du dossier de destination (omis ou null = racine)",
96 + },
97 + },
98 + required: ["fileId"],
99 + },
100 + },
101 + {
102 + name: "rename_folder",
103 + description: "Renomme un dossier.",
104 + input_schema: {
105 + type: "object" as const,
106 + properties: {
107 + folderId: {
108 + type: "string",
109 + description: "ID du dossier à renommer",
110 + },
111 + newName: {
112 + type: "string",
113 + description: "Nouveau nom du dossier",
114 + },
115 + },
116 + required: ["folderId", "newName"],
117 + },
118 + },
119 + {
120 + name: "move_folder",
121 + description: "Déplace un dossier vers un autre dossier parent.",
122 + input_schema: {
123 + type: "object" as const,
124 + properties: {
125 + folderId: {
126 + type: "string",
127 + description: "ID du dossier à déplacer",
128 + },
129 + targetParentId: {
130 + type: "string",
131 + description:
132 + "ID du dossier parent de destination (omis ou null = racine)",
133 + },
134 + },
135 + required: ["folderId"],
136 + },
137 + },
138 + {
139 + name: "delete_file",
140 + description:
141 + "Supprime définitivement un fichier. Action irréversible — confirm doit être true.",
142 + input_schema: {
143 + type: "object" as const,
144 + properties: {
145 + fileId: {
146 + type: "string",
147 + description: "ID du fichier à supprimer",
148 + },
149 + confirm: {
150 + type: "boolean",
151 + description: "Doit être true pour confirmer la suppression",
152 + },
153 + },
154 + required: ["fileId", "confirm"],
155 + },
156 + },
157 + {
158 + name: "list_shared_spaces",
159 + description:
160 + "Liste les espaces partagés dont l'utilisateur est membre. Utile pour obtenir l'ID d'un espace avant de le renommer.",
161 + input_schema: {
162 + type: "object" as const,
163 + properties: {},
164 + required: [],
165 + },
166 + },
167 + {
168 + name: "rename_shared_space",
169 + description: "Renomme un espace partagé dont l'utilisateur est membre.",
170 + input_schema: {
171 + type: "object" as const,
172 + properties: {
173 + sharedSpaceId: {
174 + type: "string",
175 + description: "ID de l'espace partagé à renommer",
176 + },
177 + newName: {
178 + type: "string",
179 + description: "Nouveau nom de l'espace partagé",
180 + },
181 + },
182 + required: ["sharedSpaceId", "newName"],
183 + },
184 + },
185 + {
186 + name: "analyze_image",
187 + description:
188 + "Analyse le contenu visuel d'une image (photo, screenshot, etc). Peut identifier objets, scènes, texte visible, personnes, lieux, etc. Utilise la vision par IA.",
189 + input_schema: {
190 + type: "object" as const,
191 + properties: {
192 + fileId: {
193 + type: "string",
194 + description: "ID du fichier image à analyser",
195 + },
196 + question: {
197 + type: "string",
198 + description:
199 + "Question spécifique sur l'image (optionnel). Par défaut: description détaillée.",
200 + },
201 + },
202 + required: ["fileId"],
203 + },
204 + },
205 + {
206 + name: "read_file_content",
207 + description:
208 + "Lit le contenu textuel d'un fichier (texte, code, markdown, JSON, CSV, etc). Pour les PDFs, extrait le texte. Pour les images, utilise analyze_image plutôt.",
209 + input_schema: {
210 + type: "object" as const,
211 + properties: {
212 + fileId: {
213 + type: "string",
214 + description: "ID du fichier à lire",
215 + },
216 + },
217 + required: ["fileId"],
218 + },
219 + },
220 +];
221 +
222 +// ─── Helpers ──────────────────────────────────────────────────────────────────
223 +
224 +/** IDs of shared spaces the user is a member of */
225 +async function getUserSharedSpaceIds(userId: string): Promise<string[]> {
226 + const memberships = await prisma.sharedSpaceMember.findMany({
227 + where: { userId },
228 + select: { sharedSpaceId: true },
229 + });
230 + return memberships.map((m) => m.sharedSpaceId);
231 +}
232 +
233 +/**
234 + * Find a file the user can access:
235 + * - owns it (userId match or null)
236 + * - or it lives in a shared-space folder the user is a member of
237 + */
238 +async function findAccessibleFile(fileId: string, userId: string) {
239 + const sharedSpaceIds = await getUserSharedSpaceIds(userId);
240 + return prisma.file.findFirst({
241 + where: {
242 + id: fileId,
243 + OR: [
244 + { userId },
245 + { userId: null },
246 + ...(sharedSpaceIds.length > 0
247 + ? [{ folder: { sharedSpaceId: { in: sharedSpaceIds } } }]
248 + : []),
249 + ],
250 + },
251 + });
252 +}
253 +
254 +/**
255 + * Find a folder the user can access:
256 + * - owns it (userId match or null)
257 + * - or it belongs to a shared space the user is a member of (root or sub-folder)
258 + */
259 +async function findAccessibleFolder(folderId: string, userId: string) {
260 + const sharedSpaceIds = await getUserSharedSpaceIds(userId);
261 + return prisma.folder.findFirst({
262 + where: {
263 + id: folderId,
264 + OR: [
265 + { userId },
266 + { userId: null },
267 + ...(sharedSpaceIds.length > 0
268 + ? [{ sharedSpaceId: { in: sharedSpaceIds } }]
269 + : []),
270 + ],
271 + },
272 + });
273 +}
274 +
275 +// ─── Tool executor ────────────────────────────────────────────────────────────
276 +
277 +async function executeTool(
278 + name: string,
279 + input: Record<string, unknown>,
280 + userId: string
281 +): Promise<string> {
282 + try {
283 + switch (name) {
284 + case "list_files": {
285 + const folderId = (input.folderId as string | undefined) ?? null;
286 +
287 + let where: Record<string, unknown>;
288 + if (folderId) {
289 + // Inside a specific folder — show all files regardless of uploader.
290 + // Access is implied by knowing the folderId (consistent with main API).
291 + where = { folderId };
292 + } else {
293 + // Root — only personal files (shared-space files live in folders)
294 + where = { folderId: null, OR: [{ userId }, { userId: null }] };
295 + }
296 +
297 + const files = await prisma.file.findMany({
298 + where,
299 + select: { id: true, name: true, mimeType: true, size: true },
300 + take: 100,
301 + orderBy: { name: "asc" },
302 + });
303 + const safe = files.map((f) => ({ ...f, size: Number(f.size) }));
304 + return JSON.stringify({ count: safe.length, files: safe });
305 + }
306 +
307 + case "list_folders": {
308 + const parentId = (input.parentId as string | undefined) ?? null;
309 +
310 + let folders;
311 + if (parentId === null) {
312 + // Root — personal folders + shared-space root folders
313 + const sharedSpaceIds = await getUserSharedSpaceIds(userId);
314 + folders = await prisma.folder.findMany({
315 + where: {
316 + parentId: null,
317 + OR: [
318 + { userId },
319 + ...(sharedSpaceIds.length > 0
320 + ? [{ sharedSpaceId: { in: sharedSpaceIds } }]
321 + : []),
322 + ],
323 + },
324 + select: { id: true, name: true, parentId: true, sharedSpaceId: true },
325 + orderBy: { name: "asc" },
326 + });
327 + } else {
328 + // Sub-folder navigation — show all children (access implied by parentId)
329 + folders = await prisma.folder.findMany({
330 + where: { parentId },
331 + select: { id: true, name: true, parentId: true, sharedSpaceId: true },
332 + orderBy: { name: "asc" },
333 + });
334 + }
335 + return JSON.stringify({ count: folders.length, folders });
336 + }
337 +
338 + case "create_folder": {
339 + const folderName = input.name as string;
340 + const parentId = (input.parentId as string | undefined) ?? null;
341 + const folder = await prisma.folder.create({
342 + data: { name: folderName, parentId, userId },
343 + });
344 + await logActivity(
345 + "folder_created",
346 + null,
347 + `Dossier "${folderName}" créé par l'agent IA`
348 + );
349 + return JSON.stringify({ success: true, folder });
350 + }
351 +
352 + case "rename_file": {
353 + const fileId = input.fileId as string;
354 + const newName = input.newName as string;
355 + const file = await findAccessibleFile(fileId, userId);
356 + if (!file)
357 + return JSON.stringify({ error: "Fichier introuvable ou accès refusé" });
358 + await prisma.file.update({
359 + where: { id: fileId },
360 + data: { name: newName },
361 + });
362 + await logActivity(
363 + "file_renamed",
364 + fileId,
365 + `Renommé en "${newName}" par l'agent IA`
366 + );
367 + return JSON.stringify({ success: true, id: fileId, newName });
368 + }
369 +
370 + case "move_file": {
371 + const fileId = input.fileId as string;
372 + const targetFolderId =
373 + (input.targetFolderId as string | undefined) ?? null;
374 + const file = await findAccessibleFile(fileId, userId);
375 + if (!file)
376 + return JSON.stringify({ error: "Fichier introuvable ou accès refusé" });
377 + await prisma.file.update({
378 + where: { id: fileId },
379 + data: { folderId: targetFolderId },
380 + });
381 + await logActivity(
382 + "file_moved",
383 + fileId,
384 + `"${file.name}" déplacé par l'agent IA`
385 + );
386 + return JSON.stringify({
387 + success: true,
388 + id: fileId,
389 + name: file.name,
390 + targetFolderId,
391 + });
392 + }
393 +
394 + case "rename_folder": {
395 + const folderId = input.folderId as string;
396 + const newName = input.newName as string;
397 + const folder = await findAccessibleFolder(folderId, userId);
398 + if (!folder)
399 + return JSON.stringify({ error: "Dossier introuvable ou accès refusé" });
400 + await prisma.folder.update({
401 + where: { id: folderId },
402 + data: { name: newName },
403 + });
404 + await logActivity(
405 + "folder_renamed",
406 + null,
407 + `Dossier renommé en "${newName}" par l'agent IA`
408 + );
409 + return JSON.stringify({ success: true, id: folderId, newName });
410 + }
411 +
412 + case "move_folder": {
413 + const folderId = input.folderId as string;
414 + const targetParentId =
415 + (input.targetParentId as string | undefined) ?? null;
416 + const folder = await findAccessibleFolder(folderId, userId);
417 + if (!folder)
418 + return JSON.stringify({ error: "Dossier introuvable ou accès refusé" });
419 + await prisma.folder.update({
420 + where: { id: folderId },
421 + data: { parentId: targetParentId },
422 + });
423 + await logActivity(
424 + "folder_moved",
425 + null,
426 + `Dossier "${folder.name}" déplacé par l'agent IA`
427 + );
428 + return JSON.stringify({
429 + success: true,
430 + id: folderId,
431 + name: folder.name,
432 + targetParentId,
433 + });
434 + }
435 +
436 + case "delete_file": {
437 + const fileId = input.fileId as string;
438 + const confirm = input.confirm as boolean;
439 + if (!confirm)
440 + return JSON.stringify({
441 + error: "Confirmation requise — passe confirm: true pour supprimer",
442 + });
443 + const file = await findAccessibleFile(fileId, userId);
444 + if (!file)
445 + return JSON.stringify({ error: "Fichier introuvable ou accès refusé" });
446 + try {
447 + await deleteFile(file.storagePath);
448 + } catch {
449 + // File may not exist on disk — continue to delete DB record
450 + }
451 + await prisma.file.delete({ where: { id: fileId } });
452 + await logActivity(
453 + "file_deleted",
454 + null,
455 + `Fichier "${file.name}" supprimé par l'agent IA`
456 + );
457 + return JSON.stringify({ success: true, deleted: file.name });
458 + }
459 +
460 + case "list_shared_spaces": {
461 + const memberships = await prisma.sharedSpaceMember.findMany({
462 + where: { userId },
463 + include: { sharedSpace: { select: { id: true, name: true } } },
464 + orderBy: { joinedAt: "asc" },
465 + });
466 + const spaces = memberships.map((m) => m.sharedSpace);
467 + return JSON.stringify({ count: spaces.length, sharedSpaces: spaces });
468 + }
469 +
470 + case "rename_shared_space": {
471 + const sharedSpaceId = input.sharedSpaceId as string;
472 + const newName = input.newName as string;
473 + // Verify membership
474 + const membership = await prisma.sharedSpaceMember.findUnique({
475 + where: { sharedSpaceId_userId: { sharedSpaceId, userId } },
476 + });
477 + if (!membership)
478 + return JSON.stringify({
479 + error: "Espace partagé introuvable ou accès refusé",
480 + });
481 + await prisma.sharedSpace.update({
482 + where: { id: sharedSpaceId },
483 + data: { name: newName },
484 + });
485 + await logActivity(
486 + "shared_space_renamed",
487 + null,
488 + `Espace partagé renommé en "${newName}" par l'agent IA`
489 + );
490 + return JSON.stringify({ success: true, id: sharedSpaceId, newName });
491 + }
492 +
493 + case "analyze_image": {
494 + const fileId = input.fileId as string;
495 + const question = (input.question as string) || "Décris cette image en détail en français. Mentionne le sujet, le contexte, les personnes visibles, le lieu, les couleurs, et tout texte visible.";
496 + const file = await findAccessibleFile(fileId, userId);
497 + if (!file) return JSON.stringify({ error: "Fichier introuvable ou accès refusé" });
498 + if (!file.mimeType.startsWith("image/")) return JSON.stringify({ error: "Ce fichier n'est pas une image" });
499 +
500 + const supported = ["image/jpeg", "image/png", "image/gif", "image/webp"];
501 + if (!supported.includes(file.mimeType)) return JSON.stringify({ error: `Format non supporté: ${file.mimeType}. Formats supportés: JPEG, PNG, GIF, WebP` });
502 +
503 + let base64: string;
504 + try { base64 = (await loadFileData(file.storagePath, file.isEncrypted)).toString("base64"); }
505 + catch { return JSON.stringify({ error: "Fichier introuvable sur le disque" }); }
506 + const visionResponse = await anthropic.messages.create({
507 + model: MODEL,
508 + max_tokens: 1024,
509 + messages: [{
510 + role: "user",
511 + content: [
512 + { type: "image", source: { type: "base64", media_type: file.mimeType as "image/jpeg" | "image/png" | "image/gif" | "image/webp", data: base64 } },
513 + { type: "text", text: question },
514 + ],
515 + }],
516 + });
517 + const description = visionResponse.content[0].type === "text" ? visionResponse.content[0].text : "";
518 + // Save description to DB
519 + await prisma.file.update({ where: { id: fileId }, data: { aiDescription: description } });
520 + return JSON.stringify({ success: true, fileName: file.name, description });
521 + }
522 +
523 + case "read_file_content": {
524 + const fileId = input.fileId as string;
525 + const file = await findAccessibleFile(fileId, userId);
526 + if (!file) return JSON.stringify({ error: "Fichier introuvable ou accès refusé" });
527 +
528 + try {
529 + if (file.mimeType.startsWith("text/") || file.mimeType.includes("json") || file.mimeType.includes("xml") || file.mimeType.includes("javascript") || file.mimeType.includes("markdown")) {
530 + const content = (await loadFileData(file.storagePath, file.isEncrypted)).toString("utf-8").substring(0, 10000);
531 + return JSON.stringify({ success: true, fileName: file.name, content });
532 + }
533 + if (file.mimeType === "application/pdf") {
534 + // Use OCR text if available
535 + if (file.ocrText) return JSON.stringify({ success: true, fileName: file.name, content: file.ocrText });
536 + return JSON.stringify({ success: true, fileName: file.name, content: "(PDF - utilise l'onglet Analyser pour extraire le texte via OCR)" });
537 + }
538 + return JSON.stringify({ error: `Type non supporté pour la lecture directe: ${file.mimeType}` });
539 + } catch (err) {
540 + return JSON.stringify({ error: `Erreur de lecture: ${(err as Error).message}` });
541 + }
542 + }
543 +
544 + default:
545 + return JSON.stringify({ error: `Outil inconnu: ${name}` });
546 + }
547 + } catch (err) {
548 + return JSON.stringify({ error: (err as Error).message });
549 + }
550 +}
551 +
552 +// ─── Route handler ────────────────────────────────────────────────────────────
553 +
554 +export async function POST(request: NextRequest) {
555 + const tempResponse = new NextResponse();
556 + const session = await getIronSession<SessionData>(
557 + request,
558 + tempResponse,
559 + sessionOptions
560 + );
561 + if (!session.isLoggedIn)
562 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
563 +
564 + const body = await request.json();
565 + const { message, history = [] } = body;
566 + if (!message)
567 + return NextResponse.json({ error: "message required" }, { status: 400 });
568 +
569 + const userId = session.userId!;
570 + const encoder = new TextEncoder();
571 +
572 + const readable = new ReadableStream({
573 + async start(controller) {
574 + const send = (data: object) => {
575 + controller.enqueue(
576 + encoder.encode(`data: ${JSON.stringify(data)}\n\n`)
577 + );
578 + };
579 +
580 + try {
581 + const systemPrompt = `Tu es un agent IA pour SPB Cloud, le cloud personnel privé de l'utilisateur. Tu as accès à des outils pour:
582 +- Lister, créer, renommer, déplacer et supprimer des fichiers et dossiers
583 +- ANALYSER des images avec ta vision IA (analyze_image) — tu PEUX voir le contenu des photos
584 +- Lire le contenu de fichiers texte (read_file_content)
585 +
586 +Réponds toujours en français. Sois concis et confirme chaque action effectuée.
587 +Avant toute suppression, liste d'abord le fichier pour confirmer son identité.
588 +Si une tâche requiert plusieurs étapes, enchaîne tes outils de manière autonome.
589 +
590 +IMPORTANT: Tu as la capacité de VOIR les images via l'outil analyze_image. Quand l'utilisateur demande de décrire, analyser, ou renommer des photos selon leur contenu, utilise cet outil pour examiner chaque image.`;
591 +
592 + const messages: Anthropic.MessageParam[] = [
593 + ...(
594 + history as { role: "user" | "assistant"; content: string }[]
595 + ).map((m) => ({
596 + role: m.role,
597 + content: m.content,
598 + })),
599 + { role: "user" as const, content: message },
600 + ];
601 +
602 + for (let i = 0; i < MAX_ITERATIONS; i++) {
603 + const response = await anthropic.messages.create({
604 + model: MODEL,
605 + max_tokens: 4096,
606 + system: systemPrompt,
607 + tools: TOOLS,
608 + messages,
609 + });
610 +
611 + // Stream any text blocks from this iteration
612 + for (const block of response.content) {
613 + if (block.type === "text" && block.text) {
614 + send({ type: "token", token: block.text });
615 + }
616 + }
617 +
618 + if (response.stop_reason === "end_turn") break;
619 +
620 + if (response.stop_reason === "tool_use") {
621 + const toolResults: Anthropic.ToolResultBlockParam[] = [];
622 +
623 + for (const block of response.content) {
624 + if (block.type === "tool_use") {
625 + // Notify client a tool is being called
626 + send({
627 + type: "tool_call",
628 + id: block.id,
629 + name: block.name,
630 + input: block.input,
631 + });
632 +
633 + const result = await executeTool(
634 + block.name,
635 + block.input as Record<string, unknown>,
636 + userId
637 + );
638 +
639 + // Notify client of the result
640 + send({
641 + type: "tool_result",
642 + id: block.id,
643 + name: block.name,
644 + result,
645 + });
646 +
647 + toolResults.push({
648 + type: "tool_result",
649 + tool_use_id: block.id,
650 + content: result,
651 + });
652 + }
653 + }
654 +
655 + // Append assistant turn + tool results for next iteration
656 + messages.push(
657 + { role: "assistant" as const, content: response.content },
658 + { role: "user" as const, content: toolResults }
659 + );
660 + } else {
661 + // stop_reason is something else — break
662 + break;
663 + }
664 + }
665 +
666 + send({ type: "done" });
667 + } catch (err) {
668 + send({ type: "error", message: (err as Error).message });
669 + } finally {
670 + controller.close();
671 + }
672 + },
673 + });
674 +
675 + return new Response(readable, {
676 + headers: {
677 + "Content-Type": "text/event-stream",
678 + "Cache-Control": "no-cache",
679 + Connection: "keep-alive",
680 + },
681 + });
682 +}
modified app/api/ai/chat/route.ts +15 −11
@@ -2,13 +2,12 @@ import { NextRequest, NextResponse } from "next/server";
2 2 import { getIronSession } from "iron-session";
3 3 import { SessionData, sessionOptions } from "@/lib/session";
4 4 import { buildFileContext, ChatMessage } from "@/lib/ai";
5 −import { getFilePath } from "@/lib/storage";
6 −import { existsSync, readFileSync } from "fs";
5 +import { loadFileData } from "@/lib/storage";
7 6 import { prisma } from "@/lib/prisma";
8 7 import Anthropic from "@anthropic-ai/sdk";
9 8
10 9 const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
11 −const MODEL = "claude-sonnet-4-6";
10 +const MODEL = "claude-opus-4-6";
12 11
13 12 // Find a file mentioned by name in the user message
14 13 async function findMentionedFile(message: string, userId?: string) {
@@ -18,7 +17,7 @@ async function findMentionedFile(message: string, userId?: string) {
18 17
19 18 const files = await prisma.file.findMany({
20 19 where,
21 − select: { id: true, name: true, mimeType: true, storagePath: true, ocrText: true },
20 + select: { id: true, name: true, mimeType: true, storagePath: true, ocrText: true, isEncrypted: true },
22 21 orderBy: { createdAt: "desc" },
23 22 });
24 23
@@ -34,14 +33,19 @@ async function buildFileBlocks(file: {
34 33 mimeType: string;
35 34 storagePath: string;
36 35 ocrText: string | null;
36 + isEncrypted: boolean;
37 37 }): Promise<Anthropic.ContentBlockParam[]> {
38 − const filePath = getFilePath(file.storagePath);
39 − if (!existsSync(filePath)) return [];
38 + let buf: Buffer;
39 + try {
40 + buf = await loadFileData(file.storagePath, file.isEncrypted);
41 + } catch {
42 + return [];
43 + }
40 44
41 45 try {
42 46 // PDFs — send as native document block (Claude reads PDFs natively)
43 47 if (file.mimeType === "application/pdf") {
44 − const base64 = readFileSync(filePath).toString("base64");
48 + const base64 = buf.toString("base64");
45 49 return [
46 50 {
47 51 type: "document",
@@ -54,7 +58,7 @@ async function buildFileBlocks(file: {
54 58 if (file.mimeType.startsWith("image/")) {
55 59 const supported = ["image/jpeg", "image/png", "image/gif", "image/webp"];
56 60 if (supported.includes(file.mimeType)) {
57 − const base64 = readFileSync(filePath).toString("base64");
61 + const base64 = buf.toString("base64");
58 62 return [
59 63 {
60 64 type: "image",
@@ -74,7 +78,7 @@ async function buildFileBlocks(file: {
74 78 file.mimeType === "application/msword"
75 79 ) {
76 80 const mammoth = await import("mammoth");
77 − const result = await mammoth.extractRawText({ path: filePath });
81 + const result = await mammoth.extractRawText({ buffer: buf });
78 82 const text = result.value.substring(0, 50000);
79 83 if (text.trim()) {
80 84 return [{ type: "text", text: `Contenu du document Word "${file.name}":\n${text}` }];
@@ -87,7 +91,7 @@ async function buildFileBlocks(file: {
87 91 file.mimeType === "application/vnd.ms-excel"
88 92 ) {
89 93 const XLSX = await import("xlsx");
90 − const workbook = XLSX.readFile(filePath);
94 + const workbook = XLSX.read(buf, { type: "buffer" });
91 95 const parts: string[] = [];
92 96 for (const sheetName of workbook.SheetNames) {
93 97 const sheet = workbook.Sheets[sheetName];
@@ -107,7 +111,7 @@ async function buildFileBlocks(file: {
107 111 file.mimeType.includes("xml") ||
108 112 file.mimeType.includes("markdown")
109 113 ) {
110 − const content = readFileSync(filePath, "utf-8").substring(0, 50000);
114 + const content = buf.toString("utf-8").substring(0, 50000);
111 115 return [
112 116 { type: "text", text: `Contenu du fichier "${file.name}":\n\`\`\`\n${content}\n\`\`\`` },
113 117 ];
modified app/api/auth/2fa/setup/route.ts +3 −3
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
2 2 import { getIronSession } from "iron-session";
3 3 import { SessionData, sessionOptions } from "@/lib/session";
4 4 import { prisma } from "@/lib/prisma";
5 −import { authenticator } from "otplib";
5 +import { generateSecret, generateURI } from "otplib";
6 6 import QRCode from "qrcode";
7 7
8 8 export async function POST(request: NextRequest) {
@@ -10,13 +10,13 @@ export async function POST(request: NextRequest) {
10 10 const session = await getIronSession<SessionData>(request, response, sessionOptions);
11 11 if (!session.isLoggedIn || !session.userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
12 12
13 − const secret = authenticator.generateSecret();
13 + const secret = generateSecret();
14 14 const user = await prisma.user.findUnique({ where: { id: session.userId } });
15 15 if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
16 16
17 17 await prisma.user.update({ where: { id: session.userId }, data: { twoFactorSecret: secret } });
18 18
19 − const otpauth = authenticator.keyuri(user.email || user.id, "SPB Cloud", secret);
19 + const otpauth = generateURI({ label: user.email || user.id, issuer: "SPB Cloud", secret });
20 20 const qrCodeUrl = await QRCode.toDataURL(otpauth);
21 21
22 22 return NextResponse.json({ secret, qrCodeUrl });
modified app/api/auth/2fa/verify/route.ts +69 −4
@@ -2,9 +2,12 @@ import { NextRequest, NextResponse } from "next/server";
2 2 import { getIronSession } from "iron-session";
3 3 import { SessionData, sessionOptions } from "@/lib/session";
4 4 import { prisma } from "@/lib/prisma";
5 −import { authenticator } from "otplib";
5 +import { verifySync } from "otplib";
6 6 import { randomBytes } from "crypto";
7 7 import { logActivity } from "@/lib/activity";
8 +import { parseUserAgent } from "@/lib/ua-parser";
9 +import { getGeoFromIp } from "@/lib/geo";
10 +import { analyzeLogin } from "@/lib/ai-security";
8 11
9 12 export async function POST(request: NextRequest) {
10 13 const body = await request.json();
@@ -18,7 +21,8 @@ export async function POST(request: NextRequest) {
18 21 const user = await prisma.user.findUnique({ where: { id: session.userId } });
19 22 if (!user?.twoFactorSecret) return NextResponse.json({ error: "Setup 2FA first" }, { status: 400 });
20 23
21 − const valid = authenticator.verify({ token, secret: user.twoFactorSecret });
24 + const result = verifySync({ token, secret: user.twoFactorSecret });
25 + const valid = result.valid;
22 26 if (!valid) return NextResponse.json({ error: "Code invalide" }, { status: 401 });
23 27
24 28 await prisma.user.update({ where: { id: session.userId }, data: { twoFactorEnabled: true } });
@@ -33,17 +37,78 @@ export async function POST(request: NextRequest) {
33 37 const user = await prisma.user.findUnique({ where: { id: session.pendingUserId } });
34 38 if (!user?.twoFactorSecret) return NextResponse.json({ error: "2FA not configured" }, { status: 400 });
35 39
36 − const valid = authenticator.verify({ token, secret: user.twoFactorSecret });
40 + const verifyResult = verifySync({ token, secret: user.twoFactorSecret });
41 + const valid = verifyResult.valid;
37 42 if (!valid) return NextResponse.json({ error: "Code invalide" }, { status: 401 });
38 43
44 + const ip = request.headers.get("x-forwarded-for") || "127.0.0.1";
45 + const ua = request.headers.get("user-agent") || "";
46 + const parsed = parseUserAgent(ua);
47 + const geo = await getGeoFromIp(ip);
48 +
49 + // AI security analysis after successful 2FA
50 + const aiResult = await analyzeLogin({
51 + userId: user.id,
52 + ip,
53 + country: geo.country,
54 + city: geo.city,
55 + device: parsed.device,
56 + browser: parsed.browser,
57 + os: parsed.os,
58 + });
59 +
60 + if (aiResult.decision === "refuse") {
61 + await prisma.loginSession.create({
62 + data: {
63 + userId: user.id,
64 + ip,
65 + userAgent: ua,
66 + device: parsed.device,
67 + browser: parsed.browser,
68 + os: parsed.os,
69 + country: geo.country,
70 + city: geo.city,
71 + status: "refused_by_ai",
72 + aiDecision: "refused",
73 + aiReason: aiResult.reason,
74 + aiRiskLevel: aiResult.riskLevel,
75 + endedAt: new Date(),
76 + },
77 + });
78 + await logActivity("LOGIN_REFUSED_AI", null, `2FA refusé par IA depuis ${ip} (${geo.country}) — ${aiResult.reason}`);
79 + return NextResponse.json(
80 + { error: `Connexion refusée par l'agent IA de sécurité. ${aiResult.reason}` },
81 + { status: 403 }
82 + );
83 + }
84 +
85 + // Record login session
86 + const loginSession = await prisma.loginSession.create({
87 + data: {
88 + userId: user.id,
89 + ip,
90 + userAgent: ua,
91 + device: parsed.device,
92 + browser: parsed.browser,
93 + os: parsed.os,
94 + country: geo.country,
95 + city: geo.city,
96 + status: "active",
97 + aiDecision: "allowed",
98 + aiReason: aiResult.reason,
99 + aiRiskLevel: aiResult.riskLevel,
100 + },
101 + });
102 +
39 103 session.isLoggedIn = true;
40 104 session.userId = user.id;
41 105 session.userRole = user.role;
42 106 session.pendingTwoFactor = false;
43 107 session.pendingUserId = undefined;
108 + session.sessionToken = loginSession.sessionToken;
44 109 session.csrfToken = randomBytes(32).toString("hex");
45 110 await session.save();
46 111
47 − await logActivity("LOGIN", null, "Login with 2FA");
112 + await logActivity("LOGIN", null, `Login with 2FA from ${ip} (${parsed.browser} / ${parsed.os})`);
48 113 return response;
49 114 }
added app/api/auth/devices/[id]/route.ts +26 −0
@@ -0,0 +1,26 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +
6 +export async function DELETE(
7 + request: NextRequest,
8 + { params }: { params: { id: string } }
9 +) {
10 + const response = NextResponse.next();
11 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
12 + if (!session.userId) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
13 +
14 + // Ensure the session belongs to this user
15 + const loginSession = await prisma.loginSession.findFirst({
16 + where: { id: params.id, userId: session.userId },
17 + });
18 + if (!loginSession) return NextResponse.json({ error: "Introuvable" }, { status: 404 });
19 +
20 + await prisma.loginSession.update({
21 + where: { id: params.id },
22 + data: { endedAt: new Date() },
23 + });
24 +
25 + return NextResponse.json({ success: true });
26 +}
added app/api/auth/devices/route.ts +74 −0
@@ -0,0 +1,74 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +import { parseUserAgent } from "@/lib/ua-parser";
6 +import { getGeoFromIp } from "@/lib/geo";
7 +
8 +export async function GET(request: NextRequest) {
9 + // Use a mutable response so we can persist a new sessionToken if needed
10 + const sessionResponse = new NextResponse();
11 + const session = await getIronSession<SessionData>(request, sessionResponse, sessionOptions);
12 + if (!session.userId) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
13 +
14 + // Backfill: user logged in before device tracking existed — create a record now
15 + if (!session.sessionToken) {
16 + const ip = request.headers.get("x-forwarded-for") || "127.0.0.1";
17 + const ua = request.headers.get("user-agent") || "";
18 + const parsed = parseUserAgent(ua);
19 + const geo = await getGeoFromIp(ip);
20 +
21 + const loginRecord = await prisma.loginSession.create({
22 + data: {
23 + userId: session.userId,
24 + ip,
25 + userAgent: ua,
26 + device: parsed.device,
27 + browser: parsed.browser,
28 + os: parsed.os,
29 + country: geo.country,
30 + city: geo.city,
31 + },
32 + });
33 +
34 + session.sessionToken = loginRecord.sessionToken;
35 + await session.save(); // writes Set-Cookie on sessionResponse
36 + }
37 +
38 + const currentToken = session.sessionToken;
39 +
40 + const sessions = await prisma.loginSession.findMany({
41 + where: { userId: session.userId },
42 + orderBy: { createdAt: "desc" },
43 + take: 20,
44 + select: {
45 + id: true,
46 + sessionToken: true,
47 + ip: true,
48 + device: true,
49 + browser: true,
50 + os: true,
51 + country: true,
52 + city: true,
53 + status: true,
54 + aiDecision: true,
55 + aiReason: true,
56 + aiRiskLevel: true,
57 + createdAt: true,
58 + endedAt: true,
59 + },
60 + });
61 +
62 + const result = sessions.map((s) => ({
63 + ...s,
64 + isCurrent: s.sessionToken === currentToken,
65 + }));
66 +
67 + // Build the final JSON response and carry over any new Set-Cookie headers
68 + const jsonResponse = NextResponse.json(result);
69 + sessionResponse.headers.getSetCookie().forEach((cookie) => {
70 + jsonResponse.headers.append("Set-Cookie", cookie);
71 + });
72 +
73 + return jsonResponse;
74 +}
modified app/api/auth/login/route.ts +65 −1
@@ -5,6 +5,10 @@ import { verifyPassword } from "@/lib/auth";
5 5 import { checkLoginRateLimit } from "@/lib/rate-limit";
6 6 import { logActivity } from "@/lib/activity";
7 7 import { randomBytes } from "crypto";
8 +import { parseUserAgent } from "@/lib/ua-parser";
9 +import { getGeoFromIp } from "@/lib/geo";
10 +import { analyzeLogin } from "@/lib/ai-security";
11 +import { prisma } from "@/lib/prisma";
8 12
9 13 export async function POST(request: NextRequest) {
10 14 const ip = request.headers.get("x-forwarded-for") || "127.0.0.1";
@@ -21,6 +25,47 @@ export async function POST(request: NextRequest) {
21 25 const response = NextResponse.json({ success: true, requires2FA: user.twoFactorEnabled });
22 26 const session = await getIronSession<SessionData>(request, response, sessionOptions);
23 27
28 + const ua = request.headers.get("user-agent") || "";
29 + const parsed = parseUserAgent(ua);
30 + const geo = await getGeoFromIp(ip);
31 +
32 + // AI security analysis (runs in parallel with 2FA check)
33 + const aiResult = await analyzeLogin({
34 + userId: user.id,
35 + ip,
36 + country: geo.country,
37 + city: geo.city,
38 + device: parsed.device,
39 + browser: parsed.browser,
40 + os: parsed.os,
41 + });
42 +
43 + if (aiResult.decision === "refuse") {
44 + // Log the refused attempt in the DB for visibility
45 + await prisma.loginSession.create({
46 + data: {
47 + userId: user.id,
48 + ip,
49 + userAgent: ua,
50 + device: parsed.device,
51 + browser: parsed.browser,
52 + os: parsed.os,
53 + country: geo.country,
54 + city: geo.city,
55 + status: "refused_by_ai",
56 + aiDecision: "refused",
57 + aiReason: aiResult.reason,
58 + aiRiskLevel: aiResult.riskLevel,
59 + endedAt: new Date(),
60 + },
61 + });
62 + await logActivity("LOGIN_REFUSED_AI", null, `Connexion refusée par IA depuis ${ip} (${geo.country}) — ${aiResult.reason}`);
63 + return NextResponse.json(
64 + { error: `Connexion refusée par l'agent IA de sécurité. ${aiResult.reason}` },
65 + { status: 403 }
66 + );
67 + }
68 +
24 69 if (user.twoFactorEnabled) {
25 70 session.pendingTwoFactor = true;
26 71 session.pendingUserId = user.id;
@@ -28,12 +73,31 @@ export async function POST(request: NextRequest) {
28 73 return response;
29 74 }
30 75
76 + // Record login session
77 + const loginSession = await prisma.loginSession.create({
78 + data: {
79 + userId: user.id,
80 + ip,
81 + userAgent: ua,
82 + device: parsed.device,
83 + browser: parsed.browser,
84 + os: parsed.os,
85 + country: geo.country,
86 + city: geo.city,
87 + status: "active",
88 + aiDecision: "allowed",
89 + aiReason: aiResult.reason,
90 + aiRiskLevel: aiResult.riskLevel,
91 + },
92 + });
93 +
31 94 session.isLoggedIn = true;
32 95 session.userId = user.id;
33 96 session.userRole = user.role;
97 + session.sessionToken = loginSession.sessionToken;
34 98 session.csrfToken = randomBytes(32).toString("hex");
35 99 await session.save();
36 100
37 − await logActivity("LOGIN", null, `Login from ${ip}`);
101 + await logActivity("LOGIN", null, `Login from ${ip} (${parsed.browser} / ${parsed.os}) — IA: ${aiResult.riskLevel}`);
38 102 return response;
39 103 }
modified app/api/auth/logout/route.ts +9 −0
@@ -2,11 +2,20 @@ import { NextRequest, NextResponse } from "next/server";
2 2 import { getIronSession } from "iron-session";
3 3 import { SessionData, sessionOptions } from "@/lib/session";
4 4 import { logActivity } from "@/lib/activity";
5 +import { prisma } from "@/lib/prisma";
5 6
6 7 export async function POST(request: NextRequest) {
7 8 const response = NextResponse.json({ success: true });
8 9 const session = await getIronSession<SessionData>(request, response, sessionOptions);
9 10
11 + // Mark the login session as ended
12 + if (session.sessionToken) {
13 + await prisma.loginSession.updateMany({
14 + where: { sessionToken: session.sessionToken, endedAt: null },
15 + data: { endedAt: new Date() },
16 + }).catch(() => {});
17 + }
18 +
10 19 await logActivity("LOGOUT");
11 20 session.destroy();
12 21
added app/api/files/[id]/comments/[commentId]/route.ts +70 −0
@@ -0,0 +1,70 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +
6 +export async function PATCH(
7 + request: NextRequest,
8 + { params }: { params: { id: string; commentId: string } }
9 +) {
10 + const response = NextResponse.next();
11 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
12 + if (!session.isLoggedIn || !session.userId) {
13 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
14 + }
15 +
16 + const comment = await prisma.comment.findUnique({
17 + where: { id: params.commentId },
18 + });
19 + if (!comment) {
20 + return NextResponse.json({ error: "Commentaire introuvable" }, { status: 404 });
21 + }
22 + if (comment.userId !== session.userId) {
23 + return NextResponse.json({ error: "Non autorise" }, { status: 403 });
24 + }
25 +
26 + const { content } = await request.json();
27 + if (!content || !content.trim()) {
28 + return NextResponse.json({ error: "Le contenu est requis" }, { status: 400 });
29 + }
30 +
31 + const updated = await prisma.comment.update({
32 + where: { id: params.commentId },
33 + data: { content: content.trim() },
34 + include: {
35 + user: {
36 + select: { id: true, name: true, username: true, avatarPath: true },
37 + },
38 + },
39 + });
40 +
41 + return NextResponse.json(updated);
42 +}
43 +
44 +export async function DELETE(
45 + request: NextRequest,
46 + { params }: { params: { id: string; commentId: string } }
47 +) {
48 + const response = NextResponse.next();
49 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
50 + if (!session.isLoggedIn || !session.userId) {
51 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
52 + }
53 +
54 + const comment = await prisma.comment.findUnique({
55 + where: { id: params.commentId },
56 + });
57 + if (!comment) {
58 + return NextResponse.json({ error: "Commentaire introuvable" }, { status: 404 });
59 + }
60 +
61 + // Only author or admin can delete
62 + const isAuthor = comment.userId === session.userId;
63 + const isAdmin = session.userRole === "admin";
64 + if (!isAuthor && !isAdmin) {
65 + return NextResponse.json({ error: "Non autorise" }, { status: 403 });
66 + }
67 +
68 + await prisma.comment.delete({ where: { id: params.commentId } });
69 + return NextResponse.json({ success: true });
70 +}
added app/api/files/[id]/comments/route.ts +92 −0
@@ -0,0 +1,92 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +import { notifyFileComment } from "@/lib/notifications";
6 +
7 +export async function GET(
8 + request: NextRequest,
9 + { params }: { params: { id: string } }
10 +) {
11 + const response = NextResponse.next();
12 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
13 + if (!session.isLoggedIn || !session.userId) {
14 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
15 + }
16 +
17 + const comments = await prisma.comment.findMany({
18 + where: { fileId: params.id },
19 + include: {
20 + user: {
21 + select: { id: true, name: true, username: true, avatarPath: true },
22 + },
23 + },
24 + orderBy: { createdAt: "asc" },
25 + });
26 +
27 + return NextResponse.json(comments);
28 +}
29 +
30 +export async function POST(
31 + request: NextRequest,
32 + { params }: { params: { id: string } }
33 +) {
34 + const response = NextResponse.next();
35 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
36 + if (!session.isLoggedIn || !session.userId) {
37 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
38 + }
39 +
40 + const { content } = await request.json();
41 + if (!content || !content.trim()) {
42 + return NextResponse.json({ error: "Le contenu est requis" }, { status: 400 });
43 + }
44 +
45 + const file = await prisma.file.findUnique({
46 + where: { id: params.id },
47 + select: { id: true, name: true, userId: true },
48 + });
49 + if (!file) {
50 + return NextResponse.json({ error: "Fichier introuvable" }, { status: 404 });
51 + }
52 +
53 + const comment = await prisma.comment.create({
54 + data: {
55 + fileId: params.id,
56 + userId: session.userId,
57 + content: content.trim(),
58 + },
59 + include: {
60 + user: {
61 + select: { id: true, name: true, username: true, avatarPath: true },
62 + },
63 + },
64 + });
65 +
66 + // Notify other commenters + file owner
67 + const commenter = await prisma.user.findUnique({
68 + where: { id: session.userId },
69 + select: { name: true, username: true },
70 + });
71 + const commenterName = commenter?.name || commenter?.username || "Quelqu'un";
72 +
73 + // Get all unique users who commented on this file (excluding the current user)
74 + const otherCommenters = await prisma.comment.findMany({
75 + where: { fileId: params.id, userId: { not: session.userId } },
76 + select: { userId: true },
77 + distinct: ["userId"],
78 + });
79 +
80 + const usersToNotify = new Set(otherCommenters.map((c) => c.userId));
81 +
82 + // Also notify file owner if they haven't commented
83 + if (file.userId && file.userId !== session.userId) {
84 + usersToNotify.add(file.userId);
85 + }
86 +
87 + for (const userId of Array.from(usersToNotify)) {
88 + await notifyFileComment(userId, commenterName, file.name, file.id);
89 + }
90 +
91 + return NextResponse.json(comment, { status: 201 });
92 +}
modified app/api/files/[id]/content/route.ts +6 −8
@@ -1,8 +1,7 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath, saveVersion } from "@/lib/storage";
3 +import { saveVersion, saveFileFromBuffer } from "@/lib/storage";
4 4 import { logActivity } from "@/lib/activity";
5 −import { writeFile, stat } from "fs/promises";
6 5 import { MAX_VERSIONS_PER_FILE } from "@/lib/config";
7 6
8 7 export async function PUT(
@@ -16,7 +15,6 @@ export async function PUT(
16 15 }
17 16
18 17 const content = await request.text();
19 − const filePath = getFilePath(file.storagePath);
20 18
21 19 // Create version before overwriting
22 20 const versionCount = await prisma.fileVersion.count({ where: { fileId: file.id } });
@@ -46,16 +44,16 @@ export async function PUT(
46 44 }
47 45 }
48 46
49 − // Write new content
50 − await writeFile(filePath, content, "utf-8");
51 − const newStat = await stat(filePath);
47 + // Write new content (chiffré au repos)
48 + const plain = Buffer.from(content, "utf-8");
49 + await saveFileFromBuffer(plain, file.storagePath);
52 50
53 51 await prisma.file.update({
54 52 where: { id: params.id },
55 − data: { size: BigInt(newStat.size) },
53 + data: { size: BigInt(plain.length), isEncrypted: true },
56 54 });
57 55
58 56 await logActivity("EDIT", file.id, `Edited ${file.name}`);
59 57
60 − return NextResponse.json({ success: true, size: Number(newStat.size) });
58 + return NextResponse.json({ success: true, size: plain.length });
61 59 }
modified app/api/files/[id]/download/route.ts +4 −17
@@ -1,9 +1,7 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
3 +import { loadFileData } from "@/lib/storage";
4 4 import { logActivity } from "@/lib/activity";
5 −import { stat } from "fs/promises";
6 −import { createReadStream } from "fs";
7 5
8 6 export async function GET(
9 7 request: NextRequest,
@@ -15,26 +13,15 @@ export async function GET(
15 13 return NextResponse.json({ error: "File not found" }, { status: 404 });
16 14 }
17 15
18 − const filePath = getFilePath(file.storagePath);
19 − const fileStat = await stat(filePath);
20 − const fileSize = fileStat.size;
16 + const data = await loadFileData(file.storagePath, file.isEncrypted);
21 17
22 18 await logActivity("DOWNLOAD", file.id, `Downloaded ${file.name}`);
23 19
24 − const stream = createReadStream(filePath);
25 − const webStream = new ReadableStream({
26 − start(controller) {
27 − stream.on("data", (chunk) => controller.enqueue(chunk));
28 − stream.on("end", () => controller.close());
29 − stream.on("error", (err) => controller.error(err));
30 − },
31 − });
32 −
33 − return new Response(webStream, {
20 + return new NextResponse(new Uint8Array(data), {
34 21 headers: {
35 22 "Content-Type": "application/octet-stream",
36 23 "Content-Disposition": `attachment; filename="${encodeURIComponent(file.name)}"`,
37 − "Content-Length": String(fileSize),
24 + "Content-Length": String(data.length),
38 25 },
39 26 });
40 27 }
modified app/api/files/[id]/duplicate/route.ts +4 −2
@@ -13,15 +13,17 @@ export async function POST(
13 13 return NextResponse.json({ error: "File not found" }, { status: 404 });
14 14 }
15 15
16 − const { storagePath, size } = await duplicateFile(file.storagePath, file.name);
16 + const { storagePath } = await duplicateFile(file.storagePath, file.name);
17 17
18 18 const duplicated = await prisma.file.create({
19 19 data: {
20 20 name: `${file.name} (copy)`,
21 21 storagePath,
22 − size: BigInt(size),
22 + // copie octet-à-octet : même état de chiffrement ; on garde la taille en clair d'origine
23 + size: file.size,
23 24 mimeType: file.mimeType,
24 25 folderId: file.folderId,
26 + isEncrypted: file.isEncrypted,
25 27 },
26 28 });
27 29
modified app/api/files/[id]/preview/route.ts +29 −16
@@ -1,8 +1,9 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
4 −import { stat } from "fs/promises";
5 −import { createReadStream } from "fs";
3 +import { getThumbnail, loadFileData } from "@/lib/storage";
4 +
5 +// Largeurs autorisées pour les rendus redimensionnés (évite la génération arbitraire)
6 +const ALLOWED_WIDTHS = [200, 400, 800, 1280, 2048];
6 7
7 8 export async function GET(
8 9 request: NextRequest,
@@ -14,24 +15,36 @@ export async function GET(
14 15 return NextResponse.json({ error: "File not found" }, { status: 404 });
15 16 }
16 17
17 − const filePath = getFilePath(file.storagePath);
18 − const fileStat = await stat(filePath);
19 − const fileSize = fileStat.size;
18 + // --- Rendu image redimensionné (miniature / version viewer) ---
19 + const wParam = request.nextUrl.searchParams.get("w");
20 + if (wParam && file.mimeType.startsWith("image/") && file.mimeType !== "image/svg+xml") {
21 + const requested = parseInt(wParam, 10);
22 + const width =
23 + ALLOWED_WIDTHS.find((w) => w >= requested) ??
24 + ALLOWED_WIDTHS[ALLOWED_WIDTHS.length - 1];
25 + try {
26 + const webp = await getThumbnail(file.storagePath, file.id, width, file.isEncrypted);
27 + return new NextResponse(new Uint8Array(webp), {
28 + headers: {
29 + "Content-Type": "image/webp",
30 + "Content-Length": String(webp.length),
31 + // Miniatures quasi-immuables (clé = id+largeur), cache agressif navigateur
32 + "Cache-Control": "private, max-age=604800",
33 + },
34 + });
35 + } catch {
36 + // En cas d'échec sharp on retombe sur l'original ci-dessous
37 + }
38 + }
20 39
21 − const stream = createReadStream(filePath);
22 − const webStream = new ReadableStream({
23 − start(controller) {
24 − stream.on("data", (chunk) => controller.enqueue(chunk));
25 − stream.on("end", () => controller.close());
26 − stream.on("error", (err) => controller.error(err));
27 − },
28 − });
40 + // --- Fichier original (déchiffré au repos) ---
41 + const data = await loadFileData(file.storagePath, file.isEncrypted);
29 42
30 − return new Response(webStream, {
43 + return new NextResponse(new Uint8Array(data), {
31 44 headers: {
32 45 "Content-Type": file.mimeType,
33 46 "Content-Disposition": `inline; filename="${encodeURIComponent(file.name)}"`,
34 − "Content-Length": String(fileSize),
47 + "Content-Length": String(data.length),
35 48 "Cache-Control": "private, max-age=3600",
36 49 },
37 50 });
modified app/api/files/[id]/route.ts +5 −4
@@ -1,6 +1,5 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { deleteFile } from "@/lib/storage";
4 3 import { logActivity } from "@/lib/activity";
5 4
6 5 export async function GET(
@@ -60,9 +59,11 @@ export async function DELETE(
60 59 return NextResponse.json({ error: "File not found" }, { status: 404 });
61 60 }
62 61
63 − await deleteFile(file.storagePath);
64 − await prisma.file.delete({ where: { id: params.id } });
65 − await logActivity("DELETE", null, `Deleted ${file.name}`);
62 + await prisma.file.update({
63 + where: { id: params.id },
64 + data: { deletedAt: new Date() },
65 + });
66 + await logActivity("TRASH", params.id, `Moved to trash: ${file.name}`);
66 67
67 68 return NextResponse.json({ success: true });
68 69 }
modified app/api/files/[id]/save-edit/route.ts +1 −0
@@ -66,6 +66,7 @@ export async function POST(
66 66 data: {
67 67 storagePath: result.storagePath,
68 68 size: BigInt(result.size),
69 + isEncrypted: true,
69 70 },
70 71 });
71 72
modified app/api/files/[id]/stream/route.ts +8 −28
@@ -1,8 +1,6 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
4 −import { stat } from "fs/promises";
5 −import { createReadStream } from "fs";
3 +import { loadFileData } from "@/lib/storage";
6 4
7 5 export async function GET(
8 6 request: NextRequest,
@@ -14,9 +12,9 @@ export async function GET(
14 12 return NextResponse.json({ error: "File not found" }, { status: 404 });
15 13 }
16 14
17 − const filePath = getFilePath(file.storagePath);
18 − const fileStat = await stat(filePath);
19 − const fileSize = fileStat.size;
15 + // Contenu chiffré au repos → on déchiffre en mémoire puis on sert (avec support Range).
16 + const data = await loadFileData(file.storagePath, file.isEncrypted);
17 + const fileSize = data.length;
20 18
21 19 const range = request.headers.get("range");
22 20
@@ -26,39 +24,21 @@ export async function GET(
26 24 const end = parts[1]
27 25 ? parseInt(parts[1], 10)
28 26 : Math.min(start + 1024 * 1024 - 1, fileSize - 1);
29 − const chunkSize = end - start + 1;
27 + const chunk = data.subarray(start, end + 1);
30 28
31 − const stream = createReadStream(filePath, { start, end });
32 − const webStream = new ReadableStream({
33 − start(controller) {
34 − stream.on("data", (chunk) => controller.enqueue(chunk));
35 − stream.on("end", () => controller.close());
36 − stream.on("error", (err) => controller.error(err));
37 − },
38 − });
39 −
40 − return new Response(webStream, {
29 + return new NextResponse(new Uint8Array(chunk), {
41 30 status: 206,
42 31 headers: {
43 32 "Content-Range": `bytes ${start}-${end}/${fileSize}`,
44 33 "Accept-Ranges": "bytes",
45 − "Content-Length": String(chunkSize),
34 + "Content-Length": String(chunk.length),
46 35 "Content-Type": file.mimeType,
47 36 "Cache-Control": "private, max-age=3600",
48 37 },
49 38 });
50 39 }
51 40
52 − const stream = createReadStream(filePath);
53 − const webStream = new ReadableStream({
54 − start(controller) {
55 − stream.on("data", (chunk) => controller.enqueue(chunk));
56 − stream.on("end", () => controller.close());
57 − stream.on("error", (err) => controller.error(err));
58 − },
59 − });
60 −
61 − return new Response(webStream, {
41 + return new NextResponse(new Uint8Array(data), {
62 42 headers: {
63 43 "Content-Length": String(fileSize),
64 44 "Content-Type": file.mimeType,
modified app/api/files/[id]/versions/[versionId]/diff/route.ts +3 −4
@@ -1,7 +1,6 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath, getVersionPath } from "@/lib/storage";
4 −import { readFile } from "fs/promises";
3 +import { loadFileData, loadVersionData } from "@/lib/storage";
5 4
6 5 export async function GET(
7 6 request: NextRequest,
@@ -21,8 +20,8 @@ export async function GET(
21 20 return NextResponse.json({ error: "Not a text file" }, { status: 400 });
22 21 }
23 22
24 − const currentContent = await readFile(getFilePath(file.storagePath), "utf-8");
25 − const versionContent = await readFile(getVersionPath(version.storagePath), "utf-8");
23 + const currentContent = (await loadFileData(file.storagePath, file.isEncrypted)).toString("utf-8");
24 + const versionContent = (await loadVersionData(version.storagePath, file.isEncrypted)).toString("utf-8");
26 25
27 26 const Diff = await import("diff");
28 27 const patch = Diff.createPatch(
modified app/api/files/[id]/versions/[versionId]/route.ts +5 −16
@@ -1,8 +1,6 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getVersionPath } from "@/lib/storage";
4 −import { createReadStream } from "fs";
5 −import { stat } from "fs/promises";
3 +import { loadVersionData } from "@/lib/storage";
6 4
7 5 export async function GET(
8 6 request: NextRequest,
@@ -17,23 +15,14 @@ export async function GET(
17 15 return NextResponse.json({ error: "Version not found" }, { status: 404 });
18 16 }
19 17
20 − const filePath = getVersionPath(version.storagePath);
21 − const fileStat = await stat(filePath);
18 + // Les versions sont des copies du fichier (même état de chiffrement que le fichier courant)
19 + const data = await loadVersionData(version.storagePath, version.file.isEncrypted);
22 20
23 − const stream = createReadStream(filePath);
24 − const webStream = new ReadableStream({
25 − start(controller) {
26 − stream.on("data", (chunk) => controller.enqueue(chunk));
27 − stream.on("end", () => controller.close());
28 − stream.on("error", (err) => controller.error(err));
29 − },
30 − });
31 −
32 − return new Response(webStream, {
21 + return new NextResponse(new Uint8Array(data), {
33 22 headers: {
34 23 "Content-Type": "application/octet-stream",
35 24 "Content-Disposition": `attachment; filename="${encodeURIComponent(version.file.name)}"`,
36 − "Content-Length": String(fileStat.size),
25 + "Content-Length": String(data.length),
37 26 },
38 27 });
39 28 }
modified app/api/files/bulk/route.ts +11 −9
@@ -2,11 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
2 2 import { getIronSession } from "iron-session";
3 3 import { SessionData, sessionOptions } from "@/lib/session";
4 4 import { prisma } from "@/lib/prisma";
5 −import { deleteFile, getFilePath } from "@/lib/storage";
5 +import { deleteFile, loadFileData } from "@/lib/storage";
6 6 import { logActivity } from "@/lib/activity";
7 7 import { encryptFile, removeEncryption } from "@/lib/encryption";
8 8 import JSZip from "jszip";
9 −import { readFileSync, existsSync } from "fs";
10 9
11 10 export async function POST(request: NextRequest) {
12 11 const response = NextResponse.next();
@@ -20,10 +19,12 @@ export async function POST(request: NextRequest) {
20 19
21 20 if (action === "delete") {
22 21 const files = await prisma.file.findMany({ where: { id: { in: fileIds } } });
22 + await prisma.file.updateMany({
23 + where: { id: { in: fileIds } },
24 + data: { deletedAt: new Date() },
25 + });
23 26 for (const file of files) {
24 − await deleteFile(file.storagePath);
25 − await prisma.file.delete({ where: { id: file.id } });
26 − await logActivity("DELETE", file.id, `Bulk delete: ${file.name}`);
27 + await logActivity("TRASH", file.id, `Moved to trash: ${file.name}`);
27 28 }
28 29 return NextResponse.json({ success: true, count: files.length });
29 30 }
@@ -41,13 +42,14 @@ export async function POST(request: NextRequest) {
41 42 const files = await prisma.file.findMany({ where: { id: { in: fileIds } } });
42 43 const zip = new JSZip();
43 44 for (const file of files) {
44 − const filePath = getFilePath(file.storagePath);
45 − if (existsSync(filePath)) {
46 − zip.file(file.name, readFileSync(filePath));
45 + try {
46 + zip.file(file.name, await loadFileData(file.storagePath, file.isEncrypted));
47 + } catch {
48 + // fichier manquant : ignoré
47 49 }
48 50 }
49 51 const buffer = await zip.generateAsync({ type: "nodebuffer" });
50 − return new NextResponse(buffer, {
52 + return new NextResponse(new Uint8Array(buffer), {
51 53 headers: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="files.zip"` },
52 54 });
53 55 }
modified app/api/files/route.ts +25 −12
@@ -16,10 +16,13 @@ export async function GET(request: NextRequest) {
16 16 const sizeMin = searchParams.get("sizeMin");
17 17 const sizeMax = searchParams.get("sizeMax");
18 18
19 + const limitParam = parseInt(searchParams.get("limit") || "50");
20 + const offsetParam = parseInt(searchParams.get("offset") || "0");
21 +
19 22 const favorite = searchParams.get("favorite");
20 23 const tagId = searchParams.get("tagId");
21 24
22 − const where: Record<string, unknown> = {};
25 + const where: Record<string, unknown> = { deletedAt: null };
23 26
24 27 // When filtering by favorite or tag, don't filter by folder
25 28 if (favorite === "true") {
@@ -52,23 +55,32 @@ export async function GET(request: NextRequest) {
52 55 if (sizeMax) (where.size as Record<string, unknown>).lte = BigInt(sizeMax);
53 56 }
54 57
55 − const files = await prisma.file.findMany({
56 − where,
57 − orderBy: { [sortBy]: order },
58 − include: {
59 − folder: true,
60 − metadata: true,
61 − tags: { include: { tag: true } },
62 − _count: { select: { versions: true } },
63 − },
64 − });
58 + const [files, total] = await Promise.all([
59 + prisma.file.findMany({
60 + where,
61 + orderBy: { [sortBy]: order },
62 + take: limitParam,
63 + skip: offsetParam,
64 + include: {
65 + folder: true,
66 + metadata: true,
67 + tags: { include: { tag: true } },
68 + _count: { select: { versions: true } },
69 + },
70 + }),
71 + prisma.file.count({ where }),
72 + ]);
65 73
66 74 const serialized = files.map((f) => ({
67 75 ...f,
68 76 size: Number(f.size),
69 77 }));
70 78
71 − return NextResponse.json(serialized);
79 + return NextResponse.json({
80 + files: serialized,
81 + total,
82 + hasMore: offsetParam + limitParam < total,
83 + });
72 84 }
73 85
74 86 export async function POST(request: NextRequest) {
@@ -117,6 +129,7 @@ export async function POST(request: NextRequest) {
117 129 size: BigInt(size),
118 130 mimeType,
119 131 folderId: folderId && folderId !== "root" ? folderId : null,
132 + isEncrypted: true,
120 133 },
121 134 });
122 135
modified app/api/files/upload-chunk/route.ts +1 −0
@@ -32,6 +32,7 @@ export async function POST(request: NextRequest) {
32 32 size: BigInt(size),
33 33 mimeType,
34 34 folderId: folderId && folderId !== "root" ? folderId : null,
35 + isEncrypted: true,
35 36 },
36 37 });
37 38
modified app/api/folders/[id]/download/route.ts +9 −6
@@ -1,14 +1,17 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
3 +import { loadFileData } from "@/lib/storage";
4 4 import JSZip from "jszip";
5 −import { readFileSync, existsSync } from "fs";
6 5
7 6 async function addFolderToZip(zip: JSZip, folderId: string, prefix: string) {
8 − const files = await prisma.file.findMany({ where: { folderId } });
7 + const files = await prisma.file.findMany({ where: { folderId, deletedAt: null } });
9 8 for (const file of files) {
10 − const filePath = getFilePath(file.storagePath);
11 − if (existsSync(filePath)) zip.file(prefix + file.name, readFileSync(filePath));
9 + try {
10 + const data = await loadFileData(file.storagePath, file.isEncrypted);
11 + zip.file(prefix + file.name, data); // déchiffré dans l'archive
12 + } catch {
13 + // fichier manquant/illisible : ignoré
14 + }
12 15 }
13 16 const subfolders = await prisma.folder.findMany({ where: { parentId: folderId } });
14 17 for (const sub of subfolders) {
@@ -24,7 +27,7 @@ export async function GET(_request: NextRequest, { params }: { params: { id: str
24 27 await addFolderToZip(zip, folder.id, "");
25 28 const buffer = await zip.generateAsync({ type: "nodebuffer" });
26 29
27 − return new NextResponse(buffer, {
30 + return new NextResponse(new Uint8Array(buffer), {
28 31 headers: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="${folder.name}.zip"` },
29 32 });
30 33 }
modified app/api/folders/[id]/route.ts +48 −4
@@ -34,15 +34,59 @@ export async function PATCH(
34 34 { params }: { params: { id: string } }
35 35 ) {
36 36 const body = await request.json();
37 − const { name } = body;
37 + const { name, parentId } = body;
38 38
39 − if (!name || !name.trim()) {
40 − return NextResponse.json({ error: "Name required" }, { status: 400 });
39 + const data: Record<string, unknown> = {};
40 +
41 + if (name !== undefined) {
42 + if (!name || !name.trim()) {
43 + return NextResponse.json({ error: "Name required" }, { status: 400 });
44 + }
45 + data.name = name.trim();
46 + }
47 +
48 + // Déplacement de dossier (avec protection anti-cycle)
49 + if (parentId !== undefined) {
50 + const target = parentId === "root" || parentId === null ? null : parentId;
51 + if (target === params.id) {
52 + return NextResponse.json(
53 + { error: "Impossible de déplacer un dossier dans lui-même" },
54 + { status: 400 }
55 + );
56 + }
57 + if (target) {
58 + // Remonte la chaîne des parents : si on retombe sur le dossier déplacé,
59 + // c'est qu'on tenterait de le mettre dans un de ses descendants.
60 + let cur: string | null = target;
61 + const visited = new Set<string>();
62 + while (cur) {
63 + if (cur === params.id) {
64 + return NextResponse.json(
65 + { error: "Impossible de déplacer un dossier dans son propre sous-dossier" },
66 + { status: 400 }
67 + );
68 + }
69 + if (visited.has(cur)) break;
70 + visited.add(cur);
71 + const p: { parentId: string | null } | null =
72 + await prisma.folder.findUnique({
73 + where: { id: cur },
74 + select: { parentId: true },
75 + });
76 + cur = p?.parentId ?? null;
77 + }
78 + }
79 + data.parentId = target;
80 + await logActivity("MOVE_FOLDER", null, `Moved folder ${params.id} -> ${parentId}`);
81 + }
82 +
83 + if (Object.keys(data).length === 0) {
84 + return NextResponse.json({ error: "Rien à mettre à jour" }, { status: 400 });
41 85 }
42 86
43 87 const folder = await prisma.folder.update({
44 88 where: { id: params.id },
45 − data: { name: name.trim() },
89 + data,
46 90 });
47 91
48 92 return NextResponse.json(folder);
added app/api/graph/route.ts +187 −0
@@ -0,0 +1,187 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +
6 +interface GraphNode {
7 + id: string;
8 + label: string;
9 + type: "root" | "folder" | "file" | "shared-space" | "user" | "tag";
10 + size?: number;
11 + mimeType?: string;
12 + count?: number;
13 + color?: string;
14 +}
15 +
16 +interface GraphEdge {
17 + source: string;
18 + target: string;
19 + type: "contains" | "member" | "tagged";
20 +}
21 +
22 +export async function GET(request: NextRequest) {
23 + const response = NextResponse.json({});
24 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
25 +
26 + if (!session.isLoggedIn || !session.userId) {
27 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
28 + }
29 +
30 + const nodes: GraphNode[] = [];
31 + const edges: GraphEdge[] = [];
32 +
33 + // Root node
34 + nodes.push({
35 + id: "root",
36 + label: "SPB Cloud",
37 + type: "root",
38 + });
39 +
40 + // Folders
41 + const folders = await prisma.folder.findMany({
42 + include: {
43 + _count: { select: { files: true, children: true } },
44 + },
45 + });
46 +
47 + for (const folder of folders) {
48 + nodes.push({
49 + id: `folder-${folder.id}`,
50 + label: folder.name,
51 + type: "folder",
52 + count: folder._count.files + folder._count.children,
53 + });
54 +
55 + if (folder.parentId) {
56 + edges.push({
57 + source: `folder-${folder.parentId}`,
58 + target: `folder-${folder.id}`,
59 + type: "contains",
60 + });
61 + } else if (folder.sharedSpaceId) {
62 + edges.push({
63 + source: `space-${folder.sharedSpaceId}`,
64 + target: `folder-${folder.id}`,
65 + type: "contains",
66 + });
67 + } else {
68 + edges.push({
69 + source: "root",
70 + target: `folder-${folder.id}`,
71 + type: "contains",
72 + });
73 + }
74 + }
75 +
76 + // Files (500 most recent, non-deleted)
77 + const files = await prisma.file.findMany({
78 + where: { deletedAt: null },
79 + orderBy: { createdAt: "desc" },
80 + take: 500,
81 + select: {
82 + id: true,
83 + name: true,
84 + size: true,
85 + mimeType: true,
86 + folderId: true,
87 + createdAt: true,
88 + },
89 + });
90 +
91 + for (const file of files) {
92 + nodes.push({
93 + id: `file-${file.id}`,
94 + label: file.name,
95 + type: "file",
96 + size: Number(file.size),
97 + mimeType: file.mimeType,
98 + });
99 +
100 + if (file.folderId) {
101 + edges.push({
102 + source: `folder-${file.folderId}`,
103 + target: `file-${file.id}`,
104 + type: "contains",
105 + });
106 + } else {
107 + edges.push({
108 + source: "root",
109 + target: `file-${file.id}`,
110 + type: "contains",
111 + });
112 + }
113 + }
114 +
115 + // Shared Spaces
116 + const sharedSpaces = await prisma.sharedSpace.findMany({
117 + include: {
118 + _count: { select: { members: true, folders: true } },
119 + },
120 + });
121 +
122 + for (const space of sharedSpaces) {
123 + nodes.push({
124 + id: `space-${space.id}`,
125 + label: space.name,
126 + type: "shared-space",
127 + count: space._count.members,
128 + });
129 + edges.push({
130 + source: "root",
131 + target: `space-${space.id}`,
132 + type: "contains",
133 + });
134 + }
135 +
136 + // Users
137 + const users = await prisma.user.findMany({
138 + select: { id: true, name: true, username: true },
139 + });
140 +
141 + for (const user of users) {
142 + nodes.push({
143 + id: `user-${user.id}`,
144 + label: user.name || user.username || "Utilisateur",
145 + type: "user",
146 + });
147 + }
148 +
149 + // Shared space memberships
150 + const memberships = await prisma.sharedSpaceMember.findMany();
151 + for (const m of memberships) {
152 + edges.push({
153 + source: `user-${m.userId}`,
154 + target: `space-${m.sharedSpaceId}`,
155 + type: "member",
156 + });
157 + }
158 +
159 + // Tags
160 + const tags = await prisma.tag.findMany({
161 + include: { files: { select: { fileId: true } } },
162 + });
163 +
164 + const fileNodeIds = new Set(nodes.filter((n) => n.type === "file").map((n) => n.id));
165 +
166 + for (const tag of tags) {
167 + nodes.push({
168 + id: `tag-${tag.id}`,
169 + label: tag.name,
170 + type: "tag",
171 + color: tag.color,
172 + count: tag.files.length,
173 + });
174 +
175 + for (const ft of tag.files) {
176 + if (fileNodeIds.has(`file-${ft.fileId}`)) {
177 + edges.push({
178 + source: `tag-${tag.id}`,
179 + target: `file-${ft.fileId}`,
180 + type: "tagged",
181 + });
182 + }
183 + }
184 + }
185 +
186 + return NextResponse.json({ nodes, edges });
187 +}
modified app/api/shared/[token]/route.ts +31 −17
@@ -1,7 +1,6 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
4 −import { readFile } from "fs/promises";
3 +import { loadFileData } from "@/lib/storage";
5 4
6 5 export async function GET(
7 6 request: NextRequest,
@@ -13,11 +12,11 @@ export async function GET(
13 12 });
14 13
15 14 if (!share || !share.active) {
16 − return NextResponse.json({ error: "Link not found or inactive" }, { status: 404 });
15 + return NextResponse.json({ error: "Lien introuvable ou inactif" }, { status: 404 });
17 16 }
18 17
19 18 if (share.expiresAt && new Date() > share.expiresAt) {
20 − return NextResponse.json({ error: "Link expired" }, { status: 410 });
19 + return NextResponse.json({ error: "Ce lien a expire" }, { status: 410 });
21 20 }
22 21
23 22 if (share.passwordHash) {
@@ -31,12 +30,27 @@ export async function GET(
31 30
32 31 const { searchParams } = new URL(request.url);
33 32 const action = searchParams.get("action");
33 + const content = searchParams.get("content");
34 34
35 − if (action === "download" || share.mode === "DOWNLOAD") {
36 − const filePath = getFilePath(share.file.storagePath);
37 − const buffer = await readFile(filePath);
35 + // Serve actual file content (binary) when ?content=true
36 + if (content === "true") {
37 + const buffer = await loadFileData(share.file.storagePath, share.file.isEncrypted);
38 38
39 − return new NextResponse(buffer, {
39 + const isDownload = action === "download" || share.mode === "DOWNLOAD";
40 +
41 + return new NextResponse(new Uint8Array(buffer), {
42 + headers: {
43 + "Content-Type": isDownload ? "application/octet-stream" : share.file.mimeType,
44 + "Content-Disposition": `${isDownload ? "attachment" : "inline"}; filename="${encodeURIComponent(share.file.name)}"`,
45 + },
46 + });
47 + }
48 +
49 + // Force download
50 + if (action === "download") {
51 + const buffer = await loadFileData(share.file.storagePath, share.file.isEncrypted);
52 +
53 + return new NextResponse(new Uint8Array(buffer), {
40 54 headers: {
41 55 "Content-Type": "application/octet-stream",
42 56 "Content-Disposition": `attachment; filename="${encodeURIComponent(share.file.name)}"`,
@@ -44,14 +58,14 @@ export async function GET(
44 58 });
45 59 }
46 60
47 − // Preview mode
48 − const filePath = getFilePath(share.file.storagePath);
49 − const buffer = await readFile(filePath);
50 −
51 − return new NextResponse(buffer, {
52 − headers: {
53 − "Content-Type": share.file.mimeType,
54 − "Content-Disposition": `inline; filename="${encodeURIComponent(share.file.name)}"`,
55 − },
61 + // DOWNLOAD mode: return JSON info (client will show download-only UI)
62 + // PREVIEW mode: return JSON info (client will render rich preview)
63 + return NextResponse.json({
64 + id: share.file.id,
65 + name: share.file.name,
66 + mimeType: share.file.mimeType,
67 + size: Number(share.file.size),
68 + mode: share.mode,
69 + expiresAt: share.expiresAt?.toISOString() || null,
56 70 });
57 71 }
modified app/api/shared/[token]/verify/route.ts +23 −10
@@ -1,7 +1,6 @@
1 1 import { NextRequest, NextResponse } from "next/server";
2 2 import { prisma } from "@/lib/prisma";
3 −import { getFilePath } from "@/lib/storage";
4 −import { readFile } from "fs/promises";
3 +import { loadFileData } from "@/lib/storage";
5 4 import bcrypt from "bcryptjs";
6 5
7 6 export async function POST(
@@ -9,7 +8,7 @@ export async function POST(
9 8 { params }: { params: { token: string } }
10 9 ) {
11 10 const body = await request.json();
12 − const { password } = body;
11 + const { password, contentOnly } = body;
13 12
14 13 const share = await prisma.sharedLink.findUnique({
15 14 where: { token: params.token },
@@ -17,28 +16,42 @@ export async function POST(
17 16 });
18 17
19 18 if (!share || !share.active) {
20 − return NextResponse.json({ error: "Link not found" }, { status: 404 });
19 + return NextResponse.json({ error: "Lien introuvable" }, { status: 404 });
21 20 }
22 21
23 22 if (share.expiresAt && new Date() > share.expiresAt) {
24 − return NextResponse.json({ error: "Link expired" }, { status: 410 });
23 + return NextResponse.json({ error: "Ce lien a expire" }, { status: 410 });
25 24 }
26 25
27 26 if (!share.passwordHash) {
28 − return NextResponse.json({ error: "No password required" }, { status: 400 });
27 + return NextResponse.json({ error: "Aucun mot de passe requis" }, { status: 400 });
29 28 }
30 29
31 30 const valid = await bcrypt.compare(password, share.passwordHash);
32 31 if (!valid) {
33 − return NextResponse.json({ error: "Wrong password" }, { status: 401 });
32 + return NextResponse.json({ error: "Mot de passe incorrect" }, { status: 401 });
34 33 }
35 34
36 − const filePath = getFilePath(share.file.storagePath);
37 − const buffer = await readFile(filePath);
35 + // If only verifying password and requesting file info (for preview mode)
36 + if (!contentOnly) {
37 + // Return file info JSON so the client can render the rich preview
38 + return NextResponse.json({
39 + verified: true,
40 + id: share.file.id,
41 + name: share.file.name,
42 + mimeType: share.file.mimeType,
43 + size: Number(share.file.size),
44 + mode: share.mode,
45 + expiresAt: share.expiresAt?.toISOString() || null,
46 + });
47 + }
48 +
49 + // Serve actual binary content after password verification
50 + const buffer = await loadFileData(share.file.storagePath, share.file.isEncrypted);
38 51
39 52 const isDownload = share.mode === "DOWNLOAD";
40 53
41 − return new NextResponse(buffer, {
54 + return new NextResponse(new Uint8Array(buffer), {
42 55 headers: {
43 56 "Content-Type": isDownload ? "application/octet-stream" : share.file.mimeType,
44 57 "Content-Disposition": `${isDownload ? "attachment" : "inline"}; filename="${encodeURIComponent(share.file.name)}"`,
added app/api/trash/route.ts +81 −0
@@ -0,0 +1,81 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { prisma } from "@/lib/prisma";
3 +import { deleteFile } from "@/lib/storage";
4 +import { logActivity } from "@/lib/activity";
5 +
6 +export async function GET() {
7 + const files = await prisma.file.findMany({
8 + where: { deletedAt: { not: null } },
9 + orderBy: { deletedAt: "desc" },
10 + include: {
11 + metadata: true,
12 + tags: { include: { tag: true } },
13 + user: { select: { id: true, name: true, username: true } },
14 + },
15 + });
16 +
17 + const serialized = files.map((f) => ({
18 + ...f,
19 + size: Number(f.size),
20 + }));
21 +
22 + return NextResponse.json(serialized);
23 +}
24 +
25 +export async function POST(request: NextRequest) {
26 + const body = await request.json();
27 + const { action, fileIds } = body as {
28 + action: "restore" | "purge" | "empty";
29 + fileIds?: string[];
30 + };
31 +
32 + if (!action) {
33 + return NextResponse.json({ error: "action required" }, { status: 400 });
34 + }
35 +
36 + // Restore files — set deletedAt back to null
37 + if (action === "restore") {
38 + if (!fileIds?.length) {
39 + return NextResponse.json({ error: "fileIds required" }, { status: 400 });
40 + }
41 + await prisma.file.updateMany({
42 + where: { id: { in: fileIds }, deletedAt: { not: null } },
43 + data: { deletedAt: null },
44 + });
45 + for (const id of fileIds) {
46 + await logActivity("RESTORE", id, "Restored from trash");
47 + }
48 + return NextResponse.json({ success: true, count: fileIds.length });
49 + }
50 +
51 + // Purge specific files — permanent delete from storage + DB
52 + if (action === "purge") {
53 + if (!fileIds?.length) {
54 + return NextResponse.json({ error: "fileIds required" }, { status: 400 });
55 + }
56 + const files = await prisma.file.findMany({
57 + where: { id: { in: fileIds }, deletedAt: { not: null } },
58 + });
59 + for (const file of files) {
60 + await deleteFile(file.storagePath);
61 + await logActivity("PURGE", null, `Permanently deleted: ${file.name}`);
62 + await prisma.file.delete({ where: { id: file.id } });
63 + }
64 + return NextResponse.json({ success: true, count: files.length });
65 + }
66 +
67 + // Empty entire trash
68 + if (action === "empty") {
69 + const files = await prisma.file.findMany({
70 + where: { deletedAt: { not: null } },
71 + });
72 + for (const file of files) {
73 + await deleteFile(file.storagePath);
74 + await prisma.file.delete({ where: { id: file.id } });
75 + }
76 + await logActivity("PURGE", null, `Emptied trash (${files.length} files)`);
77 + return NextResponse.json({ success: true, count: files.length });
78 + }
79 +
80 + return NextResponse.json({ error: "Unknown action" }, { status: 400 });
81 +}
added app/api/users/[id]/avatar/route.ts +36 −0
@@ -0,0 +1,36 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { prisma } from "@/lib/prisma";
3 +import { existsSync, readFileSync } from "fs";
4 +import path from "path";
5 +import mime from "mime-types";
6 +
7 +const AVATARS_DIR = path.join(process.env.UPLOAD_DIR || "./uploads", "avatars");
8 +
9 +export async function GET(
10 + _request: NextRequest,
11 + { params }: { params: { id: string } }
12 +) {
13 + const user = await prisma.user.findUnique({
14 + where: { id: params.id },
15 + select: { avatarPath: true },
16 + });
17 +
18 + if (!user || !user.avatarPath) {
19 + return NextResponse.json({ error: "Avatar introuvable" }, { status: 404 });
20 + }
21 +
22 + const fullPath = path.join(AVATARS_DIR, user.avatarPath);
23 + if (!existsSync(fullPath)) {
24 + return NextResponse.json({ error: "Fichier avatar introuvable" }, { status: 404 });
25 + }
26 +
27 + const buffer = readFileSync(fullPath);
28 + const mimeType = mime.lookup(user.avatarPath) || "image/png";
29 +
30 + return new NextResponse(buffer, {
31 + headers: {
32 + "Content-Type": mimeType,
33 + "Cache-Control": "public, max-age=3600",
34 + },
35 + });
36 +}
added app/api/users/profile/route.ts +100 −0
@@ -0,0 +1,100 @@
1 +import { NextRequest, NextResponse } from "next/server";
2 +import { getIronSession } from "iron-session";
3 +import { SessionData, sessionOptions } from "@/lib/session";
4 +import { prisma } from "@/lib/prisma";
5 +import { existsSync, mkdirSync, writeFileSync } from "fs";
6 +import path from "path";
7 +import { v4 as uuidv4 } from "uuid";
8 +
9 +const AVATARS_DIR = path.join(process.env.UPLOAD_DIR || "./uploads", "avatars");
10 +if (!existsSync(AVATARS_DIR)) mkdirSync(AVATARS_DIR, { recursive: true });
11 +
12 +export async function GET(request: NextRequest) {
13 + const response = NextResponse.next();
14 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
15 + if (!session.isLoggedIn || !session.userId) {
16 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
17 + }
18 +
19 + const user = await prisma.user.findUnique({
20 + where: { id: session.userId },
21 + select: {
22 + id: true,
23 + username: true,
24 + email: true,
25 + name: true,
26 + avatarPath: true,
27 + role: true,
28 + createdAt: true,
29 + },
30 + });
31 +
32 + if (!user) {
33 + return NextResponse.json({ error: "Utilisateur introuvable" }, { status: 404 });
34 + }
35 +
36 + return NextResponse.json(user);
37 +}
38 +
39 +export async function PATCH(request: NextRequest) {
40 + const response = NextResponse.next();
41 + const session = await getIronSession<SessionData>(request, response, sessionOptions);
42 + if (!session.isLoggedIn || !session.userId) {
43 + return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
44 + }
45 +
46 + const contentType = request.headers.get("content-type") || "";
47 +
48 + if (contentType.includes("multipart/form-data")) {
49 + const formData = await request.formData();
50 + const name = formData.get("name") as string | null;
51 + const avatarFile = formData.get("avatar") as File | null;
52 +
53 + const data: Record<string, string> = {};
54 + if (name !== null && name !== undefined) data.name = name;
55 +
56 + if (avatarFile && avatarFile.size > 0) {
57 + const ext = path.extname(avatarFile.name) || ".png";
58 + const avatarFilename = `${uuidv4()}${ext}`;
59 + const avatarFullPath = path.join(AVATARS_DIR, avatarFilename);
60 + const buffer = Buffer.from(await avatarFile.arrayBuffer());
61 + writeFileSync(avatarFullPath, buffer);
62 + data.avatarPath = avatarFilename;
63 + }
64 +
65 + const user = await prisma.user.update({
66 + where: { id: session.userId },
67 + data,
68 + select: {
69 + id: true,
70 + username: true,
71 + email: true,
72 + name: true,
73 + avatarPath: true,
74 + role: true,
75 + },
76 + });
77 +
78 + return NextResponse.json(user);
79 + }
80 +
81 + // JSON body fallback
82 + const body = await request.json();
83 + const data: Record<string, string> = {};
84 + if (body.name !== undefined) data.name = body.name;
85 +
86 + const user = await prisma.user.update({
87 + where: { id: session.userId },
88 + data,
89 + select: {
90 + id: true,
91 + username: true,
92 + email: true,
93 + name: true,
94 + avatarPath: true,
95 + role: true,
96 + },
97 + });
98 +
99 + return NextResponse.json(user);
100 +}
modified app/dashboard/favorites/page.tsx +4 −1
@@ -16,7 +16,10 @@ export default function FavoritesPage() {
16 16 setLoading(true);
17 17 try {
18 18 const res = await fetch("/api/files?favorite=true");
19 − if (res.ok) setFiles(await res.json());
19 + if (res.ok) {
20 + const data = await res.json();
21 + setFiles(Array.isArray(data) ? data : data.files || []);
22 + }
20 23 } catch {}
21 24 setLoading(false);
22 25 }, []);
added app/dashboard/files/page.tsx +16 −0
@@ -0,0 +1,16 @@
1 +"use client";
2 +
3 +import AppShell from "@/components/layout/AppShell";
4 +import FileExplorer from "@/components/files/FileExplorer";
5 +import Breadcrumb from "@/components/layout/Breadcrumb";
6 +
7 +export default function FilesPage() {
8 + return (
9 + <AppShell>
10 + <div className="px-4 lg:px-6 pt-4">
11 + <Breadcrumb items={[]} />
12 + </div>
13 + <FileExplorer />
14 + </AppShell>
15 + );
16 +}
added app/dashboard/graph/page.tsx +886 −0
@@ -0,0 +1,886 @@
1 +"use client";
2 +
3 +import { useEffect, useRef, useState, useCallback } from "react";
4 +import { useRouter } from "next/navigation";
5 +import AppShell from "@/components/layout/AppShell";
6 +import { motion, AnimatePresence } from "framer-motion";
7 +import {
8 + ZoomIn,
9 + ZoomOut,
10 + Maximize,
11 + Tag,
12 + X,
13 + FolderOpen,
14 + File,
15 + Users,
16 + User,
17 + Search,
18 + Eye,
19 + EyeOff,
20 + ExternalLink,
21 +} from "lucide-react";
22 +
23 +// ---------- Types ----------
24 +
25 +interface GraphNode {
26 + id: string;
27 + label: string;
28 + type: "root" | "folder" | "file" | "shared-space" | "user" | "tag";
29 + size?: number;
30 + mimeType?: string;
31 + count?: number;
32 + color?: string;
33 +}
34 +
35 +interface GraphEdge {
36 + source: string;
37 + target: string;
38 + type: "contains" | "member" | "tagged";
39 +}
40 +
41 +interface SimNode extends GraphNode {
42 + x: number;
43 + y: number;
44 + vx: number;
45 + vy: number;
46 + radius: number;
47 + pinned: boolean;
48 +}
49 +
50 +// ---------- Constants ----------
51 +
52 +const NODE_COLORS: Record<string, string> = {
53 + root: "#a855f7",
54 + folder: "#f59e0b",
55 + "shared-space": "#3b82f6",
56 + user: "#22c55e",
57 + tag: "#6b7280",
58 +};
59 +
60 +const MIME_COLORS: Record<string, string> = {
61 + image: "#10b981",
62 + video: "#a855f7",
63 + audio: "#ec4899",
64 + pdf: "#ef4444",
65 + code: "#f59e0b",
66 + text: "#6b7280",
67 + spreadsheet: "#22c55e",
68 + document: "#3b82f6",
69 + archive: "#78716c",
70 + default: "#6b7280",
71 +};
72 +
73 +function getMimeCategory(mime?: string): string {
74 + if (!mime) return "default";
75 + if (mime.startsWith("image/")) return "image";
76 + if (mime.startsWith("video/")) return "video";
77 + if (mime.startsWith("audio/")) return "audio";
78 + if (mime === "application/pdf") return "pdf";
79 + if (
80 + mime.includes("javascript") ||
81 + mime.includes("typescript") ||
82 + mime.includes("json") ||
83 + mime.includes("xml") ||
84 + mime.includes("html") ||
85 + mime.includes("css") ||
86 + mime.includes("python") ||
87 + mime.includes("java") ||
88 + mime.includes("c-src")
89 + )
90 + return "code";
91 + if (mime.includes("spreadsheet") || mime.includes("csv") || mime.includes("excel"))
92 + return "spreadsheet";
93 + if (mime.includes("document") || mime.includes("word") || mime.includes("rtf"))
94 + return "document";
95 + if (mime.includes("zip") || mime.includes("tar") || mime.includes("rar") || mime.includes("7z"))
96 + return "archive";
97 + if (mime.startsWith("text/")) return "text";
98 + return "default";
99 +}
100 +
101 +function getNodeColor(node: GraphNode): string {
102 + if (node.type === "file") return MIME_COLORS[getMimeCategory(node.mimeType)] || MIME_COLORS.default;
103 + if (node.type === "tag" && node.color) return node.color;
104 + return NODE_COLORS[node.type] || "#6b7280";
105 +}
106 +
107 +function getNodeRadius(node: GraphNode): number {
108 + switch (node.type) {
109 + case "root":
110 + return 28;
111 + case "folder":
112 + return 12 + Math.min((node.count || 0) * 0.5, 10);
113 + case "shared-space":
114 + return 16;
115 + case "user":
116 + return 12;
117 + case "tag":
118 + return 8 + Math.min((node.count || 0) * 0.3, 6);
119 + case "file": {
120 + const s = node.size || 0;
121 + if (s > 100_000_000) return 8;
122 + if (s > 10_000_000) return 6;
123 + return 4;
124 + }
125 + default:
126 + return 6;
127 + }
128 +}
129 +
130 +function formatSize(bytes?: number): string {
131 + if (!bytes) return "0 o";
132 + if (bytes < 1024) return `${bytes} o`;
133 + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} Ko`;
134 + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} Mo`;
135 + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} Go`;
136 +}
137 +
138 +// ---------- Component ----------
139 +
140 +export default function GraphPage() {
141 + const canvasRef = useRef<HTMLCanvasElement>(null);
142 + const containerRef = useRef<HTMLDivElement>(null);
143 + const animFrameRef = useRef<number>(0);
144 + const nodesRef = useRef<SimNode[]>([]);
145 + const edgesRef = useRef<GraphEdge[]>([]);
146 + const edgeMapRef = useRef<Map<string, string[]>>(new Map());
147 + // Use refs for render state to avoid re-creating the animation loop
148 + const showLabelsRef = useRef(true);
149 + const filtersRef = useRef({ files: true, folders: true, tags: true, spaces: true, users: true });
150 + const searchQueryRef = useRef("");
151 + const hoveredNodeRef = useRef<SimNode | null>(null);
152 + const selectedNodeRef = useRef<SimNode | null>(null);
153 + const cameraRef = useRef({ x: 0, y: 0, zoom: 1 });
154 + const iterationRef = useRef(0);
155 +
156 + const [loading, setLoading] = useState(true);
157 + const [selectedNode, setSelectedNode] = useState<SimNode | null>(null);
158 + const [showLabels, setShowLabels] = useState(true);
159 + const [searchQuery, setSearchQuery] = useState("");
160 + const [filters, setFilters] = useState({ files: true, folders: true, tags: true, spaces: true, users: true });
161 + const [stats, setStats] = useState({ files: 0, folders: 0, spaces: 0 });
162 +
163 + // Sync React state to refs
164 + useEffect(() => { showLabelsRef.current = showLabels; }, [showLabels]);
165 + useEffect(() => { filtersRef.current = filters; }, [filters]);
166 + useEffect(() => { searchQueryRef.current = searchQuery; }, [searchQuery]);
167 + useEffect(() => { selectedNodeRef.current = selectedNode; }, [selectedNode]);
168 +
169 + const dragRef = useRef<{
170 + node: SimNode | null;
171 + panning: boolean;
172 + startX: number;
173 + startY: number;
174 + startCamX: number;
175 + startCamY: number;
176 + }>({ node: null, panning: false, startX: 0, startY: 0, startCamX: 0, startCamY: 0 });
177 +
178 + const router = useRouter();
179 +
180 + // Node index for fast edge lookups
181 + const nodeIndexRef = useRef<Map<string, SimNode>>(new Map());
182 +
183 + const buildEdgeMap = useCallback((edges: GraphEdge[]) => {
184 + const map = new Map<string, string[]>();
185 + for (const e of edges) {
186 + if (!map.has(e.source)) map.set(e.source, []);
187 + if (!map.has(e.target)) map.set(e.target, []);
188 + map.get(e.source)!.push(e.target);
189 + map.get(e.target)!.push(e.source);
190 + }
191 + edgeMapRef.current = map;
192 + }, []);
193 +
194 + // Fetch data
195 + useEffect(() => {
196 + fetch("/api/graph")
197 + .then((r) => r.json())
198 + .then((data: { nodes: GraphNode[]; edges: GraphEdge[] }) => {
199 + const simNodes: SimNode[] = data.nodes.map((n, i) => {
200 + const angle = (i / data.nodes.length) * Math.PI * 2;
201 + const dist = n.type === "root" ? 0 : 100 + Math.random() * 300;
202 + return {
203 + ...n,
204 + x: Math.cos(angle) * dist,
205 + y: Math.sin(angle) * dist,
206 + vx: 0,
207 + vy: 0,
208 + radius: getNodeRadius(n),
209 + pinned: n.type === "root",
210 + };
211 + });
212 + nodesRef.current = simNodes;
213 + edgesRef.current = data.edges;
214 + // Build node index
215 + const idx = new Map<string, SimNode>();
216 + for (const n of simNodes) idx.set(n.id, n);
217 + nodeIndexRef.current = idx;
218 + buildEdgeMap(data.edges);
219 + setStats({
220 + files: data.nodes.filter((n) => n.type === "file").length,
221 + folders: data.nodes.filter((n) => n.type === "folder").length,
222 + spaces: data.nodes.filter((n) => n.type === "shared-space").length,
223 + });
224 + iterationRef.current = 0;
225 + setLoading(false);
226 + })
227 + .catch(() => setLoading(false));
228 + }, [buildEdgeMap]);
229 +
230 + // Visibility check using refs
231 + const isVisibleRef = useCallback((node: SimNode) => {
232 + if (node.type === "root") return true;
233 + const f = filtersRef.current;
234 + if (node.type === "file" && !f.files) return false;
235 + if (node.type === "folder" && !f.folders) return false;
236 + if (node.type === "tag" && !f.tags) return false;
237 + if (node.type === "shared-space" && !f.spaces) return false;
238 + if (node.type === "user" && !f.users) return false;
239 + return true;
240 + }, []);
241 +
242 + // Screen to world coordinate conversion
243 + const screenToWorld = useCallback((clientX: number, clientY: number) => {
244 + const canvas = canvasRef.current;
245 + if (!canvas) return { x: 0, y: 0 };
246 + const rect = canvas.getBoundingClientRect();
247 + const sx = clientX - rect.left;
248 + const sy = clientY - rect.top;
249 + const cam = cameraRef.current;
250 + const cw = rect.width;
251 + const ch = rect.height;
252 + return {
253 + x: (sx - cw / 2) / cam.zoom - cam.x,
254 + y: (sy - ch / 2) / cam.zoom - cam.y,
255 + };
256 + }, []);
257 +
258 + const findNodeAt = useCallback(
259 + (wx: number, wy: number) => {
260 + const nodes = nodesRef.current;
261 + for (let i = nodes.length - 1; i >= 0; i--) {
262 + const n = nodes[i];
263 + if (!isVisibleRef(n)) continue;
264 + const dx = n.x - wx;
265 + const dy = n.y - wy;
266 + if (dx * dx + dy * dy <= (n.radius + 6) * (n.radius + 6)) return n;
267 + }
268 + return null;
269 + },
270 + [isVisibleRef]
271 + );
272 +
273 + // ---------- Main animation loop (created ONCE) ----------
274 + useEffect(() => {
275 + if (loading) return;
276 +
277 + const canvas = canvasRef.current;
278 + if (!canvas) return;
279 +
280 + const resize = () => {
281 + const container = containerRef.current;
282 + if (!container || !canvas) return;
283 + const dpr = window.devicePixelRatio || 1;
284 + canvas.width = container.clientWidth * dpr;
285 + canvas.height = container.clientHeight * dpr;
286 + canvas.style.width = `${container.clientWidth}px`;
287 + canvas.style.height = `${container.clientHeight}px`;
288 + };
289 + resize();
290 + window.addEventListener("resize", resize);
291 +
292 + const DAMPING = 0.9;
293 + const MAX_ITER = 600;
294 + const nodeIdx = nodeIndexRef.current;
295 +
296 + const tick = () => {
297 + const nodes = nodesRef.current;
298 + const edges = edgesRef.current;
299 + const cam = cameraRef.current;
300 + const ctx = canvas.getContext("2d");
301 + if (!ctx) { animFrameRef.current = requestAnimationFrame(tick); return; }
302 +
303 + // Physics
304 + if (iterationRef.current < MAX_ITER) {
305 + iterationRef.current++;
306 + const alpha = Math.max(0, 1 - iterationRef.current / MAX_ITER);
307 + const strength = alpha * 0.4;
308 +
309 + // Repulsion (only between visible nodes, use spatial optimization for large graphs)
310 + const visibleNodes = nodes.filter(isVisibleRef);
311 + for (let i = 0; i < visibleNodes.length; i++) {
312 + const ni = visibleNodes[i];
313 + for (let j = i + 1; j < visibleNodes.length; j++) {
314 + const nj = visibleNodes[j];
315 + let dx = nj.x - ni.x;
316 + let dy = nj.y - ni.y;
317 + let dist = Math.sqrt(dx * dx + dy * dy);
318 + if (dist < 1) { dx = Math.random() - 0.5; dy = Math.random() - 0.5; dist = 1; }
319 + const minDist = ni.radius + nj.radius + 30;
320 + if (dist > minDist * 4) continue; // skip far away nodes
321 + const force = (strength * 600) / (dist * dist);
322 + const fx = (dx / dist) * force;
323 + const fy = (dy / dist) * force;
324 + if (!ni.pinned) { ni.vx -= fx; ni.vy -= fy; }
325 + if (!nj.pinned) { nj.vx += fx; nj.vy += fy; }
326 + }
327 + }
328 +
329 + // Spring (edges) - use node index for O(1) lookup
330 + for (const e of edges) {
331 + const si = nodeIdx.get(e.source);
332 + const ti = nodeIdx.get(e.target);
333 + if (!si || !ti || !isVisibleRef(si) || !isVisibleRef(ti)) continue;
334 + const dx = ti.x - si.x;
335 + const dy = ti.y - si.y;
336 + const dist = Math.sqrt(dx * dx + dy * dy) || 1;
337 + const idealLen = 60 + si.radius + ti.radius;
338 + const force = strength * 0.06 * (dist - idealLen);
339 + const fx = (dx / dist) * force;
340 + const fy = (dy / dist) * force;
341 + if (!si.pinned) { si.vx += fx; si.vy += fy; }
342 + if (!ti.pinned) { ti.vx -= fx; ti.vy -= fy; }
343 + }
344 +
345 + // Gravity toward center
346 + for (const n of visibleNodes) {
347 + if (n.pinned) continue;
348 + n.vx -= n.x * strength * 0.003;
349 + n.vy -= n.y * strength * 0.003;
350 + }
351 +
352 + // Apply velocities with clamping
353 + for (const n of nodes) {
354 + if (n.pinned) continue;
355 + n.vx *= DAMPING;
356 + n.vy *= DAMPING;
357 + // Clamp velocity to prevent nodes flying off
358 + const maxV = 10;
359 + n.vx = Math.max(-maxV, Math.min(maxV, n.vx));
360 + n.vy = Math.max(-maxV, Math.min(maxV, n.vy));
361 + n.x += n.vx;
362 + n.y += n.vy;
363 + // Clamp position to prevent NaN/Infinity
364 + if (!isFinite(n.x)) n.x = 0;
365 + if (!isFinite(n.y)) n.y = 0;
366 + }
367 + }
368 +
369 + // ---------- Render ----------
370 + const dpr = window.devicePixelRatio || 1;
371 + const cw = canvas.width / dpr;
372 + const ch = canvas.height / dpr;
373 + ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
374 + ctx.clearRect(0, 0, canvas.width, canvas.height);
375 +
376 + ctx.save();
377 + ctx.translate(cw / 2, ch / 2);
378 + ctx.scale(cam.zoom, cam.zoom);
379 + ctx.translate(cam.x, cam.y);
380 +
381 + const hNode = hoveredNodeRef.current || selectedNodeRef.current;
382 + const connectedIds = hNode ? new Set(edgeMapRef.current.get(hNode.id) || []) : null;
383 +
384 + // Viewport bounds for culling
385 + const margin = 60;
386 + const vpLeft = -cw / 2 / cam.zoom - cam.x - margin;
387 + const vpRight = cw / 2 / cam.zoom - cam.x + margin;
388 + const vpTop = -ch / 2 / cam.zoom - cam.y - margin;
389 + const vpBottom = ch / 2 / cam.zoom - cam.y + margin;
390 + const inVP = (x: number, y: number) => x >= vpLeft && x <= vpRight && y >= vpTop && y <= vpBottom;
391 +
392 + const sq = searchQueryRef.current.toLowerCase();
393 +
394 + // Edges
395 + ctx.lineWidth = 0.5;
396 + for (const e of edges) {
397 + const sn = nodeIdx.get(e.source);
398 + const tn = nodeIdx.get(e.target);
399 + if (!sn || !tn || !isVisibleRef(sn) || !isVisibleRef(tn)) continue;
400 + if (!inVP(sn.x, sn.y) && !inVP(tn.x, tn.y)) continue;
401 +
402 + const isConn = hNode && (e.source === hNode.id || e.target === hNode.id);
403 + const dimmed = hNode && !isConn;
404 +
405 + ctx.beginPath();
406 + const mx = (sn.x + tn.x) / 2;
407 + const my = (sn.y + tn.y) / 2;
408 + const edx = tn.x - sn.x;
409 + const edy = tn.y - sn.y;
410 + ctx.moveTo(sn.x, sn.y);
411 + ctx.quadraticCurveTo(mx - edy * 0.04, my + edx * 0.04, tn.x, tn.y);
412 + ctx.strokeStyle = dimmed
413 + ? "rgba(255,255,255,0.02)"
414 + : isConn
415 + ? "rgba(255,255,255,0.4)"
416 + : e.type === "tagged"
417 + ? "rgba(168,85,247,0.1)"
418 + : e.type === "member"
419 + ? "rgba(34,197,94,0.1)"
420 + : "rgba(255,255,255,0.06)";
421 + ctx.lineWidth = isConn ? 1.5 : 0.5;
422 + ctx.stroke();
423 + }
424 +
425 + // Nodes
426 + for (const n of nodes) {
427 + if (!isVisibleRef(n)) continue;
428 + if (!inVP(n.x, n.y)) continue;
429 +
430 + const color = getNodeColor(n);
431 + const isHl = sq && n.label.toLowerCase().includes(sq);
432 + const isConn = connectedIds?.has(n.id);
433 + const isSel = selectedNodeRef.current?.id === n.id;
434 + const isHov = hoveredNodeRef.current?.id === n.id;
435 + const dimmed = hNode && !isConn && hNode.id !== n.id;
436 +
437 + ctx.globalAlpha = dimmed ? 0.12 : 1;
438 +
439 + // Glow for search/selection
440 + if (isHl || isSel) {
441 + ctx.beginPath();
442 + ctx.arc(n.x, n.y, n.radius + 6, 0, Math.PI * 2);
443 + ctx.fillStyle = isHl ? "rgba(250,204,21,0.3)" : "rgba(168,85,247,0.3)";
444 + ctx.fill();
445 + }
446 +
447 + // Node circle
448 + ctx.beginPath();
449 + ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
450 + ctx.fillStyle = color;
451 + ctx.fill();
452 +
453 + // Hover/select ring
454 + if (isHov || isSel) {
455 + ctx.strokeStyle = "#fff";
456 + ctx.lineWidth = 2;
457 + ctx.stroke();
458 + }
459 +
460 + // Text inside node
461 + ctx.fillStyle = "#fff";
462 + ctx.textAlign = "center";
463 + ctx.textBaseline = "middle";
464 + if (n.type === "root") {
465 + ctx.font = `bold ${n.radius * 0.55}px Inter, system-ui, sans-serif`;
466 + ctx.fillText("SPB", n.x, n.y);
467 + } else if (n.type === "user") {
468 + ctx.font = `bold ${n.radius * 0.7}px Inter, system-ui, sans-serif`;
469 + const initials = n.label.split(" ").map((w) => w[0]).join("").toUpperCase().slice(0, 2);
470 + ctx.fillText(initials, n.x, n.y);
471 + }
472 +
473 + // Label below node
474 + if (showLabelsRef.current && cam.zoom > 0.35 && n.radius * cam.zoom > 2.5) {
475 + const maxLen = n.type === "file" ? 14 : 20;
476 + const label = n.label.length > maxLen ? n.label.slice(0, maxLen - 1) + "\u2026" : n.label;
477 + const fontSize = Math.max(8, Math.min(11, n.radius * 0.75));
478 + ctx.font = `${fontSize}px Inter, system-ui, sans-serif`;
479 + ctx.fillStyle = dimmed ? "rgba(255,255,255,0.08)" : "rgba(255,255,255,0.7)";
480 + ctx.fillText(label, n.x, n.y + n.radius + 10);
481 + }
482 +
483 + ctx.globalAlpha = 1;
484 + }
485 +
486 + ctx.restore();
487 +
488 + // Tooltip (in screen space)
489 + const hn = hoveredNodeRef.current;
490 + if (hn && !dragRef.current.node) {
491 + const sx = (hn.x + cam.x) * cam.zoom + cw / 2;
492 + const sy = (hn.y + cam.y) * cam.zoom + ch / 2;
493 +
494 + ctx.save();
495 + ctx.font = "12px Inter, system-ui, sans-serif";
496 + const text = hn.label;
497 + const tw = ctx.measureText(text).width + 16;
498 + const tx = Math.min(sx + 14, cw - tw - 8);
499 + const ty = Math.max(sy - 30, 8);
500 +
501 + ctx.fillStyle = "rgba(23,23,23,0.95)";
502 + ctx.beginPath();
503 + // roundRect fallback
504 + const r = 6;
505 + ctx.moveTo(tx + r, ty);
506 + ctx.lineTo(tx + tw - r, ty);
507 + ctx.arcTo(tx + tw, ty, tx + tw, ty + r, r);
508 + ctx.lineTo(tx + tw, ty + 28 - r);
509 + ctx.arcTo(tx + tw, ty + 28, tx + tw - r, ty + 28, r);
510 + ctx.lineTo(tx + r, ty + 28);
511 + ctx.arcTo(tx, ty + 28, tx, ty + 28 - r, r);
512 + ctx.lineTo(tx, ty + r);
513 + ctx.arcTo(tx, ty, tx + r, ty, r);
514 + ctx.fill();
515 + ctx.fillStyle = "#fff";
516 + ctx.textAlign = "left";
517 + ctx.textBaseline = "middle";
518 + ctx.fillText(text, tx + 8, ty + 14);
519 + ctx.restore();
520 + }
521 +
522 + animFrameRef.current = requestAnimationFrame(tick);
523 + };
524 +
525 + animFrameRef.current = requestAnimationFrame(tick);
526 +
527 + return () => {
528 + cancelAnimationFrame(animFrameRef.current);
529 + window.removeEventListener("resize", resize);
530 + };
531 + // Only depends on loading and isVisibleRef - NOT on hoveredNode/selectedNode/showLabels/searchQuery
532 + }, [loading, isVisibleRef]);
533 +
534 + // ---------- Mouse / Touch handlers ----------
535 + useEffect(() => {
536 + const canvas = canvasRef.current;
537 + if (!canvas) return;
538 +
539 + const onPointerDown = (e: PointerEvent) => {
540 + const wp = screenToWorld(e.clientX, e.clientY);
541 + const node = findNodeAt(wp.x, wp.y);
542 +
543 + if (node) {
544 + dragRef.current = {
545 + node,
546 + panning: false,
547 + startX: e.clientX,
548 + startY: e.clientY,
549 + startCamX: 0,
550 + startCamY: 0,
551 + };
552 + node.pinned = true;
553 + // Reset iteration so physics re-settles
554 + iterationRef.current = Math.min(iterationRef.current, 400);
555 + selectedNodeRef.current = node;
556 + setSelectedNode(node);
557 + } else {
558 + const cam = cameraRef.current;
559 + dragRef.current = {
560 + node: null,
561 + panning: true,
562 + startX: e.clientX,
563 + startY: e.clientY,
564 + startCamX: cam.x,
565 + startCamY: cam.y,
566 + };
567 + }
568 + canvas.setPointerCapture(e.pointerId);
569 + };
570 +
571 + const onPointerMove = (e: PointerEvent) => {
572 + const d = dragRef.current;
573 + if (d.node) {
574 + const wp = screenToWorld(e.clientX, e.clientY);
575 + d.node.x = wp.x;
576 + d.node.y = wp.y;
577 + d.node.vx = 0;
578 + d.node.vy = 0;
579 + } else if (d.panning) {
580 + const cam = cameraRef.current;
581 + cam.x = d.startCamX + (e.clientX - d.startX) / cam.zoom;
582 + cam.y = d.startCamY + (e.clientY - d.startY) / cam.zoom;
583 + } else {
584 + const wp = screenToWorld(e.clientX, e.clientY);
585 + const node = findNodeAt(wp.x, wp.y);
586 + hoveredNodeRef.current = node;
587 + canvas.style.cursor = node ? "pointer" : "grab";
588 + }
589 + };
590 +
591 + const onPointerUp = (e: PointerEvent) => {
592 + const d = dragRef.current;
593 + if (d.node && d.node.type !== "root") {
594 + d.node.pinned = false;
595 + }
596 + dragRef.current = { node: null, panning: false, startX: 0, startY: 0, startCamX: 0, startCamY: 0 };
597 + canvas.releasePointerCapture(e.pointerId);
598 + };
599 +
600 + const onWheel = (e: WheelEvent) => {
601 + e.preventDefault();
602 + const cam = cameraRef.current;
603 + const factor = e.deltaY > 0 ? 0.92 : 1.08;
604 + cam.zoom = Math.max(0.1, Math.min(5, cam.zoom * factor));
605 + };
606 +
607 + const onDblClick = (e: MouseEvent) => {
608 + const wp = screenToWorld(e.clientX, e.clientY);
609 + const node = findNodeAt(wp.x, wp.y);
610 + if (node) {
611 + if (node.type === "folder") {
612 + router.push(`/dashboard/folder/${node.id.replace("folder-", "")}`);
613 + } else if (node.type === "shared-space") {
614 + router.push(`/dashboard/shared-space/${node.id.replace("space-", "")}`);
615 + }
616 + }
617 + };
618 +
619 + canvas.addEventListener("pointerdown", onPointerDown);
620 + canvas.addEventListener("pointermove", onPointerMove);
621 + canvas.addEventListener("pointerup", onPointerUp);
622 + canvas.addEventListener("wheel", onWheel, { passive: false });
623 + canvas.addEventListener("dblclick", onDblClick);
624 +
625 + return () => {
626 + canvas.removeEventListener("pointerdown", onPointerDown);
627 + canvas.removeEventListener("pointermove", onPointerMove);
628 + canvas.removeEventListener("pointerup", onPointerUp);
629 + canvas.removeEventListener("wheel", onWheel);
630 + canvas.removeEventListener("dblclick", onDblClick);
631 + };
632 + }, [screenToWorld, findNodeAt, router]);
633 +
634 + // ---------- Controls ----------
635 + const zoomIn = () => { cameraRef.current.zoom = Math.min(5, cameraRef.current.zoom * 1.3); };
636 + const zoomOut = () => { cameraRef.current.zoom = Math.max(0.1, cameraRef.current.zoom / 1.3); };
637 + const recenter = () => { cameraRef.current = { x: 0, y: 0, zoom: 1 }; };
638 +
639 + const navigateToNode = (node: SimNode) => {
640 + if (node.type === "folder") router.push(`/dashboard/folder/${node.id.replace("folder-", "")}`);
641 + else if (node.type === "shared-space") router.push(`/dashboard/shared-space/${node.id.replace("space-", "")}`);
642 + else if (node.type === "file") router.push(`/dashboard/files?preview=${node.id.replace("file-", "")}`);
643 + };
644 +
645 + const toggleFilter = (key: keyof typeof filters) => {
646 + setFilters((f) => ({ ...f, [key]: !f[key] }));
647 + // Reset physics so nodes re-settle
648 + iterationRef.current = Math.min(iterationRef.current, 300);
649 + };
650 +
651 + return (
652 + <AppShell>
653 + <div className="relative h-full w-full overflow-hidden bg-[#0a0a0a]" ref={containerRef}>
654 + {/* Loading */}
655 + <AnimatePresence>
656 + {loading && (
657 + <motion.div
658 + initial={{ opacity: 1 }}
659 + exit={{ opacity: 0 }}
660 + className="absolute inset-0 z-50 flex items-center justify-center bg-[#0a0a0a]"
661 + >
662 + <div className="flex flex-col items-center gap-3">
663 + <div className="w-10 h-10 border-2 border-blue-700/30 border-t-purple-500 rounded-full animate-spin" />
664 + <span className="text-sm text-gray-400">Chargement du graphe...</span>
665 + </div>
666 + </motion.div>
667 + )}
668 + </AnimatePresence>
669 +
670 + {/* Canvas */}
671 + <canvas ref={canvasRef} className="absolute inset-0 w-full h-full touch-none" />
672 +
673 + {/* Top Controls */}
674 + {!loading && (
675 + <div className="absolute top-3 left-3 right-3 z-10 flex flex-wrap items-start gap-2">
676 + {/* Stats */}
677 + <div className="flex items-center gap-2 px-3 py-2 bg-black/60 backdrop-blur-xl border border-white/10 rounded-xl text-xs text-gray-400 shrink-0">
678 + <File className="w-3.5 h-3.5" />
679 + <span>{stats.files} fichiers</span>
680 + <span className="text-white/20">|</span>
681 + <FolderOpen className="w-3.5 h-3.5" />
682 + <span>{stats.folders} dossiers</span>
683 + <span className="text-white/20">|</span>
684 + <Users className="w-3.5 h-3.5" />
685 + <span>{stats.spaces} espaces</span>
686 + </div>
687 +
688 + {/* Search */}
689 + <div className="relative flex-1 min-w-[140px] max-w-xs">
690 + <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />
691 + <input
692 + type="text"
693 + value={searchQuery}
694 + onChange={(e) => setSearchQuery(e.target.value)}
695 + placeholder="Rechercher..."
696 + className="w-full pl-8 pr-3 py-2 bg-black/60 backdrop-blur-xl border border-white/10 rounded-xl text-xs text-white placeholder-gray-500 outline-none focus:border-blue-700/50 transition-colors"
697 + />
698 + </div>
699 +
700 + {/* Filters */}
701 + <div className="hidden sm:flex items-center gap-1">
702 + {([
703 + ["files", "Fichiers", File],
704 + ["folders", "Dossiers", FolderOpen],
705 + ["tags", "Tags", Tag],
706 + ["spaces", "Espaces", Users],
707 + ["users", "Users", User],
708 + ] as const).map(([key, label, Icon]) => (
709 + <button
710 + key={key}
711 + onClick={() => toggleFilter(key)}
712 + className={`flex items-center gap-1.5 px-2.5 py-2 rounded-xl text-xs border transition-colors ${
713 + filters[key]
714 + ? "bg-white/10 border-white/20 text-white"
715 + : "bg-black/40 border-white/5 text-gray-600"
716 + }`}
717 + >
718 + <Icon className="w-3 h-3" />
719 + <span className="hidden md:inline">{label}</span>
720 + </button>
721 + ))}
722 + </div>
723 + </div>
724 + )}
725 +
726 + {/* Zoom Controls */}
727 + {!loading && (
728 + <div className="absolute bottom-4 left-4 z-10 flex flex-col gap-1">
729 + {[
730 + { icon: ZoomIn, action: zoomIn },
731 + { icon: ZoomOut, action: zoomOut },
732 + { icon: Maximize, action: recenter },
733 + ].map(({ icon: Icon, action }, i) => (
734 + <button
735 + key={i}
736 + onClick={action}
737 + className="w-9 h-9 flex items-center justify-center bg-black/60 backdrop-blur-xl border border-white/10 rounded-xl text-gray-400 hover:text-white hover:bg-white/10 transition-colors"
738 + >
739 + <Icon className="w-4 h-4" />
740 + </button>
741 + ))}
742 + <button
743 + onClick={() => setShowLabels(!showLabels)}
744 + className="w-9 h-9 flex items-center justify-center bg-black/60 backdrop-blur-xl border border-white/10 rounded-xl text-gray-400 hover:text-white hover:bg-white/10 transition-colors"
745 + >
746 + {showLabels ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
747 + </button>
748 + </div>
749 + )}
750 +
751 + {/* Info Panel */}
752 + <AnimatePresence>
753 + {selectedNode && (
754 + <>
755 + {/* Mobile: bottom sheet */}
756 + <motion.div
757 + initial={{ y: "100%" }}
758 + animate={{ y: 0 }}
759 + exit={{ y: "100%" }}
760 + transition={{ type: "spring", damping: 25, stiffness: 300 }}
761 + className="lg:hidden absolute bottom-0 left-0 right-0 z-20 bg-[#111]/95 backdrop-blur-xl border-t border-white/10 rounded-t-2xl p-4 pb-safe max-h-[50vh] overflow-auto"
762 + >
763 + <InfoPanelContent node={selectedNode} onClose={() => setSelectedNode(null)} onNavigate={navigateToNode} />
764 + </motion.div>
765 + {/* Desktop: right panel */}
766 + <motion.div
767 + initial={{ x: "100%", opacity: 0 }}
768 + animate={{ x: 0, opacity: 1 }}
769 + exit={{ x: "100%", opacity: 0 }}
770 + transition={{ type: "spring", damping: 25, stiffness: 300 }}
771 + className="hidden lg:block absolute top-3 right-3 bottom-3 w-72 z-20 bg-[#111]/90 backdrop-blur-xl border border-white/10 rounded-2xl p-4 overflow-auto"
772 + >
773 + <InfoPanelContent node={selectedNode} onClose={() => setSelectedNode(null)} onNavigate={navigateToNode} />
774 + </motion.div>
775 + </>
776 + )}
777 + </AnimatePresence>
778 +
779 + {/* Legend */}
780 + {!loading && (
781 + <div className="absolute bottom-4 right-4 z-10 hidden sm:flex flex-col gap-1 px-3 py-2.5 bg-black/60 backdrop-blur-xl border border-white/10 rounded-xl">
782 + {[
783 + ["Dossiers", NODE_COLORS.folder],
784 + ["Fichiers", MIME_COLORS.default],
785 + ["Espaces", NODE_COLORS["shared-space"]],
786 + ["Users", NODE_COLORS.user],
787 + ["Tags", NODE_COLORS.tag],
788 + ].map(([label, color]) => (
789 + <div key={label} className="flex items-center gap-2 text-xs text-gray-500">
790 + <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: color }} />
791 + {label}
792 + </div>
793 + ))}
794 + </div>
795 + )}
796 + </div>
797 + </AppShell>
798 + );
799 +}
800 +
801 +// ---------- Info Panel ----------
802 +
803 +function InfoPanelContent({
804 + node,
805 + onClose,
806 + onNavigate,
807 +}: {
808 + node: SimNode;
809 + onClose: () => void;
810 + onNavigate: (n: SimNode) => void;
811 +}) {
812 + const typeLabels: Record<string, string> = {
813 + root: "Racine",
814 + folder: "Dossier",
815 + file: "Fichier",
816 + "shared-space": "Espace partage",
817 + user: "Utilisateur",
818 + tag: "Tag",
819 + };
820 +
821 + const typeIcons: Record<string, React.ReactNode> = {
822 + root: <div className="w-8 h-8 rounded-full bg-blue-800 flex items-center justify-center text-white text-xs font-bold">SPB</div>,
823 + folder: <FolderOpen className="w-5 h-5 text-amber-400" />,
824 + file: <File className="w-5 h-5 text-gray-400" />,
825 + "shared-space": <Users className="w-5 h-5 text-blue-400" />,
826 + user: <User className="w-5 h-5 text-green-400" />,
827 + tag: <Tag className="w-5 h-5" style={{ color: node.color || "#6b7280" }} />,
828 + };
829 +
830 + return (
831 + <div className="space-y-4">
832 + <div className="flex items-start justify-between">
833 + <div className="flex items-center gap-3">
834 + {typeIcons[node.type]}
835 + <div>
836 + <p className="text-white font-medium text-sm leading-tight">{node.label}</p>
837 + <p className="text-gray-500 text-xs mt-0.5">{typeLabels[node.type]}</p>
838 + </div>
839 + </div>
840 + <button onClick={onClose} className="p-1.5 text-gray-500 hover:text-white transition-colors rounded-lg hover:bg-white/10">
841 + <X className="w-4 h-4" />
842 + </button>
843 + </div>
844 +
845 + <div className="space-y-2 text-xs">
846 + {node.type === "file" && (
847 + <>
848 + <InfoRow label="Taille" value={formatSize(node.size)} />
849 + <InfoRow label="Type" value={node.mimeType || "Inconnu"} />
850 + <InfoRow label="Categorie" value={getMimeCategory(node.mimeType)} />
851 + </>
852 + )}
853 + {node.type === "folder" && <InfoRow label="Elements" value={`${node.count || 0} elements`} />}
854 + {node.type === "shared-space" && <InfoRow label="Membres" value={`${node.count || 0} membres`} />}
855 + {node.type === "tag" && (
856 + <>
857 + <InfoRow label="Fichiers" value={`${node.count || 0} fichiers`} />
858 + <div className="flex items-center gap-2 text-gray-400">
859 + <span>Couleur</span>
860 + <span className="w-4 h-4 rounded-full border border-white/20" style={{ backgroundColor: node.color || "#6b7280" }} />
861 + </div>
862 + </>
863 + )}
864 + </div>
865 +
866 + {node.type !== "root" && node.type !== "user" && (
867 + <button
868 + onClick={() => onNavigate(node)}
869 + className="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-blue-700/20 text-blue-300 hover:bg-blue-700/30 rounded-xl text-sm font-medium transition-colors"
870 + >
871 + <ExternalLink className="w-3.5 h-3.5" />
872 + Ouvrir
873 + </button>
874 + )}
875 + </div>
876 + );
877 +}
878 +
879 +function InfoRow({ label, value }: { label: string; value: string }) {
880 + return (
881 + <div className="flex items-center justify-between text-gray-400">
882 + <span>{label}</span>
883 + <span className="text-gray-300 text-right max-w-[60%] truncate">{value}</span>
884 + </div>
885 + );
886 +}
modified app/dashboard/page.tsx +2 −2
@@ -1,12 +1,12 @@
1 1 "use client";
2 2
3 3 import AppShell from "@/components/layout/AppShell";
4 −import FileExplorer from "@/components/files/FileExplorer";
4 +import DashboardHome from "@/components/dashboard/DashboardHome";
5 5
6 6 export default function DashboardPage() {
7 7 return (
8 8 <AppShell>
9 − <FileExplorer />
9 + <DashboardHome />
10 10 </AppShell>
11 11 );
12 12 }
added app/dashboard/recent/page.tsx +178 −0
@@ -0,0 +1,178 @@
1 +"use client";
2 +
3 +import { useState, useEffect, useCallback } from "react";
4 +import { Clock } from "lucide-react";
5 +import { motion, AnimatePresence } from "framer-motion";
6 +import AppShell from "@/components/layout/AppShell";
7 +import FileCard from "@/components/files/FileCard";
8 +import PreviewEngine from "@/components/preview/PreviewEngine";
9 +import type { FileData } from "@/types/files";
10 +
11 +function getDateGroup(dateStr: string): string {
12 + const date = new Date(dateStr);
13 + const now = new Date();
14 + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
15 + const yesterday = new Date(today);
16 + yesterday.setDate(yesterday.getDate() - 1);
17 + const weekAgo = new Date(today);
18 + weekAgo.setDate(weekAgo.getDate() - 7);
19 + const monthAgo = new Date(today);
20 + monthAgo.setMonth(monthAgo.getMonth() - 1);
21 +
22 + if (date >= today) return "Aujourd'hui";
23 + if (date >= yesterday) return "Hier";
24 + if (date >= weekAgo) return "Cette semaine";
25 + if (date >= monthAgo) return "Ce mois";
26 + return "Plus ancien";
27 +}
28 +
29 +const groupOrder = ["Aujourd'hui", "Hier", "Cette semaine", "Ce mois", "Plus ancien"];
30 +
31 +export default function RecentPage() {
32 + const [files, setFiles] = useState<FileData[]>([]);
33 + const [previewFile, setPreviewFile] = useState<FileData | null>(null);
34 + const [loading, setLoading] = useState(true);
35 + const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
36 +
37 + const fetchRecent = useCallback(async () => {
38 + setLoading(true);
39 + try {
40 + const res = await fetch("/api/files?sortBy=updatedAt&order=desc&limit=50");
41 + if (res.ok) {
42 + const data = await res.json();
43 + setFiles(Array.isArray(data) ? data : data.files || []);
44 + }
45 + } catch {}
46 + setLoading(false);
47 + }, []);
48 +
49 + useEffect(() => {
50 + fetchRecent();
51 + }, [fetchRecent]);
52 +
53 + // Group files by date category
54 + const grouped = files.reduce<Record<string, FileData[]>>((acc, file) => {
55 + const group = getDateGroup(file.updatedAt || file.createdAt);
56 + if (!acc[group]) acc[group] = [];
57 + acc[group].push(file);
58 + return acc;
59 + }, {});
60 +
61 + return (
62 + <AppShell>
63 + <div className="flex flex-col h-full lg:flex-row">
64 + <div className="flex-1 flex flex-col min-w-0">
65 + {/* Header */}
66 + <div className="px-3 sm:px-4 lg:px-6 py-3 sm:py-4 border-b border-gray-200 dark:border-white/10 flex items-center justify-between">
67 + <div>
68 + <h1 className="text-lg font-medium text-gray-900 dark:text-white flex items-center gap-2">
69 + <Clock className="w-5 h-5 text-blue-500" />
70 + Fichiers recents
71 + </h1>
72 + <p className="text-xs text-gray-500 mt-1">
73 + {files.length} fichier{files.length !== 1 ? "s" : ""}
74 + </p>
75 + </div>
76 + <div className="flex items-center gap-1">
77 + <button
78 + onClick={() => setViewMode("grid")}
79 + className={`p-2 rounded-lg transition-colors ${
80 + viewMode === "grid"
81 + ? "bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-white"
82 + : "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
83 + }`}
84 + >
85 + <svg className="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">
86 + <rect x="1" y="1" width="6" height="6" rx="1" />
87 + <rect x="9" y="1" width="6" height="6" rx="1" />
88 + <rect x="1" y="9" width="6" height="6" rx="1" />
89 + <rect x="9" y="9" width="6" height="6" rx="1" />
90 + </svg>
91 + </button>
92 + <button
93 + onClick={() => setViewMode("list")}
94 + className={`p-2 rounded-lg transition-colors ${
95 + viewMode === "list"
96 + ? "bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-white"
97 + : "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
98 + }`}
99 + >
100 + <svg className="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">
101 + <rect x="1" y="2" width="14" height="2" rx="0.5" />
102 + <rect x="1" y="7" width="14" height="2" rx="0.5" />
103 + <rect x="1" y="12" width="14" height="2" rx="0.5" />
104 + </svg>
105 + </button>
106 + </div>
107 + </div>
108 +
109 + {/* Content */}
110 + <div className="flex-1 overflow-auto px-3 sm:px-4 lg:px-6 py-3 sm:py-4">
111 + {loading ? (
112 + <div className="flex items-center justify-center h-32">
113 + <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
114 + </div>
115 + ) : files.length === 0 ? (
116 + <div className="flex flex-col items-center justify-center h-64 text-gray-500">
117 + <Clock className="w-12 h-12 mb-4 text-gray-300 dark:text-gray-600" />
118 + <p className="text-lg">Aucun fichier recent</p>
119 + <p className="text-sm mt-1 text-center px-4">
120 + Vos fichiers recemment modifies apparaitront ici
121 + </p>
122 + </div>
123 + ) : (
124 + <div className="space-y-6">
125 + <AnimatePresence>
126 + {groupOrder.map((groupName) => {
127 + const groupFiles = grouped[groupName];
128 + if (!groupFiles || groupFiles.length === 0) return null;
129 + return (
130 + <motion.div
131 + key={groupName}
132 + initial={{ opacity: 0, y: 8 }}
133 + animate={{ opacity: 1, y: 0 }}
134 + transition={{ duration: 0.2 }}
135 + >
136 + <h2 className="text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-3">
137 + {groupName}
138 + </h2>
139 + <div
140 + className={
141 + viewMode === "grid"
142 + ? "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2 sm:gap-3"
143 + : "space-y-1"
144 + }
145 + >
146 + {groupFiles.map((file) => (
147 + <FileCard
148 + key={file.id}
149 + file={file}
150 + onPreview={setPreviewFile}
151 + onRefresh={fetchRecent}
152 + viewMode={viewMode}
153 + />
154 + ))}
155 + </div>
156 + </motion.div>
157 + );
158 + })}
159 + </AnimatePresence>
160 + </div>
161 + )}
162 + </div>
163 + </div>
164 +
165 + {previewFile && (
166 + <div className="fixed inset-0 z-50 lg:relative lg:inset-auto lg:w-[400px] lg:border-l lg:border-gray-200 dark:lg:border-white/10">
167 + <PreviewEngine
168 + file={previewFile}
169 + files={files}
170 + onClose={() => setPreviewFile(null)}
171 + onNavigate={setPreviewFile}
172 + />
173 + </div>
174 + )}
175 + </div>
176 + </AppShell>
177 + );
178 +}
added app/dashboard/security/page.tsx +33 −0
@@ -0,0 +1,33 @@
1 +"use client";
2 +
3 +import AppShell from "@/components/layout/AppShell";
4 +import DevicesPanel from "@/components/auth/DevicesPanel";
5 +import { Shield } from "lucide-react";
6 +
7 +export default function SecurityPage() {
8 + return (
9 + <AppShell>
10 + <div className="p-4 lg:p-6 space-y-6">
11 + <div className="flex items-center gap-3">
12 + <div className="w-10 h-10 rounded-xl bg-emerald-500/15 flex items-center justify-center">
13 + <Shield className="w-5 h-5 text-emerald-400" />
14 + </div>
15 + <div>
16 + <h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Sécurité</h1>
17 + <p className="text-sm text-gray-500 mt-0.5">Appareils et sessions connectés à votre compte</p>
18 + </div>
19 + </div>
20 +
21 + <div className="bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-2xl p-4 lg:p-6">
22 + <div className="mb-5">
23 + <h2 className="text-base font-medium text-gray-900 dark:text-white">Appareils connectés</h2>
24 + <p className="text-sm text-gray-500 mt-0.5">
25 + IP, localisation et navigateur enregistrés à chaque connexion.
26 + </p>
27 + </div>
28 + <DevicesPanel />
29 + </div>
30 + </div>
31 + </AppShell>
32 + );
33 +}
modified app/dashboard/shared-space/[id]/page.tsx +4 −2
@@ -67,8 +67,10 @@ export default function SharedSpacePage() {
67 67 ]);
68 68 if (spaceRes.ok) setSpace(await spaceRes.json());
69 69 if (foldersRes.ok) setFolders(await foldersRes.json());
70 − if (filesRes?.ok) setFiles(await filesRes.json());
71 − else setFiles([]);
70 + if (filesRes?.ok) {
71 + const filesData = await filesRes.json();
72 + setFiles(Array.isArray(filesData) ? filesData : filesData.files || []);
73 + } else setFiles([]);
72 74 } catch {
73 75 // ignore
74 76 } finally {
added app/dashboard/shared-with-me/page.tsx +188 −0
@@ -0,0 +1,188 @@
1 +"use client";
2 +
3 +import { useState, useEffect, useCallback } from "react";
4 +import { Users, FolderOpen } from "lucide-react";
5 +import { motion, AnimatePresence } from "framer-motion";
6 +import AppShell from "@/components/layout/AppShell";
7 +import FileCard from "@/components/files/FileCard";
8 +import PreviewEngine from "@/components/preview/PreviewEngine";
9 +import { formatFileSize } from "@/lib/utils";
10 +import type { FileData } from "@/types/files";
11 +import { useRouter } from "next/navigation";
12 +
13 +interface SharedSpace {
14 + id: string;
15 + name: string;
16 + quotaBytes: number;
17 +}
18 +
19 +interface SpaceWithFiles extends SharedSpace {
20 + files: FileData[];
21 + memberCount: number;
22 +}
23 +
24 +export default function SharedWithMePage() {
25 + const router = useRouter();
26 + const [spaces, setSpaces] = useState<SpaceWithFiles[]>([]);
27 + const [previewFile, setPreviewFile] = useState<FileData | null>(null);
28 + const [loading, setLoading] = useState(true);
29 +
30 + const fetchData = useCallback(async () => {
31 + setLoading(true);
32 + try {
33 + const spacesRes = await fetch("/api/shared-spaces/mine");
34 + if (!spacesRes.ok) return;
35 + const spacesData: SharedSpace[] = await spacesRes.json();
36 +
37 + if (!Array.isArray(spacesData) || spacesData.length === 0) {
38 + setSpaces([]);
39 + return;
40 + }
41 +
42 + // Fetch details for each space
43 + const detailed = await Promise.all(
44 + spacesData.map(async (space) => {
45 + try {
46 + const res = await fetch(`/api/shared-spaces/${space.id}`);
47 + if (!res.ok) return { ...space, files: [], memberCount: 0 };
48 + const data = await res.json();
49 + // files are nested in the space response or we fetch them separately
50 + const filesRes = await fetch(`/api/files?folderId=root&sharedSpaceId=${space.id}`);
51 + const filesRaw = filesRes.ok ? await filesRes.json() : [];
52 + const files = Array.isArray(filesRaw) ? filesRaw : filesRaw.files || [];
53 + return {
54 + ...space,
55 + files,
56 + memberCount: data.members?.length || 0,
57 + };
58 + } catch {
59 + return { ...space, files: [], memberCount: 0 };
60 + }
61 + })
62 + );
63 +
64 + setSpaces(detailed);
65 + } catch {
66 + setSpaces([]);
67 + } finally {
68 + setLoading(false);
69 + }
70 + }, []);
71 +
72 + useEffect(() => {
73 + fetchData();
74 + }, [fetchData]);
75 +
76 + const allFiles = spaces.flatMap((s) => s.files);
77 +
78 + return (
79 + <AppShell>
80 + <div className="flex flex-col h-full lg:flex-row">
81 + <div className="flex-1 flex flex-col min-w-0">
82 + {/* Header */}
83 + <div className="px-3 sm:px-4 lg:px-6 py-3 sm:py-4 border-b border-gray-200 dark:border-white/10">
84 + <h1 className="text-lg font-medium text-gray-900 dark:text-white flex items-center gap-2">
85 + <Users className="w-5 h-5 text-purple-500" />
86 + Partage avec moi
87 + </h1>
88 + <p className="text-xs text-gray-500 mt-1">
89 + {spaces.length} espace{spaces.length !== 1 ? "s" : ""} partage{spaces.length !== 1 ? "s" : ""}
90 + </p>
91 + </div>
92 +
93 + {/* Content */}
94 + <div className="flex-1 overflow-auto px-3 sm:px-4 lg:px-6 py-3 sm:py-4">
95 + {loading ? (
96 + <div className="flex items-center justify-center h-32">
97 + <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
98 + </div>
99 + ) : spaces.length === 0 ? (
100 + <div className="flex flex-col items-center justify-center h-64 text-gray-500">
101 + <Users className="w-12 h-12 mb-4 text-gray-300 dark:text-gray-600" />
102 + <p className="text-lg">Aucun espace partage</p>
103 + <p className="text-sm mt-1 text-center px-4">
104 + Les espaces auxquels vous avez acces apparaitront ici
105 + </p>
106 + </div>
107 + ) : (
108 + <div className="space-y-6">
109 + <AnimatePresence>
110 + {spaces.map((space, i) => (
111 + <motion.div
112 + key={space.id}
113 + initial={{ opacity: 0, y: 8 }}
114 + animate={{ opacity: 1, y: 0 }}
115 + transition={{ duration: 0.2, delay: 0.05 * i }}
116 + >
117 + {/* Space Header */}
118 + <button
119 + onClick={() => router.push(`/dashboard/shared-space/${space.id}`)}
120 + className="flex items-center gap-3 mb-3 group w-full text-left"
121 + >
122 + <div className="w-8 h-8 rounded-xl bg-purple-500/10 dark:bg-purple-500/20 flex items-center justify-center flex-shrink-0">
123 + <FolderOpen className="w-4 h-4 text-purple-500" />
124 + </div>
125 + <div className="min-w-0 flex-1">
126 + <h2 className="text-sm font-medium text-gray-900 dark:text-white group-hover:text-purple-500 transition-colors truncate">
127 + {space.name}
128 + </h2>
129 + <p className="text-xs text-gray-400 dark:text-gray-500">
130 + {space.memberCount} membre{space.memberCount !== 1 ? "s" : ""}
131 + {" / "}
132 + {space.files.length} fichier{space.files.length !== 1 ? "s" : ""}
133 + {space.quotaBytes > 0 && (
134 + <> / Quota: {formatFileSize(space.quotaBytes)}</>
135 + )}
136 + </p>
137 + </div>
138 + </button>
139 +
140 + {/* Files Grid */}
141 + {space.files.length > 0 ? (
142 + <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2 sm:gap-3">
143 + {space.files.slice(0, 10).map((file) => (
144 + <FileCard
145 + key={file.id}
146 + file={file}
147 + onPreview={setPreviewFile}
148 + onRefresh={fetchData}
149 + viewMode="grid"
150 + />
151 + ))}
152 + </div>
153 + ) : (
154 + <div className="p-4 text-center text-sm text-gray-400 dark:text-gray-500 rounded-xl bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/5">
155 + Aucun fichier dans cet espace
156 + </div>
157 + )}
158 +
159 + {space.files.length > 10 && (
160 + <button
161 + onClick={() => router.push(`/dashboard/shared-space/${space.id}`)}
162 + className="mt-2 text-xs text-purple-500 hover:text-purple-400 transition-colors"
163 + >
164 + Voir les {space.files.length} fichiers
165 + </button>
166 + )}
167 + </motion.div>
168 + ))}
169 + </AnimatePresence>
170 + </div>
171 + )}
172 + </div>
173 + </div>
174 +
175 + {previewFile && (
176 + <div className="fixed inset-0 z-50 lg:relative lg:inset-auto lg:w-[400px] lg:border-l lg:border-gray-200 dark:lg:border-white/10">
177 + <PreviewEngine
178 + file={previewFile}
179 + files={allFiles}
180 + onClose={() => setPreviewFile(null)}
181 + onNavigate={setPreviewFile}
182 + />
183 + </div>
184 + )}
185 + </div>
186 + </AppShell>
187 + );
188 +}
added app/dashboard/trash/page.tsx +442 −0
@@ -0,0 +1,442 @@
1 +"use client";
2 +
3 +import { useState, useEffect, useCallback } from "react";
4 +import { motion, AnimatePresence } from "framer-motion";
5 +import {
6 + Trash2,
7 + RotateCcw,
8 + AlertTriangle,
9 + FileText,
10 + Image,
11 + Film,
12 + Music,
13 + FileCode,
14 + File,
15 + Check,
16 + Clock,
17 + X,
18 +} from "lucide-react";
19 +import AppShell from "@/components/layout/AppShell";
20 +
21 +interface TrashedFile {
22 + id: string;
23 + name: string;
24 + size: number;
25 + mimeType: string;
26 + deletedAt: string;
27 + createdAt: string;
28 +}
29 +
30 +function formatSize(bytes: number): string {
31 + if (bytes < 1024) return `${bytes} o`;
32 + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} Ko`;
33 + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} Mo`;
34 + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} Go`;
35 +}
36 +
37 +function daysUntilPurge(deletedAt: string): number {
38 + const deleted = new Date(deletedAt);
39 + const purgeDate = new Date(deleted.getTime() + 30 * 24 * 60 * 60 * 1000);
40 + const now = new Date();
41 + const diff = Math.ceil((purgeDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
42 + return Math.max(0, diff);
43 +}
44 +
45 +function getTypeIcon(mimeType: string) {
46 + if (mimeType.startsWith("image/")) return Image;
47 + if (mimeType.startsWith("video/")) return Film;
48 + if (mimeType.startsWith("audio/")) return Music;
49 + if (mimeType === "application/pdf") return FileText;
50 + if (
51 + mimeType.includes("javascript") ||
52 + mimeType.includes("typescript") ||
53 + mimeType.includes("json") ||
54 + mimeType.includes("xml") ||
55 + mimeType.includes("html") ||
56 + mimeType.includes("css")
57 + )
58 + return FileCode;
59 + if (mimeType.startsWith("text/")) return FileText;
60 + return File;
61 +}
62 +
63 +export default function TrashPage() {
64 + const [files, setFiles] = useState<TrashedFile[]>([]);
65 + const [selected, setSelected] = useState<Set<string>>(new Set());
66 + const [loading, setLoading] = useState(true);
67 + const [acting, setActing] = useState(false);
68 + const [showEmptyConfirm, setShowEmptyConfirm] = useState(false);
69 + const [showPurgeConfirm, setShowPurgeConfirm] = useState(false);
70 +
71 + const fetchTrash = useCallback(async () => {
72 + setLoading(true);
73 + try {
74 + const res = await fetch("/api/trash");
75 + if (res.ok) setFiles(await res.json());
76 + } catch {
77 + /* ignore */
78 + }
79 + setLoading(false);
80 + }, []);
81 +
82 + useEffect(() => {
83 + fetchTrash();
84 + }, [fetchTrash]);
85 +
86 + const toggleSelect = (id: string) => {
87 + setSelected((prev) => {
88 + const next = new Set(prev);
89 + if (next.has(id)) next.delete(id);
90 + else next.add(id);
91 + return next;
92 + });
93 + };
94 +
95 + const toggleAll = () => {
96 + if (selected.size === files.length) {
97 + setSelected(new Set());
98 + } else {
99 + setSelected(new Set(files.map((f) => f.id)));
100 + }
101 + };
102 +
103 + const handleRestore = async () => {
104 + if (selected.size === 0) return;
105 + setActing(true);
106 + try {
107 + await fetch("/api/trash", {
108 + method: "POST",
109 + headers: { "Content-Type": "application/json" },
110 + body: JSON.stringify({ action: "restore", fileIds: Array.from(selected) }),
111 + });
112 + setSelected(new Set());
113 + await fetchTrash();
114 + } catch {
115 + /* ignore */
116 + }
117 + setActing(false);
118 + };
119 +
120 + const handlePurge = async () => {
121 + if (selected.size === 0) return;
122 + setActing(true);
123 + try {
124 + await fetch("/api/trash", {
125 + method: "POST",
126 + headers: { "Content-Type": "application/json" },
127 + body: JSON.stringify({ action: "purge", fileIds: Array.from(selected) }),
128 + });
129 + setSelected(new Set());
130 + setShowPurgeConfirm(false);
131 + await fetchTrash();
132 + } catch {
133 + /* ignore */
134 + }
135 + setActing(false);
136 + };
137 +
138 + const handleEmpty = async () => {
139 + setActing(true);
140 + try {
141 + await fetch("/api/trash", {
142 + method: "POST",
143 + headers: { "Content-Type": "application/json" },
144 + body: JSON.stringify({ action: "empty" }),
145 + });
146 + setSelected(new Set());
147 + setShowEmptyConfirm(false);
148 + await fetchTrash();
149 + } catch {
150 + /* ignore */
151 + }
152 + setActing(false);
153 + };
154 +
155 + return (
156 + <AppShell>
157 + <div className="flex flex-col h-full">
158 + {/* Header */}
159 + <div className="px-3 sm:px-4 lg:px-6 py-3 sm:py-4 border-b border-gray-200 dark:border-white/10 shrink-0">
160 + <div className="flex items-center justify-between gap-3">
161 + <div className="flex items-center gap-2 min-w-0">
162 + <Trash2 className="w-5 h-5 text-red-400 shrink-0" />
163 + <h1 className="text-lg font-medium text-gray-900 dark:text-white truncate">
164 + Corbeille
165 + </h1>
166 + <span className="text-xs text-gray-500 dark:text-gray-400 tabular-nums shrink-0">
167 + {files.length} fichier{files.length !== 1 ? "s" : ""}
168 + </span>
169 + </div>
170 + {files.length > 0 && (
171 + <button
172 + onClick={() => setShowEmptyConfirm(true)}
173 + disabled={acting}
174 + className="text-xs sm:text-sm px-3 py-2 rounded-lg bg-red-500/10 text-red-500 hover:bg-red-500/20 active:bg-red-500/30 transition-colors font-medium min-h-[44px] min-w-[44px] disabled:opacity-50 shrink-0"
175 + >
176 + Vider la corbeille
177 + </button>
178 + )}
179 + </div>
180 +
181 + {/* Bulk actions */}
182 + <AnimatePresence>
183 + {selected.size > 0 && (
184 + <motion.div
185 + initial={{ height: 0, opacity: 0 }}
186 + animate={{ height: "auto", opacity: 1 }}
187 + exit={{ height: 0, opacity: 0 }}
188 + className="overflow-hidden"
189 + >
190 + <div className="flex items-center gap-2 mt-3 flex-wrap">
191 + <span className="text-sm text-gray-500 dark:text-gray-400">
192 + {selected.size} selectionne{selected.size !== 1 ? "s" : ""}
193 + </span>
194 + <button
195 + onClick={handleRestore}
196 + disabled={acting}
197 + className="flex items-center gap-1.5 text-sm px-3 py-2 rounded-lg bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20 active:bg-emerald-500/30 transition-colors font-medium min-h-[44px] disabled:opacity-50"
198 + >
199 + <RotateCcw className="w-4 h-4" />
200 + Restaurer
201 + </button>
202 + <button
203 + onClick={() => setShowPurgeConfirm(true)}
204 + disabled={acting}
205 + className="flex items-center gap-1.5 text-sm px-3 py-2 rounded-lg bg-red-500/10 text-red-500 hover:bg-red-500/20 active:bg-red-500/30 transition-colors font-medium min-h-[44px] disabled:opacity-50"
206 + >
207 + <Trash2 className="w-4 h-4" />
208 + Supprimer definitivement
209 + </button>
210 + <button
211 + onClick={() => setSelected(new Set())}
212 + className="text-sm px-2 py-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
213 + >
214 + <X className="w-4 h-4" />
215 + </button>
216 + </div>
217 + </motion.div>
218 + )}
219 + </AnimatePresence>
220 + </div>
221 +
222 + {/* Content */}
223 + <div className="flex-1 overflow-auto px-3 sm:px-4 lg:px-6 py-3 sm:py-4">
224 + {loading ? (
225 + <div className="flex items-center justify-center h-32">
226 + <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
227 + </div>
228 + ) : files.length === 0 ? (
229 + <div className="flex flex-col items-center justify-center h-64 text-gray-500">
230 + <Trash2 className="w-16 h-16 mb-4 text-gray-300 dark:text-gray-600" />
231 + <p className="text-lg font-medium text-gray-700 dark:text-gray-300">
232 + La corbeille est vide
233 + </p>
234 + <p className="text-sm mt-1 text-center px-4 text-gray-400 dark:text-gray-500">
235 + Les fichiers supprimes apparaitront ici pendant 30 jours
236 + </p>
237 + </div>
238 + ) : (
239 + <>
240 + {/* Select all */}
241 + <div className="flex items-center gap-3 mb-3 px-1">
242 + <button
243 + onClick={toggleAll}
244 + className="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors min-h-[44px]"
245 + >
246 + <div
247 + className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
248 + selected.size === files.length
249 + ? "bg-blue-500 border-blue-500"
250 + : "border-gray-300 dark:border-gray-600"
251 + }`}
252 + >
253 + {selected.size === files.length && (
254 + <Check className="w-3.5 h-3.5 text-white" />
255 + )}
256 + </div>
257 + Tout selectionner
258 + </button>
259 + </div>
260 +
261 + {/* File list */}
262 + <div className="space-y-1">
263 + <AnimatePresence>
264 + {files.map((file) => {
265 + const Icon = getTypeIcon(file.mimeType);
266 + const days = daysUntilPurge(file.deletedAt);
267 + const isSelected = selected.has(file.id);
268 +
269 + return (
270 + <motion.div
271 + key={file.id}
272 + layout
273 + initial={{ opacity: 0, y: 10 }}
274 + animate={{ opacity: 1, y: 0 }}
275 + exit={{ opacity: 0, x: -50 }}
276 + onClick={() => toggleSelect(file.id)}
277 + className={`flex items-center gap-3 px-3 py-3 rounded-xl cursor-pointer transition-colors min-h-[60px] ${
278 + isSelected
279 + ? "bg-blue-50 dark:bg-blue-500/10 border border-blue-200 dark:border-blue-500/30"
280 + : "bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 hover:bg-gray-50 dark:hover:bg-white/10 active:bg-gray-100 dark:active:bg-white/15"
281 + }`}
282 + >
283 + {/* Checkbox */}
284 + <div
285 + className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors ${
286 + isSelected
287 + ? "bg-blue-500 border-blue-500"
288 + : "border-gray-300 dark:border-gray-600"
289 + }`}
290 + >
291 + {isSelected && <Check className="w-3.5 h-3.5 text-white" />}
292 + </div>
293 +
294 + {/* Icon */}
295 + <div className="w-10 h-10 rounded-lg bg-gray-100 dark:bg-white/10 flex items-center justify-center shrink-0">
296 + <Icon className="w-5 h-5 text-gray-500 dark:text-gray-400" />
297 + </div>
298 +
299 + {/* Info */}
300 + <div className="flex-1 min-w-0">
301 + <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
302 + {file.name}
303 + </p>
304 + <div className="flex items-center gap-2 mt-0.5 flex-wrap">
305 + <span className="text-xs text-gray-500 dark:text-gray-400">
306 + {formatSize(file.size)}
307 + </span>
308 + <span className="text-xs text-gray-400 dark:text-gray-500">
309 + {new Date(file.deletedAt).toLocaleDateString("fr-FR", {
310 + day: "numeric",
311 + month: "short",
312 + })}
313 + </span>
314 + </div>
315 + </div>
316 +
317 + {/* Auto-purge badge */}
318 + <div
319 + className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs shrink-0 ${
320 + days <= 3
321 + ? "bg-red-100 dark:bg-red-500/15 text-red-600 dark:text-red-400"
322 + : days <= 7
323 + ? "bg-amber-100 dark:bg-amber-500/15 text-amber-600 dark:text-amber-400"
324 + : "bg-gray-100 dark:bg-white/10 text-gray-500 dark:text-gray-400"
325 + }`}
326 + >
327 + <Clock className="w-3 h-3" />
328 + <span className="hidden sm:inline">{days}j</span>
329 + <span className="sm:hidden">{days}</span>
330 + </div>
331 + </motion.div>
332 + );
333 + })}
334 + </AnimatePresence>
335 + </div>
336 + </>
337 + )}
338 + </div>
339 + </div>
340 +
341 + {/* Empty trash confirmation modal */}
342 + <AnimatePresence>
343 + {showEmptyConfirm && (
344 + <motion.div
345 + initial={{ opacity: 0 }}
346 + animate={{ opacity: 1 }}
347 + exit={{ opacity: 0 }}
348 + className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
349 + onClick={() => setShowEmptyConfirm(false)}
350 + >
351 + <motion.div
352 + initial={{ scale: 0.95, opacity: 0 }}
353 + animate={{ scale: 1, opacity: 1 }}
354 + exit={{ scale: 0.95, opacity: 0 }}
355 + onClick={(e) => e.stopPropagation()}
356 + className="bg-white dark:bg-[#1a1a1a] rounded-2xl p-6 max-w-sm w-full shadow-xl border border-gray-200 dark:border-white/10"
357 + >
358 + <div className="flex items-center gap-3 mb-4">
359 + <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-500/15 flex items-center justify-center">
360 + <AlertTriangle className="w-5 h-5 text-red-500" />
361 + </div>
362 + <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
363 + Vider la corbeille
364 + </h3>
365 + </div>
366 + <p className="text-sm text-gray-600 dark:text-gray-400 mb-6">
367 + Cette action supprimera definitivement {files.length} fichier
368 + {files.length !== 1 ? "s" : ""}. Cette action est irreversible.
369 + </p>
370 + <div className="flex gap-3">
371 + <button
372 + onClick={() => setShowEmptyConfirm(false)}
373 + className="flex-1 px-4 py-3 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 transition-colors min-h-[44px]"
374 + >
375 + Annuler
376 + </button>
377 + <button
378 + onClick={handleEmpty}
379 + disabled={acting}
380 + className="flex-1 px-4 py-3 rounded-xl text-sm font-medium text-white bg-red-500 hover:bg-red-600 active:bg-red-700 transition-colors min-h-[44px] disabled:opacity-50"
381 + >
382 + {acting ? "Suppression..." : "Supprimer tout"}
383 + </button>
384 + </div>
385 + </motion.div>
386 + </motion.div>
387 + )}
388 + </AnimatePresence>
389 +
390 + {/* Purge selected confirmation modal */}
391 + <AnimatePresence>
392 + {showPurgeConfirm && (
393 + <motion.div
394 + initial={{ opacity: 0 }}
395 + animate={{ opacity: 1 }}
396 + exit={{ opacity: 0 }}
397 + className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
398 + onClick={() => setShowPurgeConfirm(false)}
399 + >
400 + <motion.div
401 + initial={{ scale: 0.95, opacity: 0 }}
402 + animate={{ scale: 1, opacity: 1 }}
403 + exit={{ scale: 0.95, opacity: 0 }}
404 + onClick={(e) => e.stopPropagation()}
405 + className="bg-white dark:bg-[#1a1a1a] rounded-2xl p-6 max-w-sm w-full shadow-xl border border-gray-200 dark:border-white/10"
406 + >
407 + <div className="flex items-center gap-3 mb-4">
408 + <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-500/15 flex items-center justify-center">
409 + <AlertTriangle className="w-5 h-5 text-red-500" />
410 + </div>
411 + <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
412 + Supprimer definitivement
413 + </h3>
414 + </div>
415 + <p className="text-sm text-gray-600 dark:text-gray-400 mb-6">
416 + {selected.size} fichier{selected.size !== 1 ? "s" : ""} sera
417 + {selected.size !== 1 ? "ont" : ""} supprime
418 + {selected.size !== 1 ? "s" : ""} definitivement. Cette action est
419 + irreversible.
420 + </p>
421 + <div className="flex gap-3">
422 + <button
423 + onClick={() => setShowPurgeConfirm(false)}
424 + className="flex-1 px-4 py-3 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 transition-colors min-h-[44px]"
425 + >
426 + Annuler
427 + </button>
428 + <button
429 + onClick={handlePurge}
430 + disabled={acting}
431 + className="flex-1 px-4 py-3 rounded-xl text-sm font-medium text-white bg-red-500 hover:bg-red-600 active:bg-red-700 transition-colors min-h-[44px] disabled:opacity-50"
432 + >
433 + {acting ? "Suppression..." : "Supprimer"}
434 + </button>
435 + </div>
436 + </motion.div>
437 + </motion.div>
438 + )}
439 + </AnimatePresence>
440 + </AppShell>
441 + );
442 +}
modified app/globals.css +41 −5
@@ -1,9 +1,9 @@
1 +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
2 +
1 3 @tailwind base;
2 4 @tailwind components;
3 5 @tailwind utilities;
4 6
5 −@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
6 −
7 7 /* ===== LIGHT THEME (default) ===== */
8 8 :root {
9 9 --background: #ffffff;
@@ -101,16 +101,52 @@ button:active, a:active, [role="button"]:active {
101 101 }
102 102
103 103 ::-webkit-scrollbar-track {
104 − background: var(--scrollbar-track);
104 + background: transparent;
105 105 }
106 106
107 107 ::-webkit-scrollbar-thumb {
108 − background: var(--scrollbar-thumb);
108 + background: rgba(128, 128, 128, 0.3);
109 109 border-radius: 3px;
110 110 }
111 111
112 112 ::-webkit-scrollbar-thumb:hover {
113 − background: var(--scrollbar-thumb-hover);
113 + background: rgba(128, 128, 128, 0.5);
114 +}
115 +
116 +/* Better focus rings */
117 +*:focus-visible {
118 + outline: 2px solid rgb(29 78 216);
119 + outline-offset: 2px;
120 + border-radius: 4px;
121 +}
122 +
123 +/* Shimmer animation for skeletons */
124 +@keyframes shimmer {
125 + 0% { background-position: -200% 0; }
126 + 100% { background-position: 200% 0; }
127 +}
128 +.animate-shimmer {
129 + background: linear-gradient(90deg, transparent 25%, rgba(255, 255, 255, 0.08) 50%, transparent 75%);
130 + background-size: 200% 100%;
131 + animation: shimmer 1.5s infinite;
132 +}
133 +
134 +/* Top loader animation */
135 +@keyframes topload {
136 + 0% { width: 0; }
137 + 50% { width: 70%; }
138 + 100% { width: 100%; }
139 +}
140 +
141 +/* Smooth page transitions */
142 +.page-enter {
143 + opacity: 0;
144 + transform: translateY(8px);
145 +}
146 +.page-enter-active {
147 + opacity: 1;
148 + transform: translateY(0);
149 + transition: all 0.3s ease;
114 150 }
115 151
116 152 /* File drop zone animations */
modified app/layout.tsx +6 −2
@@ -14,7 +14,7 @@ export default function RootLayout({
14 14 children: React.ReactNode;
15 15 }>) {
16 16 return (
17 − <html lang="fr" className="dark" suppressHydrationWarning>
17 + <html lang="fr" className="light" suppressHydrationWarning>
18 18 <head>
19 19 <script
20 20 dangerouslySetInnerHTML={{
@@ -22,7 +22,11 @@ export default function RootLayout({
22 22 (function() {
23 23 try {
24 24 var theme = localStorage.getItem('spb-theme');
25 − if (theme === 'light') {
25 + // Clair par défaut : on ne passe en sombre que si explicitement choisi
26 + if (theme === 'dark') {
27 + document.documentElement.classList.add('dark');
28 + document.documentElement.classList.remove('light');
29 + } else {
26 30 document.documentElement.classList.remove('dark');
27 31 document.documentElement.classList.add('light');
28 32 }
modified app/login/page.tsx +77 −16
@@ -4,6 +4,7 @@ import { useState } from "react";
4 4 import { useRouter } from "next/navigation";
5 5 import { motion } from "framer-motion";
6 6 import { Cloud, Lock, Eye, EyeOff, Loader2, User, Shield } from "lucide-react";
7 +import { AnimatePresence } from "framer-motion";
7 8 import ThemeToggle from "@/components/theme/ThemeToggle";
8 9
9 10 export default function LoginPage() {
@@ -16,7 +17,7 @@ export default function LoginPage() {
16 17 const [needs2FA, setNeeds2FA] = useState(false);
17 18 const router = useRouter();
18 19
19 − const inputClasses = "w-full bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl px-10 py-3.5 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:border-gray-400 dark:focus:border-white/30 transition-colors shadow-sm dark:shadow-none";
20 + const inputClasses = "w-full bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl px-10 py-3.5 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:border-blue-600 dark:focus:border-blue-700/50 focus:ring-2 focus:ring-blue-700/20 dark:focus:ring-blue-700/10 transition-all duration-200 shadow-sm dark:shadow-none";
20 21
21 22 const handleSubmit = async (e: React.FormEvent) => {
22 23 e.preventDefault();
@@ -74,7 +75,38 @@ export default function LoginPage() {
74 75 };
75 76
76 77 return (
77 − <div className="min-h-screen bg-gray-50 dark:bg-[#0a0a0a] flex items-center justify-center px-4 py-8 transition-colors">
78 + <div className="min-h-screen bg-gray-50 dark:bg-[#0a0a0a] flex items-center justify-center px-4 py-8 transition-colors relative overflow-hidden">
79 + {/* Animated background orbs */}
80 + <div className="absolute inset-0 pointer-events-none overflow-hidden">
81 + <motion.div
82 + className="absolute w-[400px] h-[400px] rounded-full bg-blue-700/[0.07] dark:bg-blue-700/[0.05] blur-3xl"
83 + animate={{
84 + x: [0, 60, -30, 0],
85 + y: [0, -40, 50, 0],
86 + }}
87 + transition={{ duration: 20, repeat: Infinity, ease: "easeInOut" }}
88 + style={{ top: "-10%", left: "-5%" }}
89 + />
90 + <motion.div
91 + className="absolute w-[350px] h-[350px] rounded-full bg-blue-500/[0.06] dark:bg-blue-500/[0.04] blur-3xl"
92 + animate={{
93 + x: [0, -50, 40, 0],
94 + y: [0, 60, -30, 0],
95 + }}
96 + transition={{ duration: 25, repeat: Infinity, ease: "easeInOut" }}
97 + style={{ bottom: "-5%", right: "-5%" }}
98 + />
99 + <motion.div
100 + className="absolute w-[250px] h-[250px] rounded-full bg-pink-500/[0.05] dark:bg-pink-500/[0.03] blur-3xl"
101 + animate={{
102 + x: [0, 30, -20, 0],
103 + y: [0, -30, 20, 0],
104 + }}
105 + transition={{ duration: 18, repeat: Infinity, ease: "easeInOut" }}
106 + style={{ top: "40%", right: "20%" }}
107 + />
108 + </div>
109 +
78 110 <div className="fixed top-3 right-3 sm:top-4 sm:right-4 z-10">
79 111 <ThemeToggle />
80 112 </div>
@@ -100,8 +132,17 @@ export default function LoginPage() {
100 132 </p>
101 133 </div>
102 134
135 + <AnimatePresence mode="wait">
103 136 {!needs2FA ? (
104 − <form onSubmit={handleSubmit} className="space-y-4">
137 + <motion.form
138 + key="login-form"
139 + initial={{ opacity: 0, x: -20 }}
140 + animate={{ opacity: 1, x: 0 }}
141 + exit={{ opacity: 0, x: 20 }}
142 + transition={{ duration: 0.3 }}
143 + onSubmit={handleSubmit}
144 + className="space-y-4"
145 + >
105 146 <div className="relative">
106 147 <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500" />
107 148 <input
@@ -147,14 +188,29 @@ export default function LoginPage() {
147 188 >
148 189 {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Connexion"}
149 190 </motion.button>
150 − </form>
191 + </motion.form>
151 192 ) : (
152 − <form onSubmit={handleVerify2FA} className="space-y-4">
153 − <div className="flex justify-center mb-4">
154 − <Shield className="w-12 h-12 text-purple-500" />
155 − </div>
193 + <motion.form
194 + key="2fa-form"
195 + initial={{ opacity: 0, x: 20 }}
196 + animate={{ opacity: 1, x: 0 }}
197 + exit={{ opacity: 0, x: -20 }}
198 + transition={{ duration: 0.3 }}
199 + onSubmit={handleVerify2FA}
200 + className="space-y-4"
201 + >
202 + <motion.div
203 + initial={{ scale: 0.8, opacity: 0 }}
204 + animate={{ scale: 1, opacity: 1 }}
205 + transition={{ delay: 0.1, type: "spring", stiffness: 200 }}
206 + className="flex justify-center mb-4"
207 + >
208 + <div className="w-16 h-16 rounded-2xl bg-blue-800/10 dark:bg-blue-800/20 flex items-center justify-center">
209 + <Shield className="w-8 h-8 text-blue-600" />
210 + </div>
211 + </motion.div>
156 212 <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
157 − Entrez le code à 6 chiffres de votre app authenticator
213 + Entrez le code a 6 chiffres de votre app authenticator
158 214 </p>
159 215 <input
160 216 type="text"
@@ -162,7 +218,7 @@ export default function LoginPage() {
162 218 onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
163 219 placeholder="000000"
164 220 maxLength={6}
165 − className="w-full bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl px-4 py-3.5 text-gray-900 dark:text-white text-center text-2xl tracking-[0.3em] sm:tracking-[0.5em] font-mono focus:outline-none focus:border-gray-400 dark:focus:border-white/30 shadow-sm dark:shadow-none"
221 + className="w-full bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl px-4 py-3.5 text-gray-900 dark:text-white text-center text-2xl tracking-[0.3em] sm:tracking-[0.5em] font-mono focus:outline-none focus:border-blue-600 dark:focus:border-blue-700/50 focus:ring-2 focus:ring-blue-700/20 dark:focus:ring-blue-700/10 transition-all duration-200 shadow-sm dark:shadow-none"
166 222 autoFocus
167 223 />
168 224
@@ -178,22 +234,27 @@ export default function LoginPage() {
178 234 disabled={loading || totpCode.length !== 6}
179 235 className="w-full bg-gray-900 dark:bg-white text-white dark:text-black font-medium py-3.5 rounded-xl hover:bg-gray-800 dark:hover:bg-gray-200 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
180 236 >
181 − {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Vérifier"}
237 + {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Verifier"}
182 238 </motion.button>
183 239
184 240 <button
185 241 type="button"
186 242 onClick={() => { setNeeds2FA(false); setTotpCode(""); setError(""); }}
187 − className="w-full text-sm text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 py-2"
243 + className="w-full text-sm text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 py-2 transition-colors"
188 244 >
189 245 Retour
190 246 </button>
191 − </form>
247 + </motion.form>
192 248 )}
249 + </AnimatePresence>
193 250
194 − <p className="text-center text-gray-400 dark:text-gray-600 text-xs mt-6">
195 − SPB Private Cloud v2.0
196 − </p>
251 + <div className="mt-6 flex flex-col items-center gap-1.5">
252 + <div className="flex items-center gap-1.5 text-xs text-gray-400 dark:text-gray-500">
253 + <Shield className="w-3 h-3" />
254 + <span>Connexions analysées par <span className="text-gray-500 dark:text-gray-400 font-medium">Claude Opus 4.6</span></span>
255 + </div>
256 + <p className="text-gray-400 dark:text-gray-600 text-xs">SPB Private Cloud v2.0</p>
257 + </div>
197 258 </motion.div>
198 259 </div>
199 260 );
modified app/shared/[token]/page.tsx +537 −81
@@ -1,49 +1,194 @@
1 1 "use client";
2 2
3 −import { useEffect, useState } from "react";
3 +import { useEffect, useState, useCallback } from "react";
4 4 import { useParams } from "next/navigation";
5 5 import { motion } from "framer-motion";
6 −import { Cloud, Download, Lock, AlertCircle, Loader2 } from "lucide-react";
6 +import {
7 + Cloud,
8 + Download,
9 + Lock,
10 + AlertCircle,
11 + Loader2,
12 + FileText,
13 + Image as ImageIcon,
14 + Film,
15 + Music,
16 + FileCode,
17 + File as FileIcon,
18 + ZoomIn,
19 + ZoomOut,
20 + Clock,
21 +} from "lucide-react";
7 22 import Button from "@/components/ui/Button";
8 23
24 +interface FileInfo {
25 + id: string;
26 + name: string;
27 + mimeType: string;
28 + size: number;
29 + mode: string;
30 + expiresAt: string | null;
31 +}
32 +
33 +function formatSize(bytes: number): string {
34 + if (bytes === 0) return "0 o";
35 + const k = 1024;
36 + const sizes = ["o", "Ko", "Mo", "Go", "To"];
37 + const i = Math.floor(Math.log(bytes) / Math.log(k));
38 + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
39 +}
40 +
41 +function formatExpiry(expiresAt: string | null): string | null {
42 + if (!expiresAt) return null;
43 + const date = new Date(expiresAt);
44 + const now = new Date();
45 + const diff = date.getTime() - now.getTime();
46 + if (diff <= 0) return "Expire";
47 + const hours = Math.floor(diff / (1000 * 60 * 60));
48 + const days = Math.floor(hours / 24);
49 + if (days > 0) return `Expire dans ${days}j`;
50 + if (hours > 0) return `Expire dans ${hours}h`;
51 + const minutes = Math.floor(diff / (1000 * 60));
52 + return `Expire dans ${minutes}min`;
53 +}
54 +
55 +function getFileCategory(mimeType: string): string {
56 + if (mimeType.startsWith("image/")) return "image";
57 + if (mimeType === "application/pdf") return "pdf";
58 + if (mimeType.startsWith("video/")) return "video";
59 + if (mimeType.startsWith("audio/")) return "audio";
60 + if (
61 + mimeType.startsWith("text/") ||
62 + mimeType === "application/json" ||
63 + mimeType === "application/xml" ||
64 + mimeType === "application/javascript" ||
65 + mimeType === "application/x-yaml" ||
66 + mimeType === "application/x-sh"
67 + )
68 + return "text";
69 + if (mimeType.includes("markdown")) return "text";
70 + return "other";
71 +}
72 +
73 +function getFileIcon(category: string) {
74 + switch (category) {
75 + case "image":
76 + return <ImageIcon className="w-16 h-16 text-blue-400" />;
77 + case "pdf":
78 + return <FileText className="w-16 h-16 text-red-400" />;
79 + case "video":
80 + return <Film className="w-16 h-16 text-purple-400" />;
81 + case "audio":
82 + return <Music className="w-16 h-16 text-green-400" />;
83 + case "text":
84 + return <FileCode className="w-16 h-16 text-yellow-400" />;
85 + default:
86 + return <FileIcon className="w-16 h-16 text-gray-400" />;
87 + }
88 +}
89 +
9 90 export default function SharedPage() {
10 91 const params = useParams();
11 92 const token = params.token as string;
12 93
13 − const [state, setState] = useState<"loading" | "password" | "preview" | "error">("loading");
94 + const [state, setState] = useState<
95 + "loading" | "password" | "preview" | "download" | "error"
96 + >("loading");
14 97 const [error, setError] = useState("");
15 − const [fileInfo, setFileInfo] = useState<{
16 − fileName: string;
17 − fileType: string;
18 − mode: string;
19 − } | null>(null);
98 + const [errorType, setErrorType] = useState<"expired" | "invalid" | "network">("invalid");
99 + const [fileInfo, setFileInfo] = useState<FileInfo | null>(null);
20 100 const [password, setPassword] = useState("");
21 101 const [passwordLoading, setPasswordLoading] = useState(false);
102 + const [passwordVerified, setPasswordVerified] = useState(false);
103 + const [textContent, setTextContent] = useState<string | null>(null);
104 + const [imageZoom, setImageZoom] = useState(1);
105 +
106 + const contentUrl = useCallback(
107 + (forDownload?: boolean) => {
108 + const base = `/api/shared/${token}?content=true`;
109 + return forDownload ? `${base}&action=download` : base;
110 + },
111 + [token]
112 + );
22 113
114 + // For password-protected files, we need to fetch content via POST
115 + const fetchProtectedContent = useCallback(
116 + async (pw: string, asBlob?: boolean) => {
117 + const res = await fetch(`/api/shared/${token}/verify`, {
118 + method: "POST",
119 + headers: { "Content-Type": "application/json" },
120 + body: JSON.stringify({ password: pw, contentOnly: true }),
121 + });
122 + if (!res.ok) throw new Error("Erreur de chargement");
123 + if (asBlob) return res.blob();
124 + return res.text();
125 + },
126 + [token]
127 + );
128 +
129 + // Load text content for text/code/markdown previews
130 + useEffect(() => {
131 + if (!fileInfo || state !== "preview") return;
132 + const category = getFileCategory(fileInfo.mimeType);
133 + if (category !== "text") return;
134 +
135 + if (passwordVerified) {
136 + fetchProtectedContent(password).then((text) => {
137 + setTextContent(text as string);
138 + }).catch(() => {
139 + setTextContent("Impossible de charger le contenu.");
140 + });
141 + } else {
142 + fetch(contentUrl())
143 + .then((res) => res.text())
144 + .then(setTextContent)
145 + .catch(() => setTextContent("Impossible de charger le contenu."));
146 + }
147 + }, [fileInfo, state, contentUrl, passwordVerified, password, fetchProtectedContent]);
148 +
149 + // Initial fetch
23 150 useEffect(() => {
24 151 fetch(`/api/shared/${token}`)
25 152 .then(async (res) => {
26 153 if (!res.ok) {
27 154 const data = await res.json();
28 − setError(data.error || "Lien invalide");
155 + if (res.status === 410) {
156 + setErrorType("expired");
157 + setError(data.error || "Ce lien a expire");
158 + } else {
159 + setErrorType("invalid");
160 + setError(data.error || "Lien invalide");
161 + }
29 162 setState("error");
30 163 return;
31 164 }
32 165
33 − const contentType = res.headers.get("content-type") || "";
34 − if (contentType.includes("application/json")) {
35 − const data = await res.json();
36 − if (data.requiresPassword) {
37 − setFileInfo(data);
38 − setState("password");
39 − }
166 + const data = await res.json();
167 +
168 + if (data.requiresPassword) {
169 + setFileInfo({
170 + id: "",
171 + name: data.fileName,
172 + mimeType: data.fileType,
173 + size: 0,
174 + mode: data.mode,
175 + expiresAt: null,
176 + });
177 + setState("password");
178 + return;
179 + }
180 +
181 + // Got file info JSON
182 + setFileInfo(data);
183 + if (data.mode === "DOWNLOAD") {
184 + setState("download");
40 185 } else {
41 − // Direct file response — redirect to download/preview
42 186 setState("preview");
43 187 }
44 188 })
45 189 .catch(() => {
46 − setError("Erreur réseau");
190 + setErrorType("network");
191 + setError("Erreur reseau");
47 192 setState("error");
48 193 });
49 194 }, [token]);
@@ -51,6 +196,7 @@ export default function SharedPage() {
51 196 const handlePasswordSubmit = async (e: React.FormEvent) => {
52 197 e.preventDefault();
53 198 setPasswordLoading(true);
199 + setError("");
54 200 try {
55 201 const res = await fetch(`/api/shared/${token}/verify`, {
56 202 method: "POST",
@@ -65,105 +211,415 @@ export default function SharedPage() {
65 211 return;
66 212 }
67 213
68 − // Download the file
69 − const blob = await res.blob();
70 − const url = URL.createObjectURL(blob);
71 − const a = document.createElement("a");
72 − a.href = url;
73 − a.download = fileInfo?.fileName || "file";
74 − a.click();
75 − URL.revokeObjectURL(url);
214 + const data = await res.json();
215 + setPasswordVerified(true);
216 + setFileInfo({
217 + id: data.id,
218 + name: data.name,
219 + mimeType: data.mimeType,
220 + size: data.size,
221 + mode: data.mode,
222 + expiresAt: data.expiresAt,
223 + });
224 +
225 + if (data.mode === "DOWNLOAD") {
226 + setState("download");
227 + } else {
228 + setState("preview");
229 + }
76 230 setPasswordLoading(false);
77 231 } catch {
78 − setError("Erreur réseau");
232 + setError("Erreur reseau");
79 233 setPasswordLoading(false);
80 234 }
81 235 };
82 236
237 + const handleDownload = async () => {
238 + if (passwordVerified) {
239 + // Fetch via POST for password-protected files
240 + try {
241 + const blob = await fetchProtectedContent(password, true) as Blob;
242 + const url = URL.createObjectURL(blob);
243 + const a = document.createElement("a");
244 + a.href = url;
245 + a.download = fileInfo?.name || "file";
246 + a.click();
247 + URL.revokeObjectURL(url);
248 + } catch {
249 + setError("Erreur lors du telechargement");
250 + }
251 + } else {
252 + window.open(contentUrl(true), "_blank");
253 + }
254 + };
255 +
256 + // Loading state
83 257 if (state === "loading") {
84 258 return (
85 259 <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
86 − <Loader2 className="w-8 h-8 text-white animate-spin" />
260 + <motion.div
261 + initial={{ opacity: 0 }}
262 + animate={{ opacity: 1 }}
263 + className="flex flex-col items-center gap-4"
264 + >
265 + <Loader2 className="w-8 h-8 text-white animate-spin" />
266 + <p className="text-sm text-gray-500">Chargement...</p>
267 + </motion.div>
87 268 </div>
88 269 );
89 270 }
90 271
272 + // Error state
91 273 if (state === "error") {
92 274 return (
93 275 <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center p-4">
94 276 <motion.div
95 277 initial={{ opacity: 0, y: 20 }}
96 278 animate={{ opacity: 1, y: 0 }}
97 − className="text-center"
279 + className="text-center max-w-sm"
98 280 >
99 − <AlertCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
100 − <h1 className="text-xl font-semibold text-white mb-2">Lien invalide</h1>
101 − <p className="text-gray-400">{error}</p>
281 + {errorType === "expired" ? (
282 + <Clock className="w-16 h-16 text-yellow-400 mx-auto mb-4" />
283 + ) : (
284 + <AlertCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
285 + )}
286 + <h1 className="text-xl font-semibold text-white mb-2">
287 + {errorType === "expired"
288 + ? "Lien expire"
289 + : errorType === "network"
290 + ? "Erreur de connexion"
291 + : "Lien invalide"}
292 + </h1>
293 + <p className="text-gray-400 text-sm">{error}</p>
294 + {errorType === "expired" && (
295 + <p className="text-gray-500 text-xs mt-3">
296 + Demandez un nouveau lien au proprietaire du fichier.
297 + </p>
298 + )}
102 299 </motion.div>
103 300 </div>
104 301 );
105 302 }
106 303
304 + // Password state
107 305 if (state === "password") {
108 306 return (
109 − <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center p-4">
110 − <motion.div
111 − initial={{ opacity: 0, y: 20 }}
112 − animate={{ opacity: 1, y: 0 }}
113 − className="w-full max-w-sm"
114 − >
115 − <div className="text-center mb-6">
116 − <Lock className="w-12 h-12 text-gray-400 mx-auto mb-3" />
117 − <h1 className="text-xl font-semibold text-white">
118 − Fichier protégé
119 − </h1>
120 − <p className="text-sm text-gray-500 mt-1">{fileInfo?.fileName}</p>
121 − </div>
122 −
123 − <form onSubmit={handlePasswordSubmit} className="space-y-4">
124 − <input
125 − type="password"
126 − value={password}
127 − onChange={(e) => setPassword(e.target.value)}
128 − placeholder="Mot de passe"
129 − className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-white/20"
130 − autoFocus
131 − />
132 − {error && <p className="text-red-400 text-sm text-center">{error}</p>}
133 − <Button type="submit" className="w-full" loading={passwordLoading}>
134 − Accéder
307 + <div className="min-h-screen bg-[#0a0a0a] flex flex-col">
308 + <header className="flex items-center gap-2 px-4 py-3 border-b border-white/10">
309 + <Cloud className="w-5 h-5 text-white" />
310 + <span className="text-sm text-white font-medium">SPB Cloud</span>
311 + </header>
312 + <div className="flex-1 flex items-center justify-center p-4">
313 + <motion.div
314 + initial={{ opacity: 0, y: 20 }}
315 + animate={{ opacity: 1, y: 0 }}
316 + className="w-full max-w-sm"
317 + >
318 + <div className="bg-white/5 border border-white/10 rounded-2xl p-6">
319 + <div className="text-center mb-6">
320 + <div className="w-16 h-16 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-4">
321 + <Lock className="w-8 h-8 text-gray-400" />
322 + </div>
323 + <h1 className="text-lg font-semibold text-white">
324 + Fichier protege
325 + </h1>
326 + <p className="text-sm text-gray-500 mt-1 truncate max-w-[280px] mx-auto">
327 + {fileInfo?.name}
328 + </p>
329 + </div>
330 +
331 + <form onSubmit={handlePasswordSubmit} className="space-y-4">
332 + <input
333 + type="password"
334 + value={password}
335 + onChange={(e) => {
336 + setPassword(e.target.value);
337 + setError("");
338 + }}
339 + placeholder="Mot de passe"
340 + className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-white/20 transition-colors"
341 + autoFocus
342 + />
343 + {error && (
344 + <p className="text-red-400 text-sm text-center">{error}</p>
345 + )}
346 + <Button type="submit" className="w-full" loading={passwordLoading}>
347 + Acceder
348 + </Button>
349 + </form>
350 + </div>
351 + </motion.div>
352 + </div>
353 + <Footer expiresAt={fileInfo?.expiresAt || null} />
354 + </div>
355 + );
356 + }
357 +
358 + // Download-only mode
359 + if (state === "download") {
360 + const category = fileInfo ? getFileCategory(fileInfo.mimeType) : "other";
361 + return (
362 + <div className="min-h-screen bg-[#0a0a0a] flex flex-col">
363 + <Header fileName={fileInfo?.name} fileSize={fileInfo?.size} onDownload={handleDownload} />
364 + <div className="flex-1 flex items-center justify-center p-4">
365 + <motion.div
366 + initial={{ opacity: 0, scale: 0.95 }}
367 + animate={{ opacity: 1, scale: 1 }}
368 + className="text-center"
369 + >
370 + <div className="w-24 h-24 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-6">
371 + {getFileIcon(category)}
372 + </div>
373 + <h2 className="text-lg font-semibold text-white mb-1">
374 + {fileInfo?.name}
375 + </h2>
376 + <p className="text-sm text-gray-500 mb-6">
377 + {fileInfo ? formatSize(fileInfo.size) : ""}
378 + </p>
379 + <Button onClick={handleDownload} size="lg">
380 + <Download className="w-5 h-5" />
381 + Telecharger
135 382 </Button>
136 − </form>
137 − </motion.div>
383 + </motion.div>
384 + </div>
385 + <Footer expiresAt={fileInfo?.expiresAt || null} />
138 386 </div>
139 387 );
140 388 }
141 389
142 − // Preview state — show the file
390 + // Preview mode
391 + const category = fileInfo ? getFileCategory(fileInfo.mimeType) : "other";
392 +
143 393 return (
144 394 <div className="min-h-screen bg-[#0a0a0a] flex flex-col">
145 − <header className="flex items-center justify-between px-4 py-3 border-b border-white/10">
146 − <div className="flex items-center gap-2">
147 − <Cloud className="w-5 h-5 text-white" />
148 − <span className="text-sm text-white font-medium">SPB Cloud</span>
149 − </div>
150 − <Button
151 − size="sm"
152 − onClick={() =>
153 − window.open(`/api/shared/${token}?action=download`, "_blank")
154 − }
395 + <Header fileName={fileInfo?.name} fileSize={fileInfo?.size} onDownload={handleDownload} />
396 +
397 + <main className="flex-1 flex items-center justify-center p-2 sm:p-4 overflow-auto">
398 + <motion.div
399 + initial={{ opacity: 0 }}
400 + animate={{ opacity: 1 }}
401 + transition={{ duration: 0.3 }}
402 + className="w-full h-full flex items-center justify-center"
155 403 >
156 − <Download className="w-4 h-4" />
157 − Télécharger
158 − </Button>
159 − </header>
160 − <main className="flex-1 flex items-center justify-center p-4">
161 − <iframe
162 − src={`/api/shared/${token}`}
163 − className="w-full h-full min-h-[80vh] border-0 rounded-lg"
164 − title="Shared file"
165 − />
404 + {category === "image" && fileInfo && (
405 + <div className="relative flex flex-col items-center gap-3 max-w-full">
406 + <div className="overflow-auto max-h-[75vh] max-w-full rounded-lg">
407 + {passwordVerified ? (
408 + <ProtectedImage
409 + token={token}
410 + password={password}
411 + alt={fileInfo.name}
412 + zoom={imageZoom}
413 + fetchContent={fetchProtectedContent}
414 + />
415 + ) : (
416 + <img
417 + src={contentUrl()}
418 + alt={fileInfo.name}
419 + className="max-w-full object-contain rounded-lg transition-transform duration-200"
420 + style={{ transform: `scale(${imageZoom})`, transformOrigin: "center" }}
421 + />
422 + )}
423 + </div>
424 + <div className="flex items-center gap-2">
425 + <button
426 + onClick={() => setImageZoom((z) => Math.max(0.25, z - 0.25))}
427 + className="p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white transition-colors"
428 + aria-label="Zoom out"
429 + >
430 + <ZoomOut className="w-4 h-4" />
431 + </button>
432 + <span className="text-xs text-gray-400 min-w-[3rem] text-center">
433 + {Math.round(imageZoom * 100)}%
434 + </span>
435 + <button
436 + onClick={() => setImageZoom((z) => Math.min(4, z + 0.25))}
437 + className="p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white transition-colors"
438 + aria-label="Zoom in"
439 + >
440 + <ZoomIn className="w-4 h-4" />
441 + </button>
442 + </div>
443 + </div>
444 + )}
445 +
446 + {category === "pdf" && fileInfo && (
447 + <iframe
448 + src={passwordVerified ? undefined : contentUrl()}
449 + className="w-full h-[80vh] border-0 rounded-lg bg-white"
450 + title={fileInfo.name}
451 + />
452 + )}
453 +
454 + {category === "video" && fileInfo && (
455 + <video
456 + controls
457 + className="max-w-full max-h-[75vh] rounded-lg"
458 + preload="metadata"
459 + >
460 + {!passwordVerified && (
461 + <source src={contentUrl()} type={fileInfo.mimeType} />
462 + )}
463 + Votre navigateur ne supporte pas la lecture video.
464 + </video>
465 + )}
466 +
467 + {category === "audio" && fileInfo && (
468 + <div className="w-full max-w-lg">
469 + <div className="bg-white/5 border border-white/10 rounded-2xl p-8 text-center">
470 + <div className="w-20 h-20 rounded-2xl bg-green-500/10 border border-green-500/20 flex items-center justify-center mx-auto mb-6">
471 + <Music className="w-10 h-10 text-green-400" />
472 + </div>
473 + <h3 className="text-white font-medium mb-4 truncate">
474 + {fileInfo.name}
475 + </h3>
476 + <audio
477 + controls
478 + className="w-full"
479 + preload="metadata"
480 + >
481 + {!passwordVerified && (
482 + <source src={contentUrl()} type={fileInfo.mimeType} />
483 + )}
484 + Votre navigateur ne supporte pas la lecture audio.
485 + </audio>
486 + </div>
487 + </div>
488 + )}
489 +
490 + {category === "text" && (
491 + <div className="w-full max-w-4xl max-h-[75vh] overflow-auto">
492 + <div className="bg-white/5 border border-white/10 rounded-2xl p-4 sm:p-6">
493 + {textContent === null ? (
494 + <div className="flex items-center justify-center py-12">
495 + <Loader2 className="w-6 h-6 text-white animate-spin" />
496 + </div>
497 + ) : (
498 + <pre className="text-sm text-gray-300 whitespace-pre-wrap break-words font-mono leading-relaxed">
499 + {textContent}
500 + </pre>
501 + )}
502 + </div>
503 + </div>
504 + )}
505 +
506 + {category === "other" && fileInfo && (
507 + <div className="text-center">
508 + <div className="w-24 h-24 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center mx-auto mb-6">
509 + {getFileIcon(category)}
510 + </div>
511 + <h2 className="text-lg font-semibold text-white mb-1">
512 + {fileInfo.name}
513 + </h2>
514 + <p className="text-sm text-gray-500 mb-6">
515 + {formatSize(fileInfo.size)}
516 + </p>
517 + <p className="text-xs text-gray-600 mb-4">
518 + Apercu non disponible pour ce type de fichier.
519 + </p>
520 + <Button onClick={handleDownload}>
521 + <Download className="w-4 h-4" />
522 + Telecharger
523 + </Button>
524 + </div>
525 + )}
526 + </motion.div>
166 527 </main>
528 +
529 + <Footer expiresAt={fileInfo?.expiresAt || null} />
167 530 </div>
168 531 );
169 532 }
533 +
534 +// --- Sub-components ---
535 +
536 +function Header({
537 + fileName,
538 + fileSize,
539 + onDownload,
540 +}: {
541 + fileName?: string;
542 + fileSize?: number;
543 + onDownload: () => void;
544 +}) {
545 + return (
546 + <header className="flex items-center justify-between px-4 py-3 border-b border-white/10 bg-[#0a0a0a]/80 backdrop-blur-sm sticky top-0 z-10">
547 + <div className="flex items-center gap-3 min-w-0">
548 + <Cloud className="w-5 h-5 text-white flex-shrink-0" />
549 + <div className="min-w-0">
550 + <p className="text-sm text-white font-medium truncate max-w-[200px] sm:max-w-[400px]">
551 + {fileName || "Fichier"}
552 + </p>
553 + {fileSize !== undefined && fileSize > 0 && (
554 + <p className="text-xs text-gray-500">{formatSize(fileSize)}</p>
555 + )}
556 + </div>
557 + </div>
558 + <Button size="sm" onClick={onDownload}>
559 + <Download className="w-4 h-4" />
560 + <span className="hidden sm:inline">Telecharger</span>
561 + </Button>
562 + </header>
563 + );
564 +}
565 +
566 +function Footer({ expiresAt }: { expiresAt: string | null }) {
567 + const expiryText = formatExpiry(expiresAt);
568 + return (
569 + <footer className="px-4 py-3 border-t border-white/10 text-center">
570 + <p className="text-xs text-gray-600">
571 + Partage via SPB Cloud
572 + {expiryText && (
573 + <span className="ml-2 text-yellow-500/70">
574 + {" "}-- {expiryText}
575 + </span>
576 + )}
577 + </p>
578 + </footer>
579 + );
580 +}
581 +
582 +function ProtectedImage({
583 + token,
584 + password,
585 + alt,
586 + zoom,
587 + fetchContent,
588 +}: {
589 + token: string;
590 + password: string;
591 + alt: string;
592 + zoom: number;
593 + fetchContent: (pw: string, asBlob?: boolean) => Promise<Blob | string>;
594 +}) {
595 + const [src, setSrc] = useState<string | null>(null);
596 +
597 + useEffect(() => {
598 + let revoke = "";
599 + fetchContent(password, true).then((blob) => {
600 + const url = URL.createObjectURL(blob as Blob);
601 + revoke = url;
602 + setSrc(url);
603 + });
604 + return () => {
605 + if (revoke) URL.revokeObjectURL(revoke);
606 + };
607 + }, [token, password, fetchContent]);
608 +
609 + if (!src) {
610 + return (
611 + <div className="flex items-center justify-center py-24">
612 + <Loader2 className="w-6 h-6 text-white animate-spin" />
613 + </div>
614 + );
615 + }
616 +
617 + return (
618 + <img
619 + src={src}
620 + alt={alt}
621 + className="max-w-full object-contain rounded-lg transition-transform duration-200"
622 + style={{ transform: `scale(${zoom})`, transformOrigin: "center" }}
623 + />
624 + );
625 +}
modified components/admin/SharedSpaceManagement.tsx +4 −4
@@ -147,8 +147,8 @@ export default function SharedSpaceManagement() {
147 147 {/* Header */}
148 148 <div className="flex items-start justify-between gap-3 mb-4">
149 149 <div className="flex items-center gap-2 min-w-0">
150 − <div className="w-8 h-8 rounded-lg bg-purple-100 dark:bg-purple-500/20 flex items-center justify-center flex-shrink-0">
151 − <Users className="w-4 h-4 text-purple-600 dark:text-purple-400" />
150 + <div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-600/20 flex items-center justify-center flex-shrink-0">
151 + <Users className="w-4 h-4 text-blue-600 dark:text-blue-400" />
152 152 </div>
153 153 <div className="min-w-0">
154 154 <p className="font-medium text-gray-900 dark:text-white truncate">{space.name}</p>
@@ -173,7 +173,7 @@ export default function SharedSpaceManagement() {
173 173 </div>
174 174 <div className="w-full bg-gray-100 dark:bg-white/10 rounded-full h-1.5">
175 175 <div
176 − className={`h-1.5 rounded-full transition-all ${percent > 90 ? "bg-red-500" : percent > 70 ? "bg-yellow-500" : "bg-purple-500"}`}
176 + className={`h-1.5 rounded-full transition-all ${percent > 90 ? "bg-red-500" : percent > 70 ? "bg-yellow-500" : "bg-blue-700"}`}
177 177 style={{ width: `${percent}%` }}
178 178 />
179 179 </div>
@@ -219,7 +219,7 @@ export default function SharedSpaceManagement() {
219 219 <option key={u.id} value={u.id}>{u.name || u.username}</option>
220 220 ))}
221 221 </select>
222 − <button className="p-2 text-purple-500 hover:text-purple-700 transition-colors">
222 + <button className="p-2 text-blue-600 hover:text-blue-700 transition-colors">
223 223 <UserPlus className="w-5 h-5" />
224 224 </button>
225 225 </div>
added components/admin/SnapshotPanel.tsx +301 −0
@@ -0,0 +1,301 @@
1 +"use client";
2 +
3 +import { useState, useEffect } from "react";
4 +import { motion, AnimatePresence } from "framer-motion";
5 +import {
6 + Clock,
7 + Camera,
8 + RotateCcw,
9 + Trash2,
10 + CheckCircle,
11 + XCircle,
12 + Loader2,
13 + AlertTriangle,
14 + CalendarDays,
15 +} from "lucide-react";
16 +import Button from "../ui/Button";
17 +import { formatFileSize } from "@/lib/utils";
18 +import toast from "react-hot-toast";
19 +
20 +interface SnapshotData {
21 + id: string;
22 + label: string;
23 + snapshotDate: string;
24 + path: string;
25 + size: number;
26 + status: string;
27 + error: string | null;
28 + createdAt: string;
29 +}
30 +
31 +function StatusIcon({ status }: { status: string }) {
32 + if (status === "completed") return <CheckCircle className="w-4 h-4 text-emerald-500 flex-shrink-0" />;
33 + if (status === "failed") return <XCircle className="w-4 h-4 text-red-500 flex-shrink-0" />;
34 + return <Loader2 className="w-4 h-4 text-blue-400 animate-spin flex-shrink-0" />;
35 +}
36 +
37 +function isToday(dateStr: string): boolean {
38 + return new Date().toISOString().split("T")[0] === dateStr;
39 +}
40 +
41 +export default function SnapshotPanel() {
42 + const [snapshots, setSnapshots] = useState<SnapshotData[]>([]);
43 + const [loading, setLoading] = useState(true);
44 + const [creating, setCreating] = useState(false);
45 + const [restoringId, setRestoringId] = useState<string | null>(null);
46 + const [deletingId, setDeletingId] = useState<string | null>(null);
47 + const [confirmRestore, setConfirmRestore] = useState<SnapshotData | null>(null);
48 +
49 + const fetchSnapshots = async () => {
50 + const res = await fetch("/api/snapshots");
51 + if (res.ok) setSnapshots(await res.json());
52 + setLoading(false);
53 + };
54 +
55 + useEffect(() => {
56 + fetchSnapshots();
57 + }, []);
58 +
59 + const handleCreate = async () => {
60 + setCreating(true);
61 + try {
62 + const res = await fetch("/api/snapshots", { method: "POST" });
63 + if (res.ok) {
64 + toast.success("Snapshot créé");
65 + await fetchSnapshots();
66 + } else {
67 + const data = await res.json();
68 + toast.error(data.error || "Échec du snapshot");
69 + }
70 + } catch {
71 + toast.error("Erreur réseau");
72 + }
73 + setCreating(false);
74 + };
75 +
76 + const handleRestore = async (snapshot: SnapshotData) => {
77 + setConfirmRestore(null);
78 + setRestoringId(snapshot.id);
79 + try {
80 + const res = await fetch(`/api/snapshots/${snapshot.id}/restore`, { method: "POST" });
81 + if (res.ok) {
82 + toast.success(`Restauré au ${snapshot.label}`);
83 + await fetchSnapshots();
84 + } else {
85 + const data = await res.json();
86 + toast.error(data.error || "Échec de la restauration");
87 + }
88 + } catch {
89 + toast.error("Erreur réseau");
90 + }
91 + setRestoringId(null);
92 + };
93 +
94 + const handleDelete = async (id: string) => {
95 + setDeletingId(id);
96 + try {
97 + const res = await fetch(`/api/snapshots/${id}`, { method: "DELETE" });
98 + if (res.ok) {
99 + toast.success("Snapshot supprimé");
100 + setSnapshots((prev) => prev.filter((s) => s.id !== id));
101 + } else {
102 + toast.error("Échec de la suppression");
103 + }
104 + } catch {
105 + toast.error("Erreur réseau");
106 + }
107 + setDeletingId(null);
108 + };
109 +
110 + const todayHasSnapshot = snapshots.some(
111 + (s) => isToday(s.snapshotDate) && s.status === "completed"
112 + );
113 +
114 + return (
115 + <div className="space-y-5">
116 + {/* Header */}
117 + <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
118 + <div>
119 + <h2 className="text-lg font-medium text-gray-900 dark:text-white flex items-center gap-2">
120 + <Clock className="w-5 h-5 text-blue-400" />
121 + Snapshots quotidiens
122 + </h2>
123 + <p className="text-sm text-gray-500 mt-0.5">
124 + 7 jours conservés · restauration en un clic
125 + </p>
126 + </div>
127 + <Button
128 + size="sm"
129 + onClick={handleCreate}
130 + loading={creating}
131 + className="gap-2"
132 + >
133 + <Camera className="w-4 h-4" />
134 + {todayHasSnapshot ? "Re-snapshot maintenant" : "Snapshot maintenant"}
135 + </Button>
136 + </div>
137 +
138 + {/* Auto info banner */}
139 + <div className="flex items-start gap-2 p-3 bg-blue-500/10 border border-blue-500/20 rounded-xl text-sm text-blue-400">
140 + <CalendarDays className="w-4 h-4 mt-0.5 flex-shrink-0" />
141 + <span>
142 + Un snapshot automatique est créé chaque jour au premier démarrage du serveur.
143 + Les plus anciens sont supprimés automatiquement.
144 + </span>
145 + </div>
146 +
147 + {/* Snapshot list */}
148 + {loading ? (
149 + <div className="flex justify-center py-10">
150 + <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
151 + </div>
152 + ) : snapshots.length === 0 ? (
153 + <div className="text-center py-12 text-gray-500">
154 + <Clock className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
155 + <p className="font-medium">Aucun snapshot</p>
156 + <p className="text-sm mt-1">Créez votre premier snapshot manuellement ou attendez le démarrage automatique.</p>
157 + </div>
158 + ) : (
159 + <div className="relative space-y-2">
160 + {/* Vertical timeline line */}
161 + <div className="absolute left-[22px] top-4 bottom-4 w-px bg-gray-200 dark:bg-white/10 pointer-events-none" />
162 +
163 + {snapshots.map((snapshot, i) => {
164 + const today = isToday(snapshot.snapshotDate);
165 + return (
166 + <motion.div
167 + key={snapshot.id}
168 + initial={{ opacity: 0, x: -8 }}
169 + animate={{ opacity: 1, x: 0 }}
170 + transition={{ delay: i * 0.04 }}
171 + className={`relative flex flex-col sm:flex-row sm:items-center gap-3 p-3 pl-12 rounded-xl border transition-colors ${
172 + today
173 + ? "bg-blue-500/10 border-blue-500/30 dark:border-blue-500/30"
174 + : "bg-white dark:bg-white/5 border-gray-200 dark:border-white/10"
175 + }`}
176 + >
177 + {/* Timeline dot */}
178 + <div
179 + className={`absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 rounded-full border-2 flex items-center justify-center ${
180 + snapshot.status === "completed"
181 + ? today
182 + ? "bg-blue-500 border-blue-400"
183 + : "bg-emerald-500 border-emerald-400"
184 + : snapshot.status === "failed"
185 + ? "bg-red-500 border-red-400"
186 + : "bg-gray-400 border-gray-300"
187 + }`}
188 + />
189 +
190 + {/* Info */}
191 + <div className="flex-1 min-w-0">
192 + <div className="flex items-center gap-2 flex-wrap">
193 + <p className="text-sm font-medium text-gray-900 dark:text-white capitalize truncate">
194 + {snapshot.label}
195 + </p>
196 + {today && (
197 + <span className="text-[10px] font-semibold px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded-full uppercase tracking-wide">
198 + Aujourd&apos;hui
199 + </span>
200 + )}
201 + <StatusIcon status={snapshot.status} />
202 + </div>
203 + <p className="text-xs text-gray-500 mt-0.5">
204 + {snapshot.status === "completed"
205 + ? formatFileSize(snapshot.size)
206 + : snapshot.status === "failed"
207 + ? snapshot.error || "Erreur inconnue"
208 + : "En cours…"}
209 + {snapshot.status === "completed" && (
210 + <> · {new Date(snapshot.createdAt).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })}</>
211 + )}
212 + </p>
213 + </div>
214 +
215 + {/* Actions */}
216 + {snapshot.status === "completed" && (
217 + <div className="flex gap-1 pl-0 sm:pl-0">
218 + <button
219 + onClick={() => setConfirmRestore(snapshot)}
220 + disabled={restoringId === snapshot.id}
221 + title="Restaurer"
222 + className="min-w-[44px] min-h-[44px] flex items-center justify-center p-2.5 text-gray-400 hover:text-blue-400 dark:hover:text-blue-400 rounded-lg transition-colors disabled:opacity-50"
223 + >
224 + {restoringId === snapshot.id ? (
225 + <Loader2 className="w-4 h-4 animate-spin" />
226 + ) : (
227 + <RotateCcw className="w-4 h-4" />
228 + )}
229 + </button>
230 + <button
231 + onClick={() => handleDelete(snapshot.id)}
232 + disabled={deletingId === snapshot.id}
233 + title="Supprimer"
234 + className="min-w-[44px] min-h-[44px] flex items-center justify-center p-2.5 text-gray-400 hover:text-red-500 rounded-lg transition-colors disabled:opacity-50"
235 + >
236 + {deletingId === snapshot.id ? (
237 + <Loader2 className="w-4 h-4 animate-spin" />
238 + ) : (
239 + <Trash2 className="w-4 h-4" />
240 + )}
241 + </button>
242 + </div>
243 + )}
244 + </motion.div>
245 + );
246 + })}
247 + </div>
248 + )}
249 +
250 + {/* Restore confirmation modal */}
251 + <AnimatePresence>
252 + {confirmRestore && (
253 + <motion.div
254 + initial={{ opacity: 0 }}
255 + animate={{ opacity: 1 }}
256 + exit={{ opacity: 0 }}
257 + className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
258 + onClick={() => setConfirmRestore(null)}
259 + >
260 + <motion.div
261 + initial={{ scale: 0.95, opacity: 0 }}
262 + animate={{ scale: 1, opacity: 1 }}
263 + exit={{ scale: 0.95, opacity: 0 }}
264 + onClick={(e) => e.stopPropagation()}
265 + className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-white/10 rounded-2xl p-6 w-full max-w-md shadow-2xl"
266 + >
267 + <div className="flex items-center gap-3 mb-4">
268 + <div className="w-10 h-10 rounded-xl bg-amber-500/15 flex items-center justify-center flex-shrink-0">
269 + <AlertTriangle className="w-5 h-5 text-amber-400" />
270 + </div>
271 + <div>
272 + <h3 className="font-semibold text-gray-900 dark:text-white">Restaurer le snapshot ?</h3>
273 + <p className="text-sm text-gray-500 capitalize">{confirmRestore.label}</p>
274 + </div>
275 + </div>
276 + <p className="text-sm text-gray-600 dark:text-gray-400 mb-6">
277 + Tous vos fichiers et la base de données seront remplacés par ceux du snapshot sélectionné.
278 + <strong className="text-gray-900 dark:text-white"> Cette action est irréversible.</strong>
279 + </p>
280 + <div className="flex gap-3">
281 + <Button
282 + variant="secondary"
283 + className="flex-1"
284 + onClick={() => setConfirmRestore(null)}
285 + >
286 + Annuler
287 + </Button>
288 + <button
289 + onClick={() => handleRestore(confirmRestore)}
290 + className="flex-1 px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white rounded-xl font-medium transition-colors text-sm"
291 + >
292 + Oui, restaurer
293 + </button>
294 + </div>
295 + </motion.div>
296 + </motion.div>
297 + )}
298 + </AnimatePresence>
299 + </div>
300 + );
301 +}
modified components/admin/StatsCards.tsx +2 −2
@@ -37,8 +37,8 @@ const cards = [
37 37 label: "Dossiers",
38 38 icon: Folder,
39 39 format: (v: number) => String(v),
40 − color: "text-purple-500 dark:text-purple-400",
41 − bgColor: "bg-purple-100 dark:bg-purple-500/10",
40 + color: "text-blue-600 dark:text-blue-400",
41 + bgColor: "bg-blue-100 dark:bg-blue-500/10",
42 42 },
43 43 {
44 44 key: "shareCount",
modified components/admin/UserManagement.tsx +1 −1
@@ -133,7 +133,7 @@ export default function UserManagement() {
133 133 {user.role}
134 134 </span>
135 135 {user.twoFactorEnabled && (
136 − <Shield className="w-4 h-4 text-green-500 flex-shrink-0" title="2FA activé" />
136 + <Shield className="w-4 h-4 text-green-500 flex-shrink-0" aria-label="2FA activé" />
137 137 )}
138 138 <span className="text-xs text-gray-500 hidden sm:block">
139 139 {user._count?.files || 0} fichiers
modified components/ai/AiPanel.tsx +279 −73
@@ -21,6 +21,9 @@ import {
21 21 Download,
22 22 FlaskConical,
23 23 AlertCircle,
24 + Wrench,
25 + CheckCircle2,
26 + Bot,
24 27 } from "lucide-react";
25 28 import ReactMarkdown from "react-markdown";
26 29 import remarkGfm from "remark-gfm";
@@ -36,9 +39,17 @@ interface AiResult {
36 39 mimeType?: string;
37 40 }
38 41
42 +interface ToolEvent {
43 + id: string;
44 + name: string;
45 + input: Record<string, unknown>;
46 + result?: string;
47 +}
48 +
39 49 interface ChatMessage {
40 50 role: "user" | "assistant";
41 51 content: string;
52 + toolEvents?: ToolEvent[];
42 53 }
43 54
44 55 interface AnalyserFile {
@@ -73,7 +84,7 @@ const mimeIcon = (mime: string) => {
73 84 };
74 85
75 86 const inputClasses =
76 − "w-full bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg px-4 py-3 text-gray-900 dark:text-white text-sm focus:outline-none focus:border-purple-400 dark:focus:border-purple-500 placeholder-gray-400 dark:placeholder-gray-500";
87 + "w-full bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg px-4 py-3 text-gray-900 dark:text-white text-sm focus:outline-none focus:border-blue-600 dark:focus:border-blue-700 placeholder-gray-400 dark:placeholder-gray-500";
77 88
78 89 // Markdown renderer with code syntax highlighting
79 90 function MarkdownContent({ content }: { content: string }) {
@@ -101,7 +112,7 @@ function MarkdownContent({ content }: { content: string }) {
101 112 }
102 113 return (
103 114 <code
104 − className="bg-gray-200 dark:bg-white/15 px-1.5 py-0.5 rounded text-[11px] font-mono text-purple-700 dark:text-purple-300"
115 + className="bg-gray-200 dark:bg-white/15 px-1.5 py-0.5 rounded text-[11px] font-mono text-blue-700 dark:text-blue-300"
105 116 {...props}
106 117 >
107 118 {children}
@@ -113,7 +124,7 @@ function MarkdownContent({ content }: { content: string }) {
113 124 },
114 125 a({ href, children }) {
115 126 return (
116 − <a href={href} target="_blank" rel="noopener noreferrer" className="text-purple-500 underline underline-offset-2 hover:text-purple-400">
127 + <a href={href} target="_blank" rel="noopener noreferrer" className="text-blue-500 underline underline-offset-2 hover:text-purple-400">
117 128 {children}
118 129 </a>
119 130 );
@@ -126,6 +137,71 @@ function MarkdownContent({ content }: { content: string }) {
126 137 );
127 138 }
128 139
140 +const TOOL_LABELS: Record<string, string> = {
141 + list_files: "Lister les fichiers",
142 + list_folders: "Lister les dossiers",
143 + create_folder: "Créer un dossier",
144 + rename_file: "Renommer un fichier",
145 + move_file: "Déplacer un fichier",
146 + rename_folder: "Renommer un dossier",
147 + move_folder: "Déplacer un dossier",
148 + delete_file: "Supprimer un fichier",
149 + list_shared_spaces: "Lister les espaces partagés",
150 + rename_shared_space: "Renommer un espace partagé",
151 +};
152 +
153 +function ToolCard({ event }: { event: ToolEvent }) {
154 + const label = TOOL_LABELS[event.name] ?? event.name;
155 + const hasResult = event.result !== undefined;
156 +
157 + let resultObj: Record<string, unknown> | null = null;
158 + try {
159 + resultObj = event.result ? JSON.parse(event.result) : null;
160 + } catch {}
161 +
162 + const isError = resultObj && "error" in resultObj;
163 +
164 + return (
165 + <div className="my-1 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 overflow-hidden text-[11px]">
166 + <div className="flex items-center gap-1.5 px-2.5 py-1.5 bg-gray-100 dark:bg-white/10 border-b border-gray-200 dark:border-white/10">
167 + <Wrench className="w-3 h-3 text-blue-600 flex-shrink-0" />
168 + <span className="font-medium text-gray-700 dark:text-gray-300 flex-1">{label}</span>
169 + {hasResult ? (
170 + isError ? (
171 + <span className="text-red-500 text-[10px]">Erreur</span>
172 + ) : (
173 + <CheckCircle2 className="w-3.5 h-3.5 text-green-500 flex-shrink-0" />
174 + )
175 + ) : (
176 + <Loader2 className="w-3 h-3 animate-spin text-purple-400 flex-shrink-0" />
177 + )}
178 + </div>
179 + {Object.keys(event.input).length > 0 && (
180 + <div className="px-2.5 py-1 font-mono text-[10px] text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-white/5">
181 + {Object.entries(event.input)
182 + .map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
183 + .join(" · ")}
184 + </div>
185 + )}
186 + {hasResult && resultObj && (
187 + <div className={`px-2.5 py-1.5 text-[10px] font-mono ${isError ? "text-red-500" : "text-green-600 dark:text-green-400"}`}>
188 + {isError
189 + ? String((resultObj as { error: unknown }).error)
190 + : resultObj.success
191 + ? resultObj.deleted
192 + ? `Supprimé: ${resultObj.deleted}`
193 + : resultObj.newName
194 + ? `→ ${resultObj.newName}`
195 + : resultObj.count !== undefined
196 + ? `${resultObj.count} élément(s)`
197 + : "OK"
198 + : JSON.stringify(resultObj).slice(0, 120)}
199 + </div>
200 + )}
201 + </div>
202 + );
203 +}
204 +
129 205 export default function AiPanel() {
130 206 const [open, setOpen] = useState(false);
131 207 const [tab, setTab] = useState<Tab>("chat");
@@ -141,6 +217,9 @@ export default function AiPanel() {
141 217 const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
142 218 const [isStreaming, setIsStreaming] = useState(false);
143 219 const [streamingContent, setStreamingContent] = useState("");
220 + const [agentMode, setAgentMode] = useState(false);
221 + const [streamingEvents, setStreamingEvents] = useState<ToolEvent[]>([]);
222 + const streamingEventsRef = useRef<ToolEvent[]>([]);
144 223 const chatEndRef = useRef<HTMLDivElement>(null);
145 224
146 225 // Analyser state
@@ -220,55 +299,119 @@ export default function AiPanel() {
220 299 handleSearch(q);
221 300 };
222 301
223 − // ─── Chat (streaming) ──────────────────────────────────────
302 + // ─── Chat (streaming, dual-mode) ──────────────────────────
224 303 const handleChat = async () => {
225 304 const msg = chatInput.trim();
226 305 if (!msg || isStreaming) return;
227 306 setChatInput("");
228 307
229 − const historyToSend = [...chatHistory];
308 + const historyToSend = chatHistory.map(({ role, content }) => ({ role, content }));
230 309 setChatHistory((prev) => [...prev, { role: "user", content: msg }]);
231 310 setIsStreaming(true);
232 311 setStreamingContent("");
312 + streamingEventsRef.current = [];
313 + setStreamingEvents([]);
233 314
234 315 try {
235 − const res = await fetch("/api/ai/chat", {
236 − method: "POST",
237 − headers: { "Content-Type": "application/json" },
238 − body: JSON.stringify({ message: msg, history: historyToSend, stream: true }),
239 − });
316 + if (agentMode) {
317 + // ── Agent mode: /api/ai/agent with tool_use loop ──
318 + const res = await fetch("/api/ai/agent", {
319 + method: "POST",
320 + headers: { "Content-Type": "application/json" },
321 + body: JSON.stringify({ message: msg, history: historyToSend }),
322 + });
323 +
324 + if (!res.ok || !res.body) throw new Error("Agent stream error");
325 +
326 + const reader = res.body.getReader();
327 + const decoder = new TextDecoder();
328 + let accumulated = "";
329 + let buffer = "";
330 +
331 + while (true) {
332 + const { done, value } = await reader.read();
333 + if (done) break;
334 + buffer += decoder.decode(value, { stream: true });
335 + const lines = buffer.split("\n\n");
336 + buffer = lines.pop() ?? "";
337 +
338 + for (const line of lines) {
339 + if (!line.startsWith("data: ")) continue;
340 + const raw = line.slice(6).trim();
341 + try {
342 + const evt = JSON.parse(raw);
343 +
344 + if (evt.type === "token") {
345 + accumulated += evt.token;
346 + setStreamingContent(accumulated);
347 + } else if (evt.type === "tool_call") {
348 + const newEvt: ToolEvent = {
349 + id: evt.id,
350 + name: evt.name,
351 + input: evt.input ?? {},
352 + };
353 + streamingEventsRef.current = [...streamingEventsRef.current, newEvt];
354 + setStreamingEvents([...streamingEventsRef.current]);
355 + } else if (evt.type === "tool_result") {
356 + streamingEventsRef.current = streamingEventsRef.current.map((e) =>
357 + e.id === evt.id ? { ...e, result: evt.result } : e
358 + );
359 + setStreamingEvents([...streamingEventsRef.current]);
360 + } else if (evt.type === "done") {
361 + break;
362 + }
363 + } catch {}
364 + }
365 + }
240 366
241 − if (!res.ok || !res.body) throw new Error("Stream error");
242 −
243 − const reader = res.body.getReader();
244 − const decoder = new TextDecoder();
245 − let accumulated = "";
246 − let buffer = "";
247 −
248 − while (true) {
249 − const { done, value } = await reader.read();
250 − if (done) break;
251 − buffer += decoder.decode(value, { stream: true });
252 − const lines = buffer.split("\n\n");
253 − buffer = lines.pop() ?? "";
254 − for (const line of lines) {
255 − if (!line.startsWith("data: ")) continue;
256 − const data = line.slice(6).trim();
257 − if (data === "[DONE]") break;
258 − try {
259 − const parsed = JSON.parse(data);
260 − if (parsed.token) {
261 − accumulated += parsed.token;
262 − setStreamingContent(accumulated);
263 − }
264 − } catch {}
367 + setChatHistory((prev) => [
368 + ...prev,
369 + {
370 + role: "assistant",
371 + content: accumulated || "",
372 + toolEvents: [...streamingEventsRef.current],
373 + },
374 + ]);
375 + } else {
376 + // ── Normal chat mode: /api/ai/chat ──
377 + const res = await fetch("/api/ai/chat", {
378 + method: "POST",
379 + headers: { "Content-Type": "application/json" },
380 + body: JSON.stringify({ message: msg, history: historyToSend, stream: true }),
381 + });
382 +
383 + if (!res.ok || !res.body) throw new Error("Stream error");
384 +
385 + const reader = res.body.getReader();
386 + const decoder = new TextDecoder();
387 + let accumulated = "";
388 + let buffer = "";
389 +
390 + while (true) {
391 + const { done, value } = await reader.read();
392 + if (done) break;
393 + buffer += decoder.decode(value, { stream: true });
394 + const lines = buffer.split("\n\n");
395 + buffer = lines.pop() ?? "";
396 + for (const line of lines) {
397 + if (!line.startsWith("data: ")) continue;
398 + const data = line.slice(6).trim();
399 + if (data === "[DONE]") break;
400 + try {
401 + const parsed = JSON.parse(data);
402 + if (parsed.token) {
403 + accumulated += parsed.token;
404 + setStreamingContent(accumulated);
405 + }
406 + } catch {}
407 + }
265 408 }
266 − }
267 409
268 − setChatHistory((prev) => [
269 − ...prev,
270 − { role: "assistant", content: accumulated || "Désolé, aucune réponse." },
271 − ]);
410 + setChatHistory((prev) => [
411 + ...prev,
412 + { role: "assistant", content: accumulated || "Désolé, aucune réponse." },
413 + ]);
414 + }
272 415 } catch {
273 416 setChatHistory((prev) => [
274 417 ...prev,
@@ -277,6 +420,8 @@ export default function AiPanel() {
277 420 } finally {
278 421 setIsStreaming(false);
279 422 setStreamingContent("");
423 + streamingEventsRef.current = [];
424 + setStreamingEvents([]);
280 425 }
281 426 };
282 427
@@ -336,7 +481,7 @@ export default function AiPanel() {
336 481 {/* Toggle Button */}
337 482 <button
338 483 onClick={() => setOpen(true)}
339 − className="fixed bottom-20 right-4 sm:bottom-6 sm:right-6 z-40 w-14 h-14 rounded-full bg-purple-600 hover:bg-purple-700 text-white shadow-lg flex items-center justify-center transition-colors"
484 + className="fixed bottom-20 right-4 sm:bottom-6 sm:right-6 z-40 w-14 h-14 rounded-full bg-blue-800 hover:bg-blue-900 text-white shadow-lg flex items-center justify-center transition-colors"
340 485 title="Assistant IA"
341 486 >
342 487 <Brain className="w-6 h-6" />
@@ -385,7 +530,7 @@ export default function AiPanel() {
385 530 onClick={() => setTab(t)}
386 531 className={`flex-1 px-2 py-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${
387 532 tab === t
388 − ? "text-purple-600 dark:text-purple-400 border-b-2 border-purple-500"
533 + ? "text-blue-700 dark:text-blue-400 border-b-2 border-blue-700"
389 534 : "text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
390 535 }`}
391 536 >
@@ -402,20 +547,43 @@ export default function AiPanel() {
402 547 <div className="flex-1 overflow-auto p-4 space-y-3">
403 548 {chatHistory.length === 0 && !isStreaming && (
404 549 <div className="text-center py-6">
405 − <Brain className="w-8 h-8 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
406 − <p className="text-sm text-gray-500 mb-4">Posez une question sur vos fichiers</p>
550 + {agentMode ? (
551 + <Bot className="w-8 h-8 mx-auto mb-3 text-violet-400" />
552 + ) : (
553 + <Brain className="w-8 h-8 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
554 + )}
555 + <p className="text-sm text-gray-500 mb-4">
556 + {agentMode
557 + ? "Mode Agent — donnez un ordre, l'IA agit sur vos fichiers"
558 + : "Posez une question sur vos fichiers"}
559 + </p>
407 560 <div className="space-y-2 text-left">
408 − {[
409 − "Résume mes fichiers récents",
410 − "Quels sont mes documents importants ?",
411 − "Aide-moi à organiser mes fichiers",
412 − ].map((prompt) => (
561 + {(agentMode
562 + ? [
563 + "Liste les fichiers à la racine",
564 + "Crée un dossier Images et mets-y tous les .jpg",
565 + "Renomme tous les fichiers PDF avec le préfixe doc_",
566 + ]
567 + : [
568 + "Résume mes fichiers récents",
569 + "Quels sont mes documents importants ?",
570 + "Aide-moi à organiser mes fichiers",
571 + ]
572 + ).map((prompt) => (
413 573 <button
414 574 key={prompt}
415 575 onClick={() => setChatInput(prompt)}
416 − className="w-full text-left px-3 py-2 rounded-lg bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-xs text-gray-600 dark:text-gray-400 hover:bg-purple-50 dark:hover:bg-purple-500/10 hover:border-purple-200 dark:hover:border-purple-500/30 transition-colors"
576 + className={`w-full text-left px-3 py-2 rounded-lg border text-xs transition-colors ${
577 + agentMode
578 + ? "bg-violet-50 dark:bg-violet-500/5 border-violet-200 dark:border-violet-500/20 text-violet-700 dark:text-violet-300 hover:bg-violet-100 dark:hover:bg-violet-500/15"
579 + : "bg-gray-50 dark:bg-white/5 border-gray-200 dark:border-white/10 text-gray-600 dark:text-gray-400 hover:bg-blue-50 dark:hover:bg-blue-500/10 hover:border-blue-200 dark:hover:border-blue-500/30"
580 + }`}
417 581 >
418 − <Zap className="w-3 h-3 inline mr-1.5 text-purple-400" />
582 + {agentMode ? (
583 + <Wrench className="w-3 h-3 inline mr-1.5 text-violet-400" />
584 + ) : (
585 + <Zap className="w-3 h-3 inline mr-1.5 text-purple-400" />
586 + )}
419 587 {prompt}
420 588 </button>
421 589 ))}
@@ -426,19 +594,28 @@ export default function AiPanel() {
426 594 {chatHistory.map((msg, i) => (
427 595 <div key={i} className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
428 596 {msg.role === "assistant" && (
429 − <div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-500/20 flex items-center justify-center flex-shrink-0 mr-2 mt-0.5">
430 − <Brain className="w-3 h-3 text-purple-600 dark:text-purple-400" />
597 + <div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-800/30 flex items-center justify-center flex-shrink-0 mr-2 mt-0.5">
598 + <Brain className="w-3 h-3 text-blue-700 dark:text-blue-400" />
431 599 </div>
432 600 )}
433 601 <div
434 − className={`max-w-[82%] px-3 py-2.5 rounded-2xl text-sm leading-relaxed ${
602 + className={`max-w-[88%] px-3 py-2.5 rounded-2xl text-sm leading-relaxed ${
435 603 msg.role === "user"
436 − ? "bg-purple-600 text-white rounded-tr-sm"
604 + ? "bg-blue-800 text-white rounded-tr-sm"
437 605 : "bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-gray-100 rounded-tl-sm"
438 606 }`}
439 607 >
440 608 {msg.role === "assistant" ? (
441 − <MarkdownContent content={msg.content} />
609 + <>
610 + {msg.toolEvents && msg.toolEvents.length > 0 && (
611 + <div className="mb-2 space-y-1">
612 + {msg.toolEvents.map((e) => (
613 + <ToolCard key={e.id} event={e} />
614 + ))}
615 + </div>
616 + )}
617 + {msg.content && <MarkdownContent content={msg.content} />}
618 + </>
442 619 ) : (
443 620 msg.content
444 621 )}
@@ -448,16 +625,23 @@ export default function AiPanel() {
448 625
449 626 {isStreaming && (
450 627 <div className="flex justify-start">
451 − <div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-500/20 flex items-center justify-center flex-shrink-0 mr-2 mt-0.5">
452 − <Brain className="w-3 h-3 text-purple-600 dark:text-purple-400" />
628 + <div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-800/30 flex items-center justify-center flex-shrink-0 mr-2 mt-0.5">
629 + <Brain className="w-3 h-3 text-blue-700 dark:text-blue-400" />
453 630 </div>
454 − <div className="max-w-[82%] px-3 py-2.5 rounded-2xl rounded-tl-sm bg-gray-100 dark:bg-white/10 text-sm text-gray-900 dark:text-gray-100 leading-relaxed">
631 + <div className="max-w-[88%] px-3 py-2.5 rounded-2xl rounded-tl-sm bg-gray-100 dark:bg-white/10 text-sm text-gray-900 dark:text-gray-100 leading-relaxed">
632 + {streamingEvents.length > 0 && (
633 + <div className="mb-2 space-y-1">
634 + {streamingEvents.map((e) => (
635 + <ToolCard key={e.id} event={e} />
636 + ))}
637 + </div>
638 + )}
455 639 {streamingContent ? (
456 640 <MarkdownContent content={streamingContent} />
457 641 ) : (
458 642 <span className="flex items-center gap-1">
459 643 {[0, 150, 300].map((d) => (
460 − <span key={d} className="w-1.5 h-1.5 bg-purple-500 rounded-full animate-bounce" style={{ animationDelay: `${d}ms` }} />
644 + <span key={d} className="w-1.5 h-1.5 bg-blue-700 rounded-full animate-bounce" style={{ animationDelay: `${d}ms` }} />
461 645 ))}
462 646 </span>
463 647 )}
@@ -468,13 +652,35 @@ export default function AiPanel() {
468 652 </div>
469 653
470 654 <div className="p-4 border-t border-gray-200 dark:border-white/10">
471 − {chatHistory.length > 0 && (
655 + <div className="flex items-center justify-between mb-2">
656 + {chatHistory.length > 0 ? (
657 + <button
658 + onClick={() => setChatHistory([])}
659 + className="flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors"
660 + >
661 + <Trash2 className="w-3 h-3" /> Effacer
662 + </button>
663 + ) : (
664 + <span />
665 + )}
472 666 <button
473 − onClick={() => setChatHistory([])}
474 − className="flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors mb-2"
667 + onClick={() => setAgentMode((v) => !v)}
668 + className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-medium transition-colors ${
669 + agentMode
670 + ? "bg-violet-600 text-white"
671 + : "bg-gray-100 dark:bg-white/10 text-gray-500 dark:text-gray-400 hover:bg-violet-50 dark:hover:bg-violet-500/10 hover:text-violet-600 dark:hover:text-violet-400"
672 + }`}
673 + title={agentMode ? "Mode Agent actif — l'IA peut agir sur vos fichiers" : "Activer le Mode Agent"}
475 674 >
476 − <Trash2 className="w-3 h-3" /> Effacer la conversation
675 + <Bot className="w-3 h-3" />
676 + Mode Agent
477 677 </button>
678 + </div>
679 + {agentMode && (
680 + <p className="text-[10px] text-violet-600 dark:text-violet-400 mb-2 flex items-center gap-1">
681 + <Wrench className="w-2.5 h-2.5" />
682 + L&apos;agent peut lister, créer, renommer, déplacer et supprimer des fichiers.
683 + </p>
478 684 )}
479 685 <div className="flex gap-2">
480 686 <input
@@ -482,14 +688,14 @@ export default function AiPanel() {
482 688 value={chatInput}
483 689 onChange={(e) => setChatInput(e.target.value)}
484 690 onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && handleChat()}
485 − placeholder="Votre message..."
691 + placeholder={agentMode ? "Ex: crée un dossier Images et mets-y tous les .jpg..." : "Votre message..."}
486 692 className={`${inputClasses} flex-1`}
487 693 disabled={isStreaming}
488 694 />
489 695 <button
490 696 onClick={handleChat}
491 697 disabled={isStreaming || !chatInput.trim()}
492 − className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-lg bg-purple-600 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-colors"
698 + className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-lg bg-blue-800 hover:bg-blue-900 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-colors"
493 699 >
494 700 {isStreaming ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
495 701 </button>
@@ -513,7 +719,7 @@ export default function AiPanel() {
513 719 <button
514 720 onClick={() => handleSearch()}
515 721 disabled={searching || !query.trim()}
516 − className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-lg bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white transition-colors"
722 + className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-lg bg-blue-800 hover:bg-blue-900 disabled:opacity-50 text-white transition-colors"
517 723 >
518 724 {searching ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
519 725 </button>
@@ -545,7 +751,7 @@ export default function AiPanel() {
545 751
546 752 {answer && (
547 753 <div className="bg-purple-50 dark:bg-purple-500/10 border border-purple-200 dark:border-purple-500/20 rounded-lg p-3.5">
548 − <p className="text-xs font-medium text-purple-600 dark:text-purple-400 mb-1 flex items-center gap-1">
754 + <p className="text-xs font-medium text-blue-700 dark:text-blue-400 mb-1 flex items-center gap-1">
549 755 <Brain className="w-3 h-3" /> Synthèse IA
550 756 </p>
551 757 <p className="text-sm text-purple-800 dark:text-purple-300">{answer}</p>
@@ -582,7 +788,7 @@ export default function AiPanel() {
582 788 mimeType: r.mimeType || "",
583 789 size: 0,
584 790 })}
585 − className="flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] font-medium text-purple-600 dark:text-purple-400 bg-purple-50 dark:bg-purple-500/10 rounded-lg hover:bg-purple-100 dark:hover:bg-purple-500/20 transition-colors"
791 + className="flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] font-medium text-blue-700 dark:text-blue-400 bg-purple-50 dark:bg-purple-500/10 rounded-lg hover:bg-purple-100 dark:hover:bg-purple-500/20 transition-colors"
586 792 >
587 793 <FlaskConical className="w-3 h-3" /> Analyser
588 794 </button>
@@ -695,7 +901,7 @@ export default function AiPanel() {
695 901 <div className="p-3 bg-purple-50 dark:bg-purple-500/10 border border-purple-200 dark:border-purple-500/20 rounded-lg">
696 902 <div className="flex items-start justify-between gap-2">
697 903 <div className="min-w-0">
698 − <p className="text-xs text-purple-600 dark:text-purple-400 font-medium mb-0.5">Fichier sélectionné</p>
904 + <p className="text-xs text-blue-700 dark:text-blue-400 font-medium mb-0.5">Fichier sélectionné</p>
699 905 <p className="text-sm font-medium text-purple-900 dark:text-purple-200 truncate">{selectedFile.name}</p>
700 906 {selectedFile.folder && <p className="text-xs text-purple-400 mt-0.5">📁 {selectedFile.folder.name}</p>}
701 907 </div>
@@ -708,7 +914,7 @@ export default function AiPanel() {
708 914 </button>
709 915 </div>
710 916 {selectedFile.aiDescription && (
711 − <p className="text-xs text-purple-600 dark:text-purple-400 mt-2 border-t border-purple-200 dark:border-purple-500/30 pt-2">{selectedFile.aiDescription}</p>
917 + <p className="text-xs text-blue-700 dark:text-blue-400 mt-2 border-t border-purple-200 dark:border-purple-500/30 pt-2">{selectedFile.aiDescription}</p>
712 918 )}
713 919 {selectedFile.aiTags && (() => {
714 920 try {
@@ -716,7 +922,7 @@ export default function AiPanel() {
716 922 return (
717 923 <div className="flex flex-wrap gap-1 mt-1.5">
718 924 {tags.map((t) => (
719 − <span key={t} className="px-1.5 py-0.5 bg-purple-200 dark:bg-purple-500/30 text-purple-700 dark:text-purple-300 rounded text-[10px]">{t}</span>
925 + <span key={t} className="px-1.5 py-0.5 bg-purple-200 dark:bg-purple-500/30 text-blue-700 dark:text-blue-300 rounded text-[10px]">{t}</span>
720 926 ))}
721 927 </div>
722 928 );
@@ -751,7 +957,7 @@ export default function AiPanel() {
751 957 <button
752 958 onClick={handleAnalyseAll}
753 959 disabled={analysing}
754 − className="flex items-center justify-center gap-2 px-3 py-2.5 bg-purple-600 hover:bg-purple-700 border border-transparent rounded-lg text-xs font-medium text-white disabled:opacity-50 transition-colors col-span-full"
960 + className="flex items-center justify-center gap-2 px-3 py-2.5 bg-blue-800 hover:bg-blue-900 border border-transparent rounded-lg text-xs font-medium text-white disabled:opacity-50 transition-colors col-span-full"
755 961 >
756 962 {analysing ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Zap className="w-3.5 h-3.5" />}
757 963 Analyse complète
@@ -764,7 +970,7 @@ export default function AiPanel() {
764 970 setChatInput(`Résume le fichier ${selectedFile.name}`);
765 971 setTab("chat");
766 972 }}
767 − className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs text-purple-600 dark:text-purple-400 border border-purple-200 dark:border-purple-500/30 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors"
973 + className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs text-blue-700 dark:text-blue-400 border border-purple-200 dark:border-purple-500/30 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors"
768 974 >
769 975 <MessageSquare className="w-3.5 h-3.5" />
770 976 Demander à Claude de résumer ce fichier
added components/auth/DevicesPanel.tsx +292 −0
@@ -0,0 +1,292 @@
1 +"use client";
2 +
3 +import { useState, useEffect } from "react";
4 +import { motion, AnimatePresence } from "framer-motion";
5 +import {
6 + Monitor,
7 + Smartphone,
8 + Tablet,
9 + Globe,
10 + MapPin,
11 + Clock,
12 + ShieldCheck,
13 + ShieldX,
14 + LogOut,
15 + Loader2,
16 + Wifi,
17 + ChevronDown,
18 + ChevronUp,
19 + Bot,
20 + AlertTriangle,
21 + Shield,
22 +} from "lucide-react";
23 +import toast from "react-hot-toast";
24 +
25 +interface DeviceSession {
26 + id: string;
27 + sessionToken: string;
28 + ip: string;
29 + device: string;
30 + browser: string;
31 + os: string;
32 + country: string;
33 + city: string;
34 + status: string;
35 + aiDecision: string | null;
36 + aiReason: string | null;
37 + aiRiskLevel: string | null;
38 + createdAt: string;
39 + endedAt: string | null;
40 + isCurrent: boolean;
41 +}
42 +
43 +function DeviceIcon({ device }: { device: string }) {
44 + const cls = "w-5 h-5";
45 + if (device === "Mobile") return <Smartphone className={cls} />;
46 + if (device === "Tablet") return <Tablet className={cls} />;
47 + return <Monitor className={cls} />;
48 +}
49 +
50 +function RiskBadge({ level }: { level: string | null }) {
51 + if (!level || level === "low") return null;
52 + const config = {
53 + medium: "bg-amber-500/15 text-amber-400 border-amber-500/20",
54 + high: "bg-red-500/15 text-red-400 border-red-500/20",
55 + }[level] || "";
56 + return (
57 + <span className={`inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full border uppercase tracking-wide ${config}`}>
58 + <AlertTriangle className="w-2.5 h-2.5" />
59 + {level === "high" ? "Risque élevé" : "Risque moyen"}
60 + </span>
61 + );
62 +}
63 +
64 +function formatRelative(dateStr: string): string {
65 + const date = new Date(dateStr);
66 + const diff = Date.now() - date.getTime();
67 + const mins = Math.floor(diff / 60000);
68 + const hours = Math.floor(diff / 3600000);
69 + const days = Math.floor(diff / 86400000);
70 + if (mins < 1) return "À l'instant";
71 + if (mins < 60) return `Il y a ${mins} min`;
72 + if (hours < 24) return `Il y a ${hours}h`;
73 + if (days === 1) return "Hier";
74 + if (days < 7) return `Il y a ${days} jours`;
75 + return date.toLocaleDateString("fr-FR", { day: "numeric", month: "short", year: "numeric" });
76 +}
77 +
78 +export default function DevicesPanel() {
79 + const [sessions, setSessions] = useState<DeviceSession[]>([]);
80 + const [loading, setLoading] = useState(true);
81 + const [revokingId, setRevokingId] = useState<string | null>(null);
82 + const [expandedId, setExpandedId] = useState<string | null>(null);
83 +
84 + const fetchSessions = async () => {
85 + const res = await fetch("/api/auth/devices");
86 + if (res.ok) setSessions(await res.json());
87 + setLoading(false);
88 + };
89 +
90 + useEffect(() => { fetchSessions(); }, []);
91 +
92 + const handleRevoke = async (session: DeviceSession) => {
93 + if (session.isCurrent) { toast.error("Impossible de révoquer la session active"); return; }
94 + setRevokingId(session.id);
95 + try {
96 + const res = await fetch(`/api/auth/devices/${session.id}`, { method: "DELETE" });
97 + if (res.ok) {
98 + toast.success("Session révoquée");
99 + setSessions((prev) => prev.map((s) => s.id === session.id ? { ...s, endedAt: new Date().toISOString() } : s));
100 + } else {
101 + toast.error("Erreur lors de la révocation");
102 + }
103 + } catch { toast.error("Erreur réseau"); }
104 + setRevokingId(null);
105 + };
106 +
107 + const refused = sessions.filter((s) => s.status === "refused_by_ai");
108 + const active = sessions.filter((s) => s.status === "active" && !s.endedAt);
109 + const past = sessions.filter((s) => s.status === "active" && s.endedAt || s.status === "ended");
110 +
111 + if (loading) {
112 + return (
113 + <div className="flex justify-center py-10">
114 + <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
115 + </div>
116 + );
117 + }
118 +
119 + if (sessions.length === 0) {
120 + return (
121 + <div className="text-center py-12 text-gray-500">
122 + <Monitor className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
123 + <p>Aucune session enregistrée</p>
124 + <p className="text-sm mt-1">Les connexions futures apparaîtront ici.</p>
125 + </div>
126 + );
127 + }
128 +
129 + const SessionCard = ({ s, i }: { s: DeviceSession; i: number }) => {
130 + const isRefused = s.status === "refused_by_ai";
131 + const isActive = s.status === "active" && !s.endedAt;
132 + const isExpanded = expandedId === s.id;
133 +
134 + return (
135 + <motion.div
136 + key={s.id}
137 + initial={{ opacity: 0, y: 6 }}
138 + animate={{ opacity: 1, y: 0 }}
139 + transition={{ delay: i * 0.04 }}
140 + className={`rounded-xl border transition-colors overflow-hidden ${
141 + isRefused
142 + ? "bg-red-500/5 border-red-500/25"
143 + : s.isCurrent
144 + ? "bg-emerald-500/10 border-emerald-500/30"
145 + : isActive
146 + ? "bg-white dark:bg-white/5 border-gray-200 dark:border-white/10"
147 + : "bg-gray-50 dark:bg-white/[0.02] border-gray-100 dark:border-white/5 opacity-70"
148 + }`}
149 + >
150 + <div className="flex flex-col sm:flex-row sm:items-center gap-3 p-4">
151 + {/* Icon */}
152 + <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
153 + isRefused ? "bg-red-500/15 text-red-400"
154 + : s.isCurrent ? "bg-emerald-500/20 text-emerald-400"
155 + : isActive ? "bg-gray-100 dark:bg-white/10 text-gray-600 dark:text-gray-300"
156 + : "bg-gray-100 dark:bg-white/5 text-gray-400"
157 + }`}>
158 + {isRefused ? <ShieldX className="w-5 h-5" /> : <DeviceIcon device={s.device} />}
159 + </div>
160 +
161 + {/* Info */}
162 + <div className="flex-1 min-w-0 space-y-1">
163 + <div className="flex items-center gap-2 flex-wrap">
164 + <span className="text-sm font-medium text-gray-900 dark:text-white">
165 + {s.browser} · {s.os}
166 + </span>
167 + {isRefused && (
168 + <span className="inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 bg-red-500/15 text-red-400 border border-red-500/20 rounded-full uppercase tracking-wide">
169 + <Bot className="w-2.5 h-2.5" /> Refusé par IA
170 + </span>
171 + )}
172 + {s.isCurrent && (
173 + <span className="inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 bg-emerald-500/20 text-emerald-400 rounded-full uppercase tracking-wide">
174 + <Wifi className="w-2.5 h-2.5" /> Session active
175 + </span>
176 + )}
177 + {!isRefused && <RiskBadge level={s.aiRiskLevel} />}
178 + </div>
179 +
180 + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500">
181 + <span className="flex items-center gap-1"><Globe className="w-3 h-3" />{s.ip}</span>
182 + {(s.country || s.city) && (
183 + <span className="flex items-center gap-1">
184 + <MapPin className="w-3 h-3" />
185 + {[s.city, s.country].filter(Boolean).join(", ")}
186 + </span>
187 + )}
188 + <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatRelative(s.createdAt)}</span>
189 + {s.endedAt && (
190 + <span className="flex items-center gap-1 text-gray-400">
191 + <LogOut className="w-3 h-3" />Déconnecté {formatRelative(s.endedAt)}
192 + </span>
193 + )}
194 + </div>
195 + </div>
196 +
197 + {/* Actions */}
198 + <div className="flex items-center gap-1 flex-shrink-0">
199 + {s.aiReason && (
200 + <button
201 + onClick={() => setExpandedId(isExpanded ? null : s.id)}
202 + className="min-w-[36px] min-h-[36px] flex items-center justify-center p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg transition-colors"
203 + title="Voir analyse IA"
204 + >
205 + {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
206 + </button>
207 + )}
208 + {isActive && !s.isCurrent && (
209 + <button
210 + onClick={() => handleRevoke(s)}
211 + disabled={revokingId === s.id}
212 + title="Déconnecter"
213 + className="flex items-center gap-1 px-2.5 py-1.5 text-xs text-red-500 hover:bg-red-500/10 rounded-lg transition-colors disabled:opacity-50"
214 + >
215 + {revokingId === s.id ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <LogOut className="w-3.5 h-3.5" />}
216 + Révoquer
217 + </button>
218 + )}
219 + {s.isCurrent && <ShieldCheck className="w-4 h-4 text-emerald-400 mr-1" />}
220 + </div>
221 + </div>
222 +
223 + {/* AI reason expandable */}
224 + <AnimatePresence>
225 + {isExpanded && s.aiReason && (
226 + <motion.div
227 + initial={{ height: 0, opacity: 0 }}
228 + animate={{ height: "auto", opacity: 1 }}
229 + exit={{ height: 0, opacity: 0 }}
230 + transition={{ duration: 0.2 }}
231 + className="overflow-hidden"
232 + >
233 + <div className={`mx-4 mb-4 p-3 rounded-lg flex items-start gap-2 text-xs ${
234 + isRefused
235 + ? "bg-red-500/10 border border-red-500/20 text-red-300"
236 + : "bg-blue-500/10 border border-blue-500/20 text-blue-300"
237 + }`}>
238 + <Bot className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
239 + <div>
240 + <span className="font-semibold block mb-0.5">
241 + Analyse IA Claude Opus 4.6 — {isRefused ? "Connexion refusée" : `Risque ${s.aiRiskLevel || "faible"}`}
242 + </span>
243 + <span>{s.aiReason}</span>
244 + </div>
245 + </div>
246 + </motion.div>
247 + )}
248 + </AnimatePresence>
249 + </motion.div>
250 + );
251 + };
252 +
253 + return (
254 + <div className="space-y-6">
255 + {/* AI protection info */}
256 + <div className="flex items-start gap-2 p-3 bg-blue-500/10 border border-blue-500/20 rounded-xl text-sm text-blue-400">
257 + <Shield className="w-4 h-4 mt-0.5 flex-shrink-0" />
258 + <span>Chaque connexion est analysée en temps réel par <strong>Claude Opus 4.6</strong> pour détecter toute activité suspecte.</span>
259 + </div>
260 +
261 + {/* Refused sessions */}
262 + {refused.length > 0 && (
263 + <div className="space-y-2">
264 + <h3 className="text-xs font-semibold uppercase tracking-wider text-red-400 px-1 flex items-center gap-1.5">
265 + <ShieldX className="w-3.5 h-3.5" /> Connexions refusées par IA ({refused.length})
266 + </h3>
267 + {refused.map((s, i) => <SessionCard key={s.id} s={s} i={i} />)}
268 + </div>
269 + )}
270 +
271 + {/* Active sessions */}
272 + {active.length > 0 && (
273 + <div className="space-y-2">
274 + <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 px-1">
275 + Sessions actives ({active.length})
276 + </h3>
277 + {active.map((s, i) => <SessionCard key={s.id} s={s} i={i} />)}
278 + </div>
279 + )}
280 +
281 + {/* Past sessions */}
282 + {past.length > 0 && (
283 + <div className="space-y-2">
284 + <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 px-1">
285 + Historique ({past.length})
286 + </h3>
287 + {past.map((s, i) => <SessionCard key={s.id} s={s} i={i} />)}
288 + </div>
289 + )}
290 + </div>
291 + );
292 +}
added components/dashboard/DashboardHome.tsx +349 −0
@@ -0,0 +1,349 @@
1 +"use client";
2 +
3 +import { useState, useEffect } from "react";
4 +import { useRouter } from "next/navigation";
5 +import { motion } from "framer-motion";
6 +import {
7 + Upload,
8 + FolderPlus,
9 + Search,
10 + Trash2,
11 + HardDrive,
12 + FileText,
13 + FolderOpen,
14 + Share2,
15 + Clock,
16 + ArrowRight,
17 + Image,
18 + Video,
19 + Music,
20 + FileCode,
21 + File,
22 +} from "lucide-react";
23 +import { formatFileSize, formatDate, getFileIcon } from "@/lib/utils";
24 +import type { FileData } from "@/types/files";
25 +import PageTransition from "@/components/ui/PageTransition";
26 +import { DashboardSkeleton } from "@/components/ui/Skeleton";
27 +
28 +interface Stats {
29 + fileCount: number;
30 + folderCount: number;
31 + shareCount: number;
32 + storageUsed: number;
33 + diskFileCount: number;
34 +}
35 +
36 +interface Activity {
37 + id: string;
38 + action: string;
39 + details: string | null;
40 + createdAt: string;
41 + file: { name: string } | null;
42 +}
43 +
44 +interface SessionInfo {
45 + name?: string;
46 + username?: string;
47 + email?: string;
48 +}
49 +
50 +const actionLabels: Record<string, string> = {
51 + upload: "a mis en ligne",
52 + delete: "a supprime",
53 + download: "a telecharge",
54 + rename: "a renomme",
55 + move: "a deplace",
56 + share: "a partage",
57 + preview: "a consulte",
58 + restore: "a restaure",
59 + favorite: "a ajoute aux favoris",
60 + unfavorite: "a retire des favoris",
61 +};
62 +
63 +const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
64 + image: Image,
65 + video: Video,
66 + audio: Music,
67 + pdf: FileText,
68 + code: FileCode,
69 + document: FileText,
70 + spreadsheet: FileText,
71 + file: File,
72 + archive: File,
73 + presentation: FileText,
74 +};
75 +
76 +function getGreeting(): string {
77 + const hour = new Date().getHours();
78 + if (hour < 12) return "Bonjour";
79 + if (hour < 18) return "Bon apres-midi";
80 + return "Bonsoir";
81 +}
82 +
83 +function formatFrenchDate(): string {
84 + return new Intl.DateTimeFormat("fr-FR", {
85 + weekday: "long",
86 + year: "numeric",
87 + month: "long",
88 + day: "numeric",
89 + }).format(new Date());
90 +}
91 +
92 +export default function DashboardHome() {
93 + const router = useRouter();
94 + const [stats, setStats] = useState<Stats | null>(null);
95 + const [recentFiles, setRecentFiles] = useState<FileData[]>([]);
96 + const [activities, setActivities] = useState<Activity[]>([]);
97 + const [session, setSession] = useState<SessionInfo | null>(null);
98 + const [loading, setLoading] = useState(true);
99 +
100 + useEffect(() => {
101 + Promise.all([
102 + fetch("/api/admin/stats").then((r) => r.json()),
103 + fetch("/api/files?sortBy=updatedAt&order=desc&limit=8").then((r) => r.json()),
104 + fetch("/api/admin/activity?limit=5").then((r) => r.json()),
105 + fetch("/api/auth/session").then((r) => r.json()),
106 + ])
107 + .then(([statsData, filesData, activityData, sessionData]) => {
108 + setStats(statsData);
109 + setRecentFiles(Array.isArray(filesData) ? filesData : filesData?.files || []);
110 + setActivities(activityData.activities || []);
111 + setSession(sessionData);
112 + })
113 + .catch(console.error)
114 + .finally(() => setLoading(false));
115 + }, []);
116 +
117 + const userName = session?.name || session?.username || "Admin";
118 +
119 + if (loading) {
120 + return <DashboardSkeleton />;
121 + }
122 +
123 + const storageTotal = 1024 * 1024 * 1024 * 500; // 500 GB
124 + const storageUsed = stats?.storageUsed || 0;
125 + const storagePercent = Math.min((storageUsed / storageTotal) * 100, 100);
126 +
127 + return (
128 + <PageTransition>
129 + <div className="p-3 sm:p-4 lg:p-6 space-y-5 sm:space-y-6">
130 + {/* Welcome Header */}
131 + <motion.div
132 + initial={{ opacity: 0, y: 10 }}
133 + animate={{ opacity: 1, y: 0 }}
134 + transition={{ duration: 0.3 }}
135 + className="relative overflow-hidden rounded-2xl p-4 sm:p-6 bg-gradient-to-br from-blue-800/5 via-blue-500/5 to-transparent dark:from-blue-800/10 dark:via-blue-500/5 dark:to-transparent border border-gray-200/50 dark:border-white/5"
136 + >
137 + <div className="absolute top-0 right-0 w-32 h-32 bg-blue-700/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2 pointer-events-none" />
138 + <h1 className="text-xl sm:text-2xl font-semibold text-gray-900 dark:text-white relative">
139 + {getGreeting()}, {userName}
140 + </h1>
141 + <p className="text-sm text-gray-500 dark:text-gray-400 mt-1 capitalize relative">
142 + {formatFrenchDate()}
143 + </p>
144 + </motion.div>
145 +
146 + {/* Quick Actions */}
147 + <motion.div
148 + initial={{ opacity: 0, y: 10 }}
149 + animate={{ opacity: 1, y: 0 }}
150 + transition={{ duration: 0.3, delay: 0.05 }}
151 + className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3"
152 + >
153 + {[
154 + { label: "Upload", icon: Upload, color: "bg-blue-500/10 text-blue-500 dark:bg-blue-500/20 dark:text-blue-400", href: "/dashboard/files" },
155 + { label: "Nouveau dossier", icon: FolderPlus, color: "bg-green-500/10 text-green-500 dark:bg-green-500/20 dark:text-green-400", href: "/dashboard/files" },
156 + { label: "Recherche AI", icon: Search, color: "bg-blue-700/10 text-blue-700 dark:bg-blue-700/20 dark:text-blue-400", href: "/dashboard/files" },
157 + { label: "Corbeille", icon: Trash2, color: "bg-red-500/10 text-red-500 dark:bg-red-500/20 dark:text-red-400", href: "/dashboard/trash" },
158 + ].map((action) => (
159 + <button
160 + key={action.label}
161 + onClick={() => router.push(action.href)}
162 + className="flex flex-col items-center gap-2 p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 hover:bg-gray-50 dark:hover:bg-white/10 transition-all active:scale-95 min-h-[88px] justify-center"
163 + >
164 + <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${action.color}`}>
165 + <action.icon className="w-5 h-5" />
166 + </div>
167 + <span className="text-xs sm:text-sm font-medium text-gray-700 dark:text-gray-300 text-center leading-tight">
168 + {action.label}
169 + </span>
170 + </button>
171 + ))}
172 + </motion.div>
173 +
174 + {/* Stats Row */}
175 + <motion.div
176 + initial={{ opacity: 0, y: 10 }}
177 + animate={{ opacity: 1, y: 0 }}
178 + transition={{ duration: 0.3, delay: 0.1 }}
179 + className="grid grid-cols-2 lg:grid-cols-4 gap-2 sm:gap-3"
180 + >
181 + {[
182 + { label: "Fichiers", value: stats?.fileCount || 0, icon: FileText, color: "text-blue-500" },
183 + { label: "Dossiers", value: stats?.folderCount || 0, icon: FolderOpen, color: "text-green-500" },
184 + { label: "Partages actifs", value: stats?.shareCount || 0, icon: Share2, color: "text-purple-500" },
185 + { label: "Stockage", value: formatFileSize(storageUsed), icon: HardDrive, color: "text-orange-500" },
186 + ].map((stat) => (
187 + <div
188 + key={stat.label}
189 + className="flex items-center gap-3 p-3 sm:p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md hover:shadow-black/5 dark:hover:shadow-black/20"
190 + >
191 + <stat.icon className={`w-5 h-5 flex-shrink-0 ${stat.color}`} />
192 + <div className="min-w-0">
193 + <p className="text-lg sm:text-xl font-semibold text-gray-900 dark:text-white truncate">
194 + {typeof stat.value === "number" ? stat.value.toLocaleString() : stat.value}
195 + </p>
196 + <p className="text-xs text-gray-500 dark:text-gray-400 truncate">{stat.label}</p>
197 + </div>
198 + </div>
199 + ))}
200 + </motion.div>
201 +
202 + {/* Storage Usage */}
203 + <motion.div
204 + initial={{ opacity: 0, y: 10 }}
205 + animate={{ opacity: 1, y: 0 }}
206 + transition={{ duration: 0.3, delay: 0.15 }}
207 + className="p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10"
208 + >
209 + <div className="flex items-center justify-between mb-2">
210 + <div className="flex items-center gap-2">
211 + <HardDrive className="w-4 h-4 text-gray-500" />
212 + <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Stockage</span>
213 + </div>
214 + <span className="text-xs text-gray-500 dark:text-gray-400">
215 + {formatFileSize(storageUsed)} / {formatFileSize(storageTotal)}
216 + </span>
217 + </div>
218 + <div className="w-full h-2.5 bg-gray-100 dark:bg-white/10 rounded-full overflow-hidden">
219 + <motion.div
220 + initial={{ width: 0 }}
221 + animate={{ width: `${storagePercent}%` }}
222 + transition={{ duration: 0.8, ease: "easeOut", delay: 0.3 }}
223 + className={`h-full rounded-full ${
224 + storagePercent > 90
225 + ? "bg-red-500"
226 + : storagePercent > 70
227 + ? "bg-orange-500"
228 + : "bg-blue-500"
229 + }`}
230 + />
231 + </div>
232 + <p className="text-xs text-gray-400 mt-1.5">
233 + {storagePercent.toFixed(1)}% utilise
234 + </p>
235 + </motion.div>
236 +
237 + {/* Recent Files */}
238 + <motion.div
239 + initial={{ opacity: 0, y: 10 }}
240 + animate={{ opacity: 1, y: 0 }}
241 + transition={{ duration: 0.3, delay: 0.2 }}
242 + >
243 + <div className="flex items-center justify-between mb-3">
244 + <h2 className="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
245 + <Clock className="w-4 h-4" />
246 + Fichiers recents
247 + </h2>
248 + <button
249 + onClick={() => router.push("/dashboard/recent")}
250 + className="text-xs text-blue-500 hover:text-blue-400 flex items-center gap-1 transition-colors"
251 + >
252 + Tout voir <ArrowRight className="w-3 h-3" />
253 + </button>
254 + </div>
255 +
256 + {recentFiles.length === 0 ? (
257 + <div className="p-8 text-center text-gray-400 dark:text-gray-500 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
258 + <File className="w-10 h-10 mx-auto mb-2 opacity-50" />
259 + <p className="text-sm">Aucun fichier recent</p>
260 + </div>
261 + ) : (
262 + <div className="flex gap-2 sm:gap-3 overflow-x-auto pb-2 -mx-3 px-3 sm:-mx-4 sm:px-4 lg:-mx-6 lg:px-6 scrollbar-thin">
263 + {recentFiles.map((file, i) => {
264 + const iconType = getFileIcon(file.mimeType);
265 + const IconComponent = iconMap[iconType] || File;
266 + return (
267 + <motion.button
268 + key={file.id}
269 + initial={{ opacity: 0, scale: 0.95 }}
270 + animate={{ opacity: 1, scale: 1 }}
271 + transition={{ duration: 0.2, delay: 0.05 * i }}
272 + onClick={() => router.push("/dashboard/files")}
273 + className="flex-shrink-0 w-36 sm:w-44 p-3 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 hover:bg-gray-50 dark:hover:bg-white/10 transition-all text-left active:scale-95 hover:scale-[1.03] hover:shadow-lg hover:shadow-black/5 dark:hover:shadow-black/20"
274 + >
275 + {file.mimeType.startsWith("image/") ? (
276 + <div className="w-full h-20 rounded-xl bg-gray-100 dark:bg-white/10 mb-2 overflow-hidden">
277 + <img
278 + src={`/api/files/${file.id}/raw`}
279 + alt={file.name}
280 + className="w-full h-full object-cover"
281 + loading="lazy"
282 + />
283 + </div>
284 + ) : (
285 + <div className="w-full h-20 rounded-xl bg-gray-100 dark:bg-white/10 mb-2 flex items-center justify-center">
286 + <IconComponent className="w-8 h-8 text-gray-400 dark:text-gray-500" />
287 + </div>
288 + )}
289 + <p className="text-xs font-medium text-gray-900 dark:text-white truncate">
290 + {file.name}
291 + </p>
292 + <p className="text-[10px] text-gray-400 dark:text-gray-500 mt-0.5">
293 + {formatFileSize(file.size)}
294 + </p>
295 + </motion.button>
296 + );
297 + })}
298 + </div>
299 + )}
300 + </motion.div>
301 +
302 + {/* Recent Activity */}
303 + <motion.div
304 + initial={{ opacity: 0, y: 10 }}
305 + animate={{ opacity: 1, y: 0 }}
306 + transition={{ duration: 0.3, delay: 0.25 }}
307 + >
308 + <h2 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
309 + <Clock className="w-4 h-4" />
310 + Activite recente
311 + </h2>
312 +
313 + {activities.length === 0 ? (
314 + <div className="p-8 text-center text-gray-400 dark:text-gray-500 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
315 + <Clock className="w-10 h-10 mx-auto mb-2 opacity-50" />
316 + <p className="text-sm">Aucune activite recente</p>
317 + </div>
318 + ) : (
319 + <div className="rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 divide-y divide-gray-100 dark:divide-white/5">
320 + {activities.map((activity) => (
321 + <div key={activity.id} className="flex items-center gap-3 px-4 py-3">
322 + <div className="w-2 h-2 rounded-full bg-blue-500 flex-shrink-0" />
323 + <div className="min-w-0 flex-1">
324 + <p className="text-sm text-gray-700 dark:text-gray-300 truncate">
325 + <span className="text-gray-400 dark:text-gray-500">
326 + {actionLabels[activity.action] || activity.action}
327 + </span>{" "}
328 + {activity.file?.name && (
329 + <span className="font-medium text-gray-900 dark:text-white">
330 + {activity.file.name}
331 + </span>
332 + )}
333 + </p>
334 + {activity.details && (
335 + <p className="text-xs text-gray-400 truncate">{activity.details}</p>
336 + )}
337 + </div>
338 + <span className="text-xs text-gray-400 dark:text-gray-500 flex-shrink-0 whitespace-nowrap">
339 + {formatDate(activity.createdAt)}
340 + </span>
341 + </div>
342 + ))}
343 + </div>
344 + )}
345 + </motion.div>
346 + </div>
347 + </PageTransition>
348 + );
349 +}
modified components/files/BulkActions.tsx +1 −1
@@ -101,7 +101,7 @@ export default function BulkActions({ selectedIds, onClear, onRefresh }: BulkAct
101 101 <Button size="sm" variant="ghost" onClick={aiTagAll} loading={loading} className="min-h-[40px] whitespace-nowrap">
102 102 <Sparkles className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Tags IA</span>
103 103 </Button>
104 − <Button size="sm" variant="danger" onClick={() => { if (confirm(`Supprimer ${selectedIds.length} fichier(s) ?`)) bulkAction("delete"); }} loading={loading} className="min-h-[40px] whitespace-nowrap">
104 + <Button data-bulk-delete size="sm" variant="danger" onClick={() => { if (confirm(`Supprimer ${selectedIds.length} fichier(s) ?`)) bulkAction("delete"); }} loading={loading} className="min-h-[40px] whitespace-nowrap">
105 105 <Trash2 className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Supprimer</span>
106 106 </Button>
107 107 </div>
modified components/files/FileActions.tsx +9 −33
@@ -13,6 +13,7 @@ import {
13 13 import toast from "react-hot-toast";
14 14 import Modal from "../ui/Modal";
15 15 import Button from "../ui/Button";
16 +import MoveModal from "./MoveModal";
16 17
17 18 interface FileData {
18 19 id: string;
@@ -38,7 +39,6 @@ export default function FileActions({ file, onClose, onRefresh }: FileActionsPro
38 39 const [shareExpiry, setShareExpiry] = useState("");
39 40 const [shareMode, setShareMode] = useState<"DOWNLOAD" | "PREVIEW">("DOWNLOAD");
40 41 const [loading, setLoading] = useState(false);
41 − const [folders, setFolders] = useState<{ id: string; name: string }[]>([]);
42 42
43 43 const handleDownload = () => {
44 44 window.open(`/api/files/${file.id}/download`, "_blank");
@@ -177,14 +177,6 @@ export default function FileActions({ file, onClose, onRefresh }: FileActionsPro
177 177 onClose();
178 178 };
179 179
180 − const loadFolders = async () => {
181 − const res = await fetch("/api/folders?tree=true");
182 − if (res.ok) {
183 − const data = await res.json();
184 − setFolders(data);
185 − }
186 − };
187 −
188 180 const actions = [
189 181 { icon: Download, label: "Télécharger", action: handleDownload },
190 182 { icon: Pencil, label: "Renommer", action: () => setRenameModal(true) },
@@ -192,10 +184,7 @@ export default function FileActions({ file, onClose, onRefresh }: FileActionsPro
192 184 {
193 185 icon: FolderInput,
194 186 label: "Déplacer",
195 − action: () => {
196 − loadFolders();
197 − setMoveModal(true);
198 − },
187 + action: () => setMoveModal(true),
199 188 },
200 189 { icon: Share2, label: "Partager", action: () => setShareModal(true) },
201 190 { icon: Trash2, label: "Supprimer", action: () => setDeleteModal(true), danger: true },
@@ -323,26 +312,13 @@ export default function FileActions({ file, onClose, onRefresh }: FileActionsPro
323 312 )}
324 313 </Modal>
325 314
326 − {/* Move Modal */}
327 − <Modal isOpen={moveModal} onClose={() => setMoveModal(false)} title="Déplacer vers">
328 − <div className="space-y-1 max-h-60 overflow-y-auto">
329 − <button
330 − onClick={() => handleMove("root")}
331 − className="flex items-center gap-2 w-full px-3 py-2.5 text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 rounded-lg"
332 − >
333 − Racine
334 − </button>
335 − {folders.map((folder: { id: string; name: string }) => (
336 − <button
337 − key={folder.id}
338 − onClick={() => handleMove(folder.id)}
339 − className="flex items-center gap-2 w-full px-3 py-2.5 text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 rounded-lg"
340 − >
341 − {folder.name}
342 − </button>
343 − ))}
344 − </div>
345 − </Modal>
315 + {/* Move Modal (arborescence) */}
316 + <MoveModal
317 + isOpen={moveModal}
318 + onClose={() => setMoveModal(false)}
319 + onSelect={handleMove}
320 + itemName={file.name}
321 + />
346 322 </>
347 323 );
348 324 }
modified components/files/FileCard.tsx +10 −9
@@ -130,7 +130,7 @@ export default function FileCard({ file, onPreview, onRefresh, viewMode }: FileC
130 130 <motion.div
131 131 initial={{ opacity: 0 }}
132 132 animate={{ opacity: 1 }}
133 − className="flex items-center gap-3 px-3 py-3 hover:bg-gray-100 dark:hover:bg-white/5 rounded-lg cursor-pointer group transition-colors"
133 + className="flex items-center gap-3 px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-white/5 cursor-pointer group transition-colors"
134 134 onClick={() => onPreview(file)}
135 135 >
136 136 {/* Icon */}
@@ -156,8 +156,8 @@ export default function FileCard({ file, onPreview, onRefresh, viewMode }: FileC
156 156 )}
157 157
158 158 {isFavorite && <Star className="w-3.5 h-3.5 text-amber-400 fill-amber-400 flex-shrink-0 hidden sm:block" />}
159 − <span className="text-sm text-gray-500 hidden sm:block flex-shrink-0">{formatFileSize(file.size)}</span>
160 − <span className="text-xs text-gray-400 hidden md:block flex-shrink-0 min-w-[80px] text-right">{formatRelativeDate(file.createdAt)}</span>
159 + <span className="text-sm text-gray-500 hidden sm:block flex-shrink-0 w-24 text-right tabular-nums">{formatFileSize(file.size)}</span>
160 + <span className="text-xs text-gray-400 hidden md:block flex-shrink-0 w-28 text-right">{formatRelativeDate(file.createdAt)}</span>
161 161
162 162 {/* Actions menu */}
163 163 <div className="relative flex-shrink-0" ref={menuRef}>
@@ -187,13 +187,14 @@ export default function FileCard({ file, onPreview, onRefresh, viewMode }: FileC
187 187 <div className={`aspect-square flex items-center justify-center rounded-t-xl overflow-hidden ${isImage ? "" : bgTint}`}>
188 188 {isImage ? (
189 189 <img
190 − src={`/api/files/${file.id}/preview`}
190 + src={`/api/files/${file.id}/preview?w=400`}
191 191 alt={file.name}
192 192 className="w-full h-full object-cover"
193 193 loading="lazy"
194 + decoding="async"
194 195 />
195 196 ) : (
196 − <Icon className={`w-14 h-14 ${iconColor}`} />
197 + <Icon className={`w-10 h-10 ${iconColor}`} />
197 198 )}
198 199 </div>
199 200
@@ -218,12 +219,12 @@ export default function FileCard({ file, onPreview, onRefresh, viewMode }: FileC
218 219 </div>
219 220
220 221 {/* Info */}
221 − <div className="p-3">
222 − <p className="text-sm text-gray-700 dark:text-gray-200 truncate font-medium">{file.name}</p>
223 − <p className="text-xs text-gray-500 mt-0.5 flex items-center gap-1.5">
222 + <div className="p-2">
223 + <p className="text-[13px] leading-tight text-gray-700 dark:text-gray-200 truncate font-medium">{file.name}</p>
224 + <p className="text-[11px] text-gray-500 mt-0.5 flex items-center gap-1">
224 225 <span>{formatFileSize(file.size)}</span>
225 226 <span className="text-gray-300 dark:text-gray-700">·</span>
226 − <span>{formatRelativeDate(file.createdAt)}</span>
227 + <span className="truncate">{formatRelativeDate(file.createdAt)}</span>
227 228 </p>
228 229 <TagDots />
229 230 </div>
added components/files/FileComments.tsx +309 −0
@@ -0,0 +1,309 @@
1 +"use client";
2 +
3 +import { useState, useEffect, useCallback, useRef } from "react";
4 +import { MessageCircle, Send, MoreVertical, Pencil, Trash2 } from "lucide-react";
5 +import { motion, AnimatePresence } from "framer-motion";
6 +import UserAvatar from "@/components/ui/UserAvatar";
7 +
8 +interface CommentUser {
9 + id: string;
10 + name: string | null;
11 + username: string | null;
12 + avatarPath: string | null;
13 +}
14 +
15 +interface Comment {
16 + id: string;
17 + content: string;
18 + createdAt: string;
19 + updatedAt: string;
20 + user: CommentUser;
21 +}
22 +
23 +function timeAgo(date: string): string {
24 + const now = new Date();
25 + const d = new Date(date);
26 + const seconds = Math.floor((now.getTime() - d.getTime()) / 1000);
27 +
28 + if (seconds < 60) return "a l'instant";
29 + const minutes = Math.floor(seconds / 60);
30 + if (minutes < 60) return `il y a ${minutes}min`;
31 + const hours = Math.floor(minutes / 60);
32 + if (hours < 24) return `il y a ${hours}h`;
33 + const days = Math.floor(hours / 24);
34 + if (days < 30) return `il y a ${days}j`;
35 + const months = Math.floor(days / 30);
36 + return `il y a ${months} mois`;
37 +}
38 +
39 +interface FileCommentsProps {
40 + fileId: string;
41 + currentUserId?: string;
42 +}
43 +
44 +export default function FileComments({ fileId, currentUserId }: FileCommentsProps) {
45 + const [comments, setComments] = useState<Comment[]>([]);
46 + const [content, setContent] = useState("");
47 + const [loading, setLoading] = useState(false);
48 + const [submitting, setSubmitting] = useState(false);
49 + const [editingId, setEditingId] = useState<string | null>(null);
50 + const [editContent, setEditContent] = useState("");
51 + const [menuOpen, setMenuOpen] = useState<string | null>(null);
52 + const listRef = useRef<HTMLDivElement>(null);
53 + const menuRef = useRef<HTMLDivElement>(null);
54 +
55 + const fetchComments = useCallback(async () => {
56 + try {
57 + const res = await fetch(`/api/files/${fileId}/comments`);
58 + if (res.ok) {
59 + setComments(await res.json());
60 + }
61 + } catch {
62 + // silent
63 + }
64 + }, [fileId]);
65 +
66 + useEffect(() => {
67 + setLoading(true);
68 + fetchComments().finally(() => setLoading(false));
69 + const interval = setInterval(fetchComments, 10000);
70 + return () => clearInterval(interval);
71 + }, [fetchComments]);
72 +
73 + // Close menu on outside click
74 + useEffect(() => {
75 + function handleClick(e: MouseEvent) {
76 + if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
77 + setMenuOpen(null);
78 + }
79 + }
80 + document.addEventListener("mousedown", handleClick);
81 + return () => document.removeEventListener("mousedown", handleClick);
82 + }, []);
83 +
84 + const handleSubmit = async () => {
85 + if (!content.trim() || submitting) return;
86 + setSubmitting(true);
87 + try {
88 + const res = await fetch(`/api/files/${fileId}/comments`, {
89 + method: "POST",
90 + headers: { "Content-Type": "application/json" },
91 + body: JSON.stringify({ content: content.trim() }),
92 + });
93 + if (res.ok) {
94 + const newComment = await res.json();
95 + setComments((prev) => [...prev, newComment]);
96 + setContent("");
97 + // Scroll to bottom
98 + setTimeout(() => {
99 + listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
100 + }, 100);
101 + }
102 + } catch {
103 + // silent
104 + } finally {
105 + setSubmitting(false);
106 + }
107 + };
108 +
109 + const handleEdit = async (commentId: string) => {
110 + if (!editContent.trim()) return;
111 + try {
112 + const res = await fetch(`/api/files/${fileId}/comments/${commentId}`, {
113 + method: "PATCH",
114 + headers: { "Content-Type": "application/json" },
115 + body: JSON.stringify({ content: editContent.trim() }),
116 + });
117 + if (res.ok) {
118 + const updated = await res.json();
119 + setComments((prev) =>
120 + prev.map((c) => (c.id === commentId ? updated : c))
121 + );
122 + setEditingId(null);
123 + setEditContent("");
124 + }
125 + } catch {
126 + // silent
127 + }
128 + };
129 +
130 + const handleDelete = async (commentId: string) => {
131 + try {
132 + const res = await fetch(`/api/files/${fileId}/comments/${commentId}`, {
133 + method: "DELETE",
134 + });
135 + if (res.ok) {
136 + setComments((prev) => prev.filter((c) => c.id !== commentId));
137 + }
138 + } catch {
139 + // silent
140 + }
141 + setMenuOpen(null);
142 + };
143 +
144 + const startEdit = (comment: Comment) => {
145 + setEditingId(comment.id);
146 + setEditContent(comment.content);
147 + setMenuOpen(null);
148 + };
149 +
150 + return (
151 + <div className="flex flex-col h-full">
152 + <div className="flex items-center gap-2 px-4 py-3 border-b border-white/10">
153 + <MessageCircle className="w-4 h-4 text-gray-400" />
154 + <h3 className="text-sm font-medium text-white">
155 + Commentaires ({comments.length})
156 + </h3>
157 + </div>
158 +
159 + <div ref={listRef} className="flex-1 overflow-y-auto px-4 py-2 space-y-3">
160 + {loading && comments.length === 0 && (
161 + <div className="flex justify-center py-8">
162 + <div className="w-5 h-5 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
163 + </div>
164 + )}
165 +
166 + {!loading && comments.length === 0 && (
167 + <p className="text-center text-gray-500 text-sm py-8">
168 + Aucun commentaire
169 + </p>
170 + )}
171 +
172 + <AnimatePresence initial={false}>
173 + {comments.map((comment) => (
174 + <motion.div
175 + key={comment.id}
176 + initial={{ opacity: 0, y: 10 }}
177 + animate={{ opacity: 1, y: 0 }}
178 + exit={{ opacity: 0, y: -10 }}
179 + className="group relative"
180 + >
181 + <div className="flex gap-2.5">
182 + <div className="pt-0.5">
183 + <UserAvatar
184 + userId={comment.user.id}
185 + name={comment.user.name || comment.user.username}
186 + avatarPath={comment.user.avatarPath}
187 + size="sm"
188 + />
189 + </div>
190 + <div className="flex-1 min-w-0">
191 + <div className="flex items-center gap-2">
192 + <span className="text-xs font-medium text-white truncate">
193 + {comment.user.name || comment.user.username || "Anonyme"}
194 + </span>
195 + <span className="text-[10px] text-gray-500 flex-shrink-0">
196 + {timeAgo(comment.createdAt)}
197 + </span>
198 + {comment.updatedAt !== comment.createdAt && (
199 + <span className="text-[10px] text-gray-600 italic">(modifie)</span>
200 + )}
201 + </div>
202 +
203 + {editingId === comment.id ? (
204 + <div className="mt-1 space-y-1.5">
205 + <textarea
206 + value={editContent}
207 + onChange={(e) => setEditContent(e.target.value)}
208 + className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 resize-none focus:outline-none focus:ring-1 focus:ring-blue-500"
209 + rows={2}
210 + autoFocus
211 + />
212 + <div className="flex gap-2">
213 + <button
214 + onClick={() => handleEdit(comment.id)}
215 + className="px-3 py-1 bg-blue-600 hover:bg-blue-500 text-white text-xs rounded-md transition-colors"
216 + >
217 + Sauvegarder
218 + </button>
219 + <button
220 + onClick={() => {
221 + setEditingId(null);
222 + setEditContent("");
223 + }}
224 + className="px-3 py-1 bg-white/5 hover:bg-white/10 text-gray-400 text-xs rounded-md transition-colors"
225 + >
226 + Annuler
227 + </button>
228 + </div>
229 + </div>
230 + ) : (
231 + <p className="text-sm text-gray-300 mt-0.5 break-words whitespace-pre-wrap">
232 + {comment.content}
233 + </p>
234 + )}
235 + </div>
236 +
237 + {/* Menu for own comments */}
238 + {currentUserId === comment.user.id && editingId !== comment.id && (
239 + <div className="relative" ref={menuOpen === comment.id ? menuRef : undefined}>
240 + <button
241 + onClick={() =>
242 + setMenuOpen(menuOpen === comment.id ? null : comment.id)
243 + }
244 + className="opacity-0 group-hover:opacity-100 p-1 text-gray-500 hover:text-gray-300 transition-all min-w-[28px] min-h-[28px] flex items-center justify-center"
245 + >
246 + <MoreVertical className="w-3.5 h-3.5" />
247 + </button>
248 +
249 + <AnimatePresence>
250 + {menuOpen === comment.id && (
251 + <motion.div
252 + initial={{ opacity: 0, scale: 0.95 }}
253 + animate={{ opacity: 1, scale: 1 }}
254 + exit={{ opacity: 0, scale: 0.95 }}
255 + className="absolute right-0 top-full mt-1 bg-gray-800 border border-white/10 rounded-lg shadow-xl z-10 overflow-hidden min-w-[140px]"
256 + >
257 + <button
258 + onClick={() => startEdit(comment)}
259 + className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-300 hover:bg-white/5 transition-colors"
260 + >
261 + <Pencil className="w-3.5 h-3.5" />
262 + Modifier
263 + </button>
264 + <button
265 + onClick={() => handleDelete(comment.id)}
266 + className="flex items-center gap-2 w-full px-3 py-2 text-sm text-red-400 hover:bg-red-500/10 transition-colors"
267 + >
268 + <Trash2 className="w-3.5 h-3.5" />
269 + Supprimer
270 + </button>
271 + </motion.div>
272 + )}
273 + </AnimatePresence>
274 + </div>
275 + )}
276 + </div>
277 + </motion.div>
278 + ))}
279 + </AnimatePresence>
280 + </div>
281 +
282 + {/* Input area */}
283 + <div className="border-t border-white/10 px-4 py-3">
284 + <div className="flex gap-2">
285 + <textarea
286 + value={content}
287 + onChange={(e) => setContent(e.target.value)}
288 + placeholder="Ecrire un commentaire..."
289 + className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 resize-none focus:outline-none focus:ring-1 focus:ring-blue-500 min-h-[40px] max-h-[120px]"
290 + rows={1}
291 + onKeyDown={(e) => {
292 + if (e.key === "Enter" && !e.shiftKey) {
293 + e.preventDefault();
294 + handleSubmit();
295 + }
296 + }}
297 + />
298 + <button
299 + onClick={handleSubmit}
300 + disabled={!content.trim() || submitting}
301 + className="self-end p-2.5 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-lg transition-colors min-w-[40px] min-h-[40px] flex items-center justify-center"
302 + >
303 + <Send className="w-4 h-4" />
304 + </button>
305 + </div>
306 + </div>
307 + </div>
308 + );
309 +}
modified components/files/FileExplorer.tsx +524 −74
@@ -1,7 +1,23 @@
1 1 "use client";
2 2
3 −import { useState, useEffect, useCallback } from "react";
4 −import { Grid, List, Plus, Upload, CheckSquare, Square, Users } from "lucide-react";
3 +import { useState, useEffect, useCallback, useRef } from "react";
4 +import {
5 + Grid,
6 + List,
7 + Plus,
8 + Upload,
9 + CheckSquare,
10 + Square,
11 + Users,
12 + FolderOpen,
13 + Search,
14 + FileText,
15 + Image,
16 + Film,
17 + X,
18 + ArrowUpNarrowWide,
19 + ArrowDownWideNarrow,
20 +} from "lucide-react";
5 21 import FileCard from "./FileCard";
6 22 import FileUpload from "./FileUpload";
7 23 import PreviewEngine from "../preview/PreviewEngine";
@@ -27,10 +43,14 @@ interface FileExplorerProps {
27 43 folderId?: string | null;
28 44 }
29 45
46 +const PAGE_LIMIT = 50;
47 +
30 48 export default function FileExplorer({ folderId }: FileExplorerProps) {
31 49 const [files, setFiles] = useState<FileData[]>([]);
32 50 const [folders, setFolders] = useState<FolderData[]>([]);
33 − const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
51 + const [viewMode, setViewModeState] = useState<"grid" | "list">("list");
52 + const [sortKey, setSortKey] = useState<"name" | "date" | "size" | "type">("name");
53 + const [sortDir, setSortDir] = useState<"asc" | "desc">("asc");
34 54 const [showUpload, setShowUpload] = useState(false);
35 55 const [showCreateFolder, setShowCreateFolder] = useState(false);
36 56 const [showCreateSharedFolder, setShowCreateSharedFolder] = useState(false);
@@ -39,35 +59,165 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
39 59 const [loading, setLoading] = useState(true);
40 60 const [selectedIds, setSelectedIds] = useState<string[]>([]);
41 61 const [selectMode, setSelectMode] = useState(false);
62 + const [offset, setOffset] = useState(0);
63 + const [hasMore, setHasMore] = useState(false);
64 + const [loadingMore, setLoadingMore] = useState(false);
65 + const containerRef = useRef<HTMLDivElement>(null);
66 +
67 + // Vue & tri mémorisés (localStorage)
68 + const setViewMode = useCallback((v: "grid" | "list") => {
69 + setViewModeState(v);
70 + try { localStorage.setItem("spb-view", v); } catch {}
71 + }, []);
42 72
43 − const fetchData = useCallback(async () => {
44 − setLoading(true);
73 + useEffect(() => {
45 74 try {
46 − const params = new URLSearchParams();
47 − if (folderId) params.set("folderId", folderId);
48 − else params.set("folderId", "root");
49 − if (searchQuery) params.set("search", searchQuery);
50 −
51 − const [filesRes, foldersRes] = await Promise.all([
52 − fetch(`/api/files?${params}`),
53 − fetch(`/api/folders?parentId=${folderId || "root"}`),
54 − ]);
55 −
56 − if (filesRes.ok) setFiles(await filesRes.json());
57 − if (foldersRes.ok) setFolders(await foldersRes.json());
58 − } catch (err) {
59 − console.error("Failed to fetch data:", err);
60 − } finally {
61 − setLoading(false);
62 − }
75 + const v = localStorage.getItem("spb-view");
76 + if (v === "grid" || v === "list") setViewModeState(v);
77 + const s = localStorage.getItem("spb-sort");
78 + if (s) {
79 + const { key, dir } = JSON.parse(s);
80 + if (["name", "date", "size", "type"].includes(key)) setSortKey(key);
81 + if (dir === "asc" || dir === "desc") setSortDir(dir);
82 + }
83 + } catch {}
84 + }, []);
85 +
86 + useEffect(() => {
87 + try { localStorage.setItem("spb-sort", JSON.stringify({ key: sortKey, dir: sortDir })); } catch {}
88 + }, [sortKey, sortDir]);
89 +
90 + const fetchData = useCallback(
91 + async (loadMore = false) => {
92 + if (loadMore) {
93 + setLoadingMore(true);
94 + } else {
95 + setLoading(true);
96 + setOffset(0);
97 + }
98 +
99 + try {
100 + const currentOffset = loadMore ? offset : 0;
101 + const params = new URLSearchParams();
102 + if (folderId) params.set("folderId", folderId);
103 + else params.set("folderId", "root");
104 + if (searchQuery) params.set("search", searchQuery);
105 + params.set("limit", String(PAGE_LIMIT));
106 + params.set("offset", String(currentOffset));
107 +
108 + const [filesRes, foldersRes] = await Promise.all([
109 + fetch(`/api/files?${params}`),
110 + loadMore
111 + ? Promise.resolve(null)
112 + : fetch(`/api/folders?parentId=${folderId || "root"}`),
113 + ]);
114 +
115 + if (filesRes.ok) {
116 + const data = await filesRes.json();
117 + // Support both array response and paginated {files, total} response
118 + const newFiles = Array.isArray(data) ? data : data.files || data;
119 + const total = Array.isArray(data) ? undefined : data.total;
120 +
121 + if (loadMore) {
122 + setFiles((prev) => [...prev, ...newFiles]);
123 + } else {
124 + setFiles(newFiles);
125 + }
126 +
127 + // Determine if there are more files
128 + if (total !== undefined) {
129 + setHasMore(currentOffset + PAGE_LIMIT < total);
130 + } else {
131 + setHasMore(newFiles.length >= PAGE_LIMIT);
132 + }
133 +
134 + setOffset(currentOffset + newFiles.length);
135 + }
136 +
137 + if (foldersRes && foldersRes.ok) {
138 + setFolders(await foldersRes.json());
139 + }
140 + } catch (err) {
141 + console.error("Failed to fetch data:", err);
142 + } finally {
143 + setLoading(false);
144 + setLoadingMore(false);
145 + }
146 + },
147 + [folderId, searchQuery, offset]
148 + );
149 +
150 + useEffect(() => {
151 + fetchData();
152 + // eslint-disable-next-line react-hooks/exhaustive-deps
63 153 }, [folderId, searchQuery]);
64 154
65 − useEffect(() => { fetchData(); }, [fetchData]);
155 + // Keyboard shortcuts
156 + useEffect(() => {
157 + const handleKeyDown = (e: KeyboardEvent) => {
158 + const target = e.target as HTMLElement;
159 + // Skip if user is typing in an input
160 + if (
161 + target.tagName === "INPUT" ||
162 + target.tagName === "TEXTAREA" ||
163 + target.isContentEditable
164 + )
165 + return;
166 +
167 + // Delete selected files
168 + if (e.key === "Delete" || e.key === "Backspace") {
169 + if (selectMode && selectedIds.length > 0) {
170 + e.preventDefault();
171 + // Trigger bulk delete via the BulkActions component (it handles delete)
172 + const deleteBtn = document.querySelector(
173 + '[data-bulk-delete]'
174 + ) as HTMLButtonElement;
175 + if (deleteBtn) deleteBtn.click();
176 + }
177 + }
66 178
67 − const handleSearch = useCallback((query: string) => { setSearchQuery(query); }, []);
179 + // Ctrl/Cmd + A: select all
180 + if ((e.ctrlKey || e.metaKey) && e.key === "a") {
181 + if (files.length > 0) {
182 + e.preventDefault();
183 + if (!selectMode) setSelectMode(true);
184 + if (selectedIds.length === files.length) {
185 + setSelectedIds([]);
186 + } else {
187 + setSelectedIds(files.map((f) => f.id));
188 + }
189 + }
190 + }
191 +
192 + // Escape: clear selection or close preview
193 + if (e.key === "Escape") {
194 + if (previewFile) {
195 + setPreviewFile(null);
196 + } else if (selectMode) {
197 + setSelectedIds([]);
198 + setSelectMode(false);
199 + }
200 + }
201 +
202 + // Ctrl/Cmd + Shift + N: new folder
203 + if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "N") {
204 + e.preventDefault();
205 + setShowCreateFolder(true);
206 + }
207 + };
208 +
209 + window.addEventListener("keydown", handleKeyDown);
210 + return () => window.removeEventListener("keydown", handleKeyDown);
211 + }, [selectMode, selectedIds, files, previewFile]);
212 +
213 + const handleSearch = useCallback((query: string) => {
214 + setSearchQuery(query);
215 + }, []);
68 216
69 217 const toggleSelect = (id: string) => {
70 − setSelectedIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]);
218 + setSelectedIds((prev) =>
219 + prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
220 + );
71 221 };
72 222
73 223 const selectAll = () => {
@@ -83,15 +233,170 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
83 233 }
84 234 };
85 235
236 + const handleRefresh = useCallback(() => {
237 + fetchData(false);
238 + // eslint-disable-next-line react-hooks/exhaustive-deps
239 + }, [folderId, searchQuery]);
240 +
241 + // Skeleton components
242 + const SkeletonGrid = () => (
243 + <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 sm:gap-3 lg:grid-cols-6 xl:grid-cols-8">
244 + {Array.from({ length: 8 }).map((_, i) => (
245 + <div
246 + key={i}
247 + className="aspect-square bg-gray-100 dark:bg-white/5 rounded-xl animate-pulse"
248 + >
249 + <div className="p-4 h-full flex flex-col justify-between">
250 + <div className="w-10 h-10 bg-gray-200 dark:bg-white/10 rounded-lg" />
251 + <div className="space-y-2">
252 + <div className="h-3 bg-gray-200 dark:bg-white/10 rounded w-3/4" />
253 + <div className="h-2 bg-gray-200 dark:bg-white/10 rounded w-1/2" />
254 + </div>
255 + </div>
256 + </div>
257 + ))}
258 + </div>
259 + );
260 +
261 + const SkeletonList = () => (
262 + <div className="space-y-1">
263 + {Array.from({ length: 6 }).map((_, i) => (
264 + <div
265 + key={i}
266 + className="flex items-center gap-3 px-3 py-3 bg-gray-50 dark:bg-white/[0.02] rounded-lg animate-pulse"
267 + >
268 + <div className="w-8 h-8 bg-gray-200 dark:bg-white/10 rounded-lg flex-shrink-0" />
269 + <div className="flex-1 space-y-1.5">
270 + <div className="h-3 bg-gray-200 dark:bg-white/10 rounded w-2/5" />
271 + <div className="h-2 bg-gray-200 dark:bg-white/10 rounded w-1/4" />
272 + </div>
273 + <div className="w-16 h-3 bg-gray-200 dark:bg-white/10 rounded flex-shrink-0" />
274 + </div>
275 + ))}
276 + </div>
277 + );
278 +
279 + // Empty state
280 + const EmptyState = () => {
281 + const isSearch = searchQuery.length > 0;
282 +
283 + return (
284 + <div className="flex flex-col items-center justify-center h-64 text-gray-500">
285 + {isSearch ? (
286 + <>
287 + <div className="relative mb-6">
288 + <Search className="w-16 h-16 text-gray-200 dark:text-gray-700" />
289 + <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
290 + <X className="w-3.5 h-3.5 text-gray-400" />
291 + </div>
292 + </div>
293 + <p className="text-lg font-medium text-gray-600 dark:text-gray-400">
294 + Aucun resultat
295 + </p>
296 + <p className="text-sm mt-1 text-gray-400 dark:text-gray-500">
297 + Aucun fichier ne correspond a "{searchQuery}"
298 + </p>
299 + </>
300 + ) : (
301 + <>
302 + <div className="relative mb-6">
303 + <FolderOpen className="w-16 h-16 text-gray-200 dark:text-gray-700" />
304 + <div className="absolute -top-2 -right-4 flex gap-1.5 opacity-40">
305 + <FileText className="w-5 h-5 text-blue-400" />
306 + <Image className="w-5 h-5 text-green-400" />
307 + <Film className="w-5 h-5 text-purple-400" />
308 + </div>
309 + </div>
310 + <p className="text-lg font-medium text-gray-600 dark:text-gray-400">
311 + Dossier vide
312 + </p>
313 + <p className="text-sm mt-1 text-gray-400 dark:text-gray-500">
314 + Uploadez vos premiers fichiers pour commencer
315 + </p>
316 + <Button
317 + className="mt-4"
318 + size="sm"
319 + onClick={() => setShowUpload(true)}
320 + >
321 + <Upload className="w-4 h-4" /> Upload
322 + </Button>
323 + </>
324 + )}
325 + </div>
326 + );
327 + };
328 +
329 + // Tri (dossiers toujours triés par nom ; fichiers selon le critère choisi)
330 + const dirMul = sortDir === "asc" ? 1 : -1;
331 + const sortedFolders = [...folders].sort(
332 + (a, b) => dirMul * a.name.localeCompare(b.name, "fr")
333 + );
334 + const sortedFiles = [...files].sort((a, b) => {
335 + let r = 0;
336 + switch (sortKey) {
337 + case "date":
338 + r = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
339 + break;
340 + case "size":
341 + r = (a.size || 0) - (b.size || 0);
342 + break;
343 + case "type":
344 + r = (a.mimeType || "").localeCompare(b.mimeType || "") ||
345 + a.name.localeCompare(b.name, "fr");
346 + break;
347 + default:
348 + r = a.name.localeCompare(b.name, "fr");
349 + }
350 + return dirMul * r;
351 + });
352 +
353 + // En-tête de colonnes (vue liste)
354 + const ListHeader = () => (
355 + <div className="hidden sm:flex items-center gap-3 px-3 py-2 border-b border-gray-200 dark:border-white/10 text-[11px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
356 + <span className="w-8 flex-shrink-0" />
357 + <span className="flex-1 min-w-0">Nom</span>
358 + <span className="w-24 text-right flex-shrink-0">Taille</span>
359 + <span className="w-28 text-right flex-shrink-0 hidden md:block">Modifié</span>
360 + <span className="w-11 flex-shrink-0" />
361 + </div>
362 + );
363 +
86 364 return (
87 365 <div className="flex flex-col h-full lg:flex-row overflow-x-hidden">
88 − <div className="flex-1 flex flex-col min-w-0 overflow-x-hidden">
366 + <div
367 + ref={containerRef}
368 + className="flex-1 flex flex-col min-w-0 overflow-x-hidden"
369 + >
89 370 {/* Toolbar */}
90 371 <div className="px-4 lg:px-6 py-4 border-b border-gray-200 dark:border-white/10 flex flex-col sm:flex-row items-start sm:items-center gap-3">
91 372 <div className="flex-1 w-full sm:w-auto">
92 − <SearchBar onSearch={handleSearch} placeholder="Rechercher des fichiers..." />
373 + <SearchBar
374 + onSearch={handleSearch}
375 + placeholder="Rechercher des fichiers..."
376 + />
93 377 </div>
94 378 <div className="flex items-center gap-2 w-full sm:w-auto justify-between sm:justify-end">
379 + {/* Tri */}
380 + <div className="flex items-center gap-1">
381 + <select
382 + value={sortKey}
383 + onChange={(e) => setSortKey(e.target.value as "name" | "date" | "size" | "type")}
384 + className="bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg text-xs text-gray-600 dark:text-gray-300 h-10 pl-3 focus:outline-none"
385 + title="Trier par"
386 + >
387 + <option value="name">Nom</option>
388 + <option value="date">Date</option>
389 + <option value="size">Taille</option>
390 + <option value="type">Type</option>
391 + </select>
392 + <button
393 + onClick={() => setSortDir((d) => (d === "asc" ? "desc" : "asc"))}
394 + className="min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg bg-gray-100 dark:bg-white/5 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
395 + title={sortDir === "asc" ? "Ordre croissant" : "Ordre décroissant"}
396 + >
397 + {sortDir === "asc" ? <ArrowUpNarrowWide className="w-4 h-4" /> : <ArrowDownWideNarrow className="w-4 h-4" />}
398 + </button>
399 + </div>
95 400 <div className="flex items-center gap-1 bg-gray-100 dark:bg-white/5 rounded-lg p-1">
96 401 <button
97 402 onClick={() => setViewMode("grid")}
@@ -109,21 +414,38 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
109 414 <Button
110 415 variant={selectMode ? "secondary" : "ghost"}
111 416 size="sm"
112 − onClick={() => { setSelectMode(!selectMode); setSelectedIds([]); }}
417 + onClick={() => {
418 + setSelectMode(!selectMode);
419 + setSelectedIds([]);
420 + }}
113 421 className="min-w-[40px] min-h-[40px]"
114 422 >
115 423 <CheckSquare className="w-4 h-4" />
116 − <span className="hidden sm:inline">Sélection</span>
424 + <span className="hidden sm:inline">Selection</span>
117 425 </Button>
118 − <Button variant="ghost" size="sm" onClick={() => setShowCreateFolder(true)} className="min-w-[40px] min-h-[40px]">
426 + <Button
427 + variant="ghost"
428 + size="sm"
429 + onClick={() => setShowCreateFolder(true)}
430 + className="min-w-[40px] min-h-[40px]"
431 + >
119 432 <Plus className="w-4 h-4" />
120 433 <span className="hidden sm:inline">Dossier</span>
121 434 </Button>
122 − <Button variant="ghost" size="sm" onClick={() => setShowCreateSharedFolder(true)} className="min-w-[40px] min-h-[40px] text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300">
435 + <Button
436 + variant="ghost"
437 + size="sm"
438 + onClick={() => setShowCreateSharedFolder(true)}
439 + className="min-w-[40px] min-h-[40px] text-blue-700 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
440 + >
123 441 <Users className="w-4 h-4" />
124 − <span className="hidden sm:inline">Partagé</span>
442 + <span className="hidden sm:inline">Partage</span>
125 443 </Button>
126 − <Button size="sm" onClick={() => setShowUpload(!showUpload)} className="min-w-[40px] min-h-[40px]">
444 + <Button
445 + size="sm"
446 + onClick={() => setShowUpload(!showUpload)}
447 + className="min-w-[40px] min-h-[40px]"
448 + >
127 449 <Upload className="w-4 h-4" />
128 450 <span className="hidden sm:inline">Upload</span>
129 451 </Button>
@@ -131,14 +453,30 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
131 453 </div>
132 454
133 455 {/* Bulk Actions Bar */}
134 − <BulkActions selectedIds={selectedIds} onClear={() => { setSelectedIds([]); setSelectMode(false); }} onRefresh={fetchData} />
456 + <BulkActions
457 + selectedIds={selectedIds}
458 + onClear={() => {
459 + setSelectedIds([]);
460 + setSelectMode(false);
461 + }}
462 + onRefresh={handleRefresh}
463 + />
135 464
136 465 {/* Select All */}
137 466 {selectMode && files.length > 0 && (
138 467 <div className="px-4 lg:px-6 py-2 border-b border-gray-100 dark:border-white/5">
139 − <button onClick={selectAll} className="flex items-center gap-2 text-sm sm:text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 min-h-[40px]">
140 − {selectedIds.length === files.length ? <CheckSquare className="w-4 h-4 sm:w-3.5 sm:h-3.5" /> : <Square className="w-4 h-4 sm:w-3.5 sm:h-3.5" />}
141 − {selectedIds.length === files.length ? "Tout désélectionner" : "Tout sélectionner"}
468 + <button
469 + onClick={selectAll}
470 + className="flex items-center gap-2 text-sm sm:text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 min-h-[40px]"
471 + >
472 + {selectedIds.length === files.length ? (
473 + <CheckSquare className="w-4 h-4 sm:w-3.5 sm:h-3.5" />
474 + ) : (
475 + <Square className="w-4 h-4 sm:w-3.5 sm:h-3.5" />
476 + )}
477 + {selectedIds.length === files.length
478 + ? "Tout deselectionner"
479 + : "Tout selectionner"}
142 480 </button>
143 481 </div>
144 482 )}
@@ -146,8 +484,13 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
146 484 {/* Upload Zone */}
147 485 <AnimatePresence>
148 486 {showUpload && (
149 − <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} className="px-4 lg:px-6 pt-4">
150 − <FileUpload folderId={folderId} onUploadComplete={fetchData} />
487 + <motion.div
488 + initial={{ opacity: 0, height: 0 }}
489 + animate={{ opacity: 1, height: "auto" }}
490 + exit={{ opacity: 0, height: 0 }}
491 + className="px-4 lg:px-6 pt-4"
492 + >
493 + <FileUpload folderId={folderId} onUploadComplete={handleRefresh} />
151 494 </motion.div>
152 495 )}
153 496 </AnimatePresence>
@@ -155,34 +498,60 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
155 498 {/* Content */}
156 499 <div className="flex-1 overflow-auto overflow-x-hidden px-4 lg:px-6 py-4">
157 500 {loading ? (
158 − <div className="flex items-center justify-center h-32">
159 − <div className="w-6 h-6 border-2 border-gray-300 dark:border-white/20 border-t-gray-600 dark:border-t-white rounded-full animate-spin" />
501 + <div>
502 + {/* Skeleton for folders */}
503 + <div className="mb-6">
504 + <div className="h-3 w-16 bg-gray-200 dark:bg-white/10 rounded animate-pulse mb-3" />
505 + {viewMode === "grid" ? (
506 + <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-4 xl:grid-cols-6">
507 + {Array.from({ length: 3 }).map((_, i) => (
508 + <div
509 + key={`sf-${i}`}
510 + className="h-14 bg-gray-100 dark:bg-white/5 rounded-xl animate-pulse"
511 + />
512 + ))}
513 + </div>
514 + ) : (
515 + <div className="space-y-1">
516 + {Array.from({ length: 2 }).map((_, i) => (
517 + <div
518 + key={`sf-${i}`}
519 + className="h-12 bg-gray-50 dark:bg-white/[0.02] rounded-lg animate-pulse"
520 + />
521 + ))}
522 + </div>
523 + )}
524 + </div>
525 + {/* Skeleton for files */}
526 + <div className="h-3 w-20 bg-gray-200 dark:bg-white/10 rounded animate-pulse mb-3" />
527 + {viewMode === "grid" ? <SkeletonGrid /> : <SkeletonList />}
160 528 </div>
161 529 ) : (
162 530 <>
163 − {folders.length > 0 && (
164 − <div className="mb-6">
165 − <h3 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-3">Dossiers</h3>
166 − <div className={viewMode === "grid" ? "grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-4 xl:grid-cols-5" : "space-y-1"}>
167 − {folders.map((folder) => (
168 − <FolderCard key={folder.id} folder={folder} onRefresh={fetchData} viewMode={viewMode} />
531 + {folders.length === 0 && files.length === 0 ? (
532 + <EmptyState />
533 + ) : viewMode === "list" ? (
534 + /* ===== Vue Liste — explorateur à colonnes (dossiers d'abord) ===== */
535 + <div className="rounded-xl border border-gray-200 dark:border-white/10 overflow-hidden bg-white dark:bg-white/[0.02] shadow-sm dark:shadow-none">
536 + <ListHeader />
537 + <div className="divide-y divide-gray-100 dark:divide-white/5">
538 + {sortedFolders.map((folder) => (
539 + <FolderCard
540 + key={folder.id}
541 + folder={folder}
542 + onRefresh={handleRefresh}
543 + viewMode="list"
544 + />
169 545 ))}
170 − </div>
171 − </div>
172 − )}
173 −
174 − {files.length > 0 && (
175 − <div>
176 − <h3 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-3">
177 − Fichiers ({files.length})
178 − </h3>
179 − <div className={viewMode === "grid" ? "grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-4 xl:grid-cols-5" : "space-y-1"}>
180 − {files.map((file) => (
546 + {sortedFiles.map((file) => (
181 547 <div key={file.id} className="relative">
182 548 {selectMode && (
183 549 <button
184 − onClick={(e) => { e.stopPropagation(); toggleSelect(file.id); }}
185 − className="absolute top-2 left-2 z-10 p-1.5 bg-white/80 dark:bg-black/50 rounded-md backdrop-blur-sm min-w-[36px] min-h-[36px] flex items-center justify-center"
550 + onClick={(e) => {
551 + e.stopPropagation();
552 + toggleSelect(file.id);
553 + }}
554 + className="absolute top-1/2 -translate-y-1/2 left-1.5 z-10 p-1 bg-white/90 dark:bg-black/60 rounded-md backdrop-blur-sm flex items-center justify-center"
186 555 >
187 556 {selectedIds.includes(file.id) ? (
188 557 <CheckSquare className="w-4 h-4 text-blue-500" />
@@ -191,28 +560,95 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
191 560 )}
192 561 </button>
193 562 )}
194 − <div className={selectedIds.includes(file.id) ? "ring-2 ring-blue-500 rounded-xl" : ""}>
563 + <div className={selectedIds.includes(file.id) ? "ring-2 ring-inset ring-blue-500" : ""}>
195 564 <FileCard
196 565 file={file}
197 566 onPreview={handleFileClick}
198 − onRefresh={fetchData}
199 − viewMode={viewMode}
567 + onRefresh={handleRefresh}
568 + viewMode="list"
200 569 />
201 570 </div>
202 571 </div>
203 572 ))}
204 573 </div>
205 574 </div>
575 + ) : (
576 + /* ===== Vue Grille ===== */
577 + <>
578 + {folders.length > 0 && (
579 + <div className="mb-6">
580 + <h3 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-3">
581 + Dossiers
582 + </h3>
583 + <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-4 xl:grid-cols-6">
584 + {sortedFolders.map((folder) => (
585 + <FolderCard
586 + key={folder.id}
587 + folder={folder}
588 + onRefresh={handleRefresh}
589 + viewMode="grid"
590 + />
591 + ))}
592 + </div>
593 + </div>
594 + )}
595 + {files.length > 0 && (
596 + <div>
597 + <h3 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-3">
598 + Fichiers ({files.length}
599 + {hasMore ? "+" : ""})
600 + </h3>
601 + <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 sm:gap-3 lg:grid-cols-6 xl:grid-cols-8">
602 + {sortedFiles.map((file) => (
603 + <div key={file.id} className="relative">
604 + {selectMode && (
605 + <button
606 + onClick={(e) => {
607 + e.stopPropagation();
608 + toggleSelect(file.id);
609 + }}
610 + className="absolute top-2 left-2 z-10 p-1.5 bg-white/80 dark:bg-black/50 rounded-md backdrop-blur-sm min-w-[36px] min-h-[36px] flex items-center justify-center"
611 + >
612 + {selectedIds.includes(file.id) ? (
613 + <CheckSquare className="w-4 h-4 text-blue-500" />
614 + ) : (
615 + <Square className="w-4 h-4 text-gray-400" />
616 + )}
617 + </button>
618 + )}
619 + <div className={selectedIds.includes(file.id) ? "ring-2 ring-blue-500 rounded-xl" : ""}>
620 + <FileCard
621 + file={file}
622 + onPreview={handleFileClick}
623 + onRefresh={handleRefresh}
624 + viewMode="grid"
625 + />
626 + </div>
627 + </div>
628 + ))}
629 + </div>
630 + </div>
631 + )}
632 + </>
206 633 )}
207 634
208 − {folders.length === 0 && files.length === 0 && (
209 − <div className="flex flex-col items-center justify-center h-64 text-gray-500">
210 − <Upload className="w-12 h-12 mb-4 text-gray-300 dark:text-gray-600" />
211 − <p className="text-lg">Aucun fichier</p>
212 − <p className="text-sm mt-1">Uploadez vos premiers fichiers</p>
213 − <Button className="mt-4" size="sm" onClick={() => setShowUpload(true)}>
214 − <Upload className="w-4 h-4" /> Upload
215 − </Button>
635 + {/* Charger plus (commun aux deux vues) */}
636 + {hasMore && (
637 + <div className="mt-6 flex justify-center">
638 + <button
639 + onClick={() => fetchData(true)}
640 + disabled={loadingMore}
641 + className="px-6 py-3 text-sm font-medium text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-white/5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-xl transition-colors disabled:opacity-50 min-h-[44px]"
642 + >
643 + {loadingMore ? (
644 + <span className="flex items-center gap-2">
645 + <div className="w-4 h-4 border-2 border-gray-400 dark:border-white/30 border-t-transparent rounded-full animate-spin" />
646 + Chargement...
647 + </span>
648 + ) : (
649 + "Charger plus"
650 + )}
651 + </button>
216 652 </div>
217 653 )}
218 654 </>
@@ -222,12 +658,26 @@ export default function FileExplorer({ folderId }: FileExplorerProps) {
222 658
223 659 {previewFile && (
224 660 <div className="fixed inset-0 z-50 lg:relative lg:inset-auto lg:w-[400px] lg:border-l lg:border-gray-200 dark:lg:border-white/10">
225 − <PreviewEngine file={previewFile} files={files} onClose={() => setPreviewFile(null)} onNavigate={setPreviewFile} />
661 + <PreviewEngine
662 + file={previewFile}
663 + files={files}
664 + onClose={() => setPreviewFile(null)}
665 + onNavigate={setPreviewFile}
666 + />
226 667 </div>
227 668 )}
228 669
229 − <CreateFolderModal isOpen={showCreateFolder} onClose={() => setShowCreateFolder(false)} parentId={folderId || null} onCreated={fetchData} />
230 − <CreateSharedFolderModal isOpen={showCreateSharedFolder} onClose={() => setShowCreateSharedFolder(false)} onCreated={fetchData} />
670 + <CreateFolderModal
671 + isOpen={showCreateFolder}
672 + onClose={() => setShowCreateFolder(false)}
673 + parentId={folderId || null}
674 + onCreated={handleRefresh}
675 + />
676 + <CreateSharedFolderModal
677 + isOpen={showCreateSharedFolder}
678 + onClose={() => setShowCreateSharedFolder(false)}
679 + onCreated={handleRefresh}
680 + />
231 681 </div>
232 682 );
233 683 }
modified components/files/FileUpload.tsx +394 −73
@@ -1,16 +1,29 @@
1 1 "use client";
2 2
3 −import { useCallback, useState } from "react";
3 +import { useCallback, useState, useRef, useEffect } from "react";
4 4 import { useDropzone } from "react-dropzone";
5 5 import { motion, AnimatePresence } from "framer-motion";
6 −import { Upload, CheckCircle, AlertCircle } from "lucide-react";
6 +import {
7 + Upload,
8 + CheckCircle,
9 + AlertCircle,
10 + X,
11 + ChevronDown,
12 + ChevronUp,
13 + Clock,
14 + Ban,
15 +} from "lucide-react";
7 16 import { formatFileSize } from "@/lib/utils";
8 17
18 +type UploadStatus = "waiting" | "uploading" | "done" | "error" | "cancelled";
19 +
9 20 interface UploadItem {
21 + id: string;
10 22 file: File;
11 23 progress: number;
12 − status: "uploading" | "done" | "error";
24 + status: UploadStatus;
13 25 error?: string;
26 + xhr?: XMLHttpRequest;
14 27 }
15 28
16 29 interface FileUploadProps {
@@ -18,55 +31,197 @@ interface FileUploadProps {
18 31 onUploadComplete: () => void;
19 32 }
20 33
21 −export default function FileUpload({ folderId, onUploadComplete }: FileUploadProps) {
34 +const CONCURRENT_LIMIT = 2;
35 +
36 +export default function FileUpload({
37 + folderId,
38 + onUploadComplete,
39 +}: FileUploadProps) {
22 40 const [uploads, setUploads] = useState<UploadItem[]>([]);
41 + const [collapsed, setCollapsed] = useState(false);
42 + const [showSummary, setShowSummary] = useState(false);
43 + const activeCount = useRef(0);
44 + const queueRef = useRef<UploadItem[]>([]);
45 + const uploadsRef = useRef<UploadItem[]>([]);
46 +
47 + // Keep ref in sync with state
48 + useEffect(() => {
49 + uploadsRef.current = uploads;
50 + }, [uploads]);
51 +
52 + const updateUpload = useCallback(
53 + (id: string, patch: Partial<UploadItem>) => {
54 + setUploads((prev) =>
55 + prev.map((u) => (u.id === id ? { ...u, ...patch } : u))
56 + );
57 + },
58 + []
59 + );
60 +
61 + const processQueue = useCallback(() => {
62 + while (
63 + activeCount.current < CONCURRENT_LIMIT &&
64 + queueRef.current.length > 0
65 + ) {
66 + const item = queueRef.current.shift();
67 + if (!item) break;
68 +
69 + // Check if cancelled while waiting
70 + const current = uploadsRef.current.find((u) => u.id === item.id);
71 + if (current && current.status === "cancelled") continue;
23 72
24 − const uploadFile = useCallback(
25 − async (file: File) => {
73 + activeCount.current++;
74 + startUpload(item);
75 + }
76 + // eslint-disable-next-line react-hooks/exhaustive-deps
77 + }, []);
78 +
79 + const startUpload = useCallback(
80 + (item: UploadItem) => {
81 + const xhr = new XMLHttpRequest();
26 82 const formData = new FormData();
27 − formData.append("file", file);
83 + formData.append("file", item.file);
28 84 if (folderId) formData.append("folderId", folderId);
29 85
30 − setUploads((prev) => [
31 − ...prev,
32 − { file, progress: 0, status: "uploading" },
33 − ]);
86 + // Store xhr reference for cancel
87 + updateUpload(item.id, { status: "uploading", xhr });
34 88
35 − try {
36 − const res = await fetch("/api/files", {
37 − method: "POST",
38 − body: formData,
39 − });
89 + xhr.upload.addEventListener("progress", (e) => {
90 + if (e.lengthComputable) {
91 + const pct = Math.round((e.loaded / e.total) * 100);
92 + updateUpload(item.id, { progress: pct });
93 + }
94 + });
40 95
41 − if (!res.ok) {
42 − const data = await res.json();
43 − throw new Error(data.error || "Upload failed");
96 + xhr.addEventListener("load", () => {
97 + activeCount.current--;
98 + if (xhr.status >= 200 && xhr.status < 300) {
99 + updateUpload(item.id, {
100 + progress: 100,
101 + status: "done",
102 + xhr: undefined,
103 + });
104 + onUploadComplete();
105 + } else {
106 + let errorMsg = "Erreur upload";
107 + try {
108 + const data = JSON.parse(xhr.responseText);
109 + errorMsg = data.error || errorMsg;
110 + } catch {
111 + // ignore parse error
112 + }
113 + updateUpload(item.id, {
114 + status: "error",
115 + error: errorMsg,
116 + xhr: undefined,
117 + });
44 118 }
119 + processQueue();
120 + checkAllDone();
121 + });
45 122
46 − setUploads((prev) =>
47 − prev.map((u) =>
48 − u.file === file ? { ...u, progress: 100, status: "done" } : u
49 − )
50 − );
51 − onUploadComplete();
52 − } catch (err) {
53 − setUploads((prev) =>
54 − prev.map((u) =>
55 − u.file === file
56 − ? { ...u, status: "error", error: (err as Error).message }
57 − : u
58 − )
59 − );
60 − }
123 + xhr.addEventListener("error", () => {
124 + activeCount.current--;
125 + updateUpload(item.id, {
126 + status: "error",
127 + error: "Erreur reseau",
128 + xhr: undefined,
129 + });
130 + processQueue();
131 + checkAllDone();
132 + });
133 +
134 + xhr.addEventListener("abort", () => {
135 + activeCount.current--;
136 + updateUpload(item.id, {
137 + status: "cancelled",
138 + xhr: undefined,
139 + });
140 + processQueue();
141 + checkAllDone();
142 + });
143 +
144 + xhr.open("POST", "/api/files");
145 + xhr.send(formData);
61 146 },
62 − [folderId, onUploadComplete]
147 + // eslint-disable-next-line react-hooks/exhaustive-deps
148 + [folderId, onUploadComplete, updateUpload, processQueue]
63 149 );
64 150
151 + const checkAllDone = () => {
152 + // Use a small timeout so state has flushed
153 + setTimeout(() => {
154 + setUploads((prev) => {
155 + const allFinished = prev.every(
156 + (u) =>
157 + u.status === "done" ||
158 + u.status === "error" ||
159 + u.status === "cancelled"
160 + );
161 + if (allFinished && prev.length > 0) {
162 + setShowSummary(true);
163 + }
164 + return prev;
165 + });
166 + }, 200);
167 + };
168 +
169 + const cancelUpload = useCallback((id: string) => {
170 + setUploads((prev) =>
171 + prev.map((u) => {
172 + if (u.id === id) {
173 + if (u.xhr) u.xhr.abort();
174 + // If waiting, just mark cancelled
175 + if (u.status === "waiting") {
176 + queueRef.current = queueRef.current.filter((q) => q.id !== id);
177 + return { ...u, status: "cancelled" as UploadStatus };
178 + }
179 + }
180 + return u;
181 + })
182 + );
183 + }, []);
184 +
185 + const cancelAll = useCallback(() => {
186 + queueRef.current = [];
187 + setUploads((prev) =>
188 + prev.map((u) => {
189 + if (u.status === "uploading" && u.xhr) {
190 + u.xhr.abort();
191 + }
192 + if (u.status === "waiting" || u.status === "uploading") {
193 + return { ...u, status: "cancelled" as UploadStatus, xhr: undefined };
194 + }
195 + return u;
196 + })
197 + );
198 + activeCount.current = 0;
199 + }, []);
200 +
201 + const clearUploads = useCallback(() => {
202 + setUploads([]);
203 + setShowSummary(false);
204 + queueRef.current = [];
205 + activeCount.current = 0;
206 + }, []);
207 +
65 208 const onDrop = useCallback(
66 209 (acceptedFiles: File[]) => {
67 − acceptedFiles.forEach((file) => uploadFile(file));
210 + setShowSummary(false);
211 + const newItems: UploadItem[] = acceptedFiles.map((file) => ({
212 + id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
213 + file,
214 + progress: 0,
215 + status: "waiting" as UploadStatus,
216 + }));
217 +
218 + setUploads((prev) => [...prev, ...newItems]);
219 +
220 + // Add to queue and process
221 + queueRef.current.push(...newItems);
222 + processQueue();
68 223 },
69 − [uploadFile]
224 + [processQueue]
70 225 );
71 226
72 227 const { getRootProps, getInputProps, isDragActive } = useDropzone({
@@ -74,10 +229,18 @@ export default function FileUpload({ folderId, onUploadComplete }: FileUploadPro
74 229 noClick: false,
75 230 });
76 231
77 − const clearUploads = () => setUploads([]);
232 + const doneCount = uploads.filter((u) => u.status === "done").length;
233 + const errorCount = uploads.filter((u) => u.status === "error").length;
234 + const cancelledCount = uploads.filter(
235 + (u) => u.status === "cancelled"
236 + ).length;
237 + const hasActive = uploads.some(
238 + (u) => u.status === "uploading" || u.status === "waiting"
239 + );
78 240
79 241 return (
80 242 <div>
243 + {/* Drop zone */}
81 244 <div
82 245 {...getRootProps()}
83 246 className={`border-2 border-dashed rounded-xl p-6 sm:p-8 text-center cursor-pointer transition-all ${
@@ -89,61 +252,219 @@ export default function FileUpload({ folderId, onUploadComplete }: FileUploadPro
89 252 <input {...getInputProps()} />
90 253 <Upload className="w-8 h-8 mx-auto mb-3 text-gray-400 dark:text-gray-500" />
91 254 <p className="text-sm text-gray-500 dark:text-gray-400">
92 − {isDragActive
93 − ? "Déposez les fichiers ici..."
94 − : (
95 − <>
96 − <span className="hidden sm:inline">Glissez-déposez vos fichiers ou cliquez pour sélectionner</span>
97 − <span className="sm:hidden">Tapez pour sélectionner des fichiers</span>
98 − </>
99 − )}
255 + {isDragActive ? (
256 + "Deposez les fichiers ici..."
257 + ) : (
258 + <>
259 + <span className="hidden sm:inline">
260 + Glissez-deposez vos fichiers ou cliquez pour selectionner
261 + </span>
262 + <span className="sm:hidden">
263 + Tapez pour selectionner des fichiers
264 + </span>
265 + </>
266 + )}
100 267 </p>
101 268 <p className="text-xs text-gray-400 dark:text-gray-600 mt-1">
102 − Max {formatFileSize(parseInt(process.env.NEXT_PUBLIC_MAX_FILE_SIZE || "104857600"))}
269 + Max{" "}
270 + {formatFileSize(
271 + parseInt(process.env.NEXT_PUBLIC_MAX_FILE_SIZE || "104857600")
272 + )}
103 273 </p>
104 274 </div>
105 275
276 + {/* Upload panel */}
106 277 <AnimatePresence>
107 278 {uploads.length > 0 && (
108 279 <motion.div
109 280 initial={{ opacity: 0, height: 0 }}
110 281 animate={{ opacity: 1, height: "auto" }}
111 282 exit={{ opacity: 0, height: 0 }}
112 − className="mt-3 space-y-2"
283 + className="mt-3 bg-gray-50 dark:bg-white/[0.03] border border-gray-200 dark:border-white/10 rounded-xl overflow-hidden"
113 284 >
114 − <div className="flex items-center justify-between">
115 − <span className="text-xs text-gray-500">
116 − {uploads.filter((u) => u.status === "done").length}/{uploads.length} terminé
117 − </span>
118 − <button onClick={clearUploads} className="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 min-h-[36px] px-2">
119 − Effacer
120 − </button>
121 − </div>
122 − {uploads.map((upload, i) => (
123 − <div
124 − key={i}
125 − className="flex items-center gap-3 bg-gray-100 dark:bg-white/5 rounded-lg px-3 py-3 sm:py-2"
285 + {/* Panel header */}
286 + <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-white/10">
287 + <button
288 + onClick={() => setCollapsed(!collapsed)}
289 + className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300 min-h-[36px]"
126 290 >
127 − {upload.status === "uploading" && (
128 − <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin flex-shrink-0" />
291 + {collapsed ? (
292 + <ChevronDown className="w-4 h-4" />
293 + ) : (
294 + <ChevronUp className="w-4 h-4" />
129 295 )}
130 − {upload.status === "done" && (
131 − <CheckCircle className="w-4 h-4 text-green-500 dark:text-green-400 flex-shrink-0" />
296 + <span>
297 + {doneCount}/{uploads.length} fichiers uploades
298 + </span>
299 + {hasActive && (
300 + <span className="ml-2 w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
132 301 )}
133 − {upload.status === "error" && (
134 − <AlertCircle className="w-4 h-4 text-red-500 dark:text-red-400 flex-shrink-0" />
302 + </button>
303 + <div className="flex items-center gap-2">
304 + {hasActive && (
305 + <button
306 + onClick={cancelAll}
307 + className="text-xs text-red-500 hover:text-red-600 dark:text-red-400 dark:hover:text-red-300 px-2 min-h-[36px] font-medium"
308 + >
309 + Annuler tout
310 + </button>
311 + )}
312 + {!hasActive && (
313 + <button
314 + onClick={clearUploads}
315 + className="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-2 min-h-[36px]"
316 + >
317 + Effacer
318 + </button>
135 319 )}
136 − <span className="text-sm text-gray-600 dark:text-gray-300 truncate flex-1">
137 − {upload.file.name}
138 − </span>
139 − <span className="text-xs text-gray-500 flex-shrink-0">
140 − {formatFileSize(upload.file.size)}
141 − </span>
142 320 </div>
143 − ))}
321 + </div>
322 +
323 + {/* File list */}
324 + <AnimatePresence>
325 + {!collapsed && (
326 + <motion.div
327 + initial={{ height: 0, opacity: 0 }}
328 + animate={{ height: "auto", opacity: 1 }}
329 + exit={{ height: 0, opacity: 0 }}
330 + className="max-h-64 overflow-y-auto"
331 + >
332 + <div className="divide-y divide-gray-100 dark:divide-white/5">
333 + {uploads.map((upload) => (
334 + <UploadRow
335 + key={upload.id}
336 + upload={upload}
337 + onCancel={() => cancelUpload(upload.id)}
338 + />
339 + ))}
340 + </div>
341 + </motion.div>
342 + )}
343 + </AnimatePresence>
344 +
345 + {/* Summary */}
346 + <AnimatePresence>
347 + {showSummary && !hasActive && (
348 + <motion.div
349 + initial={{ opacity: 0 }}
350 + animate={{ opacity: 1 }}
351 + exit={{ opacity: 0 }}
352 + className="px-4 py-3 border-t border-gray-200 dark:border-white/10 text-xs text-gray-500 dark:text-gray-400 flex items-center gap-3"
353 + >
354 + {doneCount > 0 && (
355 + <span className="flex items-center gap-1 text-green-600 dark:text-green-400">
356 + <CheckCircle className="w-3.5 h-3.5" />
357 + {doneCount} termine{doneCount > 1 ? "s" : ""}
358 + </span>
359 + )}
360 + {errorCount > 0 && (
361 + <span className="flex items-center gap-1 text-red-500 dark:text-red-400">
362 + <AlertCircle className="w-3.5 h-3.5" />
363 + {errorCount} erreur{errorCount > 1 ? "s" : ""}
364 + </span>
365 + )}
366 + {cancelledCount > 0 && (
367 + <span className="flex items-center gap-1 text-gray-400">
368 + <Ban className="w-3.5 h-3.5" />
369 + {cancelledCount} annule{cancelledCount > 1 ? "s" : ""}
370 + </span>
371 + )}
372 + </motion.div>
373 + )}
374 + </AnimatePresence>
144 375 </motion.div>
145 376 )}
146 377 </AnimatePresence>
147 378 </div>
148 379 );
149 380 }
381 +
382 +function UploadRow({
383 + upload,
384 + onCancel,
385 +}: {
386 + upload: UploadItem;
387 + onCancel: () => void;
388 +}) {
389 + const { file, progress, status, error } = upload;
390 +
391 + return (
392 + <div className="px-4 py-3">
393 + <div className="flex items-center gap-3">
394 + {/* Status icon */}
395 + <div className="flex-shrink-0">
396 + {status === "waiting" && (
397 + <Clock className="w-4 h-4 text-gray-400" />
398 + )}
399 + {status === "uploading" && (
400 + <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
401 + )}
402 + {status === "done" && (
403 + <CheckCircle className="w-4 h-4 text-green-500 dark:text-green-400" />
404 + )}
405 + {status === "error" && (
406 + <AlertCircle className="w-4 h-4 text-red-500 dark:text-red-400" />
407 + )}
408 + {status === "cancelled" && (
409 + <Ban className="w-4 h-4 text-gray-400" />
410 + )}
411 + </div>
412 +
413 + {/* File info */}
414 + <div className="flex-1 min-w-0">
415 + <div className="flex items-center justify-between gap-2">
416 + <span
417 + className={`text-sm truncate ${
418 + status === "cancelled"
419 + ? "text-gray-400 line-through"
420 + : status === "error"
421 + ? "text-red-500 dark:text-red-400"
422 + : "text-gray-700 dark:text-gray-300"
423 + }`}
424 + >
425 + {file.name}
426 + </span>
427 + <div className="flex items-center gap-2 flex-shrink-0">
428 + <span className="text-xs text-gray-400">
429 + {formatFileSize(file.size)}
430 + </span>
431 + {status === "uploading" && (
432 + <span className="text-xs font-medium text-blue-500 tabular-nums w-9 text-right">
433 + {progress}%
434 + </span>
435 + )}
436 + </div>
437 + </div>
438 +
439 + {/* Progress bar */}
440 + {(status === "uploading" || status === "waiting") && (
441 + <div className="mt-1.5 h-1.5 bg-gray-200 dark:bg-white/10 rounded-full overflow-hidden">
442 + <motion.div
443 + className="h-full bg-blue-500 rounded-full"
444 + initial={{ width: 0 }}
445 + animate={{ width: `${progress}%` }}
446 + transition={{ duration: 0.3, ease: "easeOut" }}
447 + />
448 + </div>
449 + )}
450 +
451 + {/* Error message */}
452 + {status === "error" && error && (
453 + <p className="text-xs text-red-400 mt-1">{error}</p>
454 + )}
455 + </div>
456 +
457 + {/* Cancel button */}
458 + {(status === "uploading" || status === "waiting") && (
459 + <button
460 + onClick={onCancel}
461 + className="flex-shrink-0 p-1.5 rounded-md hover:bg-gray-200 dark:hover:bg-white/10 transition-colors min-w-[32px] min-h-[32px] flex items-center justify-center"
462 + title="Annuler"
463 + >
464 + <X className="w-3.5 h-3.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
465 + </button>
466 + )}
467 + </div>
468 + </div>
469 + );
470 +}
added components/files/MoveModal.tsx +116 −0
@@ -0,0 +1,116 @@
1 +"use client";
2 +
3 +import { useEffect, useState, useCallback } from "react";
4 +import { Folder, FolderOpen, Home, ChevronRight, ChevronDown } from "lucide-react";
5 +import Modal from "../ui/Modal";
6 +
7 +interface TreeFolder {
8 + id: string;
9 + name: string;
10 + children?: TreeFolder[];
11 +}
12 +
13 +interface MoveModalProps {
14 + isOpen: boolean;
15 + onClose: () => void;
16 + /** Appelée avec "root" ou l'id du dossier cible. */
17 + onSelect: (folderId: string) => void;
18 + /** Dossier (et son sous-arbre) à masquer — pour le déplacement d'un dossier. */
19 + excludeId?: string;
20 + title?: string;
21 + itemName?: string;
22 +}
23 +
24 +export default function MoveModal({
25 + isOpen,
26 + onClose,
27 + onSelect,
28 + excludeId,
29 + title = "Déplacer vers",
30 + itemName,
31 +}: MoveModalProps) {
32 + const [tree, setTree] = useState<TreeFolder[]>([]);
33 + const [expanded, setExpanded] = useState<Set<string>>(new Set());
34 + const [loading, setLoading] = useState(false);
35 +
36 + useEffect(() => {
37 + if (!isOpen) return;
38 + setLoading(true);
39 + fetch("/api/folders?tree=true")
40 + .then((r) => (r.ok ? r.json() : []))
41 + .then((data) => setTree(Array.isArray(data) ? data : []))
42 + .catch(() => setTree([]))
43 + .finally(() => setLoading(false));
44 + }, [isOpen]);
45 +
46 + const toggle = useCallback((id: string) => {
47 + setExpanded((prev) => {
48 + const next = new Set(prev);
49 + next.has(id) ? next.delete(id) : next.add(id);
50 + return next;
51 + });
52 + }, []);
53 +
54 + function renderNode(node: TreeFolder, depth: number): React.ReactNode {
55 + if (node.id === excludeId) return null; // masque le dossier déplacé + son sous-arbre
56 + const kids = node.children ?? [];
57 + const hasKids = kids.length > 0;
58 + const isOpen = expanded.has(node.id);
59 + return (
60 + <div key={node.id}>
61 + <div
62 + className="flex items-center gap-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"
63 + style={{ paddingLeft: depth * 16 }}
64 + >
65 + <button
66 + onClick={() => hasKids && toggle(node.id)}
67 + className="w-6 h-9 flex items-center justify-center flex-shrink-0 text-gray-400"
68 + tabIndex={hasKids ? 0 : -1}
69 + >
70 + {hasKids ? (
71 + isOpen ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />
72 + ) : null}
73 + </button>
74 + <button
75 + onClick={() => onSelect(node.id)}
76 + className="flex items-center gap-2 flex-1 min-w-0 py-2.5 text-sm text-gray-700 dark:text-gray-200 text-left"
77 + >
78 + {isOpen && hasKids ? (
79 + <FolderOpen className="w-4 h-4 text-blue-500 flex-shrink-0" />
80 + ) : (
81 + <Folder className="w-4 h-4 text-blue-400 flex-shrink-0" />
82 + )}
83 + <span className="truncate">{node.name}</span>
84 + </button>
85 + </div>
86 + {hasKids && isOpen && (
87 + <div>{kids.map((c) => renderNode(c, depth + 1))}</div>
88 + )}
89 + </div>
90 + );
91 + }
92 +
93 + return (
94 + <Modal isOpen={isOpen} onClose={onClose} title={title}>
95 + {itemName && (
96 + <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
97 + Déplacer <strong className="text-gray-700 dark:text-gray-200">{itemName}</strong> vers&nbsp;:
98 + </p>
99 + )}
100 + <div className="space-y-0.5 max-h-[55vh] overflow-y-auto">
101 + <button
102 + onClick={() => onSelect("root")}
103 + className="flex items-center gap-2 w-full px-2 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 rounded-lg"
104 + >
105 + <Home className="w-4 h-4 text-gray-500 flex-shrink-0" />
106 + Racine (Fichiers)
107 + </button>
108 + {loading ? (
109 + <p className="px-2 py-3 text-sm text-gray-400">Chargement…</p>
110 + ) : (
111 + tree.map((n) => renderNode(n, 0))
112 + )}
113 + </div>
114 + </Modal>
115 + );
116 +}
modified components/folders/CreateSharedFolderModal.tsx +7 −7
@@ -20,7 +20,7 @@ interface CreateSharedFolderModalProps {
20 20 }
21 21
22 22 const inputClasses =
23 − "w-full bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg px-4 py-2.5 text-gray-900 dark:text-white text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:border-purple-400 dark:focus:border-purple-500";
23 + "w-full bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg px-4 py-2.5 text-gray-900 dark:text-white text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:border-blue-600 dark:focus:border-blue-700";
24 24
25 25 export default function CreateSharedFolderModal({
26 26 isOpen,
@@ -117,7 +117,7 @@ export default function CreateSharedFolderModal({
117 117 <Users className="w-3.5 h-3.5" />
118 118 Partager avec
119 119 {selectedIds.length > 0 && (
120 − <span className="ml-auto text-purple-600 dark:text-purple-400 font-semibold">
120 + <span className="ml-auto text-blue-600 dark:text-blue-400 font-semibold">
121 121 {selectedIds.length} sélectionné(s)
122 122 </span>
123 123 )}
@@ -125,7 +125,7 @@ export default function CreateSharedFolderModal({
125 125
126 126 {loadingUsers ? (
127 127 <div className="flex items-center justify-center py-6 text-sm text-gray-400">
128 − <div className="w-4 h-4 border-2 border-gray-300 dark:border-white/20 border-t-purple-500 rounded-full animate-spin mr-2" />
128 + <div className="w-4 h-4 border-2 border-gray-300 dark:border-white/20 border-t-blue-700 rounded-full animate-spin mr-2" />
129 129 Chargement des utilisateurs...
130 130 </div>
131 131 ) : users.length === 0 ? (
@@ -162,14 +162,14 @@ export default function CreateSharedFolderModal({
162 162 onClick={() => toggleUser(u.id)}
163 163 className={`w-full flex items-center gap-3 px-3 py-2.5 text-left transition-colors border-b border-gray-50 dark:border-white/5 last:border-0 ${
164 164 isSelected
165 − ? "bg-purple-50 dark:bg-purple-500/10"
165 + ? "bg-blue-50 dark:bg-blue-500/10"
166 166 : "hover:bg-gray-50 dark:hover:bg-white/5"
167 167 }`}
168 168 >
169 169 {/* Avatar */}
170 170 <div className={`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 text-xs font-semibold ${
171 171 isSelected
172 − ? "bg-purple-500 text-white"
172 + ? "bg-blue-700 text-white"
173 173 : "bg-gray-200 dark:bg-white/10 text-gray-600 dark:text-gray-300"
174 174 }`}>
175 175 {isSelected ? <Check className="w-3.5 h-3.5" /> : initial}
@@ -185,7 +185,7 @@ export default function CreateSharedFolderModal({
185 185 {/* Checkbox indicator */}
186 186 <div className={`w-4 h-4 rounded border flex-shrink-0 flex items-center justify-center transition-colors ${
187 187 isSelected
188 − ? "bg-purple-500 border-purple-500"
188 + ? "bg-blue-700 border-blue-700"
189 189 : "border-gray-300 dark:border-white/20"
190 190 }`}>
191 191 {isSelected && <Check className="w-3 h-3 text-white" />}
@@ -200,7 +200,7 @@ export default function CreateSharedFolderModal({
200 200
201 201 {/* Info note */}
202 202 <p className="text-xs text-gray-400 dark:text-gray-500 mb-4 flex items-start gap-1.5">
203 − <span className="text-purple-400 mt-0.5">ℹ</span>
203 + <span className="text-blue-400 mt-0.5">ℹ</span>
204 204 Vous serez automatiquement membre. Le dossier apparaîtra dans la sidebar de chaque membre.
205 205 </p>
206 206
modified components/folders/FolderCard.tsx +60 −10
@@ -2,12 +2,13 @@
2 2
3 3 import { useRouter } from "next/navigation";
4 4 import { motion } from "framer-motion";
5 −import { Folder, MoreVertical, Pencil, Trash2 } from "lucide-react";
5 +import { Folder, MoreVertical, Pencil, Trash2, FolderInput } from "lucide-react";
6 6 import { useState, useRef, useEffect } from "react";
7 7 import toast from "react-hot-toast";
8 8 import Modal from "../ui/Modal";
9 9 import Button from "../ui/Button";
10 10 import SharedBadge from "../ui/SharedBadge";
11 +import MoveModal from "../files/MoveModal";
11 12
12 13 interface FolderData {
13 14 id: string;
@@ -27,10 +28,31 @@ export default function FolderCard({ folder, onRefresh, viewMode }: FolderCardPr
27 28 const [showMenu, setShowMenu] = useState(false);
28 29 const [renameModal, setRenameModal] = useState(false);
29 30 const [deleteModal, setDeleteModal] = useState(false);
31 + const [moveModal, setMoveModal] = useState(false);
30 32 const [newName, setNewName] = useState(folder.name);
31 33 const [loading, setLoading] = useState(false);
32 34 const menuRef = useRef<HTMLDivElement>(null);
33 35
36 + const handleMove = async (targetFolderId: string) => {
37 + try {
38 + const res = await fetch(`/api/folders/${folder.id}`, {
39 + method: "PATCH",
40 + headers: { "Content-Type": "application/json" },
41 + body: JSON.stringify({ parentId: targetFolderId }),
42 + });
43 + if (res.ok) {
44 + toast.success("Dossier déplacé");
45 + onRefresh();
46 + } else {
47 + const d = await res.json().catch(() => ({}));
48 + toast.error(d.error || "Déplacement impossible");
49 + }
50 + } catch {
51 + toast.error("Erreur");
52 + }
53 + setMoveModal(false);
54 + };
55 +
34 56 useEffect(() => {
35 57 function handleClick(e: MouseEvent) {
36 58 if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
@@ -87,18 +109,19 @@ export default function FolderCard({ folder, onRefresh, viewMode }: FolderCardPr
87 109 <motion.div
88 110 initial={{ opacity: 0 }}
89 111 animate={{ opacity: 1 }}
90 − className="flex items-center gap-3 px-3 py-3.5 hover:bg-gray-100 dark:hover:bg-white/5 rounded-lg cursor-pointer group transition-colors"
112 + className="flex items-center gap-3 px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-white/5 cursor-pointer group transition-colors"
91 113 onClick={() => router.push(`/dashboard/folder/${folder.id}`)}
92 114 >
93 − <Folder className="w-5 h-5 text-blue-400 flex-shrink-0" />
94 − <span className="text-sm text-gray-700 dark:text-gray-200 flex-1 truncate">{folder.name}</span>
115 + <div className="w-8 h-8 flex items-center justify-center flex-shrink-0">
116 + <Folder className="w-5 h-5 text-blue-400" />
117 + </div>
118 + <span className="text-sm font-medium text-gray-700 dark:text-gray-200 flex-1 truncate min-w-0">{folder.name}</span>
95 119 {folder.sharedSpaceId && <SharedBadge />}
96 − {folder._count && (
97 − <span className="text-xs text-gray-500">
98 − {folder._count.files} fichiers
99 − </span>
100 − )}
101 − <div className="relative" ref={menuRef}>
120 + <span className="text-sm text-gray-500 hidden sm:block flex-shrink-0 w-24 text-right tabular-nums">
121 + {folder._count ? `${folder._count.files} fich.` : ""}
122 + </span>
123 + <span className="hidden md:block flex-shrink-0 w-28 text-right text-xs text-gray-400">Dossier</span>
124 + <div className="relative flex-shrink-0" ref={menuRef}>
102 125 <button
103 126 onClick={(e) => {
104 127 e.stopPropagation();
@@ -120,6 +143,16 @@ export default function FolderCard({ folder, onRefresh, viewMode }: FolderCardPr
120 143 >
121 144 <Pencil className="w-4 h-4" /> Renommer
122 145 </button>
146 + <button
147 + onClick={(e) => {
148 + e.stopPropagation();
149 + setMoveModal(true);
150 + setShowMenu(false);
151 + }}
152 + className="flex items-center gap-2 w-full px-4 py-3 text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5"
153 + >
154 + <FolderInput className="w-4 h-4" /> Déplacer
155 + </button>
123 156 <button
124 157 onClick={(e) => {
125 158 e.stopPropagation();
@@ -148,6 +181,13 @@ export default function FolderCard({ folder, onRefresh, viewMode }: FolderCardPr
148 181 <Button variant="danger" onClick={handleDelete} loading={loading}>Supprimer</Button>
149 182 </div>
150 183 </Modal>
184 + <MoveModal
185 + isOpen={moveModal}
186 + onClose={() => setMoveModal(false)}
187 + onSelect={handleMove}
188 + excludeId={folder.id}
189 + itemName={folder.name}
190 + />
151 191 </>
152 192 );
153 193 }
@@ -197,6 +237,16 @@ export default function FolderCard({ folder, onRefresh, viewMode }: FolderCardPr
197 237 >
198 238 <Pencil className="w-4 h-4" /> Renommer
199 239 </button>
240 + <button
241 + onClick={(e) => {
242 + e.stopPropagation();
243 + setMoveModal(true);
244 + setShowMenu(false);
245 + }}
246 + className="flex items-center gap-2 w-full px-4 py-3 text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5"
247 + >
248 + <FolderInput className="w-4 h-4" /> Déplacer
249 + </button>
200 250 <button
201 251 onClick={(e) => {
202 252 e.stopPropagation();
modified components/layout/AppShell.tsx +3 −0
@@ -6,6 +6,7 @@ import MobileNav from "./MobileNav";
6 6 import ThemeToggle from "../theme/ThemeToggle";
7 7 import NotificationBell from "./NotificationBell";
8 8 import AiPanel from "../ai/AiPanel";
9 +import TopLoader from "../ui/TopLoader";
9 10
10 11 interface AppShellProps {
11 12 children: React.ReactNode;
@@ -16,6 +17,8 @@ export default function AppShell({ children }: AppShellProps) {
16 17
17 18 return (
18 19 <div className="h-screen overflow-hidden bg-gray-50 dark:bg-[#0a0a0a] flex transition-colors">
20 + <TopLoader />
21 +
19 22 {/* Desktop Sidebar — fixed height, scrolls independently */}
20 23 <div className="hidden lg:flex flex-col w-64 flex-shrink-0 h-full overflow-y-auto">
21 24 <Sidebar />
modified components/layout/Breadcrumb.tsx +1 −1
@@ -16,7 +16,7 @@ export default function Breadcrumb({ items }: BreadcrumbProps) {
16 16 return (
17 17 <nav className="flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400 overflow-x-auto pb-1 flex-nowrap scrollbar-none">
18 18 <Link
19 − href="/dashboard"
19 + href="/dashboard/files"
20 20 className="flex items-center gap-1 hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap py-1 flex-shrink-0"
21 21 >
22 22 <Home className="w-3.5 h-3.5" />
added components/layout/FolderTree.tsx +94 −0
@@ -0,0 +1,94 @@
1 +"use client";
2 +
3 +import Link from "next/link";
4 +import { usePathname } from "next/navigation";
5 +import { useEffect, useState, useCallback } from "react";
6 +import { Folder, FolderOpen, ChevronRight, ChevronDown } from "lucide-react";
7 +
8 +interface TreeFolder {
9 + id: string;
10 + name: string;
11 + children?: TreeFolder[];
12 + _count?: { files: number };
13 +}
14 +
15 +interface FolderTreeProps {
16 + onNavigate?: () => void;
17 +}
18 +
19 +export default function FolderTree({ onNavigate }: FolderTreeProps) {
20 + const pathname = usePathname();
21 + const [tree, setTree] = useState<TreeFolder[]>([]);
22 + const [expanded, setExpanded] = useState<Set<string>>(new Set());
23 +
24 + useEffect(() => {
25 + fetch("/api/folders?tree=true")
26 + .then((r) => (r.ok ? r.json() : []))
27 + .then((d) => setTree(Array.isArray(d) ? d : []))
28 + .catch(() => {});
29 + }, []);
30 +
31 + const toggle = useCallback((id: string) => {
32 + setExpanded((prev) => {
33 + const next = new Set(prev);
34 + next.has(id) ? next.delete(id) : next.add(id);
35 + return next;
36 + });
37 + }, []);
38 +
39 + function renderNode(node: TreeFolder, depth: number): React.ReactNode {
40 + const kids = node.children ?? [];
41 + const hasKids = kids.length > 0;
42 + const isOpen = expanded.has(node.id);
43 + const active = pathname === `/dashboard/folder/${node.id}`;
44 + return (
45 + <div key={node.id}>
46 + <div
47 + className={`flex items-center rounded-lg transition-colors ${
48 + active
49 + ? "bg-gray-100 dark:bg-white/10"
50 + : "hover:bg-gray-50 dark:hover:bg-white/5"
51 + }`}
52 + style={{ paddingLeft: 4 + depth * 12 }}
53 + >
54 + <button
55 + onClick={() => hasKids && toggle(node.id)}
56 + className="w-5 h-8 flex items-center justify-center flex-shrink-0 text-gray-400"
57 + tabIndex={hasKids ? 0 : -1}
58 + aria-label={hasKids ? "Déplier" : undefined}
59 + >
60 + {hasKids ? (
61 + isOpen ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />
62 + ) : null}
63 + </button>
64 + <Link
65 + href={`/dashboard/folder/${node.id}`}
66 + onClick={onNavigate}
67 + className={`flex items-center gap-2 flex-1 min-w-0 py-2 pr-2 text-sm transition-colors ${
68 + active
69 + ? "text-gray-900 dark:text-white font-medium"
70 + : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
71 + }`}
72 + >
73 + {isOpen && hasKids ? (
74 + <FolderOpen className="w-4 h-4 text-blue-500 flex-shrink-0" />
75 + ) : (
76 + <Folder className="w-4 h-4 text-blue-400 flex-shrink-0" />
77 + )}
78 + <span className="truncate flex-1">{node.name}</span>
79 + {node._count?.files ? (
80 + <span className="text-[10px] text-gray-400 dark:text-gray-600 tabular-nums">
81 + {node._count.files}
82 + </span>
83 + ) : null}
84 + </Link>
85 + </div>
86 + {hasKids && isOpen && <div>{kids.map((c) => renderNode(c, depth + 1))}</div>}
87 + </div>
88 + );
89 + }
90 +
91 + if (tree.length === 0) return null;
92 +
93 + return <div className="space-y-0.5 ml-1">{tree.map((n) => renderNode(n, 0))}</div>;
94 +}
modified components/layout/NotificationBell.tsx +193 −59
@@ -1,9 +1,18 @@
1 1 "use client";
2 2
3 −import { useState, useEffect, useRef } from "react";
4 −import { Bell, Check, CheckCheck } from "lucide-react";
3 +import { useState, useEffect, useRef, useCallback } from "react";
4 +import {
5 + Bell,
6 + Check,
7 + CheckCheck,
8 + Upload,
9 + Share2,
10 + MessageCircle,
11 + Sparkles,
12 + Database,
13 + X,
14 +} from "lucide-react";
5 15 import { motion, AnimatePresence } from "framer-motion";
6 −import { formatDate } from "@/lib/utils";
7 16
8 17 interface NotificationData {
9 18 id: string;
@@ -11,42 +20,91 @@ interface NotificationData {
11 20 title: string;
12 21 message: string;
13 22 read: boolean;
23 + data: string | null;
14 24 createdAt: string;
15 25 }
16 26
27 +const typeIcons: Record<string, typeof Upload> = {
28 + upload_complete: Upload,
29 + share: Share2,
30 + comment: MessageCircle,
31 + ai_complete: Sparkles,
32 + backup_complete: Database,
33 +};
34 +
35 +const typeColors: Record<string, string> = {
36 + upload_complete: "text-green-400 bg-green-500/10",
37 + share: "text-orange-400 bg-orange-500/10",
38 + comment: "text-blue-400 bg-blue-500/10",
39 + ai_complete: "text-blue-400 bg-blue-500/10",
40 + backup_complete: "text-cyan-400 bg-cyan-500/10",
41 +};
42 +
43 +function timeAgo(date: string): string {
44 + const now = new Date();
45 + const d = new Date(date);
46 + const seconds = Math.floor((now.getTime() - d.getTime()) / 1000);
47 +
48 + if (seconds < 60) return "a l'instant";
49 + const minutes = Math.floor(seconds / 60);
50 + if (minutes < 60) return `il y a ${minutes}min`;
51 + const hours = Math.floor(minutes / 60);
52 + if (hours < 24) return `il y a ${hours}h`;
53 + const days = Math.floor(hours / 24);
54 + if (days < 30) return `il y a ${days}j`;
55 + const months = Math.floor(days / 30);
56 + return `il y a ${months} mois`;
57 +}
58 +
17 59 export default function NotificationBell() {
18 60 const [notifications, setNotifications] = useState<NotificationData[]>([]);
19 61 const [unreadCount, setUnreadCount] = useState(0);
20 62 const [open, setOpen] = useState(false);
21 63 const ref = useRef<HTMLDivElement>(null);
22 64
23 − const fetchCount = async () => {
65 + const fetchCount = useCallback(async () => {
24 66 try {
25 67 const res = await fetch("/api/notifications?count=true");
26 68 if (res.ok) {
27 69 const data = await res.json();
28 70 setUnreadCount(data.count);
29 71 }
30 − } catch {}
31 − };
72 + } catch {
73 + // silent
74 + }
75 + }, []);
32 76
33 − const fetchNotifications = async () => {
77 + const fetchNotifications = useCallback(async () => {
34 78 try {
35 79 const res = await fetch("/api/notifications");
36 − if (res.ok) setNotifications(await res.json());
37 − } catch {}
38 − };
80 + if (res.ok) {
81 + const data = await res.json();
82 + setNotifications(data);
83 + // Update unread count from full list
84 + setUnreadCount(data.filter((n: NotificationData) => !n.read).length);
85 + }
86 + } catch {
87 + // silent
88 + }
89 + }, []);
39 90
91 + // Poll every 15 seconds
40 92 useEffect(() => {
41 93 fetchCount();
42 − const interval = setInterval(fetchCount, 30000);
94 + const interval = setInterval(fetchCount, 15000);
43 95 return () => clearInterval(interval);
44 − }, []);
96 + }, [fetchCount]);
45 97
98 + // Fetch full list when opened, and poll while open
46 99 useEffect(() => {
47 − if (open) fetchNotifications();
48 − }, [open]);
100 + if (open) {
101 + fetchNotifications();
102 + const interval = setInterval(fetchNotifications, 15000);
103 + return () => clearInterval(interval);
104 + }
105 + }, [open, fetchNotifications]);
49 106
107 + // Close on outside click
50 108 useEffect(() => {
51 109 function handleClick(e: MouseEvent) {
52 110 if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
@@ -67,17 +125,12 @@ export default function NotificationBell() {
67 125
68 126 const markRead = async (id: string) => {
69 127 await fetch(`/api/notifications/${id}`, { method: "PATCH" });
70 − setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n));
128 + setNotifications((prev) =>
129 + prev.map((n) => (n.id === id ? { ...n, read: true } : n))
130 + );
71 131 setUnreadCount((prev) => Math.max(0, prev - 1));
72 132 };
73 133
74 − const typeColors: Record<string, string> = {
75 − upload_complete: "text-green-500",
76 − backup_complete: "text-blue-500",
77 − ai_complete: "text-purple-500",
78 − share_accessed: "text-orange-500",
79 − };
80 −
81 134 return (
82 135 <div className="relative" ref={ref}>
83 136 <button
@@ -85,56 +138,137 @@ export default function NotificationBell() {
85 138 className="relative min-w-[44px] min-h-[44px] p-2.5 flex items-center justify-center text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors"
86 139 >
87 140 <Bell className="w-5 h-5" />
88 − {unreadCount > 0 && (
89 − <span className="absolute top-1 right-1 w-4 h-4 bg-red-500 text-white text-xs font-bold rounded-full flex items-center justify-center">
90 − {unreadCount > 9 ? "9+" : unreadCount}
91 − </span>
92 − )}
141 + <AnimatePresence>
142 + {unreadCount > 0 && (
143 + <motion.span
144 + initial={{ scale: 0 }}
145 + animate={{ scale: 1 }}
146 + exit={{ scale: 0 }}
147 + className="absolute top-0.5 right-0.5 min-w-[18px] h-[18px] px-1 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center"
148 + >
149 + {unreadCount > 99 ? "99+" : unreadCount}
150 + </motion.span>
151 + )}
152 + </AnimatePresence>
93 153 </button>
94 154
95 155 <AnimatePresence>
96 156 {open && (
97 157 <motion.div
98 − initial={{ opacity: 0, y: 5, scale: 0.95 }}
158 + initial={{ opacity: 0, y: 8, scale: 0.95 }}
99 159 animate={{ opacity: 1, y: 0, scale: 1 }}
100 − exit={{ opacity: 0, y: 5, scale: 0.95 }}
101 − className="fixed inset-x-4 top-16 sm:absolute sm:inset-x-auto sm:top-full sm:right-0 sm:mt-2 sm:w-80 bg-white dark:bg-gray-900 border border-gray-200 dark:border-white/10 rounded-xl shadow-2xl z-50 overflow-hidden"
160 + exit={{ opacity: 0, y: 8, scale: 0.95 }}
161 + transition={{ duration: 0.15 }}
162 + className="fixed inset-x-3 top-14 sm:absolute sm:inset-x-auto sm:top-full sm:right-0 sm:mt-2 sm:w-96 bg-white dark:bg-gray-900 border border-gray-200 dark:border-white/10 rounded-xl shadow-2xl z-50 overflow-hidden"
102 163 >
164 + {/* Header */}
103 165 <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-white/10">
104 − <h3 className="text-sm font-medium text-gray-900 dark:text-white">Notifications</h3>
105 − {unreadCount > 0 && (
106 − <button onClick={markAllRead} className="text-xs text-blue-500 hover:text-blue-600 flex items-center gap-1 min-h-[36px]">
107 − <CheckCheck className="w-3 h-3" /> Tout lire
166 + <div className="flex items-center gap-2">
167 + <h3 className="text-sm font-semibold text-gray-900 dark:text-white">
168 + Notifications
169 + </h3>
170 + {unreadCount > 0 && (
171 + <span className="px-1.5 py-0.5 bg-red-500/10 text-red-500 text-[10px] font-bold rounded-full">
172 + {unreadCount}
173 + </span>
174 + )}
175 + </div>
176 + <div className="flex items-center gap-1">
177 + {unreadCount > 0 && (
178 + <button
179 + onClick={markAllRead}
180 + className="text-xs text-blue-500 hover:text-blue-400 flex items-center gap-1 min-h-[36px] px-2 rounded-lg hover:bg-blue-500/5 transition-colors"
181 + >
182 + <CheckCheck className="w-3.5 h-3.5" />
183 + Tout marquer comme lu
184 + </button>
185 + )}
186 + <button
187 + onClick={() => setOpen(false)}
188 + className="sm:hidden p-1.5 text-gray-400 hover:text-white min-w-[36px] min-h-[36px] flex items-center justify-center"
189 + >
190 + <X className="w-4 h-4" />
108 191 </button>
109 − )}
192 + </div>
110 193 </div>
111 − <div className="max-h-80 overflow-y-auto">
194 +
195 + {/* Notification List */}
196 + <div className="max-h-[60vh] sm:max-h-96 overflow-y-auto">
112 197 {notifications.length === 0 ? (
113 − <p className="text-center text-gray-500 text-sm py-8">Aucune notification</p>
198 + <div className="flex flex-col items-center justify-center py-12 text-gray-500">
199 + <Bell className="w-8 h-8 mb-2 opacity-30" />
200 + <p className="text-sm">Aucune notification</p>
201 + </div>
114 202 ) : (
115 − notifications.map((n) => (
116 − <div
117 − key={n.id}
118 − className={`px-4 py-3.5 border-b border-gray-100 dark:border-white/5 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors cursor-pointer ${!n.read ? "bg-blue-50/50 dark:bg-blue-500/5" : ""}`}
119 − onClick={() => !n.read && markRead(n.id)}
120 − >
121 − <div className="flex items-start gap-2">
122 − <div className={`w-2 h-2 rounded-full mt-1.5 flex-shrink-0 ${n.read ? "bg-transparent" : "bg-blue-500"}`} />
123 − <div className="flex-1 min-w-0">
124 − <p className={`text-sm font-medium ${typeColors[n.type] || "text-gray-900 dark:text-white"}`}>
125 − {n.title}
126 − </p>
127 − <p className="text-xs text-gray-500 mt-0.5">{n.message}</p>
128 − <p className="text-xs text-gray-400 mt-1">{formatDate(n.createdAt)}</p>
203 + notifications.map((n, i) => {
204 + const IconComponent = typeIcons[n.type] || Bell;
205 + const colorClass =
206 + typeColors[n.type] || "text-gray-400 bg-gray-500/10";
207 +
208 + return (
209 + <motion.div
210 + key={n.id}
211 + initial={{ opacity: 0, x: -10 }}
212 + animate={{ opacity: 1, x: 0 }}
213 + transition={{ delay: i * 0.03 }}
214 + className={`px-4 py-3 border-b border-gray-100 dark:border-white/5 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors cursor-pointer ${
215 + !n.read
216 + ? "bg-blue-50/50 dark:bg-blue-500/5"
217 + : ""
218 + }`}
219 + onClick={() => {
220 + if (!n.read) markRead(n.id);
221 + }}
222 + >
223 + <div className="flex items-start gap-3">
224 + {/* Icon */}
225 + <div
226 + className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${colorClass}`}
227 + >
228 + <IconComponent className="w-4 h-4" />
229 + </div>
230 +
231 + {/* Content */}
232 + <div className="flex-1 min-w-0">
233 + <div className="flex items-center gap-2">
234 + <p
235 + className={`text-sm font-medium truncate ${
236 + n.read
237 + ? "text-gray-600 dark:text-gray-400"
238 + : "text-gray-900 dark:text-white"
239 + }`}
240 + >
241 + {n.title}
242 + </p>
243 + {!n.read && (
244 + <span className="w-2 h-2 bg-blue-500 rounded-full flex-shrink-0" />
245 + )}
246 + </div>
247 + <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">
248 + {n.message}
249 + </p>
250 + <p className="text-[10px] text-gray-400 mt-1">
251 + {timeAgo(n.createdAt)}
252 + </p>
253 + </div>
254 +
255 + {/* Mark read button */}
256 + {!n.read && (
257 + <button
258 + onClick={(e) => {
259 + e.stopPropagation();
260 + markRead(n.id);
261 + }}
262 + className="p-1.5 text-gray-400 hover:text-green-500 min-w-[32px] min-h-[32px] flex items-center justify-center rounded-lg hover:bg-green-500/10 transition-colors"
263 + title="Marquer comme lu"
264 + >
265 + <Check className="w-3.5 h-3.5" />
266 + </button>
267 + )}
129 268 </div>
130 − {!n.read && (
131 − <button className="p-1.5 text-gray-400 hover:text-green-500 min-w-[32px] min-h-[32px] flex items-center justify-center" title="Marquer comme lu">
132 − <Check className="w-3.5 h-3.5" />
133 − </button>
134 − )}
135 − </div>
136 − </div>
137 − ))
269 + </motion.div>
270 + );
271 + })
138 272 )}
139 273 </div>
140 274 </motion.div>
modified components/layout/Sidebar.tsx +59 −7
@@ -20,16 +20,31 @@ import {
20 20 Settings,
21 21 KeyRound,
22 22 Lock,
23 + Trash2,
24 + Clock,
25 + Home,
26 + Network,
27 + Shield,
28 + Camera,
23 29 } from "lucide-react";
24 30 import ThemeToggle from "../theme/ThemeToggle";
25 31 import NotificationBell from "./NotificationBell";
32 +import FolderTree from "./FolderTree";
26 33 import SharedBadge from "../ui/SharedBadge";
27 34 import ChangePasswordModal from "../auth/ChangePasswordModal";
35 +import UserAvatar from "../ui/UserAvatar";
28 36
29 37 const userNavItems = [
30 − { href: "/dashboard", label: "Fichiers", icon: FolderOpen },
38 + { href: "/dashboard", label: "Accueil", icon: Home },
39 + { href: "/dashboard/files", label: "Fichiers", icon: FolderOpen },
31 40 { href: "/dashboard/favorites", label: "Favoris", icon: Star },
41 + { href: "/dashboard/recent", label: "Recents", icon: Clock },
42 + { href: "/dashboard/graph", label: "Visualisation", icon: Network },
43 + { href: "/dashboard/shared-with-me", label: "Partage avec moi", icon: Share2 },
32 44 { href: "/dashboard/passwords", label: "Mots de passe", icon: Lock },
45 + { href: "/dashboard/trash", label: "Corbeille", icon: Trash2 },
46 + { href: "/admin/snapshots", label: "Snapshots", icon: Camera },
47 + { href: "/dashboard/security", label: "Sécurité", icon: Shield },
33 48 ];
34 49
35 50 const adminNavItems = [
@@ -41,6 +56,7 @@ const adminNavItems = [
41 56 const adminItems = [
42 57 { href: "/admin/users", label: "Utilisateurs", icon: Users },
43 58 { href: "/admin/shared-spaces", label: "Espaces partagés", icon: Users },
59 + { href: "/admin/snapshots", label: "Snapshots", icon: Clock },
44 60 { href: "/admin/backup", label: "Backups", icon: HardDrive },
45 61 { href: "/admin/api-keys", label: "Clés API", icon: Key },
46 62 { href: "/admin/settings", label: "Paramètres", icon: Settings },
@@ -71,14 +87,19 @@ export default function Sidebar({ onNavigate }: SidebarProps) {
71 87 const [showTags, setShowTags] = useState(false);
72 88 const [showAdmin, setShowAdmin] = useState(false);
73 89 const [showSpaces, setShowSpaces] = useState(true);
90 + const [showFolders, setShowFolders] = useState(true);
74 91 const [isAdmin, setIsAdmin] = useState(false);
75 92 const [showChangePassword, setShowChangePassword] = useState(false);
93 + const [sessionUser, setSessionUser] = useState<{ id: string; name?: string; email?: string; avatarPath?: string } | null>(null);
76 94
77 95 useEffect(() => {
78 96 fetch("/api/auth/session")
79 97 .then((res) => res.json())
80 98 .then((data) => {
81 99 if (data.role === "admin") setIsAdmin(true);
100 + if (data.isLoggedIn) {
101 + setSessionUser({ id: data.userId, name: data.name, email: data.email, avatarPath: data.avatarPath });
102 + }
82 103 })
83 104 .catch(() => {});
84 105
@@ -123,16 +144,18 @@ export default function Sidebar({ onNavigate }: SidebarProps) {
123 144 {navItems.map((item) => {
124 145 const isActive =
125 146 pathname === item.href ||
126 − (item.href === "/dashboard" && pathname.startsWith("/dashboard") && !pathname.includes("favorites") && !pathname.includes("shared-space") && !pathname.includes("passwords"));
147 + (item.href === "/dashboard" && pathname === "/dashboard") ||
148 + (item.href === "/dashboard/files" && pathname.startsWith("/dashboard/files")) ||
149 + (item.href === "/dashboard/files" && pathname.startsWith("/dashboard/folder"));
127 150 return (
128 151 <Link
129 152 key={item.href}
130 153 href={item.href}
131 154 onClick={handleLinkClick}
132 − className={`flex items-center gap-3 px-3 py-3 rounded-xl text-sm transition-colors min-h-[44px] ${
155 + className={`flex items-center gap-3 px-3 py-3 rounded-xl text-sm transition-all duration-200 min-h-[44px] ${
133 156 isActive
134 − ? "bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-white font-medium"
135 − : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-white/5 active:bg-gray-100 dark:active:bg-white/10"
157 + ? "bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-white font-medium border-l-[3px] border-l-blue-700 pl-[9px]"
158 + : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-white/5 active:bg-gray-100 dark:active:bg-white/10 hover:translate-x-0.5"
136 159 }`}
137 160 >
138 161 <item.icon className={`w-5 h-5 flex-shrink-0 ${item.href === "/dashboard/favorites" && pathname === item.href ? "text-yellow-400" : ""}`} />
@@ -141,6 +164,19 @@ export default function Sidebar({ onNavigate }: SidebarProps) {
141 164 );
142 165 })}
143 166
167 + {/* Folder tree */}
168 + <div className="pt-3">
169 + <button
170 + onClick={() => setShowFolders(!showFolders)}
171 + className="flex items-center gap-2 px-3 py-2.5 w-full text-xs text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors min-h-[40px] rounded-lg active:bg-gray-50 dark:active:bg-white/5"
172 + >
173 + {showFolders ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
174 + <FolderOpen className="w-3.5 h-3.5" />
175 + <span className="uppercase tracking-wider font-medium">Dossiers</span>
176 + </button>
177 + {showFolders && <FolderTree onNavigate={handleLinkClick} />}
178 + </div>
179 +
144 180 {/* Shared Spaces Section */}
145 181 {sharedSpaces.length > 0 && (
146 182 <div className="pt-3">
@@ -161,11 +197,11 @@ export default function Sidebar({ onNavigate }: SidebarProps) {
161 197 onClick={handleLinkClick}
162 198 className={`flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors min-h-[40px] ${
163 199 pathname === `/dashboard/shared-space/${space.id}`
164 − ? "bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 font-medium"
200 + ? "bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-300 font-medium"
165 201 : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-white/5 active:bg-gray-100 dark:active:bg-white/10"
166 202 }`}
167 203 >
168 − <Users className="w-4 h-4 flex-shrink-0 text-purple-400" />
204 + <Users className="w-4 h-4 flex-shrink-0 text-blue-500" />
169 205 <span className="truncate flex-1">{space.name}</span>
170 206 <SharedBadge />
171 207 </Link>
@@ -243,6 +279,22 @@ export default function Sidebar({ onNavigate }: SidebarProps) {
243 279
244 280 {/* Footer */}
245 281 <div className="px-2 py-3 border-t border-gray-200 dark:border-white/10 space-y-0.5">
282 + {/* Current user */}
283 + {sessionUser && (
284 + <div className="flex items-center gap-3 px-3 py-2.5 mb-1">
285 + <UserAvatar userId={sessionUser.id} name={sessionUser.name} avatarPath={sessionUser.avatarPath} size="sm" />
286 + <div className="min-w-0 flex-1">
287 + <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
288 + {sessionUser.name || "Utilisateur"}
289 + </p>
290 + {sessionUser.email && (
291 + <p className="text-[10px] text-gray-400 dark:text-gray-500 truncate">
292 + {sessionUser.email}
293 + </p>
294 + )}
295 + </div>
296 + </div>
297 + )}
246 298 <button
247 299 onClick={() => setShowChangePassword(true)}
248 300 className="flex items-center gap-3 px-3 py-3 rounded-xl text-sm text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-white/5 active:bg-gray-100 dark:active:bg-white/10 transition-colors w-full min-h-[44px]"
modified components/preview/PreviewEngine.tsx +15 −1
@@ -1,6 +1,6 @@
1 1 "use client";
2 2
3 −import { useState, useCallback } from "react";
3 +import { useState, useCallback, useEffect } from "react";
4 4 import { motion, AnimatePresence } from "framer-motion";
5 5 import { Info, ChevronUp } from "lucide-react";
6 6 import PreviewToolbar from "./PreviewToolbar";
@@ -29,6 +29,20 @@ export default function PreviewEngine({
29 29 const [showInfo, setShowInfo] = useState(false);
30 30 const [showMobileInfo, setShowMobileInfo] = useState(false);
31 31
32 + // Préchargement des images voisines → navigation suivant/précédent instantanée
33 + useEffect(() => {
34 + if (!file || files.length < 2) return;
35 + const idx = files.findIndex((f) => f.id === file.id);
36 + if (idx === -1) return;
37 + const neighbors = [files[idx - 1], files[idx + 1]].filter(
38 + (f): f is FileData => !!f && f.mimeType.startsWith("image/")
39 + );
40 + neighbors.forEach((f) => {
41 + const img = new Image();
42 + img.src = `/api/files/${f.id}/preview?w=2048`;
43 + });
44 + }, [file, files]);
45 +
32 46 const handleSave = useCallback(
33 47 async (data: Blob | string, asNewVersion?: boolean) => {
34 48 if (!file) return;
modified components/preview/PreviewNavigation.tsx +11 −4
@@ -27,10 +27,17 @@ export default function PreviewNavigation({
27 27
28 28 useEffect(() => {
29 29 const handleKey = (e: KeyboardEvent) => {
30 − // Don't capture if typing in an input
31 − if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;
32 − if (e.key === "ArrowLeft" && e.altKey) { e.preventDefault(); goPrev(); }
33 − if (e.key === "ArrowRight" && e.altKey) { e.preventDefault(); goNext(); }
30 + // Don't capture if typing in an input / editable field
31 + const t = e.target as HTMLElement | null;
32 + if (
33 + t instanceof HTMLInputElement ||
34 + t instanceof HTMLTextAreaElement ||
35 + t?.isContentEditable
36 + )
37 + return;
38 + // Flèches simples OU Alt+flèches : précédent / suivant
39 + if (e.key === "ArrowLeft") { e.preventDefault(); goPrev(); }
40 + if (e.key === "ArrowRight") { e.preventDefault(); goNext(); }
34 41 };
35 42 window.addEventListener("keydown", handleKey);
36 43 return () => window.removeEventListener("keydown", handleKey);
modified components/preview/plugins/ImagePreview.tsx +2 −1
@@ -138,7 +138,7 @@ export default function ImagePreview({ file }: PreviewPluginProps) {
138 138 onTouchEnd={handleTouchEnd}
139 139 >
140 140 <img
141 − src={`/api/files/${file.id}/preview`}
141 + src={`/api/files/${file.id}/preview?w=2048`}
142 142 alt={file.name}
143 143 className="max-w-full max-h-full select-none"
144 144 style={{
@@ -147,6 +147,7 @@ export default function ImagePreview({ file }: PreviewPluginProps) {
147 147 objectFit: "contain",
148 148 }}
149 149 draggable={false}
150 + decoding="async"
150 151 />
151 152 </div>
152 153 </div>
modified components/preview/plugins/PdfPreview.tsx +3 −1
@@ -104,7 +104,9 @@ export default function PdfPreview({ file, isEditing }: PreviewPluginProps) {
104 104 let cancelled = false;
105 105 const loadPdf = async () => {
106 106 try {
107 − const pdfjsLib = await import("pdfjs-dist");
107 + // Load pdfjs from public/ to avoid bundler issues with dynamic imports
108 + // eslint-disable-next-line @typescript-eslint/no-explicit-any
109 + const pdfjsLib = await (Function('return import("/pdf.min.mjs")')()) as any;
108 110 pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.min.mjs";
109 111 const loadingTask = pdfjsLib.getDocument({
110 112 url: `/api/files/${file.id}/preview`,
modified components/tags/TagSelector.tsx +1 −1
@@ -31,7 +31,7 @@ export default function TagSelector({ fileId, currentTags, onTagsChange }: TagSe
31 31 useEffect(() => {
32 32 fetch("/api/tags")
33 33 .then((res) => res.json())
34 − .then(setAllTags)
34 + .then((data) => setAllTags(Array.isArray(data) ? data : []))
35 35 .catch(() => {});
36 36 }, []);
37 37
modified components/theme/ThemeProvider.tsx +2 −2
@@ -10,7 +10,7 @@ interface ThemeContextType {
10 10 }
11 11
12 12 const ThemeContext = createContext<ThemeContextType>({
13 − theme: "dark",
13 + theme: "light",
14 14 toggleTheme: () => {},
15 15 });
16 16
@@ -19,7 +19,7 @@ export function useTheme() {
19 19 }
20 20
21 21 export default function ThemeProvider({ children }: { children: React.ReactNode }) {
22 − const [theme, setTheme] = useState<Theme>("dark");
22 + const [theme, setTheme] = useState<Theme>("light");
23 23 const [mounted, setMounted] = useState(false);
24 24
25 25 useEffect(() => {
added components/ui/PageTransition.tsx +22 −0
@@ -0,0 +1,22 @@
1 +"use client";
2 +
3 +import { motion } from "framer-motion";
4 +
5 +interface PageTransitionProps {
6 + children: React.ReactNode;
7 + className?: string;
8 +}
9 +
10 +export default function PageTransition({ children, className }: PageTransitionProps) {
11 + return (
12 + <motion.div
13 + initial={{ opacity: 0, y: 8 }}
14 + animate={{ opacity: 1, y: 0 }}
15 + exit={{ opacity: 0, y: 8 }}
16 + transition={{ duration: 0.3, ease: "easeOut" }}
17 + className={className}
18 + >
19 + {children}
20 + </motion.div>
21 + );
22 +}
modified components/ui/SharedBadge.tsx +1 −1
@@ -1,6 +1,6 @@
1 1 export default function SharedBadge() {
2 2 return (
3 − <span className="px-1.5 py-0.5 text-[10px] font-semibold rounded bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-400 leading-none whitespace-nowrap">
3 + <span className="px-1.5 py-0.5 text-[10px] font-semibold rounded bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400 leading-none whitespace-nowrap">
4 4 Partagé
5 5 </span>
6 6 );
added components/ui/Skeleton.tsx +135 −0
@@ -0,0 +1,135 @@
1 +"use client";
2 +
3 +interface SkeletonProps {
4 + className?: string;
5 + variant?: "text" | "circular" | "rectangular";
6 +}
7 +
8 +export default function Skeleton({ className = "", variant = "rectangular" }: SkeletonProps) {
9 + const baseClasses = "animate-pulse relative overflow-hidden bg-gray-200 dark:bg-white/10";
10 +
11 + const variantClasses = {
12 + text: "rounded h-4 w-full",
13 + circular: "rounded-full",
14 + rectangular: "rounded-xl",
15 + };
16 +
17 + return (
18 + <div className={`${baseClasses} ${variantClasses[variant]} ${className}`}>
19 + <div className="absolute inset-0 animate-shimmer" />
20 + </div>
21 + );
22 +}
23 +
24 +/* Preset skeleton layouts */
25 +
26 +export function SkeletonCard() {
27 + return (
28 + <div className="p-3 sm:p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
29 + <div className="flex items-center gap-3">
30 + <Skeleton variant="circular" className="w-10 h-10 flex-shrink-0" />
31 + <div className="flex-1 space-y-2">
32 + <Skeleton variant="text" className="h-4 w-3/4" />
33 + <Skeleton variant="text" className="h-3 w-1/2" />
34 + </div>
35 + </div>
36 + </div>
37 + );
38 +}
39 +
40 +export function SkeletonStat() {
41 + return (
42 + <div className="flex items-center gap-3 p-3 sm:p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
43 + <Skeleton variant="circular" className="w-10 h-10 flex-shrink-0" />
44 + <div className="flex-1 space-y-2">
45 + <Skeleton variant="text" className="h-6 w-16" />
46 + <Skeleton variant="text" className="h-3 w-20" />
47 + </div>
48 + </div>
49 + );
50 +}
51 +
52 +export function SkeletonFileCard() {
53 + return (
54 + <div className="flex-shrink-0 w-36 sm:w-44 p-3 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
55 + <Skeleton className="w-full h-20 rounded-xl mb-2" />
56 + <Skeleton variant="text" className="h-3 w-4/5 mb-1" />
57 + <Skeleton variant="text" className="h-2 w-1/3" />
58 + </div>
59 + );
60 +}
61 +
62 +export function SkeletonActivity() {
63 + return (
64 + <div className="flex items-center gap-3 px-4 py-3">
65 + <Skeleton variant="circular" className="w-2 h-2 flex-shrink-0" />
66 + <div className="flex-1 space-y-1.5">
67 + <Skeleton variant="text" className="h-3 w-3/4" />
68 + <Skeleton variant="text" className="h-2 w-1/3" />
69 + </div>
70 + <Skeleton variant="text" className="h-3 w-16 flex-shrink-0" />
71 + </div>
72 + );
73 +}
74 +
75 +export function DashboardSkeleton() {
76 + return (
77 + <div className="p-3 sm:p-4 lg:p-6 space-y-5 sm:space-y-6">
78 + {/* Welcome skeleton */}
79 + <div className="space-y-2">
80 + <Skeleton variant="text" className="h-7 w-64" />
81 + <Skeleton variant="text" className="h-4 w-48" />
82 + </div>
83 +
84 + {/* Quick actions skeleton */}
85 + <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3">
86 + {[...Array(4)].map((_, i) => (
87 + <div key={i} className="flex flex-col items-center gap-2 p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 min-h-[88px] justify-center">
88 + <Skeleton variant="rectangular" className="w-10 h-10 rounded-xl" />
89 + <Skeleton variant="text" className="h-3 w-16" />
90 + </div>
91 + ))}
92 + </div>
93 +
94 + {/* Stats skeleton */}
95 + <div className="grid grid-cols-2 lg:grid-cols-4 gap-2 sm:gap-3">
96 + {[...Array(4)].map((_, i) => (
97 + <SkeletonStat key={i} />
98 + ))}
99 + </div>
100 +
101 + {/* Storage skeleton */}
102 + <div className="p-4 rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10">
103 + <div className="flex items-center justify-between mb-3">
104 + <Skeleton variant="text" className="h-4 w-24" />
105 + <Skeleton variant="text" className="h-3 w-32" />
106 + </div>
107 + <Skeleton className="w-full h-2.5 rounded-full" />
108 + <Skeleton variant="text" className="h-3 w-20 mt-2" />
109 + </div>
110 +
111 + {/* Recent files skeleton */}
112 + <div>
113 + <div className="flex items-center justify-between mb-3">
114 + <Skeleton variant="text" className="h-4 w-32" />
115 + <Skeleton variant="text" className="h-3 w-16" />
116 + </div>
117 + <div className="flex gap-2 sm:gap-3 overflow-hidden">
118 + {[...Array(5)].map((_, i) => (
119 + <SkeletonFileCard key={i} />
120 + ))}
121 + </div>
122 + </div>
123 +
124 + {/* Activity skeleton */}
125 + <div>
126 + <Skeleton variant="text" className="h-4 w-36 mb-3" />
127 + <div className="rounded-2xl bg-white dark:bg-white/5 border border-gray-200 dark:border-white/10 divide-y divide-gray-100 dark:divide-white/5">
128 + {[...Array(4)].map((_, i) => (
129 + <SkeletonActivity key={i} />
130 + ))}
131 + </div>
132 + </div>
133 + </div>
134 + );
135 +}
added components/ui/TopLoader.tsx +64 −0
@@ -0,0 +1,64 @@
1 +"use client";
2 +
3 +import { useEffect, useState, useRef } from "react";
4 +import { usePathname } from "next/navigation";
5 +
6 +export default function TopLoader() {
7 + const pathname = usePathname();
8 + const [loading, setLoading] = useState(false);
9 + const [progress, setProgress] = useState(0);
10 + const [visible, setVisible] = useState(false);
11 + const prevPathname = useRef(pathname);
12 + const timerRef = useRef<NodeJS.Timeout | null>(null);
13 + const completeTimerRef = useRef<NodeJS.Timeout | null>(null);
14 +
15 + useEffect(() => {
16 + if (pathname !== prevPathname.current) {
17 + prevPathname.current = pathname;
18 +
19 + // Start loading
20 + setLoading(true);
21 + setVisible(true);
22 + setProgress(0);
23 +
24 + // Animate to 80% quickly
25 + if (timerRef.current) clearTimeout(timerRef.current);
26 + timerRef.current = setTimeout(() => setProgress(30), 50);
27 + timerRef.current = setTimeout(() => setProgress(60), 200);
28 + timerRef.current = setTimeout(() => setProgress(80), 400);
29 +
30 + // Complete after a short delay (page has loaded since pathname changed)
31 + if (completeTimerRef.current) clearTimeout(completeTimerRef.current);
32 + completeTimerRef.current = setTimeout(() => {
33 + setProgress(100);
34 + setTimeout(() => {
35 + setLoading(false);
36 + setTimeout(() => {
37 + setVisible(false);
38 + setProgress(0);
39 + }, 200);
40 + }, 150);
41 + }, 500);
42 + }
43 +
44 + return () => {
45 + if (timerRef.current) clearTimeout(timerRef.current);
46 + if (completeTimerRef.current) clearTimeout(completeTimerRef.current);
47 + };
48 + }, [pathname]);
49 +
50 + if (!visible) return null;
51 +
52 + return (
53 + <div className="fixed top-0 left-0 right-0 z-50 h-[2px] pointer-events-none">
54 + <div
55 + className="h-full bg-gradient-to-r from-blue-700 to-blue-500 transition-all ease-out shadow-[0_0_8px_rgba(29,78,216,0.4)]"
56 + style={{
57 + width: `${progress}%`,
58 + transitionDuration: progress === 100 ? "150ms" : "500ms",
59 + opacity: loading ? 1 : 0,
60 + }}
61 + />
62 + </div>
63 + );
64 +}
added components/ui/UserAvatar.tsx +90 −0
@@ -0,0 +1,90 @@
1 +"use client";
2 +
3 +import Image from "next/image";
4 +
5 +interface UserAvatarProps {
6 + userId: string;
7 + name?: string | null;
8 + avatarPath?: string | null;
9 + size?: "sm" | "md" | "lg";
10 +}
11 +
12 +const sizeMap = {
13 + sm: 24,
14 + md: 32,
15 + lg: 48,
16 +};
17 +
18 +const textSizeMap = {
19 + sm: "text-[10px]",
20 + md: "text-xs",
21 + lg: "text-sm",
22 +};
23 +
24 +function hashColor(str: string): string {
25 + let hash = 0;
26 + for (let i = 0; i < str.length; i++) {
27 + hash = str.charCodeAt(i) + ((hash << 5) - hash);
28 + }
29 + const colors = [
30 + "bg-blue-600",
31 + "bg-emerald-600",
32 + "bg-purple-600",
33 + "bg-rose-600",
34 + "bg-amber-600",
35 + "bg-cyan-600",
36 + "bg-indigo-600",
37 + "bg-pink-600",
38 + "bg-teal-600",
39 + "bg-orange-600",
40 + ];
41 + return colors[Math.abs(hash) % colors.length];
42 +}
43 +
44 +function getInitials(name?: string | null): string {
45 + if (!name) return "?";
46 + const parts = name.trim().split(/\s+/);
47 + if (parts.length >= 2) {
48 + return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
49 + }
50 + return name.slice(0, 2).toUpperCase();
51 +}
52 +
53 +export default function UserAvatar({
54 + userId,
55 + name,
56 + avatarPath,
57 + size = "md",
58 +}: UserAvatarProps) {
59 + const px = sizeMap[size];
60 +
61 + if (avatarPath) {
62 + return (
63 + <div
64 + className="relative rounded-full overflow-hidden flex-shrink-0"
65 + style={{ width: px, height: px }}
66 + >
67 + <Image
68 + src={`/api/users/${userId}/avatar`}
69 + alt={name || "Avatar"}
70 + width={px}
71 + height={px}
72 + className="object-cover w-full h-full"
73 + unoptimized
74 + />
75 + </div>
76 + );
77 + }
78 +
79 + const bgColor = hashColor(userId);
80 + const initials = getInitials(name);
81 +
82 + return (
83 + <div
84 + className={`${bgColor} rounded-full flex items-center justify-center flex-shrink-0 text-white font-medium ${textSizeMap[size]}`}
85 + style={{ width: px, height: px }}
86 + >
87 + {initials}
88 + </div>
89 + );
90 +}
added lib/ai-security.ts +100 −0
@@ -0,0 +1,100 @@
1 +import Anthropic from "@anthropic-ai/sdk";
2 +import { prisma } from "./prisma";
3 +
4 +const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
5 +
6 +export interface LoginContext {
7 + userId: string;
8 + ip: string;
9 + country: string;
10 + city: string;
11 + device: string;
12 + browser: string;
13 + os: string;
14 +}
15 +
16 +export interface AiSecurityDecision {
17 + decision: "allow" | "refuse";
18 + reason: string;
19 + riskLevel: "low" | "medium" | "high";
20 +}
21 +
22 +export async function analyzeLogin(ctx: LoginContext): Promise<AiSecurityDecision> {
23 + // Fail-open: if Anthropic is unavailable, allow the login
24 + try {
25 + // Fetch user's last 30 sessions (successful + refused) for context
26 + const history = await prisma.loginSession.findMany({
27 + where: { userId: ctx.userId },
28 + orderBy: { createdAt: "desc" },
29 + take: 30,
30 + select: {
31 + ip: true,
32 + country: true,
33 + city: true,
34 + device: true,
35 + browser: true,
36 + os: true,
37 + status: true,
38 + aiDecision: true,
39 + createdAt: true,
40 + },
41 + });
42 +
43 + const now = new Date();
44 + const hourUTC = now.getUTCHours();
45 +
46 + const historyText = history.length === 0
47 + ? "Aucun historique de connexion (premier login)."
48 + : history.map((s, i) => {
49 + const date = new Date(s.createdAt);
50 + return `${i + 1}. ${date.toISOString().split("T")[0]} ${date.toUTCString().split(" ")[4]}UTC | IP:${s.ip} | ${s.country}/${s.city} | ${s.device} ${s.browser} ${s.os} | statut:${s.status}`;
51 + }).join("\n");
52 +
53 + const prompt = `Tu es un agent de sécurité IA pour un cloud privé personnel. Analyse cette tentative de connexion et décide si elle est légitime ou suspecte.
54 +
55 +TENTATIVE ACTUELLE:
56 +- IP: ${ctx.ip}
57 +- Pays/Ville: ${ctx.country} / ${ctx.city}
58 +- Appareil: ${ctx.device}
59 +- Navigateur: ${ctx.browser}
60 +- OS: ${ctx.os}
61 +- Heure UTC: ${hourUTC}h
62 +
63 +HISTORIQUE DES 30 DERNIÈRES CONNEXIONS:
64 +${historyText}
65 +
66 +CRITÈRES DE SUSPICION (réfléchis à chaque point):
67 +1. Nouveau pays jamais vu dans l'historique (surtout si compte établi avec >3 sessions)
68 +2. Plusieurs connexions refusées récentes depuis la même IP
69 +3. Changement simultané de pays + appareil + navigateur inconnus
70 +4. IP connue comme suspecte ou heure très inhabituelle (ex: 2h-5h UTC si toujours connecté le jour)
71 +5. Première connexion depuis un pays étranger sans historique local
72 +
73 +RÈGLE IMPORTANTE: Si c'est le PREMIER login (historique vide) ou si les 1-2 premières connexions, autoriser (profil pas encore établi).
74 +
75 +Réponds UNIQUEMENT en JSON valide:
76 +{"decision": "allow" ou "refuse", "reason": "explication concise en français (max 150 chars)", "riskLevel": "low" ou "medium" ou "high"}`;
77 +
78 + const response = await anthropic.messages.create({
79 + model: "claude-opus-4-6",
80 + max_tokens: 256,
81 + messages: [{ role: "user", content: prompt }],
82 + });
83 +
84 + const text = response.content[0].type === "text" ? response.content[0].text : "";
85 + const jsonMatch = text.match(/\{[\s\S]*?\}/);
86 + if (!jsonMatch) throw new Error("No JSON in response");
87 +
88 + const parsed = JSON.parse(jsonMatch[0]);
89 +
90 + return {
91 + decision: parsed.decision === "refuse" ? "refuse" : "allow",
92 + reason: String(parsed.reason || "Connexion analysée").slice(0, 200),
93 + riskLevel: ["low", "medium", "high"].includes(parsed.riskLevel) ? parsed.riskLevel : "low",
94 + };
95 + } catch (err) {
96 + // Fail-open: log the error but do NOT block the login if AI is unavailable
97 + console.error("[AI Security] analyzeLogin failed, defaulting to allow:", (err as Error).message);
98 + return { decision: "allow", reason: "Analyse IA indisponible — connexion autorisée par défaut", riskLevel: "low" };
99 + }
100 +}
modified lib/ai.ts +11 −19
@@ -1,13 +1,12 @@
1 1 import Anthropic from "@anthropic-ai/sdk";
2 2 import { prisma } from "./prisma";
3 −import { readFileSync, existsSync } from "fs";
4 −import { getFilePath } from "./storage";
3 +import { loadFileData } from "./storage";
5 4
6 5 const anthropic = new Anthropic({
7 6 apiKey: process.env.ANTHROPIC_API_KEY,
8 7 });
9 8
10 −const MODEL = "claude-sonnet-4-6";
9 +const MODEL = "claude-opus-4-6";
11 10
12 11 export async function aiSearch(query: string, userId?: string): Promise<{
13 12 results: Array<{ fileId: string; name: string; relevance: string; snippet: string; folder?: string; mimeType?: string }>;
@@ -49,7 +48,7 @@ export async function aiSearch(query: string, userId?: string): Promise<{
49 48 }
50 49
51 50 export async function aiAutoTag(fileId: string): Promise<string[]> {
52 − const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, size: true, ocrText: true, storagePath: true } });
51 + const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, size: true, ocrText: true, storagePath: true, isEncrypted: true } });
53 52 if (!file) return [];
54 53
55 54 let contentHint = `Fichier: ${file.name}\nType: ${file.mimeType}\nTaille: ${Number(file.size)} bytes`;
@@ -57,8 +56,7 @@ export async function aiAutoTag(fileId: string): Promise<string[]> {
57 56
58 57 if (file.mimeType.startsWith("text/") || file.mimeType.includes("json") || file.mimeType.includes("xml")) {
59 58 try {
60 − const filePath = getFilePath(file.storagePath);
61 − if (existsSync(filePath)) contentHint += `\nContenu: ${readFileSync(filePath, "utf-8").substring(0, 1000)}`;
59 + contentHint += `\nContenu: ${(await loadFileData(file.storagePath, file.isEncrypted)).toString("utf-8").substring(0, 1000)}`;
62 60 } catch {}
63 61 }
64 62
@@ -81,14 +79,13 @@ export async function aiAutoTag(fileId: string): Promise<string[]> {
81 79 }
82 80
83 81 export async function aiDescribe(fileId: string): Promise<string> {
84 − const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, storagePath: true, ocrText: true } });
82 + const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, storagePath: true, ocrText: true, isEncrypted: true } });
85 83 if (!file) return "";
86 84
87 85 if (file.mimeType.startsWith("image/")) {
88 86 try {
89 − const filePath = getFilePath(file.storagePath);
90 − if (existsSync(filePath)) {
91 − const base64 = readFileSync(filePath).toString("base64");
87 + {
88 + const base64 = (await loadFileData(file.storagePath, file.isEncrypted)).toString("base64");
92 89 const mediaType = file.mimeType as "image/jpeg" | "image/png" | "image/gif" | "image/webp";
93 90 const response = await anthropic.messages.create({
94 91 model: MODEL,
@@ -105,8 +102,7 @@ export async function aiDescribe(fileId: string): Promise<string> {
105 102 let hint = `Fichier: ${file.name}\nType: ${file.mimeType}`;
106 103 if (file.mimeType.startsWith("text/") || file.mimeType.includes("json")) {
107 104 try {
108 − const filePath = getFilePath(file.storagePath);
109 − if (existsSync(filePath)) hint += `\nContenu: ${readFileSync(filePath, "utf-8").substring(0, 2000)}`;
105 + hint += `\nContenu: ${(await loadFileData(file.storagePath, file.isEncrypted)).toString("utf-8").substring(0, 2000)}`;
110 106 } catch {}
111 107 }
112 108 if (file.ocrText) hint += `\nOCR: ${file.ocrText.substring(0, 500)}`;
@@ -122,14 +118,12 @@ export async function aiDescribe(fileId: string): Promise<string> {
122 118 }
123 119
124 120 export async function aiOcr(fileId: string): Promise<string> {
125 − const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, storagePath: true } });
121 + const file = await prisma.file.findUnique({ where: { id: fileId }, select: { id: true, name: true, mimeType: true, storagePath: true, isEncrypted: true } });
126 122 if (!file) return "";
127 123
128 124 if (file.mimeType.startsWith("image/")) {
129 125 try {
130 − const filePath = getFilePath(file.storagePath);
131 − if (!existsSync(filePath)) return "";
132 − const base64 = readFileSync(filePath).toString("base64");
126 + const base64 = (await loadFileData(file.storagePath, file.isEncrypted)).toString("base64");
133 127 const mediaType = file.mimeType as "image/jpeg" | "image/png" | "image/gif" | "image/webp";
134 128 const response = await anthropic.messages.create({
135 129 model: MODEL,
@@ -144,9 +138,7 @@ export async function aiOcr(fileId: string): Promise<string> {
144 138
145 139 if (file.mimeType === "application/pdf") {
146 140 try {
147 − const filePath = getFilePath(file.storagePath);
148 − if (!existsSync(filePath)) return "";
149 − const base64 = readFileSync(filePath).toString("base64");
141 + const base64 = (await loadFileData(file.storagePath, file.isEncrypted)).toString("base64");
150 142 const response = await anthropic.messages.create({
151 143 model: MODEL,
152 144 max_tokens: 8192,
modified lib/encryption.ts +23 −34
@@ -1,14 +1,11 @@
1 −import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "crypto";
2 −import { readFileSync, writeFileSync, existsSync } from "fs";
1 +import { readFile, writeFile } from "fs/promises";
2 +import { existsSync } from "fs";
3 3 import { getFilePath } from "./storage";
4 +import { encryptBuffer, decryptBuffer } from "./filecrypto";
4 5 import { prisma } from "./prisma";
5 6
6 −const ALGORITHM = "aes-256-gcm";
7 −
8 −function getKey(): Buffer {
9 − const masterKey = process.env.ENCRYPTION_KEY || "default-encryption-key-change-me!";
10 − return scryptSync(masterKey, "spb-cloud-salt", 32);
11 −}
7 +// Chiffrement/déchiffrement explicite d'un fichier (action groupée "chiffrer/déchiffrer").
8 +// Format auto-porté géré par filecrypto. Le flag File.isEncrypted indique l'état sur disque.
12 9
13 10 export async function encryptFile(fileId: string): Promise<boolean> {
14 11 const file = await prisma.file.findUnique({ where: { id: fileId } });
@@ -17,46 +14,38 @@ export async function encryptFile(fileId: string): Promise<boolean> {
17 14 const filePath = getFilePath(file.storagePath);
18 15 if (!existsSync(filePath)) return false;
19 16
20 − const key = getKey();
21 − const iv = randomBytes(16);
22 − const cipher = createCipheriv(ALGORITHM, key, iv);
23 −
24 − const plaintext = readFileSync(filePath);
25 − const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
26 − const authTag = cipher.getAuthTag();
27 − const combined = Buffer.concat([authTag, encrypted]);
28 − writeFileSync(filePath, combined);
29 −
30 − await prisma.file.update({ where: { id: fileId }, data: { isEncrypted: true, encryptionIV: iv.toString("hex") } });
17 + const plain = await readFile(filePath);
18 + await writeFile(filePath, encryptBuffer(plain));
19 + await prisma.file.update({
20 + where: { id: fileId },
21 + data: { isEncrypted: true, encryptionIV: "v2" },
22 + });
31 23 return true;
32 24 }
33 25
34 26 export async function decryptFile(fileId: string): Promise<Buffer | null> {
35 27 const file = await prisma.file.findUnique({ where: { id: fileId } });
36 − if (!file || !file.isEncrypted || !file.encryptionIV) return null;
28 + if (!file) return null;
37 29
38 30 const filePath = getFilePath(file.storagePath);
39 31 if (!existsSync(filePath)) return null;
40 32
41 − const key = getKey();
42 − const iv = Buffer.from(file.encryptionIV, "hex");
43 − const combined = readFileSync(filePath);
44 − const authTag = combined.subarray(0, 16);
45 − const encrypted = combined.subarray(16);
46 − const decipher = createDecipheriv(ALGORITHM, key, iv);
47 − decipher.setAuthTag(authTag);
48 − return Buffer.concat([decipher.update(encrypted), decipher.final()]);
33 + const raw = await readFile(filePath);
34 + return file.isEncrypted ? decryptBuffer(raw) : raw;
49 35 }
50 36
51 37 export async function removeEncryption(fileId: string): Promise<boolean> {
52 − const decrypted = await decryptFile(fileId);
53 − if (!decrypted) return false;
54 −
55 38 const file = await prisma.file.findUnique({ where: { id: fileId } });
56 − if (!file) return false;
39 + if (!file || !file.isEncrypted) return false;
57 40
58 41 const filePath = getFilePath(file.storagePath);
59 − writeFileSync(filePath, decrypted);
60 − await prisma.file.update({ where: { id: fileId }, data: { isEncrypted: false, encryptionIV: null } });
42 + if (!existsSync(filePath)) return false;
43 +
44 + const raw = await readFile(filePath);
45 + await writeFile(filePath, decryptBuffer(raw));
46 + await prisma.file.update({
47 + where: { id: fileId },
48 + data: { isEncrypted: false, encryptionIV: null },
49 + });
61 50 return true;
62 51 }
added lib/filecrypto.ts +37 −0
@@ -0,0 +1,37 @@
1 +import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "crypto";
2 +
3 +// Chiffrement de CONTENU de fichiers au repos (AES-256-GCM).
4 +// Clé dédiée FILE_ENCRYPTION_KEY (≠ ENCRYPTION_KEY du gestionnaire de mots de passe).
5 +// Format auto-porté : [iv(12) | authTag(16) | ciphertext] — pas besoin de stocker l'IV en base.
6 +
7 +const ALGORITHM = "aes-256-gcm";
8 +const IV_LEN = 12;
9 +const TAG_LEN = 16;
10 +
11 +let cachedKey: Buffer | null = null;
12 +function getKey(): Buffer {
13 + if (cachedKey) return cachedKey;
14 + const master =
15 + process.env.FILE_ENCRYPTION_KEY ||
16 + process.env.ENCRYPTION_KEY ||
17 + "default-encryption-key-change-me!";
18 + cachedKey = scryptSync(master, "spb-cloud-file-salt", 32);
19 + return cachedKey;
20 +}
21 +
22 +export function encryptBuffer(plain: Buffer): Buffer {
23 + const iv = randomBytes(IV_LEN);
24 + const cipher = createCipheriv(ALGORITHM, getKey(), iv);
25 + const enc = Buffer.concat([cipher.update(plain), cipher.final()]);
26 + const tag = cipher.getAuthTag();
27 + return Buffer.concat([iv, tag, enc]);
28 +}
29 +
30 +export function decryptBuffer(data: Buffer): Buffer {
31 + const iv = data.subarray(0, IV_LEN);
32 + const tag = data.subarray(IV_LEN, IV_LEN + TAG_LEN);
33 + const enc = data.subarray(IV_LEN + TAG_LEN);
34 + const decipher = createDecipheriv(ALGORITHM, getKey(), iv);
35 + decipher.setAuthTag(tag);
36 + return Buffer.concat([decipher.update(enc), decipher.final()]);
37 +}
added lib/geo.ts +37 −0
@@ -0,0 +1,37 @@
1 +export interface GeoInfo {
2 + country: string;
3 + city: string;
4 +}
5 +
6 +const LOCAL_IPS = new Set(["127.0.0.1", "::1", "localhost"]);
7 +
8 +function isLocalIp(ip: string): boolean {
9 + if (LOCAL_IPS.has(ip)) return true;
10 + if (ip.startsWith("192.168.") || ip.startsWith("10.") || ip.startsWith("172.")) return true;
11 + return false;
12 +}
13 +
14 +export async function getGeoFromIp(ip: string): Promise<GeoInfo> {
15 + // Strip port if present (e.g. "::ffff:1.2.3.4")
16 + const cleanIp = ip.replace(/^::ffff:/, "").split(",")[0].trim();
17 +
18 + if (isLocalIp(cleanIp)) {
19 + return { country: "Réseau local", city: "" };
20 + }
21 +
22 + try {
23 + const res = await fetch(
24 + `http://ip-api.com/json/${encodeURIComponent(cleanIp)}?fields=status,country,city&lang=fr`,
25 + { signal: AbortSignal.timeout(3000) }
26 + );
27 + if (!res.ok) throw new Error("HTTP error");
28 + const data = await res.json();
29 + if (data.status === "success") {
30 + return { country: data.country || "", city: data.city || "" };
31 + }
32 + } catch {
33 + // Geo lookup failed — non-blocking
34 + }
35 +
36 + return { country: "", city: "" };
37 +}
modified lib/notifications.ts +19 −0
@@ -33,3 +33,22 @@ export async function notifyBackupComplete(userId: string, backupId: string) {
33 33 export async function notifyAiComplete(userId: string, fileName: string, action: string) {
34 34 return createNotification(userId, "ai_complete", "Analyse IA", `${action} terminée pour ${fileName}`);
35 35 }
36 +
37 +export async function notifyFileComment(userId: string, commenterName: string, fileName: string, fileId: string) {
38 + return createNotification(userId, "comment", "Nouveau commentaire", `${commenterName} a commenté sur ${fileName}`, { fileId });
39 +}
40 +
41 +export async function notifySharedSpaceUpload(spaceId: string, uploaderUserId: string, fileName: string, fileId: string) {
42 + const members = await prisma.sharedSpaceMember.findMany({
43 + where: { sharedSpaceId: spaceId, userId: { not: uploaderUserId } },
44 + select: { userId: true },
45 + });
46 + const uploader = await prisma.user.findUnique({
47 + where: { id: uploaderUserId },
48 + select: { name: true, username: true },
49 + });
50 + const uploaderName = uploader?.name || uploader?.username || "Quelqu'un";
51 + for (const member of members) {
52 + await createNotification(member.userId, "share", "Nouveau fichier partage", `${uploaderName} a ajoute ${fileName}`, { fileId, spaceId });
53 + }
54 +}
modified lib/prisma.ts +16 −1
@@ -2,8 +2,23 @@ import { PrismaClient } from "@prisma/client";
2 2
3 3 const globalForPrisma = globalThis as unknown as {
4 4 prisma: PrismaClient | undefined;
5 + prismaPragmaSet: boolean | undefined;
5 6 };
6 7
7 8 export const prisma = globalForPrisma.prisma ?? new PrismaClient();
8 9
9 −if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
10 +// SQLite: WAL est persistant (posé sur le fichier), mais busy_timeout est
11 +// par-connexion → on l'applique une fois au démarrage pour que les écritures
12 +// concurrentes attendent le verrou au lieu d'échouer ("database is locked").
13 +if (!globalForPrisma.prismaPragmaSet) {
14 + globalForPrisma.prismaPragmaSet = true;
15 + prisma
16 + .$executeRawUnsafe("PRAGMA busy_timeout = 5000;")
17 + .then(() => prisma.$executeRawUnsafe("PRAGMA synchronous = NORMAL;"))
18 + .catch(() => {
19 + /* non-SQLite ou indisponible : ignore */
20 + });
21 +}
22 +
23 +// Toujours mémoriser le client (évite l'épuisement de connexions en dev hot-reload)
24 +globalForPrisma.prisma = prisma;
modified lib/session.ts +1 −0
@@ -7,6 +7,7 @@ export interface SessionData {
7 7 csrfToken?: string;
8 8 pendingTwoFactor?: boolean;
9 9 pendingUserId?: string;
10 + sessionToken?: string; // ties the cookie to a LoginSession record
10 11 }
11 12
12 13 export const sessionOptions: SessionOptions = {
added lib/snapshot.ts +178 −0
@@ -0,0 +1,178 @@
1 +import { cp, rm, mkdir, stat, readdir } from "fs/promises";
2 +import { existsSync, mkdirSync } from "fs";
3 +import path from "path";
4 +import { prisma } from "./prisma";
5 +
6 +const SNAPSHOT_DIR = process.env.SNAPSHOT_DIR || "./snapshots";
7 +const UPLOAD_DIR = process.env.UPLOAD_DIR || "./uploads";
8 +const FILES_DIR = path.join(UPLOAD_DIR, "files");
9 +const MAX_SNAPSHOTS = 7;
10 +
11 +if (!existsSync(SNAPSHOT_DIR)) mkdirSync(SNAPSHOT_DIR, { recursive: true });
12 +
13 +function getTodayKey(): string {
14 + return new Date().toISOString().split("T")[0]; // YYYY-MM-DD
15 +}
16 +
17 +function buildLabel(dateStr: string): string {
18 + // dateStr = YYYY-MM-DD, parse in local noon to avoid timezone shifts
19 + const [y, m, d] = dateStr.split("-").map(Number);
20 + const date = new Date(y, m - 1, d, 12);
21 + return date.toLocaleDateString("fr-FR", {
22 + weekday: "long",
23 + day: "numeric",
24 + month: "long",
25 + year: "numeric",
26 + });
27 +}
28 +
29 +async function getDirSize(dir: string): Promise<number> {
30 + if (!existsSync(dir)) return 0;
31 + let total = 0;
32 + const entries = await readdir(dir, { withFileTypes: true });
33 + for (const entry of entries) {
34 + const full = path.join(dir, entry.name);
35 + if (entry.isDirectory()) {
36 + total += await getDirSize(full);
37 + } else {
38 + const s = await stat(full);
39 + total += s.size;
40 + }
41 + }
42 + return total;
43 +}
44 +
45 +export async function createSnapshot(): Promise<{ id: string; snapshotDate: string }> {
46 + const snapshotDate = getTodayKey();
47 + const snapshotPath = path.resolve(path.join(SNAPSHOT_DIR, snapshotDate));
48 + const label = buildLabel(snapshotDate);
49 +
50 + // Upsert the DB record (one per day — re-snapshot replaces the old one)
51 + let record = await prisma.snapshot.findUnique({ where: { snapshotDate } });
52 +
53 + // Remove existing snapshot dir if present
54 + if (existsSync(snapshotPath)) {
55 + await rm(snapshotPath, { recursive: true, force: true });
56 + }
57 + mkdirSync(snapshotPath, { recursive: true });
58 +
59 + if (record) {
60 + record = await prisma.snapshot.update({
61 + where: { id: record.id },
62 + data: { status: "pending", error: null, label, path: snapshotPath, createdAt: new Date() },
63 + });
64 + } else {
65 + record = await prisma.snapshot.create({
66 + data: { label, snapshotDate, path: snapshotPath, status: "pending", size: BigInt(0) },
67 + });
68 + }
69 +
70 + try {
71 + // Copy uploads/files
72 + const filesSnapshot = path.join(snapshotPath, "files");
73 + mkdirSync(filesSnapshot, { recursive: true });
74 + if (existsSync(FILES_DIR)) {
75 + await cp(FILES_DIR, filesSnapshot, { recursive: true });
76 + }
77 +
78 + // Copy SQLite DB
79 + const dbPath = path.resolve("./prisma/dev.db");
80 + const dbSnapshotDir = path.join(snapshotPath, "database");
81 + mkdirSync(dbSnapshotDir, { recursive: true });
82 + if (existsSync(dbPath)) {
83 + await cp(dbPath, path.join(dbSnapshotDir, "dev.db"));
84 + }
85 +
86 + const size = await getDirSize(snapshotPath);
87 +
88 + await prisma.snapshot.update({
89 + where: { id: record.id },
90 + data: { status: "completed", size: BigInt(size) },
91 + });
92 +
93 + // Keep only the last MAX_SNAPSHOTS days
94 + await pruneOldSnapshots();
95 +
96 + return { id: record.id, snapshotDate };
97 + } catch (error) {
98 + await prisma.snapshot.update({
99 + where: { id: record.id },
100 + data: { status: "failed", error: (error as Error).message },
101 + });
102 + throw error;
103 + }
104 +}
105 +
106 +export async function listSnapshots() {
107 + const snapshots = await prisma.snapshot.findMany({
108 + orderBy: { snapshotDate: "desc" },
109 + take: MAX_SNAPSHOTS,
110 + });
111 + return snapshots.map((s) => ({ ...s, size: Number(s.size) }));
112 +}
113 +
114 +export async function deleteSnapshot(id: string): Promise<boolean> {
115 + const snapshot = await prisma.snapshot.findUnique({ where: { id } });
116 + if (!snapshot) return false;
117 + if (existsSync(snapshot.path)) {
118 + await rm(snapshot.path, { recursive: true, force: true });
119 + }
120 + await prisma.snapshot.delete({ where: { id } });
121 + return true;
122 +}
123 +
124 +export async function restoreSnapshot(id: string): Promise<void> {
125 + const snapshot = await prisma.snapshot.findUnique({ where: { id } });
126 + if (!snapshot || snapshot.status !== "completed") {
127 + throw new Error("Snapshot introuvable ou incomplet");
128 + }
129 + if (!existsSync(snapshot.path)) {
130 + throw new Error("Fichiers du snapshot manquants sur le disque");
131 + }
132 +
133 + const filesSnapshot = path.join(snapshot.path, "files");
134 + const dbSnapshot = path.join(snapshot.path, "database", "dev.db");
135 +
136 + // Restore files dir
137 + if (existsSync(filesSnapshot)) {
138 + if (existsSync(FILES_DIR)) {
139 + await rm(FILES_DIR, { recursive: true, force: true });
140 + }
141 + await mkdir(FILES_DIR, { recursive: true });
142 + await cp(filesSnapshot, FILES_DIR, { recursive: true });
143 + }
144 +
145 + // Restore SQLite DB
146 + if (existsSync(dbSnapshot)) {
147 + const dbPath = path.resolve("./prisma/dev.db");
148 + await prisma.$disconnect();
149 + await cp(dbSnapshot, dbPath);
150 + // Prisma reconnects automatically on next query
151 + }
152 +}
153 +
154 +async function pruneOldSnapshots(): Promise<void> {
155 + const all = await prisma.snapshot.findMany({ orderBy: { snapshotDate: "desc" } });
156 + const toDelete = all.slice(MAX_SNAPSHOTS);
157 + for (const snapshot of toDelete) {
158 + if (existsSync(snapshot.path)) {
159 + await rm(snapshot.path, { recursive: true, force: true });
160 + }
161 + await prisma.snapshot.delete({ where: { id: snapshot.id } });
162 + }
163 +}
164 +
165 +/**
166 + * Called by the server on an hourly tick.
167 + * Creates a snapshot only if none exists for today yet.
168 + * Returns true if a snapshot was created.
169 + */
170 +export async function createDailySnapshotIfNeeded(): Promise<boolean> {
171 + const today = getTodayKey();
172 + const existing = await prisma.snapshot.findUnique({
173 + where: { snapshotDate: today },
174 + });
175 + if (existing?.status === "completed") return false;
176 + await createSnapshot();
177 + return true;
178 +}
modified lib/storage.ts +102 −32
@@ -1,16 +1,19 @@
1 1 import { createReadStream, createWriteStream, existsSync, mkdirSync } from "fs";
2 −import { unlink, copyFile, readdir, rm, stat } from "fs/promises";
2 +import { unlink, copyFile, readdir, rm, stat, readFile, writeFile } from "fs/promises";
3 3 import path from "path";
4 4 import { v4 as uuidv4 } from "uuid";
5 5 import { ReadStream } from "fs";
6 +import sharp from "sharp";
7 +import { encryptBuffer, decryptBuffer } from "./filecrypto";
6 8
7 9 const UPLOAD_DIR = process.env.UPLOAD_DIR || "./uploads";
8 10 const FILES_DIR = path.join(UPLOAD_DIR, "files");
9 11 const CHUNKS_DIR = path.join(UPLOAD_DIR, "chunks");
10 12 const VERSIONS_DIR = path.join(UPLOAD_DIR, "versions");
13 +const THUMBS_DIR = path.join(UPLOAD_DIR, "thumbnails");
11 14
12 15 // Ensure directories exist
13 −[FILES_DIR, CHUNKS_DIR, VERSIONS_DIR].forEach((dir) => {
16 +[FILES_DIR, CHUNKS_DIR, VERSIONS_DIR, THUMBS_DIR].forEach((dir) => {
14 17 if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
15 18 });
16 19
@@ -27,13 +30,8 @@ export async function saveFile(
27 30 const storagePath = `${uuidv4()}${ext}`;
28 31 const fullPath = path.join(FILES_DIR, storagePath);
29 32
30 − await new Promise<void>((resolve, reject) => {
31 − const stream = createWriteStream(fullPath);
32 − stream.write(buffer);
33 − stream.end();
34 − stream.on("finish", resolve);
35 − stream.on("error", reject);
36 − });
33 + // Chiffrement au repos (le fichier sur disque est chiffré ; size = taille en clair)
34 + await writeFile(fullPath, encryptBuffer(buffer));
37 35
38 36 return { storagePath, size: buffer.length };
39 37 }
@@ -66,28 +64,19 @@ export async function assembleChunks(
66 64 const fullPath = path.join(FILES_DIR, storagePath);
67 65 const chunkDir = path.join(CHUNKS_DIR, uploadId);
68 66
69 − const writeStream = createWriteStream(fullPath);
70 − let totalSize = 0;
71 −
67 + // Réassemble en mémoire puis chiffre (size = taille en clair)
68 + const parts: Buffer[] = [];
72 69 for (let i = 0; i < totalChunks; i++) {
73 70 const chunkPath = path.join(chunkDir, `chunk-${i}`);
74 − const chunkBuffer = await new Promise<Buffer>((resolve, reject) => {
75 − const chunks: Buffer[] = [];
76 − const readStream = createReadStream(chunkPath);
77 − readStream.on("data", (chunk) => chunks.push(chunk as Buffer));
78 − readStream.on("end", () => resolve(Buffer.concat(chunks)));
79 − readStream.on("error", reject);
80 − });
81 − writeStream.write(chunkBuffer);
82 − totalSize += chunkBuffer.length;
71 + parts.push(await readFile(chunkPath));
83 72 }
84 −
85 − await new Promise<void>((resolve) => writeStream.end(resolve));
73 + const full = Buffer.concat(parts);
74 + await writeFile(fullPath, encryptBuffer(full));
86 75
87 76 // Clean up chunks
88 77 await rm(chunkDir, { recursive: true, force: true });
89 78
90 − return { storagePath, size: totalSize };
79 + return { storagePath, size: full.length };
91 80 }
92 81
93 82 export async function deleteFile(storagePath: string): Promise<void> {
@@ -182,12 +171,93 @@ export async function saveFileFromBuffer(
182 171 buffer: Buffer,
183 172 storagePath: string
184 173 ): Promise<void> {
185 − const fullPath = path.join(FILES_DIR, storagePath);
186 − await new Promise<void>((resolve, reject) => {
187 − const stream = createWriteStream(fullPath);
188 − stream.write(buffer);
189 − stream.end();
190 − stream.on("finish", resolve);
191 − stream.on("error", reject);
192 − });
174 + // Chiffre au repos (écrase le fichier existant avec le contenu chiffré)
175 + await writeFile(path.join(FILES_DIR, storagePath), encryptBuffer(buffer));
176 +}
177 +
178 +// --- Thumbnails (rendus image redimensionnés, mis en cache sur disque) ---
179 +
180 +// Évite de régénérer la même miniature plusieurs fois en parallèle
181 +const inflightThumbs = new Map<string, Promise<Buffer>>();
182 +
183 +/**
184 + * Retourne le chemin d'une miniature webp de largeur `width` pour le fichier image.
185 + * Génère et met en cache à la première demande ; régénère si l'original a changé.
186 + */
187 +/**
188 + * Retourne les octets webp d'une miniature de largeur `width` (déchiffrés, prêts à servir).
189 + * Cache disque CHIFFRÉ (`<id>-<w>.webp.enc`). Régénère si l'original a changé.
190 + */
191 +export async function getThumbnail(
192 + storagePath: string,
193 + fileId: string,
194 + width: number,
195 + isEncrypted: boolean
196 +): Promise<Buffer> {
197 + const srcPath = path.join(FILES_DIR, storagePath);
198 + const cachePath = path.join(THUMBS_DIR, `${fileId}-${width}.webp.enc`);
199 +
200 + let fresh = false;
201 + if (existsSync(cachePath)) {
202 + try {
203 + const [src, thumb] = await Promise.all([stat(srcPath), stat(cachePath)]);
204 + fresh = thumb.mtimeMs >= src.mtimeMs;
205 + } catch {
206 + fresh = false;
207 + }
208 + }
209 +
210 + if (fresh) {
211 + return decryptBuffer(await readFile(cachePath));
212 + }
213 +
214 + let job = inflightThumbs.get(cachePath);
215 + if (!job) {
216 + job = (async () => {
217 + const raw = await readFile(srcPath);
218 + const src = isEncrypted ? decryptBuffer(raw) : raw;
219 + const webp = await sharp(src, { failOn: "none" })
220 + .rotate() // respecte l'orientation EXIF
221 + .resize({ width, withoutEnlargement: true })
222 + .webp({ quality: 80 })
223 + .toBuffer();
224 + await writeFile(cachePath, encryptBuffer(webp)); // cache chiffré au repos
225 + return webp;
226 + })().finally(() => inflightThumbs.delete(cachePath));
227 + inflightThumbs.set(cachePath, job);
228 + }
229 + return job;
230 +}
231 +
232 +/** Lit un fichier et le déchiffre si nécessaire → buffer en clair prêt à servir. */
233 +export async function loadFileData(
234 + storagePath: string,
235 + isEncrypted: boolean
236 +): Promise<Buffer> {
237 + const raw = await readFile(path.join(FILES_DIR, storagePath));
238 + return isEncrypted ? decryptBuffer(raw) : raw;
239 +}
240 +
241 +/** Lit une version (dans VERSIONS_DIR) et la déchiffre si nécessaire. */
242 +export async function loadVersionData(
243 + storagePath: string,
244 + isEncrypted: boolean
245 +): Promise<Buffer> {
246 + const raw = await readFile(path.join(VERSIONS_DIR, storagePath));
247 + return isEncrypted ? decryptBuffer(raw) : raw;
248 +}
249 +
250 +/** Supprime toutes les miniatures en cache d'un fichier (à appeler à la suppression). */
251 +export async function deleteThumbnails(fileId: string): Promise<void> {
252 + if (!existsSync(THUMBS_DIR)) return;
253 + try {
254 + const entries = await readdir(THUMBS_DIR);
255 + await Promise.all(
256 + entries
257 + .filter((name) => name.startsWith(`${fileId}-`))
258 + .map((name) => unlink(path.join(THUMBS_DIR, name)).catch(() => {}))
259 + );
260 + } catch {
261 + // ignore
262 + }
193 263 }
added lib/ua-parser.ts +47 −0
@@ -0,0 +1,47 @@
1 +export interface ParsedUA {
2 + device: "Desktop" | "Mobile" | "Tablet";
3 + browser: string;
4 + os: string;
5 +}
6 +
7 +export function parseUserAgent(ua: string): ParsedUA {
8 + if (!ua) return { device: "Desktop", browser: "Inconnu", os: "Inconnu" };
9 +
10 + // Device type
11 + const isTablet = /iPad|Tablet|PlayBook/i.test(ua) || (/Android/i.test(ua) && !/Mobile/i.test(ua));
12 + const isMobile = !isTablet && /Mobile|Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone/i.test(ua);
13 + const device: ParsedUA["device"] = isTablet ? "Tablet" : isMobile ? "Mobile" : "Desktop";
14 +
15 + // Browser
16 + let browser = "Inconnu";
17 + if (/Edg\//i.test(ua)) browser = "Edge";
18 + else if (/OPR\//i.test(ua) || /Opera/i.test(ua)) browser = "Opera";
19 + else if (/SamsungBrowser/i.test(ua)) browser = "Samsung Browser";
20 + else if (/Firefox/i.test(ua)) browser = "Firefox";
21 + else if (/Chrome/i.test(ua)) browser = "Chrome";
22 + else if (/Safari/i.test(ua)) browser = "Safari";
23 + else if (/MSIE|Trident/i.test(ua)) browser = "Internet Explorer";
24 + else if (/curl/i.test(ua)) browser = "cURL";
25 +
26 + // OS
27 + let os = "Inconnu";
28 + if (/Windows NT 10/i.test(ua)) os = "Windows 10/11";
29 + else if (/Windows NT 6\.3/i.test(ua)) os = "Windows 8.1";
30 + else if (/Windows NT 6\.1/i.test(ua)) os = "Windows 7";
31 + else if (/Windows/i.test(ua)) os = "Windows";
32 + else if (/iPhone OS ([\d_]+)/i.test(ua)) {
33 + const m = ua.match(/iPhone OS ([\d_]+)/i);
34 + os = `iOS ${m ? m[1].replace(/_/g, ".") : ""}`;
35 + } else if (/iPad.*OS ([\d_]+)/i.test(ua)) {
36 + const m = ua.match(/OS ([\d_]+)/i);
37 + os = `iPadOS ${m ? m[1].replace(/_/g, ".") : ""}`;
38 + } else if (/Android ([\d.]+)/i.test(ua)) {
39 + const m = ua.match(/Android ([\d.]+)/i);
40 + os = `Android ${m ? m[1] : ""}`;
41 + } else if (/Mac OS X ([\d_]+)/i.test(ua)) {
42 + const m = ua.match(/Mac OS X ([\d_]+)/i);
43 + os = `macOS ${m ? m[1].replace(/_/g, ".") : ""}`;
44 + } else if (/Linux/i.test(ua)) os = "Linux";
45 +
46 + return { device, browser, os };
47 +}
added lib/webdav.ts +1185 −0
@@ -0,0 +1,1185 @@
1 +import { IncomingMessage, ServerResponse } from "http";
2 +import { existsSync, statSync } from "fs";
3 +import { randomUUID } from "crypto";
4 +import bcrypt from "bcryptjs";
5 +import { lookup as mimeTypeLookup } from "mime-types";
6 +import { prisma } from "./prisma";
7 +import {
8 + getFilePath,
9 + getFileStream,
10 + saveFile,
11 + deleteFile,
12 + duplicateFile,
13 +} from "./storage";
14 +import { logActivity } from "./activity";
15 +
16 +// ---------------------------------------------------------------------------
17 +// Constants
18 +// ---------------------------------------------------------------------------
19 +
20 +/** Virtual folder name for shared spaces — visible in Finder as a directory */
21 +const SHARED_PREFIX = "Shared Spaces";
22 +
23 +// ---------------------------------------------------------------------------
24 +// Types
25 +// ---------------------------------------------------------------------------
26 +
27 +interface DavUser {
28 + id: string;
29 + username: string;
30 +}
31 +
32 +interface PropItem {
33 + href: string;
34 + name: string;
35 + isDir: boolean;
36 + size?: bigint | number;
37 + mimeType?: string;
38 + modifiedAt: Date;
39 + createdAt: Date;
40 +}
41 +
42 +/** Parsed DAV path context */
43 +type DavContext =
44 + | { kind: "personal-root" }
45 + | { kind: "shared-root" }
46 + | { kind: "personal"; folderParts: string[]; filename: string | null; isDir: boolean }
47 + | { kind: "shared-spaces-list" }
48 + | { kind: "shared-space-root"; spaceName: string }
49 + | { kind: "shared-content"; spaceName: string; folderParts: string[]; filename: string | null; isDir: boolean };
50 +
51 +// In-memory lock store (reset on restart — sufficient for single-instance DAV)
52 +const locks = new Map<string, string>();
53 +
54 +// ---------------------------------------------------------------------------
55 +// Helpers
56 +// ---------------------------------------------------------------------------
57 +
58 +function escapeXml(s: string): string {
59 + return s
60 + .replace(/&/g, "&amp;")
61 + .replace(/</g, "&lt;")
62 + .replace(/>/g, "&gt;")
63 + .replace(/"/g, "&quot;");
64 +}
65 +
66 +function parseBasicAuth(
67 + req: IncomingMessage
68 +): { username: string; password: string } | null {
69 + const auth = req.headers["authorization"];
70 + if (!auth?.startsWith("Basic ")) return null;
71 + const decoded = Buffer.from(auth.slice(6), "base64").toString("utf-8");
72 + const colonIdx = decoded.indexOf(":");
73 + if (colonIdx === -1) return null;
74 + return {
75 + username: decoded.slice(0, colonIdx),
76 + password: decoded.slice(colonIdx + 1),
77 + };
78 +}
79 +
80 +async function authenticate(req: IncomingMessage): Promise<DavUser | null> {
81 + const creds = parseBasicAuth(req);
82 + if (!creds) return null;
83 +
84 + const user = await prisma.user.findFirst({
85 + where: {
86 + OR: [{ username: creds.username }, { email: creds.username }],
87 + },
88 + select: { id: true, username: true, passwordHash: true },
89 + });
90 +
91 + if (!user) return null;
92 + const valid = await bcrypt.compare(creds.password, user.passwordHash);
93 + if (!valid) return null;
94 +
95 + return { id: user.id, username: user.username ?? creds.username };
96 +}
97 +
98 +async function readBody(req: IncomingMessage): Promise<Buffer> {
99 + return new Promise((resolve, reject) => {
100 + const chunks: Buffer[] = [];
101 + req.on("data", (c: Buffer) => chunks.push(c));
102 + req.on("end", () => resolve(Buffer.concat(chunks)));
103 + req.on("error", reject);
104 + });
105 +}
106 +
107 +/** Strip /dav prefix, percent-decode each segment */
108 +function getDavPath(req: IncomingMessage): string {
109 + const raw = (req.url || "/").split("?")[0];
110 + const stripped = raw.replace(/^\/dav/, "") || "/";
111 + return stripped
112 + .split("/")
113 + .map((p) => {
114 + try { return decodeURIComponent(p); } catch { return p; }
115 + })
116 + .join("/");
117 +}
118 +
119 +/** Parse a decoded DAV path into a structured context */
120 +function parseDavPath(davPath: string): DavContext {
121 + const isDir = davPath === "/" || davPath.endsWith("/");
122 + const parts = davPath.split("/").filter(Boolean);
123 +
124 + // Root
125 + if (parts.length === 0) return { kind: "personal-root" };
126 +
127 + // Shared Spaces virtual folder
128 + if (parts[0] === SHARED_PREFIX) {
129 + if (parts.length === 1) return { kind: "shared-spaces-list" };
130 + const spaceName = parts[1];
131 + if (parts.length === 2) return { kind: "shared-space-root", spaceName };
132 +
133 + const rest = parts.slice(2);
134 + const sharedIsDir = isDir || false;
135 + if (sharedIsDir || rest.length === 0) {
136 + return { kind: "shared-content", spaceName, folderParts: rest, filename: null, isDir: true };
137 + }
138 + return {
139 + kind: "shared-content",
140 + spaceName,
141 + folderParts: rest.slice(0, -1),
142 + filename: rest[rest.length - 1],
143 + isDir: false,
144 + };
145 + }
146 +
147 + // Personal content
148 + if (isDir) {
149 + return { kind: "personal", folderParts: parts, filename: null, isDir: true };
150 + }
151 + return {
152 + kind: "personal",
153 + folderParts: parts.slice(0, -1),
154 + filename: parts[parts.length - 1],
155 + isDir: false,
156 + };
157 +}
158 +
159 +function notFoundError(): Error {
160 + const err = new Error("Not found");
161 + (err as NodeJS.ErrnoException).code = "NOT_FOUND";
162 + return err;
163 +}
164 +
165 +/** Resolve personal folder path → folderId (null = root). Throws NOT_FOUND. */
166 +async function resolvePersonalFolder(
167 + userId: string,
168 + parts: string[]
169 +): Promise<string | null> {
170 + if (parts.length === 0) return null;
171 + let parentId: string | null = null;
172 + for (const part of parts) {
173 + const found: { id: string } | null = await prisma.folder.findFirst({
174 + where: { userId, name: part, parentId },
175 + });
176 + if (!found) throw notFoundError();
177 + parentId = found.id;
178 + }
179 + return parentId;
180 +}
181 +
182 +/** Find a shared space the user is a member of, by name. */
183 +async function findSharedSpace(userId: string, spaceName: string) {
184 + const membership = await prisma.sharedSpaceMember.findFirst({
185 + where: { userId, sharedSpace: { name: spaceName } },
186 + include: { sharedSpace: true },
187 + });
188 + return membership?.sharedSpace ?? null;
189 +}
190 +
191 +/** Resolve folder path within a shared space → folderId (null = space root). Throws NOT_FOUND. */
192 +async function resolveSharedFolder(
193 + spaceId: string,
194 + parts: string[]
195 +): Promise<string | null> {
196 + if (parts.length === 0) return null;
197 + let parentId: string | null = null;
198 + for (const part of parts) {
199 + const found: { id: string } | null = await prisma.folder.findFirst({
200 + where: { sharedSpaceId: spaceId, name: part, parentId },
201 + });
202 + if (!found) throw notFoundError();
203 + parentId = found.id;
204 + }
205 + return parentId;
206 +}
207 +
208 +/** Extract destination DAV path from the Destination header */
209 +function extractDestPath(header: string): string {
210 + try {
211 + const url = new URL(header);
212 + return url.pathname.replace(/^\/dav/, "") || "/";
213 + } catch {
214 + return header.replace(/^\/dav/, "") || "/";
215 + }
216 +}
217 +
218 +function decodePath(p: string): string {
219 + return p.split("/").map((s) => { try { return decodeURIComponent(s); } catch { return s; } }).join("/");
220 +}
221 +
222 +// ---------------------------------------------------------------------------
223 +// XML builders
224 +// ---------------------------------------------------------------------------
225 +
226 +function buildMultistatusXml(items: PropItem[]): string {
227 + const responses = items
228 + .map((item) => {
229 + const sizeNum = item.size !== undefined ? Number(item.size) : 0;
230 + const typeProps = item.isDir
231 + ? `<D:resourcetype><D:collection/></D:resourcetype>`
232 + : `<D:resourcetype/><D:getcontentlength>${sizeNum}</D:getcontentlength><D:getcontenttype>${escapeXml(item.mimeType || "application/octet-stream")}</D:getcontenttype>`;
233 + return ` <D:response>
234 + <D:href>${escapeXml(item.href)}</D:href>
235 + <D:propstat>
236 + <D:prop>
237 + <D:displayname>${escapeXml(item.name)}</D:displayname>
238 + ${typeProps}
239 + <D:getlastmodified>${item.modifiedAt.toUTCString()}</D:getlastmodified>
240 + <D:creationdate>${item.createdAt.toISOString()}</D:creationdate>
241 + </D:prop>
242 + <D:status>HTTP/1.1 200 OK</D:status>
243 + </D:propstat>
244 + </D:response>`;
245 + })
246 + .join("\n");
247 + return `<?xml version="1.0" encoding="utf-8"?>\n<D:multistatus xmlns:D="DAV:">\n${responses}\n</D:multistatus>`;
248 +}
249 +
250 +function buildLockXml(token: string, davPath: string, owner: string): string {
251 + return `<?xml version="1.0" encoding="utf-8"?>
252 +<D:prop xmlns:D="DAV:">
253 + <D:lockdiscovery>
254 + <D:activelock>
255 + <D:locktype><D:write/></D:locktype>
256 + <D:lockscope><D:exclusive/></D:lockscope>
257 + <D:depth>0</D:depth>
258 + <D:owner>${escapeXml(owner)}</D:owner>
259 + <D:timeout>Second-3600</D:timeout>
260 + <D:locktoken><D:href>${token}</D:href></D:locktoken>
261 + <D:lockroot><D:href>/dav${escapeXml(davPath)}</D:href></D:lockroot>
262 + </D:activelock>
263 + </D:lockdiscovery>
264 +</D:prop>`;
265 +}
266 +
267 +// ---------------------------------------------------------------------------
268 +// PROPFIND builders for each context
269 +// ---------------------------------------------------------------------------
270 +
271 +function sharedSpaceHref(spaceName: string, folderParts: string[] = [], filename?: string): string {
272 + const base = `/dav/${encodeURIComponent(SHARED_PREFIX)}/${encodeURIComponent(spaceName)}`;
273 + const folderPath = folderParts.map(encodeURIComponent).join("/");
274 + if (filename) {
275 + return `${base}${folderPath ? "/" + folderPath : ""}/${encodeURIComponent(filename)}`;
276 + }
277 + return `${base}${folderPath ? "/" + folderPath : ""}/`;
278 +}
279 +
280 +function personalHref(folderParts: string[] = [], filename?: string): string {
281 + const folderPath = folderParts.map(encodeURIComponent).join("/");
282 + if (filename) {
283 + return `/dav${folderPath ? "/" + folderPath : ""}/${encodeURIComponent(filename)}`;
284 + }
285 + return `/dav/${folderPath}/`;
286 +}
287 +
288 +async function buildPersonalRootItems(userId: string, depth: string): Promise<PropItem[]> {
289 + const now = new Date();
290 + const items: PropItem[] = [
291 + { href: "/dav/", name: "SPB Cloud", isDir: true, modifiedAt: now, createdAt: now },
292 + ];
293 +
294 + if (depth === "0") return items;
295 +
296 + // Virtual "Shared Spaces" folder
297 + items.push({
298 + href: `/dav/${encodeURIComponent(SHARED_PREFIX)}/`,
299 + name: SHARED_PREFIX,
300 + isDir: true,
301 + modifiedAt: now,
302 + createdAt: now,
303 + });
304 +
305 + const [folders, files] = await Promise.all([
306 + prisma.folder.findMany({ where: { userId, parentId: null } }),
307 + prisma.file.findMany({ where: { userId, folderId: null } }),
308 + ]);
309 +
310 + for (const f of folders) {
311 + items.push({
312 + href: `/dav/${encodeURIComponent(f.name)}/`,
313 + name: f.name,
314 + isDir: true,
315 + modifiedAt: f.createdAt,
316 + createdAt: f.createdAt,
317 + });
318 + }
319 + for (const f of files) {
320 + items.push({
321 + href: `/dav/${encodeURIComponent(f.name)}`,
322 + name: f.name,
323 + isDir: false,
324 + size: f.size,
325 + mimeType: f.mimeType,
326 + modifiedAt: f.updatedAt,
327 + createdAt: f.createdAt,
328 + });
329 + }
330 +
331 + return items;
332 +}
333 +
334 +async function buildSharedSpacesListItems(userId: string, depth: string): Promise<PropItem[]> {
335 + const now = new Date();
336 + const items: PropItem[] = [
337 + {
338 + href: `/dav/${encodeURIComponent(SHARED_PREFIX)}/`,
339 + name: SHARED_PREFIX,
340 + isDir: true,
341 + modifiedAt: now,
342 + createdAt: now,
343 + },
344 + ];
345 +
346 + if (depth === "0") return items;
347 +
348 + const memberships = await prisma.sharedSpaceMember.findMany({
349 + where: { userId },
350 + include: { sharedSpace: true },
351 + });
352 +
353 + for (const m of memberships) {
354 + items.push({
355 + href: `/dav/${encodeURIComponent(SHARED_PREFIX)}/${encodeURIComponent(m.sharedSpace.name)}/`,
356 + name: m.sharedSpace.name,
357 + isDir: true,
358 + modifiedAt: m.sharedSpace.updatedAt,
359 + createdAt: m.sharedSpace.createdAt,
360 + });
361 + }
362 +
363 + return items;
364 +}
365 +
366 +async function buildSharedSpaceRootItems(
367 + userId: string,
368 + spaceName: string,
369 + depth: string
370 +): Promise<PropItem[]> {
371 + const space = await findSharedSpace(userId, spaceName);
372 + if (!space) throw notFoundError();
373 +
374 + const now = space.updatedAt;
375 + const items: PropItem[] = [
376 + {
377 + href: `/dav/${encodeURIComponent(SHARED_PREFIX)}/${encodeURIComponent(spaceName)}/`,
378 + name: spaceName,
379 + isDir: true,
380 + modifiedAt: now,
381 + createdAt: space.createdAt,
382 + },
383 + ];
384 +
385 + if (depth === "0") return items;
386 +
387 + // Root-level folders of the space (parentId null + sharedSpaceId = spaceId)
388 + const rootFolders = await prisma.folder.findMany({
389 + where: { sharedSpaceId: space.id, parentId: null },
390 + });
391 +
392 + for (const f of rootFolders) {
393 + items.push({
394 + href: sharedSpaceHref(spaceName, [f.name]),
395 + name: f.name,
396 + isDir: true,
397 + modifiedAt: f.createdAt,
398 + createdAt: f.createdAt,
399 + });
400 + }
401 +
402 + // Files directly in the space root (folderId null, but linked via space through folder —
403 + // the schema has no direct space-to-file link, so no root files possible)
404 +
405 + return items;
406 +}
407 +
408 +async function buildSharedFolderItems(
409 + userId: string,
410 + spaceName: string,
411 + folderParts: string[],
412 + depth: string
413 +): Promise<PropItem[]> {
414 + const space = await findSharedSpace(userId, spaceName);
415 + if (!space) throw notFoundError();
416 +
417 + const folderId = await resolveSharedFolder(space.id, folderParts);
418 + if (folderId === null && folderParts.length > 0) throw notFoundError();
419 +
420 + const folderRecord = folderId
421 + ? await prisma.folder.findFirst({ where: { id: folderId } })
422 + : null;
423 +
424 + const folderHref = sharedSpaceHref(spaceName, folderParts);
425 + const items: PropItem[] = [
426 + {
427 + href: folderHref,
428 + name: folderRecord?.name ?? spaceName,
429 + isDir: true,
430 + modifiedAt: folderRecord?.createdAt ?? new Date(),
431 + createdAt: folderRecord?.createdAt ?? new Date(),
432 + },
433 + ];
434 +
435 + if (depth === "0") return items;
436 +
437 + const [subFolders, files] = await Promise.all([
438 + prisma.folder.findMany({ where: { sharedSpaceId: space.id, parentId: folderId } }),
439 + prisma.file.findMany({ where: { folderId: folderId! } }),
440 + ]);
441 +
442 + for (const sf of subFolders) {
443 + items.push({
444 + href: sharedSpaceHref(spaceName, [...folderParts, sf.name]),
445 + name: sf.name,
446 + isDir: true,
447 + modifiedAt: sf.createdAt,
448 + createdAt: sf.createdAt,
449 + });
450 + }
451 + for (const f of files) {
452 + items.push({
453 + href: sharedSpaceHref(spaceName, folderParts, f.name),
454 + name: f.name,
455 + isDir: false,
456 + size: f.size,
457 + mimeType: f.mimeType,
458 + modifiedAt: f.updatedAt,
459 + createdAt: f.createdAt,
460 + });
461 + }
462 +
463 + return items;
464 +}
465 +
466 +// ---------------------------------------------------------------------------
467 +// Method handlers
468 +// ---------------------------------------------------------------------------
469 +
470 +async function handlePropfind(
471 + req: IncomingMessage,
472 + res: ServerResponse,
473 + user: DavUser,
474 + davPath: string
475 +): Promise<void> {
476 + const depth = (req.headers["depth"] || "1") as string;
477 + const ctx = parseDavPath(davPath);
478 + let items: PropItem[] = [];
479 +
480 + try {
481 + switch (ctx.kind) {
482 + case "personal-root":
483 + items = await buildPersonalRootItems(user.id, depth);
484 + break;
485 +
486 + case "shared-spaces-list":
487 + items = await buildSharedSpacesListItems(user.id, depth);
488 + break;
489 +
490 + case "shared-space-root":
491 + items = await buildSharedSpaceRootItems(user.id, ctx.spaceName, depth);
492 + break;
493 +
494 + case "shared-content": {
495 + if (ctx.filename && !ctx.isDir) {
496 + // Single file propfind inside a shared space
497 + const space = await findSharedSpace(user.id, ctx.spaceName);
498 + if (!space) { res.writeHead(404); res.end("Not Found"); return; }
499 + const folderId = await resolveSharedFolder(space.id, ctx.folderParts);
500 + if (folderId === null) { res.writeHead(404); res.end("Not Found"); return; }
501 + const file = await prisma.file.findFirst({
502 + where: { folderId, name: ctx.filename },
503 + });
504 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
505 + items = [{
506 + href: sharedSpaceHref(ctx.spaceName, ctx.folderParts, ctx.filename),
507 + name: file.name,
508 + isDir: false,
509 + size: file.size,
510 + mimeType: file.mimeType,
511 + modifiedAt: file.updatedAt,
512 + createdAt: file.createdAt,
513 + }];
514 + } else {
515 + items = await buildSharedFolderItems(user.id, ctx.spaceName, ctx.folderParts, depth);
516 + }
517 + break;
518 + }
519 +
520 + case "personal": {
521 + if (ctx.filename && !ctx.isDir) {
522 + // Single file propfind
523 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
524 + const file = await prisma.file.findFirst({
525 + where: { userId: user.id, folderId, name: ctx.filename },
526 + });
527 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
528 + items = [{
529 + href: personalHref(ctx.folderParts, ctx.filename),
530 + name: file.name,
531 + isDir: false,
532 + size: file.size,
533 + mimeType: file.mimeType,
534 + modifiedAt: file.updatedAt,
535 + createdAt: file.createdAt,
536 + }];
537 + } else {
538 + // Folder propfind
539 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
540 + const folder = folderId
541 + ? await prisma.folder.findFirst({ where: { id: folderId, userId: user.id } })
542 + : null;
543 +
544 + const folderHref = ctx.folderParts.length === 0
545 + ? "/dav/"
546 + : personalHref(ctx.folderParts);
547 +
548 + items = [{
549 + href: folderHref,
550 + name: folder?.name ?? "Root",
551 + isDir: true,
552 + modifiedAt: folder?.createdAt ?? new Date(),
553 + createdAt: folder?.createdAt ?? new Date(),
554 + }];
555 +
556 + if (depth !== "0") {
557 + const [subFolders, files] = await Promise.all([
558 + prisma.folder.findMany({ where: { userId: user.id, parentId: folderId } }),
559 + prisma.file.findMany({ where: { userId: user.id, folderId } }),
560 + ]);
561 + for (const sf of subFolders) {
562 + items.push({
563 + href: personalHref([...ctx.folderParts, sf.name]),
564 + name: sf.name,
565 + isDir: true,
566 + modifiedAt: sf.createdAt,
567 + createdAt: sf.createdAt,
568 + });
569 + }
570 + for (const f of files) {
571 + items.push({
572 + href: personalHref(ctx.folderParts, f.name),
573 + name: f.name,
574 + isDir: false,
575 + size: f.size,
576 + mimeType: f.mimeType,
577 + modifiedAt: f.updatedAt,
578 + createdAt: f.createdAt,
579 + });
580 + }
581 + }
582 + }
583 + break;
584 + }
585 + }
586 + } catch (err: unknown) {
587 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
588 + res.writeHead(404);
589 + res.end("Not Found");
590 + return;
591 + }
592 + throw err;
593 + }
594 +
595 + res.writeHead(207, { "Content-Type": "application/xml; charset=utf-8" });
596 + res.end(buildMultistatusXml(items));
597 +}
598 +
599 +async function handleGet(
600 + req: IncomingMessage,
601 + res: ServerResponse,
602 + user: DavUser,
603 + davPath: string,
604 + headOnly: boolean
605 +): Promise<void> {
606 + const ctx = parseDavPath(davPath);
607 +
608 + // Virtual directories → simple response
609 + if (
610 + ctx.kind === "personal-root" ||
611 + ctx.kind === "shared-spaces-list" ||
612 + ctx.kind === "shared-space-root" ||
613 + (ctx.kind === "personal" && ctx.isDir) ||
614 + (ctx.kind === "shared-content" && ctx.isDir)
615 + ) {
616 + res.writeHead(200, { "Content-Type": "text/html" });
617 + res.end("<html><body>Collection</body></html>");
618 + return;
619 + }
620 +
621 + try {
622 + let file;
623 + if (ctx.kind === "personal" && ctx.filename) {
624 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
625 + file = await prisma.file.findFirst({
626 + where: { userId: user.id, folderId, name: ctx.filename },
627 + });
628 + } else if (ctx.kind === "shared-content" && ctx.filename) {
629 + const space = await findSharedSpace(user.id, ctx.spaceName);
630 + if (!space) { res.writeHead(404); res.end("Not Found"); return; }
631 + const folderId = await resolveSharedFolder(space.id, ctx.folderParts);
632 + if (folderId === null) { res.writeHead(404); res.end("Not Found"); return; }
633 + file = await prisma.file.findFirst({ where: { folderId, name: ctx.filename } });
634 + }
635 +
636 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
637 +
638 + const filePath = getFilePath(file.storagePath);
639 + if (!existsSync(filePath)) { res.writeHead(404); res.end("Not Found"); return; }
640 +
641 + const stats = statSync(filePath);
642 + res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
643 + res.setHeader("Content-Length", stats.size);
644 + res.setHeader("Last-Modified", file.updatedAt.toUTCString());
645 + res.setHeader("ETag", `"${file.id}"`);
646 + res.writeHead(200);
647 +
648 + if (headOnly) {
649 + res.end();
650 + } else {
651 + getFileStream(file.storagePath).pipe(res);
652 + }
653 + } catch (err: unknown) {
654 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
655 + res.writeHead(404);
656 + res.end("Not Found");
657 + return;
658 + }
659 + throw err;
660 + }
661 +}
662 +
663 +async function handlePut(
664 + req: IncomingMessage,
665 + res: ServerResponse,
666 + user: DavUser,
667 + davPath: string
668 +): Promise<void> {
669 + const ctx = parseDavPath(davPath);
670 +
671 + const filename =
672 + ctx.kind === "personal"
673 + ? ctx.filename
674 + : ctx.kind === "shared-content"
675 + ? ctx.filename
676 + : null;
677 +
678 + if (!filename) {
679 + res.writeHead(400);
680 + res.end("Bad Request");
681 + return;
682 + }
683 +
684 + // Discard macOS metadata noise
685 + if (filename.startsWith("._") || filename === ".DS_Store" || filename === ".localized") {
686 + await readBody(req);
687 + res.writeHead(204);
688 + res.end();
689 + return;
690 + }
691 +
692 + const body = await readBody(req);
693 + const mimeType =
694 + (mimeTypeLookup(filename) as string | false) || "application/octet-stream";
695 +
696 + try {
697 + if (ctx.kind === "personal") {
698 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
699 + const existing = await prisma.file.findFirst({
700 + where: { userId: user.id, folderId, name: filename },
701 + });
702 + if (existing) {
703 + const { storagePath, size } = await saveFile(body, filename);
704 + const old = existing.storagePath;
705 + await prisma.file.update({
706 + where: { id: existing.id },
707 + data: { storagePath, size: BigInt(size), updatedAt: new Date() },
708 + });
709 + await deleteFile(old);
710 + await logActivity("UPLOAD", existing.id, `WebDAV update: ${filename}`);
711 + res.writeHead(204);
712 + } else {
713 + const { storagePath, size } = await saveFile(body, filename);
714 + const f = await prisma.file.create({
715 + data: { name: filename, storagePath, size: BigInt(size), mimeType, folderId, userId: user.id },
716 + });
717 + await logActivity("UPLOAD", f.id, `WebDAV upload: ${filename}`);
718 + res.writeHead(201);
719 + }
720 + res.end();
721 + return;
722 + }
723 +
724 + if (ctx.kind === "shared-content") {
725 + const space = await findSharedSpace(user.id, ctx.spaceName);
726 + if (!space) { res.writeHead(403); res.end("Forbidden: not a member"); return; }
727 +
728 + if (ctx.folderParts.length === 0) {
729 + // Can't put files directly at space root (no sharedSpaceId on File)
730 + res.writeHead(409);
731 + res.end("Conflict: create a folder first, then upload files into it");
732 + return;
733 + }
734 +
735 + const folderId = await resolveSharedFolder(space.id, ctx.folderParts);
736 + if (folderId === null) { res.writeHead(404); res.end("Parent folder not found"); return; }
737 +
738 + const existing = await prisma.file.findFirst({ where: { folderId, name: filename } });
739 + if (existing) {
740 + const { storagePath, size } = await saveFile(body, filename);
741 + const old = existing.storagePath;
742 + await prisma.file.update({
743 + where: { id: existing.id },
744 + data: { storagePath, size: BigInt(size), updatedAt: new Date() },
745 + });
746 + await deleteFile(old);
747 + await logActivity("UPLOAD", existing.id, `WebDAV shared update: ${filename}`);
748 + res.writeHead(204);
749 + } else {
750 + const { storagePath, size } = await saveFile(body, filename);
751 + const f = await prisma.file.create({
752 + data: { name: filename, storagePath, size: BigInt(size), mimeType, folderId, userId: user.id },
753 + });
754 + await logActivity("UPLOAD", f.id, `WebDAV shared upload: ${filename} in ${ctx.spaceName}`);
755 + res.writeHead(201);
756 + }
757 + res.end();
758 + return;
759 + }
760 +
761 + res.writeHead(400);
762 + res.end("Bad Request");
763 + } catch (err: unknown) {
764 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
765 + res.writeHead(409);
766 + res.end("Conflict: parent folder not found");
767 + return;
768 + }
769 + throw err;
770 + }
771 +}
772 +
773 +async function handleDelete(
774 + req: IncomingMessage,
775 + res: ServerResponse,
776 + user: DavUser,
777 + davPath: string
778 +): Promise<void> {
779 + const ctx = parseDavPath(davPath);
780 +
781 + // Protect virtual roots
782 + if (
783 + ctx.kind === "personal-root" ||
784 + ctx.kind === "shared-spaces-list" ||
785 + ctx.kind === "shared-space-root"
786 + ) {
787 + res.writeHead(403);
788 + res.end("Forbidden");
789 + return;
790 + }
791 +
792 + try {
793 + if (ctx.kind === "personal") {
794 + if (!ctx.filename || ctx.isDir) {
795 + // Delete folder
796 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
797 + if (!folderId) { res.writeHead(403); res.end("Cannot delete root"); return; }
798 + const files = await prisma.file.findMany({ where: { folderId } });
799 + await Promise.all(files.map((f) => deleteFile(f.storagePath)));
800 + await prisma.folder.delete({ where: { id: folderId } });
801 + await logActivity("DELETE", undefined, `WebDAV delete folder: ${ctx.folderParts.join("/")}`);
802 + } else {
803 + const folderId = await resolvePersonalFolder(user.id, ctx.folderParts);
804 + const file = await prisma.file.findFirst({
805 + where: { userId: user.id, folderId, name: ctx.filename },
806 + });
807 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
808 + await deleteFile(file.storagePath);
809 + await prisma.file.delete({ where: { id: file.id } });
810 + await logActivity("DELETE", file.id, `WebDAV delete: ${ctx.filename}`);
811 + }
812 + }
813 +
814 + if (ctx.kind === "shared-content") {
815 + const space = await findSharedSpace(user.id, ctx.spaceName);
816 + if (!space) { res.writeHead(403); res.end("Forbidden"); return; }
817 +
818 + if (!ctx.filename || ctx.isDir) {
819 + const folderId = await resolveSharedFolder(space.id, ctx.folderParts);
820 + if (!folderId) { res.writeHead(403); res.end("Cannot delete space root"); return; }
821 + const files = await prisma.file.findMany({ where: { folderId } });
822 + await Promise.all(files.map((f) => deleteFile(f.storagePath)));
823 + await prisma.folder.delete({ where: { id: folderId } });
824 + await logActivity("DELETE", undefined, `WebDAV delete shared folder: ${ctx.folderParts.join("/")} in ${ctx.spaceName}`);
825 + } else {
826 + const folderId = await resolveSharedFolder(space.id, ctx.folderParts);
827 + if (folderId === null) { res.writeHead(404); res.end("Not Found"); return; }
828 + const file = await prisma.file.findFirst({ where: { folderId, name: ctx.filename } });
829 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
830 + await deleteFile(file.storagePath);
831 + await prisma.file.delete({ where: { id: file.id } });
832 + await logActivity("DELETE", file.id, `WebDAV shared delete: ${ctx.filename} in ${ctx.spaceName}`);
833 + }
834 + }
835 +
836 + res.writeHead(204);
837 + res.end();
838 + } catch (err: unknown) {
839 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
840 + res.writeHead(404);
841 + res.end("Not Found");
842 + return;
843 + }
844 + throw err;
845 + }
846 +}
847 +
848 +async function handleMkcol(
849 + req: IncomingMessage,
850 + res: ServerResponse,
851 + user: DavUser,
852 + davPath: string
853 +): Promise<void> {
854 + // Use raw parts directly — parseDavPath has path ambiguity for MKCOL
855 + // since MKCOL paths never have a trailing slash yet refer to a directory.
856 + const rawParts = davPath.split("/").filter(Boolean);
857 +
858 + if (rawParts.length === 0) {
859 + res.writeHead(405);
860 + res.end("Cannot create root");
861 + return;
862 + }
863 +
864 + // Protect virtual roots
865 + if (rawParts.length === 1 && rawParts[0] === SHARED_PREFIX) {
866 + res.writeHead(403);
867 + res.end("Forbidden");
868 + return;
869 + }
870 +
871 + try {
872 + if (rawParts[0] === SHARED_PREFIX) {
873 + // Shared space MKCOL: /Shared Spaces/{spaceName}/{...folderPath}
874 + if (rawParts.length < 3) {
875 + res.writeHead(403);
876 + res.end("Forbidden: cannot create shared spaces via WebDAV");
877 + return;
878 + }
879 + const spaceName = rawParts[1];
880 + const space = await findSharedSpace(user.id, spaceName);
881 + if (!space) { res.writeHead(403); res.end("Forbidden: not a member"); return; }
882 +
883 + const pathInSpace = rawParts.slice(2); // e.g. ["Documents"] or ["Documents", "SubFolder"]
884 + const folderName = pathInSpace[pathInSpace.length - 1];
885 + const parentParts = pathInSpace.slice(0, -1);
886 +
887 + const parentId = await resolveSharedFolder(space.id, parentParts);
888 + const existing = await prisma.folder.findFirst({
889 + where: { sharedSpaceId: space.id, parentId, name: folderName },
890 + });
891 + if (existing) { res.writeHead(405); res.end("Already exists"); return; }
892 +
893 + await prisma.folder.create({
894 + data: { name: folderName, parentId, userId: user.id, sharedSpaceId: space.id },
895 + });
896 + await logActivity("CREATE_FOLDER", undefined, `WebDAV shared mkdir: ${folderName} in ${spaceName}`);
897 + res.writeHead(201);
898 + res.end();
899 + return;
900 + }
901 +
902 + // Personal MKCOL: /{...folderPath}
903 + const folderName = rawParts[rawParts.length - 1];
904 + const parentParts = rawParts.slice(0, -1);
905 + const parentId = await resolvePersonalFolder(user.id, parentParts);
906 +
907 + const existing = await prisma.folder.findFirst({
908 + where: { userId: user.id, parentId, name: folderName },
909 + });
910 + if (existing) { res.writeHead(405); res.end("Already exists"); return; }
911 +
912 + await prisma.folder.create({ data: { name: folderName, parentId, userId: user.id } });
913 + await logActivity("CREATE_FOLDER", undefined, `WebDAV mkdir: ${folderName}`);
914 + res.writeHead(201);
915 + res.end();
916 + } catch (err: unknown) {
917 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
918 + res.writeHead(409);
919 + res.end("Conflict: parent not found");
920 + return;
921 + }
922 + throw err;
923 + }
924 +}
925 +
926 +async function handleMove(
927 + req: IncomingMessage,
928 + res: ServerResponse,
929 + user: DavUser,
930 + davPath: string
931 +): Promise<void> {
932 + const destination = req.headers["destination"] as string;
933 + if (!destination) { res.writeHead(400); res.end("Bad Request"); return; }
934 +
935 + const destPath = decodePath(extractDestPath(destination));
936 + const src = parseDavPath(davPath);
937 + const dst = parseDavPath(destPath);
938 +
939 + // Only support moves within the same zone (personal→personal or shared→shared same space)
940 + if (src.kind === "personal-root" || src.kind === "shared-spaces-list" || src.kind === "shared-space-root") {
941 + res.writeHead(403);
942 + res.end("Forbidden");
943 + return;
944 + }
945 +
946 + try {
947 + if (src.kind === "personal" && dst.kind === "personal") {
948 + if (src.filename && !src.isDir) {
949 + const srcFolderId = await resolvePersonalFolder(user.id, src.folderParts);
950 + const file = await prisma.file.findFirst({
951 + where: { userId: user.id, folderId: srcFolderId, name: src.filename },
952 + });
953 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
954 + const destFolderId = await resolvePersonalFolder(user.id, dst.folderParts);
955 + await prisma.file.update({
956 + where: { id: file.id },
957 + data: { name: dst.filename || src.filename, folderId: destFolderId },
958 + });
959 + await logActivity("MOVE", file.id, `WebDAV move: ${src.filename} → ${dst.filename}`);
960 + } else {
961 + const folderId = await resolvePersonalFolder(user.id, src.folderParts);
962 + if (!folderId) { res.writeHead(403); res.end("Cannot move root"); return; }
963 + const newName =
964 + dst.kind === "personal" && dst.folderParts.length > 0
965 + ? dst.folderParts[dst.folderParts.length - 1]
966 + : src.folderParts[src.folderParts.length - 1];
967 + const newParentParts = dst.kind === "personal" ? dst.folderParts.slice(0, -1) : [];
968 + const newParentId =
969 + newParentParts.length > 0 ? await resolvePersonalFolder(user.id, newParentParts) : null;
970 + await prisma.folder.update({ where: { id: folderId }, data: { name: newName, parentId: newParentId } });
971 + await logActivity("MOVE", undefined, `WebDAV move folder: ${src.folderParts.join("/")} → ${newName}`);
972 + }
973 + res.writeHead(204);
974 + res.end();
975 + return;
976 + }
977 +
978 + if (
979 + src.kind === "shared-content" &&
980 + dst.kind === "shared-content" &&
981 + src.spaceName === dst.spaceName
982 + ) {
983 + const space = await findSharedSpace(user.id, src.spaceName);
984 + if (!space) { res.writeHead(403); res.end("Forbidden"); return; }
985 +
986 + if (src.filename && !src.isDir) {
987 + const srcFolderId = await resolveSharedFolder(space.id, src.folderParts);
988 + if (srcFolderId === null) { res.writeHead(404); res.end("Not Found"); return; }
989 + const file = await prisma.file.findFirst({ where: { folderId: srcFolderId, name: src.filename } });
990 + if (!file) { res.writeHead(404); res.end("Not Found"); return; }
991 + const destFolderId = await resolveSharedFolder(space.id, dst.folderParts);
992 + if (destFolderId === null) { res.writeHead(404); res.end("Not Found"); return; }
993 + await prisma.file.update({
994 + where: { id: file.id },
995 + data: { name: dst.filename || src.filename, folderId: destFolderId },
996 + });
997 + await logActivity("MOVE", file.id, `WebDAV shared move: ${src.filename} → ${dst.filename}`);
998 + } else {
999 + const folderId = await resolveSharedFolder(space.id, src.folderParts);
1000 + if (!folderId) { res.writeHead(403); res.end("Cannot move space root"); return; }
1001 + const newName = dst.folderParts[dst.folderParts.length - 1] ?? src.folderParts[src.folderParts.length - 1];
1002 + const newParentParts = dst.folderParts.slice(0, -1);
1003 + const newParentId =
1004 + newParentParts.length > 0 ? await resolveSharedFolder(space.id, newParentParts) : null;
1005 + await prisma.folder.update({ where: { id: folderId }, data: { name: newName, parentId: newParentId } });
1006 + await logActivity("MOVE", undefined, `WebDAV shared move folder in ${src.spaceName}`);
1007 + }
1008 + res.writeHead(204);
1009 + res.end();
1010 + return;
1011 + }
1012 +
1013 + // Cross-zone moves not supported
1014 + res.writeHead(403);
1015 + res.end("Forbidden: cannot move across zones (personal ↔ shared)");
1016 + } catch (err: unknown) {
1017 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
1018 + res.writeHead(404);
1019 + res.end("Not Found");
1020 + return;
1021 + }
1022 + throw err;
1023 + }
1024 +}
1025 +
1026 +async function handleCopy(
1027 + req: IncomingMessage,
1028 + res: ServerResponse,
1029 + user: DavUser,
1030 + davPath: string
1031 +): Promise<void> {
1032 + const destination = req.headers["destination"] as string;
1033 + if (!destination) { res.writeHead(400); res.end("Bad Request"); return; }
1034 +
1035 + const destPath = decodePath(extractDestPath(destination));
1036 + const src = parseDavPath(davPath);
1037 + const dst = parseDavPath(destPath);
1038 +
1039 + const srcFilename = src.kind === "personal" || src.kind === "shared-content" ? src.filename : null;
1040 + if (!srcFilename) { res.writeHead(400); res.end("Cannot copy a directory"); return; }
1041 +
1042 + try {
1043 + let srcFile;
1044 + if (src.kind === "personal") {
1045 + const folderId = await resolvePersonalFolder(user.id, src.folderParts);
1046 + srcFile = await prisma.file.findFirst({ where: { userId: user.id, folderId, name: srcFilename } });
1047 + } else if (src.kind === "shared-content") {
1048 + const space = await findSharedSpace(user.id, src.spaceName);
1049 + if (!space) { res.writeHead(403); res.end("Forbidden"); return; }
1050 + const folderId = await resolveSharedFolder(space.id, src.folderParts);
1051 + if (folderId === null) { res.writeHead(404); res.end("Not Found"); return; }
1052 + srcFile = await prisma.file.findFirst({ where: { folderId, name: srcFilename } });
1053 + }
1054 +
1055 + if (!srcFile) { res.writeHead(404); res.end("Not Found"); return; }
1056 +
1057 + const destFilename =
1058 + dst.kind === "personal" || dst.kind === "shared-content"
1059 + ? dst.filename || srcFilename
1060 + : srcFilename;
1061 +
1062 + const { storagePath, size } = await duplicateFile(srcFile.storagePath, destFilename);
1063 +
1064 + let destFolderId: string | null = null;
1065 + if (dst.kind === "personal") {
1066 + destFolderId = await resolvePersonalFolder(user.id, dst.folderParts);
1067 + await prisma.file.create({
1068 + data: { name: destFilename, storagePath, size: BigInt(size), mimeType: srcFile.mimeType, folderId: destFolderId, userId: user.id },
1069 + });
1070 + } else if (dst.kind === "shared-content") {
1071 + const space = await findSharedSpace(user.id, dst.spaceName);
1072 + if (!space) { res.writeHead(403); res.end("Forbidden"); return; }
1073 + destFolderId = await resolveSharedFolder(space.id, dst.folderParts);
1074 + if (destFolderId === null) { res.writeHead(404); res.end("Destination folder not found"); return; }
1075 + await prisma.file.create({
1076 + data: { name: destFilename, storagePath, size: BigInt(size), mimeType: srcFile.mimeType, folderId: destFolderId, userId: user.id },
1077 + });
1078 + }
1079 +
1080 + res.writeHead(201);
1081 + res.end();
1082 + } catch (err: unknown) {
1083 + if ((err as NodeJS.ErrnoException).code === "NOT_FOUND") {
1084 + res.writeHead(404);
1085 + res.end("Not Found");
1086 + return;
1087 + }
1088 + throw err;
1089 + }
1090 +}
1091 +
1092 +async function handleLock(
1093 + req: IncomingMessage,
1094 + res: ServerResponse,
1095 + user: DavUser,
1096 + davPath: string
1097 +): Promise<void> {
1098 + const token = `opaquelocktoken:${randomUUID()}`;
1099 + locks.set(davPath, token);
1100 + res.setHeader("Lock-Token", `<${token}>`);
1101 + res.writeHead(200, { "Content-Type": "application/xml; charset=utf-8" });
1102 + res.end(buildLockXml(token, davPath, user.username));
1103 +}
1104 +
1105 +// ---------------------------------------------------------------------------
1106 +// Main dispatcher
1107 +// ---------------------------------------------------------------------------
1108 +
1109 +export async function handleWebDAV(
1110 + req: IncomingMessage,
1111 + res: ServerResponse
1112 +): Promise<void> {
1113 + const user = await authenticate(req);
1114 + if (!user) {
1115 + res.setHeader("WWW-Authenticate", 'Basic realm="SPB Cloud"');
1116 + res.writeHead(401, { "Content-Type": "text/plain" });
1117 + res.end("Unauthorized");
1118 + return;
1119 + }
1120 +
1121 + const method = req.method?.toUpperCase() || "GET";
1122 + const davPath = getDavPath(req);
1123 +
1124 + res.setHeader("DAV", "1, 2");
1125 + res.setHeader("MS-Author-Via", "DAV");
1126 + res.setHeader(
1127 + "Allow",
1128 + "OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, COPY, MOVE, PROPFIND, PROPPATCH, LOCK, UNLOCK"
1129 + );
1130 +
1131 + try {
1132 + switch (method) {
1133 + case "OPTIONS":
1134 + res.writeHead(200);
1135 + res.end();
1136 + break;
1137 + case "PROPFIND":
1138 + await handlePropfind(req, res, user, davPath);
1139 + break;
1140 + case "PROPPATCH":
1141 + res.writeHead(207, { "Content-Type": "application/xml; charset=utf-8" });
1142 + res.end(
1143 + `<?xml version="1.0"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${escapeXml("/dav" + davPath)}</D:href><D:propstat><D:prop/><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response></D:multistatus>`
1144 + );
1145 + break;
1146 + case "GET":
1147 + await handleGet(req, res, user, davPath, false);
1148 + break;
1149 + case "HEAD":
1150 + await handleGet(req, res, user, davPath, true);
1151 + break;
1152 + case "PUT":
1153 + await handlePut(req, res, user, davPath);
1154 + break;
1155 + case "DELETE":
1156 + await handleDelete(req, res, user, davPath);
1157 + break;
1158 + case "MKCOL":
1159 + await handleMkcol(req, res, user, davPath);
1160 + break;
1161 + case "MOVE":
1162 + await handleMove(req, res, user, davPath);
1163 + break;
1164 + case "COPY":
1165 + await handleCopy(req, res, user, davPath);
1166 + break;
1167 + case "LOCK":
1168 + await handleLock(req, res, user, davPath);
1169 + break;
1170 + case "UNLOCK":
1171 + res.writeHead(204);
1172 + res.end();
1173 + break;
1174 + default:
1175 + res.writeHead(405);
1176 + res.end("Method Not Allowed");
1177 + }
1178 + } catch (error) {
1179 + console.error("[WebDAV]", method, davPath, error);
1180 + if (!res.headersSent) {
1181 + res.writeHead(500);
1182 + res.end("Internal Server Error");
1183 + }
1184 + }
1185 +}
modified middleware.ts +162 −3
@@ -13,12 +13,118 @@ const publicPaths = [
13 13 "/favicon.ico",
14 14 ];
15 15
16 +// CSRF-exempt paths (public endpoints that accept POST without session)
17 +const csrfExemptPaths = [
18 + "/api/auth/login",
19 + "/api/shared/",
20 + "/api/v1/",
21 +];
22 +
23 +// --- Edge-compatible rate limiter ---
24 +const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
25 +const RATE_LIMIT_WINDOW_MS = 60_000; // 1 minute
26 +const RATE_LIMIT_MAX = 100; // 100 requests per minute per IP
27 +
28 +function cleanupRateLimitMap() {
29 + const now = Date.now();
30 + // Periodic cleanup: only run if map is large
31 + if (rateLimitMap.size > 5000) {
32 + const keysToDelete: string[] = [];
33 + rateLimitMap.forEach((entry, key) => {
34 + if (now > entry.resetAt) {
35 + keysToDelete.push(key);
36 + }
37 + });
38 + keysToDelete.forEach((key) => rateLimitMap.delete(key));
39 + }
40 +}
41 +
42 +function checkRateLimit(ip: string): boolean {
43 + const now = Date.now();
44 + const entry = rateLimitMap.get(ip);
45 +
46 + if (!entry || now > entry.resetAt) {
47 + rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
48 + return true;
49 + }
50 +
51 + entry.count++;
52 + if (entry.count > RATE_LIMIT_MAX) {
53 + return false;
54 + }
55 +
56 + return true;
57 +}
58 +
59 +function addSecurityHeaders(response: NextResponse): NextResponse {
60 + response.headers.set("X-Content-Type-Options", "nosniff");
61 + response.headers.set("X-Frame-Options", "SAMEORIGIN");
62 + response.headers.set("X-XSS-Protection", "1; mode=block");
63 + return response;
64 +}
65 +
66 +function getClientIp(request: NextRequest): string {
67 + return (
68 + request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
69 + request.headers.get("x-real-ip") ||
70 + "unknown"
71 + );
72 +}
73 +
74 +const ALLOWED_ORIGINS = (process.env.CORS_ORIGIN || "*")
75 + .split(",")
76 + .map((o) => o.trim())
77 + .filter(Boolean);
78 +
79 +function getAllowedOrigin(request: NextRequest): string {
80 + const requestOrigin = request.headers.get("origin") || "";
81 + if (ALLOWED_ORIGINS.includes("*")) return "*";
82 + if (ALLOWED_ORIGINS.includes(requestOrigin)) return requestOrigin;
83 + return ALLOWED_ORIGINS[0];
84 +}
85 +
86 +function setCorsHeaders(response: NextResponse, origin: string) {
87 + response.headers.set("Access-Control-Allow-Origin", origin);
88 + response.headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
89 + response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization, x-csrf-token");
90 + response.headers.set("Access-Control-Allow-Credentials", "true");
91 + response.headers.set("Vary", "Origin");
92 +}
93 +
16 94 export async function middleware(request: NextRequest) {
17 95 const { pathname } = request.nextUrl;
96 + const corsOrigin = getAllowedOrigin(request);
97 +
98 + // Handle CORS preflight requests
99 + if (request.method === "OPTIONS") {
100 + const preflightResponse = new NextResponse(null, { status: 204 });
101 + setCorsHeaders(preflightResponse, corsOrigin);
102 + preflightResponse.headers.set("Access-Control-Max-Age", "86400");
103 + return preflightResponse;
104 + }
18 105
19 106 // Allow public paths
20 107 if (publicPaths.some((path) => pathname.startsWith(path))) {
21 − return NextResponse.next();
108 + const response = NextResponse.next();
109 + if (pathname.startsWith("/api/")) setCorsHeaders(response, corsOrigin);
110 + addSecurityHeaders(response);
111 + return response;
112 + }
113 +
114 + // --- API rate limiting ---
115 + if (pathname.startsWith("/api/")) {
116 + const ip = getClientIp(request);
117 + cleanupRateLimitMap();
118 +
119 + if (!checkRateLimit(ip)) {
120 + const errorResponse = NextResponse.json(
121 + { error: "Trop de requetes. Reessayez dans une minute." },
122 + { status: 429 }
123 + );
124 + addSecurityHeaders(errorResponse);
125 + errorResponse.headers.set("Retry-After", "60");
126 + return errorResponse;
127 + }
22 128 }
23 129
24 130 // Check session
@@ -27,11 +133,64 @@ export async function middleware(request: NextRequest) {
27 133
28 134 if (!session.isLoggedIn) {
29 135 if (pathname.startsWith("/api/")) {
30 − return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
136 + const errorResponse = NextResponse.json({ error: "Unauthorized" }, { status: 401 });
137 + addSecurityHeaders(errorResponse);
138 + return errorResponse;
139 + }
140 + const redirectResponse = NextResponse.redirect(new URL("/login", request.url));
141 + addSecurityHeaders(redirectResponse);
142 + return redirectResponse;
143 + }
144 +
145 + // --- CSRF protection for non-GET API requests ---
146 + // SameSite=Lax cookies already protect against most CSRF attacks.
147 + // We validate the CSRF token when present, but don't block requests
148 + // that come from the same origin (checked via Referer/Origin header).
149 + if (
150 + pathname.startsWith("/api/") &&
151 + request.method !== "GET" &&
152 + !csrfExemptPaths.some((path) => pathname.startsWith(path))
153 + ) {
154 + const csrfHeader = request.headers.get("x-csrf-token");
155 + const origin = request.headers.get("origin") || "";
156 + const referer = request.headers.get("referer") || "";
157 + const host = request.headers.get("host") || "";
158 + const forwardedHost = request.headers.get("x-forwarded-host") || "";
159 + // Accept same-origin, proxy-forwarded origins (ngrok, Tailscale, custom domain)
160 + const isAllowedCorsOrigin = ALLOWED_ORIGINS.includes(origin);
161 + const isSameOrigin =
162 + !origin ||
163 + origin.includes(host) ||
164 + referer.includes(host) ||
165 + (forwardedHost && origin.includes(forwardedHost)) ||
166 + origin.includes(".ngrok") ||
167 + origin.includes("spboucher.ai") ||
168 + origin.includes("s-pb.ai") ||
169 + isAllowedCorsOrigin;
170 +
171 + // If CSRF token is present, validate it. Otherwise, rely on same-origin check.
172 + if (csrfHeader && csrfHeader !== session.csrfToken) {
173 + const errorResponse = NextResponse.json(
174 + { error: "Jeton CSRF invalide" },
175 + { status: 403 }
176 + );
177 + addSecurityHeaders(errorResponse);
178 + return errorResponse;
179 + }
180 +
181 + // Block requests from foreign origins without valid CSRF token
182 + if (!isSameOrigin && !csrfHeader) {
183 + const errorResponse = NextResponse.json(
184 + { error: "Requete cross-origin non autorisee" },
185 + { status: 403 }
186 + );
187 + addSecurityHeaders(errorResponse);
188 + return errorResponse;
31 189 }
32 − return NextResponse.redirect(new URL("/login", request.url));
33 190 }
34 191
192 + if (pathname.startsWith("/api/")) setCorsHeaders(response, corsOrigin);
193 + addSecurityHeaders(response);
35 194 return response;
36 195 }
37 196
modified next.config.mjs +18 −1
@@ -4,7 +4,19 @@ const nextConfig = {
4 4 serverComponentsExternalPackages: ["bcryptjs"],
5 5 },
6 6 async headers() {
7 + const corsOrigin = process.env.CORS_ORIGIN || "*";
8 + const primaryOrigin = corsOrigin.includes(",") ? corsOrigin.split(",")[0].trim() : corsOrigin;
7 9 return [
10 + {
11 + source: "/api/(.*)",
12 + headers: [
13 + { key: "Access-Control-Allow-Origin", value: primaryOrigin },
14 + { key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,PATCH,DELETE,OPTIONS" },
15 + { key: "Access-Control-Allow-Headers", value: "Content-Type, Authorization, x-csrf-token" },
16 + { key: "Access-Control-Allow-Credentials", value: "true" },
17 + { key: "Vary", value: "Origin" },
18 + ],
19 + },
8 20 {
9 21 source: "/(.*)",
10 22 headers: [
@@ -23,8 +35,13 @@ const nextConfig = {
23 35 ];
24 36 },
25 37 webpack: (config) => {
26 − // Avoid bundling pdfjs-dist worker
27 38 config.resolve.alias.canvas = false;
39 + config.module.rules.push({
40 + test: /pdf\.mjs$/,
41 + include: /node_modules[\\/]pdfjs-dist/,
42 + type: "javascript/auto",
43 + resolve: { fullySpecified: false },
44 + });
28 45 return config;
29 46 },
30 47 };
modified package.json +2 −2
@@ -3,9 +3,9 @@
3 3 "version": "1.0.0",
4 4 "private": true,
5 5 "scripts": {
6 − "dev": "tsx server.ts",
6 + "dev": "PORT=5001 tsx server.ts",
7 7 "build": "next build",
8 − "start": "NODE_ENV=production tsx server.ts",
8 + "start": "next build && PORT=5001 NODE_ENV=production tsx server.ts",
9 9 "lint": "next lint",
10 10 "db:generate": "prisma generate",
11 11 "db:push": "prisma db push",
added prisma/dev.db-shm +0 −0

Binary file not shown.

added prisma/dev.db-wal +0 −0

Binary file not shown.

added prisma/dev.db.bak-20260605 +0 −0

Binary file not shown.

modified prisma/schema.prisma +67 −0
@@ -14,6 +14,7 @@ model User {
14 14 username String? @unique
15 15 email String? @unique
16 16 name String?
17 + avatarPath String?
17 18 passwordHash String
18 19 role String @default("user") // admin, user, viewer
19 20 twoFactorSecret String?
@@ -29,6 +30,8 @@ model User {
29 30 activityLogs ActivityLog[]
30 31 sharedSpaces SharedSpaceMember[]
31 32 passwordEntries PasswordEntry[]
33 + comments Comment[]
34 + loginSessions LoginSession[]
32 35
33 36 @@index([email])
34 37 @@index([role])
@@ -53,6 +56,8 @@ model File {
53 56 aiTags String?
54 57 aiDescription String?
55 58 aiEmbedding String?
59 +
60 + deletedAt DateTime?
56 61 createdAt DateTime @default(now())
57 62 updatedAt DateTime @updatedAt
58 63 sharedLinks SharedLink[]
@@ -60,12 +65,14 @@ model File {
60 65 metadata FileMetadata?
61 66 tags FileTag[]
62 67 versions FileVersion[]
68 + comments Comment[]
63 69
64 70 @@index([folderId])
65 71 @@index([userId])
66 72 @@index([name])
67 73 @@index([mimeType])
68 74 @@index([createdAt])
75 + @@index([deletedAt])
69 76 }
70 77
71 78 model Folder {
@@ -235,6 +242,22 @@ model BackupLog {
235 242 completedAt DateTime?
236 243 }
237 244
245 +// ==================== SNAPSHOTS ====================
246 +
247 +model Snapshot {
248 + id String @id @default(cuid())
249 + label String // e.g. "Lundi 22 mars"
250 + snapshotDate String // YYYY-MM-DD — one snapshot per day
251 + path String // absolute directory path
252 + size BigInt @default(0)
253 + status String @default("pending") // pending, completed, failed
254 + error String?
255 + createdAt DateTime @default(now())
256 +
257 + @@unique([snapshotDate])
258 + @@index([snapshotDate])
259 +}
260 +
238 261 // ==================== SHARED SPACES ====================
239 262
240 263 // ==================== PASSWORD MANAGER ====================
@@ -281,3 +304,47 @@ model SharedSpaceMember {
281 304 @@index([sharedSpaceId])
282 305 @@index([userId])
283 306 }
307 +
308 +// ==================== LOGIN SESSIONS (device tracking) ====================
309 +
310 +model LoginSession {
311 + id String @id @default(cuid())
312 + userId String
313 + user User @relation(fields: [userId], references: [id], onDelete: Cascade)
314 + sessionToken String @unique @default(cuid())
315 + ip String
316 + userAgent String @default("")
317 + device String @default("Desktop") // Desktop, Mobile, Tablet
318 + browser String @default("Inconnu")
319 + os String @default("Inconnu")
320 + country String @default("")
321 + city String @default("")
322 + status String @default("active") // active, ended, refused_by_ai
323 + aiDecision String? // "allowed" | "refused"
324 + aiReason String? // AI explanation
325 + aiRiskLevel String? // "low" | "medium" | "high"
326 + createdAt DateTime @default(now())
327 + endedAt DateTime?
328 +
329 + @@index([userId])
330 + @@index([sessionToken])
331 + @@index([createdAt])
332 + @@index([status])
333 +}
334 +
335 +// ==================== COMMENTS ====================
336 +
337 +model Comment {
338 + id String @id @default(cuid())
339 + fileId String
340 + userId String
341 + content String
342 + file File @relation(fields: [fileId], references: [id], onDelete: Cascade)
343 + user User @relation(fields: [userId], references: [id], onDelete: Cascade)
344 + createdAt DateTime @default(now())
345 + updatedAt DateTime @updatedAt
346 +
347 + @@index([fileId])
348 + @@index([userId])
349 + @@index([createdAt])
350 +}
added public/pdf.min.mjs +28 −0
@@ -0,0 +1,28 @@
1 +/**
2 + * @licstart The following is the entire license notice for the
3 + * JavaScript code in this page
4 + *
5 + * Copyright 2024 Mozilla Foundation
6 + *
7 + * Licensed under the Apache License, Version 2.0 (the "License");
8 + * you may not use this file except in compliance with the License.
9 + * You may obtain a copy of the License at
10 + *
11 + * http://www.apache.org/licenses/LICENSE-2.0
12 + *
13 + * Unless required by applicable law or agreed to in writing, software
14 + * distributed under the License is distributed on an "AS IS" BASIS,
15 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 + * See the License for the specific language governing permissions and
17 + * limitations under the License.
18 + *
19 + * @licend The above is the entire license notice for the
20 + * JavaScript code in this page
21 + */
22 +/**
23 + * pdfjsVersion = 5.4.624
24 + * pdfjsBuild = 384c6208b
25 + */const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[.001,0,0,.001,0,0],i=1.35,n=1,s=2,r=4,a=16,o=32,l=64,h=128,d=256,c={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",p={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},g={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},m={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},f=1,b=2,w=0,y=1,A=2,v=3,x=3,E=4,C={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},S={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},T=1,_=2,M=3,D=4,P=5,k={ERRORS:0,WARNINGS:1,INFOS:5},I={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},F=0,R=1,B=2,L=3,O=4,N={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let U=k.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(U=t)}function getVerbosityLevel(){return U}function info(t){U>=k.INFOS&&console.info(`Info: ${t}`)}function warn(t){U>=k.WARNINGS&&console.warn(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function updateUrlHash(t,e,i=!1){const n=URL.parse(t);if(n){n.hash=e;return n.href}return i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function shadow(t,e,i,n=!1){Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1});return i}const H=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends H{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends H{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends H{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends H{constructor(t,e,i){super(t,"ResponseException");this.status=e;this.missing=i}}class FormatError extends H{constructor(t){super(t,"FormatError")}}class AbortException extends H{constructor(t){super(t,"AbortException")}}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}class util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return 1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return shadow(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const z=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class Util{static makeHexColor(t,e,i){return`#${z[t]}${z[e]}${z[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4];t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],d=t[i+e+1];t[i+e]=h*n+d*r+o;t[i+e+1]=h*s+d*a+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s;t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=t[0],d=t[1],c=t[2],u=t[3];let p=n*h+o,g=p,m=n*c+o,f=m,b=a*d+l,w=b,y=a*u+l,A=y;if(0!==s||0!==r){const t=s*h,e=s*c,i=r*d,n=r*u;p+=i;f+=i;m+=n;g+=n;b+=t;A+=t;y+=e;w+=e}i[0]=Math.min(i[0],p,m,g,f);i[1]=Math.min(i[1],b,y,w,A);i[2]=Math.max(i[2],p,m,g,f);i[3]=Math.max(i[3],b,y,w,A)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],r=t[3],a=i**2+n**2,o=i*s+n*r,l=s**2+r**2,h=(a+l)/2,d=Math.sqrt(h**2-(a*l-o**2));e[0]=Math.sqrt(h+d||1);e[1]=Math.sqrt(h-d||1)}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>r?null:[i,s,n,r]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t);i[1]=Math.min(i[1],e);i[2]=Math.max(i[2],t);i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i);s[1]=Math.min(s[1],e,n);s[2]=Math.max(s[2],t,i);s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,r,a,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*n,g=d*(d*(d*s+3*l*r)+3*c*a)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,r,a,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,r,a,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,r,a,o,(-h+p)/g,c);this.#t(t,e,i,n,s,r,a,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,n,s,r,a,o,l){l[0]=Math.min(l[0],t,a);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,a);l[3]=Math.max(l[3],e,o);this.#e(t,i,s,a,e,n,r,o,3*(3*(i-s)-t+a),6*(t-2*i+s),3*(i-t),l);this.#e(t,i,s,a,e,n,r,o,3*(3*(n-r)-e+o),6*(e-2*n+r),3*(n-e),l)}}let G=null,W=null;function normalizeUnicode(t){if(!G){G=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;W=new Map([["ſt","ſt"]])}return t.replaceAll(G,(t,e,i)=>e?e.normalize("NFKC"):W.get(i))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const r=Math.min(s+i,e),a=t.subarray(s,r);n.push(String.fromCharCode.apply(null,a))}return n.join("")}(t)}const V="pdfjs_internal_id_";function MathClamp(t,e,i){return Math.min(Math.max(t,e),i)}"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const n=t.name;if("#text"===n)i=t.value;else{if(!XfaText.shouldBuildText(n))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class XfaLayer{static setupStorage(t,e,i,n,s){const r=n.getValue(e,{value:null});switch(i.name){case"textarea":null!==r.value&&(t.textContent=r.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{null!==r.value&&t.setAttribute("value",r.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${n}`);for(const[e,i]of Object.entries(r))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&s.addLinkAttributes(t,r.href,r.newWindow);i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",r=document.createElement(n.name);n.attributes&&this.setAttributes({html:r,element:n,intent:s,linkService:i});const a="richText"!==s,o=t.div;o.append(r);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);r.append(t);a&&XfaText.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,r]];for(;h.length>0;){const[t,n,r]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);r.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);r.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:s,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);a&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const j="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0);s.responseType=e;s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(s.response);return}i(s.responseText)}};s.send(null)})}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=n;this.offsetX=s;this.offsetY=r;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(n%=360)<0&&(n+=360);switch(n){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+s;g=Math.abs(o-t[0])*i+r;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+s;g=Math.abs(l-t[1])*i+r;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const t=this.viewBox;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];Util.applyTransform(i,this.transform);return i}convertToViewportRectangle(t){const e=[t[0],t[1]];Util.applyTransform(e,this.transform);const i=[t[2],t[3]];Util.applyTransform(i,this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];Util.applyInverseTransform(i,this.transform);return i}}class RenderingCancelledException extends H{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t){[t]=t.split(/[#?]/,1);return t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if("string"!=typeof t)return e;if(isDataScheme(t)){warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const i=(t=>{try{return new URL(t)}catch{try{return new URL(decodeURIComponent(t))}catch{try{return new URL(t,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{return null}}}}})(t);if(!i)return e;const decode=t=>{try{let e=decodeURIComponent(t);if(e.includes("/")){e=e.split("/").at(-1);return e.test(/^\.pdf$/i)?e:t}return e}catch{return t}},n=/\.pdf$/i,s=i.pathname.split("/").at(-1);if(n.test(s))return decode(s);if(i.searchParams.size>0){const t=Array.from(i.searchParams.values()).reverse();for(const e of t)if(n.test(e))return decode(e);const e=Array.from(i.searchParams.keys()).reverse();for(const t of e)if(n.test(t))return decode(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return decode(t[0])}return e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}class PDFDateString{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){r+=h;a+=d}else if("+"===l){r-=h;a-=d}return new Date(Date.UTC(i,n,s,r,a,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,r=[0,0,parseInt(n),parseInt(s)];return new PageViewport({viewBox:r,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map(t=>parseInt(t));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform();return[e,i,n,s,r,a]}function getCurrentTransformInverse(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform().invertSelf();return[e,i,n,s,r,a]}function setLayerDimensions(t,e,i=!1,n=!0){if(e instanceof PageViewport){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:r}=t,a=util_FeatureTest.isCSSRoundSupported,o=`var(--total-scale-factor) * ${n}px`,l=`var(--total-scale-factor) * ${s}px`,h=a?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,d=a?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;if(i&&e.rotation%180!=0){r.width=d;r.height=h}else{r.width=h;r.height=d}}n&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let r=1/0,a=1/0,o=1/0;(i=OutputScale.capPixels(i,s))>0&&(r=Math.sqrt(i/(t*e)));if(-1!==n){a=n/t;o=n/e}const l=Math.min(r,a,o);if(this.sx>l||this.sy>l){this.sx=l;this.sy=l;return!0}return!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const $=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ColorScheme{static get isDarkMode(){return shadow(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class CSSConstants{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0";e.display="none";e.color="var(--comment-fg-color)";document.body.append(t);const{color:i}=window.getComputedStyle(t);t.remove();return shadow(this,"commentForegroundColor",getRGB(i))}}function applyOpacity(t,e,i,n){const s=255*(1-(n=Math.min(Math.max(n??1,0),1)));return[t=Math.round(t*n+s),e=Math.round(e*n+s),i=Math.round(i*n+s)]}function RGBToHSL(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,r=Math.max(i,n,s),a=Math.min(i,n,s),o=(r+a)/2;if(r===a)e[0]=e[1]=0;else{const t=r-a;e[1]=o<.5?t/(r+a):t/(2-r-a);switch(r){case i:e[0]=60*((n-s)/t+(n<s?6:0));break;case n:e[0]=60*((s-i)/t+2);break;case s:e[0]=60*((i-n)/t+4)}}e[2]=o}function HSLToRGB(t,e){const i=t[0],n=t[1],s=t[2],r=(1-Math.abs(2*s-1))*n,a=r*(1-Math.abs(i/60%2-1)),o=s-r/2;switch(Math.floor(i/60)){case 0:e[0]=r+o;e[1]=a+o;e[2]=o;break;case 1:e[0]=a+o;e[1]=r+o;e[2]=o;break;case 2:e[0]=o;e[1]=r+o;e[2]=a+o;break;case 3:e[0]=o;e[1]=a+o;e[2]=r+o;break;case 4:e[0]=a+o;e[1]=o;e[2]=r+o;break;case 5:case 6:e[0]=r+o;e[1]=o;e[2]=a+o}}function computeLuminance(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function contrastRatio(t,e,i){HSLToRGB(t,i);i.map(computeLuminance);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];HSLToRGB(e,i);i.map(computeLuminance);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];return n>s?(n+.05)/(s+.05):(s+.05)/(n+.05)}const X=new Map;function findContrastColor(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=X.get(i);if(n)return n;const s=new Float32Array(9),r=s.subarray(0,3),a=s.subarray(3,6);RGBToHSL(t,a);const o=s.subarray(6,9);RGBToHSL(e,o);const l=o[2]<.5,h=l?12:4.5;a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]);if(contrastRatio(a,o,r)<h){let t,e;if(l){t=a[2];e=1}else{t=0;e=a[2]}const i=.005;for(;e-t>i;){const i=a[2]=(t+e)/2;l===contrastRatio(a,o,r)<h?t=i:e=i}a[2]=l?e:t}HSLToRGB(a,r);n=Util.makeHexColor(Math.round(255*r[0]),Math.round(255*r[1]),Math.round(255*r[2]));X.set(i,n);return n}function renderRichText({html:t,dir:e,className:i},n){const s=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const n=t.split(/(?:\r\n?|\n)/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s));t<e-1&&i.append(document.createElement("br"))}s.append(i)}else XfaLayer.render({xfaHtml:t,div:s,intent:"richText"});s.firstElementChild.classList.add("richText",i);n.append(s)}function makePathFromDrawOPS(t){const e=new Path2D;if(!t)return e;for(let i=0,n=t.length;i<n;)switch(t[i++]){case F:e.moveTo(t[i++],t[i++]);break;case R:e.lineTo(t[i++],t[i++]);break;case B:e.bezierCurveTo(t[i++],t[i++],t[i++],t[i++],t[i++],t[i++]);break;case L:e.quadraticCurveTo(t[i++],t[i++],t[i++],t[i++]);break;case O:e.closePath();break;default:warn(`Unrecognized drawing path operator: ${t[i-1]}`)}return e}class PagesMapper{static#n=null;static#s=null;static#r=null;static#a=0;static#o=[];get pagesNumber(){return PagesMapper.#a}set pagesNumber(t){if(PagesMapper.#a!==t){PagesMapper.#a=t;if(0===t){PagesMapper.#s=null;PagesMapper.#n=null}}}addListener(t){PagesMapper.#o.push(t)}removeListener(t){const e=PagesMapper.#o.indexOf(t);e>=0&&PagesMapper.#o.splice(e,1)}#l(){for(const t of PagesMapper.#o)t()}#h(t){if(PagesMapper.#s)return;const e=PagesMapper.#a,i=new Uint32Array(3*e),n=PagesMapper.#s=i.subarray(0,e),s=PagesMapper.#n=i.subarray(e,2*e);if(t)for(let t=0;t<e;t++)n[t]=s[t]=t+1;PagesMapper.#r=i.subarray(2*e)}movePages(t,e,i){this.#h(!0);const n=PagesMapper.#s,s=PagesMapper.#n;PagesMapper.#r.set(s);const r=e.length,a=new Uint32Array(r);let o=0;for(let t=0;t<r;t++){const s=e[t]-1;a[t]=n[s];s<i&&(o+=1)}const l=PagesMapper.#a;let h=i-o;const d=l-r;h=MathClamp(h,0,d);for(let e=0,i=0;e<l;e++)t.has(e+1)||(n[i++]=n[e]);n.copyWithin(h+r,h,d);n.set(a,h);let c=!1;for(let t=0,e=l;t<e;t++){const e=n[t];c||=e!==t+1;s[e-1]=t+1}this.#l();c||(this.pagesNumber=0)}hasBeenAltered(){return null!==PagesMapper.#s}getPageMappingForSaving(){return{pageIndices:PagesMapper.#n?PagesMapper.#n.map(t=>t-1):null}}getPrevPageNumber(t){return PagesMapper.#r[PagesMapper.#s[t-1]-1]}getPageNumber(t){return PagesMapper.#n?.[t-1]??t}getPageId(t){return PagesMapper.#s?.[t-1]??t}static get instance(){return shadow(this,"instance",new PagesMapper)}getMapping(){return PagesMapper.#s.subarray(0,this.pagesNumber)}}class EditorToolbar{#d=null;#c=null;#u;#p=null;#g=null;#m=null;#f=null;#b=null;static#w=null;constructor(t){this.#u=t;EditorToolbar.#w||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#d=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#u._uiManager._signal;if(e instanceof AbortSignal&&!e.aborted){t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#y,{signal:e})}const i=this.#p=document.createElement("div");i.className="buttons";t.append(i);const n=this.#u.toolbarPosition;if(n){const{style:e}=t,i="ltr"===this.#u._uiManager.direction?1-n[0]:n[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*n[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#d}static#y(t){t.stopPropagation()}#A(t){this.#u._focusEventsAllowed=!1;stopEvent(t)}#v(t){this.#u._focusEventsAllowed=!0;stopEvent(t)}#x(t){const e=this.#u._uiManager._signal;if(!(e instanceof AbortSignal)||e.aborted)return!1;t.addEventListener("focusin",this.#A.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#v.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});return!0}hide(){this.#d.classList.add("hidden");this.#c?.hideDropdown()}show(){this.#d.classList.remove("hidden");this.#g?.shown();this.#m?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#u,i=document.createElement("button");i.classList.add("basic","deleteButton");i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#w[t]);this.#x(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal});this.#p.append(i)}get#E(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#x(e);this.#p.append(e,this.#E);this.#g=t}addComment(t,e=null){if(this.#m)return;const i=t.renderForToolbar();if(!i)return;this.#x(i);const n=this.#f=this.#E;if(e){this.#p.insertBefore(i,e);this.#p.insertBefore(n,e)}else this.#p.append(i,n);this.#m=t;t.toolbar=this}addColorPicker(t){if(this.#c)return;this.#c=t;const e=t.renderButton();this.#x(e);this.#p.append(e,this.#E)}async addEditSignatureButton(t){const e=this.#b=await t.renderEditButton(this.#u);this.#x(e);this.#p.append(e,this.#E)}removeButton(t){if("comment"===t){this.#m?.removeToolbarCommentButton();this.#m=null;this.#f?.remove();this.#f=null}}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;const n=this.#p.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#b&&(this.#b.title=t)}remove(){this.#d.remove();this.#c?.destroy();this.#c=null}}class FloatingToolbar{#p=null;#d=null;#C;constructor(t){this.#C=t}#S(){const t=this.#d=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");const e=this.#C._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#p=document.createElement("div");i.className="buttons";t.append(i);this.#C.hasCommentManager()&&this.#T("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#C.commentSelection("floating_button")});this.#T("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#C.highlightSelection("floating_button")});return t}#_(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const r=s.x+(e?s.width:0);if(t>i){n=r;i=t}else e?r>n&&(n=r):r<n&&(n=r)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#_(e,i),{style:r}=this.#d||=this.#S();t.append(this.#d);r.insetInlineEnd=100*n+"%";r.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#d.remove()}#T(t,e,i,n){const s=document.createElement("button");s.classList.add("basic",t);s.tabIndex=0;s.setAttribute("data-l10n-id",e);const r=document.createElement("span");s.append(r);r.className="visuallyHidden";r.setAttribute("data-l10n-id",i);const a=this.#C._signal;if(a instanceof AbortSignal&&!a.aborted){s.addEventListener("contextmenu",noContextMenu,{signal:a});s.addEventListener("click",n,{signal:a})}this.#p.append(s)}}function bindEvents(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class CurrentPointers{static#M=NaN;static#D=null;static#P=NaN;static#k=null;static initializeAndAddPointerId(t){(CurrentPointers.#D||=new Set).add(t)}static setPointer(t,e){CurrentPointers.#M||=e;CurrentPointers.#k??=t}static setTimeStamp(t){CurrentPointers.#P=t}static isSamePointerId(t){return CurrentPointers.#M===t}static isSamePointerIdOrRemove(t){if(CurrentPointers.#M===t)return!0;CurrentPointers.#D?.delete(t);return!1}static isSamePointerType(t){return CurrentPointers.#k===t}static isInitializedAndDifferentPointerType(t){return null!==CurrentPointers.#k&&!CurrentPointers.isSamePointerType(t)}static isSameTimeStamp(t){return CurrentPointers.#P===t}static isUsingMultiplePointers(){return CurrentPointers.#D?.size>=1}static clearPointerType(){CurrentPointers.#k=null}static clearPointerIds(){CurrentPointers.#M=NaN;CurrentPointers.#D=null}static clearTimeStamp(){CurrentPointers.#P=NaN}}class IdManager{#I=0;get id(){return`${u}${this.#I++}`}}class ImageManager{#F=getUuid();#I=0;#R=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return shadow(this,"_isSVGFittingCanvas",e.decode().then(()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]}))}async#B(t,e){this.#R||=new Map;let i=this.#R.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#F}_${this.#I++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,n=new FileReader,s=new Image,r=new Promise((t,r)=>{s.onload=()=>{i.bitmap=s;i.isSvg=!0;t()};n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};s.onerror=n.onerror=r});n.readAsDataURL(t);await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#R.set(t,i);i&&this.#R.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#B(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#B(t,t)}async getFromBlob(t,e){const i=await e;return this.#B(t,i)}async getFromId(t){this.#R||=new Map;const e=this.#R.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#R||=new Map;let i=this.#R.get(t);if(i?.bitmap){i.refCounter+=1;return i}const n=new OffscreenCanvas(e.width,e.height);n.getContext("2d").drawImage(e,0,0);i={bitmap:n.transferToImageBitmap(),id:`image_${this.#F}_${this.#I++}`,refCounter:1,isSvg:!1};this.#R.set(t,i);this.#R.set(i.id,i);return i}getSvgUrl(t){const e=this.#R.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#R||=new Map;const e=this.#R.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#F}_`)}}class CommandManager{#L=[];#O=!1;#N;#U=-1;constructor(t=128){this.#N=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){n&&t();if(this.#O)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#U){this.#L.length>0&&(this.#L.length=0);this.#U=0;this.#L.push(o);return}if(r&&this.#L[this.#U].type===s){a&&(o.undo=this.#L[this.#U].undo);this.#L[this.#U]=o;return}const l=this.#U+1;if(l===this.#N)this.#L.splice(0,1);else{this.#U=l;l<this.#L.length&&this.#L.splice(l)}this.#L.push(o)}undo(){if(-1===this.#U)return;this.#O=!0;const{undo:t,post:e}=this.#L[this.#U];t();e?.();this.#O=!1;this.#U-=1}redo(){if(this.#U<this.#L.length-1){this.#U+=1;this.#O=!0;const{cmd:t,post:e}=this.#L[this.#U];t();e?.();this.#O=!1}}hasSomethingToUndo(){return-1!==this.#U}hasSomethingToRedo(){return this.#U<this.#L.length-1}cleanType(t){if(-1!==this.#U){for(let e=this.#U;e>=0;e--)if(this.#L[e].type!==t){this.#L.splice(e+1,this.#U-e);this.#U=e;return}this.#L.length=0;this.#U=-1}}destroy(){this.#L=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}}}#H(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#H(e));if(!i)return;const{callback:n,options:{bubbles:s=!1,args:r=[],checker:a=null}}=i;if(!a||a(t,e)){n.bind(t,...r,e)();s||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";e.style.colorScheme="only light";document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,getRGB(n))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#z=new AbortController;#G=null;#W=null;#V=new Map;#j=new Map;#$=null;#X=null;#q=null;#K=new CommandManager;#Y=null;#Q=null;#J=null;#Z=0;#tt=new Set;#et=null;#it=null;#nt=new Set;_editorUndoBar=null;#st=!1;#rt=!1;#at=!1;#ot=null;#lt=null;#ht=null;#dt=null;#ct=!1;#ut=null;#pt=new IdManager;#gt=!1;#mt=!1;#ft=!1;#bt=null;#wt=null;#yt=null;#At=null;#vt=null;#xt=p.NONE;#Et=new Set;#Ct=null;#St=null;#Tt=null;#_t=null;#Mt=null;#Dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Pt=[0,0];#kt=null;#It=null;#Ft=null;#Rt=null;#Bt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#It.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#It.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#It.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,n,s,r,a,o,l,h,d,c,u,p,g,m){const f=this._signal=this.#z.signal;this.#It=t;this.#Ft=e;this.#Rt=i;this.#$=n;this.#Y=s;this.#St=r;this.#Mt=o;this._eventBus=a;a._on("editingaction",this.onEditingAction.bind(this),{signal:f});a._on("pagechanging",this.onPageChanging.bind(this),{signal:f});a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f});a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f});a._on("setpreference",this.onSetPreference.bind(this),{signal:f});a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f});a._on("pagesedited",this.onPagesEdited.bind(this),{signal:f});window.addEventListener("pointerdown",()=>{this.#mt=!0},{capture:!0,signal:f});window.addEventListener("pointerup",()=>{this.#mt=!1},{capture:!0,signal:f});this.#Lt();this.#Ot();this.#Nt();this.#X=o.annotationStorage;this.#ot=o.filterFactory;this.#Tt=l;this.#dt=h||null;this.#st=d;this.#rt=c;this.#at=u;this.#vt=p||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=g||null;this._supportsPinchToZoom=!1!==m;s?.setSidebarUiManager(this)}destroy(){this.#Bt?.resolve();this.#Bt=null;this.#z?.abort();this.#z=null;this._signal=null;for(const t of this.#j.values())t.destroy();this.#j.clear();this.#V.clear();this.#nt.clear();this.#At?.clear();this.#G=null;this.#Et.clear();this.#K.destroy();this.#$?.destroy();this.#Y?.destroy();this.#St?.destroy();this.#ut?.hide();this.#ut=null;this.#yt?.destroy();this.#yt=null;this.#W=null;if(this.#lt){clearTimeout(this.#lt);this.#lt=null}if(this.#kt){clearTimeout(this.#kt);this.#kt=null}this._editorUndoBar?.destroy();this.#Mt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#vt}get useNewAltTextFlow(){return this.#rt}get useNewAltTextWhenAddingImage(){return this.#at}get hcmFilter(){return shadow(this,"hcmFilter",this.#Tt?this.#ot.addHCMFilter(this.#Tt.foreground,this.#Tt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#It).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#dt?new Map(this.#dt.split(",").map(t=>{(t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase();return t})):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return shadow(this,"highlightColors",null);const e=new Map,i=!!this.#Tt;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return shadow(this,"highlightColors",e)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#J=t}setMainHighlightColorPicker(t){this.#yt=t}editAltText(t,e=!1){this.#$?.editAltText(this,t,e)}hasCommentManager(){return!!this.#Y}editComment(t,e,i,n){this.#Y?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#j.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#Y?.updateComment(t.getData())}updatePopupColor(t){this.#Y?.updatePopupColor(t)}removeComment(t){this.#Y?.removeComments([t.uid])}deleteComment(t,e){const undo=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,"comment");this.toggleComment(null);t.comment=null},undo,mustExec:!0})}toggleComment(t,e,i=void 0){this.#Y?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#Y?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#Y?.dialogElement||null}async waitForEditorsRendered(t){if(this.#j.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),onEditorsRendered=i=>{if(i.pageNumber===t){this._eventBus._off("editorsrendered",onEditorsRendered);e()}};this._eventBus.on("editorsrendered",onEditorsRendered);await i}getSignature(t){this.#St?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#St}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#at=e}onPagesEdited({pagesMapper:t}){for(const e of this.#V.values())e.updatePageIndex(t.getPrevPageNumber(e.pageIndex+1)-1);const e=this.#j,i=this.#j=new Map;for(const[n,s]of e){const e=t.getPrevPageNumber(n+1)-1;if(-1!==e){i.set(e,s);s.updatePageIndex(e)}else s.destroy()}}onPageChanging({pageNumber:t}){this.#Z=t-1}focusMainContainer(){this.#It.focus()}findParent(t,e){for(const i of this.#j.values()){const{x:n,y:s,width:r,height:a}=i.div.getBoundingClientRect();if(t>=n&&t<=n+r&&e>=s&&e<=s+a)return i}return null}disableUserSelect(t=!1){this.#Ft.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#nt.add(t)}removeShouldRescale(t){this.#nt.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#nt)t.onScaleChanging();this.#J?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Ut({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ht(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#j.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a}=i,o=i.toString(),l=this.#Ut(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const d=this.#Ht(l),c=this.#xt===p.NONE,callback=()=>{const i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a,text:o});c&&this.showAllEditors("highlight",!0,!0);e&&i?.editComment()};c?this.switchToMode(p.HIGHLIGHT,callback):callback()}commentSelection(t=""){this.highlightSelection(t,!0)}#zt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Ut(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#ut||=new FloatingToolbar(this);this.#ut.show(e,i,"ltr"===this.direction)}}getAndRemoveDataFromAnnotationStorage(t){if(!this.#X)return null;const e=`${u}${t}`,i=this.#X.getRawValue(e);i&&this.#X.remove(e);return i}addToAnnotationStorage(t){t.isEmpty()||!this.#X||this.#X.has(t.id)||this.#X.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Rt;if(i){i.setAttribute("data-l10n-id",t);e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args")}}#Gt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#Ct){this.#ut?.hide();this.#Ct=null;this.#Wt({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#Ct)return;const i=this.#Ut(t).closest(".textLayer");if(i){this.#ut?.hide();this.#Ct=e;this.#Wt({hasSelectedText:!0});if(this.#xt===p.HIGHLIGHT||this.#xt===p.NONE){this.#xt===p.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#ct=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#xt===p.HIGHLIGHT?this.#Ht(i):null;t?.toggleDrawing();if(this.#mt){const e=new AbortController,i=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Vt("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:i});window.addEventListener("blur",pointerup,{signal:i})}else{t?.toggleDrawing(!0);this.#Vt("main_toolbar")}}}}else if(this.#Ct){this.#ut?.hide();this.#Ct=null;this.#Wt({hasSelectedText:!1})}}#Vt(t=""){this.#xt===p.HIGHLIGHT?this.highlightSelection(t):this.#st&&this.#zt()}#Lt(){document.addEventListener("selectionchange",this.#Gt.bind(this),{signal:this._signal})}#jt(){if(this.#ht)return;this.#ht=new AbortController;const t=this.combinedSignal(this.#ht);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#$t(){this.#ht?.abort();this.#ht=null}blur(){this.isShiftKeyDown=!1;if(this.#ct){this.#ct=!1;this.#Vt("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#Et)if(e.div.contains(t)){this.#wt=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#wt)return;const[t,e]=this.#wt;this.#wt=null;e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal});e.focus()}#Nt(){if(this.#bt)return;this.#bt=new AbortController;const t=this.combinedSignal(this.#bt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Xt(){this.#bt?.abort();this.#bt=null}#qt(){if(this.#Q)return;this.#Q=new AbortController;const t=this.combinedSignal(this.#Q);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Kt(){this.#Q?.abort();this.#Q=null}#Ot(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Nt();this.setEditingState(!0)}removeEditListeners(){this.#Xt();this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#it)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#it)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#G?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#Et){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#it)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Yt(e);this.#Qt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#xt===p.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#ct){this.#ct=!1;this.#Vt("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}#Wt(t){if(Object.entries(t).some(([t,e])=>this.#Dt[t]!==e)){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#Dt,t)});this.#xt===p.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Jt([[g.HIGHLIGHT_FREE,!0]])}}#Jt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#jt();this.#qt();this.#Wt({isEditing:this.#xt!==p.NONE,isEmpty:this.#Zt(),hasSomethingToUndo:this.#K.hasSomethingToUndo(),hasSomethingToRedo:this.#K.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#$t();this.#Kt();this.#Wt({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#it){this.#it=t;for(const t of this.#it)this.#Jt(t.defaultPropertiesToUpdate)}}getId(){return this.#pt.id}get currentLayer(){return this.#j.get(this.#Z)}getLayer(t){return this.#j.get(t)}get currentPageIndex(){return this.#Z}addLayer(t){this.#j.set(t.pageIndex,t);this.#gt?t.enable():t.disable()}removeLayer(t){this.#j.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1,r=!1){if(this.#xt!==t){if(this.#Bt){await this.#Bt.promise;if(!this.#Bt)return}this.#Bt=Promise.withResolvers();this.#J?.commitOrRemove();this.#xt===p.POPUP&&this.#Y?.hideSidebar();this.#Y?.destroyPopup();this.#xt=t;if(t!==p.NONE){for(const t of this.#V.values())t.addStandaloneCommentButton();t===p.SIGNATURE&&await(this.#St?.loadSignatures());i&&CurrentPointers.clearPointerType();this.setEditingState(!0);await this.#te();this.unselectAll();for(const e of this.#j.values())e.updateMode(t);if(t===p.POPUP){this.#W||=await this.#Mt.getAnnotationsByType(new Set(this.#it.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#V.values()){const{annotationElementId:n,hasComment:s,deleted:r}=i;n&&t.add(n);s&&!r&&e.push(i.getData())}for(const i of this.#W){const{id:n,popupRef:s,contentsObj:r}=i;s&&r?.str&&!t.has(n)&&!this.#tt.has(n)&&e.push(i)}this.#Y?.showSidebar(e)}if(e){for(const t of this.#V.values())if(t.uid===e){this.setSelected(t);r?t.editComment():s?t.enterInEditMode():t.focus()}else t.unselect();this.#Bt.resolve()}else{n&&this.addNewEditorFromKeyboard();this.#Bt.resolve()}}else{this.setEditingState(!1);this.#ee();for(const t of this.#V.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide();this.toggleComment(null);this.#Bt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#xt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#it){switch(t){case g.CREATE:this.currentLayer.addNewEditor(e);return;case g.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#_t||=new Map).set(t,e);this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#Et)i.updateParams(t,e);else for(const i of this.#it)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#V.values())i.editorType===t&&i.show(e);(this.#_t?.get(g.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Jt([[g.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#ft!==t){this.#ft=t;for(const e of this.#j.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#te(){if(!this.#gt){this.#gt=!0;const t=[];for(const e of this.#j.values())t.push(e.enable());await Promise.all(t);for(const t of this.#V.values())t.enable()}}#ee(){this.unselectAll();if(this.#gt){this.#gt=!1;for(const t of this.#j.values())t.disable();for(const t of this.#V.values())t.disable()}}*getEditors(t){for(const e of this.#V.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#V.get(t)}addEditor(t){this.#V.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#lt&&clearTimeout(this.#lt);this.#lt=setTimeout(()=>{this.focusMainContainer();this.#lt=null},0)}this.#V.delete(t.id);t.annotationElementId&&this.#At?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#tt.has(t.annotationElementId)||this.#X?.remove(t.id)}addDeletedAnnotationElement(t){this.#tt.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#tt.has(t)}removeDeletedAnnotationElement(t){this.#tt.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Yt(t){const e=this.#j.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#G!==t){this.#G=t;t&&this.#Jt(t.propertiesToUpdate)}}get#ie(){let t=null;for(t of this.#Et);return t}updateUI(t){this.#ie===t&&this.#Jt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Jt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#Et.has(t)){this.#Et.delete(t);t.unselect();this.#Wt({hasSelectedEditor:this.hasSelection})}else{this.#Et.add(t);t.select();this.#Jt(t.propertiesToUpdate);this.#Wt({hasSelectedEditor:!0})}}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid});this.#J?.commitOrRemove();for(const e of this.#Et)e!==t&&e.unselect();this.#Et.clear();this.#Et.add(t);t.select();this.#Jt(t.propertiesToUpdate);this.#Wt({hasSelectedEditor:!0})}isSelected(t){return this.#Et.has(t)}get firstSelectedEditor(){return this.#Et.values().next().value}unselect(t){t.unselect();this.#Et.delete(t);this.#Wt({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#Et.size}get isEnterHandled(){return 1===this.#Et.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#K.undo();this.#Wt({hasSomethingToUndo:this.#K.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Zt()});this._editorUndoBar?.hide()}redo(){this.#K.redo();this.#Wt({hasSomethingToUndo:!0,hasSomethingToRedo:this.#K.hasSomethingToRedo(),isEmpty:this.#Zt()})}addCommands(t){this.#K.add(t);this.#Wt({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Zt()})}cleanUndoStack(t){this.#K.cleanType(t)}#Zt(){if(0===this.#V.size)return!0;if(1===this.#V.size)for(const t of this.#V.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#Et],undo=()=>{for(const t of e)this.#Yt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#G?.commitOrRemove()}hasSomethingToControl(){return this.#G||this.hasSelection}#Qt(t){for(const t of this.#Et)t.unselect();this.#Et.clear();for(const e of t)if(!e.isEmpty()){this.#Et.add(e);e.select()}this.#Wt({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#Et)t.commit();this.#Qt(this.#V.values())}unselectAll(){if(this.#G){this.#G.commitOrRemove();if(this.#xt!==p.NONE)return}if(!this.#J?.commitOrRemove()&&this.hasSelection){for(const t of this.#Et)t.unselect();this.#Et.clear();this.#Wt({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#Pt[0]+=t;this.#Pt[1]+=e;const[n,s]=this.#Pt,r=[...this.#Et];this.#kt&&clearTimeout(this.#kt);this.#kt=setTimeout(()=>{this.#kt=null;this.#Pt[0]=this.#Pt[1]=0;this.addCommands({cmd:()=>{for(const t of r)if(this.#V.has(t.id)){t.translateInPage(n,s);t.translationDone()}},undo:()=>{for(const t of r)if(this.#V.has(t.id)){t.translateInPage(-n,-s);t.translationDone()}},mustExec:!1})},1e3);for(const i of r){i.translateInPage(t,e);i.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#et=new Map;for(const t of this.#Et)this.#et.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#et)return!1;this.disableUserSelect(!1);const t=this.#et;this.#et=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},r]of t){r.newX=i;r.newY=n;r.newPageIndex=s;e||=i!==r.savedX||n!==r.savedY||s!==r.savedPageIndex}if(!e)return!1;const move=(t,e,i,n)=>{if(this.#V.has(t.id)){const s=this.#j.get(n);if(s)t._setParentAndPosition(s,e,i);else{t.pageIndex=n;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:s}]of t)move(e,i,n,s)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:s}]of t)move(e,i,n,s)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#et)for(const i of this.#et.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#Et.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#G===t}getActive(){return this.#G}getMode(){return this.#xt}isEditingMode(){return this.#xt!==p.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-n)/r,y:1-(t+a-i)/s,width:o/r,height:a/s});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/s,y:1-(e+o-n)/r,width:a/s,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-n)/r,y:(t-i)/s,width:o/r,height:a/s});break;default:a=(t,e,a,o)=>({x:(t-i)/s,y:(e-n)/r,width:a/s,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(a(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#q||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#q?.delete(t)}renderAnnotationElement(t){const e=this.#q?.get(t.data.id);if(!e)return;const i=this.#X.getRawValue(e);i&&(this.#xt!==p.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const n=this.#At?.get(t);if(n){n.setCanvas(e,i);this.#At.delete(t)}}addMissingCanvas(t,e){(this.#At||=new Map).set(t,e)}}class AltText{#g=null;#ne=!1;#se=null;#re=null;#ae=null;#oe=null;#le=!1;#he=null;#u=null;#de=null;#ce=null;#ue=!1;static#pe=null;static _l10n=null;constructor(t){this.#u=t;this.#ue=t._uiManager.useNewAltTextFlow;AltText.#pe||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){AltText._l10n??=t}async render(){const t=this.#se=document.createElement("button");t.className="altText";t.tabIndex="0";const e=this.#re=document.createElement("span");t.append(e);if(this.#ue){t.classList.add("new");t.setAttribute("data-l10n-id",AltText.#pe.missing);e.setAttribute("data-l10n-id",AltText.#pe["missing-label"])}else{t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button");e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label")}const i=this.#u._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:i});t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=t=>{t.preventDefault();this.#u._uiManager.editAltText(this.#u);this.#ue&&this.#u._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ge}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#le=!0;onClick(e)}},{signal:i});await this.#me();return t}get#ge(){return(this.#g?"added":null===this.#g&&this.guessedText&&"review")||"missing"}finish(){if(this.#se){this.#se.focus({focusVisible:this.#le});this.#le=!1}}isEmpty(){return this.#ue?null===this.#g:!this.#g&&!this.#ne}hasData(){return this.#ue?null!==this.#g||!!this.#de:this.isEmpty()}get guessedText(){return this.#de}async setGuessedText(t){if(null===this.#g){this.#de=t;this.#ce=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#me()}}toggleAltTextBadge(t=!1){if(this.#ue&&!this.#g){if(!this.#he){const t=this.#he=document.createElement("div");t.className="noAltTextBadge";this.#u.div.append(t)}this.#he.classList.toggle("hidden",!t)}else{this.#he?.remove();this.#he=null}}serialize(t){let e=this.#g;t||this.#de!==e||(e=this.#ce);return{altText:e,decorative:this.#ne,guessedText:this.#de,textWithDisclaimer:this.#ce}}get data(){return{altText:this.#g,decorative:this.#ne}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){if(i){this.#de=i;this.#ce=n}if(this.#g!==t||this.#ne!==e){if(!s){this.#g=t;this.#ne=e}this.#me()}}toggle(t=!1){if(this.#se){if(!t&&this.#oe){clearTimeout(this.#oe);this.#oe=null}this.#se.disabled=!t}}shown(){this.#u._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ge}})}destroy(){this.#se?.remove();this.#se=null;this.#re=null;this.#ae=null;this.#he?.remove();this.#he=null}async#me(){const t=this.#se;if(!t)return;if(this.#ue){t.classList.toggle("done",!!this.#g);t.setAttribute("data-l10n-id",AltText.#pe[this.#ge]);this.#re?.setAttribute("data-l10n-id",AltText.#pe[`${this.#ge}-label`]);if(!this.#g){this.#ae?.remove();return}}else{if(!this.#g&&!this.#ne){t.classList.remove("done");this.#ae?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#ae;if(!e){this.#ae=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#u.id}`;const i=100,n=this.#u._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#oe);this.#oe=null},{once:!0});t.addEventListener("mouseenter",()=>{this.#oe=setTimeout(()=>{this.#oe=null;this.#ae.classList.add("show");this.#u._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n});t.addEventListener("mouseleave",()=>{if(this.#oe){clearTimeout(this.#oe);this.#oe=null}this.#ae?.classList.remove("show")},{signal:n})}if(this.#ne)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#g}e.parentNode||t.append(e);const i=this.#u.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#fe=null;#be=null;#we=!1;#u=null;#ye=null;#Ae=null;#ve=null;#xe=null;#Ee=!1;#Ce=null;constructor(t){this.#u=t}renderForToolbar(){const t=this.#be=document.createElement("button");t.className="comment";return this.#S(t,!1)}renderForStandalone(){const t=this.#fe=document.createElement("button");t.className="annotationCommentButton";const e=this.#u.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#u._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`;i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#u.commentButtonColor;n&&(i.backgroundColor=n)}return this.#S(t,!0)}focusButton(){setTimeout(()=>{(this.#fe??this.#be)?.focus()},0)}onUpdatedColor(){if(!this.#fe)return;const t=this.#u.commentButtonColor;t&&(this.#fe.style.backgroundColor=t);this.#u._uiManager.updatePopupColor(this.#u)}get commentButtonWidth(){return(this.#fe?.getBoundingClientRect().width??0)/this.#u.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#Ce)return this.#Ce;if(!this.#fe)return null;const{x:t,y:e,height:i}=this.#fe.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#u.parent.boundingClientRect;return[(t-n)/r,(e+i-s)/a]}set commentPopupPositionInLayer(t){this.#Ce=t}hasDefaultPopupPosition(){return null===this.#Ce}removeStandaloneCommentButton(){this.#fe?.remove();this.#fe=null}removeToolbarCommentButton(){this.#be?.remove();this.#be=null}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#fe){this.#fe.classList.toggle("selected",t);this.#fe.ariaExpanded=e}}#S(t,e){if(!this.#u._uiManager.hasCommentManager())return null;t.tabIndex="0";t.ariaHasPopup="dialog";if(e){t.ariaControls="commentPopup";t.setAttribute("data-l10n-id","pdfjs-show-comment-button")}else{t.ariaControlsElements=[this.#u._uiManager.getCommentDialogElement()];t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button")}const i=this.#u._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i});if(e){t.addEventListener("focusin",t=>{this.#u._focusEventsAllowed=!1;stopEvent(t)},{capture:!0,signal:i});t.addEventListener("focusout",t=>{this.#u._focusEventsAllowed=!0;stopEvent(t)},{capture:!0,signal:i})}t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=e=>{e.preventDefault();t===this.#be?this.edit():this.#u.toggleComment(!0)};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#we=!0;onClick(e)}},{signal:i});t.addEventListener("pointerenter",()=>{this.#u.toggleComment(!1,!0)},{signal:i});t.addEventListener("pointerleave",()=>{this.#u.toggleComment(!1,!1)},{signal:i});return t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#u.commentButtonPosition;const{width:t,height:e,x:s,y:r}=this.#u;i=s+i*t;n=r+n*e}const s=this.#u.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=s;this.#u._uiManager.editComment(this.#u,r+i*o,a+n*l,{...t,parentDimensions:s})}finish(){if(this.#be){this.#be.focus({focusVisible:this.#we});this.#we=!1}}isDeleted(){return this.#Ee||""===this.#ve}isEmpty(){return null===this.#ve}hasBeenEdited(){return this.isDeleted()||this.#ve!==this.#ye}serialize(){return this.data}get data(){return{text:this.#ve,richText:this.#Ae,date:this.#xe,deleted:this.isDeleted()}}set data(t){t!==this.#ve&&(this.#Ae=null);if(null!==t){this.#ve=t;this.#xe=new Date;this.#Ee=!1}else{this.#ve="";this.#Ee=!0}}restoreData({text:t,richText:e,date:i}){this.#ve=t;this.#Ae=e;this.#xe=i;this.#Ee=!1}setInitialText(t,e=null){this.#ye=t;this.data=t;this.#xe=null;this.#Ae=e}shown(){}destroy(){this.#be?.remove();this.#be=null;this.#fe?.remove();this.#fe=null;this.#ve="";this.#Ae=null;this.#xe=null;this.#u=null;this.#we=!1;this.#Ee=!1}}class TouchManager{#It;#Se=!1;#Te=null;#_e;#Me;#De;#Pe;#ke=null;#Ie;#Fe=null;#Re;#Be=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:r=null,signal:a}){this.#It=t;this.#Te=i;this.#_e=e;this.#Me=n;this.#De=s;this.#Pe=r;this.#Re=new AbortController;this.#Ie=AbortSignal.any([a,this.#Re.signal]);t.addEventListener("touchstart",this.#Le.bind(this),{passive:!1,signal:this.#Ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#Le(t){if(this.#_e?.())return;if(1===t.touches.length){if(this.#ke)return;const t=this.#ke=new AbortController,e=AbortSignal.any([this.#Ie,t.signal]),i=this.#It,n={capture:!0,signal:e,passive:!1},cancelPointerDown=t=>{if("touch"===t.pointerType){this.#ke?.abort();this.#ke=null}};i.addEventListener("pointerdown",t=>{if("touch"===t.pointerType){stopEvent(t);cancelPointerDown(t)}},n);i.addEventListener("pointerup",cancelPointerDown,n);i.addEventListener("pointercancel",cancelPointerDown,n);return}if(!this.#Be){this.#Be=new AbortController;const t=AbortSignal.any([this.#Ie,this.#Be.signal]),e=this.#It,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Oe.bind(this),i);const n=this.#Ne.bind(this);e.addEventListener("touchend",n,i);e.addEventListener("touchcancel",n,i);i.capture=!0;e.addEventListener("pointerdown",stopEvent,i);e.addEventListener("pointermove",stopEvent,i);e.addEventListener("pointercancel",stopEvent,i);e.addEventListener("pointerup",stopEvent,i);this.#Me?.()}stopEvent(t);if(2!==t.touches.length||this.#Te?.()){this.#Fe=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#Fe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Oe(t){if(!this.#Fe||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:r,screenY:a}=i,o=this.#Fe,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=r-n,m=a-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Se&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=n;o.touch0Y=s;o.touch1X=r;o.touch1Y=a;if(!this.#Se){this.#Se=!0;return}const w=[(n+r)/2,(s+a)/2];this.#De?.(w,b,f)}#Ne(t){if(!(t.touches.length>=2)){if(this.#Be){this.#Be.abort();this.#Be=null;this.#Pe?.()}if(this.#Fe){stopEvent(t);this.#Fe=null;this.#Se=!1}}}destroy(){this.#Re?.abort();this.#Re=null;this.#ke?.abort();this.#ke=null}}class AnnotationEditor{#Ue=null;#He=null;#g=null;#m=null;#fe=null;#ze=!1;#Ge=null;#We="";#Ve=null;#je=null;#$e=null;#Xe=null;#qe=null;#Ke="";#Ye=!1;#Qe=null;#Je=!1;#Ze=!1;#ti=!1;#ei=null;#ii=0;#ni=0;#si=null;#ri=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#ai=!1;#oi=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;this.annotationElementId=t.annotationElementId||null;this.creationDate=t.creationDate||new Date;this.modificationDate=t.modificationDate||null;this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,n];this.pageTranslation=[s,r];const[a,o]=this.parentDimensions;this.x=t.x/a;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ai}set _isDraggable(t){this.#ai=t;this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#oi}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else{this.#li();this.#Xe?.remove();this.#Xe=null}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ye?this.#Ye=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,r]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n);this.x=(t+i)/s;this.y=(e+n)/r;this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n);this._onTranslated()}#hi([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n);this.x+=i/t;this.y+=n/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#hi(this.parentDimensions,t,e)}translateInPage(t,e){this.#Qe||=[this.x,this.y,this.width,this.height];this.#hi(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Qe||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;this.x+=t/n;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o;a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`;h.top=`${(100*a).toFixed(2)}%`;this._onTranslating(r,a);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Qe&&(this.#Qe[0]!==this.x||this.#Qe[1]!==this.y)}get _hasBeenResized(){return!!this.#Qe&&(this.#Qe[2]!==this.width||this.#Qe[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:r,width:a,height:o}=this;a*=i;o*=n;s*=i;r*=n;if(this._mustFixPosition)switch(t){case 0:s=MathClamp(s,0,i-a);r=MathClamp(r,0,n-o);break;case 90:s=MathClamp(s,0,i-o);r=MathClamp(r,a,n);break;case 180:s=MathClamp(s,a,i);r=MathClamp(r,o,n);break;case 270:s=MathClamp(s,o,i);r=MathClamp(r,0,n-a)}this.x=s/=i;this.y=r/=n;const[l,h]=this.getBaseTranslation();s+=l;r+=h;e.left=`${(100*s).toFixed(2)}%`;e.top=`${(100*r).toFixed(2)}%`;this.moveInDOM()}static#di(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#di(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#di(t,e,360-this.parentRotation)}#ci(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`;t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#ui(){if(this.#Ve)return;this.#Ve=document.createElement("div");this.#Ve.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Ve.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#pi.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#Ve)}#pi(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#g?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1;this.#je=[e.screenX,e.screenY];const s=new AbortController,r=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#gi.bind(this,t),{passive:!0,capture:!0,signal:r});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:r});window.addEventListener("contextmenu",noContextMenu,{signal:r});this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{s.abort();this.parent.togglePointerEvents(!0);this.#g?.toggle(!0);this._isDraggable=n;this.parent.div.style.cursor=a;this.div.style.cursor=o;this.#mi()};window.addEventListener("pointerup",pointerUpCallback,{signal:r});window.addEventListener("blur",pointerUpCallback,{signal:r})}#fi(t,e,i,n){this.width=i;this.height=n;this.x=t;this.y=e;this.setDims();this.fixAndSetPosition();this._onResized()}_onResized(){}#mi(){if(!this.#$e)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#$e;this.#$e=null;const s=this.x,r=this.y,a=this.width,o=this.height;s===t&&r===e&&a===i&&o===n||this.addCommands({cmd:this.#fi.bind(this,s,r,a,o),undo:this.#fi.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#gi(t,e){const[i,n]=this.parentDimensions,s=this.x,r=this.y,a=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/n,d=this.#ci(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#ci(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(a,o),b=p(a,o);let w=transf(...b);const y=AnnotationEditor._round(s+w[0]),A=AnnotationEditor._round(r+w[1]);let v,x,E=1,C=1;if(e.fromKeyboard)({deltaX:v,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#je;[v,x]=this.screenToPageTranslation(t-n,i-s);this.#je[0]=t;this.#je[1]=i}[v,x]=(S=v/i,T=x/n,[c[0]*S+c[2]*T,c[1]*S+c[3]*T]);var S,T;if(g){const t=Math.hypot(a,o);E=C=Math.max(Math.min(Math.hypot(b[0]-f[0]-v,b[1]-f[1]-x)/t,1/a,1/o),l/a,h/o)}else m?E=MathClamp(Math.abs(b[0]-f[0]-v),l,1)/a:C=MathClamp(Math.abs(b[1]-f[1]-x),h,1)/o;const _=AnnotationEditor._round(a*E),M=AnnotationEditor._round(o*C);w=transf(...p(_,M));const D=y-w[0],P=A-w[1];this.#Qe||=[this.x,this.y,this.width,this.height];this.width=_;this.height=M;this.x=D;this.y=P;this.setDims();this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#g?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#Ze)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton());this._editToolbar.addButton("delete");return this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove();this._editToolbar=null;this.#g?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#g){AltText.initialize(AnnotationEditor._l10n);this.#g=new AltText(this);if(this.#Ue){this.#g.data=this.#Ue;this.#Ue=null}}return this.#g}get altTextData(){return this.#g?.data}set altTextData(t){this.#g&&(this.#g.data=t)}get guessedAltText(){return this.#g?.guessedText}async setGuessedAltText(t){await(this.#g?.setGuessedText(t))}serializeAltText(t){return this.#g?.serialize(t)}hasAltText(){return!!this.#g&&!this.#g.isEmpty()}hasAltTextData(){return this.#g?.hasData()??!1}focusCommentButton(){this.#m?.focusButton()}addCommentButton(){return this.canAddComment?this.#m||=new Comment(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager())if(this.#fe)this._uiManager.isEditingMode()&&this.#fe.classList.remove("hidden");else if(this.hasComment){this.#fe=this.#m.renderForStandalone();this.div.append(this.#fe)}}removeStandaloneCommentButton(){this.#m.removeStandaloneCommentButton();this.#fe=null}hideStandaloneCommentButton(){this.#fe?.classList.add("hidden")}get comment(){if(!this.#m)return null;const{data:{richText:t,text:e,date:i,deleted:n}}=this.#m;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#m||=new Comment(this);"object"==typeof t&&null!==t?this.#m.restoreData(t):this.#m.data=t;if(this.hasComment){this.removeCommentButtonFromToolbar();this.addStandaloneCommentButton();this._uiManager.updateComment(this)}else{this.addCommentButtonInToolbar();this.removeStandaloneCommentButton();this._uiManager.removeComment(this)}}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;this.#m||=new Comment(this);this.#m.setInitialText(t,i);if(!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#m?.hasBeenEdited()}get hasDeletedComment(){return this.#m?.isDeleted()}get hasComment(){return!!this.#m&&!this.#m.isEmpty()&&!this.#m.isDeleted()}async editComment(t){this.#m||=new Comment(this);this.#m.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#m.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[r]=this.pageTranslation,a=r+s+1,o=n-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#m.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360);t.className=this.name;t.setAttribute("id",this.id);t.tabIndex=this.#ze?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#bi();const[e,i]=this.parentDimensions;if(this.parentRotation%180!=0){t.style.maxWidth=`${(100*i/e).toFixed(2)}%`;t.style.maxHeight=`${(100*e/i).toFixed(2)}%`}const[n,s]=this.getInitialTranslation();this.translate(n,s);bindEvents(this,t,["keydown","pointerdown","dblclick"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ri||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#wi.bind(this),onPinching:this.#yi.bind(this),onPinchEnd:this.#Ai.bind(this),signal:this._uiManager._signal}));this.addStandaloneCommentButton();this._uiManager._editorUndoBar?.hide();return t}#wi(){this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#g?.toggle(!1);this.parent.togglePointerEvents(!1)}#yi(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#ci(this.rotation),transf=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[r,a]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/r,u=AnnotationEditor.MIN_SIZE/a;n=Math.max(Math.min(n,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*n),g=AnnotationEditor._round(d*n);if(p===h&&g===d)return;this.#Qe||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),w=transf(p/2,g/2);this.x=f-w[0];this.y=b-w[1];this.width=p;this.height=g;this.setDims();this.fixAndSetPosition();this._onResizing()}#Ai(){this.#g?.toggle(!0);this.parent.togglePointerEvents(!0);this.#mi()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#Ye=!0;this._isDraggable?this.#vi(t):this.#xi(t)}}#xi(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#vi(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),r={capture:!0,passive:!1,signal:s},cancelDrag=t=>{n.abort();this.#Ge=null;this.#Ye=!1;this._uiManager.endDragSession()||this.#xi(t);i&&this._onStopDragging()};if(e){this.#ii=t.clientX;this.#ni=t.clientY;this.#Ge=t.pointerId;this.#We=t.pointerType;window.addEventListener("pointermove",t=>{if(!i){i=!0;this._uiManager.toggleComment(this,!0,!1);this._onStartDragging()}const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#Ge){stopEvent(t);return}const[r,a]=this.screenToPageTranslation(e-this.#ii,n-this.#ni);this.#ii=e;this.#ni=n;this._uiManager.dragSelectedEditors(r,a)},r);window.addEventListener("touchmove",stopEvent,r);window.addEventListener("pointerdown",t=>{t.pointerType===this.#We&&(this.#ri||t.isPrimary)&&cancelDrag(t);stopEvent(t)},r)}const pointerUpCallback=t=>{this.#Ge&&this.#Ge!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:s});window.addEventListener("blur",pointerUpCallback,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#ei&&clearTimeout(this.#ei);this.#ei=setTimeout(()=>{this.#ei=null;this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/n,h=e/n,d=this.x*s,c=this.y*r,u=this.width*s,p=this.height*r;switch(i){case 0:return[d+l+a,r-c-h-p+o,d+l+u+a,r-c-h+o];case 90:return[d+h+a,r-c+l+o,d+h+p+a,r-c+l+u+o];case 180:return[d-l-u+a,r-c+h+o,d-l+a,r-c+h+p+o];case 270:return[d-h-p+a,r-c-l-u+o,d-h+a,r-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,r]=t,a=s-i,o=r-n;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-n,o,a];case 180:return[s,e-n,a,o];case 270:return[s,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#m?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;this.parent.setEditingState(!1);this.#Ze=!0;return!0}disableEditMode(){if(!this.isInEditMode())return!1;this.parent.setEditingState(!0);this.#Ze=!1;return!0}isInEditMode(){return this.#Ze}shouldGetKeyboardEvents(){return this.#ti}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:r}=window;return e<r&&n>0&&t<s&&i>0}#bi(){if(this.#qe||!this.div)return;this.#qe=new AbortController;const t=this._uiManager.combinedSignal(this.#qe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#bi()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation;n.#Ue=t.accessibilityData;n._isCopy=t.isCopy||!1;const[s,r]=n.pageDimensions,[a,o,l,h]=n.getRectInCurrentCoords(t.rect,r);n.x=a/s;n.y=o/r;n.width=l/s;n.height=h/r;return n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#qe?.abort();this.#qe=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);this.hideCommentPopup();if(this.#ei){clearTimeout(this.#ei);this.#ei=null}this.#li();this.removeEditToolbar();if(this.#si){for(const t of this.#si.values())clearTimeout(t);this.#si=null}this.parent=null;this.#ri?.destroy();this.#ri=null;this.#Xe?.remove();this.#Xe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#ui();this.#Ve.classList.remove("hidden")}}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,r]=this.getPDFRect();return[AnnotationEditor._round(i+(s-i)*t),AnnotationEditor._round(n+(r-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#m.commentPopupPositionInLayer}set commentPopupPosition(t){this.#m.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#m.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#m.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#m?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Ve.children;if(!this.#He){this.#He=Array.from(e);const t=this.#Ei.bind(this),i=this.#Ci.bind(this),n=this._uiManager._signal;for(const e of this.#He){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:n});e.addEventListener("blur",i,{signal:n});e.addEventListener("focus",this.#Si.bind(this,s),{signal:n});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[s])}}const i=this.#He[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#He.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#Ve.append(this.#Ve.firstElementChild);else if(s>n)for(let t=0;t<s-n;t++)this.#Ve.firstElementChild.before(this.#Ve.lastElementChild);let t=0;for(const i of e){const e=this.#He[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[e])}}this.#Ti(0);this.#ti=!0;this.#Ve.firstElementChild.focus({focusVisible:!0});t.preventDefault();t.stopImmediatePropagation()}#Ei(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#Ci(t){this.#ti&&t.relatedTarget?.parentNode!==this.#Ve&&this.#li()}#Si(t){this.#Ke=this.#ti?t:""}#Ti(t){if(this.#He)for(const e of this.#He)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#ti&&this.#gi(this.#Ke,{deltaX:t,deltaY:e,fromKeyboard:!0})}#li(){this.#ti=!1;this.#Ti(-1);this.#mi()}_stopResizingWithKeyboard(){this.#li();this.div.focus()}select(){if(this.isSelected&&this._editToolbar)this._editToolbar.show();else{this.isSelected=!0;this.makeResizable();this.div?.classList.add("selectedEditor");if(this._editToolbar){this._editToolbar?.show();this.#g?.toggleAltTextBadge(!1)}else this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()})}}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){if(this.isSelected){this.isSelected=!1;this.#Ve?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#g?.toggleAltTextBadge(!0);this.hideCommentPopup()}}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){if(this.canChangeContent){this.enableEditMode();this.div.focus()}}dblclick(t){if("BUTTON"!==t.target.nodeName){this.enterInEditMode();this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid})}}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Je}set isEditing(t){this.#Je=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#si||=new Map;const{action:e}=t;let i=this.#si.get(e);i&&clearTimeout(i);i=setTimeout(()=>{this._reportTelemetry(t);this.#si.delete(e);0===this.#si.size&&(this.#si=null)},AnnotationEditor._telemetryTimeout);this.#si.set(e,i);return}t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#ze=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ze=!0}updateFakeAnnotationElement(t){if(this.#Xe||this.deleted)if(this.deleted){this.#Xe.remove();this.#Xe=null}else(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Xe.updateEdited({rect:this.getPDFRect(),popup:this.comment});else this.#Xe=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted){t.hide();return null}let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const q=3285377520,K=4294901760,Y=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:q;this.h2=t?4294967295&t:q}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);if(s<=255)e[i++]=s;else{e[i++]=s>>>8;e[i++]=255&s}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const n=i>>2,s=i-4*n,r=new Uint32Array(e.buffer,0,n);let a=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t<n;t++)if(1&t){a=r[t];a=a*d&K|a*u&Y;a=a<<15|a>>>17;a=a*c&K|a*p&Y;l^=a;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[t];o=o*d&K|o*u&Y;o=o<<15|o>>>17;o=o*c&K|o*p&Y;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}a=0;switch(s){case 3:a^=e[4*n+2]<<16;case 2:a^=e[4*n+1]<<8;case 1:a^=e[4*n];a=a*d&K|a*u&Y;a=a<<15|a>>>17;a=a*c&K|a*p&Y;1&n?l^=a:h^=a}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&K|36045*t&Y;e=4283543511*e&K|(2950163797*(e<<16|t>>>16)&K)>>>16;t^=e>>>1;t=444984403*t&K|60499*t&Y;e=3301882366*e&K|(3120437893*(e<<16|t>>>16)&K)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Q=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#_i=!1;#Mi=null;#Di=null;#Pi=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Pi.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Pi.get(t)}remove(t){const e=this.#Pi.get(t);if(void 0!==e){e instanceof AnnotationEditor&&this.#Di.delete(e.annotationElementId);this.#Pi.delete(t);0===this.#Pi.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Pi.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}}setValue(t,e){const i=this.#Pi.get(t);let n=!1;if(void 0!==i){for(const[t,s]of Object.entries(e))if(i[t]!==s){n=!0;i[t]=s}}else{n=!0;this.#Pi.set(t,e)}n&&this.#ki();if(e instanceof AnnotationEditor){(this.#Di||=new Map).set(e.annotationElementId,e);"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}}has(t){return this.#Pi.has(t)}get size(){return this.#Pi.size}#ki(){if(!this.#_i){this.#_i=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#_i){this.#_i=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Pi.size)return Q;const t=new Map,e=new MurmurHash3_64,i=[],n=Object.create(null);let s=!1;for(const[i,r]of this.#Pi){const a=r instanceof AnnotationEditor?r.serialize(!1,n):r;if(r.page){r.pageIndex=r.page._pageIndex;delete r.page}if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);s||=!!a.bitmap}}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Q}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#Pi.values()){if(!(s instanceof AnnotationEditor)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const r=s.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(s).constructor);t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;let i=o.get(t);if(!i){i=new Map;o.set(t,i)}const n=i.get(e)??0;i.set(e,n+1)}}if(n>0||i>0){t||=Object.create(null);t.comments={deleted:n,edited:i}}if(!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Mi=null}updateEditor(t,e){const i=this.#Di?.get(t);if(i){i.updateFromAnnotationLayer(e);return!0}return!1}getEditor(t){return this.#Di?.get(t)||null}get modifiedIds(){if(this.#Mi)return this.#Mi;const t=[];if(this.#Di)for(const e of this.#Di.values())e.serialize()&&t.push(e.annotationElementId);return this.#Mi={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#Pi.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#Ii;constructor(t){super();const{map:e,hash:i,transfer:n}=t.serializable,s=structuredClone(e,n?{transfer:n}:null);this.#Ii={map:s,hash:i,transfer:n}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Ii}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#Fi=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#Fi.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#Fi.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,r=new FontFace(e,n,s);this.addNativeFontFace(r);try{await r.load();this.#Fi.add(e);i?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(r)}return}unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",t||util_FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let i,n;const s=this._document.createElement("canvas");s.width=1;s.height=1;const r=s.getContext("2d");let a=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,n=o.length-3;i<n;i+=4)d=d-h+int32(o,i)|0;i<o.length&&(d=d-h+int32(o+"XXX",i)|0);l=spliceString(l,16,4,function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++a>30){warn("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,()=>{u.remove();e.complete()})}}class FontFaceObject{#Ri;constructor(t,e=null,i,n){this.compiledGlyphs=Object.create(null);this.#Ri=t;this._inspectFont=e;i&&Object.assign(this,i);n&&(this.charProcOperatorList=n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const s=makePathFromDrawOPS(n?.path);this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=s}get black(){return this.#Ri.black}get bold(){return this.#Ri.bold}get disableFontFace(){return this.#Ri.disableFontFace??!1}set disableFontFace(t){shadow(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#Ri.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#Ri.isInvalidPDFjsFont}get isType3Font(){return this.#Ri.isType3Font}get italic(){return this.#Ri.italic}get missingFile(){return this.#Ri.missingFile}get remeasure(){return this.#Ri.remeasure}get vertical(){return this.#Ri.vertical}get ascent(){return this.#Ri.ascent}get defaultWidth(){return this.#Ri.defaultWidth}get descent(){return this.#Ri.descent}get bbox(){return this.#Ri.bbox}set bbox(t){shadow(this,"bbox",t)}get fontMatrix(){return this.#Ri.fontMatrix}get fallbackName(){return this.#Ri.fallbackName}get loadedName(){return this.#Ri.loadedName}get mimetype(){return this.#Ri.mimetype}get name(){return this.#Ri.name}get data(){return this.#Ri.data}clearData(){this.#Ri.clearData()}get cssFontInfo(){return this.#Ri.cssFontInfo}get systemFontInfo(){return this.#Ri.systemFontInfo}get defaultVMetrics(){return this.#Ri.defaultVMetrics}}class CssFontInfo{#Bi;#Li;#Oi;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of CssFontInfo.strings){const r=e.encode(t[s]);i[s]=r;n+=4+r.length}const s=new ArrayBuffer(n),r=new Uint8Array(s),a=new DataView(s);let o=0;for(const t of CssFontInfo.strings){const e=i[t],n=e.length;a.setUint32(o,n);r.set(e,o+4);o+=4+n}assert(o===s.byteLength,"CssFontInfo.write: Buffer overflow");return s}constructor(t){this.#Bi=t;this.#Li=new DataView(this.#Bi);this.#Oi=new TextDecoder}#Ni(t){assert(t<CssFontInfo.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#Li.getUint32(e)+4;const i=this.#Li.getUint32(e);return this.#Oi.decode(new Uint8Array(this.#Bi,e+4,i))}get fontFamily(){return this.#Ni(0)}get fontWeight(){return this.#Ni(1)}get italicAngle(){return this.#Ni(2)}}class SystemFontInfo{#Bi;#Li;#Oi;static strings=["css","loadedName","baseFontName","src"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of SystemFontInfo.strings){const r=e.encode(t[s]);i[s]=r;n+=4+r.length}n+=4;let s,r,a=1+n;if(t.style){s=e.encode(t.style.style);r=e.encode(t.style.weight);a+=4+s.length+4+r.length}const o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let d=0;h.setUint8(d++,t.guessFallback?1:0);h.setUint32(d,0);d+=4;n=0;for(const t of SystemFontInfo.strings){const e=i[t],s=e.length;n+=4+s;h.setUint32(d,s);l.set(e,d+4);d+=4+s}h.setUint32(d-n-4,n);if(t.style){h.setUint32(d,s.length);l.set(s,d+4);d+=4+s.length;h.setUint32(d,r.length);l.set(r,d+4);d+=4+r.length}assert(d<=o.byteLength,"SubstitionInfo.write: Buffer overflow");return o.transferToFixedLength(d)}constructor(t){this.#Bi=t;this.#Li=new DataView(this.#Bi);this.#Oi=new TextDecoder}get guessFallback(){return 0!==this.#Li.getUint8(0)}#Ni(t){assert(t<SystemFontInfo.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#Li.getUint32(e)+4;const i=this.#Li.getUint32(e);return this.#Oi.decode(new Uint8Array(this.#Bi,e+4,i))}get css(){return this.#Ni(0)}get loadedName(){return this.#Ni(1)}get baseFontName(){return this.#Ni(2)}get src(){return this.#Ni(3)}get style(){let t=1;t+=4+this.#Li.getUint32(t);const e=this.#Li.getUint32(t),i=this.#Oi.decode(new Uint8Array(this.#Bi,t+4,e));t+=4+e;const n=this.#Li.getUint32(t);return{style:i,weight:this.#Oi.decode(new Uint8Array(this.#Bi,t+4,n))}}}class FontInfo{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#Ui=Math.ceil(2*this.bools.length/8);static#Hi=this.#Ui+8*this.numbers.length;static#zi=this.#Hi+1+8;static#Gi=this.#zi+1+48;static#Wi=this.#Gi+1+6;#Bi;#Oi;#Li;constructor({data:t,extra:e}){this.#Bi=t;this.#Oi=new TextDecoder;this.#Li=new DataView(this.#Bi);e&&Object.assign(this,e)}#Vi(t){assert(t<FontInfo.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,n=this.#Li.getUint8(e)>>i&3;return 0===n?void 0:2===n}get black(){return this.#Vi(0)}get bold(){return this.#Vi(1)}get disableFontFace(){return this.#Vi(2)}get fontExtraProperties(){return this.#Vi(3)}get isInvalidPDFjsFont(){return this.#Vi(4)}get isType3Font(){return this.#Vi(5)}get italic(){return this.#Vi(6)}get missingFile(){return this.#Vi(7)}get remeasure(){return this.#Vi(8)}get vertical(){return this.#Vi(9)}#ji(t){assert(t<FontInfo.numbers.length,"Invalid number index");return this.#Li.getFloat64(FontInfo.#Ui+8*t)}get ascent(){return this.#ji(0)}get defaultWidth(){return this.#ji(1)}get descent(){return this.#ji(2)}get bbox(){let t=FontInfo.#Hi;if(0===this.#Li.getUint8(t))return;t+=1;const e=[];for(let i=0;i<4;i++){e.push(this.#Li.getInt16(t,!0));t+=2}return e}get fontMatrix(){let t=FontInfo.#zi;if(0===this.#Li.getUint8(t))return;t+=1;const e=[];for(let i=0;i<6;i++){e.push(this.#Li.getFloat64(t,!0));t+=8}return e}get defaultVMetrics(){let t=FontInfo.#Gi;if(0===this.#Li.getUint8(t))return;t+=1;const e=[];for(let i=0;i<3;i++){e.push(this.#Li.getInt16(t,!0));t+=2}return e}#Ni(t){assert(t<FontInfo.strings.length,"Invalid string index");let e=FontInfo.#Wi+4;for(let i=0;i<t;i++)e+=this.#Li.getUint32(e)+4;const i=this.#Li.getUint32(e),n=new Uint8Array(i);n.set(new Uint8Array(this.#Bi,e+4,i));return this.#Oi.decode(n)}get fallbackName(){return this.#Ni(0)}get loadedName(){return this.#Ni(1)}get mimetype(){return this.#Ni(2)}get name(){return this.#Ni(3)}get data(){let t=FontInfo.#Wi;t+=4+this.#Li.getUint32(t);t+=4+this.#Li.getUint32(t);t+=4+this.#Li.getUint32(t);const e=this.#Li.getUint32(t);if(0!==e)return new Uint8Array(this.#Bi,t+4,e)}clearData(){let t=FontInfo.#Wi;t+=4+this.#Li.getUint32(t);t+=4+this.#Li.getUint32(t);t+=4+this.#Li.getUint32(t);const e=this.#Li.getUint32(t);new Uint8Array(this.#Bi,t+4,e).fill(0);this.#Li.setUint32(t,0)}get cssFontInfo(){let t=FontInfo.#Wi;t+=4+this.#Li.getUint32(t);t+=4+this.#Li.getUint32(t);const e=this.#Li.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#Bi,t+4,e));return new CssFontInfo(i.buffer)}get systemFontInfo(){let t=FontInfo.#Wi;t+=4+this.#Li.getUint32(t);const e=this.#Li.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#Bi,t+4,e));return new SystemFontInfo(i.buffer)}static write(t){const e=t.systemFontInfo?SystemFontInfo.write(t.systemFontInfo):null,i=t.cssFontInfo?CssFontInfo.write(t.cssFontInfo):null,n=new TextEncoder,s={};let r=0;for(const e of FontInfo.strings){s[e]=n.encode(t[e]);r+=4+s[e].length}const a=FontInfo.#Wi+4+r+4+(e?e.byteLength:0)+4+(i?i.byteLength:0)+4+(t.data?t.data.length:0),o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let d=0;const c=FontInfo.bools.length;let u=0,p=0;for(let e=0;e<c;e++){const i=t[FontInfo.bools[e]];u|=(void 0===i?0:i?2:1)<<p;p+=2;if(8===p||e===c-1){h.setUint8(d++,u);u=0;p=0}}assert(d===FontInfo.#Ui,"FontInfo.write: Boolean properties offset mismatch");for(const e of FontInfo.numbers){h.setFloat64(d,t[e]);d+=8}assert(d===FontInfo.#Hi,"FontInfo.write: Number properties offset mismatch");if(t.bbox){h.setUint8(d++,4);for(const e of t.bbox){h.setInt16(d,e,!0);d+=2}}else{h.setUint8(d++,0);d+=8}assert(d===FontInfo.#zi,"FontInfo.write: BBox properties offset mismatch");if(t.fontMatrix){h.setUint8(d++,6);for(const e of t.fontMatrix){h.setFloat64(d,e,!0);d+=8}}else{h.setUint8(d++,0);d+=48}assert(d===FontInfo.#Gi,"FontInfo.write: FontMatrix properties offset mismatch");if(t.defaultVMetrics){h.setUint8(d++,1);for(const e of t.defaultVMetrics){h.setInt16(d,e,!0);d+=2}}else{h.setUint8(d++,0);d+=6}assert(d===FontInfo.#Wi,"FontInfo.write: DefaultVMetrics properties offset mismatch");h.setUint32(FontInfo.#Wi,0);d+=4;for(const t of FontInfo.strings){const e=s[t],i=e.length;h.setUint32(d,i);l.set(e,d+4);d+=4+i}h.setUint32(FontInfo.#Wi,d-FontInfo.#Wi-4);if(e){const t=e.byteLength;h.setUint32(d,t);assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo");l.set(new Uint8Array(e),d+4);d+=4+t}else{h.setUint32(d,0);d+=4}if(i){const t=i.byteLength;h.setUint32(d,t);assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo");l.set(new Uint8Array(i),d+4);d+=4+t}else{h.setUint32(d,0);d+=4}if(void 0===t.data){h.setUint32(d,0);d+=4}else{h.setUint32(d,t.data.length);l.set(t.data,d+4);d+=4+t.data.length}assert(d<=o.byteLength,"FontInfo.write: Buffer overflow");return o.transferToFixedLength(d)}}class PatternInfo{static#$i=0;static#Xi=1;static#qi=2;static#Ki=3;static#Yi=4;static#Qi=8;static#Ji=12;static#Zi=16;constructor(t){this.buffer=t;this.view=new DataView(t);this.data=new Uint8Array(t)}static write(t){let e,i=null,n=[],s=[],r=[],a=[],o=null,l=null;switch(t[0]){case"RadialAxial":e="axial"===t[1]?1:2;i=t[2];r=t[3];1===e?n.push(...t[4],...t[5]):n.push(t[4][0],t[4][1],t[6],t[5][0],t[5][1],t[7]);break;case"Mesh":e=3;o=t[1];n=t[2];s=t[3];a=t[4]||[];i=t[6];l=t[7];break;default:throw new Error(`Unsupported pattern type: ${t[0]}`)}const h=Math.floor(n.length/2),d=Math.floor(s.length/3),c=r.length,u=a.length;let p=0;for(const t of a){p+=1;p=4*Math.ceil(p/4);p+=4+4*t.coords.length;p+=4+4*t.colors.length;void 0!==t.verticesPerRow&&(p+=4)}const g=new ArrayBuffer(20+8*h+3*d+8*c+(i?16:0)+(l?3:0)+p),m=new DataView(g),f=new Uint8Array(g);m.setUint8(PatternInfo.#$i,e);m.setUint8(PatternInfo.#Xi,i?1:0);m.setUint8(PatternInfo.#qi,l?1:0);m.setUint8(PatternInfo.#Ki,o);m.setUint32(PatternInfo.#Yi,h,!0);m.setUint32(PatternInfo.#Qi,d,!0);m.setUint32(PatternInfo.#Ji,c,!0);m.setUint32(PatternInfo.#Zi,u,!0);let b=20;new Float32Array(g,b,2*h).set(n);b+=8*h;f.set(s,b);b+=3*d;for(const[t,e]of r){m.setFloat32(b,t,!0);b+=4;m.setUint32(b,parseInt(e.slice(1),16),!0);b+=4}if(i)for(const t of i){m.setFloat32(b,t,!0);b+=4}if(l){f.set(l,b);b+=3}for(let t=0;t<a.length;t++){const e=a[t];m.setUint8(b,e.type);b+=1;b=4*Math.ceil(b/4);m.setUint32(b,e.coords.length,!0);b+=4;new Int32Array(g,b,e.coords.length).set(e.coords);b+=4*e.coords.length;m.setUint32(b,e.colors.length,!0);b+=4;new Int32Array(g,b,e.colors.length).set(e.colors);b+=4*e.colors.length;if(void 0!==e.verticesPerRow){m.setUint32(b,e.verticesPerRow,!0);b+=4}}return g}getIR(){const t=this.view,e=this.data[PatternInfo.#$i],i=!!this.data[PatternInfo.#Xi],n=!!this.data[PatternInfo.#qi],s=t.getUint32(PatternInfo.#Yi,!0),r=t.getUint32(PatternInfo.#Qi,!0),a=t.getUint32(PatternInfo.#Ji,!0),o=t.getUint32(PatternInfo.#Zi,!0);let l=20;const h=new Float32Array(this.buffer,l,2*s);l+=8*s;const d=new Uint8Array(this.buffer,l,3*r);l+=3*r;const c=[];for(let e=0;e<a;++e){const e=t.getFloat32(l,!0);l+=4;const i=t.getUint32(l,!0);l+=4;c.push([e,`#${i.toString(16).padStart(6,"0")}`])}let u=null;if(i){u=[];for(let e=0;e<4;++e){u.push(t.getFloat32(l,!0));l+=4}}let p=null;if(n){p=new Uint8Array(this.buffer,l,3);l+=3}const g=[];for(let e=0;e<o;++e){const e=t.getUint8(l);l+=1;l=4*Math.ceil(l/4);const i=t.getUint32(l,!0);l+=4;const n=new Int32Array(this.buffer,l,i);l+=4*i;const s=t.getUint32(l,!0);l+=4;const r=new Int32Array(this.buffer,l,s);l+=4*s;const a={type:e,coords:n,colors:r};if(e===b){a.verticesPerRow=t.getUint32(l,!0);l+=4}g.push(a)}if(1===e)return["RadialAxial","axial",u,c,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",u,c,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===e){const t=this.data[PatternInfo.#Ki];let e=null;if(h.length>0){let t=h[0],i=h[0],n=h[1],s=h[1];for(let e=0;e<h.length;e+=2){const r=h[e],a=h[e+1];t=t>r?r:t;n=n>a?a:n;i=i<r?r:i;s=s<a?a:s}e=[t,n,i,s]}return["Mesh",t,h,d,g,e,u,p]}throw new Error(`Unsupported pattern kind: ${e}`)}}class FontPathInfo{static write(t){let e,i;if(util_FeatureTest.isFloat16ArraySupported){i=new ArrayBuffer(2*t.length);e=new Float16Array(i)}else{i=new ArrayBuffer(4*t.length);e=new Float32Array(i)}e.set(t);return i}#Bi;constructor(t){this.#Bi=t}get path(){return util_FeatureTest.isFloat16ArraySupported?new Float16Array(this.#Bi):new Float32Array(this.#Bi)}}function getFactoryUrlProp(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const isRefProxy=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,J=function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...r]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const a=r.length;let o=!0;switch(s.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const t of r)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,isRefProxy,t=>"object"==typeof t&&"string"==typeof t?.name);class LoopbackPort{#o=new Map;#tn=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#tn.then(()=>{for(const[t]of this.#o)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",onAbort);s.addEventListener("abort",onAbort)}this.#o.set(e,n)}removeEventListener(t,e){const i=this.#o.get(e);i?.();this.#o.delete(e)}terminate(){for(const[,t]of this.#o)t?.();this.#o.clear()}}const Z=1,tt=2,et=1,it=2,nt=3,st=4,rt=5,at=6,ot=7,lt=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof PasswordException||t instanceof ResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"ResponseException":return new ResponseException(t.message,t.status,t.missing);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#en=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#in.bind(this),{signal:this.#en.signal})}#in({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#nn(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===Z)i.resolve(t.data);else{if(t.callback!==tt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:Z,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:tt,callbackId:t.callbackId,reason:wrapReason(e)})});return}t.streamId?this.#sn(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:a,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[s].pullCall=e;o.postMessage({sourceName:r,targetName:a,stream:at,streamId:s,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[s].cancelCall=e;this.streamControllers[s].isClosed=!0;o.postMessage({sourceName:r,targetName:a,stream:et,streamId:s,reason:wrapReason(t)});return e.promise}},i)}#sn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:n,stream:st,streamId:e,chunk:t},a)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:nt,streamId:e});delete r.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:rt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(a,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:lt,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:lt,streamId:e,reason:wrapReason(t)})})}#nn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case lt:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case ot:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case at:if(!a){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve();a.desiredSize=t.desiredSize;Promise.try(a.onPull||onFn).then(function(){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,reason:wrapReason(t)})});break;case st:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case nt:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#rn(r,e);break;case rt:assert(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#rn(r,e);break;case it:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#rn(r,e);break;case et:if(!a)break;const o=wrapReason(t.reason);Promise.try(a.onCancel||onFn,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:it,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:it,streamId:e,reason:wrapReason(t)})});a.sinkCapability.reject(o);a.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#rn(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#en?.abort();this.#en=null}}class BaseCanvasFactory{#an=!1;constructor({enableHWA:t=!1}){this.#an=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#an})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#on;#ln;#hn;#dn;#cn;#un;#I=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#dn=t;this.#cn=e}get#R(){return this.#ln||=new Map}get#pn(){return this.#un||=new Map}get#gn(){if(!this.#hn){const t=this.#cn.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#cn.createElementNS(j,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#hn=this.#cn.createElementNS(j,"defs");t.append(i);i.append(this.#hn);this.#cn.body.append(t)}return this.#hn}#mn(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++){s[t]=e[t]/255;r[t]=i[t]/255;a[t]=n[t]/255}return[s.join(","),r.join(","),a.join(",")]}#fn(t){if(void 0===this.#on){this.#on="";const t=this.#cn.URL;t!==this.#cn.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#on=updateUrlHash(t,""))}return`url(${this.#on}#${t})`}addFilter(t){if(!t)return"none";let e=this.#R.get(t);if(e)return e;const[i,n,s]=this.#mn(t),r=1===t.length?i:`${i}${n}${s}`;e=this.#R.get(r);if(e){this.#R.set(t,e);return e}const a=`g_${this.#dn}_transfer_map_${this.#I++}`,o=this.#fn(a);this.#R.set(t,o);this.#R.set(r,o);const l=this.#bn(a);this.#wn(i,n,s,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#pn.get(n);if(s?.key===i)return s.url;if(s){s.filter?.remove();s.key=i;s.url="none";s.filter=null}else{s={key:i,url:"none",filter:null};this.#pn.set(n,s)}if(!t||!e)return s.url;const r=this.#yn(t);t=Util.makeHexColor(...r);const a=this.#yn(e);e=Util.makeHexColor(...a);this.#gn.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#dn}_hcm_filter`,d=s.filter=this.#bn(h);this.#wn(l,l,l,d);this.#An(d);const getSteps=(t,e)=>{const i=r[t]/255,n=a[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};this.#wn(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);s.url=this.#fn(h);return s.url}addAlphaFilter(t){let e=this.#R.get(t);if(e)return e;const[i]=this.#mn([t]),n=`alpha_${i}`;e=this.#R.get(n);if(e){this.#R.set(t,e);return e}const s=`g_${this.#dn}_alpha_map_${this.#I++}`,r=this.#fn(s);this.#R.set(t,r);this.#R.set(n,r);const a=this.#bn(s);this.#vn(i,a);return r}addLuminosityFilter(t){let e,i,n=this.#R.get(t||"luminosity");if(n)return n;if(t){[e]=this.#mn([t]);i=`luminosity_${e}`}else i="luminosity";n=this.#R.get(i);if(n){this.#R.set(t,n);return n}const s=`g_${this.#dn}_luminosity_map_${this.#I++}`,r=this.#fn(s);this.#R.set(t,r);this.#R.set(i,r);const a=this.#bn(s);this.#xn(a);t&&this.#vn(e,a);return r}addHighlightHCMFilter(t,e,i,n,s){const r=`${e}-${i}-${n}-${s}`;let a=this.#pn.get(t);if(a?.key===r)return a.url;if(a){a.filter?.remove();a.key=r;a.url="none";a.filter=null}else{a={key:r,url:"none",filter:null};this.#pn.set(t,a)}if(!e||!i)return a.url;const[o,l]=[e,i].map(this.#yn.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[n,s].map(this.#yn.bind(this));d<h&&([h,d,c,u]=[d,h,u,c]);this.#gn.style.color="";const getSteps=(t,e,i)=>{const n=new Array(256),s=(d-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=r+t*a;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},p=`g_${this.#dn}_hcm_${t}_filter`,g=a.filter=this.#bn(p);this.#An(g);this.#wn(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);a.url=this.#fn(p);return a.url}destroy(t=!1){if(!t||!this.#un?.size){this.#hn?.parentNode.parentNode.remove();this.#hn=null;this.#ln?.clear();this.#ln=null;this.#un?.clear();this.#un=null;this.#I=0}}#xn(t){const e=this.#cn.createElementNS(j,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#An(t){const e=this.#cn.createElementNS(j,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#bn(t){const e=this.#cn.createElementNS(j,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#gn.append(e);return e}#En(t,e,i){const n=this.#cn.createElementNS(j,e);n.setAttribute("type","discrete");n.setAttribute("tableValues",i);t.append(n)}#wn(t,e,i,n){const s=this.#cn.createElementNS(j,"feComponentTransfer");n.append(s);this.#En(s,"feFuncR",t);this.#En(s,"feFuncG",e);this.#En(s,"feFuncB",i)}#vn(t,e){const i=this.#cn.createElementNS(j,"feComponentTransfer");e.append(i);this.#En(i,"feFuncA",t)}#yn(t){this.#gn.style.color=t;return getRGB(getComputedStyle(this.#gn).getPropertyValue("color"))}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}class BaseWasmFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMWasmFactory extends BaseWasmFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}t&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeWasmFactory extends BaseWasmFactory{async _fetch(t){return node_utils_fetchData(t)}}const ht="__forcedDependency",{floor:dt,ceil:ct}=Math;function expandBBox(t,e,i,n,s,r){t[4*e+0]=Math.min(t[4*e+0],i);t[4*e+1]=Math.min(t[4*e+1],n);t[4*e+2]=Math.max(t[4*e+2],s);t[4*e+3]=Math.max(t[4*e+3],r)}const ut=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Cn;#Sn;constructor(t,e){this.#Cn=t;this.#Sn=e}get length(){return this.#Cn.length}isEmpty(t){return this.#Cn[t]===ut}minX(t){return this.#Sn[4*t+0]/256}minY(t){return this.#Sn[4*t+1]/256}maxX(t){return(this.#Sn[4*t+2]+1)/256}maxY(t){return(this.#Sn[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>{if(!t)return;let i=t.get(e);if(!i){i={dependencies:new Set,isRenderingOperation:!1};t.set(e,i)}return i};class CanvasDependencyTracker{#Tn={__proto__:null};#_n={__proto__:null,transform:[],moveText:[],sameLineText:[],[ht]:[]};#Mn=new Map;#Dn=[];#Pn=[];#kn=[[1,0,0,1,0,0]];#In=[-1/0,-1/0,1/0,1/0];#Fn=new Float64Array([1/0,1/0,-1/0,-1/0]);#Rn=-1;#Bn=new Set;#Ln=new Map;#On=new Map;#Nn;#Un;#Hn;#Cn;#zn;constructor(t,e,i=!1){this.#Nn=t.width;this.#Un=t.height;this.#Gn(e);i&&(this.#zn=new Map)}growOperationsCount(t){t>=this.#Cn.length&&this.#Gn(t,this.#Cn)}#Gn(t,e){const i=new ArrayBuffer(4*t);this.#Hn=new Uint8ClampedArray(i);this.#Cn=new Uint32Array(i);if(e&&e.length>0){this.#Cn.set(e);this.#Cn.fill(ut,e.length)}else this.#Cn.fill(ut)}save(t){this.#Tn={__proto__:this.#Tn};this.#_n={__proto__:this.#_n,transform:{__proto__:this.#_n.transform},moveText:{__proto__:this.#_n.moveText},sameLineText:{__proto__:this.#_n.sameLineText},[ht]:{__proto__:this.#_n[ht]}};this.#In={__proto__:this.#In};this.#Dn.push(t);return this}restore(t){const e=Object.getPrototypeOf(this.#Tn);if(null===e)return this;this.#Tn=e;this.#_n=Object.getPrototypeOf(this.#_n);this.#In=Object.getPrototypeOf(this.#In);const i=this.#Dn.pop();if(void 0!==i){ensureDebugMetadata(this.#zn,t)?.dependencies.add(i);this.#Cn[t]=this.#Cn[i]}return this}recordOpenMarker(t){this.#Dn.push(t);return this}getOpenMarker(){return 0===this.#Dn.length?null:this.#Dn.at(-1)}recordCloseMarker(t){const e=this.#Dn.pop();if(void 0!==e){ensureDebugMetadata(this.#zn,t)?.dependencies.add(e);this.#Cn[t]=this.#Cn[e]}return this}beginMarkedContent(t){this.#Pn.push(t);return this}endMarkedContent(t){const e=this.#Pn.pop();if(void 0!==e){ensureDebugMetadata(this.#zn,t)?.dependencies.add(e);this.#Cn[t]=this.#Cn[e]}return this}pushBaseTransform(t){this.#kn.push(Util.multiplyByDOMMatrix(this.#kn.at(-1),t.getTransform()));return this}popBaseTransform(){this.#kn.length>1&&this.#kn.pop();return this}recordSimpleData(t,e){this.#Tn[t]=e;return this}recordIncrementalData(t,e){this.#_n[t].push(e);return this}resetIncrementalData(t,e){this.#_n[t].length=0;return this}recordNamedData(t,e){this.#Mn.set(t,e);return this}recordSimpleDataFromNamed(t,e,i){this.#Tn[t]=this.#Mn.get(e)??i}recordFutureForcedDependency(t,e){this.recordIncrementalData(ht,e);return this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Tn&&this.recordFutureForcedDependency(e,this.#Tn[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Bn)this.recordFutureForcedDependency(ht,t);return this}resetBBox(t){if(this.#Rn!==t){this.#Rn=t;this.#Fn[0]=1/0;this.#Fn[1]=1/0;this.#Fn[2]=-1/0;this.#Fn[3]=-1/0}return this}recordClipBox(t,e,i,n,s,r){const a=Util.multiplyByDOMMatrix(this.#kn.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,s,n,r],a,o);const l=Util.intersect(this.#In,o);if(l){this.#In[0]=l[0];this.#In[1]=l[1];this.#In[2]=l[2];this.#In[3]=l[3]}else{this.#In[0]=this.#In[1]=1/0;this.#In[2]=this.#In[3]=-1/0}return this}recordBBox(t,e,i,n,s,r){const a=this.#In;if(a[0]===1/0)return this;const o=Util.multiplyByDOMMatrix(this.#kn.at(-1),e.getTransform());if(a[0]===-1/0){Util.axialAlignedBoundingBox([i,s,n,r],o,this.#Fn);return this}const l=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,s,n,r],o,l);this.#Fn[0]=Math.min(this.#Fn[0],Math.max(l[0],a[0]));this.#Fn[1]=Math.min(this.#Fn[1],Math.max(l[1],a[1]));this.#Fn[2]=Math.max(this.#Fn[2],Math.min(l[2],a[2]));this.#Fn[3]=Math.max(this.#Fn[3],Math.min(l[3],a[3]));return this}recordCharacterBBox(t,e,i,n=1,s=0,r=0,a){const o=i.bbox;let l,h;if(o){l=o[2]!==o[0]&&o[3]!==o[1]&&this.#On.get(i);if(!1!==l){h=[0,0,0,0];Util.axialAlignedBoundingBox(o,i.fontMatrix,h);1===n&&0===s&&0===r||Util.scaleMinMax([n,0,0,-n,s,r],h);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}}if(!a)return this.recordFullPageBBox(t);const d=a();if(o&&h&&void 0===l){l=h[0]<=s-d.actualBoundingBoxLeft&&h[2]>=s+d.actualBoundingBoxRight&&h[1]<=r-d.actualBoundingBoxAscent&&h[3]>=r+d.actualBoundingBoxDescent;this.#On.set(i,l);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}return this.recordBBox(t,e,s-d.actualBoundingBoxLeft,s+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(t){this.#Fn[0]=Math.max(0,this.#In[0]);this.#Fn[1]=Math.max(0,this.#In[1]);this.#Fn[2]=Math.min(this.#Nn,this.#In[2]);this.#Fn[3]=Math.min(this.#Un,this.#In[3]);return this}getSimpleIndex(t){return this.#Tn[t]}recordDependencies(t,e){const i=this.#Bn,n=this.#Tn,s=this.#_n;for(const t of e)t in this.#Tn?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){this.#Mn.has(e)&&this.#Bn.add(this.#Mn.get(e));return this}recordOperation(t,e=!1){this.recordDependencies(t,[ht]);if(this.#zn){const e=ensureDebugMetadata(this.#zn,t),{dependencies:i}=e;this.#Bn.forEach(i.add,i);this.#Dn.forEach(i.add,i);this.#Pn.forEach(i.add,i);i.delete(t);e.isRenderingOperation=!0}if(this.#Rn===t){const i=dt(256*this.#Fn[0]/this.#Nn),n=dt(256*this.#Fn[1]/this.#Un),s=ct(256*this.#Fn[2]/this.#Nn),r=ct(256*this.#Fn[3]/this.#Un);expandBBox(this.#Hn,t,i,n,s,r);for(const e of this.#Bn)e!==t&&expandBBox(this.#Hn,e,i,n,s,r);for(const e of this.#Dn)e!==t&&expandBBox(this.#Hn,e,i,n,s,r);for(const e of this.#Pn)e!==t&&expandBBox(this.#Hn,e,i,n,s,r);if(!e){this.#Bn.clear();this.#Rn=-1}}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#Bn);this.recordOperation(t,e);this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){if(this.#Rn===t){this.#Rn=-1;this.#In[0]=Math.max(this.#In[0],this.#Fn[0]);this.#In[1]=Math.max(this.#In[1],this.#Fn[1]);this.#In[2]=Math.min(this.#In[2],this.#Fn[2]);this.#In[3]=Math.min(this.#In[3],this.#Fn[3]);e||this.#Bn.clear()}return this}_takePendingDependencies(){const t=this.#Bn;this.#Bn=new Set;return t}_extractOperation(t){const e=this.#Ln.get(t);this.#Ln.delete(t);return e}_pushPendingDependencies(t){for(const e of t)this.#Bn.add(e)}take(){this.#On.clear();return new BBoxReader(this.#Cn,this.#Hn)}takeDebugMetadata(){return this.#zn}}class CanvasNestedDependencyTracker{#Wn;#Vn;#jn;#$n=0;#Xn=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#jn===!!i)return t;this.#Wn=t;this.#Vn=e;this.#jn=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){this.#Xn++;this.#Wn.save(this.#Vn);return this}restore(t){if(this.#Xn>0){this.#Wn.restore(this.#Vn);this.#Xn--}return this}recordOpenMarker(t){this.#$n++;return this}getOpenMarker(){return this.#$n>0?this.#Vn:this.#Wn.getOpenMarker()}recordCloseMarker(t){this.#$n--;return this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){this.#Wn.pushBaseTransform(t);return this}popBaseTransform(){this.#Wn.popBaseTransform();return this}recordSimpleData(t,e){this.#Wn.recordSimpleData(t,this.#Vn);return this}recordIncrementalData(t,e){this.#Wn.recordIncrementalData(t,this.#Vn);return this}resetIncrementalData(t,e){this.#Wn.resetIncrementalData(t,this.#Vn);return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){this.#Wn.recordSimpleDataFromNamed(t,e,this.#Vn);return this}recordFutureForcedDependency(t,e){this.#Wn.recordFutureForcedDependency(t,this.#Vn);return this}inheritSimpleDataAsFutureForcedDependencies(t){this.#Wn.inheritSimpleDataAsFutureForcedDependencies(t);return this}inheritPendingDependenciesAsFutureForcedDependencies(){this.#Wn.inheritPendingDependenciesAsFutureForcedDependencies();return this}resetBBox(t){this.#jn||this.#Wn.resetBBox(this.#Vn);return this}recordClipBox(t,e,i,n,s,r){this.#jn||this.#Wn.recordClipBox(this.#Vn,e,i,n,s,r);return this}recordBBox(t,e,i,n,s,r){this.#jn||this.#Wn.recordBBox(this.#Vn,e,i,n,s,r);return this}recordCharacterBBox(t,e,i,n,s,r,a){this.#jn||this.#Wn.recordCharacterBBox(this.#Vn,e,i,n,s,r,a);return this}recordFullPageBBox(t){this.#jn||this.#Wn.recordFullPageBBox(this.#Vn);return this}getSimpleIndex(t){return this.#Wn.getSimpleIndex(t)}recordDependencies(t,e){this.#Wn.recordDependencies(this.#Vn,e);return this}recordNamedDependency(t,e){this.#Wn.recordNamedDependency(this.#Vn,e);return this}recordOperation(t){this.#Wn.recordOperation(this.#Vn,!0);return this}recordShowTextOperation(t){this.#Wn.recordShowTextOperation(this.#Vn,!0);return this}bboxToClipBoxDropOperation(t){this.#jn||this.#Wn.bboxToClipBoxDropOperation(this.#Vn,!0);return this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const pt=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],gt=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],mt=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],ft=["filter","fillColor","fillAlpha"],bt=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],wt=["transform"],yt=["transform","fillColor"],At="Fill",vt="Stroke",xt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n);t.clip(s)}class BaseShadingPattern{isModifyingCurrentTransform(){return!1}getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}_createGradient(t,e=null){let i,n=this._p0,s=this._p1;if(e){n=n.slice();s=s.slice();Util.applyTransform(n,e);Util.applyTransform(s,e)}if("axial"===this._type)i=t.createLinearGradient(n[0],n[1],s[0],s[1]);else if("radial"===this._type){let r=this._r0,a=this._r1;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t);r*=t[0];a*=t[0]}i=t.createRadialGradient(n[0],n[1],r,s[0],s[1],a)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}getPattern(t,e,i,n){let s;if(n===vt||n===At){if(this.isOriginBased()){let n=Util.transform(i,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix));const s=.001,r=Math.hypot(n[0],n[1]),a=Math.hypot(n[2],n[3]),o=(n[0]*n[2]+n[1]*n[3])/(r*a);if(Math.abs(o)<s){if(!this.isRadial())return this._createGradient(t,n);if(Math.abs(r-a)<s)return this._createGradient(t,n)}}const r=e.current.getClippedPathBoundingBox(n,getCurrentTransform(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",a,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-r[0],-r[1]);i=Util.transform(i,[1,0,0,1,r[0],r[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();s=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);s.setTransform(d)}else{applyBoundingBox(t,this._bbox);s=this._createGradient(t)}return s}}function drawTriangle(t,e,i,n,s,r,a,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[n+1]){u=i;i=n;n=u;u=r;r=a;a=u}if(l[n+1]>l[s+1]){u=n;n=s;s=u;u=a;a=o;o=u}if(l[i+1]>l[n+1]){u=i;i=n;n=u;u=r;r=a;a=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,w=(l[s+1]+e.offsetY)*e.scaleY;if(g>=w)return;const y=h[r],A=h[r+1],v=h[r+2],x=h[a],E=h[a+1],C=h[a+2],S=h[o],T=h[o+1],_=h[o+2],M=Math.round(g),D=Math.round(w);let P,k,I,F,R,B,L,O;for(let t=M;t<=D;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);P=p-(p-m)*e;k=y-(y-x)*e;I=A-(A-E)*e;F=v-(v-C)*e}else{let e;e=t>w?1:f===w?0:(f-t)/(f-w);P=m-(m-b)*e;k=x-(x-S)*e;I=E-(E-T)*e;F=C-(C-_)*e}let e;e=t<g?0:t>w?1:(g-t)/(g-w);R=p-(p-b)*e;B=y-(y-S)*e;L=A-(A-T)*e;O=v-(v-_)*e;const i=Math.round(Math.min(P,R)),n=Math.round(Math.max(P,R));let s=c*t+4*i;for(let t=i;t<=n;t++){e=(P-t)/(P-R);e<0?e=0:e>1&&(e=1);d[s++]=k-(k-B)*e|0;d[s++]=I-(I-L)*e|0;d[s++]=F-(F-O)*e|0;d[s++]=255}}}function drawFigure(t,e,i){const n=e.coords,s=e.colors;let r,a;switch(e.type){case b:const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(r=0;r<l;r++){let e=r*o;for(let r=0;r<h;r++,e++){drawTriangle(t,i,n[e],n[e+1],n[e+o],s[e],s[e+1],s[e+o]);drawTriangle(t,i,n[e+o+1],n[e+1],n[e+o],s[e+o+1],s[e+1],s[e+o])}}break;case f:for(r=0,a=n.length;r<a;r+=3)drawTriangle(t,i,n[r],n[r+1],n[r+2],s[r],s[r+1],s[r+2]);break;default:throw new Error("illegal figure")}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._coords=t[2];this._colors=t[3];this._figures=t[4];this._bounds=t[5];this._bbox=t[6];this._background=t[7];this.matrix=null}_createMeshCanvas(t,e,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-n,a=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3),h=r/o,d=a/l,c={coords:this._coords,colors:this._colors,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,n=t.length;i<n;i+=4){t[i]=e[0];t[i+1]=e[1];t[i+2]=e[2];t[i+3]=255}}for(const t of this._figures)drawFigure(f,t,c);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*d,scaleX:h,scaleY:d}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,n){applyBoundingBox(t,this._bbox);const s=new Float32Array(2);if(n===xt)Util.singularValueDecompose2dScale(getCurrentTransform(t),s);else if(this.matrix){Util.singularValueDecompose2dScale(this.matrix,s);const[t,i]=s;Util.singularValueDecompose2dScale(e.baseTransform,s);s[0]*=t;s[1]*=i}else Util.singularValueDecompose2dScale(e.baseTransform,s);const r=this._createMeshCanvas(s,n===xt?null:this._background,e.cachedCanvases);if(n!==xt){t.setTransform(...e.baseTransform);this.matrix&&t.transform(...this.matrix)}t.translate(r.offsetX,r.offsetY);t.scale(r.scaleX,r.scaleY);return t.createPattern(r.canvas,"no-repeat")}}class DummyShadingPattern extends BaseShadingPattern{getPattern(){return"hotpink"}}const Et=1,Ct=2;class TilingPattern{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n){this.color=t[1];this.operatorList=t[2];this.matrix=t[3];this.bbox=t[4];this.xstep=t[5];this.ystep=t[6];this.paintType=t[7];this.tilingType=t[8];this.ctx=e;this.canvasGraphicsFactory=i;this.baseTransform=n}createPatternCanvas(t,e){const{bbox:i,operatorList:n,paintType:s,tilingType:r,color:a,canvasGraphicsFactory:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l);h=Math.abs(h);info("TilingType: "+r);const d=i[0],c=i[1],u=i[2],p=i[3],g=u-d,m=p-c,f=new Float32Array(2);Util.singularValueDecompose2dScale(this.matrix,f);const[b,w]=f;Util.singularValueDecompose2dScale(this.baseTransform,f);const y=b*f[0],A=w*f[1];let v=g,x=m,E=!1,C=!1;const S=Math.ceil(l*y),T=Math.ceil(h*A);S>=Math.ceil(g*y)?v=l:E=!0;T>=Math.ceil(m*A)?x=h:C=!0;const _=this.getSizeAndScale(v,this.ctx.canvas.width,y),M=this.getSizeAndScale(x,this.ctx.canvas.height,A),D=t.cachedCanvases.getCanvas("pattern",_.size,M.size),P=D.context,k=o.createCanvasGraphics(P,e);k.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(k,s,a);P.translate(-_.scale*d,-M.scale*c);k.transform(0,_.scale,0,0,M.scale,0,0);P.save();k.dependencyTracker?.save();this.clipBbox(k,d,c,u,p);k.baseTransform=getCurrentTransform(k.ctx);k.executeOperatorList(n);k.endDrawing();k.dependencyTracker?.restore();P.restore();if(E||C){const e=D.canvas;E&&(v=l);C&&(x=h);const i=this.getSizeAndScale(v,this.ctx.canvas.width,y),n=this.getSizeAndScale(x,this.ctx.canvas.height,A),s=i.size,r=n.size,a=t.cachedCanvases.getCanvas("pattern-workaround",s,r),o=a.context,u=E?Math.floor(g/l):0,p=C?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,r*i,s,r,0,0,s,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:d,offsetY:c}}return{canvas:D.canvas,scaleX:_.scale,scaleY:M.scale,offsetX:d,offsetY:c}}getSizeAndScale(t,e,i){const n=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);s>=n?s=n:i=s/t;return{scale:i,size:s}}clipBbox(t,e,i,n,s){const r=n-e,a=s-i;t.ctx.rect(e,i,r,a);Util.axialAlignedBoundingBox([e,i,n,s],getCurrentTransform(t.ctx),t.current.minMax);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;switch(e){case Et:const{fillStyle:t,strokeStyle:r}=this.ctx;n.fillStyle=s.fillColor=t;n.strokeStyle=s.strokeColor=r;break;case Ct:n.fillStyle=n.strokeStyle=i;s.fillColor=s.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){let r=i;if(n!==xt){r=Util.transform(r,e.baseTransform);this.matrix&&(r=Util.transform(r,this.matrix))}const a=this.createPatternCanvas(e,s);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY);o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");l.setTransform(o);return l}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],d=n>>3,c=7&n,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let n=0;n<s;n++){for(const n=e+d;e<n;e++){const n=e<u?t[e]:255;i[p++]=128&n?h:l;i[p++]=64&n?h:l;i[p++]=32&n?h:l;i[p++]=16&n?h:l;i[p++]=8&n?h:l;i[p++]=4&n?h:l;i[p++]=2&n?h:l;i[p++]=1&n?h:l}if(0===c)continue;const n=e<u?t[e++]:255;for(let t=0;t<c;t++)i[p++]=n&1<<7-t?h:l}return{srcPos:e,destPos:p}}const St=16,Tt=new DOMMatrix,_t=new Float32Array(2),Mt=new Float32Array([1/0,1/0,-1/0,-1/0]);class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,i){let n;if(void 0!==this.cache[t]){n=this.cache[t];this.canvasFactory.reset(n,e,i)}else{n=this.canvasFactory.create(e,i);this.cache[t]=n}return n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,i,n,s,r,a,o,l,h){const[d,c,u,p,g,m]=getCurrentTransform(t);if(0===c&&0===u){const f=a*d+g,b=Math.round(f),w=o*p+m,y=Math.round(w),A=(a+l)*d+g,v=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(Math.sign(d),0,0,Math.sign(p),b,y);t.drawImage(e,i,n,s,r,0,0,v,E);t.setTransform(d,c,u,p,g,m);return[v,E]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),w=a*c+m,y=Math.round(w),A=(o+h)*u+g,v=Math.abs(Math.round(A)-b)||1,x=(a+l)*c+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(0,Math.sign(c),Math.sign(u),0,b,y);t.drawImage(e,i,n,s,r,0,0,E,v);t.setTransform(d,c,u,p,g,m);return[E,v]}t.drawImage(e,i,n,s,r,a,o,l,h);return[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}class CanvasExtraState{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=e;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=w;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this);this.clipBox=new Float32Array([0,0,t,e]);this.minMax=Mt.slice()}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();t.minMax=this.minMax.slice();return t}getPathBoundingBox(t=At,e=null){const i=this.minMax.slice();if(t===vt){e||unreachable("Stroke bounding box must include transform.");Util.singularValueDecompose2dScale(e,_t);const t=_t[0]*this.lineWidth/2,n=_t[1]*this.lineWidth/2;i[0]-=t;i[1]-=n;i[2]+=t;i[3]+=n}return i}updateClipFromPath(){const t=Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0);this.minMax.set(Mt,0)}getClippedPathBoundingBox(t=At,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}const i=e.height,n=e.width,s=i%St,r=(i-s)/St,a=0===s?r:r+1,o=t.createImageData(n,St);let l,h=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===C.GRAYSCALE_1BPP){const e=d.byteLength,i=new Uint32Array(c.buffer,0,c.byteLength>>2),m=i.length,f=n+7>>3,b=4294967295,w=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;u<a;u++){g=u<r?St:s;l=0;for(p=0;p<g;p++){const t=e-h;let s=0;const r=t>f?n:8*t-7,a=-8&r;let o=0,c=0;for(;s<a;s+=8){c=d[h++];i[l++]=128&c?b:w;i[l++]=64&c?b:w;i[l++]=32&c?b:w;i[l++]=16&c?b:w;i[l++]=8&c?b:w;i[l++]=4&c?b:w;i[l++]=2&c?b:w;i[l++]=1&c?b:w}for(;s<r;s++){if(0===o){c=d[h++];o=128}i[l++]=c&o?b:w;o>>=1}}for(;l<m;)i[l++]=0;t.putImageData(o,0,u*St)}}else if(e.kind===C.RGBA_32BPP){p=0;m=n*St*4;for(u=0;u<r;u++){c.set(d.subarray(h,h+m));h+=m;t.putImageData(o,0,p);p+=St}if(u<a){m=n*s*4;c.set(d.subarray(h,h+m));t.putImageData(o,0,p)}}else{if(e.kind!==C.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);g=St;m=n*g;for(u=0;u<a;u++){if(u>=r){g=s;m=n*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*St)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,n=e.width,s=i%St,r=(i-s)/St,a=0===s?r:r+1,o=t.createImageData(n,St);let l=0;const h=e.data,d=o.data;for(let e=0;e<a;e++){const i=e<r?St:s;({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:d,width:n,height:i,nonBlackColor:0}));t.putImageData(o,0,e*St)}}function copyCtxState(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);if(void 0!==t.setLineDash){e.setLineDash(t.getLineDash());e.lineDashOffset=t.lineDashOffset}}function resetCtxToDefault(t){t.strokeStyle=t.fillStyle="#000000";t.fillRule="nonzero";t.globalAlpha=1;t.lineWidth=1;t.lineCap="butt";t.lineJoin="miter";t.miterLimit=10;t.globalCompositeOperation="source-over";t.font="10px sans-serif";if(void 0!==t.setLineDash){t.setLineDash([]);t.lineDashOffset=0}const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function getImageSmoothingEnabled(t,e){if(e)return!0;Util.singularValueDecompose2dScale(t,_t);const i=Math.fround(OutputScale.pixelRatio*PixelsPerInch.PDF_TO_CSS_UNITS);return _t[0]<=i&&_t[1]<=i}const Dt=["butt","round","square"],Pt=["miter","round","bevel"],kt={},It={};class CanvasGraphics{constructor(t,e,i,n,s,{optionalContentConfig:r,markedContentStack:a=null},o,l,h){this.ctx=t;this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.stateStack=[];this.pendingClip=null;this.pendingEOFill=!1;this.res=null;this.xobjs=null;this.commonObjs=e;this.objs=i;this.canvasFactory=n;this.filterFactory=s;this.groupStack=[];this.baseTransform=null;this.baseTransformStack=[];this.groupLevel=0;this.smaskStack=[];this.smaskCounter=0;this.tempSMask=null;this.suspendedCtx=null;this.contentVisible=!0;this.markedContentStack=a||[];this.optionalContentConfig=r;this.cachedCanvases=new CachedCanvases(this.canvasFactory);this.cachedPatterns=new Map;this.annotationCanvasMap=o;this.viewportScale=1;this.outputScaleX=1;this.outputScaleY=1;this.pageColors=l;this._cachedScaleForStroking=[-1,0];this._cachedGetSinglePixelWidth=null;this._cachedBitmapsMap=new Map;this.dependencyTracker=h??null}getObject(t,e,i=null){if("string"==typeof e){this.dependencyTracker?.recordNamedDependency(t,e);return e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)}return i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const s=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;this.ctx.fillStyle=n||"#ffffff";this.ctx.fillRect(0,0,s,r);this.ctx.fillStyle=a;if(i){const t=this.cachedCanvases.getCanvas("transparent",s,r);this.compositeCtx=this.ctx;this.transparentCanvas=t.canvas;this.ctx=t.context;this.ctx.save();this.ctx.transform(...getCurrentTransform(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[0]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=getCurrentTransform(this.ctx)}executeOperatorList(t,e,i,n,s){const r=t.argsArray,a=t.fnArray;let o=e||0;const l=r.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,d=h?Date.now()+15:0;let c=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n&&o===n.nextBreakPoint){n.breakIt(o,i);return o}if(!s||s(o)){g=a[o];m=r[o]??null;if(g!==I.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,i);return o}}}o++;if(o===l)return o;if(h&&++c>10){if(Date.now()>d){i();return o}c=0}}}#qn(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#qn();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#Kn()}#Kn(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight;let s,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,d="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;if(a>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);a/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}s=this.cachedCanvases.getCanvas(d,e,i);r=s.context;r.clearRect(0,0,e,i);r.drawImage(t,0,0,l,h,0,0,e,i);t=s.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:n,height:s}=e,r=this.current.fillColor,a=this.current.patternFill,o=getCurrentTransform(i);let l,h,d,c;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(a?o:[o.slice(0,4),r]);l=this._cachedBitmapsMap.get(i);if(!l){l=new Map;this._cachedBitmapsMap.set(i,l)}const n=l.get(h);if(n&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);this.dependencyTracker?.recordDependencies(t,yt);return{canvas:n,offsetX:e,offsetY:i}}d=n}if(!d){c=this.cachedCanvases.getCanvas("maskCanvas",n,s);putBinaryImageMask(c.context,e)}let u=Util.transform(o,[1/n,0,0,-1/s,0,0]);u=Util.transform(u,[1,0,0,1,0,-s]);const p=Mt.slice();Util.axialAlignedBoundingBox([0,0,n,s],u,p);const[g,m,f,b]=p,w=Math.round(f-g)||1,y=Math.round(b-m)||1,A=this.cachedCanvases.getCanvas("fillCanvas",w,y),v=A.context,x=g,E=m;v.translate(-x,-E);v.transform(...u);if(!d){d=this._scaleImage(c.canvas,getCurrentTransformInverse(v));d=d.img;l&&a&&l.set(h,d)}v.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(v),e.interpolate);drawImageAtIntegerCoords(v,d,0,0,d.width,d.height,0,0,n,s);v.globalCompositeOperation="source-in";const C=Util.transform(getCurrentTransformInverse(v),[1,0,0,1,-x,-E]);v.fillStyle=a?r.getPattern(i,this,C,At,t):r;v.fillRect(0,0,n,s);if(l&&!a){this.cachedCanvases.delete("fillCanvas");l.set(h,A.canvas)}this.dependencyTracker?.recordDependencies(t,yt);return{canvas:A.canvas,offsetX:Math.round(x),offsetY:Math.round(E)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t);e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=e;this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t);this.ctx.lineCap=Dt[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t);this.ctx.lineJoin=Pt[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t);this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;if(void 0!==n.setLineDash){n.setLineDash(e);n.lineDashOffset=i}}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t);this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t);this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t);this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t);this.current.activeSMask=n?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t);this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,n="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(n,e,i);this.suspendedCtx=this.ctx;const r=this.ctx=s.context;r.setTransform(this.suspendedCtx.getTransform());copyCtxState(this.suspendedCtx,r);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function(){e.save();this.__originalSave()};t.restore=function(){e.restore();this.__originalRestore()};t.translate=function(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function(t,i,n,s,r,a){e.transform(t,i,n,s,r,a);this.__originalTransform(t,i,n,s,r,a)};t.setTransform=function(t,i,n,s,r,a){e.setTransform(t,i,n,s,r,a);this.__originalSetTransform(t,i,n,s,r,a)};t.resetTransform=function(){e.resetTransform();this.__originalResetTransform()};t.rotate=function(t){e.rotate(t);this.__originalRotate(t)};t.clip=function(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,n,s,r,a){e.bezierCurveTo(t,i,n,s,r,a);this.__originalBezierCurveTo(t,i,n,s,r,a)};t.rect=function(t,i,n,s){e.rect(t,i,n,s);this.__originalRect(t,i,n,s)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(r,this.suspendedCtx);this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,n){const s=n[0],r=n[1],a=n[2]-s,o=n[3]-r;if(0!==a&&0!==o){this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,s,r,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,n,s,r,a,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(r)if(u<0||p<0||u+i>c.width||p+n>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,n),e=t.context;e.drawImage(c,-u,-p);e.globalCompositeOperation="destination-atop";e.fillStyle=r;e.fillRect(0,0,i,n);e.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,n);t.clip(e);t.globalCompositeOperation="destination-atop";t.fillStyle=r;t.fillRect(u,p,i,n);t.restore()}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===s&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===s&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,n);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,n,o,l,i,n);e.restore()}save(t){this.inSMaskMode&&copyCtxState(this.ctx,this.suspendedCtx);this.ctx.save();const e=this.current;this.stateStack.push(e);this.current=e.clone();this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t);if(0!==this.stateStack.length){this.current=this.stateStack.pop();this.ctx.restore();this.inSMaskMode&&copyCtxState(this.suspendedCtx,this.ctx);this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}else this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,r,a){this.dependencyTracker?.recordIncrementalData("transform",t);this.ctx.transform(e,i,n,s,r,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(n){if(null!==this.dependencyTracker){const i=e===I.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}s instanceof Path2D||(s=i[0]=makePathFromDrawOPS(s));Util.axialAlignedBoundingBox(n,getCurrentTransform(this.ctx),this.current.minMax);this[e](t,s);this._pathStartIdx=t}else{s||=i[0]=new Path2D;this[e](t,s)}}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=this.ctx,s=this.current.strokeColor;n.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof s&&s?.getPattern){const i=s.isModifyingCurrentTransform()?n.getTransform():null;n.save();n.strokeStyle=s.getPattern(n,this,getCurrentTransformInverse(n),vt,t);if(i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i));e=t}this.rescaleAndStroke(e,!1);n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,pt);i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(vt,getCurrentTransform(this.ctx)));n.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=this.ctx,s=this.current.fillColor;let r=!1;if(this.current.patternFill){const i=s.isModifyingCurrentTransform()?n.getTransform():null;this.dependencyTracker?.save(t);n.save();n.fillStyle=s.getPattern(n,this,getCurrentTransformInverse(n),At,t);if(i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i));e=t}r=!0}const a=this.current.getClippedPathBoundingBox();if(this.contentVisible&&null!==a)if(this.pendingEOFill){n.fill(e,"evenodd");this.pendingEOFill=!1}else n.fill(e);this.dependencyTracker?.recordDependencies(t,gt);if(r){n.restore();this.dependencyTracker?.restore(t)}i&&this.consumePath(t,e,a)}eoFill(t,e){this.pendingEOFill=!0;this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1);this.stroke(t,e,!1);this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e);this.dependencyTracker?.recordDependencies(t,ft).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=kt}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=It}beginText(t){this.current.textMatrix=null;this.current.textMatrixScale=1;this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0;this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t);i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,r).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t);this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t);this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t);this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t);this.current.leading=-e}setFont(t,i,n){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",i,t);const s=this.commonObjs.get(i),r=this.current;if(!s)throw new Error(`Can't find font for ${i}`);r.fontMatrix=s.fontMatrix||e;0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||warn("Invalid font matrix for font "+i);if(n<0){n=-n;r.fontDirection=-1}else r.fontDirection=1;this.current.font=s;this.current.fontSize=n;if(s.isType3Font)return;const a=s.loadedName||"sans-serif",o=s.systemFontInfo?.css||`"${a}", ${s.fallbackName}`;let l="normal";s.black?l="900":s.bold&&(l="bold");const h=s.italic?"italic":"normal";let d=n;n<16?d=16:n>100&&(d=100);this.current.fontSizeScale=n/d;this.ctx.font=`${h} ${l} ${d}px ${o}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t);this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t);this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t);this.current.x=this.current.lineX+=e;this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i);this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e;i.textMatrixScale=Math.hypot(e[0],e[1]);i.x=i.lineX=0;i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading);this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#Yn(t,e,i){const n=new Path2D;n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return n}paintChar(t,e,i,n,s,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,d=o.fontSize/o.fontSizeScale,c=h&x,u=!!(h&E),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;(l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e));if(m&&(l.disableFontFace||p||g)){a.save();a.translate(i,n);a.scale(d,-d);this.dependencyTracker?.recordCharacterBBox(t,a,l);let e;if(c===w||c===A)if(s){e=a.getTransform();a.setTransform(...s);const t=this.#Yn(m,e,s);a.fill(t)}else a.fill(m);if(c===y||c===A)if(r){e||=a.getTransform();a.setTransform(...r);const{a:t,b:i,c:n,d:s}=e,o=Util.inverseTransform(r),l=Util.transform([t,i,n,s,0,0],o);Util.singularValueDecompose2dScale(l,_t);a.lineWidth*=Math.max(_t[0],_t[1])/d;a.stroke(this.#Yn(m,e,r))}else{a.lineWidth/=d;a.stroke(m)}a.restore()}else{if(c===w||c===A){a.fillText(e,i,n);this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n,()=>a.measureText(e))}if(c===y||c===A){this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n,()=>a.measureText(e)).recordDependencies(t,pt);a.strokeText(e,i,n)}}if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:i,y:n,fontSize:d,path:m});this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t,e){if(this.dependencyTracker){this.dependencyTracker.recordDependencies(t,bt).resetBBox(t);this.current.textRenderingMode&E&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies()}const i=this.current,n=i.font;if(n.isType3Font){this.showType3Text(t,e);this.dependencyTracker?.recordShowTextOperation(t);return}const s=i.fontSize;if(0===s){this.dependencyTracker?.recordOperation(t);return}const r=this.ctx,a=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,d=i.textHScale*h,c=e.length,u=n.vertical,p=u?1:-1,g=n.defaultVMetrics,m=s*i.fontMatrix[0],f=i.textRenderingMode===w&&!n.disableFontFace&&!i.patternFill;r.save();i.textMatrix&&r.transform(...i.textMatrix);r.translate(i.x,i.y+i.textRise);h>0?r.scale(d,-1):r.scale(d,1);let b,v;const C=i.textRenderingMode&x,S=C===y||C===A;if((C===w||C===A)&&i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,getCurrentTransformInverse(r),At,t);b=getCurrentTransform(r);r.restore();r.fillStyle=e}if(S&&i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,getCurrentTransformInverse(r),vt,t);v=getCurrentTransform(r);r.restore();r.strokeStyle=e}let T=i.lineWidth;const _=i.textMatrixScale;0===_||0===T?S&&(T=this.getSinglePixelWidth()):T/=_;if(1!==a){r.scale(a,a);T/=a}r.lineWidth=T;if(n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e){n.push(t.unicode);s+=t.width}const a=n.join("");r.fillText(a,0,0);if(null!==this.dependencyTracker){const e=r.measureText(a);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}i.x+=s*m*d;r.restore();this.compose();return}let M,D=0;for(M=0;M<c;++M){const i=e[M];if("number"==typeof i){D+=p*i*s/1e3;continue}let d=!1;const c=(i.isSpace?l:0)+o,w=i.fontChar,y=i.accent;let A,x,E,C=i.width;if(u){const t=i.vmetric||g,e=-(i.vmetric?t[1]:.5*C)*m,n=t[2]*m;C=t?-t[0]:C;A=e/a;x=(D+n)/a}else{A=D/a;x=0}if(n.remeasure&&C>0){E=r.measureText(w);const t=1e3*E.width/s*a;if(C<t&&this.isFontSubpixelAAEnabled){const e=C/t;d=!0;r.save();r.scale(e,1);A/=e}else C!==t&&(A+=(C-t)/2e3*s/a)}if(this.contentVisible&&(i.isInFont||n.missingFile))if(f&&!y){r.fillText(w,A,x);this.dependencyTracker?.recordCharacterBBox(t,r,E?{bbox:null}:n,s/a,A,x,()=>E??r.measureText(w))}else{this.paintChar(t,w,A,x,b,v);if(y){const e=A+s*y.offset.x/a,i=x-s*y.offset.y/a;this.paintChar(t,y.fontChar,e,i,b,v)}}D+=u?C*m-c*h:C*m+c*h;d&&r.restore()}u?i.y-=D:i.x+=D*d;r.restore();this.compose();this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,i){const n=this.ctx,s=this.current,r=s.font,a=s.fontSize,o=s.fontDirection,l=r.vertical?1:-1,h=s.charSpacing,d=s.wordSpacing,c=s.textHScale*o,u=s.fontMatrix||e,p=i.length;let g,m,f,b;if(s.textRenderingMode===v||0===a)return;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;n.save();s.textMatrix&&n.transform(...s.textMatrix);n.translate(s.x,s.y+s.textRise);n.scale(c,o);const w=this.dependencyTracker;this.dependencyTracker=w?new CanvasNestedDependencyTracker(w,t):null;for(g=0;g<p;++g){m=i[g];if("number"==typeof m){b=l*m*a/1e3;this.ctx.translate(b,0);s.x+=b*c;continue}const t=(m.isSpace?d:0)+h,e=r.charProcOperatorList[m.operatorListId];if(e){if(this.contentVisible){this.save();n.scale(a,a);n.transform(...u);this.executeOperatorList(e);this.restore()}}else warn(`Type3 character "${m.operatorListId}" is not available.`);const o=[m.width,0];Util.applyTransform(o,u);f=o[0]*a+t;n.translate(f,0);s.x+=f*c}n.restore();w&&(this.dependencyTracker=w)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,n,s,r,a){const o=new Path2D;o.rect(n,s,r-n,a-s);this.ctx.clip(o);this.dependencyTracker?.recordBBox(t,this.ctx,n,r,s,a).recordClipBox(t,this.ctx,n,r,s,a);this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||getCurrentTransform(this.ctx),n={createCanvasGraphics:(t,e)=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new CanvasNestedDependencyTracker(this.dependencyTracker,e,!0):null)};i=new TilingPattern(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.current.strokeColor=this.getColorN_Pattern(t,e);this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor=e;this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor=e;this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e,i=null){let n;if(this.cachedPatterns.has(e))n=this.cachedPatterns.get(e);else{n=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e));this.cachedPatterns.set(e,n)}i&&(n.matrix=i);return n}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,getCurrentTransformInverse(i),xt,t);const s=getCurrentTransformInverse(i);if(s){const{width:t,height:e}=i.canvas,n=Mt.slice();Util.axialAlignedBoundingBox([0,0,t,e],s,n);const[r,a,o,l]=n;this.ctx.fillRect(r,a,o-r,l-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,wt).recordDependencies(t,gt).recordOperation(t);this.compose(this.current.getClippedPathBoundingBox());this.restore(t)}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible){this.save(t);this.baseTransformStack.push(this.baseTransform);e&&this.transform(t,...e);this.baseTransform=getCurrentTransform(this.ctx);if(i){Util.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,r]=i,a=new Path2D;a.rect(e,n,s-e,r-n);this.ctx.clip(a);this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,r);this.endPath(t)}}}paintFormXObjectEnd(t){if(this.contentVisible){this.restore(t);this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const i=this.ctx;e.isolated||info("TODO: Support non-isolated groups.");e.knockout&&warn("Knockout groups not supported.");const n=getCurrentTransform(i);e.matrix&&i.transform(...e.matrix);if(!e.bbox)throw new Error("Bounding box is required.");let s=Mt.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(i),s);const r=[0,0,i.canvas.width,i.canvas.height];s=Util.intersect(s,r)||[0,0,0,0];const a=Math.floor(s[0]),o=Math.floor(s[1]),l=Math.max(Math.ceil(s[2])-a,1),h=Math.max(Math.ceil(s[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let d="groupAt"+this.groupLevel;e.smask&&(d+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(d,l,h),u=c.context;u.translate(-a,-o);u.transform(...n);let p=new Path2D;const[g,m,f,b]=e.bbox;p.rect(g,m,f-g,b-m);if(e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix));p=t}u.clip(p);e.smask&&this.smaskStack.push({canvas:c.canvas,context:u,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null});if(!e.smask||this.dependencyTracker){i.setTransform(1,0,0,1,0,0);i.translate(a,o);i.save()}copyCtxState(i,u);this.ctx=u;this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i);this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(i);this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop();this.ctx=n;this.ctx.imageSmoothingEnabled=!1;this.dependencyTracker?.popBaseTransform();if(e.smask){this.tempSMask=this.smaskStack.pop();this.restore(t);this.dependencyTracker&&this.ctx.restore()}else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t);this.ctx.save();this.ctx.setTransform(...e);const n=Mt.slice();Util.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n);this.ctx.drawImage(i.canvas,0,0);this.ctx.restore();this.compose(n)}}beginAnnotation(t,e,i,n,s,r){this.#qn();resetCtxToDefault(this.ctx);this.ctx.save();this.save(t);this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(i){const s=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0];n[5]-=i[1];(i=i.slice())[0]=i[1]=0;i[2]=s;i[3]=a;Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),_t);const{viewportScale:t}=this,r=Math.ceil(s*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l);this.annotationCanvas.savedCtx=this.ctx;this.ctx=h;this.ctx.save();this.ctx.setTransform(_t[0],0,0,-_t[1],0,a*_t[1]);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,a);this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(t,...n);this.transform(t,...s)}endAnnotation(t){if(this.annotationCanvas){this.ctx.restore();this.#Kn();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.ctx,s=this._createMaskCanvas(t,e),r=s.canvas;n.save();n.setTransform(1,0,0,1,0,0);n.drawImage(r,s.offsetX,s.offsetY);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,s.offsetX,s.offsetX+r.width,s.offsetY,s.offsetY+r.height).recordOperation(t);n.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=getCurrentTransform(o);o.transform(i,n,s,r,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]);this.dependencyTracker?.resetBBox(t);for(let e=0,d=a.length;e<d;e+=2){const d=Util.transform(l,[i,n,s,r,a[e],a[e+1]]);o.drawImage(h.canvas,d[4],d[5]);this.dependencyTracker?.recordBBox(t,this.ctx,d[4],d[4]+h.canvas.width,d[5],d[5]+h.canvas.height)}o.restore();this.compose();this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx,n=this.current.fillColor,s=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,yt);for(const r of e){const{data:e,width:a,height:o,transform:l}=r,h=this.cachedCanvases.getCanvas("maskCanvas",a,o),d=h.context;d.save();putBinaryImageMask(d,this.getObject(t,e,r));d.globalCompositeOperation="source-in";d.fillStyle=s?n.getPattern(d,this,getCurrentTransformInverse(i),At,t):n;d.fillRect(0,0,a,o);d.restore();i.save();i.transform(...l);i.scale(1,-1);drawImageAtIntegerCoords(i,h.canvas,0,0,a,o,0,-1,1,1);this.dependencyTracker?.recordBBox(t,i,0,a,0,o);i.restore()}this.compose();this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):warn("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,n,s){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r){warn("Dependent image isn't ready yet");return}const a=r.width,o=r.height,l=[];for(let t=0,e=s.length;t<e;t+=2)l.push({transform:[i,0,0,n,s[t],s[t+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,l)}applyTransferMapsToCanvas(t){if("none"!==this.current.transferMaps){t.filter=this.current.transferMaps;t.drawImage(t.canvas,0,0);t.filter="none"}return t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:n}=t,s=this.cachedCanvases.getCanvas("inlineImage",i,n),r=s.context;r.filter=this.current.transferMaps;r.drawImage(e,0,0);r.filter="none";return s.canvas}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,n=e.height,s=this.ctx;this.save(t);const{filter:r}=s;"none"!==r&&""!==r&&(s.filter="none");s.scale(1/i,-1/n);let a;if(e.bitmap)a=this.applyTransferMapsToBitmap(e);else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)a=e;else{const t=this.cachedCanvases.getCanvas("inlineImage",i,n).context;putBinaryImageData(t,e);a=this.applyTransferMapsToCanvas(t)}const o=this._scaleImage(a,getCurrentTransformInverse(s));s.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(s),e.interpolate);this.dependencyTracker?.resetBBox(t).recordBBox(t,s,0,i,-n,0).recordDependencies(t,mt).recordOperation(t);drawImageAtIntegerCoords(s,o.img,0,0,o.paintWidth,o.paintHeight,0,-n,i,n);this.compose();this.restore(t)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const n=this.ctx;let s;if(e.bitmap)s=e.bitmap;else{const t=e.width,i=e.height,n=this.cachedCanvases.getCanvas("inlineImage",t,i).context;putBinaryImageData(n,e);s=this.applyTransferMapsToCanvas(n)}this.dependencyTracker?.resetBBox(t);for(const e of i){n.save();n.transform(...e.transform);n.scale(1,-1);drawImageAtIntegerCoords(n,s,e.x,e.y,e.w,e.h,0,-1,1,1);this.dependencyTracker?.recordBBox(t,n,0,1,-1,0);n.restore()}this.dependencyTracker?.recordOperation(t);this.compose()}paintSolidColorImageMask(t){if(this.contentVisible){this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,gt).recordOperation(t);this.ctx.fillRect(0,0,1,1);this.compose()}}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t);this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t);"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0});this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t);this.markedContentStack.pop();this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const n=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath();this.pendingClip||this.compose(i);const s=this.ctx;if(this.pendingClip){n||(this.pendingClip===It?s.clip(e,"evenodd"):s.clip(e));this.pendingClip=null;this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)}else this.dependencyTracker?.recordOperation(t);this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=getCurrentTransform(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let r,a;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)r=a=1/i;else{const e=i*t;r=a=e<1?1/e:1}else if(0===t){r=1/i;a=1/n}else{const e=i*t,s=n*t;r=e<1?1/e:1;a=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t){r=h/o;a=l/o}else{const e=t*o;r=h>e?h/e:1;a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r;this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,r]=this.getScaleForStroking();if(s===r){i.lineWidth=(n||1)*s;i.stroke(t);return}const a=i.getLineDash();e&&i.save();i.scale(s,r);Tt.a=1/s;Tt.d=1/r;const o=new Path2D;o.addPath(t,Tt);if(a.length>0){const t=Math.max(s,r);i.setLineDash(a.map(e=>e/t));i.lineDashOffset/=t}i.lineWidth=n||1;i.stroke(o);e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in I)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[I[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#Qn=null;static#Jn="";static get workerPort(){return this.#Qn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Qn=t}static get workerSrc(){return this.#Jn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Jn=t}}class Metadata{#Zn;#ts;constructor({parsedData:t,rawData:e}){this.#Zn=t;this.#ts=e}getRaw(){return this.#ts}get(t){return this.#Zn.get(t)??null}[Symbol.iterator](){return this.#Zn.entries()}}const Ft=Symbol("INTERNAL");class OptionalContentGroup{#es=!1;#is=!1;#ns=!1;#ss=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:a}){this.#es=!!(t&s);this.#is=!!(t&r);this.name=e;this.intent=i;this.usage=n;this.rbGroups=a}get visible(){if(this.#ns)return this.#ss;if(!this.#ss)return!1;const{print:t,view:e}=this.usage;return this.#es?"OFF"!==e?.viewState:!this.#is||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ft&&unreachable("Internal method `_setVisible` called.");this.#ns=i;this.#ss=e}}class OptionalContentConfig{#rs=null;#as=new Map;#os=null;#ls=null;constructor(t,e=s){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#ls=t.order;for(const i of t.groups)this.#as.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#as.values())t._setVisible(Ft,!1);for(const e of t.on)this.#as.get(e)._setVisible(Ft,!0);for(const e of t.off)this.#as.get(e)._setVisible(Ft,!1);this.#os=this.getHash()}}#hs(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n<e;n++){const e=t[n];let s;if(Array.isArray(e))s=this.#hs(e);else{if(!this.#as.has(e)){warn(`Optional content group not found: ${e}`);return!0}s=this.#as.get(e).visible}switch(i){case"And":if(!s)return!1;break;case"Or":if(s)return!0;break;case"Not":return!s;default:return!0}}return"And"===i}isVisible(t){if(0===this.#as.size)return!0;if(!t){info("Optional content group not defined.");return!0}if("OCG"===t.type){if(!this.#as.has(t.id)){warn(`Optional content group not found: ${t.id}`);return!0}return this.#as.get(t.id).visible}if("OCMD"===t.type){if(t.expression)return this.#hs(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#as.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#as.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#as.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#as.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#as.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#as.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#as.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#as.get(e).visible)return!1}return!0}warn(`Unknown optional content policy ${t.policy}.`);return!0}warn(`Unknown group type ${t.type}.`);return!0}setVisibility(t,e=!0,i=!0){const n=this.#as.get(t);if(n){if(i&&e&&n.rbGroups.length)for(const e of n.rbGroups)for(const i of e)i!==t&&this.#as.get(i)?._setVisible(Ft,!1,!0);n._setVisible(Ft,!!e,!0);this.#rs=null}else warn(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#as.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#rs=null}get hasInitialVisibility(){return null===this.#os||this.getHash()===this.#os}getOrder(){return this.#as.size?this.#ls?this.#ls.slice():[...this.#as.keys()]:null}getGroup(t){return this.#as.get(t)||null}getHash(){if(null!==this.#rs)return this.#rs;const t=new MurmurHash3_64;for(const[e,i]of this.#as)t.update(`${e}:${i.visible}`);return this.#rs=t.hexdigest()}[Symbol.iterator](){return this.#as.entries()}}class BasePDFStream{#ds=null;#cs=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t;this.#ds=e;this.#cs=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){assert(!this._fullReader,"BasePDFStream.getFullReader can only be called once.");return this._fullReader=new this.#ds(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new this.#cs(this,t,e);this._rangeReaders.add(i);return i}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class BasePDFStreamReader{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}class BasePDFStreamRangeReader{_stream=null;constructor(t,e,i){this._stream=t}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}function getArrayBuffer(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}class PDFDataTransportStream extends BasePDFStream{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,PDFDataTransportStreamReader,PDFDataTransportStreamRangeReader);const{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:n}=e;if(i?.length>0){const t=getArrayBuffer(i);this._queuedChunks.push(t)}this._progressiveDone=n;e.addRangeListener((t,e)=>{this.#us(t,e)});e.addProgressListener((t,e)=>{void 0!==e&&this._fullReader?.onProgress?.({loaded:t,total:e})});e.addProgressiveReadListener(t=>{this.#us(void 0,t)});e.addProgressiveDoneListener(()=>{this._fullReader?.progressiveDone();this._progressiveDone=!0});e.transportReady()}#us(t,e){const i=getArrayBuffer(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);assert(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");e._enqueue(i)}}getFullReader(){const t=super.getFullReader();this._queuedChunks=null;return t}getRangeReader(t,e){const i=super.getRangeReader(t,e);if(i){i.onDone=()=>this._rangeReaders.delete(i);this._source.pdfDataRangeTransport.requestDataRange(t,e)}return i}cancelAllRequests(t){super.cancelAllRequests(t);this._source.pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader extends BasePDFStreamReader{_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:n}=t._source,{length:s,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone;this._contentLength=s;this._isStreamingSupported=!n;this._isRangeSupported=!i;isPdfFile(r)&&(this._filename=r);this._headersCapability.resolve()}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||=!0}}class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader{onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i);this._begin=e}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this.onDone?.()}}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this.onDone?.()}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return s;s.suggestedLength=r;if(r<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;if("identity"!==(t.get("Content-Encoding")||"identity"))return s;s.allowRangeRequests=!0;return s}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const n=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,n,s]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[n,s]}const s=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=rfc2616unquote(n);if(i){n=unescape(n);0===t&&(n=rfc5987decode(n))}s.push(n)}return s.join("")}(t);if(i)return fixupEncoding(rfc2047decode(i));i=toParamRegExp("filename","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=rfc2047decode(t);return fixupEncoding(t)}function toParamRegExp(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function textdecode(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const n=new TextDecoder(t,{fatal:!0}),s=stringToBytes(i);i=n.decode(s);e=!1}catch{}}return i}function fixupEncoding(t){if(e&&/[\x80-\xff]/.test(t)){t=textdecode("utf-8",t);e&&(t=textdecode("iso-8859-1",t))}return t}function rfc2616unquote(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');if(-1!==i){e[t]=e[t].slice(0,i);e.length=t+1}e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function rfc5987decode(t){const e=t.indexOf("'");return-1===e?t:textdecode(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function rfc2047decode(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,i,n){if("q"===i||"Q"===i)return textdecode(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{n=atob(n)}catch{}return textdecode(e,n)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(isPdfFile(t))return t}return null}function createResponseError(t,e){return new ResponseException(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function ensureResponseOrigin(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function fetchUrl(t,e,i,n){return fetch(t,{method:"GET",headers:e,signal:n.signal,mode:"cors",credentials:i?"include":"same-origin",redirect:"follow"})}function ensureResponseStatus(t,e){if(200!==t&&206!==t)throw createResponseError(t,e)}function fetch_stream_getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;warn(`getArrayBuffer - unexpected data format: ${t}`);return new Uint8Array(t).buffer}class PDFFetchStream extends BasePDFStream{_responseOrigin=null;constructor(t){super(t,PDFFetchStreamReader,PDFFetchStreamRangeReader);this.isHttp=/^https?:/i.test(t.url);this.headers=createHeaders(this.isHttp,t.httpHeaders)}}class PDFFetchStreamReader extends BasePDFStreamReader{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,length:n,rangeChunkSize:s,url:r,withCredentials:a}=t._source;this._contentLength=n;this._isStreamingSupported=!i;this._isRangeSupported=!e;const o=new Headers(t.headers);fetchUrl(r,o,a,this._abortController).then(i=>{t._responseOrigin=getResponseOrigin(i.url);ensureResponseStatus(i.status,r);this._reader=i.body.getReader();const n=i.headers,{allowRangeRequests:a,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:s,disableRange:e});this._isRangeSupported=a;this._contentLength=o||this._contentLength;this._filename=extractFilenameFromHeader(n);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n,withCredentials:s}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${i-1}`);fetchUrl(n,r,s,this._abortController).then(e=>{ensureResponseOrigin(getResponseOrigin(e.url),t._responseOrigin);ensureResponseStatus(e.status,n);this._reader=e.body.getReader();this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFNetworkStream extends BasePDFStream{#ps=new WeakMap;_responseOrigin=null;constructor(t){super(t,PDFNetworkStreamReader,PDFNetworkStreamRangeReader);this.url=t.url;this.isHttp=/^https?:/i.test(this.url);this.headers=createHeaders(this.isHttp,t.httpHeaders)}_request(t){const e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#ps.set(e,i);e.open("GET",this.url);e.withCredentials=this._source.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);i.validateStatus=t=>206===t||200===t}else i.validateStatus=t=>200===t;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>t.onError(e.status);e.onreadystatechange=this.#gs.bind(this,e);e.onprogress=this.#ms.bind(this,e);e.send(null);return e}#ms(t,e){const i=this.#ps.get(t);i?.onProgress?.(e)}#gs(t,e){const i=this.#ps.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==t.readyState)return;if(!this.#ps.has(t))return;this.#ps.delete(t);if(0===t.status&&this.isHttp){i.onError(t.status);return}const n=t.status||200;if(!i.validateStatus(n)){i.onError(t.status);return}const s=function network_getArrayBuffer(t){return"string"!=typeof t?t:stringToBytes(t).buffer}(t.response);if(206===n){const e=t.getResponseHeader("Content-Range");if(/bytes (\d+)-(\d+)\/(\d+)/.test(e))i.onDone(s);else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else s?i.onDone(s):i.onError(t.status)}_abortRequest(t){if(this.#ps.has(t)){this.#ps.delete(t);t.abort()}}getRangeReader(t,e){const i=super.getRangeReader(t,e);i&&(i.onClosed=()=>this._rangeReaders.delete(i));return i}}class PDFNetworkStreamReader extends BasePDFStreamReader{_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t);const{length:e}=t._source;this._contentLength=e;this._fullRequestXhr=t._request({onHeadersReceived:this.#fs.bind(this),onDone:this.#bs.bind(this),onError:this.#ws.bind(this),onProgress:this.#ms.bind(this)})}#fs(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,n=this._fullRequestXhr;t._responseOrigin=getResponseOrigin(n.responseURL);const s=n.getAllResponseHeaders(),r=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:a,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});a&&(this._isRangeSupported=!0);this._contentLength=o||this._contentLength;this._filename=extractFilenameFromHeader(r);this._isRangeSupported&&t._abortRequest(n);this._headersCapability.resolve()}#bs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._cachedChunks.push(t);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}#ws(t){this._storedError=createResponseError(t,this._stream.url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}#ms(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._abortRequest(this._fullRequestXhr);this._fullRequestXhr=null}}class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader{onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i);this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#fs.bind(this),onDone:this.#bs.bind(this),onError:this.#ws.bind(this),onProgress:null})}#fs(){const t=getResponseOrigin(this._requestXhr?.responseURL);try{ensureResponseOrigin(t,this._stream._responseOrigin)}catch(t){this._storedError=t;this.#ws(0)}}#bs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this.onClosed?.()}#ws(t){this._storedError??=createResponseError(t,this._stream.url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._abortRequest(this._requestXhr);this.onClosed?.()}}const Rt=/^[a-z][a-z0-9\-+.]+:/i;function getReadableStream(t){const{Readable:e}=process.getBuiltinModule("stream");if("function"==typeof e.toWeb)return e.toWeb(t);return process.getBuiltinModule("module").createRequire(import.meta.url)("node-readable-to-web-readable-stream").makeDefaultReadableStreamFromNodeReadable(t)}function node_stream_getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;warn(`getArrayBuffer - unexpected data format: ${t}`);return new Uint8Array(t).buffer}class PDFNodeStream extends BasePDFStream{constructor(t){super(t,PDFNodeStreamReader,PDFNodeStreamRangeReader);this.url=function parseUrlOrPath(t){if(Rt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.")}}class PDFNodeStreamReader extends BasePDFStreamReader{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,length:n,rangeChunkSize:s}=t._source;this._contentLength=n;this._isStreamingSupported=!i;this._isRangeSupported=!e;const r=t.url,a=process.getBuiltinModule("fs");a.promises.lstat(r).then(t=>{const e=getReadableStream(a.createReadStream(r));this._reader=e.getReader();const{size:i}=t;i<=2*s&&(this._isRangeSupported=!1);this._contentLength=i;!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=createResponseError(0,r.href));this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:node_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const n=t.url,s=process.getBuiltinModule("fs");try{const t=getReadableStream(s.createReadStream(n,{start:e,end:i-1}));this._reader=t.getReader();this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:node_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}const Bt=Symbol("INITIAL_DATA");class PDFObjects{#ys=Object.create(null);#As(t){return this.#ys[t]||={...Promise.withResolvers(),data:Bt}}get(t,e=null){if(e){const i=this.#As(t);i.promise.then(()=>e(i.data));return null}const i=this.#ys[t];if(!i||i.data===Bt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#ys[t];return!!e&&e.data!==Bt}delete(t){const e=this.#ys[t];if(!e||e.data===Bt)return!1;delete this.#ys[t];return!0}resolve(t,e=null){const i=this.#As(t);i.data=e;i.resolve()}clear(){for(const t in this.#ys){const{data:e}=this.#ys[t];e?.bitmap?.close()}this.#ys=Object.create(null)}*[Symbol.iterator](){for(const t in this.#ys){const{data:e}=this.#ys[t];e!==Bt&&(yield[t,e])}}}class TextLayer{#vs=Promise.withResolvers();#It=null;#xs=!1;#Es=!!globalThis.FontInspector?.enabled;#Cs=null;#Ss=null;#Ts=0;#_s=0;#Ms=null;#Ds=null;#Ps=0;#ks=0;#Is=Object.create(null);#Fs=[];#Rs=null;#Bs=[];#Ls=new WeakMap;#Os=null;static#Ns=new Map;static#Us=new Map;static#Hs=new WeakMap;static#zs=null;static#Gs=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Rs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Rs=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#It=this.#Ds=e;this.#ks=i.scale*OutputScale.pixelRatio;this.#Ps=i.rotation;this.#Ss={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:s,pageX:r,pageY:a}=i.rawDims;this.#Os=[1,0,0,-1,-r,a+s];this.#_s=n;this.#Ts=s;TextLayer.#Ws();e.style.setProperty("--min-font-size",TextLayer.#zs);setLayerDimensions(e,i);this.#vs.promise.finally(()=>{TextLayer.#Gs.delete(this);this.#Ss=null;this.#Is=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ms.read().then(({value:t,done:e})=>{if(e)this.#vs.resolve();else{this.#Cs??=t.lang;Object.assign(this.#Is,t.styles);this.#Vs(t.items);pump()}},this.#vs.reject)};this.#Ms=this.#Rs.getReader();TextLayer.#Gs.add(this);pump();return this.#vs.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,n=t.rotation;if(n!==this.#Ps){e?.();this.#Ps=n;setLayerDimensions(this.#Ds,{rotation:n})}if(i!==this.#ks){e?.();this.#ks=i;const t={div:null,properties:null,ctx:TextLayer.#js(this.#Cs)};for(const e of this.#Bs){t.properties=this.#Ls.get(e);t.div=e;this.#$s(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ms?.cancel(t).catch(()=>{});this.#Ms=null;this.#vs.reject(t)}get textDivs(){return this.#Bs}get textContentItemsStr(){return this.#Fs}#Vs(t){if(this.#xs)return;this.#Ss.ctx??=TextLayer.#js(this.#Cs);const e=this.#Bs,i=this.#Fs;for(const n of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#xs=!0;return}if(void 0!==n.str){i.push(n.str);this.#Xs(n)}else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#It;this.#It=document.createElement("span");this.#It.classList.add("markedContent");n.id&&this.#It.setAttribute("id",`${n.id}`);"Artifact"===n.tag&&(this.#It.ariaHidden=!0);t.append(this.#It)}else"endMarkedContent"===n.type&&(this.#It=this.#It.parentNode)}}#Xs(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Bs.push(e);const n=Util.transform(this.#Os,t.transform);let s=Math.atan2(n[1],n[0]);const r=this.#Is[t.fontName];r.vertical&&(s+=Math.PI/2);let a=this.#Es&&r.fontSubstitution||r.fontFamily;a=TextLayer.fontFamilyMap.get(a)||a;const o=Math.hypot(n[2],n[3]),l=o*TextLayer.#qs(a,r,this.#Cs);let h,d;if(0===s){h=n[4];d=n[5]-l}else{h=n[4]+l*Math.sin(s);d=n[5]-l*Math.cos(s)}const c=e.style;c.left=`${(100*h/this.#_s).toFixed(2)}%`;c.top=`${(100*d/this.#Ts).toFixed(2)}%`;c.setProperty("--font-height",`${o.toFixed(2)}px`);c.fontFamily=a;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Es&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==s&&(i.angle=s*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(u=!0)}u&&(i.canvasWidth=r.vertical?t.height:t.width);this.#Ls.set(e,i);this.#Ss.div=e;this.#Ss.properties=i;this.#$s(this.#Ss);i.hasText&&this.#It.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#It.append(t)}}#$s(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:r,fontSize:a}=i;TextLayer.#Ks(n,a*this.#ks,t);const{width:o}=n.measureText(e.textContent);o>0&&s.setProperty("--scale-x",r*this.#ks/o)}0!==i.angle&&s.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#Gs.size>0)){this.#Ns.clear();for(const{canvas:t}of this.#Us.values())t.remove();this.#Us.clear()}}static#js(t=null){let e=this.#Us.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#Us.set(t,e);this.#Hs.set(e,{size:0,family:""})}return e}static#Ks(t,e,i){const n=this.#Hs.get(t);if(e!==n.size||i!==n.family){t.font=`${e}px ${i}`;n.size=e;n.family=i}}static#Ws(){if(null!==this.#zs)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#zs=t.getBoundingClientRect().height;t.remove()}static#qs(t,e,i){const n=this.#Ns.get(t);if(n)return n;const s=this.#js(i);s.canvas.width=s.canvas.height=30;this.#Ks(s,30,t);const r=s.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;if(a)l=a/(a+o);else{util_FeatureTest.platform.isFirefox&&warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)}this.#Ns.set(t,l);return l}}function getDocument(e={}){"string"==typeof e||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});const i=new PDFDocumentLoadingTask,{docId:n}=i,s=e.url?function getUrlProp(e){if(e instanceof URL)return e.href;if("string"==typeof e){if(t)return e;const i=URL.parse(e,window.location);if(i)return i.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(e.url):null,r=e.data?function getDataProp(e){if(t&&"undefined"!=typeof Buffer&&e instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if("string"==typeof e)return stringToBytes(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||"object"==typeof e&&!isNaN(e?.length))return new Uint8Array(e);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(e.data):null,a=e.httpHeaders||null,o=!0===e.withCredentials,l=e.password??null,h=e.range instanceof PDFDataRangeTransport?e.range:null,d=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536;let c=e.worker instanceof PDFWorker?e.worker:null;const u=e.verbosity,p="string"!=typeof e.docBaseUrl||isDataScheme(e.docBaseUrl)?null:e.docBaseUrl,g=getFactoryUrlProp(e.cMapUrl),m=!1!==e.cMapPacked,f=e.CMapReaderFactory||(t?NodeCMapReaderFactory:DOMCMapReaderFactory),b=getFactoryUrlProp(e.iccUrl),w=getFactoryUrlProp(e.standardFontDataUrl),y=e.StandardFontDataFactory||(t?NodeStandardFontDataFactory:DOMStandardFontDataFactory),A=getFactoryUrlProp(e.wasmUrl),v=e.WasmFactory||(t?NodeWasmFactory:DOMWasmFactory),x=!0!==e.stopAtErrors,E=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,C=!1!==e.isEvalSupported,S="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,T="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),_=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,M="boolean"==typeof e.disableFontFace?e.disableFontFace:t,D=!0===e.fontExtraProperties,P=!0===e.enableXfa,k=e.ownerDocument||globalThis.document,I=!0===e.disableRange,F=!0===e.disableStream,R=!0===e.disableAutoFetch,B=!0===e.pdfBug,L=e.CanvasFactory||(t?NodeCanvasFactory:DOMCanvasFactory),O=e.FilterFactory||(t?NodeFilterFactory:DOMFilterFactory),N=!0===e.enableHWA,U=!1!==e.useWasm,H=h?h.length:e.length??NaN,z="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!M,G="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(f===DOMCMapReaderFactory&&y===DOMStandardFontDataFactory&&v===DOMWasmFactory&&g&&w&&A&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(w,document.baseURI)&&isValidFetchUrl(A,document.baseURI));setVerbosityLevel(u);const W={canvasFactory:new L({ownerDocument:k,enableHWA:N}),filterFactory:new O({docId:n,ownerDocument:k}),cMapReaderFactory:G?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:G?null:new y({baseUrl:w}),wasmFactory:G?null:new v({baseUrl:A})};if(!c){c=PDFWorker.create({verbosity:u,port:GlobalWorkerOptions.workerPort});i._worker=c}const V={docId:n,apiVersion:"5.4.624",data:r,password:l,disableAutoFetch:R,rangeChunkSize:d,length:H,docBaseUrl:p,enableXfa:P,evaluatorOptions:{maxImageSize:E,disableFontFace:M,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:S,isImageDecoderSupported:T,canvasMaxAreaInBytes:_,fontExtraProperties:D,useSystemFonts:z,useWasm:U,useWorkerFetch:G,cMapUrl:g,iccUrl:b,standardFontDataUrl:w,wasmUrl:A}},j={ownerDocument:k,pdfBug:B,styleElement:null,enableHWA:N,loadingParams:{disableAutoFetch:R,enableXfa:P}};c.promise.then(function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=c.messageHandler.sendWithPromise("GetDocRequest",V,r?[r.buffer]:null);let l;if(h)l=new PDFDataTransportStream({pdfDataRangeTransport:h,disableRange:I,disableStream:F});else if(!r){if(!s)throw new Error("getDocument - no `url` parameter provided.");const e=isValidFetchUrl(s)?PDFFetchStream:t?PDFNodeStream:PDFNetworkStream;l=new e({url:s,length:H,httpHeaders:a,withCredentials:o,rangeChunkSize:d,disableRange:I,disableStream:F})}return e.then(t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(n,t,c.port),s=new WorkerTransport(e,i,l,j,W);i._transport=s;e.send("Ready",null)})}).catch(i._capability.reject);return i}class PDFDocumentLoadingTask{static#dn=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#dn++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}async getData(){return this._transport.getData()}}class PDFDataRangeTransport{#vs=Promise.withResolvers();#Ys=[];#Qs=[];#Js=[];#Zs=[];constructor(t,e,i=!1,n=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=n}addRangeListener(t){this.#Zs.push(t)}addProgressListener(t){this.#Js.push(t)}addProgressiveReadListener(t){this.#Qs.push(t)}addProgressiveDoneListener(t){this.#Ys.push(t)}onDataRange(t,e){for(const i of this.#Zs)i(t,e)}onDataProgress(t,e){this.#vs.promise.then(()=>{for(const i of this.#Js)i(t,e)})}onDataProgressiveRead(t){this.#vs.promise.then(()=>{for(const e of this.#Qs)e(t)})}onDataProgressiveDone(){this.#vs.promise.then(()=>{for(const t of this.#Ys)t()})}transportReady(){this.#vs.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#tr=!1;#er=PagesMapper.instance;constructor(t,e,i,n=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=n?new StatTimer:null;this._pdfBug=n;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=!1;this.recordedBBoxes=null}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=c.ENABLE,transform:a=null,background:o=null,optionalContentConfigPromise:l=null,annotationCanvasMap:h=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:p=!1,recordOperations:g=!1,operationsFilter:m=null}){this._stats?.time("Overall");const f=this._transport.getRenderingIntent(n,s,u,p),{renderingIntent:b,cacheKey:w}=f;this.#tr=!1;l||=this._transport.getOptionalContentConfig(b);let y=this._intentStates.get(w);if(!y){y=Object.create(null);this._intentStates.set(w,y)}if(y.streamReaderCancelTimeout){clearTimeout(y.streamReaderCancelTimeout);y.streamReaderCancelTimeout=null}const A=!!(b&r);if(!y.displayReadyCapability){y.displayReadyCapability=Promise.withResolvers();y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(f)}const v=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),x=!this.recordedBBoxes&&(g||v),complete=t=>{y.renderTasks.delete(E);if(x){const t=E.gfx?.dependencyTracker.take();if(t){E.stepper&&E.stepper.setOperatorBBoxes(t,E.gfx.dependencyTracker.takeDebugMetadata());g&&(this.recordedBBoxes=t)}}A&&(this.#tr=!0);this.#ir();if(t){E.capability.reject(t);this._abortOperatorList({intentState:y,reason:t instanceof Error?t:new Error(t)})}else E.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},E=new InternalRenderTask({callback:complete,params:{canvas:e,canvasContext:t,dependencyTracker:x?new CanvasDependencyTracker(e,y.operatorList.length,v):null,viewport:i,transform:a,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:y.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!A,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:m});(y.renderTasks||=new Set).add(E);const C=E.task;Promise.all([y.displayReadyCapability.promise,l]).then(([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&b))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");E.initializeGraphics({transparency:t,optionalContentConfig:e});E.operatorListChanged()}}).catch(complete);return C}getOperatorList({intent:t="display",annotationMode:e=c.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0);let r,a=this._intentStates.get(s.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(s.cacheKey,a)}if(!a.opListReadCapability){r=Object.create(null);r.operatorListChanged=function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(r)}};a.opListReadCapability=Promise.withResolvers();(a.renderTasks||=new Set).add(r);a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(s)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#er.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>XfaText.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,i){const n=e.getReader(),s={items:[],styles:Object.create(null),lang:null};!function pump(){n.read().then(function({value:e,done:i}){if(i)t(s);else{s.lang??=e.lang;Object.assign(s.styles,e.styles);s.items.push(...e.items);pump()}},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#tr=!1;return Promise.all(t)}cleanup(t=!1){this.#tr=!0;const e=this.#ir();t&&e&&(this._stats&&=new StatTimer);return e}#ir(){if(!this.#tr||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#tr=!1;return!0}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++){e.operatorList.fnArray.push(t.fnArray[i]);e.operatorList.argsArray.push(t.argsArray[i])}e.operatorList.lastChunk=t.lastChunk;e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#ir()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:r}=i,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#er.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const pump=()=>{a.read().then(({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}},t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#ir()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}t.streamReader.cancel(new AbortException(e.message)).catch(()=>{});t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class PDFWorker{#vs=Promise.withResolvers();#nr=null;#Qn=null;#sr=null;static#rr=0;static#ar=!1;static#or=new WeakMap;static{if(t){this.#ar=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};this.fromPort=t=>{!function deprecated(t){console.log("Deprecated API usage: "+t)}("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;if(e){if(PDFWorker.#or.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#or.set(e,this);this.#lr(e)}else this.#hr()}get promise(){return this.#vs.promise}#dr(){this.#vs.resolve();this.#nr.send("configure",{verbosity:this.verbosity})}get port(){return this.#Qn}get messageHandler(){return this.#nr}#lr(t){this.#Qn=t;this.#nr=new MessageHandler("main","worker",t);this.#nr.on("ready",()=>{});this.#dr()}#hr(){if(PDFWorker.#ar||PDFWorker.#cr){this.#ur();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{n.abort();i.destroy();e.terminate();this.destroyed?this.#vs.reject(new Error("Worker was destroyed")):this.#ur()},n=new AbortController;e.addEventListener("error",()=>{this.#sr||terminateEarly()},{signal:n.signal});i.on("test",t=>{n.abort();if(!this.destroyed&&t){this.#nr=i;this.#Qn=e;this.#sr=e;this.#dr()}else terminateEarly()});i.on("ready",t=>{n.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this.#ur()}});const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this.#ur()}#ur(){if(!PDFWorker.#ar){warn("Setting up fake worker.");PDFWorker.#ar=!0}PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this.#vs.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this.#Qn=e;const i="fake"+PDFWorker.#rr++,n=new MessageHandler(i+"_worker",i,e);t.setup(n,e);this.#nr=new MessageHandler(i,i+"_worker",e);this.#dr()}).catch(t=>{this.#vs.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0;this.#sr?.terminate();this.#sr=null;PDFWorker.#or.delete(this.#Qn);this.#Qn=null;this.#nr?.destroy();this.#nr=null}static create(t){const e=this.#or.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#cr(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#cr)return this.#cr;return(await import(
26 +/*webpackIgnore: true*/
27 +/*@vite-ignore*/
28 +this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#pr=null;#gr=new Map;#mr=null;#fr=new Map;#br=new Map;#wr=new Map;#yr=null;#er=PagesMapper.instance;constructor(t,e,i,n,s){this.messageHandler=t;this.loadingTask=e;this.#mr=i;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement});this.enableHWA=n.enableHWA;this.loadingParams=n.loadingParams;this._params=n;this.canvasFactory=s.canvasFactory;this.filterFactory=s.filterFactory;this.cMapReaderFactory=s.cMapReaderFactory;this.standardFontDataFactory=s.standardFontDataFactory;this.wasmFactory=s.wasmFactory;this.destroyed=!1;this.destroyCapability=null;this.setupMessageHandler();this.#er.addListener(this.#Ar.bind(this))}#Ar(){const t=new Map,e=new Map;for(let i=0,n=this.#er.pagesNumber;i<n;i++){const n=this.#er.getPrevPageNumber(i+1)-1,s=this.#fr.get(n);s&&t.set(i,s);const r=this.#br.get(n);r&&e.set(i,r)}this.#fr=t;this.#br=e}#vr(t,e=null){const i=this.#gr.get(t);if(i)return i;const n=this.messageHandler.sendWithPromise(t,e);this.#gr.set(t,n);return n}#ms({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:MathClamp(Math.round(t/e*100),0,100)})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=c.ENABLE,i=null,u=!1,p=!1){let g=s,m=Q;switch(t){case"any":g=n;break;case"display":break;case"print":g=r;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&r&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case c.DISABLE:g+=l;break;case c.ENABLE:break;case c.ENABLE_FORMS:g+=a;break;case c.ENABLE_STORAGE:g+=o;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}u&&(g+=h);p&&(g+=d);const{ids:b,hash:w}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,w].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#yr?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#fr.values())t.push(e._destroy());this.#fr.clear();this.#br.clear();this.#wr.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then(()=>{this.commonObjs.clear();this.fontLoader.clear();this.#gr.clear();this.filterFactory.destroy();TextLayer.cleanup();this.#mr?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()},this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this.#mr,"GetReader - no `BasePDFStream` instance available.");this.#pr=this.#mr.getFullReader();this.#pr.onProgress=t=>this.#ms(t);e.onPull=()=>{this.#pr.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{this.#pr.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this.#pr.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:n}=this.#pr;e&&i&&(this.#pr.onProgress=null);return{isStreamingSupported:e,isRangeSupported:i,contentLength:n}});t.on("GetRangeReader",(t,e)=>{assert(this.#mr,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#mr.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{i.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}}else e.close()});t.on("GetDoc",({pdfInfo:t})=>{this.#er.pagesNumber=t.numPages;this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))});t.on("DocException",t=>{e._capability.reject(wrapReason(t))});t.on("PasswordRequest",t=>{this.#yr=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#yr.reject(t):this.#yr.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#yr.reject(t)}return this.#yr.promise});t.on("DataLoaded",t=>{this.#ms({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#fr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)});t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const s=new FontInfo(n),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new FontFaceObject(s,r,n.extra,n.charProcOperatorList);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a.fontExtraProperties&&a.data&&a.clearData();this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=n;assert(o,"The imageRef must be defined.");for(const t of this.#fr.values())for(const[,i]of t.objs)if(i?.ref===o){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new FontPathInfo(n));break;case"Image":this.commonObjs.resolve(e,n);break;case"Pattern":const l=new PatternInfo(n);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null});t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#fr.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()});t.on("DocProgress",t=>{this.destroyed||this.#ms(t)});t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#pr?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){return this.messageHandler.sendWithPromise("ExtractPages",{pageInfos:t})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.#er.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#er.getPageId(t)-1,n=this.#br.get(e);if(n)return n;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#wr.set(t.refStr,i);const n=new PDFPageProxy(e,t,this,this._params.pdfBug);this.#fr.set(e,n);return n});this.#br.set(e,s);return s}async getPageIndex(t){if(!isRefProxy(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen});return this.#er.getPageNumber(e+1)-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.#er.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#vr("GetFieldObjects")}hasJSActions(){return this.#vr("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#vr("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.#er.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.#er.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#vr("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#gr.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this.#pr?.filename??null,contentLength:this.#pr?.contentLength??null,hasStructTree:t[2]}));this.#gr.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#fr.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#gr.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#wr.get(e);return i>=0?this.#er.getPageNumber(i+1):null}}class RenderTask{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#xr=null;static#Er=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=n;this.annotationCanvasMap=s;this.operatorListIdx=null;this.operatorList=r;this._pageIndex=a;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvas;this._canvasContext=e.canvas?null:e.canvasContext;this._enableHWA=u;this._dependencyTracker=e.dependencyTracker;this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Er.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Er.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{viewport:i,transform:n,background:s,dependencyTracker:r}=this.params,a=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r);this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#xr){window.cancelAnimationFrame(this.#xr);this.#xr=null}InternalRenderTask.#Er.delete(this._canvas);t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e);this.callback(t);this.task.onError?.(t)}operatorListChanged(){if(this.graphicsReady){this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#xr=window.requestAnimationFrame(()=>{this.#xr=null;this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Er.delete(this._canvas);this.callback()}}}}}const Lt="5.4.624",Ot="384c6208b";class ColorPicker{#Cr=null;#Sr=null;#Tr;#_r=null;#Mr=!1;#Dr=!1;#u=null;#Pr;#kr=null;#C=null;static#Ir=null;static get _keyboardManager(){return shadow(this,"_keyboardManager",new KeyboardManager([[["Escape","mac+Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home","mac+Home"],ColorPicker.prototype._moveToBeginning],[["End","mac+End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#Dr=!1;this.#u=t}else this.#Dr=!0;this.#C=t?._uiManager||e;this.#Pr=this.#C._eventBus;this.#Tr=t?.color?.toUpperCase()||this.#C?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#Ir||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Cr=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.ariaHasPopup="true";this.#u&&(t.ariaControls=`${this.#u.id}_colorpicker_dropdown`);const e=this.#C._signal;t.addEventListener("click",this.#Fr.bind(this),{signal:e});t.addEventListener("keydown",this.#Rr.bind(this),{signal:e});const i=this.#Sr=document.createElement("span");i.className="swatch";i.ariaHidden="true";i.style.backgroundColor=this.#Tr;t.append(i);return t}renderMainDropdown(){const t=this.#_r=this.#Br();t.ariaOrientation="horizontal";t.ariaLabelledBy="highlightColorPickerLabel";return t}#Br(){const t=document.createElement("div"),e=this.#C._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.className="dropdown";t.role="listbox";t.ariaMultiSelectable="false";t.ariaOrientation="vertical";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");this.#u&&(t.id=`${this.#u.id}_colorpicker_dropdown`);for(const[i,n]of this.#C.highlightColors){const s=document.createElement("button");s.tabIndex="0";s.role="option";s.setAttribute("data-color",n);s.title=i;s.setAttribute("data-l10n-id",ColorPicker.#Ir[i]);const r=document.createElement("span");s.append(r);r.className="swatch";r.style.backgroundColor=n;s.ariaSelected=n===this.#Tr;s.addEventListener("click",this.#Lr.bind(this,n),{signal:e});t.append(s)}t.addEventListener("keydown",this.#Rr.bind(this),{signal:e});return t}#Lr(t,e){e.stopPropagation();this.#Pr.dispatch("switchannotationeditorparams",{source:this,type:g.HIGHLIGHT_COLOR,value:t});this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Cr){this.#Fr(t);return}const e=t.target.getAttribute("data-color");e&&this.#Lr(e,t)}_moveToNext(t){this.#Or?t.target!==this.#Cr?t.target.nextSibling?.focus():this.#_r.firstElementChild?.focus():this.#Fr(t)}_moveToPrevious(t){if(t.target!==this.#_r?.firstElementChild&&t.target!==this.#Cr){this.#Or||this.#Fr(t);t.target.previousSibling?.focus()}else this.#Or&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Or?this.#_r.firstElementChild?.focus():this.#Fr(t)}_moveToEnd(t){this.#Or?this.#_r.lastElementChild?.focus():this.#Fr(t)}#Rr(t){ColorPicker._keyboardManager.exec(this,t)}#Fr(t){if(this.#Or){this.hideDropdown();return}this.#Mr=0===t.detail;if(!this.#kr){this.#kr=new AbortController;window.addEventListener("pointerdown",this.#y.bind(this),{signal:this.#C.combinedSignal(this.#kr)})}this.#Cr.ariaExpanded="true";if(this.#_r){this.#_r.classList.remove("hidden");return}const e=this.#_r=this.#Br();this.#Cr.append(e)}#y(t){this.#_r?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#_r?.classList.add("hidden");this.#Cr.ariaExpanded="false";this.#kr?.abort();this.#kr=null}get#Or(){return this.#_r&&!this.#_r.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#Dr)if(this.#Or){this.hideDropdown();this.#Cr.focus({preventScroll:!0,focusVisible:this.#Mr})}else this.#u?.unselect()}updateColor(t){this.#Sr&&(this.#Sr.style.backgroundColor=t);if(!this.#_r)return;const e=this.#C.highlightColors.values();for(const i of this.#_r.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Cr?.remove();this.#Cr=null;this.#Sr=null;this.#_r?.remove();this.#_r=null}}class BasicColorPicker{#Nr=null;#u=null;#C=null;static#Ir=null;constructor(t){this.#u=t;this.#C=t._uiManager;BasicColorPicker.#Ir||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#Nr)return this.#Nr;const{editorType:t,colorType:e,color:i}=this.#u,n=this.#Nr=document.createElement("input");n.type="color";n.value=i||"#000000";n.className="basicColorPicker";n.tabIndex=0;n.setAttribute("data-l10n-id",BasicColorPicker.#Ir[t]);n.addEventListener("input",()=>{this.#C.updateParams(e,n.value)},{signal:this.#C._signal});return n}update(t){this.#Nr&&(this.#Nr.value=t)}destroy(){this.#Nr?.remove();this.#Nr=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[scaleAndClamp(1-Math.min(1,t+n)),scaleAndClamp(1-Math.min(1,i+n)),scaleAndClamp(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,r=1-i;return["CMYK",n,s,r,Math.min(n,s,r)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");n.setAttribute("version","1.1");if(!i){n.setAttribute("width",`${t}px`);n.setAttribute("height",`${e}px`)}n.setAttribute("preserveAspectRatio","none");n.setAttribute("viewBox",`0 0 ${t} ${e}`);return n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(j,t)}}const Nt=new WeakSet,Ut=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S.LINK:return new LinkAnnotationElement(t);case S.TEXT:return new TextAnnotationElement(t);case S.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case S.POPUP:return new PopupAnnotationElement(t);case S.FREETEXT:return new FreeTextAnnotationElement(t);case S.LINE:return new LineAnnotationElement(t);case S.SQUARE:return new SquareAnnotationElement(t);case S.CIRCLE:return new CircleAnnotationElement(t);case S.POLYLINE:return new PolylineAnnotationElement(t);case S.CARET:return new CaretAnnotationElement(t);case S.INK:return new InkAnnotationElement(t);case S.POLYGON:return new PolygonAnnotationElement(t);case S.HIGHLIGHT:return new HighlightAnnotationElement(t);case S.UNDERLINE:return new UnderlineAnnotationElement(t);case S.SQUIGGLY:return new SquigglyAnnotationElement(t);case S.STRIKEOUT:return new StrikeOutAnnotationElement(t);case S.STAMP:return new StampAnnotationElement(t);case S.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Ur=null;#Hr=!1;#zr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableComment=t.enableComment;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;this.hasOwnCommentButton=!1;e&&(this.contentElement=this.container=this._createContainer(i));n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)if(e[t+1]>r){r=e[t+1];s=e[t+2]}else e[t+1]===r&&(s=Math.max(s,e[t+2]));return[s,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)if(t[e+1]>r){r=t[e+1];s=t[e]}else t[e+1]===r&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,r]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}}=this.parent;t[1]=e[3]-t[1]+e[1];t[0]=100*(t[0]-s)/i;t[1]=100*(t[1]-r)/n;return t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${u}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${u}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date});t||this.removePopup()}removePopup(){(this.#zr?.popup||this.popup)?.remove();this.#zr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#Ur||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#Gr(e);let n=this.#zr?.popup||this.popup;if(!n&&i?.text){this._createPopup(i);n=this.#zr.popup}if(n){n.updateEdited(t);if(i?.deleted){n.remove();this.#zr=null;this.popup=null}}}resetEdited(){if(this.#Ur){this.#Gr(this.#Ur.rect);this.#zr?.popup.resetEdited();this.#Ur=null}}#Gr(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t);e.left=100*(t[0]-a)/s+"%";e.top=100*(r-t[3]+o)/r+"%";if(0===n){e.width=100*(t[2]-t[0])/s+"%";e.height=100*(t[3]-t[1])/r+"%"}else this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||this instanceof LinkAnnotationElement||(s.tabIndex=0);const{style:r}=s;r.zIndex=this.parent.zIndex;this.parent.zIndex+=2;e.alternativeText&&(s.title=e.alternativeText);e.noRotate&&s.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,s);return s}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case T:r.borderStyle="solid";break;case _:r.borderStyle="dashed";break;case M:warn("Unimplemented border style: beveled");break;case D:warn("Unimplemented border style: inset");break;case P:r.borderBottomStyle="solid"}const n=e.borderColor||null;if(n){this.#Hr=!0;r.borderColor=Util.makeHexColor(0|n[0],0|n[1],0|n[2])}else r.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=n.rawDims;r.left=100*(l[0]-c)/h+"%";r.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){r.width=100*a/h+"%";r.height=100*o/d+"%"}else this.setRotation(p,s);return s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:r}=this;t%180!=0&&([s,r]=[r,s]);e.style.width=100*s/i+"%";e.style.height=100*r/n+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const n=i.detail[t],s=n[0],r=n.slice(1);i.target.style[e]=ColorConverters[`${s}_HTML`](r);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${s}_rgb`](r)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const r=i[n];if(r){r({detail:{[n]:s},target:t});delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(n===r&&s===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#Hr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`];this.container.classList.add("hasBorder")}const o=n-e,l=s-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);d.role="none";const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,n=t.length;i<n;i+=8){const n=t[i],r=t[i+1],d=t[i+2],c=t[i+3],p=h.createElement("rect"),g=(d-e)/o,m=(s-r)/l,f=(n-d)/o,b=(r-c)/l;p.setAttribute("x",g);p.setAttribute("y",m);p.setAttribute("width",f);p.setAttribute("height",b);u.append(p);a?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}if(this.#Hr){a.push("</g></svg>')");r.backgroundImage=a.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,n;if(t){i={str:t.text};n=t.date}else{i=e.contentsObj;n=e.modificationDate}this.#zr=new PopupAnnotationElement({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#zr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#zr}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:r}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${s}"]`);!a||Nt.has(a)?i.push({id:s,exportValue:n,domElement:a}):warn(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(Nt.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class EditorAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.editor=t.editor}render(){this.container.className="editorAnnotation";return this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t;t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id);this.container.remove();this.container=null;this.removePopup()}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);n=!0}else if(t.action){this._bindNamedAction(i,t.action,t.overlaidText);n=!0}else if(t.attachment){this.#Wr(i,t.attachment,t.overlaidText,t.attachmentDest);n=!0}else if(t.setOCGState){this.#Vr(i,t.setOCGState,t.overlaidText);n=!0}else if(t.dest){this._bindLink(i,t.dest,t.overlaidText);n=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);n=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);n=!0}else if(this.isTooltipOnly&&!n){this._bindLink(i,"");n=!0}}this.container.classList.add("linkAnnotation");if(n){this.contentElement=i;this.container.append(i)}return this.container}#jr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#jr();i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};i&&(t.title=i);this.#jr()}#Wr(t,e,i="",n=null){t.href=this.linkService.getAnchorUrl("");e.description?t.title=e.description:i&&(t.title=i);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,n);return!1};this.#jr()}#Vr(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};i&&(t.title=i);this.#jr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}});return!1})}e.overlaidText&&(t.title=e.overlaidText);t.onclick||(t.onclick=()=>!1);this.#jr()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#jr();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,r=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Nt.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,r]of i)if("Action"===r||this.data.actions?.[r]){"Focus"!==r&&"Blur"!==r||(e||={focused:!1});this._setEventListener(t,e,s,r,n);"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,r=t.style;let a;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(i*s))||1);a=Math.min(s,roundToOneDecimal(e/i))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,roundToOneDecimal(t/i))}r.fontSize=`calc(${a}px * var(--total-scale-factor))`;r.color=Util.makeHexColor(n[0],n[1],n[2]);null!==this.data.textAlignment&&(r.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id)){r.domElement&&(r.domElement[e]=i);s.setValue(r.id,{[n]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&s.length>r&&(s=s.slice(0,r));let a=n.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:s,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=a??s;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type=this.data.password?"password":"text";i.setAttribute("value",a??s);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Nt.add(i);this.contentElement=i;i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:d}=this.data,c=!!h&&this.enableScripting;l&&(i.title=l);this._setRequired(i,this.data.required);r&&(i.maxLength=r);i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value});this.setPropertyOnSiblings(i,"value",n.target.value,"value");o.formattedValue=null});i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null});let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(c){e.type=h;d&&(e.step=d)}if(o.userValue){const t=o.userValue;if(c)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Ut).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)});i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const n={value(i){o.userValue=i.detail.value??"";c||t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n;null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};c&&(s.value=n);t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n){s.removeAttribute("maxLength");return}s.setAttribute("maxLength",n);let r=o.userValue;if(r&&!(r.length<=n)){r=r.slice(0,n);s.value=o.userValue=r;t.setValue(e,{value:r});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}})}}};this._dispatchEventFromSandbox(n,i)});i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:n}=t.target;if(o.lastCommittedValue!==n){o.lastCommittedValue=n;o.userValue=n;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}});const n=blurListener;blurListener=null;i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(c){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf();i.step=""}else{s.includes("T")||(s=`${s}T00:00`);s=new Date(s).valueOf()}i.type="text"}o.userValue=s;o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});n(t)});this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:r,selectionEnd:a}=n;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})});this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof n){n="Off"!==n;t.setValue(i,{value:n})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");Nt.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="checkbox";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.setAttribute("exportValue",e.exportValue);s.tabIndex=0;s.addEventListener("change",n=>{const{name:s,checked:r}=n.target;for(const n of this._getElementsByName(s,i)){const i=r&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i);t.setValue(n.id,{value:i})}t.setValue(i,{value:r})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue});if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n){n=n!==e.buttonValue;t.setValue(i,{value:n})}if(n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");Nt.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="radio";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.tabIndex=0;s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue});if(this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e);t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");Nt.add(n);n.setAttribute("data-element-id",e);n.disabled=this.data.readOnly;this._setRequired(n,this.data.required);n.name=this.data.fieldName;n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;if(!this.data.combo){n.size=this.data.options.length;this.data.multiSelect&&(n.multiple=!0)}n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);s=!1}n.append(e)}let r=null;if(s){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);n.prepend(t);r=()=>{t.remove();n.removeEventListener("input",r);r=null};n.addEventListener("input",r)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let a=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",i=>{const s={value(i){r?.();const s=i.detail.value,o=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,r=i.detail.remove;s[r].selected=!1;n.remove(r);if(s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]});a=getValue(!1)},insert(i){const{index:s,displayValue:r,exportValue:o}=i.detail.insert,l=n.children[s],h=document.createElement("option");h.textContent=r;h.value=o;l?l.before(h):n.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");s.textContent=e;s.value=i;n.append(s)}n.options.length>0&&(n.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)});n.addEventListener("input",i=>{const n=getValue(!0),s=getValue(!1);t.setValue(e,{value:n});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})});this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)}else n.addEventListener("input",function(i){t.setValue(e,{value:getValue(!0)})});this.data.combo&&this._setTextStyle(n);this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;super(t,{isRenderable:!s&&AnnotationElement._hasPopupData(e)});this.elements=i;if(s&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#$r();for(const e of i)e.popup=t}else this.popup=null}#$r(){return new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation");t.role="comment";const e=this.popup=this.#$r(),i=[];for(const t of this.elements){t.popup=e;t.container.ariaHasPopup="dialog";i.push(t.data.id);t.addHighlightArea()}this.container.setAttribute("aria-controls",i.map(t=>`${V}${t}`).join(","));return this.container}}class PopupElement{#Y=null;#Xr=this.#Rr.bind(this);#qr=this.#Kr.bind(this);#Yr=this.#Qr.bind(this);#Jr=this.#Zr.bind(this);#ta=null;#It=null;#ea=null;#ia=null;#na=null;#sa=null;#ra=null;#aa=!1;#oa=null;#la=null;#U=null;#ha=null;#da=null;#Ce=null;#ca=null;#Ae=null;#ua=null;#Ur=null;#pa=!1;#ga=null;#ma=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#It=t;this.#ua=n;this.#ea=r;this.#Ae=a;this.#sa=o;this.#ta=e;this.#ca=l;this.#ra=h;this.#na=i;this.#Y=c;this.#ga=i[0];this.#ia=PDFDateString.toDateObject(s);this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup());if(!c){this.#fa();this.#It.hidden=!0;d&&this.#Zr()}}#fa(){if(this.#la)return;this.#la=new AbortController;const{signal:t}=this.#la;for(const e of this.trigger){e.addEventListener("click",this.#Jr,{signal:t});e.addEventListener("pointerenter",this.#Yr,{signal:t});e.addEventListener("pointerleave",this.#qr,{signal:t});e.classList.add("popupTriggerArea")}for(const e of this.#na)e.container?.addEventListener("keydown",this.#Xr,{signal:t})}#ba(){const t=this.#na.find(t=>t.hasCommentButton);t&&(this.#da=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#ha){this.#ha.parentNode||this.#ga.container.after(this.#ha);return}this.#da||this.#ba();if(!this.#da)return;const{signal:t}=this.#la=new AbortController,e=this.#ga.hasOwnCommentButton,togglePopup=()=>{this.#Y.toggleCommentPopup(this,!0,void 0,!e)},showPopup=()=>{this.#Y.toggleCommentPopup(this,!1,!0,!e)},hidePopup=()=>{this.#Y.toggleCommentPopup(this,!1,!1)};if(e){this.#ha=this.#ga.container;for(const e of this.trigger){e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.addEventListener("keydown",this.#Xr,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});e.classList.add("popupTriggerArea")}}else{const e=this.#ha=document.createElement("button");e.className="annotationCommentButton";const i=this.#ga.container;e.style.zIndex=i.style.zIndex+1;e.tabIndex=0;e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.setAttribute("data-l10n-id","pdfjs-show-comment-button");this.#wa();this.#ya();e.addEventListener("keydown",this.#Xr,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});i.after(e)}}#ya(){if(this.#ga.extraPopupElement&&!this.#ga.editor)return;this.#ha||this.renderCommentButton();const[t,e]=this.#da,{style:i}=this.#ha;i.left=`calc(${t}%)`;i.top=`calc(${e}% - var(--comment-button-dim))`}#wa(){if(!this.#ga.extraPopupElement){this.#ha||this.renderCommentButton();this.#ha.style.backgroundColor=this.commentButtonColor||""}}get commentButtonColor(){const{color:t,opacity:e}=this.#ga.commentData;return t?this.#sa._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#ha?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#ga.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#ha}get comment(){this.#ma||=this.#ga.commentText;return this.#ma}set comment(t){t!==this.comment&&(this.#ga.commentText=this.#ma=t)}focus(){this.#ga.container?.focus()}get parentBoundingClientRect(){return this.#ga.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#ha){this.#ha.classList.toggle("selected",t);this.#ha.ariaExpanded=e}}setSelectedCommentButton(t){this.#ha.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#Ce)return this.#Ce;const{x:t,y:e,height:i}=this.#ha.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#ga.layer.getBoundingClientRect();return[(t-n)/r,(e+i-s)/a]}set commentPopupPosition(t){this.#Ce=t}hasDefaultPopupPosition(){return null===this.#Ce}get commentButtonPosition(){return this.#da}get commentButtonWidth(){return this.#ha.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#Ce||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:r,width:a,height:o}=n;this.#Y.showDialog(null,this,s+e*a,r+i*o,{...t,parentDimensions:n})}render(){if(this.#oa)return;const t=this.#oa=document.createElement("div");t.className="popup";if(this.#ta){const e=t.style.outlineColor=Util.makeHexColor(...this.#ta);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";if(this.#ua?.str){const t=document.createElement("span");t.className="title";e.append(t);({dir:t.dir,str:t.textContent}=this.#ua)}t.append(e);if(this.#ia){const t=document.createElement("time");t.className="popupDate";t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ia.valueOf()}));t.dateTime=this.#ia.toISOString();e.append(t)}renderRichText({html:this.#Aa||this.#ea.str,dir:this.#ea?.dir,className:"popupContent"},t);this.#It.append(t)}get#Aa(){const t=this.#Ae,e=this.#ea;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ae.html||null}get#va(){return this.#Aa?.attributes?.style?.fontSize||0}get#xa(){return this.#Aa?.attributes?.style?.color||null}#Ea(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#xa,fontSize:this.#va?`calc(${this.#va}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}#Rr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#aa)&&this.#Zr()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#Y){if(i){this.remove();this.#ma=null}else if(e)if(e.deleted)this.remove();else{this.#wa();this.#ma=e.text}if(t){this.#da=null;this.#ba();this.#ya()}}else if(i||e?.deleted)this.remove();else{this.#fa();this.#Ur||={contentsObj:this.#ea,richText:this.#Ae};t&&(this.#U=null);if(e&&e.text){this.#Ae=this.#Ea(e.text);this.#ia=PDFDateString.toDateObject(e.date);this.#ea=null}this.#oa?.remove();this.#oa=null}}resetEdited(){if(this.#Ur){({contentsObj:this.#ea,richText:this.#Ae}=this.#Ur);this.#Ur=null;this.#oa?.remove();this.#oa=null;this.#U=null}}remove(){this.#la?.abort();this.#la=null;this.#oa?.remove();this.#oa=null;this.#pa=!1;this.#aa=!1;this.#ha?.remove();this.#ha=null;if(this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Ca(){if(null!==this.#U)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#sa;let r=!!this.#ra,a=r?this.#ra:this.#ca;for(const t of this.#na)if(!a||null!==Util.intersect(t.data.rect,a)){a=t.data.rect;r=!0;break}const o=Util.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=r?a[2]-a[0]+5:0,h=o[0]+l,d=o[1];this.#U=[100*(h-n)/e,100*(d-s)/i];const{style:c}=this.#It;c.left=`${this.#U[0]}%`;c.top=`${this.#U[1]}%`}#Zr(){if(this.#Y)this.#Y.toggleCommentPopup(this,!1);else{this.#aa=!this.#aa;if(this.#aa){this.#Qr();this.#It.addEventListener("click",this.#Jr);this.#It.addEventListener("keydown",this.#Xr)}else{this.#Kr();this.#It.removeEventListener("click",this.#Jr);this.#It.removeEventListener("keydown",this.#Xr)}}}#Qr(){this.#oa||this.render();if(this.isVisible)this.#aa&&this.#It.classList.add("focused");else{this.#Ca();this.#It.hidden=!1;this.#It.style.zIndex=parseInt(this.#It.style.zIndex)+1e3}}#Kr(){this.#It.classList.remove("focused");if(!this.#aa&&this.isVisible){this.#It.hidden=!0;this.#It.style.zIndex=parseInt(this.#It.style.zIndex)-1e3}}forceHide(){this.#pa=this.isVisible;this.#pa&&(this.#It.hidden=!0)}maybeShow(){if(!this.#Y){this.#fa();if(this.#pa){this.#oa||this.#Qr();this.#pa=!1;this.#It.hidden=!1}}}get isVisible(){return!this.#Y&&!1===this.#It.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=p.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent");t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e;t.append(i)}this.container.append(t)}if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#Sa=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Sa=this.svgFactory.createElement("svg:line");s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);s.setAttribute("stroke-width",t.borderStyle.width||1);s.setAttribute("stroke","transparent");s.setAttribute("fill","transparent");n.append(s);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Sa}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Ta=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Ta=this.svgFactory.createElement("svg:rect");r.setAttribute("x",s/2);r.setAttribute("y",s/2);r.setAttribute("width",e-s);r.setAttribute("height",i-s);r.setAttribute("stroke-width",s||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");n.append(r);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ta}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#_a=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#_a=this.svgFactory.createElement("svg:ellipse");r.setAttribute("cx",e/2);r.setAttribute("cy",i/2);r.setAttribute("rx",e/2-s/2);r.setAttribute("ry",i/2-s/2);r.setAttribute("stroke-width",s||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");n.append(r);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#_a}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#Ma=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="polylineAnnotation";this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(s,r,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#Ma=this.svgFactory.createElement(this.svgElementName);l.setAttribute("points",o);l.setAttribute("stroke-width",i.width||1);l.setAttribute("stroke","transparent");l.setAttribute("fill","transparent");a.append(l);this.container.append(a);if(!n&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ma}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t);this.containerClassName="polygonAnnotation";this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("caretAnnotation");if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}}class InkAnnotationElement extends AnnotationElement{#Da=null;#Pa=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="inkAnnotation";this.svgElementName="svg:polyline";this.annotationEditorType="InkHighlight"===this.data.it?p.HIGHLIGHT:p.INK}#ka(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:r,width:a,height:o}=this.#ka(e,t),l=this.svgFactory.create(a,o,!0),h=this.#Da=this.svgFactory.createElement("svg:g");l.append(h);h.setAttribute("stroke-width",n.width||1);h.setAttribute("stroke-linecap","round");h.setAttribute("stroke-linejoin","round");h.setAttribute("stroke-miterlimit",10);h.setAttribute("stroke","transparent");h.setAttribute("fill","transparent");h.setAttribute("transform",r);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Pa.push(e);e.setAttribute("points",i[t].join(","));h.append(e)}if(!s&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.append(l);this._editOnDoubleClick();return this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#Da;e>=0&&s.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#Pa.length;t<e;t++)this.#Pa[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#ka(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`);s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Pa}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0});this.annotationEditorType=p.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("highlightAnnotation");this._editOnDoubleClick();if(t){const e=document.createElement("mark");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("underlineAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("squigglyAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("strikeoutAnnotation");if(t){const e=document.createElement("s");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.annotationEditorType=p.STAMP}render(){this.container.classList.add("stampAnnotation");this.container.setAttribute("role","img");if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this._editOnDoubleClick();return this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#Ia=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename;this.content=e.content;this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let i;if(e.hasAppearance||0===e.fillAlpha)i=document.createElement("div");else{i=document.createElement("img");i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`;e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)}i.addEventListener("dblclick",this.#Fa.bind(this));this.#Ia=i;const{isMac:n}=util_FeatureTest.platform;t.addEventListener("keydown",t=>{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#Fa()});if(!e.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}else i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#Ia}addHighlightArea(){this.container.classList.add("highlightArea")}#Fa(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Ra=null;#Ba=null;#X=null;#La=new Map;#Oa=null;#Na=null;#na=[];#Ua=!1;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t;this.#Ra=e;this.#Ba=i;this.#Oa=a||null;this.#Na=l||null;this.#X=h||new AnnotationStorage;this.page=s;this.viewport=r;this.zIndex=0;this._annotationEditorUIManager=n;this._commentManager=o||null}hasEditableAnnotations(){return this.#La.size>0}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const n=new Map,s=[],r={data:null,layer:i,linkService:this.#Na,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#X,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===S.POPUP;if(e){const e=n.get(t.id);if(!e)continue;if(!this._commentManager){s.push(t);continue}r.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;if(!e){this.#na.push(i);if(t.popupRef){const e=n.get(t.popupRef);e?e.push(i):n.set(t.popupRef,[i])}}const a=i.render();t.hidden&&(a.style.visibility="hidden");if(i._isEditable){this.#La.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}await this.#Ha();for(const t of s){const e=r.elements=n.get(t.id);r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;const s=i.render();i.contentElement.id=`${V}${t.id}`;t.hidden&&(s.style.visibility="hidden");e.at(-1).container.after(s)}this.#za()}async#Ha(){if(0===this.#na.length)return;this.div.replaceChildren();const t=[];if(!this.#Ua){this.#Ua=!0;for(const{contentElement:e,data:{id:i}}of this.#na){const n=e.id=`${V}${i}`;t.push(this.#Oa?.getAriaAttributes(n).then(t=>{if(t)for(const[i,n]of t)e.setAttribute(i,n)}))}}this.#na.sort(({data:{rect:[t,e,i,n]}},{data:{rect:[s,r,a,o]}})=>{if(t===i&&e===n)return 1;if(s===a&&r===o)return-1;const l=(e+n)/2,h=(r+o)/2;if(l>=o&&h<=e)return-1;if(h>=n&&l<=r)return 1;return(t+i)/2-(s+a)/2});const e=document.createDocumentFragment();for(const t of this.#na){e.append(t.container);this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render())}this.div.append(e);await Promise.all(t);if(this.#Ra)for(const t of this.#na)this.#Ra.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#Na,svgFactory:new DOMSVGFactory,parent:this};for(const i of t){i.borderStyle||=AnnotationLayer._defaultBorderStyle;e.data=i;const t=AnnotationElementFactory.create(e);if(t.isRenderable){t.render();t.contentElement.id=`${V}${i.id}`;this.#na.push(t)}}await this.#Ha()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#za();e.hidden=!1}#za(){if(!this.#Ba)return;const t=this.div;for(const[e,i]of this.#Ba){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i);const r=this.#La.get(e);if(r)if(r._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i);r._hasNoCanvas=!1}else r.canvas=i}this.#Ba.clear()}getEditableAnnotations(){return Array.from(this.#La.values())}getEditableAnnotation(t){return this.#La.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#Na,annotationStorage:this.#X});s.render();s.contentElement.id=`${V}${i}`;s.createOrUpdatePopup();this.#na.push(s);return s}removeAnnotation(t){const e=this.#na.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#na.splice(e,1);this.#Ra?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#Ha()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:T,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ht=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#Ga="";#Wa=`${this.id}-editor`;#Va=null;#va;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=p.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#va=t.fontSize||FreeTextEditor._defaultFontSize;this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert");this.canAddComment=!1}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case g.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case g.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case g.FREETEXT_SIZE:this.#ja(e);break;case g.FREETEXT_COLOR:this.#wa(e)}}static get defaultPropertiesToUpdate(){return[[g.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[g.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[g.FREETEXT_SIZE,this.#va],[g.FREETEXT_COLOR,this.color]]}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return g.FREETEXT_COLOR}#ja(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#va)*this.parentScale);this.#va=t;this.#$a()},e=this.#va;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color;this._colorPicker?.update(this.color);super.onUpdatedColor()}#wa(t){const setColor=t=>{this.color=t;this.onUpdatedColor()},e=this.color;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#va)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Va=new AbortController;const t=this._uiManager.combinedSignal(this.#Va);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t});return!0}disableEditMode(){if(!super.disableEditMode())return!1;this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#Wa);this._isDraggable=!0;this.#Va?.abort();this.#Va=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing");return!0}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Xa(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#qa(i));e=i}return t.join("\n")}#$a(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=n;e.classList.toggle("hidden",s)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Ga,e=this.#Ga=this.#Xa().trimEnd();if(t===e)return;const setText=t=>{this.#Ga=t;if(t){this.#Ka();this._uiManager.rebuild(this);this.#$a()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#$a()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy||this.annotationElementId){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#Wa);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#va}px * var(--total-scale-factor))`;i.color=this.color;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);if(this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(s[0]-h)/o;u=e+this.height-(s[1]-d)/l;break;case 90:c=t+(s[0]-h)/o;u=e-(s[1]-d)/l;[r,a]=[a,-r];break;case 180:c=t-this.width+(s[0]-h)/o;u=e-(s[1]-d)/l;[r,a]=[-r,-a];break;case 270:c=t+(s[0]-h-this.height*l)/o;u=e+(s[1]-d-this.width*o)/l;[r,a]=[-a,r]}this.setAt(c*i,u*n,r,a)}else this._moveAfterPaste(t,e);this.#Ka();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#qa(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ht,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=FreeTextEditor.#Ya(e.getData("text")||"").replaceAll(Ht,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize();s.deleteFromDocument();const r=s.getRangeAt(0);if(!n.includes("\n")){r.insertNode(document.createTextNode(n));this.editorDiv.normalize();s.collapseToStart();return}const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;h.push(a.nodeValue.slice(o).replaceAll(Ht,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#qa(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Ht,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#qa(i))}}this.#Ga=`${l.join("\n")}${n}${h.join("\n")}`;this.#Ka();const d=new Range;let c=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}s.removeAllRanges();s.addRange(d)}#Ka(){this.editorDiv.replaceChildren();if(this.#Ga)for(const t of this.#Ga.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Qa(){return this.#Ga.replaceAll(" "," ")}static#Ya(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=FreeTextEditor._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:g,parent:{page:{pageNumber:m}}}=t;if(!u||0===u.length)return null;n=t={annotationType:p.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:g,pageIndex:m-1,rect:s.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}const s=await super.deserialize(t,e,i);s.#va=t.fontSize;s.color=Util.makeHexColor(...t.color);s.#Ga=FreeTextEditor.#Ya(t.value);s._initialData=n;t.comment&&s.setCommentData(t);return s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#va,value:this.#Qa()});this.addComment(i);if(t){i.isCopy=!0;return i}if(this.annotationElementId&&!this.#Ja(i))return null;i.id=this.annotationElementId;return i}#Ja(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#va}px * var(--total-scale-factor))`;i.color=this.color;e.replaceChildren();for(const t of this.#Ga.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#Ga}});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2){r[a]=e+t[a]*n;r[a+1]=i+t[a+1]*s}return r}static _rescaleAndSwap(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2){r[a]=e+t[a+1]*n;r[a+1]=i+t[a]*s}return r}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,r=t.length;s<r;s+=2){n[s]=e+t[s];n[s+1]=i+t[s+1]}return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,n,s,r){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+r)/6,(i+s)/2,(n+r)/2]}}class FreeDrawOutliner{#Za;#to=[];#eo;#io;#no=[];#so=new Float32Array(18);#ro;#ao;#oo;#lo;#ho;#do;#co=[];static#uo=8;static#po=2;static#go=FreeDrawOutliner.#uo+FreeDrawOutliner.#po;constructor({x:t,y:e},i,n,s,r,a=0){this.#Za=i;this.#do=s*n;this.#io=r;this.#so.set([NaN,NaN,NaN,NaN,t,e],6);this.#eo=a;this.#lo=FreeDrawOutliner.#uo*n;this.#oo=FreeDrawOutliner.#go*n;this.#ho=n;this.#co.push(t,e)}isEmpty(){return isNaN(this.#so[8])}#mo(){const t=this.#so.subarray(4,6),e=this.#so.subarray(16,18),[i,n,s,r]=this.#Za;return[(this.#ro+(t[0]-e[0])/2-i)/s,(this.#ao+(t[1]-e[1])/2-n)/r,(this.#ro+(e[0]-t[0])/2-i)/s,(this.#ao+(e[1]-t[1])/2-n)/r]}add({x:t,y:e}){this.#ro=t;this.#ao=e;const[i,n,s,r]=this.#Za;let[a,o,l,h]=this.#so.subarray(8,12);const d=t-l,c=e-h,u=Math.hypot(d,c);if(u<this.#oo)return!1;const p=u-this.#lo,g=p/u,m=g*d,f=g*c;let b=a,w=o;a=l;o=h;l+=m;h+=f;this.#co?.push(t,e);const y=m/p,A=-f/p*this.#do,v=y*this.#do;this.#so.set(this.#so.subarray(2,8),0);this.#so.set([l+A,h+v],4);this.#so.set(this.#so.subarray(14,18),12);this.#so.set([l-A,h-v],16);if(isNaN(this.#so[6])){if(0===this.#no.length){this.#so.set([a+A,o+v],2);this.#no.push(NaN,NaN,NaN,NaN,(a+A-i)/s,(o+v-n)/r);this.#so.set([a-A,o-v],14);this.#to.push(NaN,NaN,NaN,NaN,(a-A-i)/s,(o-v-n)/r)}this.#so.set([b,w,a,o,l,h],6);return!this.isEmpty()}this.#so.set([b,w,a,o,l,h],6);if(Math.abs(Math.atan2(w-o,b-a)-Math.atan2(f,m))<Math.PI/2){[a,o,l,h]=this.#so.subarray(2,6);this.#no.push(NaN,NaN,NaN,NaN,((a+l)/2-i)/s,((o+h)/2-n)/r);[a,o,b,w]=this.#so.subarray(14,18);this.#to.push(NaN,NaN,NaN,NaN,((b+a)/2-i)/s,((w+o)/2-n)/r);return!0}[b,w,a,o,l,h]=this.#so.subarray(0,6);this.#no.push(((b+5*a)/6-i)/s,((w+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r);[l,h,a,o,b,w]=this.#so.subarray(12,18);this.#to.push(((b+5*a)/6-i)/s,((w+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r);return!0}toSVGPath(){if(this.isEmpty())return"";const t=this.#no,e=this.#to;if(isNaN(this.#so[6])&&!this.isEmpty())return this.#fo();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#bo(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#wo(i);return i.join(" ")}#fo(){const[t,e,i,n]=this.#Za,[s,r,a,o]=this.#mo();return`M${(this.#so[2]-t)/i} ${(this.#so[3]-e)/n} L${(this.#so[4]-t)/i} ${(this.#so[5]-e)/n} L${s} ${r} L${a} ${o} L${(this.#so[16]-t)/i} ${(this.#so[17]-e)/n} L${(this.#so[14]-t)/i} ${(this.#so[15]-e)/n} Z`}#wo(t){const e=this.#to;t.push(`L${e[4]} ${e[5]} Z`)}#bo(t){const[e,i,n,s]=this.#Za,r=this.#so.subarray(4,6),a=this.#so.subarray(16,18),[o,l,h,d]=this.#mo();t.push(`L${(r[0]-e)/n} ${(r[1]-i)/s} L${o} ${l} L${h} ${d} L${(a[0]-e)/n} ${(a[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,r){return new FreeDrawOutline(t,e,i,n,s,r)}getOutlines(){const t=this.#no,e=this.#to,i=this.#so,[n,s,r,a]=this.#Za,o=new Float32Array((this.#co?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2){o[t]=(this.#co[t]-n)/r;o[t+1]=(this.#co[t+1]-s)/a}o[o.length-2]=(this.#ro-n)/r;o[o.length-1]=(this.#ao-s)/a;if(isNaN(i[6])&&!this.isEmpty())return this.#yo(o);const l=new Float32Array(this.#no.length+24+this.#to.length);let h=t.length;for(let e=0;e<h;e+=2)if(isNaN(t[e]))l[e]=l[e+1]=NaN;else{l[e]=t[e];l[e+1]=t[e+1]}h=this.#Ao(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#vo(l,h);return this.newFreeDrawOutline(l,o,this.#Za,this.#ho,this.#eo,this.#io)}#yo(t){const e=this.#so,[i,n,s,r]=this.#Za,[a,o,l,h]=this.#mo(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/r,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/r,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/r],0);return this.newFreeDrawOutline(d,t,this.#Za,this.#ho,this.#eo,this.#io)}#vo(t,e){const i=this.#to;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#Ao(t,e){const i=this.#so.subarray(4,6),n=this.#so.subarray(16,18),[s,r,a,o]=this.#Za,[l,h,d,c]=this.#mo();t.set([NaN,NaN,NaN,NaN,(i[0]-s)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(n[0]-s)/a,(n[1]-r)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Za;#xo=new Float32Array(4);#eo;#io;#co;#ho;#Eo;constructor(t,e,i,n,s,r){super();this.#Eo=t;this.#co=e;this.#Za=i;this.#ho=n;this.#eo=s;this.#io=r;this.firstPoint=[NaN,NaN];this.lastPoint=[NaN,NaN];this.#Co(r);const[a,o,l,h]=this.#xo;for(let e=0,i=t.length;e<i;e+=2){t[e]=(t[e]-a)/l;t[e+1]=(t[e+1]-o)/h}for(let t=0,i=e.length;t<i;t+=2){e[t]=(e[t]-a)/l;e[t+1]=(e[t+1]-o)/h}}toSVGPath(){const t=[`M${this.#Eo[4]} ${this.#Eo[5]}`];for(let e=6,i=this.#Eo.length;e<i;e+=6)isNaN(this.#Eo[e])?t.push(`L${this.#Eo[e+4]} ${this.#Eo[e+5]}`):t.push(`C${this.#Eo[e]} ${this.#Eo[e+1]} ${this.#Eo[e+2]} ${this.#Eo[e+3]} ${this.#Eo[e+4]} ${this.#Eo[e+5]}`);t.push("Z");return t.join(" ")}serialize([t,e,i,n],s){const r=i-t,a=n-e;let o,l;switch(s){case 0:o=Outline._rescale(this.#Eo,t,n,r,-a);l=Outline._rescale(this.#co,t,n,r,-a);break;case 90:o=Outline._rescaleAndSwap(this.#Eo,t,e,r,a);l=Outline._rescaleAndSwap(this.#co,t,e,r,a);break;case 180:o=Outline._rescale(this.#Eo,i,e,-r,a);l=Outline._rescale(this.#co,i,e,-r,a);break;case 270:o=Outline._rescaleAndSwap(this.#Eo,i,n,-r,-a);l=Outline._rescaleAndSwap(this.#co,i,n,-r,-a)}return{outline:Array.from(o),points:[Array.from(l)]}}#Co(t){const e=this.#Eo;let i=e[4],n=e[5];const s=[i,n,i,n];let r=i,a=n,o=i,l=n;const h=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,c=e.length;t<c;t+=6){const c=e[t+4],u=e[t+5];if(isNaN(e[t])){Util.pointBoundingBox(c,u,s);if(a>u){r=c;a=u}else a===u&&(r=h(r,c));if(l<u){o=c;l=u}else l===u&&(o=h(o,c))}else{d[0]=d[1]=1/0;d[2]=d[3]=-1/0;Util.bezierBoundingBox(i,n,...e.slice(t,t+6),d);Util.rectBoundingBox(d[0],d[1],d[2],d[3],s);if(a>d[1]){r=d[0];a=d[1]}else a===d[1]&&(r=h(r,d[0]));if(l<d[3]){o=d[2];l=d[3]}else l===d[3]&&(o=h(o,d[2]))}i=c;n=u}const c=this.#xo;c[0]=s[0]-this.#eo;c[1]=s[1]-this.#eo;c[2]=s[2]-s[0]+2*this.#eo;c[3]=s[3]-s[1]+2*this.#eo;this.firstPoint=[r,a];this.lastPoint=[o,l]}get box(){return this.#xo}newOutliner(t,e,i,n,s,r=0){return new FreeDrawOutliner(t,e,i,n,s,r)}getNewOutline(t,e){const[i,n,s,r]=this.#xo,[a,o,l,h]=this.#Za,d=s*l,c=r*h,u=i*l+a,p=n*h+o,g=this.newOutliner({x:this.#co[0]*d+u,y:this.#co[1]*c+p},this.#Za,this.#ho,t,this.#io,e??this.#eo);for(let t=2;t<this.#co.length;t+=2)g.add({x:this.#co[t]*d+u,y:this.#co[t+1]*c+p});return g.getOutlines()}}class HighlightOutliner{#Za;#So;#To;#_o=[];#Mo=[];constructor(t,e=0,i=0,n=!0){const s=[1/0,1/0,-1/0,-1/0],r=1e-4;for(const{x:i,y:n,width:a,height:o}of t){const t=Math.floor((i-e)/r)*r,l=Math.ceil((i+a+e)/r)*r,h=Math.floor((n-e)/r)*r,d=Math.ceil((n+o+e)/r)*r,c=[t,h,d,!0],u=[l,h,d,!1];this.#_o.push(c,u);Util.rectBoundingBox(t,h,l,d,s)}const a=s[2]-s[0]+2*i,o=s[3]-s[1]+2*i,l=s[0]-i,h=s[1]-i;let d=n?-1/0:1/0,c=1/0;const u=this.#_o.at(n?-1:-2),p=[u[0],u[2]];for(const t of this.#_o){const[e,i,s,r]=t;if(!r&&n)if(i<c){c=i;d=e}else i===c&&(d=Math.max(d,e));else if(r&&!n)if(i<c){c=i;d=e}else i===c&&(d=Math.min(d,e));t[0]=(e-l)/a;t[1]=(i-h)/o;t[2]=(s-h)/o}this.#Za=new Float32Array([l,h,a,o]);this.#So=[d,c];this.#To=p}getOutlines(){this.#_o.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#_o)if(e[3]){t.push(...this.#Do(e));this.#Po(e)}else{this.#ko(e);t.push(...this.#Do(e))}return this.#Io(t)}#Io(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s);s.push(n);i.add(n);i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,d=r;s=[e,a];n.push(s);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,r,a,o,l]=t;if(h!==e){s.push(h,d,e,d===r?r:a);h=e}d=d===r?a:r}s.push(h,d)}return new HighlightOutline(n,this.#Za,this.#So,this.#To)}#Fo(t){const e=this.#Mo;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,r=e[s][0];if(r===t)return s;r<t?i=s+1:n=s-1}return n+1}#Po([,t,e]){const i=this.#Fo(t);this.#Mo.splice(i,0,[t,e])}#ko([,t,e]){const i=this.#Fo(t);for(let n=i;n<this.#Mo.length;n++){const[i,s]=this.#Mo[n];if(i!==t)break;if(i===t&&s===e){this.#Mo.splice(n,1);return}}for(let n=i-1;n>=0;n--){const[i,s]=this.#Mo[n];if(i!==t)break;if(i===t&&s===e){this.#Mo.splice(n,1);return}}}#Do(t){const[e,i,n]=t,s=[[e,i,n]],r=this.#Fo(n);for(let t=0;t<r;t++){const[i,n]=this.#Mo[t];for(let t=0,r=s.length;t<r;t++){const[,a,o]=s[t];if(!(n<=a||o<=i))if(a>=i)if(o>n)s[t][1]=n;else{if(1===r)return[];s.splice(t,1);t--;r--}else{s[t][2]=i;o>n&&s.push([e,n,o])}}}return s}}class HighlightOutline extends Outline{#Za;#Ro;constructor(t,e,i,n){super();this.#Ro=t;this.#Za=e;this.firstPoint=i;this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#Ro){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const r=e[s],a=e[s+1];if(r===i){t.push(`V${a}`);n=a}else if(a===n){t.push(`H${r}`);i=r}}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const r=[],a=i-t,o=n-e;for(const e of this.#Ro){const i=new Array(e.length);for(let s=0;s<e.length;s+=2){i[s]=t+e[s]*a;i[s+1]=n-e[s+1]*o}r.push(i)}return r}get box(){return this.#Za}get classNamesForOutlining(){return["highlightOutline"]}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,i,n,s,r){return new FreeHighlightOutline(t,e,i,n,s,r)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,i,n,s,r=0){return new FreeHighlightOutliner(t,e,i,n,s,r)}}class HighlightEditor extends AnnotationEditor{#Bo=null;#Lo=0;#Oo;#No=null;#c=null;#Uo=null;#Ho=null;#zo=0;#Go=null;#Wo=null;#I=null;#Vo=!1;#So=null;#To=null;#jo=null;#ve="";#do;#$o="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=p.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=HighlightEditor.prototype;return shadow(this,"_keyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"});this.color=t.color||HighlightEditor._defaultColor;this.#do=t.thickness||HighlightEditor._defaultThickness;this.opacity=t.opacity||HighlightEditor._defaultOpacity;this.#Oo=t.boxes||null;this.#$o=t.methodOfCreation||"";this.#ve=t.text||"";this._isDraggable=!1;this.defaultL10nId="pdfjs-editor-highlight-editor";if(t.highlightId>-1){this.#Vo=!0;this.#Xo(t);this.#qo()}else if(this.#Oo){this.#Bo=t.anchorNode;this.#Lo=t.anchorOffset;this.#Ho=t.focusNode;this.#zo=t.focusOffset;this.#Ko();this.#qo();this.rotate(this.rotation)}this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#Vo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#do,methodOfCreation:this.#$o}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#Ko(){const t=new HighlightOutliner(this.#Oo,.001);this.#Wo=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#Wo.box;const e=new HighlightOutliner(this.#Oo,.0025,.001,"ltr"===this._uiManager.direction);this.#Uo=e.getOutlines();const{firstPoint:i}=this.#Wo;this.#So=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#Uo;this.#To=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#Xo({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#Wo=t;this.#Uo=t.getNewOutline(this.#do/2+1.5,.0025);if(e>=0){this.#I=e;this.#No=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#jo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#Uo.box,path:{d:this.#Uo.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#I,{bbox:HighlightEditor.#Yo(this.#Wo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#jo,{bbox:HighlightEditor.#Yo(this.#Uo.box,e),path:{d:this.#Uo.toSVGPath()}})}const[n,s,r,a]=t.box;switch(this.rotation){case 0:this.x=n;this.y=s;this.width=r;this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=s;this.y=1-n;this.width=r*e/t;this.height=a*t/e;break}case 180:this.x=1-n;this.y=1-s;this.width=r;this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s;this.y=n;this.width=r*e/t;this.height=a*t/e;break}}const{firstPoint:o}=t;this.#So=[(o[0]-n)/r,(o[1]-s)/a];const{lastPoint:l}=this.#Uo;this.#To=[(l[0]-n)/r,(l[1]-s)/a]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case g.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#To}get commentButtonPosition(){return this.#So}updateParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:this.#wa(e);break;case g.HIGHLIGHT_THICKNESS:this.#Qo(e)}}static get defaultPropertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,this.#do||HighlightEditor._defaultThickness],[g.HIGHLIGHT_FREE,this.#Vo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#I,{root:{fill:this.color,"fill-opacity":this.opacity}});this.#c?.updateColor(this.color);super.onUpdatedColor()}#wa(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.opacity=e;this.onUpdatedColor()},e=this.color,i=this.opacity;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Qo(t){const e=this.#do,setThickness=t=>{this.#do=t;this.#Jo(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#c=new ColorPicker({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Zo())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Zo())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#tl();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#qo();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#tl();else if(t){this.#qo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#Jo(t){if(this.#Vo){this.#Xo({highlightOutlines:this.#Wo.getNewOutline(t/2)});this.fixAndSetPosition();this.setDims()}}#tl(){if(null!==this.#I&&this.parent){this.parent.drawLayer.remove(this.#I);this.#I=null;this.parent.drawLayer.remove(this.#jo);this.#jo=null}}#qo(t=this.parent){if(null===this.#I){({id:this.#I,clipPathId:this.#No}=t.drawLayer.draw({bbox:this.#Wo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Vo},path:{d:this.#Wo.toSVGPath()}},!1,!0));this.#jo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Vo},bbox:this.#Uo.box,path:{d:this.#Uo.toSVGPath()}},this.#Vo);this.#Go&&(this.#Go.style.clipPath=this.#No)}}static#Yo([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Vo){t=(t-this.rotation+360)%360;i=HighlightEditor.#Yo(this.#Wo.box,t)}else i=HighlightEditor.#Yo([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#I,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#jo,{bbox:HighlightEditor.#Yo(this.#Uo.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#ve){t.setAttribute("aria-label",this.#ve);t.setAttribute("role","mark")}this.#Vo?t.classList.add("free"):this.div.addEventListener("keydown",this.#el.bind(this),{signal:this._uiManager._signal});const e=this.#Go=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#No;this.setDims();bindEvents(this,this.#Go,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!1}})}#el(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#il(!0);break;case 1:case 3:this.#il(!1)}}#il(t){if(!this.#Bo)return;const e=window.getSelection();t?e.setPosition(this.#Bo,this.#Lo):e.setPosition(this.#Ho,this.#zo)}select(){super.select();this.#jo&&this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#jo){this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{selected:!1}});this.#Vo||this.#il(!1)}}get _mustFixPosition(){return!this.#Vo}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#I,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#jo,{rootClass:{hidden:!t}})}}#Zo(){return this.#Vo?this.rotation:0}#nl(){if(this.#Vo)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#Oo,r=new Float32Array(8*s.length);let a=0;for(const{x:o,y:l,width:h,height:d}of s){const s=o*t+i,c=(1-l)*e+n;r[a]=r[a+4]=s;r[a+1]=r[a+3]=c;r[a+2]=r[a+6]=s+h*t;r[a+5]=r[a+7]=c-d*e;a+=8}return r}#sl(t){return this.#Wo.serialize(t,this.#Zo())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#rl(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#al.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:n,y:s},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#al(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#rl(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:s,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:p.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:p.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}const{color:s,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...s);l.opacity=o||1;a&&(l.#do=t.thickness);l._initialData=n;t.comment&&l.setCommentData(t);const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(r){const t=l.#Oo=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-c)/h,y:1-(r[e+1]-u)/d,width:(r[e+2]-r[e])/h,height:(r[e+1]-r[e+5])/d});l.#Ko();l.#qo();l.rotate(l.rotation)}else if(a){l.#Vo=!0;const t=a[0],i={x:t[0]-c,y:d-(t[1]-u)},n=new FreeHighlightOutliner(i,[0,0,h,d],1,l.#do/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2){i.x=t[e]-c;i.y=d-(t[e+1]-u);n.add(i)}const{id:s,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);l.#Xo({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:r});l.#qo();l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#do,quadPoints:this.#nl(),outlines:this.#sl(i.rect)});this.addComment(i);if(this.annotationElementId&&!this.#Ja(i))return null;i.id=this.annotationElementId;return i}#Ja(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#ol=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#ol[t]=e}toSVGProperties(){const t=this.#ol;this.#ol=Object.create(null);return{root:t}}reset(){this.#ol=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#ll=null;#hl;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#dl=null;static#cl=null;static#ul=null;static _INNER_MARGIN=3;constructor(t){super(t);this.#hl=t.mustBeCommitted||!1;this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color);super.onUpdatedColor()}_addOutlines(t){if(t.drawOutlines){this.#pl(t);this.#qo()}}#pl({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ll=t;this._drawingOptions||=i;this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#gl(t,this.parent);this.#ml(t.box)}#gl(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#dl.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],setter=i=>{n.updateProperty(e,i);const s=this.#ll.updateProperty(e,i);s&&this.#ml(s);this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties());t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathResizingSVGProperties(this.#fl()),{bbox:this.#bl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathResizedSVGProperties(this.#fl()),{bbox:this.#bl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#bl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathTranslatedSVGProperties(this.#fl(),this.parentDimensions),{bbox:this.#bl()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#hl){this.#hl=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#tl();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#qo();this.#ml(this.#ll.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#tl()}else if(t){this._uiManager.addShouldRescale(this);this.#qo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#tl(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#qo(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#gl(this.#ll,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#wl([t,e,i,n]){const{parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/s),n*(s/r)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(r/s),n*(s/r)];default:return[t,e,i,n]}}#fl(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(s/r),n*(r/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/r),n*(r/s)];default:return[t,e,i,n]}}#ml(t){[this.x,this.y,this.width,this.height]=this.#wl(t);if(this.div){this.fixAndSetPosition();this.setDims()}this._onResized()}#bl(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*s+r)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(a/o),n*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),n*(o/a)];case 6:return[1-t-n*(o/a),1-e,n*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-n*(o/a),i*(a/o),n*(o/a)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/a),e,n*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-n*(o/a),i*(a/o),n*(o/a)];case 14:return[1-t,1-e-i*(a/o),n*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),n*(o/a)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#bl()},this.#ll.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#ml(this.#ll.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}const i=super.render();i.classList.add("draw");const n=document.createElement("div");i.append(n);n.setAttribute("aria-hidden","true");n.className="internal";this.setDims();this._uiManager.addShouldRescale(this);this.disableEditing();this._isCopy&&this._moveAfterPaste(t,e);return i}static createDrawerInstance(t,e,i,n,s){unreachable("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=n;if(CurrentPointers.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:d,height:c}=s.getBoundingClientRect(),u=DrawingEditor.#cl=new AbortController,p=t.combinedSignal(u);CurrentPointers.setPointer(l,o);window.addEventListener("pointerup",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p});window.addEventListener("pointercancel",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p});window.addEventListener("pointerdown",t=>{if(CurrentPointers.isSamePointerType(t.pointerType)){CurrentPointers.initializeAndAddPointerId(t.pointerId);if(DrawingEditor.#dl.isCancellable()){DrawingEditor.#dl.removeLastElement();DrawingEditor.#dl.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}},{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});s.addEventListener("touchmove",t=>{CurrentPointers.isSameTimeStamp(t.timeStamp)&&stopEvent(t)},{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#dl)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.startNew(r,a,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#dl=this.createDrawerInstance(r,a,d,c,h);DrawingEditor.#ul=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#ul.toSVGProperties(),DrawingEditor.#dl.defaultSVGProperties),!0,!1))}}static _drawMove(t){CurrentPointers.isSameTimeStamp(t.timeStamp);if(!DrawingEditor.#dl)return;const{offsetX:e,offsetY:i,pointerId:n}=t;if(CurrentPointers.isSamePointerId(n))if(CurrentPointers.isUsingMultiplePointers())this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.add(e,i));CurrentPointers.setTimeStamp(t.timeStamp);stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#dl=null;DrawingEditor.#ul=null;CurrentPointers.clearTimeStamp()}if(DrawingEditor.#cl){DrawingEditor.#cl.abort();DrawingEditor.#cl=null;CurrentPointers.clearPointerIds()}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#dl,i=this._currentDrawId,n=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:g.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(g.DRAW_STEP);if(!DrawingEditor.#dl.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#dl.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:DrawingEditor.#ul,mustBeCommitted:!t});this._cleanup(!0);return r}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,r){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#pl({drawOutlines:o});l.#qo();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#ll.serialize([e,i,n,s],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getPDFRect()});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#so=new Float64Array(6);#Sa;#yl;#Ps;#do;#co;#Al="";#vl=0;#Ro=new InkDrawOutline;#xl;#El;constructor(t,e,i,n,s,r){this.#xl=i;this.#El=n;this.#Ps=s;this.#do=r;[t,e]=this.#Cl(t,e);const a=this.#Sa=[NaN,NaN,NaN,NaN,t,e];this.#co=[t,e];this.#yl=[{line:a,points:this.#co}];this.#so.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#do=e)}#Cl(t,e){return Outline._normalizePoint(t,e,this.#xl,this.#El,this.#Ps)}isEmpty(){return!this.#yl||0===this.#yl.length}isCancellable(){return this.#co.length<=10}add(t,e){[t,e]=this.#Cl(t,e);const[i,n,s,r]=this.#so.subarray(2,6),a=t-s,o=e-r;if(Math.hypot(this.#xl*a,this.#El*o)<=2)return null;this.#co.push(t,e);if(isNaN(i)){this.#so.set([s,r,t,e],2);this.#Sa.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#so[0])&&this.#Sa.splice(6,6);this.#so.set([i,n,s,r,t,e],0);this.#Sa.push(...Outline.createBezierPoints(i,n,s,r,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#co.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#xl=i;this.#El=n;this.#Ps=s;[t,e]=this.#Cl(t,e);const r=this.#Sa=[NaN,NaN,NaN,NaN,t,e];this.#co=[t,e];const a=this.#yl.at(-1);if(a){a.line=new Float32Array(a.line);a.points=new Float32Array(a.points)}this.#yl.push({line:r,points:this.#co});this.#so.set(r,0);this.#vl=0;this.toSVGPath();return null}getLastElement(){return this.#yl.at(-1)}setLastElement(t){if(!this.#yl)return this.#Ro.setLastElement(t);this.#yl.push(t);this.#Sa=t.line;this.#co=t.points;this.#vl=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#yl)return this.#Ro.removeLastElement();this.#yl.pop();this.#Al="";for(let t=0,e=this.#yl.length;t<e;t++){const{line:e,points:i}=this.#yl[t];this.#Sa=e;this.#co=i;this.#vl=0;this.toSVGPath()}return{path:{d:this.#Al}}}toSVGPath(){const t=Outline.svgRound(this.#Sa[4]),e=Outline.svgRound(this.#Sa[5]);if(2===this.#co.length){this.#Al=`${this.#Al} M ${t} ${e} Z`;return this.#Al}if(this.#co.length<=6){const i=this.#Al.lastIndexOf("M");this.#Al=`${this.#Al.slice(0,i)} M ${t} ${e}`;this.#vl=6}if(4===this.#co.length){const t=Outline.svgRound(this.#Sa[10]),e=Outline.svgRound(this.#Sa[11]);this.#Al=`${this.#Al} L ${t} ${e}`;this.#vl=12;return this.#Al}const i=[];if(0===this.#vl){i.push(`M ${t} ${e}`);this.#vl=6}for(let t=this.#vl,e=this.#Sa.length;t<e;t+=6){const[e,n,s,r,a,o]=this.#Sa.slice(t,t+6).map(Outline.svgRound);i.push(`C${e} ${n} ${s} ${r} ${a} ${o}`)}this.#Al+=i.join(" ");this.#vl=this.#Sa.length;return this.#Al}getOutlines(t,e,i,n){const s=this.#yl.at(-1);s.line=new Float32Array(s.line);s.points=new Float32Array(s.points);this.#Ro.build(this.#yl,t,e,i,this.#Ps,this.#do,n);this.#so=null;this.#Sa=null;this.#yl=null;this.#Al=null;return this.#Ro}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#xo;#Sl=0;#eo;#yl;#xl;#El;#Tl;#Ps;#do;build(t,e,i,n,s,r,a){this.#xl=e;this.#El=i;this.#Tl=n;this.#Ps=s;this.#do=r;this.#eo=a??0;this.#yl=t;this.#_l()}get thickness(){return this.#do}setLastElement(t){this.#yl.push(t);return{path:{d:this.toSVGPath()}}}removeLastElement(){this.#yl.pop();return{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#yl){t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`);if(6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else for(let i=6,n=e.length;i<n;i+=6){const[n,s,r,a,o,l]=e.subarray(i,i+6).map(Outline.svgRound);t.push(`C${n} ${s} ${r} ${a} ${o} ${l}`)}else t.push("Z")}return t.join("")}serialize([t,e,i,n],s){const r=[],a=[],[o,l,h,d]=this.#Ml();let c,u,p,g,m,f,b,w,y;switch(this.#Ps){case 0:y=Outline._rescale;c=t;u=e+n;p=i;g=-n;m=t+o*i;f=e+(1-l-d)*n;b=t+(o+h)*i;w=e+(1-l)*n;break;case 90:y=Outline._rescaleAndSwap;c=t;u=e;p=i;g=n;m=t+l*i;f=e+o*n;b=t+(l+d)*i;w=e+(o+h)*n;break;case 180:y=Outline._rescale;c=t+i;u=e;p=-i;g=n;m=t+(1-o-h)*i;f=e+l*n;b=t+(1-o)*i;w=e+(l+d)*n;break;case 270:y=Outline._rescaleAndSwap;c=t+i;u=e+n;p=-i;g=-n;m=t+(1-l-d)*i;f=e+(1-o-h)*n;b=t+(1-l)*i;w=e+(1-o)*n}for(const{line:t,points:e}of this.#yl){r.push(y(t,c,u,p,g,s?new Array(t.length):null));a.push(y(e,c,u,p,g,s?new Array(e.length):null))}return{lines:r,points:a,rect:[m,f,b,w]}}static deserialize(t,e,i,n,s,{paths:{lines:r,points:a},rotation:o,thickness:l}){const h=[];let d,c,u,p,g;switch(o){case 0:g=Outline._rescale;d=-t/i;c=e/n+1;u=1/i;p=-1/n;break;case 90:g=Outline._rescaleAndSwap;d=-e/n;c=-t/i;u=1/n;p=1/i;break;case 180:g=Outline._rescale;d=t/i+1;c=-e/n;u=-1/i;p=1/n;break;case 270:g=Outline._rescaleAndSwap;d=e/n+1;c=t/i+1;u=-1/n;p=-1/i}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));r.push(i);let[n,s,a,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let r=4;r<e;r+=2){const e=t[r],l=t[r+1];i.set(Outline.createBezierPoints(n,s,a,o,e,l),3*(r-2));[n,s,a,o]=[a,o,e,l]}}}for(let t=0,e=r.length;t<e;t++)h.push({line:g(r[t].map(t=>t??NaN),d,c,u,p),points:g(a[t].map(t=>t??NaN),d,c,u,p)});const m=new this.prototype.constructor;m.build(h,i,n,1,o,l,s);return m}#Dl(t=this.#do){const e=this.#eo+t/2*this.#Tl;return this.#Ps%180==0?[e/this.#xl,e/this.#El]:[e/this.#El,e/this.#xl]}#Ml(){const[t,e,i,n]=this.#xo,[s,r]=this.#Dl(0);return[t+s,e+r,i-2*s,n-2*r]}#_l(){const t=this.#xo=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#yl){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6)Util.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],n=e[5];for(let s=6,r=e.length;s<r;s+=6){const[r,a,o,l,h,d]=e.subarray(s,s+6);Util.bezierBoundingBox(i,n,r,a,o,l,h,d,t);i=h;n=d}}const[e,i]=this.#Dl();t[0]=MathClamp(t[0]-e,0,1);t[1]=MathClamp(t[1]-i,0,1);t[2]=MathClamp(t[2]+e,0,1);t[3]=MathClamp(t[3]+i,0,1);t[2]-=t[0];t[3]-=t[1]}get box(){return this.#xo}updateProperty(t,e){return"stroke-width"===t?this.#Qo(e):null}#Qo(t){const[e,i]=this.#Dl();this.#do=t;const[n,s]=this.#Dl(),[r,a]=[n-e,s-i],o=this.#xo;o[0]-=r;o[1]-=a;o[2]+=2*r;o[3]+=2*a;return o}updateParentDimensions([t,e],i){const[n,s]=this.#Dl();this.#xl=t;this.#El=e;this.#Tl=i;const[r,a]=this.#Dl(),o=r-n,l=a-s,h=this.#xo;h[0]-=o;h[1]-=l;h[2]+=2*o;h[3]+=2*l;return h}updateRotation(t){this.#Sl=t;return{path:{transform:this.rotationTransform}}}get viewBox(){return this.#xo.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#xo;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#xo;let i=0,n=0,s=0,r=0,a=0,o=0;switch(this.#Sl){case 90:n=e/t;s=-t/e;a=t;break;case 180:i=-1;r=-1;a=t;o=e;break;case 270:n=-e/t;s=t/e;o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${r} ${Outline.svgRound(a)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,r]=this.#Dl(),[a,o,l,h]=this.#xo;if(Math.abs(l-s)<=Outline.PRECISION||Math.abs(h-r)<=Outline.PRECISION){const s=t+i/2-(a+l/2),r=e+n/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${r})`}}}const d=(i-2*s)/(l-2*s),c=(n-2*r)/(h-2*r),u=l/i,p=h/n;return{path:{"transform-origin":`${Outline.svgRound(a)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(s)} ${Outline.svgRound(r)}) scale(${d} ${c}) translate(${Outline.svgRound(-s)} ${Outline.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,r]=this.#Dl(),a=this.#xo,[o,l,h,d]=a;a[0]=t;a[1]=e;a[2]=i;a[3]=n;if(Math.abs(h-s)<=Outline.PRECISION||Math.abs(d-r)<=Outline.PRECISION){const s=t+i/2-(o+h/2),r=e+n/2-(l+d/2);for(const{line:t,points:e}of this.#yl){Outline._translate(t,s,r,t);Outline._translate(e,s,r,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const c=(i-2*s)/(h-2*s),u=(n-2*r)/(d-2*r),p=-c*(o+s)+t+s,g=-u*(l+r)+e+r;if(1!==c||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#yl){Outline._rescale(t,p,g,c,u,t);Outline._rescale(e,p,g,c,u,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,r=this.#xo,a=t-r[0],o=e-r[1];if(this.#xl===n&&this.#El===s)for(const{line:t,points:e}of this.#yl){Outline._translate(t,a,o,t);Outline._translate(e,a,o,e)}else{const t=this.#xl/n,e=this.#El/s;this.#xl=n;this.#El=s;for(const{line:i,points:n}of this.#yl){Outline._rescale(i,a,o,t,e,i);Outline._rescale(n,a,o,t,e,n)}r[2]*=t;r[3]*=e}r[0]=t;r[1]=e;return{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#xo;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{constructor(t){super();this._viewParameters=t;super.updateProperties({fill:"none",stroke:AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){if("stroke-width"===t){e??=this["stroke-width"];e*=this._viewParameters.realScale}super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this._viewParameters);t.updateAll(this);return t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=p.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"});this._willKeepAspectRatio=!0;this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!0}static get typesMap(){return shadow(this,"typesMap",new Map([[g.INK_THICKNESS,"stroke-width"],[g.INK_COLOR,"stroke"],[g.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new InkDrawOutliner(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,r){return InkDrawOutline.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){let n=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:g},parent:{page:{pageNumber:m}}}=t;n=t={annotationType:p.INK,color:Array.from(a),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:m-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:g}}const s=await super.deserialize(t,e,i);s._initialData=n;t.comment&&s.setCommentData(t);return s}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return g.INK_COLOR}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width");i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;if(t){super.onScaleChangingWhenDrawing();this._defaultDrawingOptions.updateSVGProperty("stroke-width");t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=InkEditor.getDefaultDrawingOptions({stroke:Util.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":s,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:AnnotationEditor._colorManager.convert(n),opacity:s,thickness:r,paths:{lines:e,points:i}});this.addComment(a);if(t){a.isCopy=!0;return a}if(this.annotationElementId&&!this.#Ja(a))return null;a.id=this.annotationElementId;return a}#Ja(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted){t.hide();return null}const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment});return null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();t.endsWith("Z")||(t+="Z");return t}}class SignatureExtractor{static#Pl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#kl(t,e,i,n){n-=e;return 0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#Il=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Fl(t,e,i,n,s,r,a){const o=this.#kl(i,n,s,r);for(let s=0;s<8;s++){const r=(-s+o-a+16)%8;if(0!==t[(i+this.#Il[2*r])*e+(n+this.#Il[2*r+1])])return r}return-1}static#Rl(t,e,i,n,s,r,a){const o=this.#kl(i,n,s,r);for(let s=0;s<8;s++){const r=(s+o+a+16)%8;if(0!==t[(i+this.#Il[2*r])*e+(n+this.#Il[2*r+1])])return r}return-1}static#Bl(t,e,i,n){const s=t.length,r=new Int32Array(s);for(let e=0;e<s;e++)r[e]=t[e]<=n?1:0;for(let t=1;t<i-1;t++)r[t*e]=r[t*e+e-1]=0;for(let t=0;t<e;t++)r[t]=r[e*i-1-t]=0;let a,o=1;const l=[];for(let t=1;t<i-1;t++){a=1;for(let i=1;i<e-1;i++){const n=t*e+i,s=r[n];if(0===s)continue;let h=t,d=i;if(1===s&&0===r[n-1]){o+=1;d-=1}else{if(!(s>=1&&0===r[n+1])){1!==s&&(a=Math.abs(s));continue}o+=1;d+=1;s>1&&(a=s)}const c=[i,t],u=d===i+1,p={isHole:u,points:c,id:o,parent:0};l.push(p);let g;for(const t of l)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#Fl(r,e,t,i,h,d,0);if(-1===m){r[n]=-o;1!==r[n]&&(a=Math.abs(r[n]));continue}let f=this.#Il[2*m],b=this.#Il[2*m+1];const w=t+f,y=i+b;h=w;d=y;let A=t,v=i;for(;;){const s=this.#Rl(r,e,A,v,h,d,1);f=this.#Il[2*s];b=this.#Il[2*s+1];const l=A+f,u=v+b;c.push(u,l);const p=A*e+v;0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o);if(l===t&&u===i&&A===w&&v===y){1!==r[n]&&(a=Math.abs(r[n]));break}h=A;d=v;A=l;v=u}}}return l}static#Ll(t,e,i,n){if(i-e<=4){for(let s=e;s<i-2;s+=2)n.push(t[s],t[s+1]);return}const s=t[e],r=t[e+1],a=t[i-4]-s,o=t[i-3]-r,l=Math.hypot(a,o),h=a/l,d=o/l,c=h*r-d*s,u=o/a,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),w=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*w),Math.atan(Math.abs(f-m)*w));let A=0,v=e;for(let n=e+2;n<i-2;n+=2){const e=Math.abs(c-h*t[n+1]+d*t[n]);if(e>A){v=n;A=e}}if(A>(l*y)**2){this.#Ll(t,e,v+2,n);this.#Ll(t,v,i,n)}else n.push(s,r)}static#Ol(t){const e=[],i=t.length;this.#Ll(t,0,i,e);e.push(t[i-2],t[i-1]);return e.length<=4?null:e}static#Nl(t,e,i,n,s,r){const a=new Float32Array(r**2),o=-2*n**2,l=r>>1;for(let t=0;t<r;t++){const e=(t-l)**2;for(let i=0;i<r;i++)a[t*r+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),d=-2*s**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/d);const c=t.length,u=new Uint8Array(c),p=new Uint32Array(256);for(let n=0;n<i;n++)for(let s=0;s<e;s++){const o=n*e+s,d=t[o];let c=0,g=0;for(let o=0;o<r;o++){const u=n+o-l;if(!(u<0||u>=i))for(let i=0;i<r;i++){const n=s+i-l;if(n<0||n>=e)continue;const p=t[u*e+n],m=a[o*r+i]*h[Math.abs(p-d)];c+=p*m;g+=m}}p[u[o]=Math.round(c/g)]++}return[u,p]}static#Ul(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#Hl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,r=i.length;e<r;e++){const r=i[e]=t[e<<2];n=Math.max(n,r);s=Math.min(s,r)}const r=255/(n-s);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-s)*r;return i}static#zl(t){let e,i=-1/0,n=-1/0;const s=t.findIndex(t=>0!==t);let r=s,a=s;for(e=s;e<256;e++){const s=t[e];if(s>i){if(e-r>n){n=e-r;a=e-1}i=s;r=e}}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#Gl(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#Pl;let r=i,a=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const d=Math.floor(h);h=h===d?d-1:d;for(let i=0;i<h;i++){r=Math.ceil(o/2);a=Math.ceil(l/2);const i=new OffscreenCanvas(r,a);i.getContext("2d").drawImage(t,0,0,o,l,0,0,r,a);o=r;l=a;t!==e&&t.close();t=i.transferToImageBitmap()}const c=Math.min(s/r,s/a);r=Math.round(r*c);a=Math.round(a*c)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white";o.fillRect(0,0,r,a);o.filter="grayscale(1)";o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const l=o.getImageData(0,0,r,a).data;return[this.#Hl(l),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:n},s,r,a,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const d=h.font=`${i} ${n} 200px ${e}`,{actualBoundingBoxLeft:c,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),w=1.5,y=Math.ceil(Math.max(Math.abs(c)+Math.abs(u)||0,b)*w),A=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*w);l=new OffscreenCanvas(y,A);h=l.getContext("2d",{alpha:!0,willReadFrequently:!0});h.font=d;h.filter="grayscale(1)";h.fillStyle="white";h.fillRect(0,0,y,A);h.fillStyle="black";h.fillText(t,.5*y/2,1.5*A/2);const v=this.#Hl(h.getImageData(0,0,y,A).data),x=this.#Ul(v),E=this.#zl(x),C=this.#Bl(v,y,A,E);return this.processDrawnLines({lines:{curves:C,width:y,height:A},pageWidth:s,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,n,s){const[r,a,o]=this.#Gl(t),[l,h]=this.#Nl(r,a,o,Math.hypot(a,o)*this.#Pl.sigmaSFactor,this.#Pl.sigmaR,this.#Pl.kernelSize),d=this.#zl(h),c=this.#Bl(l,a,o,d);return this.processDrawnLines({lines:{curves:c,width:a,height:o},pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:r,areContours:a}){n%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,d=t.thickness??0,c=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=r?this.#Ol(t):t;if(!e)continue;m.push(e);const i=e.length,n=new Float32Array(i),s=new Float32Array(3*(2===i?2:i-2));c.push({line:s,points:n});if(2===i){n[0]=e[0]*p;n[1]=e[1]*g;s.set([NaN,NaN,NaN,NaN,n[0],n[1]],0);continue}let[a,o,l,h]=e;a*=p;o*=g;l*=p;h*=g;n.set([a,o,l,h],0);s.set([NaN,NaN,NaN,NaN,a,o],0);for(let t=4;t<i;t+=2){const i=n[t]=e[t]*p,r=n[t+1]=e[t+1]*g;s.set(Outline.createBezierPoints(a,o,l,h,i,r),3*(t-2));[a,o,l,h]=[l,h,i,r]}}if(0===c.length)return null;const f=a?new ContourDrawOutline:new InkDrawOutline;f.build(c,e,i,1,n,a?0:d,s);return{outline:f,newCurves:m,areContours:a,thickness:d,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:n,height:s}){let r,a=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];a=Math.min(a,i);o=Math.max(o,i)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,d=8+3*h,c=new Uint32Array(d);let u=0;c[u++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*r.BYTES_PER_ELEMENT;c[u++]=0;c[u++]=n;c[u++]=s;c[u++]=e?0:1;c[u++]=Math.max(0,Math.floor(i??0));c[u++]=h;c[u++]=r.BYTES_PER_ELEMENT;for(const e of t){c[u++]=e.length-2;c[u++]=e[0];c[u++]=e[1]}const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready;g.write(c);const m=r.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i<n;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const f=await new Response(p.readable).arrayBuffer();return new Uint8Array(f).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:i,writable:n}=new DecompressionStream("deflate-raw"),s=n.getWriter();await s.ready;s.write(e).then(async()=>{await s.ready;await s.close()}).catch(()=>{});let r=null,a=0;for await(const t of i){r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]);r.set(t,a);a+=t.length}const o=new Uint32Array(r.buffer,0,r.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],d=o[3],c=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(r.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,f)}a=0;for(let t=0;t<p;t++){const e=o[3*t+8],i=new Float32Array(e+2);m.push(i);for(let e=0;e<2;e++)i[e]=o[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+b[a++]}return{areContours:c,thickness:u,outlines:m,width:h,height:d}}catch(t){warn(`decompressSignature: ${t}`);return null}}}class SignatureOptions extends DrawingOptions{constructor(){super();super.updateProperties({fill:AnnotationEditor._defaultLineColor,"stroke-width":0})}clone(){const t=new SignatureOptions;t.updateAll(this);return t}}class DrawnSignatureOptions extends InkDrawingOptions{constructor(t){super(t);super.updateProperties({stroke:AnnotationEditor._defaultLineColor,"stroke-width":1})}clone(){const t=new DrawnSignatureOptions(this._viewParameters);t.updateAll(this);return t}}class SignatureEditor extends DrawingEditor{#Wl=!1;#Vl=null;#jl=null;#$l=null;static _type="signature";static _editorType=p.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});this._willKeepAspectRatio=!0;this.#jl=t.signatureData||null;this.#Vl=null;this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new SignatureOptions;this._defaultDrawnSignatureOptions=new DrawnSignatureOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!1}static get typesMap(){return shadow(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#Vl}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i){this._isCopy=!1;t=this.x;e=this.y}super.render();if(null===this._drawId)if(this.#jl){const{lines:t,mustSmooth:e,areContours:i,description:n,uuid:s,heightInPage:r}=this.#jl,{rawDims:{pageWidth:a,pageHeight:o},rotation:l}=this.parent.viewport,h=SignatureExtractor.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:l,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,r,n,s)}else{this.div.setAttribute("data-l10n-args",JSON.stringify({description:""}));this.div.hidden=!0;this._uiManager.getSignature(this)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#Vl||""}));if(i){this._isCopy=!0;this._moveAfterPaste(t,e)}return this.div}setUuid(t){this.#$l=t;this.addEditToolbar()}getUuid(){return this.#$l}get description(){return this.#Vl}set description(t){this.#Vl=t;if(this.div){this.div.setAttribute("data-l10n-args",JSON.stringify({description:t}));super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)})}}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#jl,r=Math.max(n,s);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:r}=this,{outline:a}=this.#jl=t;this.#Wl=a instanceof ContourDrawOutline;this.description=i;let o;if(this.#Wl)o=SignatureEditor.getDefaultDrawingOptions();else{o=SignatureEditor._defaultDrawnSignatureOptions.clone();o.updateProperties({"stroke-width":a.thickness})}this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h;this.width*=h/this.height;if(this.width>=1){h*=.9/this.width;this.width=.9}this.height=h;this.setDims();this.x=s;this.y=r;this.center();this._onResized();this.onScaleChanging();this.rotate();this._uiManager.addToAnnotationStorage(this);this.setUuid(n);this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}});this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.process(t,e,i,n,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,n,s,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){if(t)this._drawingOptions=SignatureEditor.getDefaultDrawingOptions();else{this._drawingOptions=SignatureEditor._defaultDrawnSignatureOptions.clone();this._drawingOptions.updateProperties({"stroke-width":e})}}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Wl,color:[0,0,0],thickness:this.#Wl?0:n});this.addComment(s);if(t){s.paths={lines:e,points:i};s.uuid=this.#$l;s.isCopy=!0}else s.lines=e;this.#Vl&&(s.accessibilityData={type:"Figure",alt:this.#Vl});return s}static deserializeDraw(t,e,i,n,s,r){return r.areContours?ContourDrawOutline.deserialize(t,e,i,n,s,r):InkDrawOutline.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);n.#Wl=t.areContours;n.description=t.accessibilityData?.alt||"";n.#$l=t.uuid;return n}}class StampEditor extends AnnotationEditor{#Xl=null;#ql=null;#Kl=null;#Yl=null;#Ql=null;#Jl="";#Zl=null;#th=!1;#eh=null;#ih=!1;#nh=!1;static _type="stamp";static _editorType=p.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Yl=t.bitmapUrl;this.#Ql=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return $.includes(t)}static paste(t,e){e.pasteEditor({mode:p.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#sh(t,e=!1){if(t){this.#Xl=t.bitmap;if(!e){this.#ql=t.id;this.#ih=t.isSvg}t.file&&(this.#Jl=t.file.name);this.#rh()}else this.remove()}#ah(){this.#Kl=null;this._uiManager.enableWaiting(!1);if(this.#Zl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Xl)this.addEditToolbar().then(()=>{this._editToolbar.hide();this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Xl){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:s,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:n,width:s,height:r,channels:n.length/(s*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#oh(){if(this.#ql){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#ql).then(t=>this.#sh(t,!0)).finally(()=>this.#ah());return}if(this.#Yl){const t=this.#Yl;this.#Yl=null;this._uiManager.enableWaiting(!0);this.#Kl=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#sh(t)).finally(()=>this.#ah());return}if(this.#Ql){const t=this.#Ql;this.#Ql=null;this._uiManager.enableWaiting(!0);this.#Kl=this._uiManager.imageManager.getFromFile(t).then(t=>this.#sh(t)).finally(()=>this.#ah());return}const t=document.createElement("input");t.type="file";t.accept=$.join(",");const e=this._uiManager._signal;this.#Kl=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#sh(e)}else this.remove();i()},{signal:e});t.addEventListener("cancel",()=>{this.remove();i()},{signal:e})}).finally(()=>this.#ah());t.click()}remove(){if(this.#ql){this.#Xl=null;this._uiManager.imageManager.deleteId(this.#ql);this.#Zl?.remove();this.#Zl=null;if(this.#eh){clearTimeout(this.#eh);this.#eh=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#ql&&null===this.#Zl&&this.#oh();this.isAttachedToDOM||this.parent.add(this)}}else this.#ql&&this.#oh()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#Kl||this.#Xl||this.#Yl||this.#Ql||this.#ql||this.#th)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.createAltText();this.#th||(this.#Xl?this.#rh():this.#oh());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(i&&this._uiManager.imageManager.isValidId(i)){this.#ql=i;n&&(this.#Xl=n);this.#th=!1;this.#rh()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#eh&&clearTimeout(this.#eh);this.#eh=setTimeout(()=>{this.#eh=null;this.#lh()},200)}#rh(){const{div:t}=this;let{width:e,height:i}=this.#Xl;const[n,s]=this.pageDimensions,r=.75;if(this.width){e=this.width*n;i=this.height*s}else if(e>r*n||i>r*s){const t=Math.min(r*n/e,r*s/i);e*=t;i*=t}this._uiManager.enableWaiting(!1);const a=this.#Zl=document.createElement("canvas");a.setAttribute("role","img");this.addContainer(a);this.width=e/n;this.height=i/s;this.setDims();this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#lh();if(!this.#nh){this.parent.addUndoableEditor(this);this.#nh=!0}this._reportTelemetry({action:"inserted_image"});this.#Jl&&this.div.setAttribute("aria-description",this.#Jl);this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#Xl,r=new OutputScale;let a=this.#Xl,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t);l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#ih||(a=this.#hh(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(ColorScheme.isDarkMode){c="#8f8f9d";u="#42414d"}const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let d=null;if(i){let e,i;if(r.symmetric&&a.width<t&&a.height<t){e=a.width;i=a.height}else{a=this.#Xl;if(n>t||s>t){const r=Math.min(t/n,t/s);e=Math.floor(n*r);i=Math.floor(s*r);this.#ih||(a=this.#hh(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#hh(t,e){const{width:i,height:n}=this.#Xl;let s=i,r=n,a=this.#Xl;for(;s>2*t||r>2*e;){const i=s,n=r;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2));r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(s,r);o.getContext("2d").drawImage(a,0,0,i,n,0,0,s,r);a=o.transferToImageBitmap()}return a}#lh(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new OutputScale,r=Math.ceil(i*t*s.sx),a=Math.ceil(n*e*s.sy),o=this.#Zl;if(!o||o.width===r&&o.height===a)return;o.width=r;o.height=a;const l=this.#ih?this.#Xl:this.#hh(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#dh(t){if(t){if(this.#ih){const t=this._uiManager.imageManager.getSvgUrl(this.#ql);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Xl);t.getContext("2d").drawImage(this.#Xl,0,0);return t.toDataURL()}if(this.#ih){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);s.getContext("2d").drawImage(this.#Xl,0,0,this.#Xl.width,this.#Xl.height,0,0,i,n);return s.transferToImageBitmap()}return structuredClone(this.#Xl)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof StampAnnotationElement){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:g},container:m,parent:{page:{pageNumber:f}},canvas:b}=t;let w,y;if(b){delete t.canvas;({id:w,bitmap:y}=i.imageManager.getFromCanvas(m.id,b));b.remove()}else{s=!0;t._hasNoCanvas=!0}const A=(await e._structTree.getAriaAttributes(`${V}${o}`))?.get("aria-label")||"";n=t={annotationType:p.STAMP,bitmapId:w,bitmap:y,pageIndex:f-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:l,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:g}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;if(s){i.addMissingCanvas(t.id,r);r.#th=!0}else if(h&&i.imageManager.isValidId(h)){r.#ql=h;o&&(r.#Xl=o)}else r.#Yl=l;r.#ih=d;const[u,g]=r.pageDimensions;r.width=(a[2]-a[0])/u;r.height=(a[3]-a[1])/g;c&&(r.altTextData=c);r._initialData=n;t.comment&&r.setCommentData(t);r.#nh=!!n;return r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#ql,isSvg:this.#ih});this.addComment(i);if(t){i.bitmapUrl=this.#dh(!0);i.accessibilityData=this.serializeAltText(!0);i.isCopy=!0;return i}const{decorative:n,altText:s}=this.serializeAltText(!1);!n&&s&&(i.accessibilityData={type:"Figure",alt:s});if(this.annotationElementId){const t=this.#Ja(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1;i.id=this.annotationElementId;delete i.bitmapId;return i}if(null===e)return i;e.stamps||=new Map;const r=this.#ih?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#ql)){if(this.#ih){const t=e.stamps.get(this.#ql);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#dh(!1)}}}else{e.stamps.set(this.#ql,{area:r,serialized:i});i.bitmap=this.#dh(!1)}return i}#Ja(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}}class AnnotationEditorLayer{#Ra;#ch=!1;#uh=null;#ph=null;#gh=null;#mh=new Map;#fh=!1;#bh=!1;#wh=!1;#yh=null;#Ah=null;#vh=null;#xh=null;#Eh=null;#Ch=-1;#C;static _initialized=!1;static#it=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#it.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#C=t;this.pageIndex=e;this.div=i;this.#Ra=s;this.#uh=r;this.viewport=l;this.#vh=o;this.drawLayer=a;this._structTree=n;this.#C.addLayer(this)}updatePageIndex(t){this.pageIndex=t}get isEmpty(){return 0===this.#mh.size}get isInvisible(){return this.isEmpty&&this.#C.getMode()===p.NONE}updateToolbar(t){this.#C.updateToolbar(t)}updateMode(t=this.#C.getMode()){this.#Sh();switch(t){case p.NONE:this.div.classList.toggle("nonEditing",!0);this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case p.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case p.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;e.toggle("nonEditing",!1);if(t===p.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#it.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#vh?.div}setEditingState(t){this.#C.setEditingState(t)}addCommands(t){this.#C.addCommands(t)}cleanUndoStack(t){this.#C.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#uh?.togglePointerEvents(t)}get#Th(){return 0!==this.#mh.size?this.#mh.values():this.#C.getEditors(this.pageIndex)}async enable(){this.#wh=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);this.div.classList.toggle("nonEditing",!1);this.#Eh?.abort();this.#Eh=null;const t=new Set;for(const e of this.#Th){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#C.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}const e=this.#uh;if(e)for(const i of e.getEditableAnnotations()){i.hide();if(this.#C.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#wh=!1;this.#C._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){this.#bh=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);this.div.classList.toggle("nonEditing",!0);if(this.#vh&&!this.#Eh){this.#Eh=new AbortController;const t=this.#C.combinedSignal(this.#Eh);this.#vh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#Ch>500){this.#Ch=n;return}this.#Ch=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);s.toggle("getElements",!1);if(!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${u}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#mh.get(a);if(null===l?.annotationElementId){t.stopPropagation();t.preventDefault();l.dblclick(t)}},{signal:t,capture:!0})}const t=this.#uh,e=[];if(t){const i=new Map,n=new Map;for(const t of this.#Th){t.disableEditing();if(t.annotationElementId)if(null===t.serialize()){n.set(t.annotationElementId,t);this.getEditableAnnotation(t.annotationElementId)?.show();t.remove()}else i.set(t.annotationElementId,t);else e.push(t)}const s=t.getEditableAnnotations();for(const t of s){const{id:e}=t.data;if(this.#C.isDeletedAnnotationElement(e)){t.updateEdited({deleted:!0});continue}let s=n.get(e);if(s){s.resetAnnotationElement(t);s.show(!1);t.show()}else{s=i.get(e);if(s){this.#C.addChangedExistingAnnotation(s);s.renderAnnotationElement(t)&&s.show(!1)}t.show()}}}this.#Sh();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#it.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);t?.updateFakeAnnotations(e);this.#bh=!1}getEditableAnnotation(t){return this.#uh?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#C.getActive()!==t&&this.#C.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#vh?.div&&!this.#xh){this.#xh=new AbortController;const t=this.#C.combinedSignal(this.#xh);this.#vh.div.addEventListener("pointerdown",this.#_h.bind(this),{signal:t});this.#vh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#vh?.div&&this.#xh){this.#xh.abort();this.#xh=null;this.#vh.div.classList.remove("highlighting")}}#_h(t){this.#C.unselectAll();const{target:e}=t;if(e===this.#vh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#vh.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#C.showAllEditors("highlight",!0,!0);this.#vh.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#C.direction,{target:this.#vh.div,x:t.x,y:t.y});this.#vh.div.addEventListener("pointerup",()=>{this.#vh.div.classList.remove("free");this.toggleDrawing(!0)},{once:!0,signal:this.#C._signal});t.preventDefault()}}enableClick(){if(this.#ph)return;this.#ph=new AbortController;const t=this.#C.combinedSignal(this.#ph);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ph?.abort();this.#ph=null}attach(t){this.#mh.set(t.id,t);const{annotationElementId:e}=t;e&&this.#C.isDeletedAnnotationElement(e)&&this.#C.removeDeletedAnnotationElement(t)}detach(t){this.#mh.delete(t.id);this.#Ra?.removePointerInTextLayer(t.contentDiv);!this.#bh&&t.annotationElementId&&this.#C.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#C.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#C.addDeletedAnnotationElement(t);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#C.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#wh);this.#C.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#gh){t._focusEventsAllowed=!1;this.#gh=setTimeout(()=>{this.#gh=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#C._signal});e.focus()}},0)}t._structTreeParentId=this.#Ra?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#mh.values())if(e.uid===t)return e;return null}getNextId(){return this.#C.getId()}get#Mh(){return AnnotationEditorLayer.#it.get(this.#C.getMode())}combinedSignal(t){return this.#C.combinedSignal(t)}#Dh(t){const e=this.#Mh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Mh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t);await this.#C.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#Ph(),s=this.getNextId(),r=this.#Dh({parent:this,id:s,x:i,y:n,uiManager:this.#C,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(AnnotationEditorLayer.#it.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#C))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#Dh({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#C,isCentered:e,...i});s&&this.add(s);return s}get boundingClientRect(){return this.div.getBoundingClientRect()}#Ph(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),r=Math.max(0,e),a=(s+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Ph(),!0,t)}setSelected(t){this.#C.setSelected(t)}toggleSelected(t){this.#C.toggleSelected(t)}unselect(t){this.#C.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#fh)return;this.#fh=!1;if(this.#Mh?.isDrawer&&this.#Mh.supportMultipleDrawings)return;if(!this.#ch){this.#ch=!0;return}const i=this.#C.getMode();i!==p.STAMP&&i!==p.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#C.unselectAll()}pointerdown(t){this.#C.getMode()===p.HIGHLIGHT&&this.enableTextSelection();if(this.#fh){this.#fh=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#fh=!0;if(this.#Mh?.isDrawer){this.startDrawingSession(t);return}const i=this.#C.getActive();this.#ch=!i||i.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:!0});if(this.#yh){this.#Mh.startDrawing(this,this.#C,!1,t);return}this.#C.setCurrentDrawingSession(this);this.#yh=new AbortController;const e=this.#C.combinedSignal(this.#yh);this.div.addEventListener("blur",({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#Ah=null;this.commitOrRemove()}},{signal:e});this.#Mh.startDrawing(this,this.#C,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#Ah=t);return}this.#Ah&&setTimeout(()=>{this.#Ah?.focus();this.#Ah=null},0)}endDrawingSession(t=!1){if(!this.#yh)return null;this.#C.setCurrentDrawingSession(null);this.#yh.abort();this.#yh=null;this.#Ah=null;return this.#Mh.endDrawing(t)}findNewParent(t,e,i){const n=this.#C.findParent(e,i);if(null===n||n===this)return!1;n.changeParent(t);return!0}commitOrRemove(){if(this.#yh){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#yh&&this.#Mh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#C.getActive()?.parent===this){this.#C.commitOrRemove();this.#C.setActiveEditor(null)}if(this.#gh){clearTimeout(this.#gh);this.#gh=null}for(const t of this.#mh.values()){this.#Ra?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#mh.clear();this.#C.removeLayer(this)}#Sh(){for(const t of this.#mh.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#C.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#C.commitOrRemove();this.#Sh();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#mh.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#C.viewParameters.realScale}}class DrawLayer{#sa=null;#kh=new Map;#Ih=new Map;static#I=0;setParent(t){if(this.#sa){if(this.#sa!==t){if(this.#kh.size>0)for(const e of this.#kh.values()){e.remove();t.append(e)}this.#sa=t}}else this.#sa=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#Fh(t,[e,i,n,s]){const{style:r}=t;r.top=100*i+"%";r.left=100*e+"%";r.width=100*n+"%";r.height=100*s+"%"}#Rh(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#sa.append(t);t.setAttribute("aria-hidden",!0);return t}#Bh(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n);i.setAttribute("clipPathUnits","objectBoundingBox");const s=DrawLayer._svgFactory.createElement("use");i.append(s);s.setAttribute("href",`#${e}`);s.classList.add("clip");return n}#Lh(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=DrawLayer.#I++,s=this.#Rh(),r=DrawLayer._svgFactory.createElement("defs");s.append(r);const a=DrawLayer._svgFactory.createElement("path");r.append(a);const o=`path_${n}`;a.setAttribute("id",o);a.setAttribute("vector-effect","non-scaling-stroke");e&&this.#Ih.set(n,a);const l=i?this.#Bh(r,o):null,h=DrawLayer._svgFactory.createElement("use");s.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(s,t);this.#kh.set(n,s);return{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#I++,n=this.#Rh(),s=DrawLayer._svgFactory.createElement("defs");n.append(s);const r=DrawLayer._svgFactory.createElement("path");s.append(r);const a=`path_${i}`;r.setAttribute("id",a);r.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");s.append(t);o=`mask_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const n=DrawLayer._svgFactory.createElement("use");t.append(n);n.setAttribute("href",`#${a}`);n.setAttribute("stroke","none");n.setAttribute("fill","black");n.setAttribute("fill-rule","nonzero");n.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");n.append(l);l.setAttribute("href",`#${a}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();n.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(n,t);this.#kh.set(i,n);return i}finalizeDraw(t,e){this.#Ih.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:r}=e,a="number"==typeof t?this.#kh.get(t):t;if(a){i&&this.#Lh(a,i);n&&DrawLayer.#Fh(a,n);if(s){const{classList:t}=a;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(r){const t=a.firstElementChild.firstElementChild;this.#Lh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#kh.get(t);if(i){e.#sa.append(i);this.#kh.delete(t);e.#kh.set(t,i)}}remove(t){this.#Ih.delete(t);if(null!==this.#sa){this.#kh.get(t).remove();this.#kh.delete(t)}}destroy(){this.#sa=null;for(const t of this.#kh.values())t.remove();this.#kh.clear();this.#Ih.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner};globalThis.pdfjsLib={AbortException,AnnotationEditorLayer,AnnotationEditorParamsType:g,AnnotationEditorType:p,AnnotationEditorUIManager,AnnotationLayer,AnnotationMode:c,AnnotationType:S,applyOpacity,build:Ot,ColorPicker,createValidAbsoluteUrl,CSSConstants,DOMSVGFactory,DrawLayer,FeatureTest:util_FeatureTest,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,GlobalWorkerOptions,ImageKind:C,InvalidPDFException,isDataScheme,isPdfFile,isValidExplicitDest:J,MathClamp,noContextMenu,normalizeUnicode,OPS:I,OutputScale,PagesMapper,PasswordResponses:N,PDFDataRangeTransport,PDFDateString,PDFWorker,PermissionFlag:m,PixelsPerInch,RenderingCancelledException,renderRichText,ResponseException,setLayerDimensions,shadow,SignatureExtractor,stopEvent,SupportedImageMimeTypes:$,TextLayer,TouchManager,updateUrlHash,Util,VerbosityLevel:k,version:Lt,XfaLayer};export{AbortException,AnnotationEditorLayer,g as AnnotationEditorParamsType,p as AnnotationEditorType,AnnotationEditorUIManager,AnnotationLayer,c as AnnotationMode,S as AnnotationType,CSSConstants,ColorPicker,DOMSVGFactory,DrawLayer,util_FeatureTest as FeatureTest,GlobalWorkerOptions,C as ImageKind,InvalidPDFException,MathClamp,I as OPS,OutputScale,PDFDataRangeTransport,PDFDateString,PDFWorker,PagesMapper,N as PasswordResponses,m as PermissionFlag,PixelsPerInch,RenderingCancelledException,ResponseException,SignatureExtractor,$ as SupportedImageMimeTypes,TextLayer,TouchManager,Util,k as VerbosityLevel,XfaLayer,applyOpacity,Ot as build,createValidAbsoluteUrl,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,isDataScheme,isPdfFile,J as isValidExplicitDest,noContextMenu,normalizeUnicode,renderRichText,setLayerDimensions,shadow,stopEvent,updateUrlHash,Lt as version};
\ No newline at end of file
added scripts/encrypt-migrate.ts +60 −0
@@ -0,0 +1,60 @@
1 +import { prisma } from "../lib/prisma";
2 +import { encryptBuffer } from "../lib/filecrypto";
3 +import { readFile, writeFile } from "fs/promises";
4 +import { existsSync } from "fs";
5 +import path from "path";
6 +
7 +const UPLOAD_DIR = process.env.UPLOAD_DIR || "./uploads";
8 +const FILES_DIR = path.join(UPLOAD_DIR, "files");
9 +const VERSIONS_DIR = path.join(UPLOAD_DIR, "versions");
10 +
11 +// Idempotent : ne chiffre que les fichiers isEncrypted=false (+ leurs versions au même moment).
12 +// Usage: tsx scripts/encrypt-migrate.ts [fileId] (fileId optionnel = ne traiter qu'un fichier)
13 +async function main() {
14 + const onlyId = process.argv[2];
15 + const where: { isEncrypted: boolean; id?: string } = { isEncrypted: false };
16 + if (onlyId) where.id = onlyId;
17 +
18 + const files = await prisma.file.findMany({
19 + where,
20 + select: { id: true, storagePath: true, name: true },
21 + });
22 + console.log(`À chiffrer : ${files.length} fichier(s)${onlyId ? " (ciblé)" : ""}`);
23 +
24 + let ok = 0, miss = 0, err = 0;
25 + for (const f of files) {
26 + const fp = path.join(FILES_DIR, f.storagePath);
27 + if (!existsSync(fp)) { miss++; console.warn("MANQUANT", f.id, f.name); continue; }
28 + try {
29 + const plain = await readFile(fp);
30 + await writeFile(fp, encryptBuffer(plain));
31 +
32 + // Chiffre aussi les versions de ce fichier (une seule fois, à la transition)
33 + const versions = await prisma.fileVersion.findMany({
34 + where: { fileId: f.id },
35 + select: { storagePath: true },
36 + });
37 + for (const v of versions) {
38 + const vp = path.join(VERSIONS_DIR, v.storagePath);
39 + if (existsSync(vp)) {
40 + const vpl = await readFile(vp);
41 + await writeFile(vp, encryptBuffer(vpl));
42 + }
43 + }
44 +
45 + await prisma.file.update({
46 + where: { id: f.id },
47 + data: { isEncrypted: true, encryptionIV: "v2" },
48 + });
49 + ok++;
50 + if (ok % 100 === 0) console.log(` ... ${ok} chiffrés`);
51 + } catch (e) {
52 + err++;
53 + console.error("ERREUR", f.id, f.name, (e as Error).message);
54 + }
55 + }
56 + console.log(`Terminé. ok=${ok} manquants=${miss} erreurs=${err}`);
57 + await prisma.$disconnect();
58 +}
59 +
60 +main();
added server.ts +38 −0
@@ -0,0 +1,38 @@
1 +import { createServer } from "http";
2 +import next from "next";
3 +import { handleWebDAV } from "./lib/webdav";
4 +import { createDailySnapshotIfNeeded } from "./lib/snapshot";
5 +
6 +const dev = process.env.NODE_ENV !== "production";
7 +const port = parseInt(process.env.PORT || "5001", 10);
8 +
9 +const app = next({ dev });
10 +const handle = app.getRequestHandler();
11 +
12 +app.prepare().then(() => {
13 + createServer(async (req, res) => {
14 + const parsedUrl = new URL(req.url!, `http://${req.headers.host || "localhost"}`);
15 +
16 + if (parsedUrl.pathname?.startsWith("/dav")) {
17 + await handleWebDAV(req, res);
18 + } else {
19 + await handle(req, res);
20 + }
21 + }).listen(port, () => {
22 + console.log(`> SPB Cloud ready on http://localhost:${port}`);
23 + console.log(`> WebDAV endpoint: http://localhost:${port}/dav`);
24 + console.log(`> WebDAV public: https://cloud.spboucher.ai/dav`);
25 +
26 + // Daily snapshot: attempt immediately on startup, then check every hour
27 + const runSnapshot = () => {
28 + createDailySnapshotIfNeeded()
29 + .then((created) => { if (created) console.log("> [Snapshot] Snapshot quotidien créé"); })
30 + .catch((err) => console.error("> [Snapshot] Erreur:", err));
31 + };
32 + runSnapshot();
33 + setInterval(runSnapshot, 60 * 60 * 1000); // re-check every hour
34 + });
35 +}).catch((err) => {
36 + console.error("Failed to start server:", err);
37 + process.exit(1);
38 +});
added spb.sh +205 −0
@@ -0,0 +1,205 @@
1 +#!/usr/bin/env bash
2 +# spb — SPB Private Cloud CLI
3 +# Usage: spb <command> [options]
4 +#
5 +# Install: copy this file to ~/bin/spb and run: chmod +x ~/bin/spb
6 +# Config: spb config (set server URL and API key)
7 +
8 +set -e
9 +
10 +CONFIG_DIR="$HOME/.spb"
11 +CONFIG_FILE="$CONFIG_DIR/config"
12 +DEFAULT_URL="https://cloud.spboucher.ai"
13 +
14 +# ─── Load config ───────────────────────────────────────────────────────────────
15 +load_config() {
16 + if [ -f "$CONFIG_FILE" ]; then
17 + source "$CONFIG_FILE"
18 + fi
19 +}
20 +
21 +save_config() {
22 + mkdir -p "$CONFIG_DIR"
23 + chmod 700 "$CONFIG_DIR"
24 + cat > "$CONFIG_FILE" <<EOF
25 +SPB_URL="$SPB_URL"
26 +SPB_KEY="$SPB_KEY"
27 +EOF
28 + chmod 600 "$CONFIG_FILE"
29 +}
30 +
31 +require_config() {
32 + load_config
33 + if [ -z "$SPB_URL" ] || [ -z "$SPB_KEY" ]; then
34 + echo "❌ Not configured. Run: spb config"
35 + exit 1
36 + fi
37 +}
38 +
39 +# ─── Commands ─────────────────────────────────────────────────────────────────
40 +
41 +cmd_config() {
42 + load_config
43 + [ -z "$SPB_URL" ] && SPB_URL="$DEFAULT_URL"
44 + echo ""
45 + read -p " Server URL [${SPB_URL}]: " input_url
46 + [ -n "$input_url" ] && SPB_URL="$input_url"
47 + read -p " API Key [${SPB_KEY:0:12}...]: " input_key
48 + [ -n "$input_key" ] && SPB_KEY="$input_key"
49 + save_config
50 + echo " ✅ Config saved in $CONFIG_FILE"
51 + echo ""
52 +}
53 +
54 +cmd_upload() {
55 + require_config
56 + local file="$1"
57 + local folder_id="$2"
58 +
59 + if [ -z "$file" ]; then
60 + echo "Usage: spb upload <file> [folder_id]"
61 + exit 1
62 + fi
63 +
64 + if [ ! -f "$file" ]; then
65 + echo "❌ File not found: $file"
66 + exit 1
67 + fi
68 +
69 + local filename
70 + filename=$(basename "$file")
71 + echo " ⬆️ Uploading: $filename"
72 +
73 + local args=(-s -X POST -H "Authorization: Bearer $SPB_KEY" -F "file=@$file")
74 + [ -n "$folder_id" ] && args+=(-F "folderId=$folder_id")
75 +
76 + local response
77 + response=$(curl "${args[@]}" "$SPB_URL/api/v1/files")
78 +
79 + local name
80 + name=$(echo "$response" | grep -o '"name":"[^"]*"' | head -1 | cut -d'"' -f4)
81 +
82 + if [ -n "$name" ]; then
83 + echo " ✅ Uploaded: $name"
84 + else
85 + echo " ❌ Upload failed:"
86 + echo " $response"
87 + exit 1
88 + fi
89 +}
90 +
91 +cmd_upload_dir() {
92 + require_config
93 + local dir="$1"
94 + local folder_id="$2"
95 +
96 + if [ -z "$dir" ] || [ ! -d "$dir" ]; then
97 + echo "Usage: spb upload-dir <directory> [folder_id]"
98 + exit 1
99 + fi
100 +
101 + # Auto-create a folder with the directory name if no folder_id provided
102 + if [ -z "$folder_id" ]; then
103 + local dir_name
104 + dir_name=$(basename "$dir")
105 + echo " 📁 Creating folder: $dir_name"
106 + local response
107 + response=$(curl -s -X POST \
108 + -H "Authorization: Bearer $SPB_KEY" \
109 + -H "Content-Type: application/json" \
110 + -d "{\"name\":\"$dir_name\"}" \
111 + "$SPB_URL/api/v1/folders")
112 + folder_id=$(echo "$response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
113 + if [ -z "$folder_id" ]; then
114 + echo " ❌ Failed to create folder: $response"
115 + exit 1
116 + fi
117 + echo " ✅ Folder created (id: $folder_id)"
118 + fi
119 +
120 + local count=0
121 + while IFS= read -r -d '' file; do
122 + cmd_upload "$file" "$folder_id"
123 + count=$((count + 1))
124 + done < <(find "$dir" -maxdepth 1 -type f -print0)
125 +
126 + echo ""
127 + echo " ✅ Done: $count file(s) uploaded into folder"
128 +}
129 +
130 +cmd_ls() {
131 + require_config
132 + local folder_id="${1:-}"
133 + local url="$SPB_URL/api/v1/files"
134 + [ -n "$folder_id" ] && url="$url?folderId=$folder_id"
135 +
136 + local response
137 + response=$(curl -s -H "Authorization: Bearer $SPB_KEY" "$url")
138 +
139 + echo ""
140 + echo " 📁 Files:"
141 + echo "$response" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 | while read -r name; do
142 + echo " • $name"
143 + done
144 + echo ""
145 +}
146 +
147 +cmd_folders() {
148 + require_config
149 + local response
150 + response=$(curl -s -H "Authorization: Bearer $SPB_KEY" "$SPB_URL/api/v1/folders")
151 +
152 + echo ""
153 + echo " 📂 Folders:"
154 + # Parse id and name pairs
155 + echo "$response" | python3 -c "
156 +import sys, json
157 +data = json.load(sys.stdin)
158 +for f in data.get('folders', []):
159 + parent = f' (parent: {f[\"parentId\"]})' if f.get('parentId') else ''
160 + print(f' {f[\"id\"]} → {f[\"name\"]}{parent}')
161 +" 2>/dev/null || echo "$response" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 | while read -r name; do
162 + echo " • $name"
163 + done
164 + echo ""
165 +}
166 +
167 +cmd_help() {
168 + cat <<'HELP'
169 +
170 + spb — SPB Private Cloud CLI
171 +
172 + Commands:
173 + spb config Configure server URL and API key
174 + spb upload <file> [folder_id] Upload a file
175 + spb upload-dir <dir> [folder_id] Upload all files in a directory
176 + spb ls [folder_id] List files (optionally in a folder)
177 + spb folders List all folders with their IDs
178 + spb help Show this help
179 +
180 + Examples:
181 + spb config # URL par défaut: https://cloud.spboucher.ai
182 + spb upload rapport.pdf
183 + spb upload photo.jpg abc123def
184 + spb upload-dir ~/Documents/reports
185 + spb ls
186 + spb folders
187 +
188 +HELP
189 +}
190 +
191 +# ─── Main ─────────────────────────────────────────────────────────────────────
192 +
193 +case "${1:-help}" in
194 + config) cmd_config ;;
195 + upload) cmd_upload "$2" "$3" ;;
196 + upload-dir) cmd_upload_dir "$2" "$3" ;;
197 + ls) cmd_ls "$2" ;;
198 + folders) cmd_folders ;;
199 + help|--help) cmd_help ;;
200 + *)
201 + echo "Unknown command: $1"
202 + cmd_help
203 + exit 1
204 + ;;
205 +esac
added start-cloud.sh +15 −0
@@ -0,0 +1,15 @@
1 +#!/bin/bash
2 +export PATH="$HOME/local/node-v22.15.0-darwin-arm64/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
3 +cd "$HOME/spb-private-cloud" || exit 1
4 +
5 +export NODE_ENV=production
6 +export PORT=5001
7 +
8 +# Build de production si absent (premier lancement / après nettoyage de .next)
9 +if [ ! -f ".next/BUILD_ID" ]; then
10 + echo "> [start] Aucun build trouvé — next build..."
11 + npm run build || { echo "> [start] build échoué"; exit 1; }
12 +fi
13 +
14 +# server.ts lit NODE_ENV : production => next({ dev:false }) (build optimisé)
15 +exec npx tsx server.ts
16