@senseihq/emaki-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -2
  3. package/package.json +44 -4
  4. package/plugin/.claude-plugin/plugin.json +19 -0
  5. package/plugin/PLAYBOOK.md +137 -0
  6. package/plugin/README.md +51 -0
  7. package/plugin/agents/fact-checker.md +28 -0
  8. package/plugin/agents/localizer.md +34 -0
  9. package/plugin/agents/scene-builder.md +43 -0
  10. package/plugin/agents/story-planner.md +42 -0
  11. package/plugin/agents/story-writer.md +34 -0
  12. package/plugin/agents/visual-reviewer.md +33 -0
  13. package/plugin/modules/campaign/README.md +30 -0
  14. package/plugin/modules/campaign/calendar.csv +2 -0
  15. package/plugin/modules/campaign/day-script.template.md +42 -0
  16. package/plugin/modules/posting-desk/README.md +37 -0
  17. package/plugin/skills/emaki/SKILL.md +107 -0
  18. package/plugin/skills/emaki/references/01-interview.md +68 -0
  19. package/plugin/skills/emaki/references/02-architecture.md +69 -0
  20. package/plugin/skills/emaki/references/03-content-model.md +68 -0
  21. package/plugin/skills/emaki/references/04-scene-authoring.md +99 -0
  22. package/plugin/skills/emaki/references/05-voice-and-video.md +97 -0
  23. package/plugin/skills/emaki/references/06-i18n.md +37 -0
  24. package/plugin/skills/emaki/references/07-quality-gates.md +44 -0
  25. package/plugin/skills/emaki/references/08-feedback-loop.md +32 -0
  26. package/plugin/skills/emaki/references/09-publishing.md +14 -0
  27. package/plugin/skills/story-build/SKILL.md +37 -0
  28. package/plugin/skills/story-localize/SKILL.md +24 -0
  29. package/plugin/skills/story-media/SKILL.md +38 -0
  30. package/plugin/skills/story-publish/SKILL.md +36 -0
  31. package/plugin/skills/story-review/SKILL.md +29 -0
  32. package/plugin/templates/brief.md +32 -0
  33. package/plugin/templates/change-request.md +7 -0
  34. package/plugin/templates/changelog.md +4 -0
  35. package/plugin/templates/decisions.md +5 -0
  36. package/plugin/templates/glossary.md +4 -0
  37. package/plugin/templates/item-card.md +34 -0
  38. package/plugin/templates/outline.md +19 -0
  39. package/plugin/templates/review-sheet.md +12 -0
  40. package/plugin/templates/style-guide.md +21 -0
  41. package/plugin/templates/tracker.md +11 -0
  42. package/src/api.js +20 -0
  43. package/src/campaign.js +157 -0
  44. package/src/capture.js +205 -0
  45. package/src/carousel.js +91 -0
  46. package/src/config.js +32 -0
  47. package/src/day-script.js +66 -0
  48. package/src/desk-client.js +37 -0
  49. package/src/desk-plan.js +57 -0
  50. package/src/films.js +152 -0
  51. package/src/http.js +30 -0
  52. package/src/index.js +353 -0
  53. package/src/init.js +110 -0
  54. package/src/media.js +236 -0
  55. package/src/migrate.js +67 -0
  56. package/src/plugin.js +106 -0
  57. package/src/publish.js +118 -0
  58. package/src/stage.js +107 -0
  59. package/src/stories.js +66 -0
  60. package/src/tts.js +290 -0
  61. package/src/upload/instagram.js +34 -0
  62. package/src/upload/youtube.js +90 -0
  63. package/src/util.js +66 -0
  64. package/src/voice.js +295 -0
  65. package/src/youtube-text.js +58 -0
  66. package/templates/content/films/index.json +1 -0
  67. package/templates/content/films/measure-the-right-work/film.json +68 -0
  68. package/templates/content/films/measure-the-right-work/look.css +17 -0
  69. package/templates/content/films/measure-the-right-work/scene-close.json +153 -0
  70. package/templates/content/films/measure-the-right-work/scene-groups.json +99 -0
  71. package/templates/content/films/measure-the-right-work/scene-hook.json +96 -0
  72. package/templates/content/films/measure-the-right-work/scene-pair.json +190 -0
  73. package/templates/content/films/measure-the-right-work/scene-problem.json +162 -0
  74. package/templates/content/films/measure-the-right-work/score.js +19 -0
  75. package/templates/content/films/measure-the-right-work/strings/en.json +50 -0
  76. package/templates/content/films/measure-the-right-work/strings/es.json +50 -0
  77. package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
  78. package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
  79. package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
  80. package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
  81. package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
  82. package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
  83. package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
  84. package/templates/content/films/measure-the-right-work/voice/en.json +7 -0
  85. package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
  86. package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
  87. package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
  88. package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
  89. package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
  90. package/templates/content/films/measure-the-right-work/voice/es.json +7 -0
  91. package/templates/content/logos/brand.svg +1 -0
  92. package/templates/content/site.json +10 -0
  93. package/templates/content/stories/en/measure-the-right-work.json +13 -0
  94. package/templates/content/stories/es/measure-the-right-work.json +13 -0
  95. package/templates/content/stories/index.json +12 -0
  96. package/templates/content/ui/en.json +1 -0
  97. package/templates/content/ui/es.json +1 -0
  98. package/templates/emaki.config.json +67 -0
  99. package/templates/film/look.css +17 -0
  100. package/templates/film/scene-close.json +153 -0
  101. package/templates/film/scene-template.json +71 -0
  102. package/templates/film/score.js +12 -0
