Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(demo): seed demo with dummy data (#776)

Corentin Thomasset0514f906d491
diff --git a/apps/papra-client/package.json b/apps/papra-client/package.json
index 0e75b340..99398709 100644
--- a/apps/papra-client/package.json
+++ b/apps/papra-client/package.json
@@ -23,7 +23,8 @@
"test": "vitest run",
"test:watch": "vitest watch",
"typecheck": "tsc --noEmit",
- "script:sync-i18n-key-order": "tsx src/scripts/sync-i18n-key-order.script.ts"
+ "script:sync-i18n-key-order": "tsx src/scripts/sync-i18n-key-order.script.ts",
+ "script:generate-demo-documents-fixtures": "tsx src/scripts/generate-demo-documents-fixtures.script.ts"
},
"dependencies": {
"@branchlet/core": "^1.0.0",
@@ -56,6 +57,7 @@
"devDependencies": {
"@antfu/eslint-config": "catalog:",
"@iconify-json/tabler": "^1.2.19",
+ "@papra/lecture": "workspace:*",
"@types/node": "catalog:",
"eslint": "catalog:",
"eslint-plugin-solid": "^0.14.5",
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.ts
index 4c5c522b..386c20d4 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -1,10 +1,14 @@
import type { ApiKey } from '../api-keys/api-keys.types';
import type { Document } from '../documents/documents.types';
import type { Webhook } from '../webhooks/webhooks.types';
+import type {
+ DocumentFile,
+} from './demo.storage';
import { FetchError } from 'ofetch';
import { createRouter } from 'radix3';
import { get } from '../shared/utils/get';
import { defineHandler } from './demo-api-mock.models';
+import { createId, randomString } from './demo.models';
import {
apiKeyStorage,
documentFileStorage,
@@ -16,16 +20,7 @@ import {
webhooksStorage,
} from './demo.storage';
import { findMany, getValues } from './demo.storage.models';
-
-const corpus = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
-
-function randomString({ length = 10 }: { length?: number } = {}) {
- return Array.from({ length }, () => corpus[Math.floor(Math.random() * corpus.length)]).join('');
-}
-
-function createId({ prefix }: { prefix: string }) {
- return `${prefix}_${randomString({ length: 24 })}`;
-}
+import { demoUser } from './seed/users.fixtures';
function assert(condition: unknown, { message = 'Error', status }: { message?: string; status?: number } = {}): asserts condition {
if (!condition) {
@@ -46,18 +41,27 @@ function fromBase64(base64: string) {
return fetch(base64).then(res => res.blob());
}
-async function serializeFile(file: File) {
+async function serializeFile(file: File): Promise<DocumentFile> {
return {
name: file.name,
size: file.size,
type: file.type,
// base64
- content: await toBase64(file),
+ base64Content: await toBase64(file),
};
}
-async function deserializeFile({ name, type, content }: Awaited<ReturnType<typeof serializeFile>>) {
- return new File([await fromBase64(content)], name, { type });
+async function deserializeFile(storageInfo: DocumentFile): Promise<File> {
+ if ('path' in storageInfo) {
+ const { path, name } = storageInfo;
+ const response = await fetch(path);
+ const blob = await response.blob();
+ return new File([blob], name);
+ }
+
+ const { name, type, base64Content } = storageInfo;
+
+ return new File([await fromBase64(base64Content)], name, { type });
}
const inMemoryApiMock: Record<string, { handler: any }> = {
@@ -81,12 +85,7 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
path: '/api/users/me',
method: 'GET',
handler: () => ({
- user: {
- id: 'usr_1',
- email: '[email protected]',
- name: 'Jane Doe',
- permissions: [],
- },
+ user: demoUser,
}),
}),
@@ -119,7 +118,9 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
} = query ?? {};
return {
- documents: filteredDocuments.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize),
+ documents: filteredDocuments
+ .toSorted((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
+ .slice(pageIndex * pageSize, (pageIndex + 1) * pageSize),
documentsCount: filteredDocuments.length,
};
},
@@ -593,11 +594,7 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
return {
members: [{
id: 'mem_1',
- user: {
- id: 'usr_1',
- email: '[email protected]',
- name: 'Jane Doe',
- },
+ user: demoUser,
role: 'owner',
organizationId,
}],
@@ -774,6 +771,38 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
},
}),
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/documents/:documentId/activity',
+ method: 'GET',
+ handler: async ({ params: { organizationId, documentId }, query }) => {
+ const key = `${organizationId}:${documentId}`;
+ const document = await documentStorage.getItem(key);
+
+ assert(document, { status: 404 });
+
+ const {
+ pageIndex = 0,
+ } = query ?? {};
+
+ // Return mock activity for demo - just a created event
+ const activities = pageIndex === 0
+ ? [{
+ id: 'activity_1',
+ documentId,
+ event: 'created',
+ eventData: {},
+ createdAt: document.createdAt,
+ user: {
+ id: 'usr_1',
+ name: 'Sherlock Holmes',
+ },
+ }]
+ : [];
+
+ return { activities };
+ },
+ }),
+
...defineHandler({
path: '/api/organizations/:organizationId/subscription',
method: 'GET',
diff --git a/apps/papra-client/src/modules/demo/demo-http-client.ts b/apps/papra-client/src/modules/demo/demo-http-client.ts
index f9d511dc..f971e56e 100644
--- a/apps/papra-client/src/modules/demo/demo-http-client.ts
+++ b/apps/papra-client/src/modules/demo/demo-http-client.ts
@@ -3,8 +3,11 @@ import type { MappedResponseType } from 'ofetch';
import type { HttpClientOptions, ResponseType } from '../shared/http/http-client';
import { joinUrlPaths } from '@corentinth/chisels';
import { router } from './demo-api-mock';
+import { ensureDemoStorageSeeded } from './demo.storage';
export async function demoHttpClient<A, R extends ResponseType = 'json'>(options: HttpClientOptions<R>): Promise<MappedResponseType<R, A>> {
+ await ensureDemoStorageSeeded();
+
const path = `/${joinUrlPaths(options.method ?? 'GET', options.url)}`;
const matchedRoute = router.lookup(path);
diff --git a/apps/papra-client/src/modules/demo/demo.constants.ts b/apps/papra-client/src/modules/demo/demo.constants.ts
new file mode 100644
index 00000000..7a78943c
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/demo.constants.ts
@@ -0,0 +1 @@
+export const DEMO_IS_SEEDED_KEY = 'demo:is-seeded';
diff --git a/apps/papra-client/src/modules/demo/demo.models.ts b/apps/papra-client/src/modules/demo/demo.models.ts
new file mode 100644
index 00000000..384f101d
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/demo.models.ts
@@ -0,0 +1,9 @@
+const corpus = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+
+export function randomString({ length = 10 }: { length?: number } = {}) {
+ return Array.from({ length }, () => corpus[Math.floor(Math.random() * corpus.length)]).join('');
+}
+
+export function createId({ prefix }: { prefix: string }) {
+ return `${prefix}_${randomString({ length: 24 })}`;
+}
diff --git a/apps/papra-client/src/modules/demo/demo.provider.tsx b/apps/papra-client/src/modules/demo/demo.provider.tsx
index 8e334eb5..0c69b1c3 100644
--- a/apps/papra-client/src/modules/demo/demo.provider.tsx
+++ b/apps/papra-client/src/modules/demo/demo.provider.tsx
@@ -1,5 +1,5 @@
import type { Component } from 'solid-js';
-import { A, useNavigate } from '@solidjs/router';
+import { A } from '@solidjs/router';
import { createSignal } from 'solid-js';
import { Portal } from 'solid-js/web';
import { useI18n } from '../i18n/i18n.provider';
@@ -8,12 +8,12 @@ import { clearDemoStorage } from './demo.storage';
export const DemoIndicator: Component = () => {
const [getIsMinified, setIsMinified] = createSignal(false);
- const navigate = useNavigate();
const { t, te } = useI18n();
const clearDemo = async () => {
await clearDemoStorage();
- navigate('/');
+ // Navigate to / forcing a full reload
+ window.location.href = '/';
};
return (
diff --git a/apps/papra-client/src/modules/demo/demo.storage.ts b/apps/papra-client/src/modules/demo/demo.storage.ts
index 8230c19c..91a2edab 100644
--- a/apps/papra-client/src/modules/demo/demo.storage.ts
+++ b/apps/papra-client/src/modules/demo/demo.storage.ts
@@ -7,14 +7,22 @@ import type { Webhook } from '../webhooks/webhooks.types';
import { createStorage, prefixStorage } from 'unstorage';
import localStorageDriver from 'unstorage/drivers/localstorage';
import { trackingServices } from '../tracking/tracking.services';
+import { DEMO_IS_SEEDED_KEY } from './demo.constants';
+import { createId } from './demo.models';
+import { documentFixtures } from './seed/documents.fixtures';
+import { tagsFixtures } from './seed/tags.fixtures';
const storage = createStorage<any>({
driver: localStorageDriver({ base: 'demo:' }),
});
+export type DocumentFileStoredFile = { name: string; size: number; type: string; base64Content: string };
+export type DocumentFileRemoteFile = { name: string; path: string };
+export type DocumentFile = DocumentFileStoredFile | DocumentFileRemoteFile;
+
export const organizationStorage = prefixStorage<Organization>(storage, 'organizations');
export const documentStorage = prefixStorage<Document>(storage, 'documents');
-export const documentFileStorage = prefixStorage(storage, 'documentFiles');
+export const documentFileStorage = prefixStorage<DocumentFile>(storage, 'documentFiles');
export const tagStorage = prefixStorage<Omit<Tag, 'documentsCount'>>(storage, 'tags');
export const tagDocumentStorage = prefixStorage<{ documentId: string; tagId: string; id: string }>(storage, 'tagDocuments');
export const taggingRuleStorage = prefixStorage<TaggingRule>(storage, 'taggingRules');
@@ -23,5 +31,106 @@ export const webhooksStorage = prefixStorage<Webhook>(storage, 'webhooks');
export async function clearDemoStorage() {
await storage.clear();
+ localStorage.removeItem(DEMO_IS_SEEDED_KEY);
trackingServices.capture({ event: 'Demo storage cleared' });
}
+
+// Simple in-memory lock to prevent concurrent seeding
+let seedingPromise: Promise<void> | null = null;
+
+export async function ensureDemoStorageSeeded() {
+ // If already seeded, return immediately
+ if (localStorage.getItem(DEMO_IS_SEEDED_KEY)) {
+ return;
+ }
+
+ // If seeding is in progress, wait for it
+ if (seedingPromise) {
+ return seedingPromise;
+ }
+
+ await clearDemoStorage();
+
+ // Start seeding
+ seedingPromise = seedDemoStorage()
+ .then(() => {
+ localStorage.setItem(DEMO_IS_SEEDED_KEY, 'true');
+ })
+ .finally(() => {
+ seedingPromise = null;
+ });
+
+ return seedingPromise;
+}
+
+const idTuple = <T extends { id: string }>(item: T): [string, T] => [item.id, item];
+
+export async function seedDemoStorage() {
+ const organizationId = 'org_1GAP1Miap135XEcbKuBQF948'; // hard coded for better navigation on reset
+ const now = new Date('2026-01-20T00:00:00Z');
+ const lastMonth = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
+
+ // Create default organization
+ await organizationStorage.setItem(...idTuple({
+ id: organizationId,
+ name: 'My organization',
+ createdAt: lastMonth,
+ updatedAt: lastMonth,
+ }));
+
+ const tags = tagsFixtures.map(tag => ({
+ id: createId({ prefix: 'tag' }),
+ organizationId,
+ name: tag.name,
+ color: tag.color,
+ description: tag.description,
+ createdAt: lastMonth,
+ updatedAt: lastMonth,
+ }));
+
+ const tagsPromises = tagStorage.setItems(tags.map(tag => ({ key: tag.id, value: tag })));
+
+ const documentsPromises = documentFixtures.flatMap((fixture) => {
+ const documentId = createId({ prefix: 'doc' });
+
+ const key = `${organizationId}:${documentId}`;
+
+ const documentPromise = documentStorage.setItem(key, {
+ id: documentId,
+ organizationId,
+ name: fixture.name,
+ mimeType: fixture.mimeType,
+ content: fixture.content,
+ originalSize: fixture.size,
+ createdAt: fixture.date,
+ updatedAt: fixture.date,
+ tags: [],
+ });
+
+ const documentFilePromise = documentFileStorage.setItem(`${organizationId}:${documentId}`, { path: fixture.fileUrl, name: fixture.name });
+
+ const tagIds = tags
+ .filter(tag => fixture.tags.includes(tag.name))
+ .map(tag => tag.id);
+
+ const tagDocumentPromise = tagDocumentStorage.setItems(tagIds.map((tagId) => {
+ const id = createId({ prefix: 'tagdoc' });
+
+ return {
+ key: id,
+ value: {
+ id,
+ documentId,
+ tagId,
+ },
+ };
+ }));
+
+ return [documentPromise, documentFilePromise, tagDocumentPromise];
+ });
+
+ await Promise.all([
+ tagsPromises,
+ ...documentsPromises,
+ ]);
+}
diff --git a/apps/papra-client/src/modules/demo/seed/documents.fixtures.ts b/apps/papra-client/src/modules/demo/seed/documents.fixtures.ts
new file mode 100644
index 00000000..4f9a9ab7
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents.fixtures.ts
@@ -0,0 +1,5 @@
+import type { DemoDocumentFixture } from './fixtures.types';
+
+const documentsFixtures = import.meta.glob('./documents/*.demo-document.ts', { eager: true }) as Record<string, { default: DemoDocumentFixture }>;
+
+export const documentFixtures = Object.values(documentsFixtures).map(module => module.default);
diff --git a/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.file.pdf
new file mode 100644
index 00000000..52c4ab13
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.ts
new file mode 100644
index 00000000..a4ab8203
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/001.demo-document.ts
@@ -0,0 +1,35 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './001.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Blackmail letter from Reginald Thornton-Fiennes',
+ fileUrl,
+ date: new Date('2026-01-20'),
+ mimeType: 'application/pdf',
+ size: 31564,
+ tags: ['Cases'],
+ content: `
+blackmail letter from reginald thornton fiennes date january 20 2026
+reggie com to sherlock holmes sleuth subject the secrets you
+ve kept dear i hope this finds well or at
+very least in a state of mild desperation m sure
+re aware that our paths have crossed on numerous occasions
+over years conversations though often laced with wit and sarcasm
+left me an unshakeable feeling there s more than meets
+eye been doing some digging oh how wish could say
+it was mere coincidence led moment truth but no my
+curiosity has proven too great appears your remarkable faculties not
+only served line work also as amateur spy private investigator
+reason believe watching yes even all scandals see just wealthy
+socialite penchant for fast cars high stakes poker nephew lord
+harrington man far influence ll ever humble abode 221b baker
+street two weeks come clean about what know anything less
+will result releasing incriminating evidence ruin reputation leave questioning everything
+thought knew yourself don t didn warn 14 days respond
+yours sincerely secret life exposed world theft sensitive information estate
+unwavering
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.file.pdf
new file mode 100644
index 00000000..94fb05d7
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.ts
new file mode 100644
index 00000000..3b51af84
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/002.demo-document.ts
@@ -0,0 +1,41 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './002.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Contract private investigation - Pemberton',
+ fileUrl,
+ date: new Date('2024-09-22'),
+ mimeType: 'application/pdf',
+ size: 54921,
+ tags: ['Legal', 'Cases'],
+ content: `
+contract private investigation pemberton number sh 2024 087 date 22nd
+september parties service provider sherlock holmes consulting detective 221b baker
+street marylebone london nw1 6xe email sherlockholmes co uk client
+lady victoria estate 15 belgrave square sw1x 8hu v pembertonltd
+com services the agrees to conduct a into matter of
+missing family heirloom jewellery as described in attached case brief
+appendix scope work includes terms and conditions initial consultation assessment
+evidence gathering witness interviews background research verification surveillance operations if
+required analysis deduction written report findings court testimony necessary billed
+separately 1 duration commence 25th continue until resolution or termination
+not exceed 60 days without mutual agreement 2 fees 3
+payment 4 confidentiality all information regarding this shall remain strictly
+confidential will disclose details any third party consent except by
+law 5 reporting 6 either may terminate with 7 notice
+remains liable for expenses incurred up limitations reasonable include but
+are limited fee 500 paid upon signing hourly rate 250
+per hour estimated total 000 reimbursed at cost travel materials
+specialist consultations 50 deposit 750 due balance within 14 completion
+invoiced monthly via bank transfer account provided weekly progress updates
+verbal preferred final comprehensive conclusion become property no guarantee specific
+outcome reserves right decline use illegal methods refuse involves criminal
+activity accommodation exceeding 200 require prior approval signatures signature name
+dr john h watson address is governed laws england wales
+disputes be resolved through arbitration attorney contact mycroft associates legal
+holmeslegal laboratory forensic testing expert document retrieval costs communication equipment
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.file.pdf
new file mode 100644
index 00000000..77af2be2
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.ts
new file mode 100644
index 00000000..53260908
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/003.demo-document.ts
@@ -0,0 +1,33 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './003.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Digital resume',
+ fileUrl,
+ date: new Date('2025-03-15'),
+ mimeType: 'application/pdf',
+ size: 38370,
+ tags: ['Personal'],
+ content: `
+digital resume contact information summary highly skilled and renowned detective
+with over a decade of experience in solving complex cases
+proven track record delivering results under tight deadlines while maintaining
+impeccable work standards discretion expertise spans forensic analysis surveillance hacking
+disguise techniques skills email sholmes mindpalace net phone 1 202
+555 1234 linkedin com sherlockholmes twitter investigation extensive gathering intelligence
+conducting interviews analyzing evidence dna fingerprints other physical to identify
+patterns connections including human observation cctv monitoring tracking proficient computer
+forensics breaching secure systems recovering data from encrypted files creating
+convincing disguises blend various environments social situations consulting 2015 present
+worked on high profile for prominent clients government agencies private
+corporations developed executed plans gather conduct solve crimes collaborated law
+enforcement provide expert testimony royal scottish constabulary 2005 2010 served
+as inspector the edinburgh division conducted crime scenes analyzed education
+awards recognition university cambridge 2000 2004 studied sociology criminology science
+psychology s award outstanding service london metropolitan police department specialized
+investigative services
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.file.pdf
new file mode 100644
index 00000000..604d093f
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.ts
new file mode 100644
index 00000000..e4ef017e
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/004.demo-document.ts
@@ -0,0 +1,33 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './004.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Dr Watson letter - Missing heirloom',
+ fileUrl,
+ date: new Date('2026-01-20'),
+ mimeType: 'application/pdf',
+ size: 31307,
+ tags: ['Personal', 'Cases'],
+ content: `
+dr watson letter missing heirloom from john jwatson example com
+to sherlock holmes sherlockholmes date 20 january 2026 subject the
+curious case of dear i hope this finds you well
+am writing my office at st bart s hospital where
+have been observing a most peculiar lady emily windsor prominent
+socialite and cousin royal family has approached me with request
+for assistance it appears that her priceless diamond necklace passed
+down through generations gone was last seen during christmas gathering
+their estate in countryside is frantic as holds significant historical
+sentimental value believes theft may be linked recent string high
+profile burglaries area she reason believe notorious thief known only
+by his alias fox behind working personal investigator gather evidence
+track leads however could do your exceptional skills shed some
+light on unique expertise forensic analysis cryptography deduction would invaluable
+uncovering truth dastardly crime willing take join tomorrow morning attached
+few details regarding investigation so far looking forward hearing soon
+best regards
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.file.pdf
new file mode 100644
index 00000000..e3d7c1f3
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.ts
new file mode 100644
index 00000000..1574f5ae
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/005.demo-document.ts
@@ -0,0 +1,30 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './005.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Laptop insurance policy',
+ fileUrl,
+ date: new Date('2026-01-20'),
+ mimeType: 'application/pdf',
+ size: 52945,
+ tags: ['Legal'],
+ content: `
+laptop insurance policy number shlpi 001 date january 20 2026
+expiration 19 2027 insured information field value name sherlock holmes
+address 221b baker street london uk email sholmes com phone
+44 7777 123456 coverage details terms and conditions exclusions claims
+procedure device apple macbook pro 16 inch valuation 10 000
+deductible 500 premium 150 per annum 1 the policyholder acknowledges
+that they have read understood of this 2 agrees to
+maintain in good condition report any damage or loss company
+within 24 hours 3 is responsible for paying additional costs
+expenses associated with repairing replacing intentional caused intentionally by their
+authorized users pre existing defects existed prior effective natural disasters
+such as floods earthquakes hurricanes signing below i acknowledge signature
+contact our department at sholmesinsurance provide proof ownership documentation supporting
+claim will investigate settle accordance
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.file.pdf
new file mode 100644
index 00000000..26fd311b
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.ts
new file mode 100644
index 00000000..588fe704
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/006.demo-document.ts
@@ -0,0 +1,27 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './006.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Receipt for Groceries',
+ fileUrl,
+ date: new Date('2026-01-20'),
+ mimeType: 'application/pdf',
+ size: 50374,
+ tags: ['Receipts'],
+ content: `
+receipt for groceries date january 20 2026 store tesco superstore
+123 regent st london sw1e 7na order number tcgro000023 item
+quantity unit price subtotal bread wholemeal 2 loaves 1 40
+eggs 12 pack 50 80 chicken breast fillets 500g 6
+00 3 brown rice bag 25 fresh carrots 750g bunch
+0 60 45 apple juice 1l bottle toothpaste colgate tubes
+16 30 vat 26 total 19 56 payment method credit
+card visa signature 1234 last 4 digits only of purchase
+notes this has been archived in our digital document archive
+future reference received a 10 discount on the bill being
+frequent customer paid with my clubcard to earn points
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.file.pdf
new file mode 100644
index 00000000..94d28d90
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.ts
new file mode 100644
index 00000000..b9fb3202
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/007.demo-document.ts
@@ -0,0 +1,25 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './007.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Rent receipt - April 2025',
+ fileUrl,
+ date: new Date('2025-04-01'),
+ mimeType: 'application/pdf',
+ size: 38421,
+ tags: ['Receipts', 'Property'],
+ content: `
+rent receipt april 2025 221b baker street marylebone london nw1
+6xe date 1st received from mr sherlock holmes for first
+floor flat period amount 2 000 00 two thousand pounds
+payment method bank transfer 29th march breakdown total paid signature
+m hudson mrs martha landlord notes thank you finally fixing
+the bullet holes in wall though i do wish d
+asked before repainting that shade of green is rather unusual
+also dr watson left his umbrella last visit h monthly
+1 850 service charge 150
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.file.pdf
new file mode 100644
index 00000000..0164cd4b
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.ts
new file mode 100644
index 00000000..bffbd7f0
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/008.demo-document.ts
@@ -0,0 +1,25 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './008.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Rent receipt - July 2025',
+ fileUrl,
+ date: new Date('2025-07-01'),
+ mimeType: 'application/pdf',
+ size: 37805,
+ tags: ['Receipts', 'Property'],
+ content: `
+rent receipt july 2025 221b baker street marylebone london nw1
+6xe date 1st received from mr sherlock holmes for first
+floor flat period amount 2 000 00 two thousand pounds
+payment method bank transfer 30th june breakdown total paid signature
+m hudson mrs martha landlord notes the windows will need
+washing after whatever smoke came your chemistry set last tuesday
+i ve scheduled a cleaner next week please try to
+keep explosions minimum during tourist season h monthly 1 850
+service charge 150
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.file.pdf
new file mode 100644
index 00000000..207c08cb
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.ts
new file mode 100644
index 00000000..e9a79130
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/009.demo-document.ts
@@ -0,0 +1,25 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './009.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Rent receipt - June 2025',
+ fileUrl,
+ date: new Date('2025-06-01'),
+ mimeType: 'application/pdf',
+ size: 37851,
+ tags: ['Receipts', 'Property'],
+ content: `
+rent receipt june 2025 221b baker street marylebone london nw1
+6xe date 1st received from mr sherlock holmes for first
+floor flat period amount 2 000 00 two thousand pounds
+payment method bank transfer 30th may breakdown total paid signature
+m hudson mrs martha landlord notes i ve taken the
+liberty of stocking kitchen with proper tea and biscuits you
+really must eat something besides whatever experimental substances keep in
+test tubes your brother mycroft stopped by asking after h
+monthly 1 850 service charge 150
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.file.pdf
new file mode 100644
index 00000000..4a3bfe99
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.ts
new file mode 100644
index 00000000..1bbb33eb
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/010.demo-document.ts
@@ -0,0 +1,25 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './010.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Rent receipt - March 2025',
+ fileUrl,
+ date: new Date('2025-03-01'),
+ mimeType: 'application/pdf',
+ size: 37532,
+ tags: ['Receipts', 'Property'],
+ content: `
+rent receipt march 2025 221b baker street marylebone london nw1
+6xe date 1st received from mr sherlock holmes for first
+floor flat period amount 2 000 00 two thousand pounds
+payment method bank transfer 28th february breakdown total paid signature
+m hudson mrs martha landlord notes please remember to keep
+the violin playing reasonable hours new tenants downstairs have complained
+again also whatever chemical experiment you were conducting last tuesday
+has stained bathroom sink h monthly 1 850 service charge
+150
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.file.pdf
new file mode 100644
index 00000000..484738c9
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.ts
new file mode 100644
index 00000000..01a9a4e4
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/011.demo-document.ts
@@ -0,0 +1,25 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './011.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Rent receipt - May 2025',
+ fileUrl,
+ date: new Date('2025-05-01'),
+ mimeType: 'application/pdf',
+ size: 38711,
+ tags: ['Receipts', 'Property'],
+ content: `
+rent receipt may 2025 221b baker street marylebone london nw1
+6xe date 1st received from mr sherlock holmes for first
+floor flat period amount 2 000 00 two thousand pounds
+payment method bank transfer 29th april breakdown total paid signature
+m hudson mrs martha landlord notes the postman mentioned he
+s been bringing rather a lot of parcels marked fragile
+chemical supplies i trust you re being careful also early
+this month much appreciated h monthly 1 850 service charge
+150
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.file.pdf
new file mode 100644
index 00000000..14ce3c9f
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.ts
new file mode 100644
index 00000000..67fd458f
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/012.demo-document.ts
@@ -0,0 +1,30 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './012.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Violin receipt',
+ fileUrl,
+ date: new Date('2025-11-08'),
+ mimeType: 'application/pdf',
+ size: 51229,
+ tags: ['Receipts'],
+ content: `
+violin receipt vendor information transaction details item description price quantity
+customized the baker 2 500 00 1 hard case with
+lock 150 tuning mute 20 bridge adjustment service 50 subtotal
+720 tax 540 80 total 3 260 payment method purchase
+notes custom made to specifications of our client mr sherlock
+holmes features a unique pattern on its body and distinctive
+sound hole design is designed for optimal protection during transportation
+has been included convenience delivery items will be delivered address
+221b street london w1a 5bj by courier next working day
+return policy please contact us within 14 days if you
+wish any due unsatisfactory quality or performance refunds issued in
+full minus shipping costs incurred company name strings ltd 145
+regent w1b 5sa phone number 020 7123 4567 email info
+example com credit card visa exp date 02 2027
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.file.pdf b/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.file.pdf
new file mode 100644
index 00000000..d248c650
Binary files /dev/null and b/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.file.pdf differ
diff --git a/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.ts b/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.ts
new file mode 100644
index 00000000..9963f52e
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/documents/013.demo-document.ts
@@ -0,0 +1,29 @@
+import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './013.demo-document.file.pdf?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: 'Water incident report',
+ fileUrl,
+ date: new Date('2024-08-14'),
+ mimeType: 'application/pdf',
+ size: 32493,
+ tags: ['Property'],
+ content: `
+water incident report from s holmes first floor to mrs
+m hudson landlord subject aquatic invasion date 14 august 2024
+is currently cascading the ceiling onto my desk at a
+rate suggesting upstairs tenant has installed small waterfall feature they
+have not facts solution ring competent tradesperson i ve compiled
+list of three who understand basic physics bucket catching deluge
+will reach capacity by 19 47 tomorrow shall be out
+investigating an actual mystery do try flood building in absence
+sh additional note leak distinct metallic odour copper piping corroded
+could told you this would happen fact did may bathroom
+northwest quadrant duration 3 days noticed sooner if still brought
+tea casualties one chemical analysis irreplaceable culprit your economical plumber
+june
+
+`.trim(),
+};
+
+export default demoDocumentFixture;
diff --git a/apps/papra-client/src/modules/demo/seed/documents/generate/.gitkeep b/apps/papra-client/src/modules/demo/seed/documents/generate/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/apps/papra-client/src/modules/demo/seed/fixtures.types.ts b/apps/papra-client/src/modules/demo/seed/fixtures.types.ts
new file mode 100644
index 00000000..b34335e9
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/fixtures.types.ts
@@ -0,0 +1,11 @@
+import type { DemoTagFixtureNames } from './tags.fixtures';
+
+export type DemoDocumentFixture = {
+ name: string;
+ date: Date;
+ fileUrl: string;
+ content: string;
+ tags: DemoTagFixtureNames[];
+ mimeType: string;
+ size: number;
+};
diff --git a/apps/papra-client/src/modules/demo/seed/tags.fixtures.ts b/apps/papra-client/src/modules/demo/seed/tags.fixtures.ts
new file mode 100644
index 00000000..520914c3
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/tags.fixtures.ts
@@ -0,0 +1,33 @@
+export const tagsFixtures = [
+ {
+ name: 'Receipts',
+ color: '#10b981',
+ description: 'Payment receipts and bills',
+ },
+ {
+ name: 'Legal',
+ color: '#3b82f6',
+ description: 'Legal documents and contracts',
+ },
+ {
+ name: 'Personal',
+ color: '#8b5cf6',
+ description: 'Personal correspondence and documents',
+ },
+ {
+ name: 'Cases',
+ color: '#ef4444',
+ description: 'Investigation cases and related documents',
+ },
+ {
+ name: 'Property',
+ color: '#f59e0b',
+ description: 'Property and rental documents',
+ },
+] as const satisfies {
+ name: string;
+ color: string;
+ description: string;
+}[];
+
+export type DemoTagFixtureNames = (typeof tagsFixtures)[number]['name'];
diff --git a/apps/papra-client/src/modules/demo/seed/users.fixtures.ts b/apps/papra-client/src/modules/demo/seed/users.fixtures.ts
new file mode 100644
index 00000000..69258683
--- /dev/null
+++ b/apps/papra-client/src/modules/demo/seed/users.fixtures.ts
@@ -0,0 +1,6 @@
+export const demoUser = {
+ id: 'usr_1',
+ email: '[email protected]',
+ name: 'Sherlock Holmes',
+ permissions: [],
+};
diff --git a/apps/papra-client/src/scripts/generate-demo-documents-fixtures.script.ts b/apps/papra-client/src/scripts/generate-demo-documents-fixtures.script.ts
new file mode 100644
index 00000000..b1c58927
--- /dev/null
+++ b/apps/papra-client/src/scripts/generate-demo-documents-fixtures.script.ts
@@ -0,0 +1,197 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import process from 'node:process';
+import { fileURLToPath } from 'node:url';
+import { extractText } from '@papra/lecture';
+
+// Configuration
+const DELETE_AFTER_PROCESSING = false;
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+const DOCUMENTS_DIR = path.join(__dirname, '../modules/demo/seed/documents');
+const GENERATE_DIR = path.join(DOCUMENTS_DIR, 'generate');
+
+type FileMetadata = {
+ filename: string;
+ path: string;
+ size: number;
+ extension: string;
+ mimeType: string;
+};
+
+function getNextFixtureNumber(): string {
+ const files = fs.readdirSync(DOCUMENTS_DIR);
+ const fixtureFiles = files.filter(file => /^\d{3}\.demo-document\.ts$/.test(file));
+
+ if (fixtureFiles.length === 0) {
+ return '001';
+ }
+
+ const numbers = fixtureFiles.map(file => Number.parseInt(file.substring(0, 3), 10));
+ const maxNumber = Math.max(...numbers);
+ const nextNumber = maxNumber + 1;
+
+ return nextNumber.toString().padStart(3, '0');
+}
+
+function getMimeType({ filename }: { filename: string }): string {
+ const ext = path.extname(filename).toLowerCase();
+ const mimeTypes: Record<string, string> = {
+ '.pdf': 'application/pdf',
+ '.txt': 'text/plain',
+ '.doc': 'application/msword',
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ '.rtf': 'application/rtf',
+ '.odt': 'application/vnd.oasis.opendocument.text',
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ '.odp': 'application/vnd.oasis.opendocument.presentation',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.png': 'image/png',
+ '.gif': 'image/gif',
+ '.bmp': 'image/bmp',
+ '.tiff': 'image/tiff',
+ '.webp': 'image/webp',
+ };
+
+ return mimeTypes[ext] || 'application/octet-stream';
+}
+
+function getFilesToProcess(): FileMetadata[] {
+ const files = fs.readdirSync(GENERATE_DIR);
+
+ return files
+ .filter(filename => filename !== '.gitkeep')
+ .map((filename) => {
+ const filePath = path.join(GENERATE_DIR, filename);
+ const stats = fs.statSync(filePath);
+ const extension = path.extname(filename);
+ const mimeType = getMimeType({ filename });
+
+ return {
+ filename,
+ path: filePath,
+ size: stats.size,
+ extension,
+ mimeType,
+ };
+ });
+}
+
+async function extractTextFromFile({ filePath, mimeType }: { filePath: string; mimeType: string }): Promise<string> {
+ const fileBuffer = fs.readFileSync(filePath);
+ const arrayBuffer = fileBuffer.buffer.slice(
+ fileBuffer.byteOffset,
+ fileBuffer.byteOffset + fileBuffer.byteLength,
+ );
+
+ const result = await extractText({
+ arrayBuffer,
+ mimeType,
+ });
+
+ if (result.error) {
+ throw result.error;
+ }
+
+ // Remove duplicated words, lines breaks, punctuations, and extra spaces
+ const simplifiedContentWords = [...new Set(
+ result.textContent
+ ?.replace(/[\r\n]+/g, ' ') // Normalize line breaks
+ .replace(/[^\w\s]|_/g, ' ') // Remove punctuations
+ .replace(/\s+/g, ' ') // Remove extra spaces
+ .trim()
+ .toLowerCase()
+ .split(' '),
+ )];
+
+ // multi-lined content
+ const wordPerLine = 10;
+ let simplifiedContent = '';
+ for (let i = 0; i < simplifiedContentWords.length; i += wordPerLine) {
+ const lineWords = simplifiedContentWords.slice(i, i + wordPerLine);
+ simplifiedContent += `${lineWords.join(' ')}\n`;
+ }
+
+ return simplifiedContent;
+}
+
+function generateFixtureFile({ fixtureNumber, metadata, content }: { fixtureNumber: string; metadata: FileMetadata; content: string }): string {
+ const nameWithoutExt = path.basename(metadata.filename, metadata.extension);
+
+ return `import type { DemoDocumentFixture } from '../fixtures.types';
+import fileUrl from './${fixtureNumber}.demo-document.file${metadata.extension}?url';
+
+const demoDocumentFixture: DemoDocumentFixture = {
+ name: '${nameWithoutExt}',
+ fileUrl,
+ date: new Date('${new Date().toISOString().split('T')[0]}'),
+ mimeType: '${metadata.mimeType}',
+ size: ${metadata.size},
+ tags: [],
+ content: \`
+${content}
+\`.trim(),
+};
+
+export default demoDocumentFixture;
+`;
+}
+
+async function processFile({ file, fixtureNumber }: { file: FileMetadata; fixtureNumber: string }): Promise<void> {
+ console.log(`\nProcessing: ${file.filename}`);
+
+ const content = await extractTextFromFile({ filePath: file.path, mimeType: file.mimeType });
+
+ const fileDestPath = path.join(DOCUMENTS_DIR, `${fixtureNumber}.demo-document.file${file.extension}`);
+ fs.copyFileSync(file.path, fileDestPath);
+
+ const fixtureContent = generateFixtureFile({ fixtureNumber, metadata: file, content });
+ const fixtureDestPath = path.join(DOCUMENTS_DIR, `${fixtureNumber}.demo-document.ts`);
+ fs.writeFileSync(fixtureDestPath, fixtureContent, 'utf-8');
+ console.log(`Generated fixture: ${fixtureDestPath}`);
+
+ // Delete source file if configured
+ if (DELETE_AFTER_PROCESSING) {
+ fs.unlinkSync(file.path);
+ console.log(`Deleted source file: ${file.path}`);
+ }
+}
+
+async function main() {
+ console.log(`Generate directory: ${GENERATE_DIR}`);
+ console.log(`Output directory: ${DOCUMENTS_DIR}`);
+ console.log(`Delete after processing: ${DELETE_AFTER_PROCESSING}\n`);
+
+ // Get files to process
+ const files = getFilesToProcess();
+
+ if (files.length === 0) {
+ console.log('No files to process.');
+ return;
+ }
+
+ console.log(`Found ${files.length} file(s) to process:\n`);
+ files.forEach(file => console.log(` - ${file.filename}`));
+
+ // Process each file
+ let currentFixtureNumber = Number.parseInt(getNextFixtureNumber(), 10);
+
+ for (const file of files) {
+ try {
+ const fixtureNumber = currentFixtureNumber.toString().padStart(3, '0');
+ await processFile({ file, fixtureNumber });
+ currentFixtureNumber++;
+ } catch (error) {
+ console.error(`\nError processing ${file.filename}:`, error);
+ }
+ }
+}
+
+// Execute
+main().catch((error) => {
+ console.error('Fatal error:', error);
+ process.exit(1);
+});
diff --git a/apps/papra-client/vite.config.ts b/apps/papra-client/vite.config.ts
index 5820b25c..4d7f7606 100644
--- a/apps/papra-client/vite.config.ts
+++ b/apps/papra-client/vite.config.ts
@@ -1,12 +1,18 @@
+import type { Plugin } from 'vite';
+import fs from 'node:fs';
import path from 'node:path';
+import { env } from 'node:process';
import unoCssPlugin from 'unocss/vite';
import { defineConfig } from 'vite';
import solidPlugin from 'vite-plugin-solid';
+const isDemoMode = env.VITE_IS_DEMO_MODE === 'true';
+
export default defineConfig({
plugins: [
unoCssPlugin(),
solidPlugin(),
+ cleanDemoAssetsPlugin(),
],
server: {
port: 3000,
@@ -31,3 +37,27 @@ export default defineConfig({
// exclude: [...configDefaults.exclude, '**/*.e2e.test.ts'],
// },
});
+
+function cleanDemoAssetsPlugin(): Plugin {
+ return {
+ name: 'clean-demo-assets',
+ closeBundle() {
+ if (!isDemoMode) {
+ const startedAt = Date.now();
+ const distDir = path.resolve(__dirname, 'dist/assets');
+ const files = fs.readdirSync(distDir);
+
+ const demoPdfPattern = /\d{3}\.demo-document\.file-.+$/;
+
+ files.forEach((file) => {
+ if (demoPdfPattern.test(file)) {
+ const filePath = path.join(distDir, file);
+ fs.unlinkSync(filePath);
+ }
+ });
+ const duration = Date.now() - startedAt;
+ console.log(`[clean-demo-assets] Removed demo documents from build output in ${duration}ms`);
+ }
+ },
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c2622c8c..c9a8e359 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -368,6 +368,9 @@ importers:
'@iconify-json/tabler':
specifier: ^1.2.19
version: 1.2.19
+ '@papra/lecture':
+ specifier: workspace:*
+ version: link:../../packages/lecture
'@types/node':
specifier: 'catalog:'
version: 24.0.10