@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/README.md CHANGED
@@ -6,11 +6,23 @@ Make TikTok photo slideshows and Instagram carousels for your app with the codin
6
6
 
7
7
  Your agent writes the words. open-slideshow renders the slides on your machine, checks them, and gets them to your phone or your accounts. It never calls a model, needs no account, and costs nothing to run.
8
8
 
9
+ And it learns what works for your app. Views and likes come back to each deck, so your agent sees which hooks, templates and posting times beat your usual post. It tests hooks against each other, turns a post that did well into part 2 or another language, puts your app's real screens in a phone, and finds the next idea in your comments and reviews.
10
+
11
+ **Set up with skills**, in any agent that reads skills (Claude Code, Codex, Cursor and more):
12
+
13
+ ```sh
14
+ npx skills add appeeky/open-slideshow
15
+ ```
16
+
17
+ Then ask your agent: *"make a TikTok slideshow about how to fall asleep faster"*. The first time, it gives you the one command that adds open-slideshow's tools (the MCP server) to your agent.
18
+
19
+ Or set up the skill and the tools in one go:
20
+
9
21
  ```sh
10
22
  npx @appeeky/open-slideshow agent claude # or codex, cursor
11
23
  ```
12
24
 
13
- Then ask your agent: *"make a TikTok slideshow about how to fall asleep faster"*.
25
+ More ways, including the Claude Code plugin, are under [Set up your agent](#set-up-your-agent).
14
26
 
15
27
  ## What it makes
16
28
 
@@ -31,23 +43,67 @@ Every picture below was written by an agent and rendered by open-slideshow. The
31
43
  **In Japanese** · `soft-shadow`, lines broken between phrases, not inside words
32
44
  ![Japanese slideshow in the soft-shadow theme](assets/examples/asa.jpg)
33
45
 
34
- ## What your agent gets
35
-
36
- - **10 themes**, from TikTok-style outlined captions to editorial pages. Your agent shows you all of them in one picture and you pick once.
37
- - **7 templates**: tips, mistakes, story, before / after, ranking, quotes and checklist. Each one sets which slides go in which order and what to write on each. A preview shows all of them in your theme.
38
- - **Your brand, before every deck.** The agent reads what your app does, who it is for, the tone, the claims you never make and every hook you already used. It asks you for anything that is missing.
39
- - **What already works.** With an Appeeky key, your agent finds the most liked TikTok slideshows on your topic, reads their hooks and writes its own on the angles that work ($0.01 a search from your Appeeky balance).
40
- - **Checks before you post**:
41
- - text that does not fit, or a glyph a font cannot draw;
42
- - missing images, or photos without a credit;
43
- - platform limits;
44
- - phrases that sound machine-written;
45
- - hooks you already used.
46
- - **Your language.** Fonts for Latin, Cyrillic, Greek and Vietnamese ship with open-slideshow. Fonts for Japanese, Chinese, Korean, Arabic, Hebrew, Thai and Hindi download once, the first time a deck needs them.
47
- - **Photos** from Openverse with no key (CC0, public domain or CC BY), from Unsplash or Pexels with your own key, or from your own files.
48
- - **A posting calendar**: days, a time window or fixed times, with time zones and clock changes handled.
49
- - **Posting is up to you.** Export the images, add them to Photos on macOS and post from your phone, or post and schedule through [Appeeky](https://appeeky.com) with your own key.
50
- - **Detailed skills.** A short flow plus nine guides cover brand, writing, templates, images, languages, review (every lint code), publishing, channels and troubleshooting (every error message). The agent reads a guide only when it needs one.
46
+ ## What's included
47
+
48
+ Everything runs on your machine. The **Needs** column says when something needs more than open-slideshow itself.
49
+
50
+ ### Write
51
+
52
+ | Feature | What it does | Tools | Needs |
53
+ |---|---|---|---|
54
+ | Brand context | Before every deck the agent reads what your app does, who it is for, the tone, the claims you never make and every hook you already used, and asks for what is missing | `brand_context`, `brand_set` | |
55
+ | Brand kit | Colours (contrast checked), fonts and logo from your website, proposed before anything is saved | `brand_kit` | |
56
+ | 14 templates | Tips, mistakes, story, before / after, ranking, quotes, checklist, myth vs fact, this instead of that, things I wish I knew, how-to, comparison, POV, hot takes. Each sets the slide order, what goes on each slide and example hooks | `templates_list`, `templates_preview` | |
57
+ | Idea queue | Ideas from questions in comments, wishes and praise in reviews, your listing's features and channel topics, with the words behind each | `ideas_collect`, `ideas_list`, `idea_add` | |
58
+ | What already works | The most liked TikTok slideshows on your topic, to study their hooks ($0.01 a search) | `viral_search` | Appeeky key |
59
+ | Languages | Latin, Cyrillic, Greek and Vietnamese built in; Japanese, Chinese, Korean, Arabic, Hebrew, Thai and Hindi download once | | |
60
+
61
+ ### Design
62
+
63
+ | Feature | What it does | Tools | Needs |
64
+ |---|---|---|---|
65
+ | 10 themes | TikTok-style outlined captions to editorial pages, all in one picture so you pick once | `themes_preview` | |
66
+ | Photos | Search and import, with license and author kept: Openverse (no key), Unsplash, Pexels, or your own files | `image_search`, `image_import` | Unsplash or Pexels key (optional) |
67
+ | Screenshot slides | Your app's own screen inside a phone, from your repo or your App Store listing | `app_screenshots` | |
68
+ | Preview | The deck on a phone you can swipe, with TikTok's buttons on a toggle, plus a GIF for a pull request | `deck_preview` | |
69
+ | Video | The slides as an MP4 for Reels and Shorts | `deck_video` | ffmpeg |
70
+
71
+ ### Check
72
+
73
+ | Feature | What it does | Tools | Needs |
74
+ |---|---|---|---|
75
+ | Lint before posting | Text that does not fit, missing glyphs, platform limits, phrases that sound machine-written, hooks you already used | `deck_render`, `deck_lint` | |
76
+ | Readability | Words under TikTok's buttons and caption, small text, photos too bright or busy behind the words; a sheet with TikTok's buttons drawn on | `deck_render` (`safe_zones`) | |
77
+ | Image rights | Every image keeps its license; one nobody said you may post blocks publishing | `image_license` | |
78
+
79
+ ### Post
80
+
81
+ | Feature | What it does | Tools | Needs |
82
+ |---|---|---|---|
83
+ | Export | The images, caption and credits in a folder | `deck_publish` | |
84
+ | Photos | The images in a Photos album, to post from your phone with a trending sound | `deck_publish` | macOS |
85
+ | Post and schedule | To your TikTok and Instagram accounts, now or at a time | `deck_publish` | Appeeky or Postiz key |
86
+ | Spec draft | A draft file that Appeeky Spec sends after review | `deck_publish` | Appeeky Spec repo |
87
+ | Posting calendar | Channels with days, a time window or fixed times, time zones handled; a weekly run on GitHub Actions | `channel_save`, `plan`, `due` | |
88
+
89
+ ### Learn
90
+
91
+ | Feature | What it does | Tools | Needs |
92
+ |---|---|---|---|
93
+ | Results | Views, likes, comments, shares and saves back on each deck, or typed in for posts made from your phone | `results_sync`, `results_record` | Appeeky key or Spec repo for automatic sync |
94
+ | Insights | Which templates, themes, hook kinds and posting times beat your usual post, the best hooks, decks worth posting again | `insights` | |
95
+ | Hook tests | The same deck with up to five covers, posted on different days; a winner only once each has enough views | `hook_test` | |
96
+ | Series | Part 2 with the same look and a "Part 2/3" label | `series_next`, `series_list` | |
97
+ | Translations | The same deck in another language with the same photos | `deck_translate` | |
98
+ | Reposts | A deck that did well, again after 30 days with a new hook | `deck_repost` | |
99
+
100
+ ### For your agent
101
+
102
+ | Feature | What it does |
103
+ |---|---|
104
+ | MCP server | Every tool above, for Claude Code, Codex, Cursor or any MCP client |
105
+ | Skill | A short flow plus fourteen guides (brand, writing, templates, images, languages, review, publishing, channels, results, series, screenshots, video, ideas, troubleshooting), read only when needed |
106
+ | CLI | The same things from a terminal or CI (`open-slideshow help`) |
51
107
 
52
108
  ## Set up your agent
53
109
 
@@ -123,8 +179,9 @@ With an App Store id, it reads your listing and imports your icon for the app sl
123
179
  4. **Template.** It suggests a shape that fits the topic, and can show you previews.
124
180
  5. **Write.** It writes the deck in your brand's voice.
125
181
  6. **Photos.** It searches for photos, shows you the thumbnails and imports the ones that fit.
126
- 7. **Render and look.** It renders the deck, looks at every slide, fixes what does not read, and shows you the sheet.
182
+ 7. **Render and look.** It renders the deck, looks at every slide, fixes what does not read, and shows you the sheet. A phone preview shows it the way your viewers will see it.
127
183
  8. **Publish, with your yes.** It shows what would happen and waits for you before anything is exported, posted or scheduled.
184
+ 9. **Learn.** Once the numbers are in, it tells you what worked and suggests the next deck: a hook test, part 2, a translation or a repost.
128
185
 
129
186
  ## A deck
130
187
 
@@ -150,7 +207,7 @@ hashtags: [sleep, sleeptips]
150
207
  accounts: [tiktok]
151
208
  ```
152
209
 
153
- Slide kinds: `cover`, `tip`, `list`, `quote`, `bridge`, `app`, `text`. Set `template: tips` (or another) and lint checks the slides follow it. Words in `*stars*` get the accent.
210
+ Slide kinds: `cover`, `tip`, `list`, `quote`, `bridge`, `app`, `text`, `screenshot`. Set `template: tips` (or another) and lint checks the slides follow it. Words in `*stars*` get the accent.
154
211
 
155
212
  ## Posting and scheduling
156
213
 
@@ -185,7 +242,9 @@ Merging the pull request is your yes. Add `ANTHROPIC_API_KEY` and `APPEEKY_API_K
185
242
 
186
243
  open-slideshow is a standalone tool. If it finds `appeeky.spec.yaml`, it works inside the Spec repo:
187
244
 
188
- - It reads the app, `appeeky/playbook.md` (brand), the store listing, connected accounts and past posts from Spec.
245
+ - It reads the app, `appeeky/playbook.md` (brand), the store listing and its languages, connected accounts and past posts from Spec.
246
+ - Ideas come from Spec's reviews and comments; screenshot slides use the screenshots in `appeeky/screenshots/`.
247
+ - Results come from Spec's `appeeky/social/posts.jsonl` once Spec has sent a draft and pulled its numbers.
189
248
  - It writes decks under `appeeky/social/slides/`.
190
249
  - It can publish as a Spec draft, which Spec sends after review.
191
250
 
@@ -196,7 +255,9 @@ It never changes Spec's own files.
196
255
  ```
197
256
  open-slideshow.yaml app, brand and defaults
198
257
  decks/<id>/deck.yaml the slides, caption, hashtags, accounts, time
199
- decks/<id>/renders/ 01.jpg … NN.jpg, sheet.jpg, manifest.json
258
+ decks/<id>/renders/ 01.jpg … NN.jpg, sheet.jpg, sheet-safe.jpg, manifest.json,
259
+ preview.html, preview.gif, video.mp4 when made
260
+ ideas.yaml the idea queue
200
261
  channels/<id>.yaml a posting plan: schedule, content rules, design
201
262
  images/<hash>.jpg/.json imported images with their license and author
202
263
  .open-slideshow/ plan, history, cache
@@ -211,6 +272,15 @@ open-slideshow templates a picture of the slideshow shapes
211
272
  open-slideshow render <deck> render to JPEGs
212
273
  open-slideshow lint <deck> check a deck
213
274
  open-slideshow viral <topic> the most liked TikTok slideshows on a topic (Appeeky key)
275
+ open-slideshow preview <deck> --gif a phone preview page and a GIF
276
+ open-slideshow video <deck> an MP4 for Reels and Shorts (needs ffmpeg)
277
+ open-slideshow screenshots import the app's screenshots
278
+ open-slideshow brand-kit <url> colours, fonts and logo from your website (--apply to save)
279
+ open-slideshow license <ref> <license> record who may post an image
280
+ open-slideshow results sync views and likes for published decks
281
+ open-slideshow insights what worked: hooks, templates, themes, times, hook tests
282
+ open-slideshow ideas collect ideas from comments, reviews and your listing
283
+ open-slideshow series series and their parts
214
284
  open-slideshow publish <deck> --to export|photos|appeeky|postiz|spec-draft --yes
215
285
  open-slideshow publish --scheduled --to appeeky|postiz --yes every rendered deck with a time ahead (CI)
216
286
  open-slideshow plan / due posting calendar
@@ -219,7 +289,7 @@ open-slideshow mcp the MCP server your agent talks to
219
289
 
220
290
  ## Privacy
221
291
 
222
- - Nothing leaves your machine unless you ask: an image search, a viral search, the App Store lookup for your app, or posting. The one exception: the first deck in Japanese, Chinese, Korean, Arabic, Hebrew, Thai or Hindi downloads that script's font from jsDelivr into `~/.cache/open-slideshow` (set `OPEN_SLIDESHOW_OFFLINE=1` to turn it off).
292
+ - Nothing leaves your machine unless you ask: an image search, a viral search, the App Store lookup for your app (and its reviews and screenshots), reading your website for a brand kit, fetching post results, or posting. The one exception: the first deck in Japanese, Chinese, Korean, Arabic, Hebrew, Thai or Hindi downloads that script's font from jsDelivr into `~/.cache/open-slideshow` (set `OPEN_SLIDESHOW_OFFLINE=1` to turn it off).
223
293
  - No telemetry.
224
294
  - Keys come from your environment (`APPEEKY_API_KEY`, `UNSPLASH_ACCESS_KEY`, `PEXELS_API_KEY`) and are never written to files.
225
295
 
package/dist/bin.js CHANGED
File without changes
package/dist/brand.d.ts CHANGED
@@ -20,6 +20,8 @@ export interface AppStoreInfo {
20
20
  export declare function fetchAppStore(ws: Workspace, id: string, country?: string): Promise<AppStoreInfo | null>;
21
21
  /** Sets the app icon from the App Store when the brand has none. */
22
22
  export declare function ensureIcon(ws: Workspace, info: AppStoreInfo | null): Promise<string | undefined>;
23
+ /** The store listing Spec keeps (appeeky/store/<store>/<locale>.yaml), in the primary locale. */
24
+ export declare function specListing(ws: Workspace, locale?: string | undefined): string | undefined;
23
25
  export interface UsedHook {
24
26
  hook: string;
25
27
  deck?: string;
package/dist/brand.js CHANGED
@@ -1,5 +1,6 @@
1
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import YAML from "yaml";
3
4
  import { brandSchema } from "./schema.js";
4
5
  import { listDecks, readJson, readJsonl, historyFile, resolveImage, writeAtomic } from "./workspace.js";
5
6
  import { plainText } from "./text.js";
@@ -94,26 +95,32 @@ function readText(file, max) {
94
95
  const t = readFileSync(file, "utf8").trim();
95
96
  return t.length > max ? `${t.slice(0, max)}\n…(cut)` : t;
96
97
  }
97
- /** The store listing Spec keeps: the first locale's text files. */
98
- function specListing(ws) {
98
+ /** The store listing Spec keeps (appeeky/store/<store>/<locale>.yaml), in the primary locale. */
99
+ export function specListing(ws, locale = ws.spec?.locales[0]) {
99
100
  const dir = ws.spec?.store_dir;
100
- if (!dir || !existsSync(dir))
101
+ if (!dir || !existsSync(dir) || !locale)
101
102
  return undefined;
102
- const parts = [];
103
- const walk = (d, depth) => {
104
- if (depth > 3 || parts.join("").length > 3000)
105
- return;
106
- for (const f of readdirSync(d).sort()) {
107
- const p = join(d, f);
108
- const st = statSync(p);
109
- if (st.isDirectory())
110
- walk(p, depth + 1);
111
- else if (/^(name|subtitle|promotional[-_]?text|description)\.(txt|md)$/i.test(f))
112
- parts.push(`${f.replace(/\.\w+$/, "")}: ${readFileSync(p, "utf8").trim().slice(0, 1500)}`);
103
+ for (const store of ["app-store", "google-play"]) {
104
+ const file = [join(dir, store, `${locale}.yaml`), join(dir, store, `${locale}.yml`)].find((f) => existsSync(f));
105
+ if (!file)
106
+ continue;
107
+ let data;
108
+ try {
109
+ data = (YAML.parse(readFileSync(file, "utf8")) ?? {});
113
110
  }
114
- };
115
- walk(dir, 0);
116
- return parts.length ? parts.join("\n").slice(0, 3500) : undefined;
111
+ catch {
112
+ continue;
113
+ }
114
+ const parts = [];
115
+ for (const key of ["name", "title", "subtitle", "shortDescription", "promotionalText", "description", "fullDescription"]) {
116
+ const v = data[key];
117
+ if (typeof v === "string" && v.trim())
118
+ parts.push(`${key}: ${v.trim().slice(0, 1500)}`);
119
+ }
120
+ if (parts.length)
121
+ return `(${store}, ${locale})\n${parts.join("\n")}`.slice(0, 3500);
122
+ }
123
+ return undefined;
117
124
  }
118
125
  /** Hooks already used, newest first, with how they did when Spec has the numbers. */
119
126
  export function usedHooks(ws, limit = 200) {
@@ -135,7 +142,7 @@ export function usedHooks(ws, limit = 200) {
135
142
  add({ hook: e.hook, deck: e.deck, at: e.at });
136
143
  if (ws.spec && existsSync(ws.spec.posts_file)) {
137
144
  for (const p of readJsonl(ws.spec.posts_file)) {
138
- const first = (p.content ?? "").split("\n")[0]?.trim();
145
+ const first = (p.text ?? p.content ?? "").split("\n")[0]?.trim();
139
146
  if (!first)
140
147
  continue;
141
148
  const m = (k) => (p.platforms ?? []).reduce((s, x) => s + (x.metrics?.[k] ?? 0), 0);
@@ -221,6 +228,16 @@ export async function brandContext(ws, opts = {}) {
221
228
  md.push("", "## Store listing (appeeky/store)", listing);
222
229
  md.push("", `## Default theme: ${theme.name} (${theme.id})`, theme.description);
223
230
  md.push("", "## Do not write", banned.join(", "));
231
+ if (ws.spec && ws.spec.locales.length > 1)
232
+ md.push("", `## Store languages: ${ws.spec.locales.join(", ")}`, "A deck that did well can be translated for each (deck_translate).");
233
+ const { insights } = await import("./results.js");
234
+ const learned = insights(ws);
235
+ if (learned.measured >= 2)
236
+ md.push("", learned.markdown.replace(/^# /, "## "));
237
+ const { readIdeas } = await import("./ideas.js");
238
+ const fresh = readIdeas(ws).filter((i) => i.status === "new");
239
+ if (fresh.length)
240
+ md.push("", `## Ideas waiting (${fresh.length}, ideas_list): ${fresh.slice(0, 3).map((i) => `"${i.text}"`).join("; ")}`);
224
241
  if (hooks.length) {
225
242
  md.push("", `## Hooks already used (${hooks.length}, newest first): do not repeat them or their angle`);
226
243
  for (const h of hooks.slice(0, 60))
@@ -0,0 +1,50 @@
1
+ import type { Colors } from "./schema.js";
2
+ import { type Workspace } from "./workspace.js";
3
+ /** A web page or stylesheet as text, over https only, never from a private address. */
4
+ export declare function fetchText(raw: string, max?: number): Promise<{
5
+ url: string;
6
+ text: string;
7
+ }>;
8
+ /** Colours in some CSS or HTML, most used first, with the brand's own variables counted extra. */
9
+ export declare function colorsIn(text: string): {
10
+ hex: string;
11
+ count: number;
12
+ }[];
13
+ /** Font families named in the CSS and Google Fonts links. */
14
+ export declare function fontsIn(text: string): string[];
15
+ /** The best logo on the page: an Apple touch icon, then the largest icon. Never the share image: it is a banner, not a logo. */
16
+ export declare function logoIn(html: string, base: string): string | undefined;
17
+ /** Picks a background, text and accent from the brand's colours, keeping text readable. */
18
+ export declare function proposeColors(found: string[], opts?: {
19
+ dark?: boolean;
20
+ }): {
21
+ colors: Colors;
22
+ why: string[];
23
+ };
24
+ /** The theme whose fonts are closest to the brand's. */
25
+ export declare function themeForFonts(fonts: string[]): {
26
+ theme: string;
27
+ why: string;
28
+ } | undefined;
29
+ export interface BrandKit {
30
+ source: string;
31
+ colors_found: string[];
32
+ colors: Colors;
33
+ fonts: string[];
34
+ theme?: {
35
+ theme: string;
36
+ why: string;
37
+ };
38
+ logo?: string;
39
+ notes: string[];
40
+ applied: boolean;
41
+ icon?: string;
42
+ }
43
+ /**
44
+ * Brand colours, fonts and logo from the app's website (or the playbook in a Spec repo). It only
45
+ * proposes; with apply it saves the colours as the brand colours and imports the logo as the icon.
46
+ */
47
+ export declare function brandKit(ws: Workspace, opts?: {
48
+ url?: string;
49
+ apply?: boolean;
50
+ }): Promise<BrandKit>;
@@ -0,0 +1,212 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { fetchAppStore } from "./brand.js";
3
+ import { assertPublicUrl, importImageFromUrl } from "./images.js";
4
+ import { contrast, hexToRgb, luminance, readableOn, rgbToHex, THEMES } from "./themes.js";
5
+ import { saveSettings, UserError } from "./workspace.js";
6
+ const MAX_PAGE = 2 * 1024 * 1024;
7
+ /** A web page or stylesheet as text, over https only, never from a private address. */
8
+ export async function fetchText(raw, max = MAX_PAGE) {
9
+ let current = raw;
10
+ for (let hop = 0; hop < 4; hop++) {
11
+ const url = await assertPublicUrl(current);
12
+ const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(15_000), headers: { "user-agent": "open-slideshow", accept: "text/html,text/css,*/*;q=0.5" } });
13
+ if (res.status >= 300 && res.status < 400) {
14
+ const loc = res.headers.get("location");
15
+ if (!loc)
16
+ throw new UserError("redirect without a location");
17
+ current = new URL(loc, url).toString();
18
+ continue;
19
+ }
20
+ if (res.status === 401 || res.status === 403 || res.status === 429)
21
+ throw new UserError(`${url.hostname} refused to be read (HTTP ${res.status}); try again later, or give the brand colours with brand_set colors`);
22
+ if (!res.ok)
23
+ throw new UserError(`${url.hostname}: HTTP ${res.status}`);
24
+ const chunks = [];
25
+ let total = 0;
26
+ for await (const chunk of res.body) {
27
+ total += chunk.byteLength;
28
+ if (total > max)
29
+ break;
30
+ chunks.push(Buffer.from(chunk));
31
+ }
32
+ return { url: url.toString(), text: Buffer.concat(chunks).toString("utf8") };
33
+ }
34
+ throw new UserError("too many redirects");
35
+ }
36
+ const HEX = /#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b/g;
37
+ const RGB = /rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/g;
38
+ function normHex(h) {
39
+ const x = h.replace("#", "").toLowerCase();
40
+ return `#${x.length === 3 ? [...x].map((c) => c + c).join("") : x}`;
41
+ }
42
+ const saturation = (hex) => {
43
+ const [r, g, b] = hexToRgb(hex).map((v) => v / 255);
44
+ const max = Math.max(r, g, b);
45
+ const min = Math.min(r, g, b);
46
+ return max === 0 ? 0 : (max - min) / max;
47
+ };
48
+ /** Colours in some CSS or HTML, most used first, with the brand's own variables counted extra. */
49
+ export function colorsIn(text) {
50
+ const counts = new Map();
51
+ const add = (hex, n = 1) => counts.set(hex, (counts.get(hex) ?? 0) + n);
52
+ for (const m of text.matchAll(HEX))
53
+ add(normHex(m[0]));
54
+ for (const m of text.matchAll(RGB))
55
+ add(rgbToHex([Number(m[1]), Number(m[2]), Number(m[3])].map((v) => Math.min(255, v))));
56
+ // --brand, --primary, --accent… and <meta name="theme-color"> say what the brand colour is.
57
+ for (const m of text.matchAll(/--(?:brand|primary|accent|main|theme)[\w-]*\s*:\s*(#[0-9a-fA-F]{3,6})\b/g))
58
+ add(normHex(m[1]), 25);
59
+ for (const m of text.matchAll(/<meta[^>]+name=["']theme-color["'][^>]*content=["'](#[0-9a-fA-F]{3,6})["']/gi))
60
+ add(normHex(m[1]), 40);
61
+ for (const m of text.matchAll(/<meta[^>]+content=["'](#[0-9a-fA-F]{3,6})["'][^>]*name=["']theme-color["']/gi))
62
+ add(normHex(m[1]), 40);
63
+ return [...counts.entries()].map(([hex, count]) => ({ hex, count })).sort((a, b) => b.count - a.count);
64
+ }
65
+ /** Font families named in the CSS and Google Fonts links. */
66
+ export function fontsIn(text) {
67
+ const out = new Map();
68
+ const add = (f) => {
69
+ const name = f.trim().replace(/^["']|["']$/g, "");
70
+ if (!name || /[:;{}()]/.test(name) || name.length > 40 || /^(inherit|initial|sans-serif|serif|monospace|system-ui|-apple-system|blinkmacsystemfont|var\(.*|ui-[\w-]+|arial|helvetica( neue)?|segoe ui|roboto|apple color emoji|segoe ui emoji)$/i.test(name))
71
+ return;
72
+ out.set(name, (out.get(name) ?? 0) + 1);
73
+ };
74
+ for (const m of text.matchAll(/font-family\s*:\s*([^;}"']+(?:["'][^"']+["'][^;}]*)?)/gi))
75
+ add(m[1].split(",")[0]);
76
+ for (const m of text.matchAll(/fonts\.googleapis\.com\/css2?\?family=([^"'&>]+)/gi))
77
+ for (const f of decodeURIComponent(m[1]).split("&family="))
78
+ add(f.split(":")[0].replace(/\+/g, " "));
79
+ return [...out.entries()].sort((a, b) => b[1] - a[1]).map(([f]) => f).slice(0, 5);
80
+ }
81
+ /** The best logo on the page: an Apple touch icon, then the largest icon. Never the share image: it is a banner, not a logo. */
82
+ export function logoIn(html, base) {
83
+ const links = [...html.matchAll(/<link[^>]+>/gi)].map((m) => m[0]);
84
+ const href = (tag) => tag.match(/href=["']([^"']+)["']/i)?.[1];
85
+ const touch = links.find((l) => /rel=["'][^"']*apple-touch-icon/i.test(l));
86
+ const icon = links.filter((l) => /rel=["'][^"']*icon/i.test(l)).sort((a, b) => Number(b.match(/sizes=["'](\d+)/)?.[1] ?? 0) - Number(a.match(/sizes=["'](\d+)/)?.[1] ?? 0))[0];
87
+ for (const c of [touch && href(touch), icon && href(icon)]) {
88
+ if (!c || /\.(svgz?|ico)(\?|$)/i.test(c))
89
+ continue;
90
+ try {
91
+ return new URL(c, base).toString();
92
+ }
93
+ catch {
94
+ /* not a URL */
95
+ }
96
+ }
97
+ return undefined;
98
+ }
99
+ /** Picks a background, text and accent from the brand's colours, keeping text readable. */
100
+ export function proposeColors(found, opts = {}) {
101
+ const why = [];
102
+ const neutral = (h) => saturation(h) < 0.12;
103
+ const vivid = found.filter((h) => saturation(h) > 0.35 && luminance(h) > 0.03 && luminance(h) < 0.85);
104
+ const accent = vivid[0] ?? found.find((h) => luminance(h) > 0.03 && luminance(h) < 0.9) ?? "#ff4d6d";
105
+ // Backgrounds and text are the site's near-greys; a pastel is an accent, not a page.
106
+ const darks = found.filter((h) => luminance(h) < 0.03 && neutral(h));
107
+ const lights = found.filter((h) => luminance(h) > 0.85 && neutral(h));
108
+ // A light page unless the site says it is dark (its theme-color) or has no light greys at all.
109
+ const darkSite = !!darks.length && (opts.dark || !lights.length);
110
+ const bg = darkSite ? darks[0] : lights.find((h) => h !== "#ffffff") ?? "#ffffff";
111
+ let fg = darkSite ? lights[0] ?? "#ffffff" : darks[0] ?? "#111111";
112
+ if (contrast(fg, bg) < 4.5) {
113
+ fg = readableOn(bg);
114
+ why.push("text colour changed to stay readable on the background");
115
+ }
116
+ if (contrast(accent, bg) < 3)
117
+ why.push(`the accent ${accent} is faint on ${bg}: use a theme where *words* sit on an accent box (highlight-box), or pick another accent`);
118
+ why.unshift(`accent ${accent} is the brand's most used strong colour`);
119
+ return { colors: { bg, fg, accent }, why };
120
+ }
121
+ /** The theme whose fonts are closest to the brand's. */
122
+ export function themeForFonts(fonts) {
123
+ const f = fonts.join(" ").toLowerCase();
124
+ if (!f)
125
+ return undefined;
126
+ if (/serif|playfair|lora|merriweather|garamond|libre baskerville|dm serif|fraunces|instrument serif|crimson/.test(f) && !/sans/.test(f))
127
+ return { theme: "editorial-ink", why: "the brand uses a serif" };
128
+ if (/anton|bebas|oswald|league gothic|archivo black|condensed|impact/.test(f))
129
+ return { theme: "bold-poster", why: "the brand uses a tall, condensed display font" };
130
+ if (/inter|sf pro|geist|manrope|dm sans|plus jakarta|poppins|nunito|work sans|outfit/.test(f))
131
+ return { theme: "clean-note", why: "the brand uses a clean sans-serif" };
132
+ return undefined;
133
+ }
134
+ /**
135
+ * Brand colours, fonts and logo from the app's website (or the playbook in a Spec repo). It only
136
+ * proposes; with apply it saves the colours as the brand colours and imports the logo as the icon.
137
+ */
138
+ export async function brandKit(ws, opts = {}) {
139
+ const notes = [];
140
+ let text = "";
141
+ let source = "";
142
+ let logo;
143
+ let url = opts.url;
144
+ if (!url && ws.settings.app.app_store_id) {
145
+ const store = await fetchAppStore(ws, ws.settings.app.app_store_id, ws.settings.app.country);
146
+ if (store?.seller)
147
+ notes.push(`App Store seller: ${store.seller}`);
148
+ const lookup = await fetch(`https://itunes.apple.com/lookup?id=${encodeURIComponent(ws.settings.app.app_store_id)}`, { signal: AbortSignal.timeout(10_000) })
149
+ .then((r) => r.json())
150
+ .catch(() => ({ results: [] }));
151
+ url = lookup.results?.[0]?.sellerUrl;
152
+ }
153
+ if (url) {
154
+ const page = await fetchText(url);
155
+ source = page.url;
156
+ text = page.text;
157
+ logo = logoIn(page.text, page.url);
158
+ // Same-site stylesheets hold most of the colours.
159
+ const sheets = [...page.text.matchAll(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)].map((m) => m[0].match(/href=["']([^"']+)["']/i)?.[1]).filter((h) => !!h);
160
+ for (const href of sheets.slice(0, 4)) {
161
+ try {
162
+ const u = new URL(href, page.url);
163
+ if (u.hostname !== new URL(page.url).hostname)
164
+ continue;
165
+ text += `\n${(await fetchText(u.toString(), 600_000)).text}`;
166
+ }
167
+ catch {
168
+ /* a stylesheet that does not load is fine */
169
+ }
170
+ }
171
+ }
172
+ if (ws.spec?.playbook && existsSync(ws.spec.playbook)) {
173
+ const pb = readFileSync(ws.spec.playbook, "utf8");
174
+ if (/#[0-9a-fA-F]{3,6}\b/.test(pb)) {
175
+ text = `${pb.split("\n").filter((l) => /colou?r|brand|#[0-9a-f]{3,6}/i.test(l)).join("\n")}\n${text}`;
176
+ source = source ? `${source} + appeeky/playbook.md` : "appeeky/playbook.md";
177
+ }
178
+ }
179
+ if (!text)
180
+ throw new UserError(ws.settings.app.app_store_id ? "the App Store listing names no website for this app; give the website (url)" : "give the app's website (url), or set the App Store id so its seller website can be read");
181
+ const found = colorsIn(text).map((c) => c.hex);
182
+ if (!found.length)
183
+ throw new UserError(`no colours found on ${source}; give the brand colours with brand_set colors`);
184
+ const themeColor = text.match(/<meta[^>]+name=["']theme-color["'][^>]*content=["'](#[0-9a-fA-F]{3,6})["']/i)?.[1];
185
+ const { colors, why } = proposeColors(found, { dark: !!themeColor && luminance(normHex(themeColor)) < 0.03 });
186
+ notes.push(...why);
187
+ const fonts = fontsIn(text);
188
+ const theme = themeForFonts(fonts);
189
+ if (fonts.length && !theme)
190
+ notes.push(`the brand's fonts (${fonts.join(", ")}) are not built in; the themes use TikTok Sans, Inter, Anton and Instrument Serif`);
191
+ let icon;
192
+ if (opts.apply) {
193
+ const s = structuredClone(ws.settings);
194
+ s.brand.colors = colors;
195
+ if (logo && !s.brand.icon) {
196
+ try {
197
+ // Icons are small (a touch icon is 180 px); the app slide draws them small too.
198
+ icon = (await importImageFromUrl(ws, logo, { source: "website", license: "own", note: "brand logo" }, { minSize: 120 })).ref;
199
+ s.brand.icon = icon;
200
+ }
201
+ catch (e) {
202
+ notes.push(`the logo could not be imported (${e.message}); import it with image_import`);
203
+ }
204
+ }
205
+ if (!logo && !s.brand.icon)
206
+ notes.push("no logo found on the site (only a favicon); import the app icon with image_import, or set the App Store id");
207
+ if (theme && THEMES.some((t) => t.id === theme.theme))
208
+ notes.push(`try the ${theme.theme} theme (${theme.why})`);
209
+ saveSettings(ws, s);
210
+ }
211
+ return { source, colors_found: found.slice(0, 12), colors, fonts, ...(theme ? { theme } : {}), ...(logo ? { logo } : {}), notes, applied: !!opts.apply, ...(icon ? { icon } : {}) };
212
+ }