// The demo workspace, built once and consumed twice: seed.ts appends it to a // server's sync log, make-example-pack.ts zips it into the web client's // first-launch pack. Everything here is pure content: Loro docs, PDF bytes and // their hashes; persistence stays with the callers. import { createHash, randomUUID } from 'node:crypto'; import { PDFDocument, StandardFonts } from 'pdf-lib'; import { LoroDoc, LoroMap, LoroMovableList } from 'loro-crdt'; export const SEED_DEVICE = 'seed'; // Fixed Loro peer id for the seed docs, so every imported change is attributable // to one known device instead of a random peer that reads as "Unknown device". // The client names this peer at bootstrap (SEED_PEER_ID in web identity.ts must // match). Decimal string, kept inside 2^53 like the client's derived peer ids. const SEED_PEER_ID = '700000000000001'; const now = (): string => new Date().toISOString(); const daysAgo = (n: number): string => new Date(Date.now() - n * 86_400_000).toISOString(); const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); const courses = [ { code: '18.01', name: 'Single Variable Calculus', exam_date: '2026-09-01', topics: [ 'Differentiation', 'Applications of Differentiation', 'The Definite Integral', 'Techniques of Integration', 'Exploring the Infinite', ], }, { code: '6.006', name: 'Introduction to Algorithms', exam_date: '2026-09-05', topics: [ 'Algorithm Analysis', 'Sorting and Trees', 'Hashing', 'Numerics', 'Graphs', 'Shortest Paths', 'Dynamic Programming', ], }, { code: '8.01', name: 'Classical Mechanics', exam_date: '2026-09-02', topics: [ 'Kinematics', "Newton's Laws of Motion", 'Circular Motion', 'Momentum and Impulse', 'Work and Energy', 'Rotational Motion', ], }, ]; // The same container conventions as the web app's repos: entities are child // LoroMaps in per-kind registries, ordering lives in MovableLists. function setEntity(doc: LoroDoc, registry: string, id: string, fields: Record) { const reg = doc.getMap(registry); const existing = reg.get(id); const entry = existing instanceof LoroMap ? existing : reg.setContainer(id, new LoroMap()); for (const [key, value] of Object.entries(fields)) entry.set(key, value); return entry; } function childList(parent: LoroMap, key: string): LoroMovableList { const value = parent.get(key); return value instanceof LoroMovableList ? value : parent.setContainer(key, new LoroMovableList()); } function childMap(parent: LoroMap, key: string): LoroMap { const value = parent.get(key); return value instanceof LoroMap ? value : parent.setContainer(key, new LoroMap()); } // Real-looking lecture handouts, so screenshots and demos read like actual // course material. The first two calculus pages keep their exact line layout; // the docs screenshot spec places annotations over those lines. interface PageSpec { title: string; lines: string[]; } const CALC_PAGES: PageSpec[] = [ { title: 'Lecture 3: Limits and continuity', lines: [ 'Definition. Let f be defined near a. We say that the limit of f(x) as x', 'approaches a equals L, written lim f(x) = L, when f(x) gets arbitrarily', 'close to L for all x sufficiently close to a.', '', 'Definition. f is continuous at a when lim f(x) = f(a) as x approaches a.', 'Informally: small changes in the input produce small changes in the output.', '', 'Theorem (squeeze). If g(x) <= f(x) <= h(x) near a and g and h share the', 'limit L at a, then f also has limit L at a.', '', 'Example. lim (sin x)/x = 1 as x approaches 0, by the squeeze theorem', 'applied to cos x <= (sin x)/x <= 1.', ], }, { title: 'Lecture 4: The derivative', lines: [ "Definition. The derivative of f at a is f'(a) = lim (f(a+h) - f(a)) / h", 'as h approaches 0, when this limit exists.', '', 'Every differentiable function is continuous; the converse fails, as the', 'absolute value function shows at 0.', '', 'Power rule. For every integer n, d/dx x^n = n x^(n-1).', 'Examples. d/dx x^2 = 2x, d/dx x^3 = 3x^2, d/dx 1/x = -1/x^2.', '', 'The sum and product rules follow from the definition by computation.', ], }, { title: 'Lecture 5: The chain rule', lines: [ 'Theorem. If g is differentiable at a and f at g(a), then the composite', "f(g(x)) is differentiable at a with derivative f'(g(a)) g'(a).", '', 'In Leibniz notation: dy/dx = (dy/du)(du/dx), with u = g(x).', '', 'Example. d/dx sin(x^2) = 2x cos(x^2): the outer derivative evaluated at', 'the inner function, times the inner derivative.', '', 'The rule composes: three nested functions give a product of three', 'derivatives, each taken at the right point.', ], }, { title: 'Lecture 9: The definite integral', lines: [ 'Definition. The definite integral of f from a to b is the limit of the', 'Riemann sums sum f(x_i) dx over partitions of [a, b] as the mesh goes', 'to zero, when that limit exists.', '', 'Geometrically: the signed area between the graph of f and the x axis.', '', 'Properties. The integral is linear, additive over adjacent intervals,', 'and monotone: f <= g on [a, b] implies the same for their integrals.', ], }, { title: 'Lecture 10: The fundamental theorem', lines: [ 'Theorem (FTC, part 1). If f is continuous on [a, b], the function', "F(x) = integral of f from a to x is differentiable, with F' = f.", '', 'Theorem (FTC, part 2). If F is any antiderivative of f on [a, b], the', 'integral of f from a to b equals F(b) - F(a).', '', 'Differentiation and integration are inverse operations; this is the', 'bridge between the two halves of the course.', ], }, { title: 'Lecture 12: Techniques of integration', lines: [ 'Substitution reverses the chain rule: with u = g(x), integrate', "f(g(x)) g'(x) dx as f(u) du.", '', 'Integration by parts reverses the product rule:', 'integral of u dv = uv - integral of v du.', '', 'Choose u by LIATE (logs, inverse trig, algebraic, trig, exponential):', 'differentiate what simplifies, integrate what stays manageable.', ], }, ]; const MECH_PAGES: PageSpec[] = [ { title: 'Lecture 2: Kinematics in one dimension', lines: [ 'Position x(t), velocity v = dx/dt, acceleration a = dv/dt: each is the', 'rate of change of the one before.', '', 'Constant acceleration. v = v0 + a t and x = x0 + v0 t + a t^2 / 2.', 'Eliminating t gives v^2 = v0^2 + 2 a (x - x0).', '', 'Free fall is the special case a = -g with g about 9.8 m/s^2.', ], }, { title: "Lecture 4: Newton's laws", lines: [ 'First law. With no net force, velocity is constant.', '', 'Second law. F = m a: the net force on a body equals its mass times its', 'acceleration. It is a vector equation, one component per axis.', '', 'Third law. Forces come in pairs: if A pushes B, then B pushes A with', 'equal magnitude and opposite direction, acting on different bodies.', ], }, { title: 'Lecture 7: Momentum and impulse', lines: [ 'Momentum p = m v. The second law in its general form: F = dp/dt.', '', 'Impulse. The change in momentum equals the integral of force over time;', 'a large force over a short time and a small force over a long time can', 'deliver the same impulse.', '', 'In an isolated system the total momentum is conserved, which is what', 'makes collision problems tractable.', ], }, ]; async function makePdfBytes(header: string, pages: PageSpec[]): Promise { const pdf = await PDFDocument.create(); const font = await pdf.embedFont(StandardFonts.Helvetica); const bold = await pdf.embedFont(StandardFonts.HelveticaBold); for (const spec of pages) { const page = pdf.addPage([595, 842]); page.drawText(header, { x: 60, y: 786, size: 10, font }); page.drawText(spec.title, { x: 60, y: 756, size: 16, font: bold }); spec.lines.forEach((line, i) => { if (line) page.drawText(line, { x: 60, y: 712 - i * 22, size: 11, font }); }); } return Buffer.from(await pdf.save()); } // A highlight box over lines [from, to] (0-based, inclusive) of the handout // grid, in the top-left-normalized coordinates annotations use. function lineBox(from: number, to: number, width = 0.8) { const topPdfY = 712 - 22 * from + 14; return { x: 60 / 595 - 0.01, y: (842 - topPdfY) / 842, width, height: (22 * (to - from + 1)) / 842, }; } export interface SeedBlobSpec { hash: string; bytes: Buffer; mime: string; } export interface SeedDocumentSpec { id: string; originalName: string; pageCount: number; extractedText: string; contentHash: string; textHash: string; pdf: Buffer; } export interface SeedContent { workspace: LoroDoc; attempts: LoroDoc; /** Annotation docs keyed by their sync doc id (ann:). */ annDocs: Map; blobs: SeedBlobSpec[]; documents: SeedDocumentSpec[]; courseCount: number; } function seedDoc(): LoroDoc { const doc = new LoroDoc(); doc.setPeerId(SEED_PEER_ID as `${number}`); doc.setRecordTimestamp(true); return doc; } function addAnnotation( doc: LoroDoc, spec: { page: number; type: 'highlight' | 'drawing' | 'note'; color: string; data: Record; }, ): void { const entry = doc.getMap('annotations').setContainer(randomUUID(), new LoroMap()); entry.set('page', spec.page); entry.set('type', spec.type); entry.set('color', spec.color); entry.set('data', spec.data); entry.set('created_at', now()); doc.commit({ message: `annotation.add:${spec.type}@${spec.page}` }); } const slideRef = (docId: string, page: number, label: string): string => `${label}`; const mention = (entryId: string, term: string): string => `@${term}`; export async function buildSeedContent(): Promise { const workspace = seedDoc(); const attempts = seedDoc(); const courseOrder = workspace.getMovableList('course_order'); const layout = workspace.getMap('layout'); const courseIds = new Map(); const topicIds = new Map(); // "code/topic" -> id for (const c of courses) { const courseId = randomUUID(); courseIds.set(c.code, courseId); setEntity(workspace, 'courses', courseId, { code: c.code, name: c.name, exam_date: c.exam_date, created_at: now(), }); courseOrder.push(courseId); const courseLayout = layout.setContainer(courseId, new LoroMap()); const topicOrder = childList(courseLayout, 'topic_order'); // One tagged change per entity so history reads "Added the course X", // "Added the chapter Y" instead of a single untagged "Made a change". workspace.commit({ message: `course.add:${c.name}` }); for (const name of c.topics) { const topicId = randomUUID(); topicIds.set(`${c.code}/${name}`, topicId); setEntity(workspace, 'topics', topicId, { course_id: courseId, name }); topicOrder.push(topicId); workspace.commit({ message: `topic.add:${name}` }); } } // --- the two annotated handouts --- const calcPdf = await makePdfBytes('18.01 Single Variable Calculus', CALC_PAGES); const mechPdf = await makePdfBytes('8.01 Classical Mechanics', MECH_PAGES); const calcText = CALC_PAGES.map((p) => [p.title, ...p.lines].join(' ')).join(' '); const mechText = MECH_PAGES.map((p) => [p.title, ...p.lines].join(' ')).join(' '); const documents: SeedDocumentSpec[] = [ { id: randomUUID(), originalName: 'Calculus - lecture notes.pdf', pageCount: CALC_PAGES.length, extractedText: calcText, contentHash: sha256(calcPdf), textHash: sha256(Buffer.from(calcText, 'utf8')), pdf: calcPdf, }, { id: randomUUID(), originalName: 'Mechanics - lecture notes.pdf', pageCount: MECH_PAGES.length, extractedText: mechText, contentHash: sha256(mechPdf), textHash: sha256(Buffer.from(mechText, 'utf8')), pdf: mechPdf, }, ]; const [calcDoc, mechDoc] = documents; const blobs: SeedBlobSpec[] = [ { hash: calcDoc.contentHash, bytes: calcPdf, mime: 'application/pdf' }, { hash: mechDoc.contentHash, bytes: mechPdf, mime: 'application/pdf' }, { hash: calcDoc.textHash, bytes: Buffer.from(calcText, 'utf8'), mime: 'text/plain; charset=utf-8', }, { hash: mechDoc.textHash, bytes: Buffer.from(mechText, 'utf8'), mime: 'text/plain; charset=utf-8', }, ]; const placeDocument = (doc: SeedDocumentSpec, code: string, topic: string) => { const courseId = courseIds.get(code)!; const topicId = topicIds.get(`${code}/${topic}`)!; setEntity(workspace, 'documents', doc.id, { course_id: courseId, topic_id: topicId, original_name: doc.originalName, page_count: doc.pageCount, uploaded_at: now(), has_preview: false, content_hash: doc.contentHash, render_hash: null, text_hash: doc.textHash, }); const courseLayout = layout.get(courseId) as LoroMap; childList(courseLayout, `items:${topicId}`).push(`doc:${doc.id}`); workspace.commit({ message: `document.add:${doc.originalName}` }); }; placeDocument(calcDoc, '18.01', 'Differentiation'); placeDocument(mechDoc, '8.01', 'Kinematics'); const addLink = (code: string, topic: string, title: string, url: string) => { const courseId = courseIds.get(code)!; const topicId = topicIds.get(`${code}/${topic}`)!; const linkId = randomUUID(); setEntity(workspace, 'links', linkId, { course_id: courseId, topic_id: topicId, title, url, created_at: now(), }); const courseLayout = layout.get(courseId) as LoroMap; childList(courseLayout, `items:${topicId}`).push(`link:${linkId}`); workspace.commit({ message: `link.add:${title}` }); }; addLink( '18.01', 'Differentiation', 'Lecture videos (MIT OpenCourseWare)', 'https://ocw.mit.edu/courses/18-01sc-single-variable-calculus-fall-2010/', ); addLink( '18.01', 'Techniques of Integration', "Paul's Online Notes: integration techniques", 'https://tutorial.math.lamar.edu/classes/calcii/inttechintro.aspx', ); addLink( '8.01', 'Kinematics', 'Lecture videos (MIT OpenCourseWare)', 'https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/', ); addLink( '6.006', 'Graphs', 'Course site (MIT OpenCourseWare)', 'https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/', ); // --- lexicon entries, tagged with their course and linked to slides --- const addLexicon = ( term: string, definitionMd: string, code: string, link: { doc: SeedDocumentSpec; page: number }, ): string => { const id = randomUUID(); const created = now(); setEntity(workspace, 'lexicon', id, { term, definition_md: definitionMd, created_at: created, updated_at: created, }); const entry = childMap(workspace.getMap('lexicon'), id); childMap(entry, 'courses').set(courseIds.get(code)!, true); childMap(entry, 'links'); workspace.commit({ message: `lexicon.add:${term}` }); childMap(entry, 'links').set(randomUUID(), { document_id: link.doc.id, page: link.page, }); workspace.commit({ message: `lexicon.link_add:${term}` }); return id; }; const limitEntry = addLexicon( 'Limit', 'The value a function approaches as its input approaches a point. The whole course stands on this definition: derivatives and integrals are both limits.', '18.01', { doc: calcDoc, page: 1 }, ); addLexicon( 'Derivative', 'The instantaneous rate of change of a function: the slope of the tangent line, defined as the limit of the difference quotient.', '18.01', { doc: calcDoc, page: 2 }, ); addLexicon( 'Fundamental theorem of calculus', 'Differentiation and integration are inverse operations. Part 1 differentiates the area function back to the integrand; part 2 evaluates integrals from any antiderivative.', '18.01', { doc: calcDoc, page: 5 }, ); const momentumEntry = addLexicon( 'Momentum', "Mass times velocity, p = mv. Newton's second law in its general form is F = dp/dt, and total momentum is conserved in isolated systems.", '8.01', { doc: mechDoc, page: 3 }, ); // --- annotations: a workspace that looks studied in, not empty --- const annDocs = new Map(); const calcAnn = seedDoc(); annDocs.set(`ann:${calcDoc.id}`, calcAnn); // The squeeze theorem statement, highlighted. addAnnotation(calcAnn, { page: 1, type: 'highlight', color: '#f2c14e', data: lineBox(7, 8), }); // A note in the margin of the (sin x)/x example, cross-linking the lexicon // and the derivative page. addAnnotation(calcAnn, { page: 1, type: 'note', color: '#6c8cff', data: { x: 0.7, y: 0.62, html: `

