@appeeky/open-slideshow 0.1.0 → 0.2.0

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 (55) hide show
  1. package/README.md +93 -23
  2. package/dist/bin.js +0 -0
  3. package/dist/brand.d.ts +2 -0
  4. package/dist/brand.js +36 -19
  5. package/dist/brandkit.d.ts +50 -0
  6. package/dist/brandkit.js +212 -0
  7. package/dist/cli.js +94 -0
  8. package/dist/decks.js +11 -1
  9. package/dist/ideas.d.ts +50 -0
  10. package/dist/ideas.js +146 -0
  11. package/dist/images.d.ts +15 -2
  12. package/dist/images.js +23 -5
  13. package/dist/index.d.ts +9 -0
  14. package/dist/index.js +9 -0
  15. package/dist/lint.d.ts +5 -2
  16. package/dist/lint.js +18 -2
  17. package/dist/mcp.js +72 -2
  18. package/dist/preview.d.ts +18 -0
  19. package/dist/preview.js +96 -0
  20. package/dist/publish.d.ts +5 -0
  21. package/dist/publish.js +6 -1
  22. package/dist/readability.d.ts +19 -0
  23. package/dist/readability.js +42 -0
  24. package/dist/render.d.ts +21 -2
  25. package/dist/render.js +143 -11
  26. package/dist/results.d.ts +89 -0
  27. package/dist/results.js +252 -0
  28. package/dist/schema.d.ts +166 -11
  29. package/dist/schema.js +38 -1
  30. package/dist/screenshots.d.ts +18 -0
  31. package/dist/screenshots.js +69 -0
  32. package/dist/templates.d.ts +4 -1
  33. package/dist/templates.js +145 -0
  34. package/dist/text.js +2 -1
  35. package/dist/variants.d.ts +48 -0
  36. package/dist/variants.js +175 -0
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/dist/video.d.ts +22 -0
  40. package/dist/video.js +59 -0
  41. package/dist/workspace.d.ts +5 -0
  42. package/dist/workspace.js +16 -0
  43. package/package.json +1 -1
  44. package/skills/open-slideshow/SKILL.md +16 -3
  45. package/skills/open-slideshow/references/brand.md +10 -0
  46. package/skills/open-slideshow/references/ideas.md +23 -0
  47. package/skills/open-slideshow/references/images.md +9 -1
  48. package/skills/open-slideshow/references/languages.md +10 -0
  49. package/skills/open-slideshow/references/results.md +47 -0
  50. package/skills/open-slideshow/references/review.md +8 -1
  51. package/skills/open-slideshow/references/screenshots.md +26 -0
  52. package/skills/open-slideshow/references/series.md +20 -0
  53. package/skills/open-slideshow/references/templates.md +37 -0
  54. package/skills/open-slideshow/references/troubleshooting.md +11 -1
  55. package/skills/open-slideshow/references/video.md +18 -0
package/dist/render.js CHANGED
@@ -5,11 +5,11 @@ import { join } from "node:path";
5
5
  import satori from "satori";
6
6
  import { Resvg } from "@resvg/resvg-js";
7
7
  import sharp from "sharp";
8
- import { satoriFonts, missingChars, glyphReport, fontStack, ensureScriptFonts, SCRIPTS, pickFont } from "./fonts.js";
8
+ import { satoriFonts, missingChars, glyphReport, fontStack, ensureScriptFonts, SCRIPTS, pickFont, measure } from "./fonts.js";
9
9
  import { COMPLEX, shaperReady, shapeLine } from "./shape.js";
10
10
  import { fit, plainText, upperCase, isRtl } from "./text.js";
11
11
  import { SIZES } from "./schema.js";
12
- import { getTheme, withColors, readableOn, mix } from "./themes.js";
12
+ import { getTheme, withColors, readableOn, mix, luminance } from "./themes.js";
13
13
  export const RENDERER_VERSION = "1";
