@nitrimandylis/leftonread 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -2
  3. package/dist/lor.js +2185 -0
  4. package/man/lor.1 +126 -0
  5. package/package.json +47 -4
package/dist/lor.js ADDED
@@ -0,0 +1,2185 @@
1
+ #!/usr/bin/env node
2
+
3
+ // leftonread.ts
4
+ import { parseArgs } from "node:util";
5
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, realpathSync, writeFileSync } from "node:fs";
6
+ import { spawn } from "node:child_process";
7
+ import { dirname as dirname2, join as join3, resolve as resolve2 } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ // ingest.ts
11
+ import { DatabaseSync } from "node:sqlite";
12
+ import { spawnSync } from "node:child_process";
13
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
14
+ import { basename, dirname, join, resolve } from "node:path";
15
+ import { homedir, tmpdir } from "node:os";
16
+ var DATA_DIR = join(homedir(), ".config", "leftonread");
17
+ var DEFAULT_DB = join(DATA_DIR, "data.db");
18
+ var SCHEMA = `
19
+ CREATE TABLE IF NOT EXISTS chats (
20
+ id TEXT PRIMARY KEY,
21
+ title TEXT NOT NULL,
22
+ is_group INTEGER NOT NULL,
23
+ participants TEXT NOT NULL
24
+ );
25
+ CREATE TABLE IF NOT EXISTS messages (
26
+ id INTEGER PRIMARY KEY,
27
+ chat_id TEXT NOT NULL,
28
+ sender TEXT NOT NULL,
29
+ ts INTEGER NOT NULL,
30
+ content TEXT NOT NULL,
31
+ kind TEXT NOT NULL,
32
+ link TEXT,
33
+ caption TEXT,
34
+ creator TEXT,
35
+ reel TEXT,
36
+ UNIQUE (chat_id, ts, sender, content)
37
+ );
38
+ CREATE INDEX IF NOT EXISTS messages_chat_ts ON messages (chat_id, ts);
39
+ CREATE TABLE IF NOT EXISTS reactions (
40
+ message_id INTEGER NOT NULL,
41
+ actor TEXT NOT NULL,
42
+ emoji TEXT NOT NULL
43
+ );
44
+ CREATE INDEX IF NOT EXISTS reactions_message ON reactions (message_id);
45
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
46
+ CREATE TABLE IF NOT EXISTS saved (code TEXT PRIMARY KEY, link TEXT NOT NULL, creator TEXT, ts INTEGER NOT NULL);
47
+ CREATE TABLE IF NOT EXISTS captions (code TEXT PRIMARY KEY, caption TEXT NOT NULL, ok INTEGER NOT NULL);
48
+ CREATE TABLE IF NOT EXISTS categories (code TEXT PRIMARY KEY, category TEXT NOT NULL);
49
+ `;
50
+ function openDb(path) {
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ const db = new DatabaseSync(path);
53
+ db.exec(SCHEMA);
54
+ return db;
55
+ }
56
+ function fixMojibake(s) {
57
+ for (let i = 0;i < s.length; i++) {
58
+ if (s.charCodeAt(i) > 255)
59
+ return s;
60
+ }
61
+ return Buffer.from(s, "latin1").toString("utf8");
62
+ }
63
+ var REEL_RE = /instagram\.com\/reels?\/([A-Za-z0-9_-]+)/;
64
+ var POST_RE = /instagram\.com\/(?:p|reels?|tv)\/([A-Za-z0-9_-]+)/;
65
+ var SYSTEM_RE = /^(Reacted .+ to your message|Liked a message|.+ sent an attachment\.|.+ (changed|named) the group|.+ added .+ to the group|.+ left the group|.+ (started|ended) (a )?(video|audio) chat|.+ missed (a|an) (video|audio) (call|chat))/;
66
+ function reelCode(link) {
67
+ const match = REEL_RE.exec(link);
68
+ return match ? match[1] : null;
69
+ }
70
+ function kindOf(m) {
71
+ if (m.share) {
72
+ if (m.share.link && reelCode(m.share.link))
73
+ return "reel";
74
+ return "share";
75
+ }
76
+ if (m.photos)
77
+ return "photo";
78
+ if (m.videos)
79
+ return "video";
80
+ if (m.audio_files)
81
+ return "audio";
82
+ if (m.call_duration !== undefined)
83
+ return "call";
84
+ const content = m.content ?? "";
85
+ if (content === "")
86
+ return "other";
87
+ if (SYSTEM_RE.test(content))
88
+ return "system";
89
+ return "text";
90
+ }
91
+ function findMessageFiles(root) {
92
+ const found = [];
93
+ const stack = [root];
94
+ while (stack.length > 0) {
95
+ const dir = stack.pop();
96
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
97
+ const full = join(dir, entry.name);
98
+ if (entry.isDirectory())
99
+ stack.push(full);
100
+ else if (entry.isFile() && /^message_\d+\.json$/.test(entry.name) && basename(dirname(dirname(full))) === "inbox") {
101
+ found.push(full);
102
+ }
103
+ }
104
+ }
105
+ return found.sort();
106
+ }
107
+ var MESSAGES_GLOB = "*/messages/inbox/*/message_*.json";
108
+ var SAVED_GLOB = "*/saved/saved_posts.json";
109
+ function extractZip(zip, into, patterns) {
110
+ const isWindows = process.platform === "win32";
111
+ const result = isWindows ? spawnSync("tar", ["-xf", zip, "-C", into, ...patterns], { encoding: "utf8" }) : spawnSync("unzip", ["-qo", zip, ...patterns, "-d", into], { encoding: "utf8" });
112
+ if (result.error) {
113
+ throw new Error(`${isWindows ? "tar" : "unzip"} is needed to read zip files. Install it, or extract the zip and pass the folder.`);
114
+ }
115
+ if (result.status === 11 || isWindows && result.status === 1)
116
+ return false;
117
+ if (result.status !== 0)
118
+ throw new Error(`could not unzip ${zip}: ${result.stderr.trim()}`);
119
+ return true;
120
+ }
121
+ function parseSaved(json) {
122
+ const found = [];
123
+ function walk(node, creator) {
124
+ if (Array.isArray(node)) {
125
+ for (const item of node)
126
+ walk(item, creator);
127
+ return;
128
+ }
129
+ if (node === null || typeof node !== "object")
130
+ return;
131
+ const obj = node;
132
+ const owner = typeof obj.title === "string" && obj.title !== "" ? obj.title : creator;
133
+ if (typeof obj.href === "string" && typeof obj.timestamp === "number") {
134
+ const match = POST_RE.exec(obj.href);
135
+ if (match)
136
+ found.push({ code: match[1], link: obj.href, creator: owner, ts: obj.timestamp * 1000 });
137
+ }
138
+ for (const key in obj)
139
+ walk(obj[key], owner);
140
+ }
141
+ walk(json, null);
142
+ return found;
143
+ }
144
+ function findSavedFiles(root) {
145
+ const found = [];
146
+ const stack = [root];
147
+ while (stack.length > 0) {
148
+ const dir = stack.pop();
149
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
150
+ const full = join(dir, entry.name);
151
+ if (entry.isDirectory())
152
+ stack.push(full);
153
+ else if (entry.isFile() && entry.name === "saved_posts.json" && basename(dir) === "saved")
154
+ found.push(full);
155
+ }
156
+ }
157
+ return found;
158
+ }
159
+ function ingest(inputs, dbPath) {
160
+ const temp = mkdtempSync(join(tmpdir(), "leftonread-"));
161
+ const db = openDb(dbPath);
162
+ try {
163
+ const files = [];
164
+ const savedFiles = [];
165
+ for (const input of inputs) {
166
+ let stat;
167
+ try {
168
+ stat = statSync(input);
169
+ } catch {
170
+ throw new Error(`no such file or folder: ${input}`);
171
+ }
172
+ let root = input;
173
+ if (!stat.isDirectory()) {
174
+ root = join(temp, String(files.length) + "-" + basename(input));
175
+ mkdirSync(root);
176
+ extractZip(input, root, [MESSAGES_GLOB]);
177
+ extractZip(input, root, [SAVED_GLOB]);
178
+ }
179
+ files.push(...findMessageFiles(root));
180
+ savedFiles.push(...findSavedFiles(root));
181
+ }
182
+ if (files.length === 0) {
183
+ throw new Error("found no messages/inbox/*/message_N.json files. Request the export with Messages ticked, in JSON format.");
184
+ }
185
+ const insertChat = db.prepare("INSERT INTO chats (id, title, is_group, participants) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET title = excluded.title, is_group = excluded.is_group, participants = excluded.participants");
186
+ const insertMessage = db.prepare("INSERT OR IGNORE INTO messages (chat_id, sender, ts, content, kind, link, caption, creator, reel) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
187
+ const insertReaction = db.prepare("INSERT INTO reactions (message_id, actor, emoji) VALUES (?, ?, ?)");
188
+ let added = 0;
189
+ db.exec("BEGIN");
190
+ for (const file of files) {
191
+ const text = readFileSync(file, "utf8");
192
+ const thread = JSON.parse(text, (_key, value) => typeof value === "string" ? fixMojibake(value) : value);
193
+ const chatId = basename(dirname(file));
194
+ const participants = (thread.participants ?? []).map((p) => p.name);
195
+ insertChat.run(chatId, thread.title ?? chatId, participants.length > 2 ? 1 : 0, JSON.stringify(participants));
196
+ for (const m of thread.messages ?? []) {
197
+ if (!m.sender_name || !m.timestamp_ms)
198
+ continue;
199
+ const link = m.share?.link ?? m.photos?.[0]?.uri ?? null;
200
+ const result = insertMessage.run(chatId, m.sender_name, m.timestamp_ms, m.content ?? "", kindOf(m), link, m.share?.share_text ?? null, m.share?.original_content_owner ?? null, m.share?.link ? reelCode(m.share.link) : null);
201
+ if (result.changes === 0)
202
+ continue;
203
+ added++;
204
+ for (const r of m.reactions ?? []) {
205
+ insertReaction.run(result.lastInsertRowid, r.actor, r.reaction);
206
+ }
207
+ }
208
+ }
209
+ const insertSaved = db.prepare("INSERT OR IGNORE INTO saved (code, link, creator, ts) VALUES (?, ?, ?, ?)");
210
+ for (const file of savedFiles) {
211
+ const json = JSON.parse(readFileSync(file, "utf8"), (_key, value) => typeof value === "string" ? fixMojibake(value) : value);
212
+ for (const post of parseSaved(json))
213
+ insertSaved.run(post.code, post.link, post.creator, post.ts);
214
+ }
215
+ const sources = new Set(getSources(db));
216
+ for (const input of inputs)
217
+ sources.add(resolve(input));
218
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('sources', ?)").run(JSON.stringify([...sources]));
219
+ db.exec("COMMIT");
220
+ const owner = detectOwner(db);
221
+ if (owner)
222
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('owner', ?)").run(owner);
223
+ const count = (sql) => db.prepare(sql).get().n;
224
+ return {
225
+ db: dbPath,
226
+ files: files.length,
227
+ chats: count("SELECT COUNT(*) AS n FROM chats"),
228
+ messages: count("SELECT COUNT(*) AS n FROM messages"),
229
+ added,
230
+ reels: count("SELECT COUNT(*) AS n FROM messages WHERE kind = 'reel'"),
231
+ saved: count("SELECT COUNT(*) AS n FROM saved"),
232
+ owner
233
+ };
234
+ } catch (error) {
235
+ if (db.isTransaction)
236
+ db.exec("ROLLBACK");
237
+ throw error;
238
+ } finally {
239
+ db.close();
240
+ rmSync(temp, { recursive: true, force: true });
241
+ }
242
+ }
243
+ function detectOwner(db) {
244
+ const fromAttachments = db.prepare("SELECT sender, COUNT(*) AS n FROM messages WHERE content = 'You sent an attachment.' GROUP BY sender ORDER BY n DESC LIMIT 1").get();
245
+ if (fromAttachments)
246
+ return fromAttachments.sender;
247
+ const seen = new Map;
248
+ for (const row of db.prepare("SELECT participants FROM chats").all()) {
249
+ for (const name of JSON.parse(row.participants)) {
250
+ seen.set(name, (seen.get(name) ?? 0) + 1);
251
+ }
252
+ }
253
+ let best = null;
254
+ let bestCount = 0;
255
+ for (const [name, n] of seen) {
256
+ if (n > bestCount) {
257
+ best = name;
258
+ bestCount = n;
259
+ }
260
+ }
261
+ return best;
262
+ }
263
+ function getOwner(db) {
264
+ const row = db.prepare("SELECT value FROM meta WHERE key = 'owner'").get();
265
+ if (!row)
266
+ throw new Error("could not tell whose export this is. Run ingest again.");
267
+ return row.value;
268
+ }
269
+ function getSources(db) {
270
+ const row = db.prepare("SELECT value FROM meta WHERE key = 'sources'").get();
271
+ return row ? JSON.parse(row.value) : [];
272
+ }
273
+
274
+ // page.ts
275
+ function firstName(name) {
276
+ return name.trim().split(/\s+/)[0] || name;
277
+ }
278
+ var EMBED_SCRIPT = String.raw`
279
+ let embedScript = null;
280
+ function processEmbeds() {
281
+ if (window.instgrm) window.instgrm.Embeds.process();
282
+ else if (!embedScript) {
283
+ embedScript = document.createElement("script");
284
+ embedScript.src = "https://www.instagram.com/embed.js";
285
+ embedScript.async = true;
286
+ document.body.append(embedScript);
287
+ }
288
+ }
289
+
290
+ // Instagram's iframes are heavy, so each embed loads only when its card scrolls into view.
291
+ const embedObserver = new IntersectionObserver((entries) => {
292
+ for (const entry of entries) {
293
+ if (!entry.isIntersecting) continue;
294
+ embedObserver.unobserve(entry.target);
295
+ const quote = document.createElement("blockquote");
296
+ quote.className = "instagram-media";
297
+ quote.setAttribute("data-instgrm-permalink", entry.target.dataset.link);
298
+ quote.setAttribute("data-instgrm-version", "14");
299
+ const link = el("a", "", "View on Instagram");
300
+ link.href = entry.target.dataset.link;
301
+ link.target = "_blank";
302
+ quote.append(link);
303
+ entry.target.append(quote);
304
+ processEmbeds();
305
+ }
306
+ }, { rootMargin: "400px" });
307
+
308
+ `;
309
+ function inlineJson(data) {
310
+ return JSON.stringify(data).replace(/</g, "\\u003c");
311
+ }
312
+ function page(title, css, data, script, body) {
313
+ return `<!doctype html>
314
+ <html lang="en">
315
+ <head>
316
+ <meta charset="utf-8">
317
+ <meta name="viewport" content="width=device-width, initial-scale=1">
318
+ <title>${title}</title>
319
+ <style>
320
+ /* Paper and ink, one loud colour for "them". Headings in Futura, reading text in Georgia, nothing under 15px. */
321
+ :root { --bg: #f4efe6; --ink: #141414; --muted: #6b665c; --line: #d6cfc0; --them: #ff3d7f; --display: Futura, "Century Gothic", "Trebuchet MS", "Helvetica Neue", Arial, sans-serif; }
322
+ @media (prefers-color-scheme: dark) {
323
+ :root { --bg: #141414; --ink: #f4efe6; --muted: #a39d90; --line: #3a3833; --them: #c8f03c; }
324
+ }
325
+ * { box-sizing: border-box; }
326
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 18px/1.5 Georgia, "Times New Roman", serif; }
327
+ a { color: inherit; }
328
+ main { max-width: 1100px; margin: 0 auto; padding: 40px 20px 96px; }
329
+ h1 { font: 700 clamp(44px, 7vw, 84px)/1 var(--display); letter-spacing: -0.02em; margin: 14px 0 10px; }
330
+ h2, h3 { font-family: var(--display); }
331
+ button { font: 700 15px/1 var(--display); letter-spacing: 0.06em; text-transform: uppercase; padding: 12px 16px; border: 2px solid var(--ink); border-radius: 0; background: transparent; color: var(--ink); cursor: pointer; }
332
+ button:hover { background: var(--ink); color: var(--bg); }
333
+ .muted { color: var(--muted); }
334
+ ${css}
335
+ </style>
336
+ </head>
337
+ <body>
338
+ ${body}
339
+ <script id="data" type="application/json">${inlineJson(data)}</script>
340
+ <script>
341
+ const DATA = JSON.parse(document.getElementById("data").textContent);
342
+ function el(tag, cls, text) {
343
+ const node = document.createElement(tag);
344
+ if (cls) node.className = cls;
345
+ if (text !== undefined) node.textContent = text;
346
+ return node;
347
+ }
348
+ ${script}
349
+ </script>
350
+ </body>
351
+ </html>
352
+ `;
353
+ }
354
+
355
+ // wrapped.ts
356
+ var HOUR = 60 * 60 * 1000;
357
+ var CONVERSATION_GAP = 6 * HOUR;
358
+ var SPOKEN = new Set(["text", "reel", "share", "photo", "video", "audio", "call"]);
359
+ function pad(n) {
360
+ return n < 10 ? "0" + n : String(n);
361
+ }
362
+ function dayKey(ts) {
363
+ const d = new Date(ts);
364
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
365
+ }
366
+ function nextDayKey(key) {
367
+ const [y, m, d] = key.split("-").map(Number);
368
+ return dayKey(new Date(y, m - 1, d + 1).getTime());
369
+ }
370
+ function median(values) {
371
+ if (values.length === 0)
372
+ return null;
373
+ const sorted = [...values].sort((a, b) => a - b);
374
+ const mid = Math.floor(sorted.length / 2);
375
+ return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
376
+ }
377
+ function longestStreak(timestamps) {
378
+ const days = [...new Set(timestamps.map(dayKey))].sort();
379
+ if (days.length === 0)
380
+ return { days: 0, from: null, to: null };
381
+ let best = { days: 1, from: days[0], to: days[0] };
382
+ let runStart = days[0];
383
+ let runLength = 1;
384
+ for (let i = 1;i < days.length; i++) {
385
+ if (nextDayKey(days[i - 1]) === days[i]) {
386
+ runLength++;
387
+ } else {
388
+ runStart = days[i];
389
+ runLength = 1;
390
+ }
391
+ if (runLength > best.days)
392
+ best = { days: runLength, from: runStart, to: days[i] };
393
+ }
394
+ return best;
395
+ }
396
+ function topEmoji(emojis) {
397
+ const counts = new Map;
398
+ for (const e of emojis)
399
+ counts.set(e, (counts.get(e) ?? 0) + 1);
400
+ let best = null;
401
+ for (const [e, n] of counts) {
402
+ if (best === null || n > counts.get(best))
403
+ best = e;
404
+ }
405
+ return best;
406
+ }
407
+ function tokenize(text) {
408
+ const words = text.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? [];
409
+ return words.filter((w) => w.length >= 3 && !/^\d+$/.test(w));
410
+ }
411
+ function chatStats(id, them, isGroup, owner, label, messages, reactions, words) {
412
+ const side = (sender) => sender === owner ? "me" : "them";
413
+ const spoken = messages.filter((m) => SPOKEN.has(m.kind));
414
+ const members = new Map;
415
+ const member = (sender) => {
416
+ if (!members.has(sender))
417
+ members.set(sender, { name: label(sender), sent: 0, starts: 0, reels: 0, reactions: 0, emoji: null });
418
+ return members.get(sender);
419
+ };
420
+ let opener = null;
421
+ const sent = { me: 0, them: 0 };
422
+ const starts = { me: 0, them: 0 };
423
+ const reels = { me: 0, them: 0 };
424
+ const lags = { me: [], them: [] };
425
+ const hours = new Array(24).fill(0);
426
+ const months = new Map;
427
+ for (let i = 0;i < spoken.length; i++) {
428
+ const m = spoken[i];
429
+ const who = side(m.sender);
430
+ sent[who]++;
431
+ member(m.sender).sent++;
432
+ if (m.kind === "reel") {
433
+ reels[who]++;
434
+ member(m.sender).reels++;
435
+ }
436
+ hours[new Date(m.ts).getHours()]++;
437
+ const month = dayKey(m.ts).slice(0, 7);
438
+ if (!months.has(month))
439
+ months.set(month, { month, me: 0, them: 0 });
440
+ months.get(month)[who]++;
441
+ const previous = spoken[i - 1];
442
+ if (!previous || m.ts - previous.ts >= CONVERSATION_GAP) {
443
+ starts[who]++;
444
+ member(m.sender).starts++;
445
+ opener = m;
446
+ } else if (opener && side(opener.sender) !== who) {
447
+ lags[who].push((m.ts - opener.ts) / 60000);
448
+ opener = null;
449
+ }
450
+ }
451
+ const emojisBy = new Map;
452
+ for (const r of reactions) {
453
+ member(r.actor).reactions++;
454
+ if (!emojisBy.has(r.actor))
455
+ emojisBy.set(r.actor, []);
456
+ emojisBy.get(r.actor).push(r.emoji);
457
+ }
458
+ for (const [actor, emojis] of emojisBy)
459
+ member(actor).emoji = topEmoji(emojis);
460
+ const peakHour = hours.indexOf(Math.max(...hours));
461
+ const round = (n) => n === null ? null : Math.round(n * 10) / 10;
462
+ const mine = reactions.filter((r) => r.actor === owner).map((r) => r.emoji);
463
+ const theirs = reactions.filter((r) => r.actor !== owner).map((r) => r.emoji);
464
+ return {
465
+ id,
466
+ them,
467
+ isGroup,
468
+ members: [...members.values()].sort((a, b) => b.sent - a.sent),
469
+ since: spoken.length ? dayKey(spoken[0].ts) : "",
470
+ until: spoken.length ? dayKey(spoken[spoken.length - 1].ts) : "",
471
+ total: spoken.length,
472
+ sent,
473
+ starts,
474
+ replyMinutes: { me: round(median(lags.me)), them: round(median(lags.them)) },
475
+ peakHour,
476
+ hours,
477
+ months: [...months.values()],
478
+ streak: longestStreak(spoken.map((m) => m.ts)),
479
+ words,
480
+ reels,
481
+ reactions: {
482
+ me: { count: mine.length, top: topEmoji(mine) },
483
+ them: { count: theirs.length, top: topEmoji(theirs) }
484
+ }
485
+ };
486
+ }
487
+ function wordsOnlyHere(textByChat) {
488
+ const perChat = new Map;
489
+ const global = new Map;
490
+ for (const [chat, texts] of textByChat) {
491
+ const counts = new Map;
492
+ for (const text of texts) {
493
+ for (const word of tokenize(text)) {
494
+ counts.set(word, (counts.get(word) ?? 0) + 1);
495
+ global.set(word, (global.get(word) ?? 0) + 1);
496
+ }
497
+ }
498
+ perChat.set(chat, counts);
499
+ }
500
+ const result = new Map;
501
+ for (const [chat, counts] of perChat) {
502
+ const words = [];
503
+ for (const [word, count] of counts) {
504
+ const elsewhere = global.get(word) - count;
505
+ if (count >= 5 && elsewhere <= 2)
506
+ words.push({ word, count });
507
+ }
508
+ words.sort((a, b) => b.count - a.count);
509
+ result.set(chat, words.slice(0, 8));
510
+ }
511
+ return result;
512
+ }
513
+ function buildWrapped(db, anon) {
514
+ const owner = getOwner(db);
515
+ const chats = db.prepare("SELECT id, title, is_group, participants FROM chats").all();
516
+ const messages = db.prepare("SELECT chat_id, sender, ts, content, kind FROM messages ORDER BY chat_id, ts").all();
517
+ const reactions = db.prepare("SELECT m.chat_id AS chat_id, r.actor AS actor, r.emoji AS emoji FROM reactions r JOIN messages m ON m.id = r.message_id").all();
518
+ const byChat = new Map;
519
+ const textByChat = new Map;
520
+ for (const m of messages) {
521
+ if (!byChat.has(m.chat_id)) {
522
+ byChat.set(m.chat_id, []);
523
+ textByChat.set(m.chat_id, []);
524
+ }
525
+ byChat.get(m.chat_id).push(m);
526
+ if (m.kind === "text")
527
+ textByChat.get(m.chat_id).push(m.content);
528
+ }
529
+ const reactionsByChat = new Map;
530
+ for (const r of reactions) {
531
+ if (!reactionsByChat.has(r.chat_id))
532
+ reactionsByChat.set(r.chat_id, []);
533
+ reactionsByChat.get(r.chat_id).push(r);
534
+ }
535
+ const words = wordsOnlyHere(textByChat);
536
+ const overview = { messages: 0, chats: chats.length, reelsSent: 0, reelsReceived: 0, list: [] };
537
+ const stats = [];
538
+ let anonNumber = 0;
539
+ for (const chat of chats) {
540
+ const chatMessages = byChat.get(chat.id) ?? [];
541
+ const spoken = chatMessages.filter((m) => SPOKEN.has(m.kind));
542
+ overview.messages += spoken.length;
543
+ for (const m of spoken) {
544
+ if (m.kind !== "reel")
545
+ continue;
546
+ if (m.sender === owner)
547
+ overview.reelsSent++;
548
+ else
549
+ overview.reelsReceived++;
550
+ }
551
+ if (spoken.length === 0)
552
+ continue;
553
+ anonNumber++;
554
+ const isGroup = chat.is_group === 1;
555
+ const other = JSON.parse(chat.participants).find((name) => name !== owner) ?? chat.title;
556
+ let title = isGroup ? chat.title : firstName(other);
557
+ if (anon)
558
+ title = isGroup ? `group ${anonNumber}` : `chat ${anonNumber}`;
559
+ const mine = spoken.filter((m) => m.sender === owner).length;
560
+ overview.list.push({ id: chat.id, title, isGroup, total: spoken.length, mine });
561
+ const labels = new Map;
562
+ const label = (sender) => {
563
+ if (sender === owner)
564
+ return "you";
565
+ if (!labels.has(sender)) {
566
+ const stand = isGroup ? `person ${labels.size + 1}` : "them";
567
+ labels.set(sender, anon ? stand : firstName(sender));
568
+ }
569
+ return labels.get(sender);
570
+ };
571
+ const them = isGroup ? title : label(other);
572
+ stats.push(chatStats(chat.id, them, isGroup, owner, label, chatMessages, reactionsByChat.get(chat.id) ?? [], words.get(chat.id) ?? []));
573
+ }
574
+ overview.list.sort((a, b) => b.total - a.total);
575
+ stats.sort((a, b) => b.total - a.total);
576
+ return { overview, chats: stats };
577
+ }
578
+ var CSS = `
579
+ .lede { font-size: 22px; max-width: 34em; margin: 12px 0 40px; }
580
+ .chatlist { list-style: none; padding: 0; margin: 0; }
581
+ .chatlist li { display: grid; grid-template-columns: 1fr auto; align-items: baseline; gap: 8px 16px; padding: 18px 0; border-top: 2px solid var(--ink); }
582
+ .chatlist .name { font: 700 30px/1.1 var(--display); text-decoration: none; }
583
+ .chatlist a.name:hover { text-decoration: underline; text-decoration-thickness: 3px; }
584
+ .chatlist .n { font: 700 20px var(--display); }
585
+ .chatlist .bar { grid-column: 1 / -1; height: 22px; display: flex; background: var(--them); }
586
+ .chatlist .bar span { background: var(--ink); }
587
+ .key { display: flex; gap: 24px; margin: 0 0 14px; font-size: 16px; }
588
+ .key i { display: inline-block; width: 16px; height: 16px; margin-right: 8px; vertical-align: -2px; background: var(--ink); }
589
+ .key i.them { background: var(--them); }
590
+ .slides { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 36px 28px; margin-top: 36px; }
591
+ .slides figure { margin: 0; }
592
+ .slides canvas { width: 100%; height: auto; display: block; }
593
+ .slides button { margin-top: 10px; width: 100%; }
594
+ .back { font: 700 16px var(--display); }
595
+ `;
596
+ var SCRIPT = String.raw`
597
+ // Each slide is a poster: one number as big as the slide allows, one sentence, one plain shape.
598
+ // Nothing on a slide is set smaller than 52px, so it still reads at phone size.
599
+ const DISPLAY = 'Futura, "Century Gothic", "Trebuchet MS", "Helvetica Neue", Arial, sans-serif';
600
+ const TEXT = 'Georgia, "Times New Roman", serif';
601
+ const W = 1080, H = 1920, X = 80, MAX = W - 2 * X;
602
+ const INK = "#141414", PAPER = "#f4efe6", PINK = "#ff3d7f", LIME = "#c8f03c", BLUE = "#2a3bff", ORANGE = "#ff7a1a";
603
+ const root = document.getElementById("root");
604
+
605
+ const fmt = (n) => n.toLocaleString("en-US");
606
+ const monthName = (key) => key ? new Date(key + "T12:00").toLocaleDateString("en-US", { month: "short", year: "numeric" }) : "";
607
+ const monthLetter = (key) => new Date(key + "-15T12:00").toLocaleDateString("en-US", { month: "short" }).charAt(0);
608
+ const dayName = (key) => key ? new Date(key + "T12:00").toLocaleDateString("en-US", { day: "numeric", month: "short" }) : "";
609
+ function lag(minutes) {
610
+ if (minutes === null) return "n/a";
611
+ if (minutes < 1) return Math.round(minutes * 60) + " sec";
612
+ if (minutes < 90) return Math.round(minutes) + " min";
613
+ return (Math.round(minutes / 6) / 10) + " h";
614
+ }
615
+
616
+ function display(ctx, size) {
617
+ ctx.font = "700 " + size + "px " + DISPLAY;
618
+ }
619
+ function text(ctx, size) {
620
+ ctx.font = "400 " + size + "px " + TEXT;
621
+ }
622
+
623
+ // Sets the display font at the largest size, up to start, where words fit maxWidth. Returns the size.
624
+ function fit(ctx, words, start, maxWidth) {
625
+ let size = start;
626
+ display(ctx, size);
627
+ while (size > 52 && ctx.measureText(words).width > maxWidth) {
628
+ size -= 4;
629
+ display(ctx, size);
630
+ }
631
+ return size;
632
+ }
633
+
634
+ // Draws a sentence over as many lines as it needs. Returns the y of the next free line.
635
+ function wrap(ctx, sentence, x, y, maxWidth, lineHeight) {
636
+ let line = "";
637
+ for (const word of sentence.split(" ")) {
638
+ const test = line ? line + " " + word : word;
639
+ if (ctx.measureText(test).width > maxWidth && line) {
640
+ ctx.fillText(line, x, y);
641
+ y += lineHeight;
642
+ line = word;
643
+ } else {
644
+ line = test;
645
+ }
646
+ }
647
+ if (line) ctx.fillText(line, x, y);
648
+ return y + lineHeight;
649
+ }
650
+
651
+ // The small capital line that names a slide.
652
+ function kicker(ctx, words) {
653
+ display(ctx, 52);
654
+ ctx.letterSpacing = "5px";
655
+ ctx.fillText(words.toUpperCase(), X, 170);
656
+ ctx.letterSpacing = "0px";
657
+ }
658
+
659
+ function footer(ctx) {
660
+ display(ctx, 52);
661
+ ctx.fillText("leftonread", X, H - 84);
662
+ }
663
+
664
+ // A plain symbol like "❤" draws as a text glyph; adding U+FE0F asks for the colour emoji.
665
+ function colour(emoji) {
666
+ if (emoji.length === 1 && emoji.charCodeAt(0) >= 0x2600 && emoji.charCodeAt(0) <= 0x27bf) return emoji + String.fromCharCode(0xfe0f);
667
+ return emoji;
668
+ }
669
+
670
+ function emojiAt(ctx, emoji, y) {
671
+ if (!emoji) return;
672
+ emoji = colour(emoji);
673
+ ctx.font = "200px " + TEXT;
674
+ ctx.textAlign = "right";
675
+ ctx.fillText(emoji, W - X, y);
676
+ ctx.textAlign = "left";
677
+ }
678
+
679
+ // A slide cut into two fields, theirs on top and yours below. The cut sits where the two
680
+ // numbers meet, so the bigger number owns more of the slide.
681
+ // top and bottom are { ground, ink, label, number, value, emoji }.
682
+ function split(ctx, title, top, bottom, sentence) {
683
+ const total = top.value + bottom.value;
684
+ let share = total > 0 ? top.value / total : 0.5;
685
+ share = Math.max(0.32, Math.min(0.6, share)); // both fields keep room for their number
686
+ const cut = Math.round(H * share);
687
+ const room = MAX - (top.emoji || bottom.emoji ? 260 : 0);
688
+
689
+ ctx.fillStyle = top.ground;
690
+ ctx.fillRect(0, 0, W, cut);
691
+ ctx.fillStyle = top.ink;
692
+ kicker(ctx, title);
693
+ text(ctx, 64);
694
+ ctx.fillText(top.label, X, cut - 350);
695
+ fit(ctx, top.number, 290, room);
696
+ ctx.fillText(top.number, X - 8, cut - 80);
697
+ emojiAt(ctx, top.emoji, cut - 100);
698
+
699
+ ctx.fillStyle = bottom.ground;
700
+ ctx.fillRect(0, cut, W, H - cut);
701
+ ctx.fillStyle = bottom.ink;
702
+ text(ctx, 64);
703
+ ctx.fillText(bottom.label, X, cut + 130);
704
+ fit(ctx, bottom.number, 290, room);
705
+ ctx.fillText(bottom.number, X - 8, cut + 400);
706
+ emojiAt(ctx, bottom.emoji, cut + 380);
707
+ text(ctx, 56);
708
+ wrap(ctx, sentence, X, H - 290, MAX, 70);
709
+ footer(ctx);
710
+ }
711
+
712
+ // A slide with one flat ground and one ink.
713
+ function plain(ctx, ground, ink, title) {
714
+ ctx.fillStyle = ground;
715
+ ctx.fillRect(0, 0, W, H);
716
+ ctx.fillStyle = ink;
717
+ kicker(ctx, title);
718
+ footer(ctx);
719
+ }
720
+
721
+ // A group slide: up to six people ranked by one number, each with a bar. Your row gets the loud colour.
722
+ // rows are { name, value, emoji }, biggest first.
723
+ function board(ctx, ground, ink, loud, title, rows, sentence) {
724
+ plain(ctx, ground, ink, title);
725
+ const most = Math.max(1, rows[0].value);
726
+ rows.forEach((row, i) => {
727
+ const y = 260 + i * 205;
728
+ ctx.fillStyle = ink;
729
+ fit(ctx, row.name, 76, MAX - 400);
730
+ ctx.fillText(row.name, X, y + 70);
731
+ display(ctx, 76);
732
+ ctx.textAlign = "right";
733
+ ctx.fillText(fmt(row.value) + (row.emoji ? " " + colour(row.emoji) : ""), W - X, y + 70);
734
+ ctx.textAlign = "left";
735
+ ctx.fillStyle = row.name === "you" ? loud : ink;
736
+ ctx.fillRect(X, y + 100, Math.max(12, MAX * row.value / most), 56);
737
+ });
738
+ ctx.fillStyle = ink;
739
+ text(ctx, 56);
740
+ wrap(ctx, sentence, X, H - 290, MAX, 70);
741
+ }
742
+
743
+ // The six people with the most of one tally (sent, starts, reels or reactions).
744
+ function ranked(c, tally) {
745
+ const rows = c.members.filter((m) => m[tally] > 0).map((m) => ({ name: m.name, value: m[tally], emoji: null }));
746
+ rows.sort((a, b) => b.value - a.value);
747
+ return rows.slice(0, 6);
748
+ }
749
+ const capital = (name) => (name === "you" ? "You" : name);
750
+
751
+ function slidesFor(c) {
752
+ const slides = [];
753
+ const months = c.months.slice(-12);
754
+
755
+ slides.push((ctx) => {
756
+ plain(ctx, LIME, INK, monthName(c.since) + " to " + monthName(c.until));
757
+ text(ctx, 110);
758
+ if (!c.isGroup) ctx.fillText("you &", X, 400);
759
+ const size = fit(ctx, c.them, 300, MAX);
760
+ ctx.fillText(c.them, X - 8, 420 + size * 0.85);
761
+ const y = 420 + size + 130;
762
+ fit(ctx, fmt(c.total), 200, MAX);
763
+ ctx.fillText(fmt(c.total), X - 6, y + 110);
764
+ text(ctx, 60);
765
+ ctx.fillText("messages since " + monthName(c.since), X, y + 200);
766
+ // One bar per month, as tall as the month was busy.
767
+ const most = Math.max(1, ...months.map((m) => m.me + m.them));
768
+ const column = MAX / months.length, base = 1640, tallest = base - (y + 290);
769
+ months.forEach((m, i) => {
770
+ const height = Math.max(8, tallest * (m.me + m.them) / most);
771
+ ctx.fillRect(X + i * column, base - height, column - 14, height);
772
+ });
773
+ display(ctx, 52);
774
+ ctx.textAlign = "center";
775
+ months.forEach((m, i) => ctx.fillText(monthLetter(m.month), X + i * column + (column - 14) / 2, base + 70));
776
+ ctx.textAlign = "left";
777
+ });
778
+
779
+ if (c.isGroup) {
780
+ const talkers = ranked(c, "sent");
781
+ slides.push((ctx) => {
782
+ const pct = Math.round(100 * talkers[0].value / c.total);
783
+ board(ctx, PINK, INK, PAPER, "who talks most", talkers, capital(talkers[0].name) + " sent " + pct + "% of the messages.");
784
+ });
785
+ const starters = ranked(c, "starts");
786
+ slides.push((ctx) => {
787
+ board(ctx, INK, PAPER, LIME, "who starts", starters, capital(starters[0].name) + " broke the silence " + fmt(starters[0].value) + " times.");
788
+ });
789
+ }
790
+
791
+ const startTotal = c.starts.me + c.starts.them;
792
+ if (!c.isGroup && startTotal > 0) {
793
+ slides.push((ctx) => {
794
+ const youMore = c.starts.me >= c.starts.them;
795
+ const pct = Math.round(100 * Math.max(c.starts.me, c.starts.them) / startTotal);
796
+ split(
797
+ ctx,
798
+ "who texts first",
799
+ { ground: PINK, ink: INK, label: c.them + " starts", number: fmt(c.starts.them), value: c.starts.them },
800
+ { ground: INK, ink: PAPER, label: "you start", number: fmt(c.starts.me), value: c.starts.me },
801
+ pct + "% of your conversations start with " + (youMore ? "you" : c.them) + ".",
802
+ );
803
+ });
804
+ }
805
+
806
+ if (!c.isGroup && (c.replyMinutes.me !== null || c.replyMinutes.them !== null)) {
807
+ slides.push((ctx) => {
808
+ plain(ctx, BLUE, PAPER, "reply time");
809
+ const slowest = Math.max(c.replyMinutes.me ?? 0, c.replyMinutes.them ?? 0, 0.01);
810
+ const rows = [
811
+ { label: c.them + " replies in", minutes: c.replyMinutes.them, color: LIME, y: 300 },
812
+ { label: "you reply in", minutes: c.replyMinutes.me, color: PINK, y: 920 },
813
+ ];
814
+ for (const row of rows) {
815
+ ctx.fillStyle = PAPER;
816
+ text(ctx, 64);
817
+ ctx.fillText(row.label, X, row.y + 60);
818
+ fit(ctx, lag(row.minutes), 280, MAX);
819
+ ctx.fillText(lag(row.minutes), X - 8, row.y + 330);
820
+ // The bar is as long as the wait.
821
+ ctx.fillStyle = row.color;
822
+ ctx.fillRect(X, row.y + 400, Math.max(40, MAX * (row.minutes ?? 0) / slowest), 90);
823
+ }
824
+ ctx.fillStyle = PAPER;
825
+ text(ctx, 56);
826
+ wrap(ctx, "How long a first message usually waits for an answer.", X, H - 290, MAX, 70);
827
+ });
828
+ }
829
+
830
+ slides.push((ctx) => {
831
+ plain(ctx, INK, PAPER, "peak hour");
832
+ ctx.fillStyle = LIME;
833
+ fit(ctx, String(c.peakHour).padStart(2, "0") + ":00", 330, MAX);
834
+ ctx.fillText(String(c.peakHour).padStart(2, "0") + ":00", X - 10, 520);
835
+ ctx.fillStyle = PAPER;
836
+ text(ctx, 64);
837
+ ctx.fillText(c.isGroup ? "is when this chat is busiest." : "is when you two text most.", X, 640);
838
+ // 24 bars, midnight on the left. The peak hour is the bright one.
839
+ const most = Math.max(1, ...c.hours);
840
+ const column = MAX / 24, base = 1560;
841
+ c.hours.forEach((n, hour) => {
842
+ const height = Math.max(6, 760 * n / most);
843
+ ctx.fillStyle = hour === c.peakHour ? LIME : "#5a574f";
844
+ ctx.fillRect(X + hour * column, base - height, column - 8, height);
845
+ });
846
+ ctx.fillStyle = PAPER;
847
+ display(ctx, 52);
848
+ for (const hour of [0, 6, 12, 18]) ctx.fillText(String(hour).padStart(2, "0"), X + hour * column, base + 76);
849
+ });
850
+
851
+ if (c.streak.days > 1) {
852
+ slides.push((ctx) => {
853
+ plain(ctx, ORANGE, INK, "longest streak");
854
+ fit(ctx, String(c.streak.days), 440, MAX);
855
+ ctx.fillText(String(c.streak.days), X - 14, 610);
856
+ display(ctx, 96);
857
+ ctx.fillText("days in a row", X, 740);
858
+ text(ctx, 60);
859
+ ctx.fillText(dayName(c.streak.from) + " to " + dayName(c.streak.to), X, 830);
860
+ // One block per day, a week to a row. Rows get thinner so a long streak still fits.
861
+ const top = 920, cell = MAX / 7;
862
+ const rows = Math.ceil(c.streak.days / 7);
863
+ const step = Math.min(cell, (1700 - top) / rows);
864
+ for (let day = 0; day < c.streak.days; day++) {
865
+ ctx.fillRect(X + (day % 7) * cell, top + Math.floor(day / 7) * step, cell - 12, Math.max(3, step - 12));
866
+ }
867
+ });
868
+ }
869
+
870
+ if (c.words.length > 0) {
871
+ slides.push((ctx) => {
872
+ plain(ctx, PAPER, INK, c.isGroup ? "only this chat says" : "only you two say");
873
+ // The more a word is said, the bigger it is set.
874
+ const words = c.words.slice(0, 6);
875
+ const most = words[0].count;
876
+ let y = 250;
877
+ for (const w of words) {
878
+ const size = fit(ctx, w.word, Math.max(96, Math.round(190 * Math.sqrt(w.count / most))), MAX - 250);
879
+ y += size * 0.9;
880
+ ctx.fillStyle = INK;
881
+ ctx.fillText(w.word, X - 4, y);
882
+ ctx.fillStyle = PINK;
883
+ display(ctx, 56);
884
+ ctx.textAlign = "right";
885
+ ctx.fillText("×" + fmt(w.count), W - X, y);
886
+ ctx.textAlign = "left";
887
+ y += 50;
888
+ }
889
+ ctx.fillStyle = INK;
890
+ text(ctx, 56);
891
+ wrap(ctx, "Hardly anyone else in your DMs uses these words.", X, H - 290, MAX, 70);
892
+ });
893
+ }
894
+
895
+ if (c.isGroup) {
896
+ const senders = ranked(c, "reels");
897
+ if (senders.length > 0) {
898
+ slides.push((ctx) => {
899
+ const total = c.reels.me + c.reels.them;
900
+ board(ctx, BLUE, PAPER, LIME, "reels", senders, capital(senders[0].name) + " sent " + fmt(senders[0].value) + " of the " + fmt(total) + " reels.");
901
+ });
902
+ }
903
+ const reactors = ranked(c, "reactions");
904
+ for (const row of reactors) row.emoji = c.members.find((m) => m.name === row.name).emoji;
905
+ if (reactors.length > 0) {
906
+ slides.push((ctx) => {
907
+ board(ctx, ORANGE, INK, PAPER, "reactions", reactors, "Reactions given, next to each person's favourite emoji.");
908
+ });
909
+ }
910
+ return slides;
911
+ }
912
+
913
+ if (c.reels.me + c.reels.them > 0) {
914
+ slides.push((ctx) => {
915
+ const diff = Math.abs(c.reels.me - c.reels.them);
916
+ const line = diff === 0 ? "Exactly even." : (c.reels.me > c.reels.them ? "You" : c.them) + " sent " + fmt(diff) + " more.";
917
+ split(
918
+ ctx,
919
+ "reels",
920
+ { ground: LIME, ink: INK, label: c.them + " sent", number: fmt(c.reels.them), value: c.reels.them },
921
+ { ground: BLUE, ink: PAPER, label: "you sent", number: fmt(c.reels.me), value: c.reels.me },
922
+ line,
923
+ );
924
+ });
925
+ }
926
+
927
+ if (c.reactions.me.count + c.reactions.them.count > 0) {
928
+ slides.push((ctx) => {
929
+ split(
930
+ ctx,
931
+ "reactions",
932
+ { ground: ORANGE, ink: INK, label: c.them + " reacted", number: fmt(c.reactions.them.count), value: c.reactions.them.count, emoji: c.reactions.them.top },
933
+ { ground: PAPER, ink: INK, label: "you reacted", number: fmt(c.reactions.me.count), value: c.reactions.me.count, emoji: c.reactions.me.top },
934
+ "Next to each number, the emoji that person uses most.",
935
+ );
936
+ });
937
+ }
938
+ return slides;
939
+ }
940
+
941
+ function showOverview() {
942
+ root.replaceChildren();
943
+ const o = DATA.overview;
944
+ root.append(el("h1", "", fmt(o.messages) + " messages in " + fmt(o.chats) + " chats"));
945
+ root.append(el("p", "lede", "You sent " + fmt(o.reelsSent) + " reels and got " + fmt(o.reelsReceived) + " back. A longer bar is a busier chat. Open a chat for its slides."));
946
+ const key = el("p", "key");
947
+ const yours = el("span", "", "your messages"), theirs = el("span", "", "theirs");
948
+ yours.prepend(el("i"));
949
+ theirs.prepend(el("i", "them"));
950
+ key.append(yours, theirs);
951
+ root.append(key);
952
+
953
+ const list = el("ul", "chatlist");
954
+ const max = o.list.length ? o.list[0].total : 1;
955
+ for (const chat of o.list) {
956
+ const li = el("li");
957
+ const a = el("a", "name", chat.title + (chat.isGroup ? " (group)" : ""));
958
+ a.href = "#chat=" + encodeURIComponent(chat.id);
959
+ li.append(a);
960
+ li.append(el("span", "n", fmt(chat.total)));
961
+ const bar = el("div", "bar");
962
+ bar.style.width = Math.max(1, 100 * chat.total / max) + "%";
963
+ const share = el("span");
964
+ share.style.width = (100 * chat.mine / chat.total) + "%";
965
+ bar.append(share);
966
+ li.append(bar);
967
+ list.append(li);
968
+ }
969
+ root.append(list);
970
+ }
971
+
972
+ function showChat(c) {
973
+ root.replaceChildren();
974
+ const back = el("a", "back", "← all chats");
975
+ back.href = "#";
976
+ root.append(back, el("h1", "", c.isGroup ? c.them : "You & " + c.them));
977
+ root.append(el("p", "lede", fmt(c.total) + " messages, " + monthName(c.since) + " to " + monthName(c.until) + "."));
978
+ const grid = el("div", "slides");
979
+ slidesFor(c).forEach((draw, i) => {
980
+ const figure = el("figure");
981
+ const canvas = el("canvas");
982
+ canvas.width = W;
983
+ canvas.height = H;
984
+ const ctx = canvas.getContext("2d");
985
+ ctx.textBaseline = "alphabetic";
986
+ draw(ctx);
987
+ const button = el("button", "", "Save PNG");
988
+ button.onclick = () => canvas.toBlob((blob) => {
989
+ const a = document.createElement("a");
990
+ a.href = URL.createObjectURL(blob);
991
+ a.download = "wrapped-" + c.them.toLowerCase() + "-" + (i + 1) + ".png";
992
+ a.click();
993
+ URL.revokeObjectURL(a.href);
994
+ });
995
+ figure.append(canvas, button);
996
+ grid.append(figure);
997
+ });
998
+ root.append(grid);
999
+ }
1000
+
1001
+ function route() {
1002
+ const match = /^#chat=(.+)$/.exec(location.hash);
1003
+ const chat = match && DATA.chats.find((c) => c.id === decodeURIComponent(match[1]));
1004
+ if (chat) showChat(chat);
1005
+ else showOverview();
1006
+ window.scrollTo(0, 0);
1007
+ }
1008
+ if (!location.hash && DATA.initial) location.hash = "chat=" + encodeURIComponent(DATA.initial);
1009
+ window.addEventListener("hashchange", route);
1010
+ route();
1011
+ `;
1012
+ function wrappedHtml(data) {
1013
+ return page("Wrapped", CSS, data, SCRIPT, `<main id="root"></main>`);
1014
+ }
1015
+
1016
+ // reels.ts
1017
+ var LAUGH_WINDOW = 30 * 60 * 1000;
1018
+ var LAUGH_RE = /(ha){2,}|(ah){2,}|(χα){2,}|(xa){2,}|(χε){2,}|(xe){2,}|(ja){2,}|\blo+l\b|\blmf?ao|\bxd+\b|😂|🤣|💀|😭/i;
1019
+ var REACTION_WEIGHT = { "\uD83D\uDE02": 3, "\uD83E\uDD23": 3, "\uD83D\uDC80": 3, "\uD83D\uDE2D": 3, "❤️": 2, "❤": 2, "\uD83D\uDE0D": 2, "\uD83D\uDD25": 2 };
1020
+ function isLaugh(text) {
1021
+ return LAUGH_RE.test(text);
1022
+ }
1023
+ function reactionWeight(emoji) {
1024
+ return REACTION_WEIGHT[emoji] ?? 1;
1025
+ }
1026
+ function scoreReel(reactions, laughs, chatCount) {
1027
+ let score = 0;
1028
+ for (const emoji in reactions)
1029
+ score += reactionWeight(emoji) * reactions[emoji];
1030
+ return score + 2 * laughs + 1.5 * (chatCount - 1);
1031
+ }
1032
+ function buildReels(db, anon) {
1033
+ const owner = getOwner(db);
1034
+ const titles = new Map;
1035
+ let anonNumber = 0;
1036
+ for (const chat of db.prepare("SELECT id, title, is_group, participants FROM chats").all()) {
1037
+ anonNumber++;
1038
+ const other = JSON.parse(chat.participants).find((name) => name !== owner) ?? chat.title;
1039
+ let title = chat.is_group === 1 ? chat.title : firstName(other);
1040
+ if (anon)
1041
+ title = `chat ${anonNumber}`;
1042
+ titles.set(chat.id, title);
1043
+ }
1044
+ const person = (name) => name === owner ? "You" : anon ? "them" : firstName(name);
1045
+ const reactionsByMessage = new Map;
1046
+ const reactionRows = db.prepare("SELECT r.message_id AS id, r.emoji AS emoji FROM reactions r JOIN messages m ON m.id = r.message_id WHERE m.kind = 'reel'").all();
1047
+ for (const r of reactionRows) {
1048
+ if (!reactionsByMessage.has(r.id))
1049
+ reactionsByMessage.set(r.id, []);
1050
+ reactionsByMessage.get(r.id).push(r.emoji);
1051
+ }
1052
+ const reels = new Map;
1053
+ const rows = db.prepare("SELECT id, chat_id, sender, ts, content, kind, caption, creator, reel FROM messages WHERE kind IN ('reel', 'text') ORDER BY chat_id, ts").all();
1054
+ let currentChat = "";
1055
+ let lastReel = null;
1056
+ for (const row of rows) {
1057
+ if (row.chat_id !== currentChat) {
1058
+ currentChat = row.chat_id;
1059
+ lastReel = null;
1060
+ }
1061
+ if (row.kind === "text") {
1062
+ if (lastReel && row.sender !== lastReel.sender && row.ts - lastReel.ts <= LAUGH_WINDOW && !lastReel.laughed.has(row.sender) && isLaugh(row.content)) {
1063
+ lastReel.laughed.add(row.sender);
1064
+ lastReel.reel.laughs++;
1065
+ }
1066
+ continue;
1067
+ }
1068
+ const code = row.reel;
1069
+ let reel = reels.get(code);
1070
+ if (!reel) {
1071
+ reel = { code, caption: row.caption ?? "", creator: row.creator ?? "", ts: row.ts, month: "", from: person(row.sender), chats: [], senders: [], reactions: {}, laughs: 0, score: 0 };
1072
+ reels.set(code, reel);
1073
+ }
1074
+ if (row.ts < reel.ts) {
1075
+ reel.ts = row.ts;
1076
+ reel.from = person(row.sender);
1077
+ }
1078
+ const title = titles.get(row.chat_id) ?? row.chat_id;
1079
+ if (!reel.chats.includes(title))
1080
+ reel.chats.push(title);
1081
+ const sender = person(row.sender);
1082
+ if (!reel.senders.includes(sender))
1083
+ reel.senders.push(sender);
1084
+ for (const emoji of reactionsByMessage.get(row.id) ?? []) {
1085
+ reel.reactions[emoji] = (reel.reactions[emoji] ?? 0) + 1;
1086
+ }
1087
+ lastReel = { reel, sender: row.sender, ts: row.ts, laughed: new Set };
1088
+ }
1089
+ const list = [...reels.values()];
1090
+ for (const reel of list) {
1091
+ const d = new Date(reel.ts);
1092
+ reel.month = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
1093
+ reel.score = scoreReel(reel.reactions, reel.laughs, reel.chats.length);
1094
+ }
1095
+ list.sort((a, b) => b.score - a.score || b.ts - a.ts);
1096
+ return list;
1097
+ }
1098
+ var CSS2 = `
1099
+ .search { position: sticky; top: 0; background: var(--bg); padding: 12px 0; z-index: 2; }
1100
+ .search input { width: 100%; font: inherit; font-size: 22px; padding: 12px 0; border: none; border-bottom: 2px solid var(--ink); border-radius: 0; background: transparent; color: var(--ink); outline: none; }
1101
+ .search input:focus { border-bottom-width: 4px; }
1102
+ .count { margin: 8px 0 0; font-size: 15px; }
1103
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 36px 24px; margin-top: 24px; }
1104
+ .card { border-top: 2px solid var(--ink); padding-top: 10px; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
1105
+ .card header { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; font: 700 16px var(--display); }
1106
+ .card .rank { font-size: 56px; line-height: 1; }
1107
+ .card .caption { margin: 0; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
1108
+ .card .meta { font-size: 15px; }
1109
+ .embed { min-height: 120px; }
1110
+ .embed blockquote { margin: 0 !important; min-width: 0 !important; width: 100% !important; }
1111
+ #more { height: 1px; }
1112
+ `;
1113
+ var SCRIPT2 = EMBED_SCRIPT + String.raw`
1114
+ const PAGE = 30;
1115
+ const input = document.getElementById("q");
1116
+ const counter = document.getElementById("count");
1117
+ const grid = document.getElementById("grid");
1118
+ const more = document.getElementById("more");
1119
+ const fmt = (n) => n.toLocaleString("en-US");
1120
+
1121
+ DATA.reels.forEach((r, i) => {
1122
+ r.rank = i + 1;
1123
+ r.haystack = [r.caption, r.creator, r.chats.join(" "), r.senders.join(" "), r.month].join(" ").toLowerCase();
1124
+ });
1125
+
1126
+ function card(r) {
1127
+ const node = el("article", "card");
1128
+ const header = el("header");
1129
+ header.append(el("span", "rank", String(r.rank)), el("span", "muted", "@" + (r.creator || "unknown")));
1130
+ node.append(header);
1131
+ if (r.caption) node.append(el("p", "caption", r.caption));
1132
+ const bits = [r.from + " sent it in " + r.chats[0], r.month];
1133
+ if (r.chats.length > 1) bits.push("in " + r.chats.length + " chats");
1134
+ const reactions = Object.entries(r.reactions).map(([e, n]) => e + (n > 1 ? "×" + n : "")).join(" ");
1135
+ if (reactions) bits.push(reactions);
1136
+ if (r.laughs) bits.push(r.laughs + (r.laughs === 1 ? " laugh" : " laughs"));
1137
+ node.append(el("div", "meta muted", bits.join(" · ")));
1138
+ const embed = el("div", "embed");
1139
+ embed.dataset.link = "https://www.instagram.com/reel/" + r.code + "/";
1140
+ node.append(embed);
1141
+ embedObserver.observe(embed);
1142
+ return node;
1143
+ }
1144
+
1145
+ let matches = DATA.reels;
1146
+ let shown = 0;
1147
+ function showMore() {
1148
+ const next = matches.slice(shown, shown + PAGE);
1149
+ for (const r of next) grid.append(card(r));
1150
+ shown += next.length;
1151
+ }
1152
+ new IntersectionObserver((entries) => {
1153
+ if (entries[0].isIntersecting && shown < matches.length) showMore();
1154
+ }, { rootMargin: "800px" }).observe(more);
1155
+
1156
+ function search() {
1157
+ const terms = input.value.toLowerCase().split(/\s+/).filter(Boolean);
1158
+ matches = DATA.reels.filter((r) => terms.every((t) => r.haystack.includes(t)));
1159
+ counter.textContent = fmt(matches.length) + " of " + fmt(DATA.reels.length) + " reels";
1160
+ grid.replaceChildren();
1161
+ shown = 0;
1162
+ showMore();
1163
+ }
1164
+ let timer = 0;
1165
+ input.addEventListener("input", () => {
1166
+ clearTimeout(timer);
1167
+ timer = setTimeout(search, 150);
1168
+ });
1169
+ search();
1170
+ `;
1171
+ var BODY = `<main id="root">
1172
+ <h1>Best reels</h1>
1173
+ <p class="muted">Every reel traded in your DMs, ranked by reactions, laugh replies within 30 minutes, and how many chats it was forwarded to.</p>
1174
+ <div class="search"><input id="q" type="search" placeholder="Search caption, creator, chat, person, month (2026-03)" autofocus><p id="count" class="count muted"></p></div>
1175
+ <section id="grid" class="grid"></section>
1176
+ <div id="more"></div>
1177
+ </main>`;
1178
+ function reelsHtml(reels) {
1179
+ return page("Best reels", CSS2, { reels }, SCRIPT2, BODY);
1180
+ }
1181
+
1182
+ // keepsake.ts
1183
+ import { existsSync, mkdirSync as mkdirSync2, statSync as statSync2 } from "node:fs";
1184
+ import { join as join2 } from "node:path";
1185
+ import { pathToFileURL } from "node:url";
1186
+ var MINUTE = 60 * 1000;
1187
+ var SPOKEN2 = new Set(["text", "reel", "share", "photo", "video", "audio", "call"]);
1188
+ var FIRST_PHRASES = [
1189
+ ["The first “miss you”", /\bmiss (you|u|ya)\b|μου λε[ιί]π/i],
1190
+ ["The first “love you”", /\b(love|luv) (you|u|ya)\b|σ.?αγαπ[αά]/i]
1191
+ ];
1192
+ function lineText(m) {
1193
+ if (m.kind === "reel")
1194
+ return "sent a reel" + (m.caption ? ": " + m.caption.split(`
1195
+ `)[0].slice(0, 120) : "");
1196
+ if (m.kind === "share")
1197
+ return "sent a link";
1198
+ if (m.kind === "photo")
1199
+ return "sent a photo";
1200
+ if (m.kind === "video")
1201
+ return "sent a video";
1202
+ if (m.kind === "audio")
1203
+ return "sent a voice note";
1204
+ if (m.kind === "call")
1205
+ return "called";
1206
+ return m.content;
1207
+ }
1208
+ function withContext(messages, index, who) {
1209
+ const lines = [];
1210
+ const start = messages[index];
1211
+ for (let i = index;i < messages.length && lines.length < 4; i++) {
1212
+ if (messages[i].ts - start.ts > 10 * MINUTE)
1213
+ break;
1214
+ lines.push({ who: who(messages[i].sender), text: lineText(messages[i]), ts: messages[i].ts });
1215
+ }
1216
+ return lines;
1217
+ }
1218
+ function landed(messages, index) {
1219
+ const m = messages[index];
1220
+ const laughed = new Set;
1221
+ for (let i = index + 1;i < messages.length && messages[i].ts - m.ts <= 5 * MINUTE; i++) {
1222
+ if (messages[i].sender !== m.sender && messages[i].kind === "text" && isLaugh(messages[i].content))
1223
+ laughed.add(messages[i].sender);
1224
+ }
1225
+ return m.reactions + laughed.size;
1226
+ }
1227
+ function findMoments(messages, who, jokes) {
1228
+ const firsts = [];
1229
+ const addFirst = (title, index) => {
1230
+ if (index < 0)
1231
+ return;
1232
+ const m = messages[index];
1233
+ firsts.push({ id: "first-" + m.id, ts: m.ts, title, note: "", lines: withContext(messages, index, who), photo: m.kind === "photo" ? m.link : null });
1234
+ };
1235
+ addFirst("The very first message", 0);
1236
+ addFirst("The first reel", messages.findIndex((m) => m.kind === "reel"));
1237
+ addFirst("The first photo", messages.findIndex((m) => m.kind === "photo"));
1238
+ addFirst("The first voice note", messages.findIndex((m) => m.kind === "audio"));
1239
+ addFirst("The first call", messages.findIndex((m) => m.kind === "call"));
1240
+ for (const [title, re] of FIRST_PHRASES)
1241
+ addFirst(title, messages.findIndex((m) => m.kind === "text" && re.test(m.content)));
1242
+ firsts.sort((a, b) => a.ts - b.ts);
1243
+ const scored = messages.map((m, i) => ({ i, score: m.kind === "photo" ? 0 : landed(messages, i) })).filter((s) => s.score >= 2);
1244
+ scored.sort((a, b) => b.score - a.score || messages[a.i].ts - messages[b.i].ts);
1245
+ const moments = scored.slice(0, 12).map(({ i, score }) => ({
1246
+ id: "moment-" + messages[i].id,
1247
+ ts: messages[i].ts,
1248
+ title: new Date(messages[i].ts).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" }),
1249
+ note: score + " reactions and laughs",
1250
+ lines: withContext(messages, i, who),
1251
+ photo: null
1252
+ }));
1253
+ moments.sort((a, b) => a.ts - b.ts);
1254
+ const inside = [];
1255
+ for (const { word, count } of jokes.slice(0, 6)) {
1256
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}])`, "iu");
1257
+ const index = messages.findIndex((m) => m.kind === "text" && re.test(m.content));
1258
+ if (index < 0)
1259
+ continue;
1260
+ inside.push({ id: "joke-" + word, ts: messages[index].ts, title: `“${word}” is born`, note: `said ${count} times since`, lines: withContext(messages, index, who), photo: null });
1261
+ }
1262
+ const bestPerMonth = new Map;
1263
+ const firstPhoto = messages.findIndex((m) => m.kind === "photo");
1264
+ messages.forEach((m, i) => {
1265
+ if (m.kind !== "photo" || !m.link || i === firstPhoto)
1266
+ return;
1267
+ const d = new Date(m.ts);
1268
+ const month = `${d.getFullYear()}-${d.getMonth()}`;
1269
+ const best = bestPerMonth.get(month);
1270
+ if (best === undefined || m.reactions > messages[best].reactions)
1271
+ bestPerMonth.set(month, i);
1272
+ });
1273
+ const photos = [...bestPerMonth.values()].map((i) => ({
1274
+ id: "photo-" + messages[i].id,
1275
+ ts: messages[i].ts,
1276
+ title: new Date(messages[i].ts).toLocaleDateString("en-GB", { month: "long", year: "numeric" }),
1277
+ note: who(messages[i].sender) + " sent it",
1278
+ lines: [],
1279
+ photo: messages[i].link
1280
+ }));
1281
+ photos.sort((a, b) => a.ts - b.ts);
1282
+ return [
1283
+ { id: "firsts", title: "Firsts", moments: firsts },
1284
+ { id: "moments", title: "Moments that landed", moments },
1285
+ { id: "jokes", title: "Inside jokes", moments: inside },
1286
+ { id: "photos", title: "A photo a month", moments: photos }
1287
+ ].filter((c) => c.moments.length > 0);
1288
+ }
1289
+ function resolvePhotos(db, uris, mediaDir) {
1290
+ const found = new Map;
1291
+ for (const source of getSources(db)) {
1292
+ const missing = uris.filter((uri) => !found.has(uri));
1293
+ if (missing.length === 0)
1294
+ break;
1295
+ if (!existsSync(source))
1296
+ continue;
1297
+ let root = source;
1298
+ if (!statSync2(source).isDirectory()) {
1299
+ root = mediaDir;
1300
+ mkdirSync2(mediaDir, { recursive: true });
1301
+ extractZip(source, mediaDir, missing);
1302
+ }
1303
+ for (const uri of missing) {
1304
+ const path = join2(root, uri);
1305
+ if (existsSync(path))
1306
+ found.set(uri, pathToFileURL(path).href);
1307
+ }
1308
+ }
1309
+ return found;
1310
+ }
1311
+ function buildKeepsake(db, chatId, anon, mediaDir) {
1312
+ const owner = getOwner(db);
1313
+ const chat = db.prepare("SELECT title, is_group, participants FROM chats WHERE id = ?").get(chatId);
1314
+ const other = JSON.parse(chat.participants).find((name) => name !== owner) ?? chat.title;
1315
+ const who = (sender) => sender === owner ? "You" : anon ? "them" : firstName(sender);
1316
+ const messages = db.prepare("SELECT m.id, m.chat_id, m.sender, m.ts, m.content, m.kind, m.link, m.caption, (SELECT COUNT(*) FROM reactions r WHERE r.message_id = m.id) AS reactions FROM messages m WHERE m.chat_id = ? ORDER BY m.ts").all(chatId).filter((m) => SPOKEN2.has(m.kind));
1317
+ if (messages.length === 0)
1318
+ throw new Error("that chat has no messages.");
1319
+ const textByChat = new Map;
1320
+ for (const row of db.prepare("SELECT chat_id, content FROM messages WHERE kind = 'text'").all()) {
1321
+ if (!textByChat.has(row.chat_id))
1322
+ textByChat.set(row.chat_id, []);
1323
+ textByChat.get(row.chat_id).push(row.content);
1324
+ }
1325
+ const jokes = wordsOnlyHere(textByChat).get(chatId) ?? [];
1326
+ const chapters = findMoments(messages, who, jokes);
1327
+ const uris = chapters.flatMap((c) => c.moments.map((m) => m.photo)).filter((uri) => uri !== null);
1328
+ const files = resolvePhotos(db, uris, mediaDir);
1329
+ for (const chapter of chapters) {
1330
+ for (const moment of chapter.moments) {
1331
+ if (moment.photo)
1332
+ moment.photo = files.get(moment.photo) ?? null;
1333
+ }
1334
+ if (chapter.id === "photos")
1335
+ chapter.moments = chapter.moments.filter((m) => m.photo);
1336
+ }
1337
+ const them = anon ? "them" : chat.is_group === 1 ? chat.title : firstName(other);
1338
+ return {
1339
+ chatId,
1340
+ title: chat.is_group === 1 ? them : "You & " + them,
1341
+ since: messages[0].ts,
1342
+ until: messages[messages.length - 1].ts,
1343
+ total: messages.length,
1344
+ chapters: chapters.filter((c) => c.moments.length > 0)
1345
+ };
1346
+ }
1347
+ var CSS3 = `
1348
+ .toolbar { position: sticky; top: 0; z-index: 2; display: flex; gap: 8px; align-items: center; padding: 12px 0; background: var(--bg); border-bottom: 1px solid var(--line); }
1349
+ .toolbar .primary { background: var(--ink); color: var(--bg); }
1350
+ .toolbar .muted { margin-left: auto; font-size: 15px; }
1351
+ .cover { padding: 48px 0 24px; }
1352
+ .cover input { font: inherit; font-size: clamp(44px, 8vw, 88px); font-family: var(--display); font-weight: 700; letter-spacing: -0.02em; border: none; background: transparent; color: var(--ink); width: 100%; padding: 0; }
1353
+ .chapter { margin-top: 40px; }
1354
+ .chapter > header { display: flex; align-items: center; gap: 8px; border-bottom: 2px solid var(--ink); padding-bottom: 6px; }
1355
+ .chapter > header h2 { margin: 0; flex: 1; font-size: 30px; }
1356
+ .chapter > header button { padding: 5px 10px; }
1357
+ .moment { border-bottom: 1px solid var(--line); padding: 18px 0 20px; break-inside: avoid; }
1358
+ .moment.dropped { opacity: 0.35; }
1359
+ .moment h3 { margin: 0; font-size: 18px; }
1360
+ .moment .note { font-size: 15px; margin-top: 2px; }
1361
+ .moment label { float: right; font: 700 15px var(--display); cursor: pointer; }
1362
+ .moment img { display: block; max-width: 100%; max-height: 420px; margin: 12px 0 0; }
1363
+ .line { margin: 6px 0 0; overflow-wrap: anywhere; }
1364
+ .line b { margin-right: 6px; }
1365
+ .line .muted { font-size: 15px; }
1366
+ .moment textarea { width: 100%; margin-top: 12px; font: inherit; font-style: italic; padding: 6px 0; border: none; border-bottom: 1px dashed var(--ink); border-radius: 0; background: transparent; color: var(--ink); resize: vertical; }
1367
+ .caption-print { display: none; font-style: italic; margin: 10px 0 0; }
1368
+ @page { size: A5; margin: 14mm 12mm; }
1369
+ @media print {
1370
+ :root { --bg: #fff; --ink: #111; --line: #ddd; --muted: #666; }
1371
+ main { padding: 0; max-width: none; }
1372
+ .toolbar, .chapter > header button, .moment label, .moment textarea, .moment.dropped, .chapter.empty { display: none !important; }
1373
+ .caption-print { display: block; }
1374
+ .cover { height: 170mm; display: flex; flex-direction: column; justify-content: flex-end; padding: 0; }
1375
+ .chapter { break-before: page; margin-top: 0; }
1376
+ .moment { border: none; padding: 0; margin-top: 10mm; }
1377
+ .moment img { max-height: 120mm; }
1378
+ }
1379
+ `;
1380
+ var SCRIPT3 = String.raw`
1381
+ const KEY = "lor-keepsake-" + DATA.chatId;
1382
+ const fmt = (n) => n.toLocaleString("en-US");
1383
+ const month = (ts) => new Date(ts).toLocaleDateString("en-GB", { month: "long", year: "numeric" });
1384
+ const time = (ts) => new Date(ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
1385
+
1386
+ function load() {
1387
+ try {
1388
+ const saved = JSON.parse(localStorage.getItem(KEY));
1389
+ if (saved) {
1390
+ for (const c of DATA.chapters) if (!saved.order.includes(c.id)) saved.order.push(c.id);
1391
+ return saved;
1392
+ }
1393
+ } catch {}
1394
+ return { title: DATA.title, order: DATA.chapters.map((c) => c.id), dropped: {}, captions: {} };
1395
+ }
1396
+ let picks = load();
1397
+ function save() {
1398
+ try { localStorage.setItem(KEY, JSON.stringify(picks)); } catch {}
1399
+ }
1400
+
1401
+ const root = document.getElementById("root");
1402
+
1403
+ function render() {
1404
+ root.replaceChildren();
1405
+ const toolbar = el("div", "toolbar");
1406
+ const print = el("button", "primary", "Save PDF");
1407
+ print.onclick = () => window.print();
1408
+ const reset = el("button", "", "Reset picks");
1409
+ reset.onclick = () => {
1410
+ if (!confirm("Undo every keep, drop, caption and reorder?")) return;
1411
+ picks = { title: DATA.title, order: DATA.chapters.map((c) => c.id), dropped: {}, captions: {} };
1412
+ save();
1413
+ render();
1414
+ };
1415
+ const kept = DATA.chapters.flatMap((c) => c.moments).filter((m) => !picks.dropped[m.id]).length;
1416
+ toolbar.append(print, reset, el("span", "muted", kept + " moments kept. Print as A5."));
1417
+ root.append(toolbar);
1418
+
1419
+ const cover = el("section", "cover");
1420
+ const title = el("input");
1421
+ title.value = picks.title;
1422
+ title.oninput = () => { picks.title = title.value; save(); };
1423
+ cover.append(title, el("p", "muted", fmt(DATA.total) + " messages, " + month(DATA.since) + " to " + month(DATA.until)));
1424
+ root.append(cover);
1425
+
1426
+ const chapters = picks.order.map((id) => DATA.chapters.find((c) => c.id === id)).filter(Boolean);
1427
+ chapters.forEach((chapter, index) => {
1428
+ const section = el("section", "chapter");
1429
+ if (chapter.moments.every((m) => picks.dropped[m.id])) section.classList.add("empty");
1430
+ const header = el("header");
1431
+ header.append(el("h2", "", chapter.title));
1432
+ const move = (step) => {
1433
+ const order = chapters.map((c) => c.id);
1434
+ const target = index + step;
1435
+ if (target < 0 || target >= order.length) return;
1436
+ [order[index], order[target]] = [order[target], order[index]];
1437
+ picks.order = order;
1438
+ save();
1439
+ render();
1440
+ };
1441
+ const up = el("button", "", "↑");
1442
+ up.title = "Move chapter up";
1443
+ up.onclick = () => move(-1);
1444
+ const down = el("button", "", "↓");
1445
+ down.title = "Move chapter down";
1446
+ down.onclick = () => move(1);
1447
+ header.append(up, down);
1448
+ section.append(header);
1449
+
1450
+ for (const m of chapter.moments) {
1451
+ const card = el("article", "moment" + (picks.dropped[m.id] ? " dropped" : ""));
1452
+ const label = el("label");
1453
+ const keep = el("input");
1454
+ keep.type = "checkbox";
1455
+ keep.checked = !picks.dropped[m.id];
1456
+ keep.onchange = () => {
1457
+ if (keep.checked) delete picks.dropped[m.id];
1458
+ else picks.dropped[m.id] = true;
1459
+ save();
1460
+ render();
1461
+ };
1462
+ label.append(keep, " keep");
1463
+ card.append(label, el("h3", "", m.title));
1464
+ if (m.note) card.append(el("div", "note muted", m.note));
1465
+ for (const line of m.lines) {
1466
+ const p = el("p", "line");
1467
+ p.append(el("b", "", line.who), line.text, el("span", "muted", " " + time(line.ts)));
1468
+ card.append(p);
1469
+ }
1470
+ if (m.photo) {
1471
+ const img = el("img");
1472
+ img.src = m.photo;
1473
+ img.alt = "Photo from " + m.title;
1474
+ img.loading = "lazy";
1475
+ card.append(img);
1476
+ }
1477
+ const caption = el("textarea");
1478
+ caption.rows = 2;
1479
+ caption.placeholder = "Add a caption (optional)";
1480
+ caption.setAttribute("aria-label", "Caption for " + m.title);
1481
+ caption.value = picks.captions[m.id] ?? "";
1482
+ const printed = el("p", "caption-print", caption.value);
1483
+ caption.oninput = () => {
1484
+ picks.captions[m.id] = caption.value;
1485
+ printed.textContent = caption.value;
1486
+ save();
1487
+ };
1488
+ card.append(caption, printed);
1489
+ section.append(card);
1490
+ }
1491
+ root.append(section);
1492
+ });
1493
+ }
1494
+ render();
1495
+ `;
1496
+ function keepsakeHtml(keepsake) {
1497
+ return page("Keepsake", CSS3, keepsake, SCRIPT3, `<main id="root"></main>`);
1498
+ }
1499
+
1500
+ // taste.ts
1501
+ function topCounts(counts, limit) {
1502
+ return [...counts].map(([creator, count]) => ({ creator, count })).sort((a, b) => b.count - a.count).slice(0, limit);
1503
+ }
1504
+ function introductions(shares, members) {
1505
+ const firstSent = new Map;
1506
+ const introducedBy = new Map;
1507
+ for (const s of shares) {
1508
+ for (const person of members.get(s.chat) ?? []) {
1509
+ if (person === s.sender)
1510
+ continue;
1511
+ if (firstSent.get(person)?.has(s.creator))
1512
+ continue;
1513
+ if (!introducedBy.has(person))
1514
+ introducedBy.set(person, new Map);
1515
+ const seen = introducedBy.get(person);
1516
+ if (!seen.has(s.creator))
1517
+ seen.set(s.creator, s.sender);
1518
+ }
1519
+ if (!firstSent.has(s.sender))
1520
+ firstSent.set(s.sender, new Set);
1521
+ firstSent.get(s.sender).add(s.creator);
1522
+ }
1523
+ for (const [person, creators] of introducedBy) {
1524
+ for (const creator of creators.keys()) {
1525
+ if (!firstSent.get(person)?.has(creator))
1526
+ creators.delete(creator);
1527
+ }
1528
+ }
1529
+ return introducedBy;
1530
+ }
1531
+ function buildTaste(db, anon) {
1532
+ const owner = getOwner(db);
1533
+ const members = new Map;
1534
+ const dmWith = new Map;
1535
+ for (const chat of db.prepare("SELECT id, is_group, participants FROM chats").all()) {
1536
+ const people = JSON.parse(chat.participants);
1537
+ members.set(chat.id, people);
1538
+ const other = people.find((name) => name !== owner);
1539
+ if (chat.is_group === 0 && other)
1540
+ dmWith.set(other, chat.id);
1541
+ }
1542
+ const shares = db.prepare("SELECT chat_id AS chat, sender, ts, creator FROM messages WHERE kind = 'reel' AND creator IS NOT NULL AND creator != '' ORDER BY ts").all();
1543
+ const sentBy = new Map;
1544
+ for (const s of shares) {
1545
+ if (!sentBy.has(s.sender))
1546
+ sentBy.set(s.sender, new Map);
1547
+ const counts = sentBy.get(s.sender);
1548
+ counts.set(s.creator, (counts.get(s.creator) ?? 0) + 1);
1549
+ }
1550
+ let anonNumber = 0;
1551
+ const names = new Map;
1552
+ const label = (person) => {
1553
+ if (person === owner)
1554
+ return "You";
1555
+ if (!names.has(person))
1556
+ names.set(person, anon ? `friend ${++anonNumber}` : firstName(person));
1557
+ return names.get(person);
1558
+ };
1559
+ const people = [...sentBy].map(([person, counts]) => ({ name: label(person), total: [...counts.values()].reduce((a, b) => a + b, 0), top: topCounts(counts, 10) })).sort((a, b) => b.total - a.total);
1560
+ const intro = introductions(shares, members);
1561
+ const mine = sentBy.get(owner) ?? new Map;
1562
+ const friends = [];
1563
+ for (const [friend, chat] of dmWith) {
1564
+ const theirs = new Map;
1565
+ for (const s of shares) {
1566
+ if (s.chat === chat && s.sender === friend)
1567
+ theirs.set(s.creator, (theirs.get(s.creator) ?? 0) + 1);
1568
+ }
1569
+ if (theirs.size === 0)
1570
+ continue;
1571
+ const both = new Map;
1572
+ for (const [creator, n] of theirs) {
1573
+ if (mine.has(creator))
1574
+ both.set(creator, n + mine.get(creator));
1575
+ }
1576
+ const from = (person, by) => [...intro.get(person) ?? new Map].filter(([, introducer]) => introducer === by).map(([creator]) => creator);
1577
+ friends.push({
1578
+ name: label(friend),
1579
+ overlap: both.size / theirs.size,
1580
+ shared: topCounts(both, 12),
1581
+ gotYouInto: from(owner, friend),
1582
+ youGotThemInto: from(friend, owner)
1583
+ });
1584
+ }
1585
+ friends.sort((a, b) => b.shared.length - a.shared.length || b.overlap - a.overlap);
1586
+ return { people, friends };
1587
+ }
1588
+ var CSS4 = `
1589
+ .friends { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 36px 24px; margin-top: 20px; }
1590
+ .friend, .person { border-top: 2px solid var(--ink); padding-top: 10px; min-width: 0; }
1591
+ .friend h3, .person h3 { margin: 0 0 4px; font-size: 36px; line-height: 1.1; }
1592
+ .meter { height: 14px; background: var(--them); margin: 10px 0 14px; }
1593
+ .meter div { height: 100%; background: var(--ink); }
1594
+ .tags { margin: 2px 0 14px; font-size: 16px; overflow-wrap: anywhere; }
1595
+ h2 { margin: 64px 0 0; font-size: 30px; }
1596
+ .people { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 36px 24px; margin-top: 20px; }
1597
+ .person ol { margin: 8px 0 0; padding-left: 28px; font-size: 16px; }
1598
+ `;
1599
+ var SCRIPT4 = String.raw`
1600
+ const root = document.getElementById("root");
1601
+ const tags = (list) => el("p", "tags muted", list.map((t) => "@" + t).join(", "));
1602
+
1603
+ root.append(el("h2", "", "Friends, by creators in common"));
1604
+ root.append(el("p", "muted", "Got you into: they sent you a creator before you had ever sent it to anyone, and then you started sending it too."));
1605
+ const friends = el("section", "friends");
1606
+ for (const f of DATA.friends) {
1607
+ const card = el("article", "friend");
1608
+ card.append(el("h3", "", f.name), el("span", "muted", "you also send " + Math.round(100 * f.overlap) + "% of the creators " + f.name + " sends you"));
1609
+ const meter = el("div", "meter");
1610
+ const fill = el("div");
1611
+ fill.style.width = Math.max(1, 100 * f.overlap) + "%";
1612
+ meter.append(fill);
1613
+ card.append(meter);
1614
+ if (f.shared.length) card.append(el("b", "", "Both of you send"), tags(f.shared.map((c) => c.creator)));
1615
+ if (f.gotYouInto.length) card.append(el("b", "", f.name + " got you into " + f.gotYouInto.length), tags(f.gotYouInto.slice(0, 12)));
1616
+ if (f.youGotThemInto.length) card.append(el("b", "", "You got " + f.name + " into " + f.youGotThemInto.length), tags(f.youGotThemInto.slice(0, 12)));
1617
+ friends.append(card);
1618
+ }
1619
+ root.append(friends);
1620
+
1621
+ root.append(el("h2", "", "Everyone's most sent creators"));
1622
+ const people = el("section", "people");
1623
+ for (const p of DATA.people) {
1624
+ const card = el("article", "person");
1625
+ card.append(el("h3", "", p.name), el("span", "muted", p.total.toLocaleString("en-US") + " reels sent"));
1626
+ const list = el("ol");
1627
+ for (const c of p.top) list.append(el("li", "", "@" + c.creator + " ×" + c.count));
1628
+ card.append(list);
1629
+ people.append(card);
1630
+ }
1631
+ root.append(people);
1632
+ `;
1633
+ function tasteHtml(taste) {
1634
+ return page("Taste map", CSS4, taste, SCRIPT4, `<main id="root"><h1>Taste map</h1></main>`);
1635
+ }
1636
+
1637
+ // backlog.ts
1638
+ import { spawnSync as spawnSync2 } from "node:child_process";
1639
+ import { tmpdir as tmpdir2 } from "node:os";
1640
+ var CATEGORIES = ["recipe", "place", "experience", "product", "workout", "tip"];
1641
+ var RULES = {
1642
+ recipe: ["!recipe*", "!ingredients", "!tbsp", "!tsp", "!συνταγη", "!συνταγες", "!συνταγης", "!υλικα", "bake", "baking", "oven", "air fryer", "how to make", "meal prep", "φουρνο", "μαγειρ*", "\uD83C\uDF5D", "\uD83C\uDF70", "\uD83E\uDD58", "\uD83C\uDF73", "\uD83E\uDDC1", "\uD83C\uDF6A", "\uD83E\uDD57", "\uD83D\uDC69‍\uD83C\uDF73", "\uD83D\uDC68‍\uD83C\uDF73"],
1643
+ place: ["!\uD83D\uDCCD", "restaurant*", "cafe", "coffee shop", "bar", "rooftop", "brunch", "bakery", "hidden gem", "must visit", "located in", "εστιατορι*", "καφε", "μπαρ", "ταβερν*", "μεζεδοπωλ*", "σουβλατζιδικ*", "φουρναρ*"],
1644
+ experience: ["!itinerary", "!things to do", "!tickets", "concert", "festival", "hike", "hiking", "trip", "weekend in", "road trip", "beach", "island", "εκδρομ*", "συναυλι*", "φεστιβαλ", "παραλι*", "νησι*", "✈️", "\uD83C\uDF9F️", "\uD83C\uDFAB", "\uD83C\uDFDD️", "⛰️"],
1645
+ product: ["!promo code", "!amazon finds", "!discount code", "link in bio", "amazon", "discount", "shop now", "haul", "skincare", "προσφορ*", "εκπτωσ*", "\uD83D\uDECD️"],
1646
+ workout: ["!reps", "!sets of", "!προπονησ*", "workout", "exercise", "gym", "abs", "glutes", "stretch*", "mobility", "γυμναστηρι*", "ασκησ*", "\uD83D\uDCAA", "\uD83C\uDFCB️", "\uD83C\uDFC3"],
1647
+ tip: ["!step by step", "!συμβουλ*", "tips", "hack", "hacks", "how to", "tutorial", "guide", "did you know", "productivity", "μαθε", "κολπ*"]
1648
+ };
1649
+ var MEME_RE = /(?<!\p{L})(memes?|funny|relatable|humou?r|comedy|fyp|lol|lmf?ao|skit|parody)(?!\p{L})|😂|🤣|💀|😭|🎬/u;
1650
+ function normalize(text) {
1651
+ return text.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f\ufe0f]/g, "").normalize("NFC");
1652
+ }
1653
+ function escape(word) {
1654
+ return word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1655
+ }
1656
+ function keywordPattern(keyword) {
1657
+ const stem = keyword.endsWith("*");
1658
+ const word = escape(normalize(stem ? keyword.slice(0, -1) : keyword));
1659
+ if (!/\p{L}/u.test(word))
1660
+ return word;
1661
+ return `(?<!\\p{L})${word}${stem ? "\\p{L}*" : "(?!\\p{L})"}`;
1662
+ }
1663
+ var PATTERNS = CATEGORIES.map((category) => {
1664
+ const strong = RULES[category].filter((k) => k.startsWith("!")).map((k) => keywordPattern(k.slice(1)));
1665
+ const weak = RULES[category].filter((k) => !k.startsWith("!")).map(keywordPattern);
1666
+ return { category, strong: new RegExp(strong.join("|"), "gu"), weak: new RegExp(weak.join("|"), "gu") };
1667
+ });
1668
+ function ruleCategory(caption) {
1669
+ const text = normalize(caption).replace(/#[\p{L}\p{N}_]+/gu, " ");
1670
+ if (MEME_RE.test(normalize(caption)))
1671
+ return null;
1672
+ let best = null;
1673
+ let bestScore = 1;
1674
+ for (const { category, strong, weak } of PATTERNS) {
1675
+ const score = 2 * (text.match(strong)?.length ?? 0) + (text.match(weak)?.length ?? 0);
1676
+ if (score > bestScore) {
1677
+ best = category;
1678
+ bestScore = score;
1679
+ }
1680
+ }
1681
+ return best;
1682
+ }
1683
+ function sleep(ms) {
1684
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
1685
+ }
1686
+ function fetchSavedCaptions(db, log) {
1687
+ const missing = db.prepare("SELECT s.code AS code, s.link AS link FROM saved s LEFT JOIN captions c ON c.code = s.code WHERE c.code IS NULL").all();
1688
+ if (missing.length === 0)
1689
+ return;
1690
+ if (spawnSync2("yt-dlp", ["--version"]).error) {
1691
+ throw new Error("yt-dlp is needed to read the captions of your saved posts: https://github.com/yt-dlp/yt-dlp#installation");
1692
+ }
1693
+ const save = db.prepare("INSERT OR REPLACE INTO captions (code, caption, ok) VALUES (?, ?, ?)");
1694
+ missing.forEach((post, i) => {
1695
+ if (i > 0)
1696
+ sleep(2000);
1697
+ log(`reading saved post ${i + 1}/${missing.length}`);
1698
+ const result = spawnSync2("yt-dlp", ["-J", "--skip-download", "--ignore-no-formats-error", "--no-warnings", post.link], { encoding: "utf8", timeout: 60000 });
1699
+ let caption = "";
1700
+ try {
1701
+ const info = JSON.parse(result.stdout);
1702
+ caption = info.description ?? info.entries?.[0]?.description ?? info.title ?? "";
1703
+ } catch {}
1704
+ save.run(post.code, caption, caption ? 1 : 0);
1705
+ });
1706
+ }
1707
+ var LABEL_SCHEMA = {
1708
+ type: "object",
1709
+ properties: {
1710
+ labels: {
1711
+ type: "array",
1712
+ items: {
1713
+ type: "object",
1714
+ properties: { i: { type: "integer" }, category: { type: "string", enum: [...CATEGORIES, "none"] } },
1715
+ required: ["i", "category"],
1716
+ additionalProperties: false
1717
+ }
1718
+ }
1719
+ },
1720
+ required: ["labels"],
1721
+ additionalProperties: false
1722
+ };
1723
+ function labelWithClaude(items) {
1724
+ const lines = items.map((item, i) => `${i} @${item.creator} ${item.caption.replace(/\s+/g, " ").slice(0, 400)}`).join(`
1725
+ `);
1726
+ const prompt = `Each line is an Instagram post: index, creator, caption. Label each one with what someone saving it would want to do later:
1727
+ ` + `recipe (cook it), place (go to a specific venue or city spot), experience (an event, trip or activity), product (buy it), workout (train with it), tip (learn a skill or trick).
1728
+ ` + `Use none for memes, jokes, news, music and anything else. Most posts are none.
1729
+
1730
+ ` + lines;
1731
+ const args = [
1732
+ "-p",
1733
+ "--model",
1734
+ "opus",
1735
+ "--effort",
1736
+ "low",
1737
+ "--tools",
1738
+ "",
1739
+ "--strict-mcp-config",
1740
+ "--setting-sources",
1741
+ "",
1742
+ "--no-session-persistence",
1743
+ "--system-prompt",
1744
+ "You sort Instagram posts into categories.",
1745
+ "--output-format",
1746
+ "json",
1747
+ "--json-schema",
1748
+ JSON.stringify(LABEL_SCHEMA)
1749
+ ];
1750
+ const result = spawnSync2("claude", args, { input: prompt, encoding: "utf8", cwd: tmpdir2(), timeout: 5 * 60 * 1000, maxBuffer: 16 * 1024 * 1024 });
1751
+ if (result.error)
1752
+ throw new Error("--llm needs Claude Code installed and logged in: https://code.claude.com");
1753
+ let reply;
1754
+ try {
1755
+ reply = JSON.parse(result.stdout);
1756
+ } catch {
1757
+ throw new Error(`claude -p failed: ${(result.stderr || result.stdout).trim().slice(0, 300)}`);
1758
+ }
1759
+ if (reply.is_error)
1760
+ throw new Error(`claude -p failed: ${String(reply.result ?? reply.subtype).slice(0, 300)}`);
1761
+ const labels = new Map;
1762
+ for (const { i, category } of reply.structured_output?.labels ?? []) {
1763
+ if (items[i])
1764
+ labels.set(items[i].code, category);
1765
+ }
1766
+ return labels;
1767
+ }
1768
+ function buildBacklog(db, anon, options) {
1769
+ fetchSavedCaptions(db, options.log);
1770
+ const candidates = [];
1771
+ for (const r of buildReels(db, anon)) {
1772
+ candidates.push({ code: r.code, link: `https://www.instagram.com/reel/${r.code}/`, caption: r.caption, creator: r.creator, ts: r.ts, source: r.from, chats: r.chats });
1773
+ }
1774
+ const saved = db.prepare("SELECT s.code AS code, s.link AS link, s.creator AS creator, s.ts AS ts, c.caption AS caption FROM saved s LEFT JOIN captions c ON c.code = s.code").all();
1775
+ const shared = new Set(candidates.map((c) => c.code));
1776
+ for (const s of saved) {
1777
+ if (shared.has(s.code))
1778
+ continue;
1779
+ candidates.push({ code: s.code, link: s.link, caption: s.caption ?? "", creator: s.creator ?? "", ts: s.ts, source: "saved", chats: [] });
1780
+ }
1781
+ const cached = new Map;
1782
+ for (const row of db.prepare("SELECT code, category FROM categories").all())
1783
+ cached.set(row.code, row.category);
1784
+ const items = [];
1785
+ const unplaced = [];
1786
+ for (const c of candidates) {
1787
+ const byRule = ruleCategory(c.caption);
1788
+ if (byRule)
1789
+ items.push({ ...c, category: byRule, by: "rules" });
1790
+ else if (cached.has(c.code)) {
1791
+ const category = cached.get(c.code);
1792
+ if (category !== "none")
1793
+ items.push({ ...c, category, by: "llm" });
1794
+ } else if (c.caption.trim() !== "")
1795
+ unplaced.push(c);
1796
+ }
1797
+ let llmLabelled = 0;
1798
+ if (options.llm && unplaced.length > 0) {
1799
+ const save = db.prepare("INSERT OR REPLACE INTO categories (code, category) VALUES (?, ?)");
1800
+ const byCode = new Map(candidates.map((c) => [c.code, c]));
1801
+ for (let start = 0;start < unplaced.length; start += 100) {
1802
+ options.log(`asking Claude about ${Math.min(start + 100, unplaced.length)}/${unplaced.length}`);
1803
+ const labels = labelWithClaude(unplaced.slice(start, start + 100));
1804
+ for (const [code, category] of labels) {
1805
+ save.run(code, category);
1806
+ llmLabelled++;
1807
+ if (category !== "none")
1808
+ items.push({ ...byCode.get(code), category, by: "llm" });
1809
+ }
1810
+ }
1811
+ }
1812
+ items.sort((a, b) => b.ts - a.ts);
1813
+ const stillUnplaced = options.llm ? unplaced.length - llmLabelled : unplaced.length;
1814
+ return { items, unplaced: stillUnplaced, llmLabelled };
1815
+ }
1816
+ var LABELS = {
1817
+ recipe: "To cook",
1818
+ place: "To go",
1819
+ experience: "To do",
1820
+ product: "To buy",
1821
+ workout: "To train",
1822
+ tip: "To learn"
1823
+ };
1824
+ var CSS5 = `
1825
+ .tabs { display: flex; flex-wrap: wrap; margin: 24px 0 8px; }
1826
+ .tabs button { margin: 0 -1px -1px 0; }
1827
+ .tabs button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
1828
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 36px 24px; margin-top: 24px; }
1829
+ .card { border-top: 2px solid var(--ink); padding-top: 10px; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
1830
+ .card .caption { margin: 0; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
1831
+ .card .meta { font-size: 15px; }
1832
+ .embed { min-height: 120px; }
1833
+ .embed blockquote { margin: 0 !important; min-width: 0 !important; width: 100% !important; }
1834
+ `;
1835
+ var SCRIPT5 = EMBED_SCRIPT + String.raw`
1836
+ const tabs = document.getElementById("tabs");
1837
+ const grid = document.getElementById("grid");
1838
+ let current = null;
1839
+
1840
+ function show(category) {
1841
+ current = category;
1842
+ for (const b of tabs.children) b.setAttribute("aria-pressed", String(b.dataset.category === category));
1843
+ grid.replaceChildren();
1844
+ for (const item of DATA.items.filter((i) => i.category === category)) {
1845
+ const card = el("article", "card");
1846
+ card.append(el("b", "", "@" + (item.creator || "unknown")));
1847
+ if (item.caption) card.append(el("p", "caption", item.caption));
1848
+ const when = new Date(item.ts).toLocaleDateString("en-US", { month: "short", year: "numeric" });
1849
+ const where = item.source === "saved" ? "you saved it" : item.source + " sent it in " + item.chats[0];
1850
+ card.append(el("div", "meta muted", where + " · " + when + (item.by === "llm" ? " · sorted by Claude" : "")));
1851
+ const embed = el("div", "embed");
1852
+ embed.dataset.link = item.link;
1853
+ card.append(embed);
1854
+ embedObserver.observe(embed);
1855
+ grid.append(card);
1856
+ }
1857
+ }
1858
+
1859
+ for (const [category, label] of Object.entries(DATA.labels)) {
1860
+ const count = DATA.items.filter((i) => i.category === category).length;
1861
+ if (count === 0) continue;
1862
+ const b = el("button", "", label + " " + count);
1863
+ b.dataset.category = category;
1864
+ b.onclick = () => show(category);
1865
+ tabs.append(b);
1866
+ }
1867
+ if (tabs.firstChild) show(tabs.firstChild.dataset.category);
1868
+ else grid.append(el("p", "muted", "Nothing to sort yet."));
1869
+ `;
1870
+ function backlogHtml(items) {
1871
+ const body = `<main id="root"><h1>Backlog</h1><p class="muted">Shared reels and saved posts, sorted by the words in their captions.</p><nav id="tabs" class="tabs"></nav><section id="grid" class="grid"></section></main>`;
1872
+ return page("Backlog", CSS5, { items, labels: LABELS }, SCRIPT5, body);
1873
+ }
1874
+ // package.json
1875
+ var package_default = {
1876
+ name: "@nitrimandylis/leftonread",
1877
+ version: "0.3.1",
1878
+ description: "Turn your Instagram data export into a per-chat Wrapped and a ranked archive of every reel you traded. Runs locally.",
1879
+ license: "MIT",
1880
+ type: "module",
1881
+ bin: {
1882
+ lor: "dist/lor.js"
1883
+ },
1884
+ files: [
1885
+ "dist",
1886
+ "man",
1887
+ "README.md",
1888
+ "LICENSE"
1889
+ ],
1890
+ man: [
1891
+ "man/lor.1"
1892
+ ],
1893
+ engines: {
1894
+ node: ">=24"
1895
+ },
1896
+ keywords: [
1897
+ "instagram",
1898
+ "export",
1899
+ "wrapped",
1900
+ "reels",
1901
+ "dm",
1902
+ "cli"
1903
+ ],
1904
+ repository: {
1905
+ type: "git",
1906
+ url: "git+https://github.com/nitrimandylis/leftonread.git"
1907
+ },
1908
+ publishConfig: {
1909
+ access: "public"
1910
+ },
1911
+ scripts: {
1912
+ build: "bun build leftonread.ts --target=node --format=esm --outfile dist/lor.js",
1913
+ prepack: "bun run build",
1914
+ test: "bun test",
1915
+ typecheck: "tsc --noEmit",
1916
+ compile: "bun build --compile leftonread.ts --outfile ~/.bun/bin/lor && mkdir -p $(brew --prefix)/share/man/man1 && cp man/lor.1 $(brew --prefix)/share/man/man1/ && ([ -d ~/.claude/skills ] && cp -R leftonread-cli ~/.claude/skills/ || true)"
1917
+ },
1918
+ devDependencies: {
1919
+ "@types/bun": "^1.3.14",
1920
+ "@types/node": "^24",
1921
+ typescript: "^5"
1922
+ }
1923
+ };
1924
+
1925
+ // leftonread.ts
1926
+ var HELP = `lor ${package_default.version}: your Instagram export, turned into pages you actually open.
1927
+ Everything runs locally. Nothing leaves your machine.
1928
+
1929
+ Usage:
1930
+ lor ingest <zip|folder>... read an export (all zip parts at once is fine)
1931
+ lor chats list chats and message counts
1932
+ lor wrapped [--chat name] per-chat Wrapped with story slides (Save PNG)
1933
+ lor reels every shared reel, ranked by how it landed
1934
+ lor keepsake --chat name a printable A5 booklet of one chat's best moments
1935
+ lor taste the creators you and each friend send, and who got whom into them
1936
+ lor backlog [--llm] reels and saved posts to cook, visit, do, buy, train, learn
1937
+
1938
+ Options:
1939
+ --db <path> database file (default ~/.config/leftonread/data.db)
1940
+ --out <path> where the page is written (default ~/.config/leftonread/)
1941
+ --no-open write the HTML but do not open the browser
1942
+ --anon replace other people's names in pages and output
1943
+ --llm backlog: let Claude sort what the rules cannot, through
1944
+ claude -p (sends public captions only)
1945
+ --json print one JSON value instead of the summary
1946
+ -h, --help show this help
1947
+ -v, --version show the version
1948
+
1949
+ Get the export: Instagram > Accounts Center > Your information and permissions >
1950
+ Download your information. Pick Messages (and Saved, for backlog), format JSON, any date range.`;
1951
+
1952
+ class UsageError extends Error {
1953
+ }
1954
+ function fail(message, code = 1) {
1955
+ console.error(`lor: ${message}`);
1956
+ process.exit(code);
1957
+ }
1958
+ function openInBrowser(path) {
1959
+ let command = "xdg-open";
1960
+ let args = [path];
1961
+ if (process.platform === "darwin")
1962
+ command = "open";
1963
+ if (process.platform === "win32") {
1964
+ command = "cmd";
1965
+ args = ["/c", "start", "", path];
1966
+ }
1967
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
1968
+ child.on("error", () => console.error(`lor: could not open a browser. Open ${path} yourself.`));
1969
+ child.unref();
1970
+ }
1971
+ function requireDb(path) {
1972
+ if (!existsSync2(path))
1973
+ fail(`no data yet. Run: lor ingest <your-export.zip>`);
1974
+ return openDb(path);
1975
+ }
1976
+ var FLAGS = {
1977
+ db: { type: "string" },
1978
+ out: { type: "string" },
1979
+ chat: { type: "string" },
1980
+ "no-open": { type: "boolean" },
1981
+ anon: { type: "boolean" },
1982
+ llm: { type: "boolean" },
1983
+ json: { type: "boolean" },
1984
+ help: { type: "boolean", short: "h" },
1985
+ version: { type: "boolean", short: "v" }
1986
+ };
1987
+ var ALLOWED = {
1988
+ ingest: [],
1989
+ chats: [],
1990
+ wrapped: ["out", "chat", "no-open", "anon"],
1991
+ reels: ["out", "no-open", "anon"],
1992
+ keepsake: ["out", "chat", "no-open", "anon"],
1993
+ taste: ["out", "no-open", "anon"],
1994
+ backlog: ["out", "no-open", "anon", "llm"]
1995
+ };
1996
+ function save(path, html) {
1997
+ mkdirSync3(dirname2(path), { recursive: true });
1998
+ writeFileSync(path, html);
1999
+ }
2000
+ function writePage(path, html, json, noOpen) {
2001
+ save(path, html);
2002
+ if (json)
2003
+ return;
2004
+ console.log(path);
2005
+ if (!noOpen)
2006
+ openInBrowser(path);
2007
+ }
2008
+ function main(argv) {
2009
+ let parsed;
2010
+ try {
2011
+ parsed = parseArgs({ args: argv, options: FLAGS, allowPositionals: true, strict: true });
2012
+ } catch (error) {
2013
+ fail(`${error.message}
2014
+ Run lor --help for usage.`, 2);
2015
+ }
2016
+ const { values, positionals } = parsed;
2017
+ if (values.help) {
2018
+ console.log(HELP);
2019
+ return;
2020
+ }
2021
+ if (values.version) {
2022
+ console.log(package_default.version);
2023
+ return;
2024
+ }
2025
+ const [command, ...rest] = positionals;
2026
+ if (!command) {
2027
+ console.log(HELP);
2028
+ return;
2029
+ }
2030
+ if (!(command in ALLOWED))
2031
+ fail(`unknown command "${command}". Run lor --help.`, 2);
2032
+ for (const flag of ["out", "chat", "no-open", "anon", "llm"]) {
2033
+ if (values[flag] !== undefined && !ALLOWED[command].includes(flag))
2034
+ fail(`--${flag} does not apply to ${command}.`, 2);
2035
+ }
2036
+ if (command !== "ingest" && rest.length > 0)
2037
+ fail(`${command} takes no arguments, got "${rest[0]}".`, 2);
2038
+ const dbPath = resolve2(values.db ?? DEFAULT_DB);
2039
+ const json = values.json === true;
2040
+ try {
2041
+ if (command === "ingest") {
2042
+ if (rest.length === 0)
2043
+ throw new UsageError("ingest needs at least one export zip or folder.");
2044
+ const summary = ingest(rest, dbPath);
2045
+ if (json)
2046
+ console.log(JSON.stringify(summary));
2047
+ else {
2048
+ console.log(`Read ${summary.files} files: ${summary.added.toLocaleString("en-US")} new messages.`);
2049
+ console.log(`${summary.chats} chats, ${summary.messages.toLocaleString("en-US")} messages, ${summary.reels.toLocaleString("en-US")} reels, ${summary.saved.toLocaleString("en-US")} saved posts. Owner: ${summary.owner ?? "unknown"}.`);
2050
+ console.log(`Saved to ${summary.db}. Next: lor wrapped, lor reels, lor keepsake --chat <name>`);
2051
+ }
2052
+ return;
2053
+ }
2054
+ const db = requireDb(dbPath);
2055
+ if (command === "chats") {
2056
+ const { overview } = buildWrapped(db, false);
2057
+ if (json)
2058
+ console.log(JSON.stringify(overview.list));
2059
+ else
2060
+ for (const c of overview.list)
2061
+ console.log(`${String(c.total).padStart(8)} ${c.title}${c.isGroup ? " (group)" : ""}`);
2062
+ return;
2063
+ }
2064
+ if (command === "wrapped") {
2065
+ const { overview, chats } = buildWrapped(db, values.anon === true);
2066
+ let initial = null;
2067
+ if (values.chat !== undefined) {
2068
+ const wanted = values.chat.toLowerCase();
2069
+ const real = values.anon ? buildWrapped(db, false).chats : chats;
2070
+ const match = real.find((c) => c.them.toLowerCase().includes(wanted));
2071
+ if (!match)
2072
+ throw new UsageError(`no chat matches "${values.chat}". Run lor chats.`);
2073
+ initial = chats.find((c) => c.id === match.id) ?? null;
2074
+ }
2075
+ const path = resolve2(values.out ?? join3(DATA_DIR, "wrapped.html"));
2076
+ save(path, wrappedHtml({ overview, chats, initial: initial ? initial.id : null }));
2077
+ if (json) {
2078
+ console.log(JSON.stringify(initial ? { path, chat: initial } : { path, overview, chats }));
2079
+ } else {
2080
+ const top = chats[0];
2081
+ console.log(`${overview.messages.toLocaleString("en-US")} messages across ${overview.chats} chats.`);
2082
+ if (initial)
2083
+ console.log(`${initial.isGroup ? initial.them : "You & " + initial.them}: ${initial.total.toLocaleString("en-US")} messages, longest streak ${initial.streak.days} days.`);
2084
+ else if (top)
2085
+ console.log(`Top chat: ${top.them}, ${top.total.toLocaleString("en-US")} messages.`);
2086
+ console.log(path);
2087
+ }
2088
+ if (!values["no-open"] && !json)
2089
+ openInBrowser(path);
2090
+ return;
2091
+ }
2092
+ if (command === "reels") {
2093
+ const reels = buildReels(db, values.anon === true);
2094
+ const path = resolve2(values.out ?? join3(DATA_DIR, "reels.html"));
2095
+ save(path, reelsHtml(reels));
2096
+ if (json) {
2097
+ console.log(JSON.stringify({ path, total: reels.length, top: reels.slice(0, 20) }));
2098
+ } else {
2099
+ console.log(`${reels.length.toLocaleString("en-US")} reels ranked.`);
2100
+ for (const r of reels.slice(0, 5)) {
2101
+ console.log(` ${r.score.toFixed(1).padStart(5)} @${r.creator || "unknown"} ${r.caption.split(`
2102
+ `)[0].slice(0, 60)}`);
2103
+ }
2104
+ console.log(path);
2105
+ }
2106
+ if (!values["no-open"] && !json)
2107
+ openInBrowser(path);
2108
+ return;
2109
+ }
2110
+ const out = (name) => resolve2(values.out ?? join3(DATA_DIR, name));
2111
+ const noOpen = values["no-open"] === true;
2112
+ if (command === "keepsake") {
2113
+ if (values.chat === undefined)
2114
+ throw new UsageError("keepsake needs --chat <name>. Run lor chats.");
2115
+ const wanted = values.chat.toLowerCase();
2116
+ const match = buildWrapped(db, false).overview.list.find((c) => c.title.toLowerCase().includes(wanted));
2117
+ if (!match)
2118
+ throw new UsageError(`no chat matches "${values.chat}". Run lor chats.`);
2119
+ const keepsake = buildKeepsake(db, match.id, values.anon === true, join3(dirname2(dbPath), "media"));
2120
+ const path = out("keepsake.html");
2121
+ const counts = keepsake.chapters.map((c) => ({ chapter: c.title, moments: c.moments.length }));
2122
+ if (json)
2123
+ console.log(JSON.stringify({ path, title: keepsake.title, chapters: counts }));
2124
+ else {
2125
+ console.log(`${keepsake.title}: ${counts.map((c) => `${c.chapter} ${c.moments}`).join(", ")}.`);
2126
+ console.log("Keep or drop moments, add captions, then Save PDF.");
2127
+ }
2128
+ writePage(path, keepsakeHtml(keepsake), json, noOpen);
2129
+ return;
2130
+ }
2131
+ if (command === "taste") {
2132
+ const taste = buildTaste(db, values.anon === true);
2133
+ const path = out("taste.html");
2134
+ if (json)
2135
+ console.log(JSON.stringify({ path, ...taste }));
2136
+ else {
2137
+ for (const f of taste.friends.slice(0, 5)) {
2138
+ console.log(` ${f.name}: ${Math.round(100 * f.overlap)}% overlap, got you into ${f.gotYouInto.length}, you got them into ${f.youGotThemInto.length}`);
2139
+ }
2140
+ }
2141
+ writePage(path, tasteHtml(taste), json, noOpen);
2142
+ return;
2143
+ }
2144
+ if (command === "backlog") {
2145
+ const backlog = buildBacklog(db, values.anon === true, {
2146
+ llm: values.llm === true,
2147
+ log: (line) => process.stderr.write(`\r${line} `)
2148
+ });
2149
+ process.stderr.write("\r");
2150
+ const path = out("backlog.html");
2151
+ const counts = {};
2152
+ for (const item of backlog.items)
2153
+ counts[item.category] = (counts[item.category] ?? 0) + 1;
2154
+ if (json)
2155
+ console.log(JSON.stringify({ path, counts, unplaced: backlog.unplaced, items: backlog.items }));
2156
+ else {
2157
+ console.log(Object.entries(counts).map(([c, n]) => `${n} ${c}`).join(", ") || "Nothing sorted.");
2158
+ if (!values.llm && backlog.unplaced > 0)
2159
+ console.log(`${backlog.unplaced.toLocaleString("en-US")} captions the rules could not place. --llm lets Claude try.`);
2160
+ }
2161
+ writePage(path, backlogHtml(backlog.items), json, noOpen);
2162
+ return;
2163
+ }
2164
+ } catch (error) {
2165
+ fail(error.message, error instanceof UsageError ? 2 : 1);
2166
+ }
2167
+ }
2168
+ function isEntry() {
2169
+ const script = process.argv[1];
2170
+ if (!script)
2171
+ return false;
2172
+ const self = fileURLToPath(import.meta.url);
2173
+ if (script === self)
2174
+ return true;
2175
+ try {
2176
+ return realpathSync(script) === realpathSync(self);
2177
+ } catch {
2178
+ return false;
2179
+ }
2180
+ }
2181
+ if (isEntry())
2182
+ main(process.argv.slice(2));
2183
+ export {
2184
+ main
2185
+ };