// Optional script: pre-populates a fresh instance with the demo workspace // (built in seed-content.ts, shared with the web client's example pack). // Entities live in the clients' Loro docs, so the fixtures are appended to the // sync log as snapshots; every device bootstraps them from there. The PDF // bytes and their extracted text land in the content-addressed store, plus a // documents-table row per file for the server-side pipeline. // Run with: npm run seed. Honours DB_DIALECT (sqlite default / postgres). import fs from 'node:fs'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { LoroDoc } from 'loro-crdt'; import { eq } from 'drizzle-orm'; import { openDrizzle } from '../infrastructure/persistence/drizzle/db'; import { storeBytes, writeMeta } from '../infrastructure/external/cas'; import { buildSeedContent, SEED_DEVICE } from './seed-content'; async function seed(): Promise { const { db, schema, close } = await openDrizzle(); try { const existing = await db .select({ id: schema.crdtUpdates.id }) .from(schema.crdtUpdates) .where(eq(schema.crdtUpdates.docId, 'workspace')) .limit(1); if (existing[0]) { console.log('\u23ed\ufe0f workspace log already has entries, seed skipped.'); return; } const content = await buildSeedContent(); for (const blob of content.blobs) { storeBytes(blob.bytes); writeMeta(blob.hash, { mime: blob.mime, size: blob.bytes.length, userId: null }); // The null owner (auth off) is stored as '' in blob_owners; without a // row the owner-scoped blob GET would 404 the seeded documents. await db .insert(schema.blobOwners) .values({ hash: blob.hash, userId: '' }) .onConflictDoNothing(); } const uploadsDir = process.env.UPLOADS_DIR ?? path.join(process.cwd(), 'uploads'); fs.mkdirSync(uploadsDir, { recursive: true }); for (const doc of content.documents) { const filename = `seed-${randomUUID()}.pdf`; const filepath = path.join(uploadsDir, filename); fs.writeFileSync(filepath, doc.pdf); await db.insert(schema.documents).values({ id: doc.id, userId: null, originalName: doc.originalName, filename, filepath, extractedText: doc.extractedText, pageCount: doc.pageCount, contentHash: doc.contentHash, textHash: doc.textHash, }); } const row = (docId: string, doc: LoroDoc) => ({ userId: null, docId, seq: 1, payloadHash: storeBytes(Buffer.from(doc.export({ mode: 'snapshot' }))).hash, deviceId: SEED_DEVICE, }); await db .insert(schema.crdtUpdates) .values([ row('workspace', content.workspace), row('attempts', content.attempts), ...[...content.annDocs.entries()].map(([docId, doc]) => row(docId, doc)), ]); console.log( `\u2705 seeded ${content.courseCount} courses with study fixtures into the sync log.`, ); } finally { await close(); } } void seed();