Classic exam question. Uses the ${mention(limitEntry, 'Limit')} definition; compare with the difference quotient on ${slideRef(calcDoc.id, 2, 'page 2')}.

`, }, }); // The power rule, highlighted, with a freehand underline beneath the examples. addAnnotation(calcAnn, { page: 2, type: 'highlight', color: '#f2c14e', data: lineBox(6, 7), }); addAnnotation(calcAnn, { page: 2, type: 'drawing', color: '#e0526f', data: { points: Array.from({ length: 9 }, (_, i) => ({ x: 0.1 + i * 0.05, y: 0.315 + (i % 2 ? 0.004 : -0.004), })), }, }); // The integral definition and the FTC, marked for revision. addAnnotation(calcAnn, { page: 4, type: 'highlight', color: '#8fd18a', data: lineBox(0, 2), }); addAnnotation(calcAnn, { page: 5, type: 'note', color: '#6c8cff', data: { x: 0.7, y: 0.3, html: '

Both parts come up every year. Part 2 is the one used for computations.

', }, }); const mechAnn = seedDoc(); annDocs.set(`ann:${mechDoc.id}`, mechAnn); addAnnotation(mechAnn, { page: 2, type: 'highlight', color: '#f2c14e', data: lineBox(2, 3), }); addAnnotation(mechAnn, { page: 3, type: 'note', color: '#6c8cff', data: { x: 0.7, y: 0.25, html: `

