@appeeky/open-slideshow 0.0.0-stage → 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 (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +297 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +9 -0
  5. package/dist/brand.d.ts +57 -0
  6. package/dist/brand.js +263 -0
  7. package/dist/brandkit.d.ts +50 -0
  8. package/dist/brandkit.js +212 -0
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +355 -0
  11. package/dist/decks.d.ts +44 -0
  12. package/dist/decks.js +100 -0
  13. package/dist/fonts.d.ts +45 -0
  14. package/dist/fonts.js +243 -0
  15. package/dist/gallery.d.ts +35 -0
  16. package/dist/gallery.js +109 -0
  17. package/dist/ideas.d.ts +50 -0
  18. package/dist/ideas.js +146 -0
  19. package/dist/images.d.ts +62 -0
  20. package/dist/images.js +241 -0
  21. package/dist/index.d.ts +21 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lint.d.ts +36 -0
  24. package/dist/lint.js +197 -0
  25. package/dist/mcp.d.ts +3 -0
  26. package/dist/mcp.js +303 -0
  27. package/dist/preview.d.ts +18 -0
  28. package/dist/preview.js +96 -0
  29. package/dist/publish.d.ts +105 -0
  30. package/dist/publish.js +406 -0
  31. package/dist/readability.d.ts +19 -0
  32. package/dist/readability.js +42 -0
  33. package/dist/render.d.ts +92 -0
  34. package/dist/render.js +647 -0
  35. package/dist/results.d.ts +89 -0
  36. package/dist/results.js +252 -0
  37. package/dist/schedule.d.ts +19 -0
  38. package/dist/schedule.js +114 -0
  39. package/dist/schema.d.ts +1159 -0
  40. package/dist/schema.js +211 -0
  41. package/dist/screenshots.d.ts +18 -0
  42. package/dist/screenshots.js +69 -0
  43. package/dist/shape.d.ts +31 -0
  44. package/dist/shape.js +169 -0
  45. package/dist/skill.d.ts +7 -0
  46. package/dist/skill.js +17 -0
  47. package/dist/templates.d.ts +47 -0
  48. package/dist/templates.js +330 -0
  49. package/dist/text.d.ts +40 -0
  50. package/dist/text.js +231 -0
  51. package/dist/themes.d.ts +43 -0
  52. package/dist/themes.js +202 -0
  53. package/dist/variants.d.ts +48 -0
  54. package/dist/variants.js +175 -0
  55. package/dist/version.d.ts +1 -0
  56. package/dist/version.js +1 -0
  57. package/dist/video.d.ts +22 -0
  58. package/dist/video.js +59 -0
  59. package/dist/viral.d.ts +12 -0
  60. package/dist/viral.js +35 -0
  61. package/dist/workspace.d.ts +85 -0
  62. package/dist/workspace.js +322 -0
  63. package/package.json +65 -4
  64. package/skills/open-slideshow/SKILL.md +65 -0
  65. package/skills/open-slideshow/references/brand.md +64 -0
  66. package/skills/open-slideshow/references/channels.md +63 -0
  67. package/skills/open-slideshow/references/ideas.md +23 -0
  68. package/skills/open-slideshow/references/images.md +61 -0
  69. package/skills/open-slideshow/references/languages.md +51 -0
  70. package/skills/open-slideshow/references/publishing.md +70 -0
  71. package/skills/open-slideshow/references/results.md +47 -0
  72. package/skills/open-slideshow/references/review.md +81 -0
  73. package/skills/open-slideshow/references/screenshots.md +26 -0
  74. package/skills/open-slideshow/references/series.md +20 -0
  75. package/skills/open-slideshow/references/templates.md +96 -0
  76. package/skills/open-slideshow/references/troubleshooting.md +92 -0
  77. package/skills/open-slideshow/references/video.md +18 -0
  78. package/skills/open-slideshow/references/writing.md +76 -0
@@ -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
+ }
@@ -0,0 +1,19 @@
1
+ import { type Channel } from "./schema.js";
2
+ import { type Workspace } from "./workspace.js";
3
+ export interface Slot {
4
+ channel: string;
5
+ /** Post time, ISO with the channel's offset. */
6
+ at: string;
7
+ /** When the deck for it should be ready. */
8
+ prepare_at: string;
9
+ deck?: string;
10
+ note?: string;
11
+ }
12
+ export declare function checkTimezone(tz: string): string;
13
+ export declare function planSlots(ch: Channel, from: Date, days: number): Slot[];
14
+ export declare function readPlan(ws: Workspace): Slot[];
15
+ /** Adds new slots to the saved plan; slots already there keep their deck. Past slots without a deck are dropped. */
16
+ export declare function savePlan(ws: Workspace, fresh: Slot[], now?: Date): Slot[];
17
+ /** Slots that need a deck now. */
18
+ export declare function dueSlots(ws: Workspace, now?: Date): Slot[];
19
+ export declare function assignSlot(ws: Workspace, channel: string, at: string, deck: string): Slot;
@@ -0,0 +1,114 @@
1
+ import { createHash } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import { DateTime, IANAZone } from "luxon";
4
+ import { DAYS } from "./schema.js";
5
+ import { listDecks, readJson, UserError, writeAtomic } from "./workspace.js";
6
+ /** A repeatable 0–1 number for a key, so the same day always gets the same random time. */
7
+ function seeded(key) {
8
+ return createHash("sha256").update(key).digest().readUInt32BE(0) / 0xffffffff;
9
+ }
10
+ const minutes = (hhmm) => {
11
+ const [h, m] = hhmm.split(":").map(Number);
12
+ return h * 60 + m;
13
+ };
14
+ export function checkTimezone(tz) {
15
+ if (!IANAZone.isValidZone(tz))
16
+ throw new UserError(`unknown time zone "${tz}"; use a name like Europe/Istanbul or America/New_York`);
17
+ return tz;
18
+ }
19
+ /** Local times (minutes after midnight) for one day. */
20
+ function dayTimes(s, key) {
21
+ if (s.mode === "fixed") {
22
+ if (!s.times.length)
23
+ throw new UserError("fixed schedules need times");
24
+ return { times: [...new Set(s.times.map(minutes))].sort((a, b) => a - b) };
25
+ }
26
+ let start = minutes(s.window.start);
27
+ let end = minutes(s.window.end);
28
+ if (end <= start)
29
+ end += 24 * 60; // a window past midnight, e.g. 22:00–01:00
30
+ const span = end - start;
31
+ const need = (s.per_day - 1) * s.min_gap;
32
+ if (need > span) {
33
+ // Cannot keep the gap: spread evenly and say so.
34
+ const step = s.per_day > 1 ? span / (s.per_day - 1) : 0;
35
+ return { times: Array.from({ length: s.per_day }, (_, i) => Math.round(start + i * step)), note: `window too short for ${s.per_day} posts ${s.min_gap} min apart; spread evenly` };
36
+ }
37
+ // Spread the free minutes randomly between the posts, keeping the minimum gap.
38
+ const free = span - need;
39
+ const cuts = Array.from({ length: s.per_day }, (_, i) => seeded(`${key}:${i}`) * free).sort((a, b) => a - b);
40
+ return { times: cuts.map((c, i) => Math.round(start + c + i * s.min_gap)) };
41
+ }
42
+ function prepareAt(at, s) {
43
+ if (s.prepare === "at_post_time")
44
+ return at;
45
+ if (s.prepare === "day_before")
46
+ return at.minus({ days: 1 });
47
+ return at.minus({ hours: s.prepare.hours_before });
48
+ }
49
+ export function planSlots(ch, from, days) {
50
+ const s = ch.schedule;
51
+ const tz = checkTimezone(s.timezone);
52
+ if (days < 1 || days > 62)
53
+ throw new UserError("plan between 1 and 62 days");
54
+ const start = DateTime.fromJSDate(from, { zone: tz }).startOf("day");
55
+ const slots = [];
56
+ for (let d = 0; d < days; d++) {
57
+ const day = start.plus({ days: d });
58
+ const weekday = DAYS[day.weekday % 7];
59
+ if (!s.days.includes(weekday))
60
+ continue;
61
+ const { times, note } = dayTimes(s, `${ch.id}:${day.toISODate()}`);
62
+ for (const t of times) {
63
+ let at = day.plus({ minutes: t });
64
+ // Luxon moves a time that does not exist (spring-forward gap) forward; keep it, but say so.
65
+ const wanted = `${String(Math.floor((t % 1440) / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`;
66
+ const dst = t < 1440 && at.toFormat("HH:mm") !== wanted ? `${wanted} does not exist that day (clocks change); moved to ${at.toFormat("HH:mm")}` : undefined;
67
+ at = at.set({ second: 0, millisecond: 0 });
68
+ if (at.toMillis() <= from.getTime())
69
+ continue;
70
+ slots.push({ channel: ch.id, at: at.toISO({ suppressMilliseconds: true }), prepare_at: prepareAt(at, s).toISO({ suppressMilliseconds: true }), ...(note || dst ? { note: [note, dst].filter(Boolean).join("; ") } : {}) });
71
+ }
72
+ }
73
+ return slots;
74
+ }
75
+ const planFile = (ws) => join(ws.state, "plan.json");
76
+ export function readPlan(ws) {
77
+ return readJson(planFile(ws), { slots: [] }).slots;
78
+ }
79
+ /** Adds new slots to the saved plan; slots already there keep their deck. Past slots without a deck are dropped. */
80
+ export function savePlan(ws, fresh, now = new Date()) {
81
+ const old = readPlan(ws);
82
+ const key = (s) => `${s.channel}|${s.at}`;
83
+ const byKey = new Map(old.map((s) => [key(s), s]));
84
+ for (const s of fresh)
85
+ if (!byKey.has(key(s)))
86
+ byKey.set(key(s), s);
87
+ const decks = new Map(listDecks(ws).map((d) => [d.id, d.deck]));
88
+ const kept = [...byKey.values()].filter((s) => {
89
+ if (s.deck && !decks.has(s.deck))
90
+ delete s.deck; // the deck was deleted: the slot is free again
91
+ return s.deck || Date.parse(s.at) > now.getTime();
92
+ });
93
+ kept.sort((a, b) => a.at.localeCompare(b.at));
94
+ writeAtomic(planFile(ws), JSON.stringify({ slots: kept }, null, 2));
95
+ return kept;
96
+ }
97
+ /** Slots that need a deck now. */
98
+ export function dueSlots(ws, now = new Date()) {
99
+ return readPlan(ws).filter((s) => !s.deck && Date.parse(s.prepare_at) <= now.getTime() && Date.parse(s.at) > now.getTime());
100
+ }
101
+ export function assignSlot(ws, channel, at, deck) {
102
+ const slots = readPlan(ws);
103
+ const slot = slots.find((s) => s.channel === channel && s.at === at);
104
+ if (!slot)
105
+ throw new UserError(`no slot for ${channel} at ${at}; run plan first`);
106
+ if (slot.deck && slot.deck !== deck)
107
+ throw new UserError(`slot ${at} already has deck ${slot.deck}`);
108
+ const other = slots.find((s) => s.deck === deck && s !== slot);
109
+ if (other)
110
+ throw new UserError(`deck ${deck} is already in the slot at ${other.at}`);
111
+ slot.deck = deck;
112
+ writeAtomic(planFile(ws), JSON.stringify({ slots }, null, 2));
113
+ return slot;
114
+ }