@senseihq/emaki-cli 0.1.0 → 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.
- package/README.md +42 -7
- package/package.json +4 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/modules/campaign/README.md +10 -3
- package/plugin/modules/campaign/day-script.template.md +2 -1
- package/plugin/modules/posting-desk/README.md +2 -2
- package/plugin/skills/emaki/references/03-content-model.md +7 -4
- package/plugin/skills/emaki/references/04-scene-authoring.md +3 -0
- package/plugin/skills/emaki/references/05-voice-and-video.md +41 -8
- package/plugin/skills/emaki/references/09-publishing.md +5 -2
- package/plugin/skills/story-media/SKILL.md +2 -0
- package/plugin/skills/story-publish/SKILL.md +18 -4
- package/src/api.js +12 -1
- package/src/campaign.js +157 -0
- package/src/capture.js +69 -33
- package/src/carousel.js +91 -0
- package/src/day-script.js +66 -0
- package/src/desk-client.js +37 -0
- package/src/desk-plan.js +57 -0
- package/src/films.js +12 -5
- package/src/http.js +30 -0
- package/src/index.js +161 -3
- package/src/init.js +5 -4
- package/src/media.js +236 -0
- package/src/migrate.js +67 -0
- package/src/publish.js +118 -0
- package/src/stage.js +107 -0
- package/src/stories.js +66 -0
- package/src/upload/instagram.js +34 -0
- package/src/upload/youtube.js +90 -0
- package/src/util.js +7 -0
- package/src/voice.js +119 -40
- package/src/youtube-text.js +58 -0
- package/templates/content/films/measure-the-right-work/film.json +9 -0
- package/templates/content/films/measure-the-right-work/look.css +1 -0
- package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
- package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
- package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
- package/templates/film/look.css +1 -0
package/src/capture.js
CHANGED
|
@@ -2,17 +2,25 @@
|
|
|
2
2
|
// window.__show = { meta, ready, seek(t), audio() } (installCapture in @senseihq/emaki; ShowPage in each wrapper).
|
|
3
3
|
// Playwright is an optional dependency: `npm i -D playwright && npx playwright install chromium`.
|
|
4
4
|
import { spawn } from 'node:child_process'
|
|
5
|
-
import { mkdirSync, renameSync, writeFileSync, readFileSync } from 'node:fs'
|
|
5
|
+
import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync } from 'node:fs'
|
|
6
6
|
import { connect } from 'node:net'
|
|
7
|
-
import { join } from 'node:path'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
8
|
import { SIZES, SUFFIX } from './config.js'
|
|
9
|
-
import {
|
|
9
|
+
import { encodeArgs, frameRange, musicFor, muxArgs, renderOut, renderSteps, retrying, staleRender } from './media.js'
|
|
10
|
+
import { die, mediaLength, run } from './util.js'
|
|
10
11
|
|
|
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() {
|
|
12
20
|
try {
|
|
13
21
|
return (await import('playwright')).chromium
|
|
14
22
|
} catch {
|
|
15
|
-
return die('sheet and
|
|
23
|
+
return die('sheet, render and carousel need Playwright: npm i -D playwright && npx playwright install chromium')
|
|
16
24
|
}
|
|
17
25
|
}
|
|
18
26
|
|
|
@@ -113,52 +121,80 @@ export async function sheet(p, slug, { locale, url, at, log = console.info } = {
|
|
|
113
121
|
}
|
|
114
122
|
}
|
|
115
123
|
|
|
116
|
-
/** Frame-by-frame capture to MP4
|
|
117
|
-
|
|
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
|
+
} = {}) {
|
|
118
132
|
p.filmDir(slug)
|
|
133
|
+
const steps = renderSteps({ audioOnly, coverOnly })
|
|
119
134
|
const layouts = o === 'both' ? ['landscape', 'portrait'] : [o]
|
|
120
135
|
const out = p.prod(slug, locale, 'render')
|
|
121
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}`)
|
|
122
139
|
const site = await openSite(p, url), made = []
|
|
123
140
|
const browser = await (await chromium()).launch()
|
|
124
141
|
try {
|
|
125
|
-
let
|
|
142
|
+
let audio
|
|
126
143
|
for (const layout of layouts) {
|
|
127
144
|
const { page, meta, errors } = await openShow(browser, site, slug, layout, locale)
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
+
}
|
|
132
154
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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)
|
|
146
187
|
}
|
|
147
|
-
|
|
148
|
-
await done.catch((e) => die(e.message))
|
|
149
|
-
if (errors.length) die('the page reported errors: ' + errors.slice(0, 3).join('; '))
|
|
150
|
-
renameSync(tmp, dst)
|
|
151
|
-
await page.evaluate((t) => window.__show.seek(t), meta.cover)
|
|
188
|
+
await call((t) => window.__show.seek(t), meta.cover)
|
|
152
189
|
const cover = join(out, `${slug}-${locale}-cover-${SUFFIX[layout]}.jpg`)
|
|
153
190
|
writeFileSync(cover, await page.screenshot({ type: 'jpeg', quality: 92 }))
|
|
154
|
-
log(`
|
|
191
|
+
log(` cover: ${p.rel(cover)} (film time ${meta.cover.toFixed(1)} s)`)
|
|
155
192
|
if (layout === 'landscape' && p.cfg.coversDir) {
|
|
156
193
|
const siteCover = join(p.root, p.cfg.coversDir, locale === p.site.defaultLocale ? `${slug}.jpg` : `${slug}.${locale}.jpg`)
|
|
157
|
-
mkdirSync(
|
|
194
|
+
mkdirSync(dirname(siteCover), { recursive: true })
|
|
158
195
|
run('ffmpeg', ['-y', '-loglevel', 'error', '-i', cover, '-vf', 'scale=1600:-2', '-q:v', '3', siteCover])
|
|
159
196
|
log(` cover for the site: ${p.rel(siteCover)}`)
|
|
160
197
|
}
|
|
161
|
-
made.push(dst)
|
|
162
198
|
await page.close()
|
|
163
199
|
}
|
|
164
200
|
return made
|
package/src/carousel.js
ADDED
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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
|
+
}
|
|
@@ -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
|
+
}
|
package/src/desk-plan.js
ADDED
|
@@ -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
CHANGED
|
@@ -31,6 +31,12 @@ const list = (xs) => xs.slice(0, 8).join(', ') + (xs.length > 8 ? ' …' : '')
|
|
|
31
31
|
export function validateFilm(p, slug) {
|
|
32
32
|
const issues = [], d = p.filmDir(slug), film = load(join(d, 'film.json')), used = new Set()
|
|
33
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
|
+
}
|
|
34
40
|
for (const s of film.scenes) {
|
|
35
41
|
const sj = join(d, `scene-${s.id}.json`), js = join(d, `scene-${s.id}.js`)
|
|
36
42
|
if (!exists(sj) && !exists(js)) {
|
|
@@ -46,7 +52,7 @@ export function validateFilm(p, slug) {
|
|
|
46
52
|
}
|
|
47
53
|
if (!(s.dur > 0 && s.dur < 60)) issues.push(`scene ${s.id}: dur ${s.dur} looks wrong`)
|
|
48
54
|
}
|
|
49
|
-
if (film.scenes.at(-1)?.id !== 'close') issues.push('the last scene should be "close" (the punchline card is the cover)')
|
|
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')
|
|
50
56
|
for (const loc of p.site.locales) {
|
|
51
57
|
const sp = join(d, 'strings', `${loc}.json`)
|
|
52
58
|
if (!exists(sp)) {
|
|
@@ -83,7 +89,7 @@ export function validateStory(p, entry) {
|
|
|
83
89
|
for (const k of ['title', 'dek', 'sections']) if (!b[k] || (Array.isArray(b[k]) && !b[k].length)) issues.push(`${loc}: ${k} is empty`)
|
|
84
90
|
if (film && !b.takeaway) issues.push(`${loc}: a film story needs a takeaway (the closing line)`)
|
|
85
91
|
for (const s of b.sections ?? [])
|
|
86
|
-
if (s.motion == null && film && !sceneIds.has(s.id) && !['more', 'sources'].includes(s.id))
|
|
92
|
+
if (s.motion == null && s.figure == null && film && !sceneIds.has(s.id) && !['more', 'sources'].includes(s.id))
|
|
87
93
|
issues.push(`(info) ${loc}: section ${s.id} has no figure (no scene of that id)`)
|
|
88
94
|
}
|
|
89
95
|
return issues
|
|
@@ -109,7 +115,7 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
|
|
|
109
115
|
const T = join(TEMPLATES, 'film')
|
|
110
116
|
const name = (i) => i.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
|
|
111
117
|
const film = {
|
|
112
|
-
title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9',
|
|
118
|
+
title: title || name(slug), look: 'Describe the look in one paragraph.', background: '#F3F0E9', dark: { background: '#1E1B18' },
|
|
113
119
|
fonts: { display: { family: 'Fraunces', weights: [300, 400] }, sans: { family: 'Inter', weights: [400, 600] } },
|
|
114
120
|
scenes: ids.map((i) => ({ id: i, name: name(i), dur: i === 'close' ? 5.5 : 10, desc: 'What this scene shows.' }))
|
|
115
121
|
}
|
|
@@ -130,7 +136,8 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
|
|
|
130
136
|
for (const loc of p.site.locales) {
|
|
131
137
|
save(join(d, 'strings', `${loc}.json`), strings)
|
|
132
138
|
save(join(d, 'voice', `${loc}.json`), voice)
|
|
133
|
-
|
|
139
|
+
const body = join(p.content, 'stories', loc, `${slug}.json`)
|
|
140
|
+
if (!exists(body)) save(body, {
|
|
134
141
|
title: film.title, dek: 'One or two sentences.',
|
|
135
142
|
sections: ids.filter((i) => !['hook', 'close'].includes(i)).map((i) => ({ id: i, eyebrow: name(i), title: 'Section title', body: ['Paragraph.'] })),
|
|
136
143
|
takeaway: strings['close.title'], takeawaySub: strings['close.sub'], sources: []
|
|
@@ -138,7 +145,7 @@ export function newFilm(p, slug, { scenes, title, date } = {}) {
|
|
|
138
145
|
}
|
|
139
146
|
const ip = join(p.content, 'stories', 'index.json')
|
|
140
147
|
const index = exists(ip) ? load(ip) : []
|
|
141
|
-
index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
|
|
148
|
+
if (!index.some((e) => e.slug === slug)) index.push({ slug, publish_date: date || today(), kind: 'film', tags: [], minutes: 4 })
|
|
142
149
|
save(ip, index.sort((a, b) => a.publish_date.localeCompare(b.publish_date)))
|
|
143
150
|
manifest(p)
|
|
144
151
|
return { slug, scenes: ids.length, locales: p.site.locales.length }
|
package/src/http.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// HTTP for the media pipeline (stage, publish): one injectable fetch, and failures as MotionErrors that name the
|
|
2
|
+
// method, the URL without its query (where tokens travel) and the response status and text. Credentials go in headers
|
|
3
|
+
// or bodies, never into a message.
|
|
4
|
+
import { die } from './util.js'
|
|
5
|
+
|
|
6
|
+
const bare = (url) => String(url).split('?')[0]
|
|
7
|
+
|
|
8
|
+
/** Sends one request; a non-2xx answer or a network error stops the run. Returns the Response. */
|
|
9
|
+
export async function call(fetchFn, method, url, { body, headers = {} } = {}) {
|
|
10
|
+
let r
|
|
11
|
+
try {
|
|
12
|
+
r = await fetchFn(url, { method, body, headers })
|
|
13
|
+
} catch (e) {
|
|
14
|
+
die(`${method} ${bare(url)}: ${e instanceof Error ? e.message : e}`)
|
|
15
|
+
}
|
|
16
|
+
if (!r.ok) die(`${method} ${bare(url)} → ${r.status}: ${(await r.text()).slice(0, 400)}`)
|
|
17
|
+
return r
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** call() and parse the JSON answer ({} for an empty body). */
|
|
21
|
+
export async function callJson(fetchFn, method, url, opts) {
|
|
22
|
+
const text = await (await call(fetchFn, method, url, opts)).text()
|
|
23
|
+
return text ? JSON.parse(text) : {}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Dies naming every missing variable: credentials come from the environment (or CI secrets) only. */
|
|
27
|
+
export function need(env, ...names) {
|
|
28
|
+
const missing = names.filter((n) => !env[n])
|
|
29
|
+
if (missing.length) die(`missing ${missing.join(', ')}: set them in the environment (or CI secrets), never in emaki.config.json`)
|
|
30
|
+
}
|