package/src/capture.js ADDED
@@ -0,0 +1,205 @@
1
+ // sheet and render drive the site's capture page in headless Chromium: /show/<slug>?capture=1 installs
2
+ // window.__show = { meta, ready, seek(t), audio() } (installCapture in @senseihq/emaki; ShowPage in each wrapper).
3
+ // Playwright is an optional dependency: `npm i -D playwright && npx playwright install chromium`.
4
+ import { spawn } from 'node:child_process'
5
+ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync } from 'node:fs'
6
+ import { connect } from 'node:net'
7
+ import { dirname, join } from 'node:path'
8
+ import { SIZES, SUFFIX } from './config.js'
9
+ import { encodeArgs, frameRange, musicFor, muxArgs, renderOut, renderSteps, retrying, staleRender } from './media.js'
10
+ import { die, mediaLength, run } from './util.js'
11
+
12
+ /** page.evaluate that survives the dev server reloading the page under it (a file saved mid-render): it waits for
13
+ * the show to come back and repeats the same call (render.py's call()). */
14
+ const evaluate = (page, fn, arg) => retrying(() => page.evaluate(fn, arg), async () => {
15
+ await page.waitForFunction(() => window.__show, null, { timeout: 30000 })
16
+ await page.evaluate(() => window.__show.ready)
17
+ })
18
+
19
+ export async function chromium() {
20
+ try {
21
+ return (await import('playwright')).chromium
22
+ } catch {
23
+ return die('sheet, render and carousel need Playwright: npm i -D playwright && npx playwright install chromium')
24
+ }
25
+ }
26
+
27
+ const portOpen = (port) => new Promise((ok) => {
28
+ const s = connect({ port, host: '127.0.0.1' })
29
+ s.setTimeout(500)
30
+ s.once('connect', () => { s.destroy(); ok(true) })
31
+ s.once('error', () => ok(false))
32
+ s.once('timeout', () => { s.destroy(); ok(false) })
33
+ })
34
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
35
+
36
+ /** The site to capture: `url` if given (must answer), else the dev server (emaki.config.json devCommand), started if
37
+ * nothing listens on the port yet and stopped afterwards. */
38
+ export async function openSite(p, url) {
39
+ const port = p.cfg.port ?? 5199
40
+ let proc = null
41
+ const base = (url ?? `http://localhost:${port}`).replace(/\/$/, '')
42
+ if (url) {
43
+ try {
44
+ await fetch(url, { signal: AbortSignal.timeout(10000) })
45
+ } catch (e) {
46
+ die(`the site at ${url} is not responding (${e.message}); start it, or leave out --url to let emaki start it`)
47
+ }
48
+ } else if (!(await portOpen(port))) {
49
+ const cmd = (p.cfg.devCommand ?? 'npm run dev -- --port {port} --strictPort').replaceAll('{port}', String(port))
50
+ proc = spawn(cmd, { shell: true, cwd: p.root, stdio: 'ignore', detached: process.platform !== 'win32' })
51
+ let up = false
52
+ for (let i = 0; i < 120 && !(up = await portOpen(port)); i++) await sleep(500)
53
+ if (!up) { stop(); die(`the dev server did not start (${cmd})`) }
54
+ }
55
+ function stop() {
56
+ if (!proc) return
57
+ try { process.kill(-proc.pid) } catch { proc.kill() }
58
+ }
59
+ const showPath = p.cfg.showPath ?? '/show/{slug}?capture=1&o={layout}&locale={locale}'
60
+ return {
61
+ base,
62
+ show: (slug, layout, locale) => base + showPath.replaceAll('{slug}', slug).replaceAll('{layout}', layout).replaceAll('{locale}', locale),
63
+ close: stop
64
+ }
65
+ }
66
+
67
+ async function openShow(browser, site, slug, layout, locale) {
68
+ const [width, height] = SIZES[layout]
69
+ const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 })
70
+ const errors = []
71
+ page.on('pageerror', (e) => errors.push(String(e)))
72
+ await page.goto(site.show(slug, layout, locale))
73
+ await page.waitForFunction(() => window.__show, null, { timeout: 30000 })
74
+ await page.evaluate(() => window.__show.ready)
75
+ return { page, meta: await page.evaluate(() => window.__show.meta), errors }
76
+ }
77
+
78
+ /** A contact sheet: each scene's final picture (or --at scene:t,...) in both orientations, side by side. */
79
+ export async function sheet(p, slug, { locale, url, at, log = console.info } = {}) {
80
+ p.filmDir(slug)
81
+ const out = p.prod(slug, locale, 'sheets')
82
+ mkdirSync(out, { recursive: true })
83
+ const site = await openSite(p, url), shots = []
84
+ const browser = await (await chromium()).launch()
85
+ try {
86
+ for (const layout of ['landscape', 'portrait']) {
87
+ const { page, meta, errors } = await openShow(browser, site, slug, layout, locale)
88
+ const starts = Object.fromEntries(meta.scenes.map((s) => [s.id, [s.start, s.dur]]))
89
+ const pts = at
90
+ ? String(at).split(',').map((x) => { const [sid, t] = x.split(':'); return [sid, parseFloat(t)] })
91
+ : Object.entries(starts).map(([sid, [, d]]) => [sid, d - 0.4])
92
+ for (const [i, [sid, t]] of pts.entries()) {
93
+ if (!starts[sid]) die(`no scene "${sid}"`)
94
+ await page.evaluate((x) => window.__show.seek(x), starts[sid][0] + t)
95
+ await page.waitForTimeout(80)
96
+ const f = join(out, `${layout}-${String(i).padStart(2, '0')}-${sid}.jpg`)
97
+ writeFileSync(f, await page.screenshot({ type: 'jpeg', quality: 82 }))
98
+ shots.push({ layout, i, f, sid })
99
+ }
100
+ if (errors.length) log('page errors: ' + errors.slice(0, 3).join(' | '))
101
+ await page.close()
102
+ }
103
+ // Compose in the browser: landscape 960x540 with its portrait 304x540 beside it, three per row.
104
+ const n = shots.filter((s) => s.layout === 'landscape').length, cols = Math.min(3, n), rows = Math.ceil(n / cols)
105
+ const img = (s) => `data:image/jpeg;base64,${readFileSync(s.f).toString('base64')}`
106
+ const cells = shots.map((s) => {
107
+ const r = Math.floor(s.i / cols), c = s.i % cols
108
+ const [x, w] = s.layout === 'landscape' ? [c * 1290, 960] : [c * 1290 + 966, 304]
109
+ return `<img src="${img(s)}" style="position:absolute;left:${x}px;top:${r * 550}px;width:${w}px;height:540px">`
110
+ }).join('')
111
+ const page = await browser.newPage({ viewport: { width: cols * 1290, height: rows * 550 } })
112
+ await page.setContent(`<body style="margin:0;background:#fff;position:relative">${cells}</body>`)
113
+ await page.waitForFunction(() => [...document.images].every((i) => i.complete))
114
+ const dst = join(out, `${slug}-${locale}-sheet.jpg`)
115
+ writeFileSync(dst, await page.screenshot({ type: 'jpeg', quality: 85, fullPage: true }))
116
+ log(`sheet: ${p.rel(dst)}`)
117
+ return dst
118
+ } finally {
119
+ await browser.close()
120
+ site.close()
121
+ }
122
+ }
123
+
124
+ /** Frame-by-frame capture to MP4 with its music, plus a cover JPEG per orientation (render.py).
125
+ * `from`/`to` capture a range of film time; `out` is a file (one layout) or a folder. `music`: synth (the page's
126
+ * score, saved as score.wav), export (the audio of production/<slug>/<locale>/<slug>.mp4) or none. `audioOnly` lays
127
+ * the music on the existing render without capturing frames; `coverOnly` saves just the covers. */
128
+ export async function render(p, slug, {
129
+ locale, url, o = 'both', fps = 30, from = 0, to = undefined, out: target = undefined, music: mode = 'synth',
130
+ audioOnly = false, coverOnly = false, log = console.info
131
+ } = {}) {
132
+ p.filmDir(slug)
133
+ const steps = renderSteps({ audioOnly, coverOnly })
134
+ const layouts = o === 'both' ? ['landscape', 'portrait'] : [o]
135
+ const out = p.prod(slug, locale, 'render')
136
+ mkdirSync(out, { recursive: true })
137
+ const music = musicFor(mode, { exportFile: p.prod(slug, locale, `${slug}.mp4`), exists: existsSync })
138
+ if (steps.music && music.note) log(` ${music.note}`)
139
+ const site = await openSite(p, url), made = []
140
+ const browser = await (await chromium()).launch()
141
+ try {
142
+ let audio
143
+ for (const layout of layouts) {
144
+ const { page, meta, errors } = await openShow(browser, site, slug, layout, locale)
145
+ const call = (fn, arg) => evaluate(page, fn, arg)
146
+ const dst = renderOut(out, slug, locale, layout, { out: target, layouts: layouts.length })
147
+ if (steps.music && audio === undefined) {
148
+ audio = music.kind === 'file' ? music.file : null
149
+ if (music.kind === 'synth') {
150
+ const b64 = await call(() => window.__show.audio())
151
+ if (b64) writeFileSync((audio = join(out, 'score.wav')), Buffer.from(b64, 'base64'))
152
+ log(b64 ? ` score: ${p.rel(audio)}` : ' the film has no score: silent picture')
153
+ }
154
+ }
155
+ if (steps.frames) {
156
+ const { t0, end, frames, seconds } = frameRange(meta.duration, fps, from, to)
157
+ log(`${slug}: ${layout} at ${fps} fps, ${t0 ? `${t0.toFixed(1)}–` : ''}${end.toFixed(1)} s, ${audio ? `music: ${mode}` : 'no music'}`)
158
+ const tmp = dst.replace(/\.mp4$/i, '.part.mp4')
159
+ mkdirSync(dirname(dst), { recursive: true })
160
+ const ff = spawn('ffmpeg', encodeArgs({ fps, seconds, dst: tmp, audio, t0 }), { stdio: ['pipe', 'inherit', 'inherit'] })
161
+ const done = new Promise((ok, bad) => { ff.on('close', (c) => (c ? bad(new Error('ffmpeg failed')) : ok())); ff.on('error', bad) })
162
+ const began = Date.now()
163
+ for (let i = 0; i < frames; i++) {
164
+ await call((t) => window.__show.seek(t), t0 + i / fps)
165
+ const jpg = await page.screenshot({ type: 'jpeg', quality: 94 })
166
+ if (!ff.stdin.write(jpg)) await new Promise((r) => ff.stdin.once('drain', r))
167
+ if (i % (fps * 10) === 0) log(` ${layout} ${(t0 + i / fps).toFixed(1).padStart(6)}s / ${end.toFixed(1)}s`)
168
+ }
169
+ ff.stdin.end()
170
+ await done.catch((e) => die(e.message))
171
+ if (errors.length) die('the page reported errors: ' + errors.slice(0, 3).join('; '))
172
+ renameSync(tmp, dst)
173
+ log(` wrote ${p.rel(dst)} (${frames} frames, ${Math.round((Date.now() - began) / 1000)}s)`)
174
+ made.push(dst)
175
+ } else if (steps.music) {
176
+ if (!existsSync(dst)) die(`--audio-only needs ${p.rel(dst)}; render it first`)
177
+ const dur = mediaLength(dst)
178
+ const stale = staleRender(dur, meta.duration, Boolean(from) || to != null)
179
+ if (stale) log(` warning: ${p.rel(dst)}: ${stale}`)
180
+ if (audio) {
181
+ const tmp = dst.replace(/\.mp4$/i, '.mux.mp4')
182
+ run('ffmpeg', muxArgs(dst, audio, Number(from) || 0, dur, tmp))
183
+ renameSync(tmp, dst)
184
+ log(` music laid on ${p.rel(dst)}`)
185
+ } else log(` no music to lay on ${p.rel(dst)}`)
186
+ made.push(dst)
187
+ }
188
+ await call((t) => window.__show.seek(t), meta.cover)
189
+ const cover = join(out, `${slug}-${locale}-cover-${SUFFIX[layout]}.jpg`)
190
+ writeFileSync(cover, await page.screenshot({ type: 'jpeg', quality: 92 }))
191
+ log(` cover: ${p.rel(cover)} (film time ${meta.cover.toFixed(1)} s)`)
192
+ if (layout === 'landscape' && p.cfg.coversDir) {
193
+ const siteCover = join(p.root, p.cfg.coversDir, locale === p.site.defaultLocale ? `${slug}.jpg` : `${slug}.${locale}.jpg`)
194
+ mkdirSync(dirname(siteCover), { recursive: true })
195
+ run('ffmpeg', ['-y', '-loglevel', 'error', '-i', cover, '-vf', 'scale=1600:-2', '-q:v', '3', siteCover])
196
+ log(` cover for the site: ${p.rel(siteCover)}`)
197
+ }
198
+ await page.close()
199
+ }
200
+ return made
201
+ } finally {
202
+ await browser.close()
203
+ site.close()
204
+ }
205
+ }
@@ -0,0 +1,91 @@
1
+ // emaki carousel <slug…> | --all: render a campaign day's Instagram carousel (1080×1350 PNGs) from the numbered lines
2
+ // of its day script's "Instagram carousel" section, into <campaign>/carousels/<slug>/slide-01.png …, which
3
+ // `emaki stage` turns into JPEG and stages. Needs Playwright with Chromium.
4
+ //
5
+ // The look is a paper card in the Zen-Sumi palette. emaki.config.json "carousel" adjusts it: marks ({ topic: "構" }),
6
+ // mark (default), footer (default: the site's address), swipe and last (the corner line), or template (an HTML file
7
+ // of your own with {text} {i} {total} {topic} {mark} {size} {cls} {bar} {swipe} {footer}).
8
+ import { mkdirSync, readdirSync, readFileSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { chromium } from './capture.js'
11
+ import { campaignDir, dayScriptPath, slidesOf, slugOfScript, topicOf } from './day-script.js'
12
+ import { die, exists, pad2 } from './util.js'
13
+
14
+ const PAGE = `<!doctype html><html><head><meta charset="utf-8">
15
+ <link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400&family=Inter:wght@400;600&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet">
16
+ <style>
17
+ html,body{margin:0;width:1080px;height:1350px;background:#F3F0E9;color:#1F1916}
18
+ body{position:relative;font-family:Inter,system-ui,sans-serif;
19
+ background-image:radial-gradient(circle at 18px 18px,#DCD7CD 2px,transparent 2.5px);background-size:36px 36px}
20
+ .k{position:absolute;left:84px;top:78px;font-family:'Hiragino Mincho ProN','Yu Mincho',serif;font-size:76px;color:#C25237;line-height:1}
21
+ .p{position:absolute;left:184px;top:104px;font:500 22px 'JetBrains Mono',monospace;letter-spacing:.14em;text-transform:uppercase;color:#7F7975}
22
+ .n{position:absolute;right:84px;top:104px;font:500 22px 'JetBrains Mono',monospace;color:#7F7975}
23
+ .card{position:absolute;left:84px;right:84px;top:250px;bottom:250px;display:flex;align-items:center;padding:0 64px;
24
+ background:#FCFAF6;border:2px solid #DCD7CD;border-radius:28px}
25
+ .t{font-family:Fraunces,Georgia,serif;font-weight:400;font-size:{size}px;line-height:1.14;letter-spacing:-.02em;white-space:pre-line}
26
+ .first .t{font-weight:300}
27
+ .bar{position:absolute;left:148px;bottom:310px;width:120px;height:6px;border-radius:3px;background:#C25237}
28
+ .u{position:absolute;left:84px;bottom:120px;font:500 26px 'JetBrains Mono',monospace;color:#C25237}
29
+ .s{position:absolute;right:84px;bottom:120px;font:600 24px Inter,sans-serif;color:#48413D}
30
+ </style></head><body class="{cls}">
31
+ <div class="k">{mark}</div><div class="p">{topic}</div><div class="n">{i} / {total}</div>
32
+ <div class="card"><div class="t">{text}</div></div>{bar}
33
+ <div class="u">{footer}</div><div class="s">{swipe}</div>
34
+ </body></html>`
35
+
36
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
37
+
38
+ /** The slides and the topic of a day's carousel. */
39
+ export function carouselSlides(p, slug, locale = p.site.defaultLocale) {
40
+ const f = dayScriptPath(p, slug, locale)
41
+ if (!f) die(`no day script for ${slug} in ${p.rel(join(campaignDir(p), 'days'))}/`)
42
+ const md = readFileSync(f, 'utf-8')
43
+ return { topic: topicOf(md), slides: slidesOf(md) }
44
+ }
45
+
46
+ /** One slide's page. Slide 1 is set large with the accent bar; longer text is set smaller. */
47
+ export function slideHtml(p, text, i, total, topic) {
48
+ const c = p.cfg.carousel ?? {}
49
+ const tpl = c.template ? readFileSync(join(p.root, c.template), 'utf-8') : PAGE
50
+ const n = text.length, size = i === 1 ? 92 : n < 60 ? 72 : n < 110 ? 60 : 50
51
+ const vals = {
52
+ size, cls: i === 1 ? 'first' : '', mark: esc(c.marks?.[topic] ?? c.mark ?? ''), topic: esc(topic), i, total, text: esc(text),
53
+ bar: i === 1 ? '<div class="bar"></div>' : '', footer: esc(c.footer ?? (p.site.url ?? '').replace(/^https?:\/\//, '').replace(/\/$/, '')),
54
+ swipe: esc(i < total ? (c.swipe ?? 'Swipe →') : (c.last ?? 'Full story: link in bio'))
55
+ }
56
+ return tpl.replace(/\{(\w+)\}/g, (m, k) => (k in vals ? String(vals[k]) : m))
57
+ }
58
+
59
+ /** Headless Chromium at the carousel's size; shoot(html, file) writes one PNG. */
60
+ async function openChromium() {
61
+ const browser = await (await chromium()).launch()
62
+ const page = await browser.newPage({ viewport: { width: 1080, height: 1350 } })
63
+ return {
64
+ shoot: async (html, file) => { await page.setContent(html, { waitUntil: 'networkidle' }); await page.screenshot({ path: file }) },
65
+ close: () => browser.close()
66
+ }
67
+ }
68
+
69
+ export async function carousel(p, slugs = [], { all = false, locale = p.site.defaultLocale, open = openChromium, log = console.info } = {}) {
70
+ const days = join(campaignDir(p), 'days')
71
+ if (all) slugs = exists(days) ? readdirSync(days).filter((n) => /^day-\d+-.+\.md$/.test(n)).sort().map(slugOfScript) : []
72
+ if (!slugs.length) die('name a slug, or --all for every day script')
73
+ const work = slugs.map((slug) => {
74
+ const s = carouselSlides(p, slug, locale)
75
+ if (!s.slides.length) die(`${slug}: no carousel slides (numbered lines under "## N · Instagram carousel")`)
76
+ return { slug, ...s }
77
+ })
78
+ const shot = await open(), made = []
79
+ try {
80
+ for (const w of work) {
81
+ const dir = join(campaignDir(p), 'carousels', w.slug)
82
+ mkdirSync(dir, { recursive: true })
83
+ for (const [k, text] of w.slides.entries()) await shot.shoot(slideHtml(p, text, k + 1, w.slides.length, w.topic), join(dir, `slide-${pad2(k + 1)}.png`))
84
+ log(`${w.slug}: ${w.slides.length} slides → ${p.rel(dir)}`)
85
+ made.push({ slug: w.slug, slides: w.slides.length, dir: p.rel(dir) })
86
+ }
87
+ } finally {
88
+ await shot.close()
89
+ }
90
+ return made
91
+ }
package/src/config.js ADDED
@@ -0,0 +1,32 @@
1
+ // The project a command runs in: emaki.config.json at its root (all optional), content/ (deployed: films, stories,
2
+ // site.json) and production/ (never deployed: takes, renders, sheets).
3
+ import { join, relative } from 'node:path'
4
+ import { die, exists, load } from './util.js'
5
+
6
+ export const SIZES = { landscape: [1920, 1080], portrait: [1080, 1920] }
7
+ export const SUFFIX = { landscape: '16x9', portrait: '9x16' }
8
+ export const KEY = /\{\{\s*([\w.-]+)\s*\}\}/g
9
+
10
+ /** @param {string} [root] */
11
+ export function project(root = process.cwd()) {
12
+ const cfgPath = join(root, 'emaki.config.json')
13
+ const cfg = exists(cfgPath) ? load(cfgPath) : {}
14
+ const content = join(root, cfg.content ?? 'content')
15
+ const production = join(root, cfg.production ?? 'production')
16
+ const films = join(content, 'films')
17
+ const sitePath = join(content, 'site.json')
18
+ const site = exists(sitePath) ? load(sitePath) : { locales: ['en'], defaultLocale: 'en' }
19
+ const p = {
20
+ root, cfg, cfgPath, content, production, films, site,
21
+ lead: cfg.lead ?? 0.6,
22
+ tail: cfg.tail ?? 1.2,
23
+ rel: (x) => relative(root, x) || '.',
24
+ filmDir(slug) {
25
+ const d = join(films, slug)
26
+ if (!exists(join(d, 'film.json'))) die(`no film "${slug}" in ${p.rel(films)}/`)
27
+ return d
28
+ },
29
+ prod: (slug, locale, ...parts) => join(production, slug, locale, ...parts)
30
+ }
31
+ return p
32
+ }
@@ -0,0 +1,66 @@
1
+ // A campaign day script (<campaign>/days/day-NN-<slug>.md, or days/<locale>/…): one piece's copy for every channel.
2
+ // Reads both the website's labels (**YouTube title:**, **YouTube description:**) and the plugin template's (**Title:**,
3
+ // **Description:** under "## N · YouTube").
4
+ import { readdirSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { exists } from './util.js'
7
+
8
+ /** The campaign folder: emaki.config.json "campaign" (default campaign/). */
9
+ export const campaignDir = (p) => join(p.root, p.cfg.campaign ?? 'campaign')
10
+
11
+ /** The slug in a day script's file name: day-07-some-slug.md → some-slug. */
12
+ export const slugOfScript = (file) => file.replace(/^.*\//, '').replace(/\.md$/, '').replace(/^day-\d+-/, '')
13
+
14
+ /** Path of the day script for a slug (the locale's folder first), or null. */
15
+ export function dayScriptPath(p, slug, locale) {
16
+ for (const dir of [join(campaignDir(p), 'days', locale), join(campaignDir(p), 'days')]) {
17
+ if (!exists(dir)) continue
18
+ const f = readdirSync(dir).sort().find((n) => /^day-\d+-.+\.md$/.test(n) && slugOfScript(n) === slug)
19
+ if (f) return join(dir, f)
20
+ }
21
+ return null
22
+ }
23
+
24
+ export const dayScript = (p, slug, locale) => {
25
+ const f = dayScriptPath(p, slug, locale)
26
+ return f ? readFileSync(f, 'utf-8') : null
27
+ }
28
+
29
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
30
+
31
+ /** The text after **Label:** up to a blank line before the next label, the next label line, a heading, or the end. */
32
+ export function field(md, ...labels) {
33
+ for (const label of labels) {
34
+ const m = md.match(new RegExp(`\\*\\*${esc(label)}:\\*\\*[ \\t]*([\\s\\S]*?)(?=\\n\\s*\\n\\*\\*|\\n\\*\\*[^*\\n]+:\\*\\*|\\n#{1,6} |$(?![\\s\\S]))`))
35
+ if (m) return m[1].trim()
36
+ }
37
+ return ''
38
+ }
39
+
40
+ /** "1. text" lines of a block, numbers dropped. */
41
+ export const numbered = (block) => block.split('\n').map((l) => l.trim()).filter((l) => /^\d+\.\s/.test(l)).map((l) => l.replace(/^\d+\.\s*/, '').trim())
42
+
43
+ /** The channel copy of a day script. */
44
+ export function channelCopy(md) {
45
+ const ytDesc = field(md, 'YouTube description', 'Description')
46
+ const thread = md.includes('**Thread:**') ? md.split('**Thread:**')[1].split('\n## ')[0] : ''
47
+ return {
48
+ youtube: { title: field(md, 'YouTube title', 'Title').slice(0, 100), description: ytDesc, tags: [...ytDesc.matchAll(/#(\w+)/g)].map((m) => m[1]) },
49
+ caption: [field(md, 'Caption'), field(md, 'Hashtags')].filter(Boolean).join('\n\n'),
50
+ x: { text: field(md, 'Post'), thread: numbered(thread) }
51
+ }
52
+ }
53
+
54
+ /** The topic in the heading: "# Day 01 · Mon Nov 16 · DBD: Title" → DBD. */
55
+ export const topicOf = (md) => md.match(/^# Day \d+ · .+? · (.+?): /m)?.[1] ?? ''
56
+
57
+ /** The carousel slides: the numbered lines of "## N · Instagram carousel" before **Caption:** (\n in a line breaks it). */
58
+ export function slidesOf(md) {
59
+ const parts = md.split(/^## \d+ · Instagram carousel.*$/m)
60
+ if (parts.length < 2) return []
61
+ const block = parts[1].split('**Caption:**')[0].split(/^## /m)[0]
62
+ return numbered(block).map((s) => s.replaceAll('\\n', '\n'))
63
+ }
64
+
65
+ /** The voiceover table: | # | Voiceover | On screen | rows. */
66
+ export const beatsOf = (md) => [...md.matchAll(/^\| (\d+) \| (.+?) \| (.+?) \|$/gm)].map((m) => ({ n: Number(m[1]), text: m[2].trim(), screen: m[3].trim() }))
@@ -0,0 +1,37 @@
1
+ // The posting desk as the producing machine sees it: the HTTP contract of @senseihq/emaki-posting's createDesk
2
+ // (media/<key> PUT, stage, production, requests), called with the stager's Cloudflare Access service token.
3
+ // ADMIN_ORIGIN (default: content/site.json url), ADMIN_API (default /api/admin),
4
+ // STAGER_CLIENT_ID, STAGER_CLIENT_SECRET.
5
+ import { createHash } from 'node:crypto'
6
+ import { validKey } from '@senseihq/emaki-posting'
7
+ import { callJson, need } from './http.js'
8
+ import { die } from './util.js'
9
+
10
+ export const deskOrigin = (p, env) => (env.ADMIN_ORIGIN || p.site.url || '').replace(/\/$/, '')
11
+
12
+ export function deskClient(p, { env = process.env, fetch = globalThis.fetch } = {}) {
13
+ need(env, 'STAGER_CLIENT_ID', 'STAGER_CLIENT_SECRET')
14
+ const origin = deskOrigin(p, env)
15
+ if (!origin) die('no desk origin: set ADMIN_ORIGIN, or "url" in content/site.json')
16
+ const api = origin + (env.ADMIN_API || '/api/admin').replace(/\/$/, '')
17
+ const auth = { 'CF-Access-Client-Id': env.STAGER_CLIENT_ID, 'CF-Access-Client-Secret': env.STAGER_CLIENT_SECRET }
18
+ const post = (path, data) => callJson(fetch, 'POST', api + path, { body: JSON.stringify(data), headers: { ...auth, 'content-type': 'application/json' } })
19
+ return {
20
+ origin,
21
+ /** Uploads one file to the desk's media store; the desk checks the sha256. */
22
+ async putMedia(key, bytes, type) {
23
+ if (!validKey(key)) die(`bad media key "${key}": <slug>/<file>, lower-case letters, digits, . _ -`)
24
+ const sha256 = createHash('sha256').update(bytes).digest('hex')
25
+ await callJson(fetch, 'PUT', `${api}/media/${key}`, { body: bytes, headers: { ...auth, 'x-content-sha256': sha256, 'content-type': type } })
26
+ return sha256
27
+ },
28
+ /** Stages one channel's post (media already uploaded); returns { content_sha }. */
29
+ stage: (slug, channel, postBody) => post('/stage', { slug, channel, post: postBody }),
30
+ /** Reports scripts and production status for the desk's plan; returns { saved }. */
31
+ production: (items) => post('/production', { items }),
32
+ /** The open requests from the desk, each with its thread. */
33
+ requests: async () => (await callJson(fetch, 'GET', api + '/requests', { headers: auth })).requests ?? [],
34
+ /** Answers a request, optionally moving it to working or done. */
35
+ reply: (id, reply, status) => post('/requests', { id, reply, ...(status ? { status } : {}) })
36
+ }
37
+ }
@@ -0,0 +1,57 @@
1
+ // emaki stage status | requests | reply: the producing machine's side of the desk's plan. It reports each piece's
2
+ // script and what exists for it (the desk shows it beside the piece), reads the open motion requests people left on
3
+ // the desk, and answers them.
4
+ import { readdirSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { campaignDir, dayScriptPath } from './day-script.js'
7
+ import { deskClient } from './desk-client.js'
8
+ import { filmFiles, storiesIndex } from './stories.js'
9
+ import { die, exists, load } from './util.js'
10
+
11
+ const count = (dir, test) => (exists(dir) ? readdirSync(dir).filter(test).length : 0)
12
+
13
+ /** One piece's script and production status, in the shape the desk stores (Production in @senseihq/emaki-posting). */
14
+ export function pieceStatus(p, slug, locale) {
15
+ const film = join(p.films, slug), files = filmFiles(p, slug, locale)
16
+ const voice = join(film, 'voice', `${locale}.json`), fj = join(film, 'film.json')
17
+ const takesNeeded = exists(voice) ? load(voice).length : exists(fj) ? (load(fj).scenes ?? []).length : 0
18
+ const base = { motion: exists(fj), takes: count(p.prod(slug, locale, 'takes'), (n) => /^take-\d+\.(wav|mp3|m4a|aiff)$/.test(n)), takesNeeded }
19
+ const day = dayScriptPath(p, slug, locale)
20
+ if (day)
21
+ return { script: readFileSync(day, 'utf-8'), status: { ...base, short: Boolean(files.tall), carousel: count(join(campaignDir(p), 'carousels', slug), (n) => n.endsWith('.png')) } }
22
+ const script = join(film, 'script.md')
23
+ return { script: exists(script) ? readFileSync(script, 'utf-8') : null, status: { ...base, film: true, render: Boolean(files.wide) } }
24
+ }
25
+
26
+ /** Reports every story (or one) to the desk's plan. */
27
+ export async function productionStatus(p, slug, { locale, env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
28
+ locale ??= p.site.defaultLocale
29
+ const desk = deskClient(p, { env, fetch })
30
+ const ip = storiesIndex(p)
31
+ const slugs = (exists(ip) ? load(ip) : []).map((e) => e.slug).filter((s) => !slug || s === slug)
32
+ if (slug && !slugs.length) die(`${slug} is not in ${p.rel(ip)}`)
33
+ const r = await desk.production(slugs.map((s) => ({ slug: s, ...pieceStatus(p, s, locale) })))
34
+ log(`reported ${r.saved} piece(s)`)
35
+ return r
36
+ }
37
+
38
+ /** The open motion requests, each with its thread. */
39
+ export async function deskRequests(p, { env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
40
+ const list = await deskClient(p, { env, fetch }).requests()
41
+ if (!list.length) log('no open requests')
42
+ for (const r of list) {
43
+ log(`#${r.id} ${r.slug} · ${r.kind} · ${r.status} · ${r.author} ${String(r.at ?? '').slice(0, 16)}`)
44
+ log(` ${r.body}`)
45
+ for (const t of r.thread ?? []) log(` ↳ ${t.author}: ${t.body}`)
46
+ }
47
+ return list
48
+ }
49
+
50
+ /** Answers request `id`; status 'working' or 'done' moves it on the desk. */
51
+ export async function deskReply(p, id, text, { status, env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
52
+ const n = Number(id)
53
+ if (!Number.isInteger(n) || n <= 0) die(`request id must be a number (got "${id}")`)
54
+ if (status && !['working', 'done'].includes(status)) die(`status must be working or done (got "${status}")`)
55
+ await deskClient(p, { env, fetch }).reply(n, text ?? '', status)
56
+ log('sent')
57
+ }
package/src/films.js ADDED
@@ -0,0 +1,152 @@
1
+ // manifest, validate, new: the content contracts. A film is a folder (film.json, look.css, scene-<id>.json, score.js,
2
+ // strings/<locale>.json, voice/<locale>.json, timing.<locale>.json); a story is index.json + stories/<locale>/<slug>.json.
3
+ import { readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { KEY } from './config.js'
7
+ import { die, exists, load, save, today } from './util.js'
8
+
9
+ export const TEMPLATES = fileURLToPath(new URL('../templates/', import.meta.url))
10
+
11
+ export const filmSlugs = (p) =>
12
+ exists(p.films) ? readdirSync(p.films).filter((d) => exists(join(p.films, d, 'film.json'))).sort() : []
13
+
14
+ /** content/films/index.json: the film list the fetch loader reads. */
15
+ export function manifest(p) {
16
+ const slugs = filmSlugs(p)
17
+ save(join(p.films, 'index.json'), slugs)
18
+ return { count: slugs.length, path: p.rel(join(p.films, 'index.json')) }
19
+ }
20
+
21
+ /** Every {{key}} a scene uses. */
22
+ export function keysIn(obj, out = new Set()) {
23
+ if (typeof obj === 'string') for (const m of obj.matchAll(KEY)) out.add(m[1])
24
+ else if (Array.isArray(obj)) obj.forEach((x) => keysIn(x, out))
25
+ else if (obj && typeof obj === 'object') Object.values(obj).forEach((x) => keysIn(x, out))
26
+ return out
27
+ }
28
+
29
+ const list = (xs) => xs.slice(0, 8).join(', ') + (xs.length > 8 ? ' …' : '')
30
+
31
+ export function validateFilm(p, slug) {
32
+ const issues = [], d = p.filmDir(slug), film = load(join(d, 'film.json')), used = new Set()
33
+ if (!exists(join(d, 'look.css'))) issues.push('look.css is missing')
34
+ else {
35
+ // Dark is opt-in: film.json's dark block turns it on, look.css draws it. One without the other is a mistake.
36
+ const styled = readFileSync(join(d, 'look.css'), 'utf-8').includes('#stage[data-mode="dark"]')
37
+ if (film.dark && !styled) issues.push('film.json has a dark block but look.css never styles #stage[data-mode="dark"]')
38
+ if (!film.dark && styled) issues.push('look.css styles #stage[data-mode="dark"] but film.json has no dark block (those styles never apply)')
39
+ }
40
+ for (const s of film.scenes) {
41
+ const sj = join(d, `scene-${s.id}.json`), js = join(d, `scene-${s.id}.js`)
42
+ if (!exists(sj) && !exists(js)) {
43
+ issues.push(`scene ${s.id}: no scene-${s.id}.json (or .js)`)
44
+ continue
45
+ }
46
+ if (exists(sj)) {
47
+ const spec = load(sj)
48
+ keysIn(spec, used)
49
+ if (!('portrait' in spec)) issues.push(`scene ${s.id}: no portrait block (needed for 9:16 and article figures)`)
50
+ const ids = (spec.components ?? []).map((c) => c.id)
51
+ if (ids.length !== new Set(ids).size) issues.push(`scene ${s.id}: duplicate component ids`)
52
+ }
53
+ if (!(s.dur > 0 && s.dur < 60)) issues.push(`scene ${s.id}: dur ${s.dur} looks wrong`)
54
+ }
55
+ if (!film.cover && film.scenes.at(-1)?.id !== 'close') issues.push('the last scene should be "close" (the punchline card is the cover), or film.json should name its cover')
56
+ for (const loc of p.site.locales) {
57
+ const sp = join(d, 'strings', `${loc}.json`)
58
+ if (!exists(sp)) {
59
+ if (used.size) issues.push(`strings/${loc}.json is missing`)
60
+ continue
61
+ }
62
+ const st = load(sp)
63
+ const missing = [...used].filter((k) => !(k in st)).sort()
64
+ const unused = Object.keys(st).filter((k) => !used.has(k)).sort()
65
+ if (missing.length) issues.push(`strings/${loc}.json: missing ${list(missing)}`)
66
+ if (unused.length) issues.push(`strings/${loc}.json: unused ${list(unused)}`)
67
+ const vp = join(d, 'voice', `${loc}.json`)
68
+ if (exists(vp)) {
69
+ const v = new Set(load(vp).map((x) => x.scene))
70
+ const gap = film.scenes.map((s) => s.id).filter((id) => !v.has(id))
71
+ if (gap.length) issues.push(`voice/${loc}.json: no line for ${gap.join(', ')}`)
72
+ }
73
+ }
74
+ return issues
75
+ }
76
+
77
+ export function validateStory(p, entry) {
78
+ const issues = [], slug = entry.slug
79
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.publish_date ?? '')) issues.push('publish_date must be YYYY-MM-DD')
80
+ const film = entry.film ?? (exists(join(p.films, slug, 'film.json')) ? slug : null)
81
+ const sceneIds = new Set(film ? load(join(p.films, film, 'film.json')).scenes.map((s) => s.id) : [])
82
+ for (const loc of p.site.locales) {
83
+ const f = join(p.content, 'stories', loc, `${slug}.json`)
84
+ if (!exists(f)) {
85
+ issues.push(loc === p.site.defaultLocale ? `stories/${loc}/${slug}.json is missing` : `(info) stories/${loc}/${slug}.json not translated yet`)
86
+ continue
87
+ }
88
+ const b = load(f)
89
+ for (const k of ['title', 'dek', 'sections']) if (!b[k] || (Array.isArray(b[k]) && !b[k].length)) issues.push(`${loc}: ${k} is empty`)
90
+ if (film && !b.takeaway) issues.push(`${loc}: a film story needs a takeaway (the closing line)`)
91
+ for (const s of b.sections ?? [])
92
+ if (s.motion == null && s.figure == null && film && !sceneIds.has(s.id) && !['more', 'sources'].includes(s.id))
93
+ issues.push(`(info) ${loc}: section ${s.id} has no figure (no scene of that id)`)
94
+ }
95
+ return issues
96
+ }
97
+
98
+ /** All problems (lines prefixed "(info)" are notes, not failures). */
99
+ export function validate(p, slug) {
100
+ const ip = join(p.content, 'stories', 'index.json')
101
+ const index = exists(ip) ? load(ip) : []
102
+ const out = []
103
+ for (const s of slug ? [slug] : filmSlugs(p)) for (const i of validateFilm(p, s)) out.push(`film ${s}: ${i}`)
104
+ for (const e of index) if (!slug || e.slug === slug) for (const i of validateStory(p, e)) out.push(`story ${e.slug}: ${i}`)
105
+ return { lines: out, problems: out.filter((l) => !l.includes('(info)')).length }
106
+ }
107
+
108
+ /** Scaffolds a story + film with every locale's strings, voice script and story body. */
109
+ export function newFilm(p, slug, { scenes, title, date } = {}) {
110
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) die('slug: lower-case letters, digits and dashes')
111
+ const d = join(p.films, slug)
112
+ if (exists(d)) die(`${p.rel(d)} already exists`)
113
+ const ids = String(scenes ?? 'hook,idea,how').split(',').map((s) => s.trim()).filter(Boolean)
114
+ if (ids.at(-1) !== 'close') ids.push('close')
115
+ const T = join(TEMPLATES, 'film')
116
+ const name = (i) => i.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
117
+ const film = {
118
+ title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9', dark: { background: '#1E1B18' },
119
+ fonts: { display: { family: 'Fraunces', weights: [300, 400] }, sans: { family: 'Inter', weights: [400, 600] } },
120
+ scenes: ids.map((i) => ({ id: i, name: name(i), dur: i === 'close' ? 5.5 : 10, desc: 'What this scene shows.' }))
121
+ }
122
+ save(join(d, 'film.json'), film)
123
+ mkdirSync(d, { recursive: true })
124
+ writeFileSync(join(d, 'look.css'), readFileSync(join(T, 'look.css'), 'utf-8'))
125
+ writeFileSync(join(d, 'score.js'), readFileSync(join(T, 'score.js'), 'utf-8'))
126
+ const tpl = readFileSync(join(T, 'scene-template.json'), 'utf-8'), close = readFileSync(join(T, 'scene-close.json'), 'utf-8')
127
+ let strings = {}
128
+ const voice = []
129
+ for (const i of ids) {
130
+ writeFileSync(join(d, `scene-${i}.json`), (i === 'close' ? close : tpl).replaceAll('__ID__', i))
131
+ strings = i === 'close'
132
+ ? { ...strings, 'close.title': 'The punchline.', 'close.sub': 'One line under it.' }
133
+ : { ...strings, [`${i}.eyebrow`]: name(i), [`${i}.line`]: 'The headline for this scene.', [`${i}.sub`]: 'One supporting line.', [`${i}.label`]: 'Label' }
134
+ voice.push({ scene: i, text: 'What the narrator says over this scene.', say: null })
135
+ }
136
+ for (const loc of p.site.locales) {
137
+ save(join(d, 'strings', `${loc}.json`), strings)
138
+ save(join(d, 'voice', `${loc}.json`), voice)
139
+ const body = join(p.content, 'stories', loc, `${slug}.json`)
140
+ if (!exists(body)) save(body, {
141
+ title: film.title, dek: 'One or two sentences.',
142
+ sections: ids.filter((i) => !['hook', 'close'].includes(i)).map((i) => ({ id: i, eyebrow: name(i), title: 'Section title', body: ['Paragraph.'] })),
143
+ takeaway: strings['close.title'], takeawaySub: strings['close.sub'], sources: []
144
+ })
145
+ }
146
+ const ip = join(p.content, 'stories', 'index.json')
147
+ const index = exists(ip) ? load(ip) : []
148
+ if (!index.some((e) => e.slug === slug)) index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
149
+ save(ip, index.sort((a, b) => a.publish_date.localeCompare(b.publish_date)))
150
+ manifest(p)
151
+ return { slug, scenes: ids.length, locales: p.site.locales.length }
152
+ }