14
14
  const el = (type, style, children, extra = {}) => ({
15
15
  type,
@@ -154,6 +154,8 @@ function blockEl(b, theme, style, align) {
154
154
  }
155
155
  return div({ marginTop: b.gap_before, flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start" }, lines);
156
156
  }
157
+ /** Body text under this size (on a 1080-wide slide) is hard to read on a phone. */
158
+ export const SMALL_TEXT = 38;
157
159
  const blocksHeight = (blocks) => blocks.reduce((h, b) => h + b.gap_before + b.fitted.height, 0);
158
160
  /** Fits a slide's words into the box: the title gets what is left after the smaller text. */
159
161
  function planText(slide, index, tipNumber, theme, box, color, muted, scale) {
@@ -199,6 +201,8 @@ function planText(slide, index, tipNumber, theme, box, color, muted, scale) {
199
201
  }
200
202
  blocks.push(...lower);
201
203
  for (const b of blocks) {
204
+ if (!b.fitted.overflow && (b.kind === "body" || b.kind === "item") && b.fitted.size < SMALL_TEXT)
205
+ issues.push({ slide: index, level: "warning", code: "small-text", message: `slide ${index + 1}: the ${b.kind === "item" ? "list" : "body"} is drawn at ${b.fitted.size}px, small on a phone; cut words so it can be bigger` });
202
206
  if (b.fitted.overflow)
203
207
  issues.push({ slide: index, level: "error", code: "text-overflow", message: `slide ${index + 1}: the ${b.kind} does not fit even at the smallest size; shorten it` });
204
208
  else if (b.fitted.broke_word)
@@ -210,6 +214,9 @@ function planText(slide, index, tipNumber, theme, box, color, muted, scale) {
210
214
  }
211
215
  // ---------- images ----------
212
216
  async function cropTo(file, w, h, focus) {
217
+ return `data:image/jpeg;base64,${(await cropBuffer(file, w, h, focus)).toString("base64")}`;
218
+ }
219
+ async function cropBuffer(file, w, h, focus) {
213
220
  const img = sharp(file, { limitInputPixels: 80_000_000 }).rotate();
214
221
  const meta = await sharp(await img.toBuffer()).metadata();
215
222
  const iw = meta.width ?? w;
@@ -221,8 +228,33 @@ async function cropTo(file, w, h, focus) {
221
228
  const fy = (focus?.y ?? 50) / 100;
222
229
  const left = Math.min(Math.max(0, Math.round(sw * fx - w / 2)), sw - w);
223
230
  const top = Math.min(Math.max(0, Math.round(sh * fy - h / 2)), sh - h);
224
- const out = await sharp(file, { limitInputPixels: 80_000_000 }).rotate().resize(sw, sh).extract({ left, top, width: w, height: h }).jpeg({ quality: 90 }).toBuffer();
225
- return `data:image/jpeg;base64,${out.toString("base64")}`;
231
+ return sharp(file, { limitInputPixels: 80_000_000 }).rotate().resize(sw, sh).extract({ left, top, width: w, height: h }).jpeg({ quality: 90 }).toBuffer();
232
+ }
233
+ /**
234
+ * How well white words read over the part of the photo behind them: the photo's brightness there
235
+ * (after the theme's darkening) and how busy it is. Outline and box styles carry their own contrast.
236
+ */
237
+ async function photoReadability(photo, rects, W, H, scrim, style, index) {
238
+ if (!rects.length || style === "outline" || style === "box")
239
+ return [];
240
+ const x0 = Math.max(0, Math.min(...rects.map((r) => r.x0)));
241
+ const y0 = Math.max(0, Math.min(...rects.map((r) => r.y0)));
242
+ const x1 = Math.min(W, Math.max(...rects.map((r) => r.x1)));
243
+ const y1 = Math.min(H, Math.max(...rects.map((r) => r.y1)));
244
+ if (x1 - x0 < 8 || y1 - y0 < 8)
245
+ return [];
246
+ const stats = await sharp(photo).extract({ left: x0, top: y0, width: x1 - x0, height: y1 - y0 }).greyscale().stats();
247
+ const ch = stats.channels[0];
248
+ const keep = 1 - scrim;
249
+ const grey = Math.round(ch.mean * keep);
250
+ const hex = `#${grey.toString(16).padStart(2, "0").repeat(3)}`;
251
+ const ratio = 1.05 / (luminance(hex) + 0.05);
252
+ const issues = [];
253
+ if (ratio < 2.6)
254
+ issues.push({ slide: index, level: "warning", code: "photo-contrast", message: `slide ${index + 1}: the photo behind the words is bright (contrast ${ratio.toFixed(1)}:1); use text_style outline or box, move the words (text_position) or the photo (focus), or pick a darker photo` });
255
+ else if (ch.stdev * keep > 72)
256
+ issues.push({ slide: index, level: "warning", code: "busy-photo", message: `slide ${index + 1}: the photo behind the words is busy; the words may be hard to read. Try text_style outline or box, or move them to a calmer part (text_position)` });
257
+ return issues;
226
258
  }
227
259
  function readImage(ctx, path) {
228
260
  const cached = ctx.images?.get(path);
@@ -255,6 +287,28 @@ function handleText(ctx) {
255
287
  return undefined;
256
288
  return h.startsWith("@") ? h : `@${h}`;
257
289
  }
290
+ function lineWidth(b, line) {
291
+ const text = line.map((r) => r.text).join("");
292
+ return measure(b.role, b.role.uppercase ? upperCase(text, b.locale) : text, b.fitted.size, b.locale);
293
+ }
294
+ /** The rectangles of all lines of the blocks, laid out from (left, top) in a column `width` wide. */
295
+ function lineRects(blocks, left, top, width, align) {
296
+ const out = [];
297
+ let y = top;
298
+ for (const b of blocks) {
299
+ y += b.gap_before;
300
+ const lh = b.fitted.size * b.line_height;
301
+ const marker = b.marker !== undefined ? Math.round(b.fitted.size * 1.3) : 0;
302
+ for (const line of b.fitted.lines) {
303
+ const w = Math.min(width, lineWidth(b, line) + marker);
304
+ const rtl = isRtl(line.map((r) => r.text).join(""));
305
+ const x0 = align === "center" ? left + (width - w) / 2 : rtl ? left + width - w : left;
306
+ out.push({ x0: Math.round(x0), y0: Math.round(y), x1: Math.round(x0 + w), y1: Math.round(y + lh) });
307
+ y += lh;
308
+ }
309
+ }
310
+ return out;
311
+ }
258
312
  async function photoLayout(ctx, a, f) {
259
313
  const t = ctx.theme;
260
314
  const style = a.slide.text_style ?? a.deck.text_style ?? t.text_style;
@@ -264,7 +318,9 @@ async function photoLayout(ctx, a, f) {
264
318
  const plan = planText(a.slide, a.index, a.tipNumber, t, { width, height: safe - (a.slide.kind === "app" ? BADGE_H : 0), locale: ctx.locale }, style === "box" ? t.colors.fg : "#ffffff", style === "box" ? t.colors.muted : "#f0f0f0", 1);
265
319
  const issues = [...plan.issues];
266
320
  const children = [];
267
- const img = a.dry ? null : await imageEl(ctx, a.slide, f.W, f.H, { position: "absolute", left: 0, top: 0 });
321
+ const path = !a.dry && a.slide.image ? ctx.resolveImage(a.slide.image) : null;
322
+ const photo = path ? await cropBuffer(readImage(ctx, path), f.W, f.H, a.slide.focus) : null;
323
+ const img = photo ? el("img", { width: f.W, height: f.H, position: "absolute", left: 0, top: 0 }, undefined, { src: `data:image/jpeg;base64,${photo.toString("base64")}`, width: f.W, height: f.H }) : null;
268
324
  if (img)
269
325
  children.push(img);
270
326
  else {
@@ -283,7 +339,10 @@ async function photoLayout(ctx, a, f) {
283
339
  children.push(div({ position: "absolute", left: f.pad, top: Math.max(f.top, top), width, flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start" }, [...plan.blocks.map((b) => blockEl(b, t, style, align)), ...(a.slide.kind === "app" ? [await appBadge(ctx, f, t, "dark")] : [])]));
284
340
  if (a.deck.show_handle && handleText(ctx))
285
341
  children.push(div({ position: "absolute", left: f.pad, top: Math.round(f.top * 0.45), fontFamily: fontStack("Inter"), fontWeight: 600, fontSize: 30, color: "#ffffff", opacity: 0.85, textShadow: "0 2px 8px rgba(0,0,0,0.5)" }, handleText(ctx)));
286
- return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
342
+ const lines = lineRects(plan.blocks, f.pad, Math.max(f.top, top), width, align);
343
+ if (photo)
344
+ issues.push(...(await photoReadability(photo, lines, f.W, f.H, t.align === "left" ? t.scrim * 0.6 : t.scrim, style, a.index)));
345
+ return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues, lines };
287
346
  }
288
347
  const BADGE_H = 196;
289
348
  async function appBadge(ctx, f, t, tone) {
@@ -323,7 +382,7 @@ async function magazineLayout(ctx, a, f) {
323
382
  const fadeStart = Math.max(0, top - 260);
324
383
  children.push(div({ position: "absolute", left: 0, top: fadeStart, width: f.W, height: f.H - fadeStart, backgroundImage: `linear-gradient(180deg, ${t.colors.bg}00 0%, ${t.colors.bg}e6 38%, ${t.colors.bg} 60%)` }));
325
384
  children.push(div({ position: "absolute", left: f.pad, top, width, flexDirection: "column" }, plan.blocks.map((b) => blockEl(b, t, "plain", "left"))));
326
- return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
385
+ return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues, lines: lineRects(plan.blocks, f.pad, top, width, "left") };
327
386
  }
328
387
  const safeTop = f.top + (header ? 40 : 0);
329
388
  const safe = f.H - safeTop - f.bottom;
@@ -345,7 +404,7 @@ async function magazineLayout(ctx, a, f) {
345
404
  children.push(div({ position: "absolute", left: f.pad, top: imgTop, width, height: imageHeight, borderRadius: 32, backgroundColor: t.colors.card }));
346
405
  }
347
406
  }
348
- return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
407
+ return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues, lines: lineRects(plan.blocks, f.pad, textTop, width, "left") };
349
408
  }
350
409
  async function plainLayout(ctx, a, f) {
351
410
  const t = ctx.theme;
@@ -377,8 +436,69 @@ async function plainLayout(ctx, a, f) {
377
436
  return {
378
437
  tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, [div({ position: "absolute", left: f.pad, top, width, flexDirection: "column" }, content)]),
379
438
  issues,
439
+ lines: lineRects(plan.blocks, f.pad, top + headerH + 40, width, "left"),
380
440
  };
381
441
  }
442
+ /** Screen width / height of a phone screenshot when the real one cannot be read (dry runs). */
443
+ const PHONE_ASPECT = 1179 / 2556;
444
+ /** A screenshot of the app inside a phone, with the title (and body) above it. */
445
+ async function screenshotLayout(ctx, a, f) {
446
+ const t = ctx.theme;
447
+ const width = f.W - f.pad * 2;
448
+ const safe = f.H - f.top - f.bottom;
449
+ const issues = [];
450
+ const onPhoto = t.design === "photo";
451
+ const fg = onPhoto ? "#ffffff" : t.colors.fg;
452
+ const muted = onPhoto ? "#eeeeee" : t.colors.muted;
453
+ const align = t.design === "photo" ? t.align : "left";
454
+ const hasText = !!(a.slide.title || a.slide.body);
455
+ const plan = hasText ? planText(a.slide, a.index, undefined, t, { width, height: Math.round(safe * 0.3), locale: ctx.locale }, fg, muted, 0.9) : { blocks: [], issues: [] };
456
+ issues.push(...plan.issues);
457
+ const textH = blocksHeight(plan.blocks);
458
+ const gap = hasText ? 44 : 0;
459
+ const path = !a.dry && a.slide.image ? ctx.resolveImage(a.slide.image) : null;
460
+ if (a.slide.image && !a.dry && !path)
461
+ issues.push({ slide: a.index, level: "error", code: "image-missing", message: `slide ${a.index + 1}: image ${a.slide.image} not found` });
462
+ let aspect = PHONE_ASPECT;
463
+ if (path) {
464
+ const m = await sharp(readImage(ctx, path)).metadata();
465
+ if (m.width && m.height)
466
+ aspect = Math.min(Math.max(m.width / m.height, 0.4), 0.8);
467
+ }
468
+ let outerH = Math.floor(safe - textH - gap);
469
+ const bezel = Math.max(10, Math.round(outerH * 0.018));
470
+ let innerH = outerH - bezel * 2;
471
+ let innerW = Math.round(innerH * aspect);
472
+ if (innerW + bezel * 2 > width) {
473
+ innerW = width - bezel * 2;
474
+ innerH = Math.round(innerW / aspect);
475
+ outerH = innerH + bezel * 2;
476
+ }
477
+ const outerW = innerW + bezel * 2;
478
+ if (innerH < 400)
479
+ issues.push({ slide: a.index, level: "warning", code: "small-screenshot", message: `slide ${a.index + 1}: the screenshot is small; shorten the text above it` });
480
+ const radius = Math.round(outerW * 0.12);
481
+ const screen = path
482
+ ? el("img", { position: "absolute", left: bezel, top: bezel, width: innerW, height: innerH, borderRadius: Math.max(8, radius - bezel) }, undefined, { src: await cropTo(readImage(ctx, path), innerW, innerH), width: innerW, height: innerH })
483
+ : div({ position: "absolute", left: bezel, top: bezel, width: innerW, height: innerH, borderRadius: Math.max(8, radius - bezel), backgroundColor: mix(t.colors.bg, "#888888", 0.4) });
484
+ const phone = div({ position: "relative", width: outerW, height: outerH, flexShrink: 0, borderRadius: radius, backgroundColor: "#0b0b0c" }, [screen]);
485
+ const top = f.top + Math.max(0, Math.round((safe - textH - gap - outerH) / 2));
486
+ const bg = onPhoto ? div({ position: "absolute", left: 0, top: 0, width: f.W, height: f.H, backgroundImage: `linear-gradient(160deg, ${mix(t.colors.bg, t.colors.accent, 0.35)}, ${t.colors.bg})` }) : null;
487
+ const column = div({ position: "absolute", left: f.pad, top, width, flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start" }, [
488
+ ...plan.blocks.map((b) => blockEl(b, t, onPhoto ? (t.text_style === "box" ? "plain" : t.text_style) : "plain", align)),
489
+ div({ marginTop: gap, width, justifyContent: "center" }, [phone]),
490
+ ]);
491
+ return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, [...(bg ? [bg] : []), column]), issues, lines: lineRects(plan.blocks, f.pad, top, width, align) };
492
+ }
493
+ /** "Part 2", "Part 2/5" or the series' own label, filled in. */
494
+ export function seriesLabel(s) {
495
+ const fill = (x) => x.replace(/\{part\}/g, String(s.part)).replace(/\{of\}/g, s.of ? String(s.of) : "");
496
+ return s.label ? fill(s.label) : `Part ${s.part}${s.of ? `/${s.of}` : ""}`;
497
+ }
498
+ function seriesPill(ctx, f, s) {
499
+ const t = ctx.theme;
500
+ return div({ position: "absolute", right: f.pad, top: f.top, backgroundColor: t.colors.accent, color: readableOn(t.colors.accent), borderRadius: 999, padding: "10px 26px", fontFamily: fontStack("Inter"), fontWeight: 700, fontSize: 34 }, seriesLabel(s));
501
+ }
382
502
  export function tipNumbers(slides) {
383
503
  let n = 0;
384
504
  return slides.map((s) => (s.kind === "tip" ? (n = s.number ?? n + 1) : undefined));
@@ -387,7 +507,15 @@ export async function laySlide(ctx, a) {
387
507
  const f = frameFor(ctx.size);
388
508
  const all = [a.slide.title, a.slide.body, ...(a.slide.items ?? []), a.slide.author, ctx.brand.name, ctx.brand.handle].filter(Boolean).join(" ");
389
509
  const failed = await ensureScriptFonts(all, ctx.locale);
390
- const laid = ctx.theme.design === "photo" ? await photoLayout(ctx, a, f) : ctx.theme.design === "magazine" ? await magazineLayout(ctx, a, f) : await plainLayout(ctx, a, f);
510
+ const laid = a.slide.kind === "screenshot"
511
+ ? await screenshotLayout(ctx, a, f)
512
+ : ctx.theme.design === "photo"
513
+ ? await photoLayout(ctx, a, f)
514
+ : ctx.theme.design === "magazine"
515
+ ? await magazineLayout(ctx, a, f)
516
+ : await plainLayout(ctx, a, f);
517
+ if (a.deck.series && a.slide.kind === "cover")
518
+ laid.tree.props.children.push(seriesPill(ctx, f, a.deck.series));
391
519
  const text = [a.slide.title, a.slide.body, ...(a.slide.items ?? []), a.slide.author].filter(Boolean).map((s) => plainText(s)).join(" ");
392
520
  const roles = [ctx.theme.display, ctx.theme.body];
393
521
  const reports = roles.map((r) => glyphReport(r, ctx.theme.display.uppercase && r === ctx.theme.display ? upperCase(text, ctx.locale) : text, ctx.locale));
@@ -456,7 +584,7 @@ export function themeFor(deck) {
456
584
  export function renderHash(deck, ctx) {
457
585
  const h = createHash("sha256");
458
586
  h.update(RENDERER_VERSION);
459
- h.update(JSON.stringify({ size: deck.size, theme: ctx.theme, full_cover: deck.full_cover, text_style: deck.text_style, show_handle: deck.show_handle, slides: deck.slides, brand: { n: ctx.brand.name, h: ctx.brand.handle } }));
587
+ h.update(JSON.stringify({ size: deck.size, theme: ctx.theme, full_cover: deck.full_cover, text_style: deck.text_style, show_handle: deck.show_handle, slides: deck.slides, brand: { n: ctx.brand.name, h: ctx.brand.handle }, series: deck.series }));
460
588
  const images = [...deck.slides.map((s) => s.image), ctx.brand.icon].filter(Boolean);
461
589
  for (const ref of images) {
462
590
  const p = ref === ctx.brand.icon ? ref : ctx.resolveImage(ref);
@@ -474,9 +602,11 @@ export async function renderDeck(deck, ctx, outDir) {
474
602
  const files = [];
475
603
  const issues = [];
476
604
  const buffers = [];
605
+ const lines = [];
477
606
  for (let i = 0; i < deck.slides.length; i++) {
478
607
  const laid = await laySlide(ctx, { deck, slide: deck.slides[i], index: i, tipNumber: numbers[i] });
479
608
  issues.push(...laid.issues);
609
+ lines.push(laid.lines);
480
610
  const jpg = await rasterize(laid.tree, deck.size);
481
611
  const name = `${String(i + 1).padStart(2, "0")}.jpg`;
482
612
  writeFileSync(join(outDir, name), jpg);
@@ -488,7 +618,9 @@ export async function renderDeck(deck, ctx, outDir) {
488
618
  if (/^\d{2}\.jpg$/.test(f) && !files.includes(f))
489
619
  unlinkSync(join(outDir, f));
490
620
  writeFileSync(join(outDir, "sheet.jpg"), await contactSheet(buffers, deck.size));
491
- return { files, sheet: "sheet.jpg", hash: renderHash(deck, ctx), issues };
621
+ const { safeZoneSlide } = await import("./readability.js");
622
+ writeFileSync(join(outDir, "sheet-safe.jpg"), await contactSheet(await Promise.all(buffers.map((b) => safeZoneSlide(b, deck.size))), deck.size));
623
+ return { files, sheet: "sheet.jpg", safe_sheet: "sheet-safe.jpg", hash: renderHash(deck, ctx), issues, lines };
492
624
  }
493
625
  /** All slides side by side in one image, small, for a quick look. */
494
626
  export async function contactSheet(slides, size, columns = Math.min(slides.length, 5), labels) {
@@ -0,0 +1,89 @@
1
+ import type { Deck } from "./schema.js";
2
+ import { type Workspace } from "./workspace.js";
3
+ /** The numbers a result can carry. */
4
+ export declare const METRICS: readonly ["views", "likes", "comments", "shares", "saves", "reach"];
5
+ export type Metric = (typeof METRICS)[number];
6
+ export type Metrics = Partial<Record<Metric, number>>;
7
+ /** Fetches a post's numbers by its Appeeky post id. */
8
+ export type AnalyticsFetcher = (postId: string) => Promise<{
9
+ platform: string;
10
+ analytics: Record<string, unknown>;
11
+ }[]>;
12
+ export interface SyncReport {
13
+ updated: {
14
+ deck: string;
15
+ source: string;
16
+ platform?: string;
17
+ metrics: Metrics;
18
+ }[];
19
+ skipped: {
20
+ deck: string;
21
+ why: string;
22
+ }[];
23
+ }
24
+ /**
25
+ * Brings in how published decks did: from a Spec repo's posts.jsonl (after `appeeky-spec social pull`)
26
+ * for decks sent as Spec drafts, and from Appeeky for decks posted through it. Postiz, Photos and
27
+ * exports have no numbers here: record them with recordResult.
28
+ */
29
+ export declare function syncResults(ws: Workspace, fetcher?: AnalyticsFetcher, now?: Date): Promise<SyncReport>;
30
+ /** Numbers a person read off the app, for posts made with Photos, export or Postiz. */
31
+ export declare function recordResult(ws: Workspace, id: string, metrics: Metrics & {
32
+ platform?: string;
33
+ }, now?: Date): Deck;
34
+ /** A deck's totals over every platform it went to. */
35
+ export declare function totals(deck: Deck): Metrics & {
36
+ engagement?: number;
37
+ };
38
+ export declare const hookOfDeck: (deck: Deck) => string;
39
+ /** What a hook is like, in plain words a person can act on. */
40
+ export declare function hookTraits(hook: string): string[];
41
+ export interface Group {
42
+ by: string;
43
+ value: string;
44
+ decks: number;
45
+ median_views: number;
46
+ median_engagement?: number;
47
+ /** Median views compared with all measured decks: 1.5 is 50% above. */
48
+ lift: number;
49
+ }
50
+ export interface Experiment {
51
+ id: string;
52
+ variants: {
53
+ deck: string;
54
+ variant?: string;
55
+ hook: string;
56
+ views?: number;
57
+ engagement?: number;
58
+ }[];
59
+ winner?: string;
60
+ verdict: string;
61
+ }
62
+ export interface Insights {
63
+ measured: number;
64
+ median_views: number;
65
+ top: {
66
+ deck: string;
67
+ hook: string;
68
+ views: number;
69
+ engagement?: number;
70
+ }[];
71
+ groups: Group[];
72
+ experiments: Experiment[];
73
+ repost_candidates: {
74
+ deck: string;
75
+ hook: string;
76
+ views: number;
77
+ posted: string;
78
+ }[];
79
+ markdown: string;
80
+ }
81
+ /** Views a variant needs before a hook test can call a winner. */
82
+ export declare const MIN_TEST_VIEWS = 300;
83
+ export declare function experimentVerdict(variants: Experiment["variants"]): {
84
+ winner?: string;
85
+ verdict: string;
86
+ };
87
+ export declare function insights(ws: Workspace, now?: Date, opts?: {
88
+ repost_after_days?: number;
89
+ }): Insights;
@@ -0,0 +1,252 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import YAML from "yaml";
4
+ import { plainText } from "./text.js";
5
+ import { listDecks, loadDeck, readJsonl, saveDeck, UserError } from "./workspace.js";
6
+ /** The numbers a result can carry. */
7
+ export const METRICS = ["views", "likes", "comments", "shares", "saves", "reach"];
8
+ function pick(m) {
9
+ const out = {};
10
+ for (const k of METRICS) {
11
+ const v = m?.[k];
12
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0)
13
+ out[k] = Math.round(v);
14
+ }
15
+ // Instagram counts impressions, not views.
16
+ if (out.views === undefined && typeof m?.impressions === "number")
17
+ out.views = Math.round(m.impressions);
18
+ return out;
19
+ }
20
+ /** Keeps one result per source and platform: the newest replaces the one before. */
21
+ function upsert(deck, r) {
22
+ const results = deck.results.filter((x) => !(x.source === r.source && (x.platform ?? "") === (r.platform ?? "")));
23
+ return { ...deck, results: [...results, r] };
24
+ }
25
+ /** The post id Spec gave a draft after `social push`, read back from the draft file. */
26
+ function specPostId(ws, draftFile) {
27
+ const file = join(ws.root, draftFile);
28
+ if (!existsSync(file))
29
+ return undefined;
30
+ try {
31
+ const d = YAML.parse(readFileSync(file, "utf8"));
32
+ return typeof d?.postId === "string" ? d.postId : undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ /**
39
+ * Brings in how published decks did: from a Spec repo's posts.jsonl (after `appeeky-spec social pull`)
40
+ * for decks sent as Spec drafts, and from Appeeky for decks posted through it. Postiz, Photos and
41
+ * exports have no numbers here: record them with recordResult.
42
+ */
43
+ export async function syncResults(ws, fetcher, now = new Date()) {
44
+ const report = { updated: [], skipped: [] };
45
+ const specPosts = ws.spec && existsSync(ws.spec.posts_file) ? readJsonl(ws.spec.posts_file) : [];
46
+ for (const { id, deck } of listDecks(ws)) {
47
+ if (!deck || !deck.published.length)
48
+ continue;
49
+ let next = deck;
50
+ let touched = false;
51
+ for (const p of deck.published) {
52
+ if (p.provider === "spec-draft" && p.draft_file) {
53
+ const postId = specPostId(ws, p.draft_file);
54
+ if (!postId) {
55
+ report.skipped.push({ deck: id, why: `${p.draft_file} is not sent yet (Spec writes postId after social push)` });
56
+ continue;
57
+ }
58
+ const row = specPosts.find((r) => r.id === postId);
59
+ if (!row) {
60
+ report.skipped.push({ deck: id, why: `post ${postId} is not in posts.jsonl yet; run appeeky-spec social pull` });
61
+ continue;
62
+ }
63
+ for (const pl of row.platforms ?? []) {
64
+ const metrics = pick(pl.metrics);
65
+ if (!Object.keys(metrics).length)
66
+ continue;
67
+ next = upsert(next, { at: now.toISOString(), source: "spec", platform: pl.platform, ...metrics });
68
+ report.updated.push({ deck: id, source: "spec", platform: pl.platform, metrics });
69
+ touched = true;
70
+ }
71
+ }
72
+ else if (p.provider === "appeeky" && p.post_id) {
73
+ if (!fetcher) {
74
+ report.skipped.push({ deck: id, why: "posted through Appeeky; set APPEEKY_API_KEY to read its numbers" });
75
+ continue;
76
+ }
77
+ try {
78
+ for (const a of await fetcher(p.post_id)) {
79
+ const metrics = pick(a.analytics);
80
+ if (!Object.keys(metrics).length)
81
+ continue;
82
+ next = upsert(next, { at: now.toISOString(), source: "appeeky", platform: a.platform, ...metrics });
83
+ report.updated.push({ deck: id, source: "appeeky", platform: a.platform, metrics });
84
+ touched = true;
85
+ }
86
+ }
87
+ catch (e) {
88
+ report.skipped.push({ deck: id, why: e.message });
89
+ }
90
+ }
91
+ else if (p.provider !== "export") {
92
+ if (!deck.results.length)
93
+ report.skipped.push({ deck: id, why: `posted with ${p.provider}: record its numbers by hand (results_record)` });
94
+ }
95
+ }
96
+ if (touched)
97
+ saveDeck(ws, next);
98
+ }
99
+ return report;
100
+ }
101
+ /** Numbers a person read off the app, for posts made with Photos, export or Postiz. */
102
+ export function recordResult(ws, id, metrics, now = new Date()) {
103
+ const deck = loadDeck(ws, id);
104
+ if (deck.status !== "published" && !deck.published.length)
105
+ throw new UserError(`deck ${id} is not published; numbers belong to a posted deck (publish it with export or photos first, then post it)`);
106
+ const clean = pick(metrics);
107
+ if (!Object.keys(clean).length)
108
+ throw new UserError(`give at least one of ${METRICS.join(", ")}`);
109
+ return saveDeck(ws, upsert(deck, { at: now.toISOString(), source: "manual", platform: metrics.platform, ...clean }));
110
+ }
111
+ // ---------- insights ----------
112
+ /** A deck's totals over every platform it went to. */
113
+ export function totals(deck) {
114
+ const t = {};
115
+ for (const r of deck.results)
116
+ for (const k of METRICS)
117
+ if (r[k] !== undefined)
118
+ t[k] = (t[k] ?? 0) + r[k];
119
+ const acts = (t.likes ?? 0) + (t.comments ?? 0) + (t.shares ?? 0) + (t.saves ?? 0);
120
+ return { ...t, ...(t.views ? { engagement: acts / t.views } : {}) };
121
+ }
122
+ export const hookOfDeck = (deck) => plainText((deck.slides.find((s) => s.kind === "cover") ?? deck.slides[0])?.title ?? "");
123
+ /** What a hook is like, in plain words a person can act on. */
124
+ export function hookTraits(hook) {
125
+ const t = [];
126
+ const words = hook.split(/\s+/).filter(Boolean).length;
127
+ t.push(words <= 7 ? "short hook (≤7 words)" : words <= 11 ? "medium hook (8–11 words)" : "long hook (12+ words)");
128
+ if (/\d/.test(hook))
129
+ t.push("number in the hook");
130
+ if (/\?\s*$/.test(hook))
131
+ t.push("question hook");
132
+ if (/^(i|i'm|i've|my|me)\b/i.test(hook))
133
+ t.push("first-person hook");
134
+ if (/\byou(r)?\b/i.test(hook))
135
+ t.push("speaks to 'you'");
136
+ if (/^pov\b/i.test(hook))
137
+ t.push("POV hook");
138
+ if (/\b(stop|never|don't|mistake|wrong)\b/i.test(hook))
139
+ t.push("warning hook");
140
+ return t;
141
+ }
142
+ const median = (xs) => {
143
+ const s = [...xs].sort((a, b) => a - b);
144
+ const m = Math.floor(s.length / 2);
145
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
146
+ };
147
+ function postedAt(deck) {
148
+ const p = deck.published.at(-1);
149
+ return p?.scheduled_for ?? p?.at;
150
+ }
151
+ /** Views a variant needs before a hook test can call a winner. */
152
+ export const MIN_TEST_VIEWS = 300;
153
+ export function experimentVerdict(variants) {
154
+ const measured = variants.filter((v) => v.views !== undefined);
155
+ if (measured.length < variants.length)
156
+ return { verdict: `waiting for numbers (${measured.length} of ${variants.length} variants measured)` };
157
+ const sorted = [...measured].sort((a, b) => b.views - a.views);
158
+ const [first, second] = sorted;
159
+ if (!first || !second)
160
+ return { verdict: "needs at least two variants" };
161
+ if (second.views < MIN_TEST_VIEWS)
162
+ return { verdict: `too early: every variant needs ${MIN_TEST_VIEWS}+ views` };
163
+ if (first.views < second.views * 1.2)
164
+ return { verdict: `no clear winner (${first.views} vs ${second.views} views); the hooks did about the same` };
165
+ return { winner: first.deck, verdict: `${first.deck} wins with ${Math.round((first.views / second.views - 1) * 100)}% more views: "${first.hook}"` };
166
+ }
167
+ export function insights(ws, now = new Date(), opts = {}) {
168
+ const decks = listDecks(ws)
169
+ .map((d) => d.deck)
170
+ .filter((d) => !!d);
171
+ const measured = decks.filter((d) => totals(d).views !== undefined);
172
+ const views = measured.map((d) => totals(d).views);
173
+ const base = views.length ? median(views) : 0;
174
+ const buckets = new Map();
175
+ const put = (by, value, d) => {
176
+ if (!value)
177
+ return;
178
+ const key = `${by}\u0000${value}`;
179
+ buckets.set(key, [...(buckets.get(key) ?? []), d]);
180
+ };
181
+ for (const d of measured) {
182
+ // Hook test variants share everything but the cover: count their design once (variant a).
183
+ if (!d.variant || d.variant === "a") {
184
+ put("template", d.template, d);
185
+ put("theme", d.theme, d);
186
+ put("slides", d.slides.length <= 5 ? "5 or fewer slides" : d.slides.length <= 8 ? "6–8 slides" : "9+ slides", d);
187
+ put("size", d.size, d);
188
+ put("channel", d.channel, d);
189
+ if (d.slides.some((s) => s.kind === "screenshot"))
190
+ put("slides", "shows an app screenshot", d);
191
+ }
192
+ for (const t of hookTraits(hookOfDeck(d)))
193
+ put("hook", t, d);
194
+ const at = postedAt(d);
195
+ if (at) {
196
+ const h = new Date(at).getUTCHours();
197
+ put("time (UTC)", h < 12 ? "morning (before 12 UTC)" : h < 18 ? "afternoon (12–18 UTC)" : "evening (after 18 UTC)", d);
198
+ }
199
+ }
200
+ const groups = [...buckets.entries()]
201
+ .filter(([, ds]) => ds.length >= 2)
202
+ .map(([key, ds]) => {
203
+ const [by, value] = key.split("\u0000");
204
+ const v = ds.map((d) => totals(d).views);
205
+ const e = ds.map((d) => totals(d).engagement).filter((x) => x !== undefined);
206
+ const mv = median(v);
207
+ return { by, value, decks: ds.length, median_views: Math.round(mv), ...(e.length ? { median_engagement: Math.round(median(e) * 1000) / 1000 } : {}), lift: base ? Math.round((mv / base) * 100) / 100 : 1 };
208
+ })
209
+ .sort((a, b) => b.lift - a.lift);
210
+ const top = [...measured]
211
+ .sort((a, b) => totals(b).views - totals(a).views)
212
+ .slice(0, 5)
213
+ .map((d) => ({ deck: d.id, hook: hookOfDeck(d), views: totals(d).views, ...(totals(d).engagement !== undefined ? { engagement: Math.round(totals(d).engagement * 1000) / 1000 } : {}) }));
214
+ const byExperiment = new Map();
215
+ for (const d of decks)
216
+ if (d.experiment)
217
+ byExperiment.set(d.experiment, [...(byExperiment.get(d.experiment) ?? []), d]);
218
+ const experiments = [...byExperiment.entries()].map(([id, ds]) => {
219
+ const variants = ds
220
+ .sort((a, b) => (a.variant ?? "").localeCompare(b.variant ?? ""))
221
+ .map((d) => ({ deck: d.id, variant: d.variant, hook: hookOfDeck(d), views: totals(d).views, engagement: totals(d).engagement }));
222
+ return { id, variants, ...experimentVerdict(variants) };
223
+ });
224
+ const after = (opts.repost_after_days ?? 30) * 86_400_000;
225
+ const reposted = new Set(decks.map((d) => d.repost_of).filter(Boolean));
226
+ const repost_candidates = measured
227
+ .filter((d) => !reposted.has(d.id) && !d.repost_of && totals(d).views >= base && postedAt(d) && now.getTime() - Date.parse(postedAt(d)) >= after)
228
+ .sort((a, b) => totals(b).views - totals(a).views)
229
+ .slice(0, 5)
230
+ .map((d) => ({ deck: d.id, hook: hookOfDeck(d), views: totals(d).views, posted: postedAt(d) }));
231
+ return { measured: measured.length, median_views: Math.round(base), top, groups, experiments, repost_candidates, markdown: insightsMarkdown(measured.length, base, top, groups, experiments, repost_candidates) };
232
+ }
233
+ function insightsMarkdown(n, base, top, groups, experiments, reposts) {
234
+ if (!n && !experiments.length)
235
+ return "No results yet. After posting, run results_sync (Appeeky or Spec) or results_record (numbers read off the app).";
236
+ const md = [`# What worked (${n} measured deck${n === 1 ? "" : "s"}, median ${Math.round(base)} views)`];
237
+ if (top.length)
238
+ md.push("", "## Best decks", ...top.map((t) => `- ${t.views} views${t.engagement !== undefined ? `, ${(t.engagement * 100).toFixed(1)}% engagement` : ""}: "${t.hook}" (${t.deck})`));
239
+ const strong = groups.filter((g) => g.lift >= 1.2).slice(0, 6);
240
+ const weak = groups.filter((g) => g.lift <= 0.8).slice(-4);
241
+ if (strong.length)
242
+ md.push("", "## Do more of", ...strong.map((g) => `- ${g.by}: ${g.value}: ${g.lift}× the median (${g.decks} decks)`));
243
+ if (weak.length)
244
+ md.push("", "## Do less of", ...weak.map((g) => `- ${g.by}: ${g.value}: ${g.lift}× the median (${g.decks} decks)`));
245
+ if (n < 6)
246
+ md.push("", `Only ${n} measured deck${n === 1 ? "" : "s"}: treat these as hints, not rules.`);
247
+ if (experiments.length)
248
+ md.push("", "## Hook tests", ...experiments.map((e) => `- ${e.id}: ${e.verdict}`));
249
+ if (reposts.length)
250
+ md.push("", "## Worth posting again (with a new hook, deck_repost)", ...reposts.map((r) => `- "${r.hook}" (${r.deck}, ${r.views} views, posted ${r.posted.slice(0, 10)})`));
251
+ return md.join("\n");
252
+ }