${mention(momentumEntry, 'Momentum')} conservation solves most collision problems without knowing the forces.

`, }, }); // --- exercises and a week of practice attempts --- const addExercise = ( doc: SeedDocumentSpec, code: string, topic: string, row: Record, ): string => { const id = randomUUID(); setEntity(workspace, 'exercises', id, { document_id: doc.id, course_id: courseIds.get(code)!, topic_id: topicIds.get(`${code}/${topic}`)!, source: 'seed', created_at: now(), ...row, }); workspace.commit({ message: 'exercise.add' }); return id; }; const calcExercises = [ addExercise(calcDoc, '18.01', 'Differentiation', { type: 'mcq', question: 'The derivative of f(x) = x^2 is:', options: JSON.stringify(['2x', 'x', 'x^2', '2']), correct_answer: '2x', explanation: 'Apply the power rule: d/dx x^n = n x^(n-1).', difficulty: 'easy', }), addExercise(calcDoc, '18.01', 'Differentiation', { type: 'mcq', question: 'The limit of (sin x)/x as x approaches 0 is:', options: JSON.stringify(['1', '0', 'infinity', 'undefined']), correct_answer: '1', explanation: 'A classic limit, provable with the squeeze theorem.', difficulty: 'easy', }), addExercise(calcDoc, '18.01', 'Differentiation', { type: 'true_false', question: 'Every differentiable function is continuous.', options: null, correct_answer: 'true', explanation: 'Differentiability implies continuity; the converse fails.', difficulty: 'medium', }), addExercise(calcDoc, '18.01', 'Differentiation', { type: 'open', question: 'State the definition of the derivative of f at a point a.', correct_answer: "f'(a) is the limit of (f(a+h) - f(a)) / h as h approaches 0.", explanation: 'The difference quotient definition.', options: null, difficulty: 'medium', }), addExercise(calcDoc, '18.01', 'The Definite Integral', { type: 'mcq', question: 'By the fundamental theorem, the integral of f from a to b equals:', options: JSON.stringify(['F(b) - F(a)', 'F(a) - F(b)', "F'(b) - F'(a)", 'F(b) + F(a)']), correct_answer: 'F(b) - F(a)', explanation: 'Part 2 of the FTC, with F any antiderivative of f.', difficulty: 'medium', }), ]; const mechExercises = [ addExercise(mechDoc, '8.01', "Newton's Laws of Motion", { type: 'mcq', question: "Newton's second law, in its general form, states:", options: JSON.stringify(['F = dp/dt', 'F = mv', 'F = m/a', 'p = ma']), correct_answer: 'F = dp/dt', explanation: 'F = ma is the constant-mass special case.', difficulty: 'medium', }), addExercise(mechDoc, '8.01', 'Momentum and Impulse', { type: 'true_false', question: 'In an isolated system the total momentum is conserved.', options: null, correct_answer: 'true', explanation: 'No external force means dp/dt = 0 for the system.', difficulty: 'easy', }), ]; // A believable practice history: a rough first day, steady improvement. const practice: { exercise: string; answer: string; correct: boolean; age: number }[] = [ { exercise: calcExercises[0], answer: 'x', correct: false, age: 6 }, { exercise: calcExercises[1], answer: '0', correct: false, age: 6 }, { exercise: calcExercises[0], answer: '2x', correct: true, age: 5 }, { exercise: calcExercises[2], answer: 'true', correct: true, age: 4 }, { exercise: calcExercises[1], answer: '1', correct: true, age: 3 }, { exercise: calcExercises[4], answer: 'F(b) - F(a)', correct: true, age: 2 }, { exercise: mechExercises[0], answer: 'F = mv', correct: false, age: 2 }, { exercise: mechExercises[0], answer: 'F = dp/dt', correct: true, age: 1 }, { exercise: mechExercises[1], answer: 'true', correct: true, age: 0 }, ]; for (const p of practice) { const attemptId = randomUUID(); attempts.getMap('attempts').set(attemptId, { attempt_id: attemptId, exercise_id: p.exercise, user_answer: p.answer, is_correct: p.correct, mode: 'practice', answered_at: daysAgo(p.age), }); attempts.commit({ message: 'exercise.attempt' }); } return { workspace, attempts, annDocs, blobs, documents, courseCount: courses.length }; }