@senseihq/emaki-posting 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.
@@ -0,0 +1,90 @@
1
+ // The desk on Cloudflare: rows in D1 (migrations/ in this package), media in a private R2 bucket. The binding
2
+ // shapes are declared here, so this needs no Cloudflare types package.
3
+ import { contentSha } from '../rules.js';
4
+ const nowIso = () => new Date().toISOString();
5
+ const parse = (r) => ({ ...r, post: JSON.parse(String(r.post)) });
6
+ export function d1Store(db) {
7
+ const audit = async (actor, action, slug, channel, detail) => {
8
+ await db.prepare('INSERT INTO audit (at, actor, action, slug, channel, detail) VALUES (?, ?, ?, ?, ?, ?)').bind(nowIso(), actor, action, slug ?? null, channel ?? null, detail ?? null).run();
9
+ };
10
+ const readRequests = (openOnly = false) => db.prepare(`SELECT * FROM requests ${openOnly ? "WHERE parent IS NULL AND status != 'done'" : ''} ORDER BY id`).all().then((r) => r.results);
11
+ return {
12
+ audit,
13
+ async readAll() {
14
+ const [staged, approvals, posts, settings, schedule] = await Promise.all([
15
+ db.prepare('SELECT * FROM staged').all(),
16
+ db.prepare('SELECT * FROM approvals ORDER BY id').all(),
17
+ db.prepare('SELECT * FROM posts ORDER BY id').all(),
18
+ db.prepare('SELECT key, value FROM settings').all(),
19
+ db.prepare('SELECT slug, publish_date FROM schedule').all(),
20
+ ]);
21
+ return {
22
+ staged: staged.results.map(parse), approvals: approvals.results, posts: posts.results,
23
+ paused: (settings.results.find((s) => s.key === 'paused')?.value ?? '1') !== '0',
24
+ schedule: schedule.results,
25
+ };
26
+ },
27
+ recentAudit: (n = 40) => db.prepare('SELECT * FROM audit ORDER BY id DESC LIMIT ?').bind(n).all().then((r) => r.results),
28
+ async stage(actor, slug, channel, post) {
29
+ const sha = await contentSha(channel, post);
30
+ await db.prepare('INSERT INTO staged (slug, channel, post, content_sha, staged_by, staged_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (slug, channel) DO UPDATE SET post = excluded.post, content_sha = excluded.content_sha, staged_by = excluded.staged_by, staged_at = excluded.staged_at')
31
+ .bind(slug, channel, JSON.stringify(post), sha, actor, nowIso()).run();
32
+ await audit(actor, 'stage', slug, channel, sha.slice(0, 12));
33
+ return sha;
34
+ },
35
+ async approve(actor, slug, channel, seen) {
36
+ const row = await db.prepare('SELECT content_sha FROM staged WHERE slug = ? AND channel = ?').bind(slug, channel).first();
37
+ if (!row || row.content_sha !== seen)
38
+ return false;
39
+ await db.prepare('INSERT INTO approvals (slug, channel, content_sha, approved_by, approved_at) VALUES (?, ?, ?, ?, ?)').bind(slug, channel, row.content_sha, actor, nowIso()).run();
40
+ await audit(actor, 'approve', slug, channel, row.content_sha.slice(0, 12));
41
+ return true;
42
+ },
43
+ async revoke(actor, slug, channel) {
44
+ await db.prepare('UPDATE approvals SET revoked_at = ? WHERE slug = ? AND channel = ? AND revoked_at IS NULL').bind(nowIso(), slug, channel).run();
45
+ await audit(actor, 'revoke', slug, channel);
46
+ },
47
+ async setPaused(actor, paused) {
48
+ await db.prepare("INSERT INTO settings (key, value) VALUES ('paused', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").bind(paused ? '1' : '0').run();
49
+ await audit(actor, paused ? 'pause' : 'resume');
50
+ },
51
+ async recordPost(actor, p) {
52
+ await db.prepare('INSERT INTO posts (slug, channel, content_sha, status, url, external_id, detail, run, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
53
+ .bind(p.slug, p.channel, p.content_sha, p.status, p.url ?? null, p.external_id ?? null, p.detail ?? null, p.run ?? null, nowIso()).run();
54
+ await audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
55
+ },
56
+ readSchedule: () => db.prepare('SELECT slug, publish_date FROM schedule').all().then((r) => r.results),
57
+ async setDates(actor, moved, why) {
58
+ if (!moved.size)
59
+ return;
60
+ const now = nowIso();
61
+ await db.batch([...moved].map(([slug, d]) => db.prepare('INSERT INTO schedule (slug, publish_date, set_by, set_at) VALUES (?, ?, ?, ?) ON CONFLICT (slug) DO UPDATE SET publish_date = excluded.publish_date, set_by = excluded.set_by, set_at = excluded.set_at').bind(slug, d, actor, now)));
62
+ await audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([s, d]) => `${s}→${d}`).join(', ')}`.slice(0, 1900));
63
+ },
64
+ readProduction: () => db.prepare('SELECT slug, script, status, updated_at FROM production').all()
65
+ .then((r) => r.results.map((x) => ({ ...x, status: JSON.parse(x.status) }))),
66
+ async saveProduction(slug, script, status) {
67
+ await db.prepare('INSERT INTO production (slug, script, status, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (slug) DO UPDATE SET script = excluded.script, status = excluded.status, updated_at = excluded.updated_at')
68
+ .bind(slug, script, JSON.stringify(status), nowIso()).run();
69
+ },
70
+ readRequests,
71
+ async addRequest(actor, slug, kind, body, parent = null) {
72
+ await db.prepare('INSERT INTO requests (slug, kind, body, author, at, parent) VALUES (?, ?, ?, ?, ?, ?)').bind(slug, kind, body.slice(0, 4000), actor, nowIso(), parent).run();
73
+ await audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
74
+ },
75
+ async setRequestStatus(actor, id, status) {
76
+ await db.prepare('UPDATE requests SET status = ? WHERE id = ?').bind(status, id).run();
77
+ await audit(actor, `request:${status}`, null, null, `#${id}`);
78
+ },
79
+ };
80
+ }
81
+ export function r2Media(bucket) {
82
+ return {
83
+ async get(key) {
84
+ const o = await bucket.get(key);
85
+ return o ? { body: o.body, size: o.size, contentType: o.httpMetadata?.contentType, sha256: o.customMetadata?.sha256 } : null;
86
+ },
87
+ async head(key) { const h = await bucket.head(key); return h ? { size: h.size, sha256: h.customMetadata?.sha256 } : null; },
88
+ async put(key, body, o) { await bucket.put(key, body, { httpMetadata: { contentType: o.contentType }, customMetadata: { sha256: o.sha256 } }); },
89
+ };
90
+ }
@@ -0,0 +1,4 @@
1
+ export * from './rules.js';
2
+ export * from './access.js';
3
+ export * from './store.js';
4
+ export { createDesk, HttpError, type DeskOptions, type Piece } from './api.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // @senseihq/emaki-posting: the posting desk. Pieces are staged by the machine that renders them, approved by a person
2
+ // for exactly the content staged, and posted by a CI job when their date comes. Framework-free core; adapters in
3
+ // ./cloudflare (D1 + R2) and ./sveltekit (hook + routes).
4
+ export * from './rules.js';
5
+ export * from './access.js';
6
+ export * from './store.js';
7
+ export { createDesk, HttpError } from './api.js';
@@ -0,0 +1,112 @@
1
+ export declare const CHANNELS: readonly ["youtube", "instagram_reel", "instagram_carousel", "x"];
2
+ export type Channel = (typeof CHANNELS)[number];
3
+ export declare const CHANNEL_NAMES: Record<Channel, string>;
4
+ export declare const isChannel: (c: string) => c is Channel;
5
+ export interface MediaRef {
6
+ key: string;
7
+ sha256: string;
8
+ type: string;
9
+ }
10
+ export interface StagedPost {
11
+ title?: string;
12
+ description?: string;
13
+ tags?: string[];
14
+ caption?: string;
15
+ text?: string;
16
+ thread?: string[];
17
+ short?: boolean;
18
+ media: MediaRef[];
19
+ }
20
+ export interface StagedRow {
21
+ slug: string;
22
+ channel: Channel;
23
+ post: StagedPost;
24
+ content_sha: string;
25
+ staged_by: string;
26
+ staged_at: string;
27
+ }
28
+ export interface ApprovalRow {
29
+ id: number;
30
+ slug: string;
31
+ channel: Channel;
32
+ content_sha: string;
33
+ approved_by: string;
34
+ approved_at: string;
35
+ revoked_at: string | null;
36
+ }
37
+ export interface PostRow {
38
+ id: number;
39
+ slug: string;
40
+ channel: Channel;
41
+ content_sha: string;
42
+ status: 'posted' | 'dry-run' | 'failed';
43
+ url: string | null;
44
+ external_id: string | null;
45
+ detail: string | null;
46
+ run: string | null;
47
+ at: string;
48
+ }
49
+ export declare function sha256(data: string | ArrayBuffer): Promise<string>;
50
+ /** JSON with sorted keys, so the same post always fingerprints the same. */
51
+ export declare function canonical(v: unknown): string;
52
+ /** The fingerprint an approval is given for: the channel and everything that goes out on it, media by sha256. */
53
+ export declare const contentSha: (channel: Channel, post: StagedPost) => Promise<string>;
54
+ export type ChannelState = 'not-staged' | 'awaiting' | 'changed' | 'approved' | 'posted' | 'failed';
55
+ /** Where one article's channel stands. An approval counts only for the exact content now staged. */
56
+ export declare function channelState(staged: StagedRow | undefined, approvals: ApprovalRow[], posts: PostRow[]): ChannelState;
57
+ /** What the poster may post now: approved for the staged content, not yet posted, article date reached, not paused. */
58
+ export declare function due(rows: {
59
+ slug: string;
60
+ date: string;
61
+ planned?: string;
62
+ staged: StagedRow[];
63
+ approvals: ApprovalRow[];
64
+ posts: PostRow[];
65
+ }[], today: string, paused: boolean): StagedRow[];
66
+ /** A short-lived, signed public URL for one media file (Instagram fetches media from a URL). */
67
+ export declare function signMedia(key: string, secret: string, origin: string, ttl?: number, now?: number, path?: string): Promise<string>;
68
+ export declare function checkSignature(key: string, exp: string, sig: string, secret: string, now?: number): Promise<boolean>;
69
+ /** Media keys: <slug>/<file>, lower-case, no path tricks. */
70
+ export declare const validKey: (k: string) => boolean;
71
+ /** Each article's publish date as set in /admin, else as built from index.json. */
72
+ export declare function effectiveDates(articles: {
73
+ slug: string;
74
+ date: string;
75
+ }[], overrides: {
76
+ slug: string;
77
+ publish_date: string;
78
+ }[]): Map<string, string>;
79
+ /**
80
+ * "Make next": `slug` takes the first upcoming publishing slot and every other upcoming article moves down one slot.
81
+ * The slots (dates) stay where they are; only which article sits in each changes. Upcoming = dated after today.
82
+ * Returns the new date of every article that moves.
83
+ */
84
+ export declare function makeNext(dates: Map<string, string>, slug: string, today: string): Map<string, string>;
85
+ export interface Production {
86
+ motion?: boolean;
87
+ film?: boolean;
88
+ takes?: number;
89
+ takesNeeded?: number;
90
+ render?: boolean;
91
+ short?: boolean;
92
+ carousel?: number;
93
+ }
94
+ export interface RequestRow {
95
+ id: number;
96
+ slug: string;
97
+ kind: string;
98
+ body: string;
99
+ author: string;
100
+ at: string;
101
+ status: string;
102
+ parent: number | null;
103
+ }
104
+ export interface AuditRow {
105
+ id: number;
106
+ at: string;
107
+ actor: string;
108
+ action: string;
109
+ slug: string | null;
110
+ channel: string | null;
111
+ detail: string | null;
112
+ }
package/dist/rules.js ADDED
@@ -0,0 +1,97 @@
1
+ // The posting desk's rules: what is staged, what an approval covers, what may go out and when. Plain functions over
2
+ // plain rows, no storage and no framework (tested in spec/rules.spec.ts). Stores live in ./store.ts and ./cloudflare.
3
+ export const CHANNELS = ['youtube', 'instagram_reel', 'instagram_carousel', 'x'];
4
+ export const CHANNEL_NAMES = { youtube: 'YouTube', instagram_reel: 'Instagram Reel', instagram_carousel: 'Instagram carousel', x: 'X' };
5
+ export const isChannel = (c) => CHANNELS.includes(c);
6
+ const enc = new TextEncoder();
7
+ export async function sha256(data) {
8
+ const buf = await crypto.subtle.digest('SHA-256', typeof data === 'string' ? enc.encode(data) : data);
9
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
10
+ }
11
+ /** JSON with sorted keys, so the same post always fingerprints the same. */
12
+ export function canonical(v) {
13
+ if (Array.isArray(v))
14
+ return `[${v.map(canonical).join(',')}]`;
15
+ if (v && typeof v === 'object')
16
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
17
+ return JSON.stringify(v ?? null);
18
+ }
19
+ /** The fingerprint an approval is given for: the channel and everything that goes out on it, media by sha256. */
20
+ export const contentSha = (channel, post) => sha256(canonical({ channel, post }));
21
+ /** Where one article's channel stands. An approval counts only for the exact content now staged. */
22
+ export function channelState(staged, approvals, posts) {
23
+ if (posts.some((p) => p.status === 'posted'))
24
+ return 'posted';
25
+ if (!staged)
26
+ return 'not-staged';
27
+ const live = approvals.filter((a) => !a.revoked_at);
28
+ if (live.some((a) => a.content_sha === staged.content_sha)) {
29
+ const last = posts.filter((p) => p.content_sha === staged.content_sha).at(-1);
30
+ return last?.status === 'failed' ? 'failed' : 'approved';
31
+ }
32
+ return live.length ? 'changed' : 'awaiting';
33
+ }
34
+ /** What the poster may post now: approved for the staged content, not yet posted, article date reached, not paused. */
35
+ export function due(rows, today, paused) {
36
+ if (paused)
37
+ return [];
38
+ const out = [];
39
+ for (const r of rows) {
40
+ // `date` is the article's date as built (it is live on the site); `planned` is the date set in /admin. Both must
41
+ // have come, so nothing is posted for an article the site has not published yet.
42
+ if (r.date > today || (r.planned ?? r.date) > today)
43
+ continue;
44
+ for (const s of r.staged) {
45
+ const state = channelState(s, r.approvals.filter((a) => a.channel === s.channel), r.posts.filter((p) => p.channel === s.channel));
46
+ if (state === 'approved')
47
+ out.push(s);
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ /** A short-lived, signed public URL for one media file (Instagram fetches media from a URL). */
53
+ export async function signMedia(key, secret, origin, ttl = 3600, now = Date.now(), path = '/m') {
54
+ const exp = Math.floor(now / 1000) + ttl;
55
+ const sig = await hmac(secret, `${key}:${exp}`);
56
+ return `${origin}${path}/${key.split('/').map(encodeURIComponent).join('/')}?exp=${exp}&sig=${sig}`;
57
+ }
58
+ export async function checkSignature(key, exp, sig, secret, now = Date.now()) {
59
+ if (!secret || !/^\d+$/.test(exp) || Number(exp) * 1000 < now)
60
+ return false;
61
+ const want = await hmac(secret, `${key}:${exp}`);
62
+ if (want.length !== sig.length)
63
+ return false;
64
+ let d = 0;
65
+ for (let i = 0; i < want.length; i++)
66
+ d |= want.charCodeAt(i) ^ sig.charCodeAt(i);
67
+ return d === 0;
68
+ }
69
+ async function hmac(secret, msg) {
70
+ const k = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
71
+ const s = await crypto.subtle.sign('HMAC', k, enc.encode(msg));
72
+ return [...new Uint8Array(s)].map((b) => b.toString(16).padStart(2, '0')).join('');
73
+ }
74
+ /** Media keys: <slug>/<file>, lower-case, no path tricks. */
75
+ export const validKey = (k) => /^[a-z0-9-]+\/[a-z0-9._-]+$/.test(k) && !k.includes('..');
76
+ // ── Planning ────────────────────────────────────────────────────────────────────────────────────────────
77
+ /** Each article's publish date as set in /admin, else as built from index.json. */
78
+ export function effectiveDates(articles, overrides) {
79
+ const o = new Map(overrides.map((r) => [r.slug, r.publish_date]));
80
+ return new Map(articles.map((a) => [a.slug, o.get(a.slug) ?? a.date]));
81
+ }
82
+ /**
83
+ * "Make next": `slug` takes the first upcoming publishing slot and every other upcoming article moves down one slot.
84
+ * The slots (dates) stay where they are; only which article sits in each changes. Upcoming = dated after today.
85
+ * Returns the new date of every article that moves.
86
+ */
87
+ export function makeNext(dates, slug, today) {
88
+ const upcoming = [...dates].filter(([, d]) => d > today).sort((a, b) => a[1].localeCompare(b[1]) || a[0].localeCompare(b[0]));
89
+ if (!upcoming.some(([s]) => s === slug))
90
+ return new Map();
91
+ const slots = upcoming.map(([, d]) => d);
92
+ const order = [slug, ...upcoming.map(([s]) => s).filter((s) => s !== slug)];
93
+ const moved = new Map();
94
+ order.forEach((s, i) => { if (dates.get(s) !== slots[i])
95
+ moved.set(s, slots[i]); });
96
+ return moved;
97
+ }
@@ -0,0 +1,69 @@
1
+ import { type ApprovalRow, type AuditRow, type Channel, type PostRow, type Production, type RequestRow, type StagedPost, type StagedRow } from './rules.js';
2
+ export interface DeskState {
3
+ staged: StagedRow[];
4
+ approvals: ApprovalRow[];
5
+ posts: PostRow[];
6
+ paused: boolean;
7
+ schedule: {
8
+ slug: string;
9
+ publish_date: string;
10
+ }[];
11
+ }
12
+ export interface PostingStore {
13
+ readAll(): Promise<DeskState>;
14
+ recentAudit(n?: number): Promise<AuditRow[]>;
15
+ audit(actor: string, action: string, slug?: string | null, channel?: string | null, detail?: string): Promise<void>;
16
+ /** Stores the post as it will go out; returns its fingerprint (restaging changes it, so old approvals lapse). */
17
+ stage(actor: string, slug: string, channel: Channel, post: StagedPost): Promise<string>;
18
+ /** Approves only the content the approver saw: false if it was restaged since. */
19
+ approve(actor: string, slug: string, channel: Channel, contentShaSeen: string): Promise<boolean>;
20
+ revoke(actor: string, slug: string, channel: Channel): Promise<void>;
21
+ setPaused(actor: string, paused: boolean): Promise<void>;
22
+ recordPost(actor: string, p: {
23
+ slug: string;
24
+ channel: Channel;
25
+ content_sha: string;
26
+ status: PostRow['status'];
27
+ url?: string;
28
+ external_id?: string;
29
+ detail?: string;
30
+ run?: string;
31
+ }): Promise<void>;
32
+ readSchedule(): Promise<{
33
+ slug: string;
34
+ publish_date: string;
35
+ }[]>;
36
+ setDates(actor: string, moved: Map<string, string>, why: string): Promise<void>;
37
+ readProduction(): Promise<{
38
+ slug: string;
39
+ script: string | null;
40
+ status: Production;
41
+ updated_at: string;
42
+ }[]>;
43
+ saveProduction(slug: string, script: string | null, status: Production): Promise<void>;
44
+ readRequests(openOnly?: boolean): Promise<RequestRow[]>;
45
+ addRequest(actor: string, slug: string, kind: string, body: string, parent?: number | null): Promise<void>;
46
+ setRequestStatus(actor: string, id: number, status: string): Promise<void>;
47
+ }
48
+ /** Media files (rendered video, cover images, captions), kept private and addressed as <slug>/<file>. */
49
+ export interface MediaObject {
50
+ body: ReadableStream | ArrayBuffer;
51
+ size: number;
52
+ contentType?: string;
53
+ sha256?: string;
54
+ }
55
+ export interface MediaStore {
56
+ get(key: string): Promise<MediaObject | null>;
57
+ head(key: string): Promise<{
58
+ size: number;
59
+ sha256?: string;
60
+ } | null>;
61
+ put(key: string, body: ArrayBuffer, o: {
62
+ contentType: string;
63
+ sha256: string;
64
+ }): Promise<void>;
65
+ }
66
+ /** Everything in memory. Starts paused, like the real one. */
67
+ export declare function memoryStore(): PostingStore & {
68
+ media: MediaStore;
69
+ };
package/dist/store.js ADDED
@@ -0,0 +1,72 @@
1
+ // Where the desk keeps its rows. The rules (./rules.ts) never touch storage; the API (./api.ts) talks to a
2
+ // PostingStore and a MediaStore. ./cloudflare has D1 + R2; memoryStore() is for tests, demos and local dev; any other
3
+ // database (Postgres, SQLite, KV) only needs these methods.
4
+ import { contentSha } from './rules.js';
5
+ const now = () => new Date().toISOString();
6
+ /** Everything in memory. Starts paused, like the real one. */
7
+ export function memoryStore() {
8
+ const s = { staged: [], approvals: [], posts: [], paused: true, schedule: [] };
9
+ const log = [], production = new Map();
10
+ const requests = [], files = new Map();
11
+ let id = 0;
12
+ const store = {
13
+ async readAll() { return structuredClone(s); },
14
+ async recentAudit(n = 40) { return log.slice(-n).reverse(); },
15
+ async audit(actor, action, slug = null, channel = null, detail) { log.push({ id: ++id, at: now(), actor, action, slug, channel, detail: detail ?? null }); },
16
+ async stage(actor, slug, channel, post) {
17
+ const sha = await contentSha(channel, post);
18
+ s.staged = s.staged.filter((r) => !(r.slug === slug && r.channel === channel));
19
+ s.staged.push({ slug, channel, post: structuredClone(post), content_sha: sha, staged_by: actor, staged_at: now() });
20
+ await store.audit(actor, 'stage', slug, channel, sha.slice(0, 12));
21
+ return sha;
22
+ },
23
+ async approve(actor, slug, channel, seen) {
24
+ const row = s.staged.find((r) => r.slug === slug && r.channel === channel);
25
+ if (!row || row.content_sha !== seen)
26
+ return false;
27
+ s.approvals.push({ id: ++id, slug, channel, content_sha: seen, approved_by: actor, approved_at: now(), revoked_at: null });
28
+ await store.audit(actor, 'approve', slug, channel, seen.slice(0, 12));
29
+ return true;
30
+ },
31
+ async revoke(actor, slug, channel) {
32
+ for (const a of s.approvals)
33
+ if (a.slug === slug && a.channel === channel && !a.revoked_at)
34
+ a.revoked_at = now();
35
+ await store.audit(actor, 'revoke', slug, channel);
36
+ },
37
+ async setPaused(actor, paused) { s.paused = paused; await store.audit(actor, paused ? 'pause' : 'resume'); },
38
+ async recordPost(actor, p) {
39
+ s.posts.push({ id: ++id, slug: p.slug, channel: p.channel, content_sha: p.content_sha, status: p.status, url: p.url ?? null, external_id: p.external_id ?? null, detail: p.detail ?? null, run: p.run ?? null, at: now() });
40
+ await store.audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
41
+ },
42
+ async readSchedule() { return structuredClone(s.schedule); },
43
+ async setDates(actor, moved, why) {
44
+ if (!moved.size)
45
+ return;
46
+ for (const [slug, d] of moved) {
47
+ s.schedule = s.schedule.filter((x) => x.slug !== slug);
48
+ s.schedule.push({ slug, publish_date: d });
49
+ }
50
+ await store.audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([x, d]) => `${x}→${d}`).join(', ')}`);
51
+ },
52
+ async readProduction() { return [...production.values()]; },
53
+ async saveProduction(slug, script, status) { production.set(slug, { slug, script, status, updated_at: now() }); },
54
+ async readRequests(openOnly = false) { return requests.filter((r) => !openOnly || (!r.parent && r.status !== 'done')); },
55
+ async addRequest(actor, slug, kind, body, parent = null) {
56
+ requests.push({ id: ++id, slug, kind, body: body.slice(0, 4000), author: actor, at: now(), status: 'open', parent });
57
+ await store.audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
58
+ },
59
+ async setRequestStatus(actor, rid, status) {
60
+ const r = requests.find((x) => x.id === rid);
61
+ if (r)
62
+ r.status = status;
63
+ await store.audit(actor, `request:${status}`, null, null, `#${rid}`);
64
+ },
65
+ media: {
66
+ async get(key) { const f = files.get(key); return f ? { body: f.bytes, size: f.bytes.byteLength, contentType: f.contentType, sha256: f.sha256 } : null; },
67
+ async head(key) { const f = files.get(key); return f ? { size: f.bytes.byteLength, sha256: f.sha256 } : null; },
68
+ async put(key, bytes, o) { files.set(key, { bytes, ...o }); },
69
+ },
70
+ };
71
+ return store;
72
+ }
@@ -0,0 +1,33 @@
1
+ import type { createDesk } from '../api.js';
2
+ type Desk = ReturnType<typeof createDesk>;
3
+ interface Event {
4
+ request: Request;
5
+ url: URL;
6
+ params: Record<string, string | undefined>;
7
+ locals: Record<string, unknown>;
8
+ platform?: unknown;
9
+ }
10
+ type Resolve = (event: never) => Response | Promise<Response>;
11
+ export interface HandleOptions {
12
+ /** Private env (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUD, ADMIN_EMAILS, STAGER_CLIENT_IDS, POSTER_CLIENT_IDS). */
13
+ env: () => Record<string, string | undefined>;
14
+ /** Let a local admin in when Access is not configured (pass SvelteKit's `dev`). */
15
+ dev?: boolean;
16
+ }
17
+ /** Guards the admin pages and API: a valid Access token whose role may use the path, else 403. Sets locals.caller. */
18
+ export declare function postingHandle(o: HandleOptions): ({ event, resolve }: {
19
+ event: Event;
20
+ resolve: Resolve;
21
+ }) => Promise<Response>;
22
+ /** GET/POST/PUT for src/routes/<api>/[...path]/+server.ts. `desk` builds the desk for this request (bindings live on
23
+ * event.platform). */
24
+ export declare function apiRoutes(desk: (event: Event) => Desk | Promise<Desk>): {
25
+ GET: (event: Event) => Promise<Response>;
26
+ POST: (event: Event) => Promise<Response>;
27
+ PUT: (event: Event) => Promise<Response>;
28
+ };
29
+ /** GET for src/routes/m/[...key]/+server.ts: the signed, short-lived public media links. */
30
+ export declare function mediaRoute(desk: (event: Event) => Desk | Promise<Desk>): {
31
+ GET: (event: Event) => Promise<Response>;
32
+ };
33
+ export {};
@@ -0,0 +1,46 @@
1
+ // SvelteKit glue: a hook that guards the admin paths with Cloudflare Access and the role rules, and route handlers
2
+ // for the API and the signed media links. Typed structurally, so this does not import @sveltejs/kit.
3
+ //
4
+ // // src/hooks.server.ts
5
+ // import { postingHandle } from '@senseihq/emaki-posting/sveltekit';
6
+ // import { env } from '$env/dynamic/private'; import { dev } from '$app/environment';
7
+ // export const handle = postingHandle({ env: () => env, dev });
8
+ //
9
+ // // src/routes/api/admin/[...path]/+server.ts // src/routes/m/[...key]/+server.ts
10
+ // export const { GET, POST, PUT } = apiRoutes(desk); export const { GET } = mediaRoute(desk);
11
+ // (desk = (event) => createDesk({ store: d1Store(event.platform.env.DB), media: r2Media(event.platform.env.MEDIA), ... }))
12
+ import { accessFromEnv, allowed, callerOf, isAdminPath, paths } from '../access.js';
13
+ /** Guards the admin pages and API: a valid Access token whose role may use the path, else 403. Sets locals.caller. */
14
+ export function postingHandle(o) {
15
+ return async ({ event, resolve }) => {
16
+ const path = event.url.pathname;
17
+ if (!isAdminPath(path))
18
+ return resolve(event);
19
+ const caller = await callerOf(event.request, accessFromEnv(o.env()), { dev: o.dev });
20
+ if (!caller || !allowed(caller.role, path, event.request.method)) {
21
+ return path.startsWith(paths.api + '/')
22
+ ? new Response(JSON.stringify({ ok: false, reason: 'Not allowed' }), { status: 403, headers: { 'content-type': 'application/json' } })
23
+ : new Response('Not allowed', { status: 403 });
24
+ }
25
+ event.locals.caller = caller;
26
+ const res = await resolve(event);
27
+ res.headers.set('cache-control', 'no-store');
28
+ res.headers.set('x-robots-tag', 'noindex');
29
+ return res;
30
+ };
31
+ }
32
+ /** GET/POST/PUT for src/routes/<api>/[...path]/+server.ts. `desk` builds the desk for this request (bindings live on
33
+ * event.platform). */
34
+ export function apiRoutes(desk) {
35
+ const h = async (event) => {
36
+ const caller = event.locals.caller;
37
+ if (!caller)
38
+ return new Response('Not allowed', { status: 403 });
39
+ return (await desk(event)).api(event.request, caller, event.params.path ?? '');
40
+ };
41
+ return { GET: h, POST: h, PUT: h };
42
+ }
43
+ /** GET for src/routes/m/[...key]/+server.ts: the signed, short-lived public media links. */
44
+ export function mediaRoute(desk) {
45
+ return { GET: async (event) => (await desk(event)).signedMedia(event.params.key ?? '', event.url) };
46
+ }
@@ -0,0 +1,53 @@
1
+ -- Posting: what is staged, what the approver approved, what was posted, and who did what.
2
+
3
+ -- One row per article and channel: the post as it will go out. Written by the stager (the stager).
4
+ -- `content_sha` fingerprints everything that will be posted (the media's sha256 and the text); an approval holds
5
+ -- the fingerprint it was given for, so restaging different content voids it.
6
+ CREATE TABLE IF NOT EXISTS staged (
7
+ slug TEXT NOT NULL,
8
+ channel TEXT NOT NULL, -- youtube | instagram_reel | instagram_carousel | x
9
+ post TEXT NOT NULL, -- JSON: title/description/tags, caption, text/thread, media [{key, sha256, type}]
10
+ content_sha TEXT NOT NULL,
11
+ staged_by TEXT NOT NULL,
12
+ staged_at TEXT NOT NULL,
13
+ PRIMARY KEY (slug, channel)
14
+ );
15
+
16
+ CREATE TABLE IF NOT EXISTS approvals (
17
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
18
+ slug TEXT NOT NULL,
19
+ channel TEXT NOT NULL,
20
+ content_sha TEXT NOT NULL,
21
+ approved_by TEXT NOT NULL,
22
+ approved_at TEXT NOT NULL,
23
+ revoked_at TEXT
24
+ );
25
+ CREATE INDEX IF NOT EXISTS approvals_slug ON approvals (slug, channel);
26
+
27
+ CREATE TABLE IF NOT EXISTS posts (
28
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
29
+ slug TEXT NOT NULL,
30
+ channel TEXT NOT NULL,
31
+ content_sha TEXT NOT NULL,
32
+ status TEXT NOT NULL, -- posted | dry-run | failed
33
+ url TEXT,
34
+ external_id TEXT,
35
+ detail TEXT,
36
+ run TEXT, -- the GitHub Actions run URL
37
+ at TEXT NOT NULL
38
+ );
39
+ CREATE INDEX IF NOT EXISTS posts_slug ON posts (slug, channel);
40
+
41
+ CREATE TABLE IF NOT EXISTS audit (
42
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
43
+ at TEXT NOT NULL,
44
+ actor TEXT NOT NULL,
45
+ action TEXT NOT NULL, -- approve | revoke | pause | resume | stage | upload | posted | failed | dry-run
46
+ slug TEXT,
47
+ channel TEXT,
48
+ detail TEXT
49
+ );
50
+
51
+ CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
52
+ -- Posting starts paused: nothing goes out until an admin resumes it in /admin.
53
+ INSERT OR IGNORE INTO settings (key, value) VALUES ('paused', '1');
@@ -0,0 +1,31 @@
1
+ -- Planning: the posting order, what is produced, and motion requests.
2
+
3
+ -- The order set in /admin ("Make next"): an article's publish date, overriding index.json until the morning
4
+ -- schedule job (poster/sync_schedule.py) writes it into index.json and the site rebuilds.
5
+ CREATE TABLE IF NOT EXISTS schedule (
6
+ slug TEXT PRIMARY KEY,
7
+ publish_date TEXT NOT NULL,
8
+ set_by TEXT NOT NULL,
9
+ set_at TEXT NOT NULL
10
+ );
11
+
12
+ -- What exists for each piece, reported by the Mac (`emaki stage status`): the day script and its parts.
13
+ CREATE TABLE IF NOT EXISTS production (
14
+ slug TEXT PRIMARY KEY,
15
+ script TEXT, -- the day script (markdown), or the film's voiceover script
16
+ status TEXT NOT NULL, -- JSON: {motion, takes, render, short, carousel, film}
17
+ updated_at TEXT NOT NULL
18
+ );
19
+
20
+ -- Requests to the motion builder from /admin: generate or edit a piece's motion, with a reply thread.
21
+ CREATE TABLE IF NOT EXISTS requests (
22
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
23
+ slug TEXT NOT NULL,
24
+ kind TEXT NOT NULL, -- generate | edit | note
25
+ body TEXT NOT NULL,
26
+ author TEXT NOT NULL,
27
+ at TEXT NOT NULL,
28
+ status TEXT NOT NULL DEFAULT 'open', -- open | working | done
29
+ parent INTEGER -- a reply belongs to a request
30
+ );
31
+ CREATE INDEX IF NOT EXISTS requests_slug ON requests (slug, id);