@senseihq/emaki-posting 0.1.0 → 0.1.2

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,18 @@
1
+ // What every desk handler works with: the options it was created with, plus the lookups they share.
2
+ import type { DeskOptions, Piece } from '../api.js';
3
+ import type { Channel, RequestRow } from '../rules.js';
4
+ import type { MediaStore, PostingStore } from '../store.js';
5
+
6
+ export interface DeskContext {
7
+ o: DeskOptions;
8
+ store: PostingStore;
9
+ media: MediaStore;
10
+ /** The channels a piece is expected to go out on. */
11
+ expected: (p: Piece) => Channel[];
12
+ /** The slugs of the pieces in the built site. */
13
+ slugs: () => Promise<Set<string>>;
14
+ }
15
+
16
+ /** The top-level requests that pass `keep`, each with its replies as `thread`. */
17
+ export const threaded = (requests: RequestRow[], keep: (r: RequestRow) => boolean) =>
18
+ requests.filter((r) => !r.parent && keep(r)).map((r) => ({ ...r, thread: requests.filter((x) => x.parent === r.id) }));
@@ -0,0 +1,8 @@
1
+ // Responses and errors shared by the desk's handlers.
2
+
3
+ export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } }
4
+
5
+ export const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
6
+ export const fail = (status: number, reason: string): never => { throw new HttpError(status, reason); };
7
+ /** The JSON body every API refusal has. */
8
+ export const refusal = (status: number, reason: string) => json({ ok: false, reason }, status);
@@ -0,0 +1,123 @@
1
+ // The handlers behind the machines' API: the producing machine stages posts and uploads media; the CI poster reads
2
+ // the approved queue and reports outcomes. Each takes the desk's context first; the router in ../api.ts picks one.
3
+ import { checkSignature, due, isChannel, sha256, signMedia, validKey, type Channel, type MediaRef, type Production, type StagedPost, type StagedRow } from '../rules.js';
4
+ import type { Caller } from '../access.js';
5
+ import type { Piece } from '../api.js';
6
+ import type { DeskState, MediaObject } from '../store.js';
7
+ import { threaded, type DeskContext } from './context.js';
8
+ import { fail } from './http.js';
9
+
10
+ const TYPES: Record<string, string> = { mp4: 'video/mp4', jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', srt: 'text/plain; charset=utf-8', vtt: 'text/vtt' };
11
+ const MAX = 95 * 1024 * 1024; // under the Workers request-body limit
12
+ const OUTCOMES = ['posted', 'dry-run', 'failed'];
13
+ const REQUEST_STATES = ['open', 'working', 'done'];
14
+
15
+ /** Each piece with what the desk holds for it, as due() reads it. */
16
+ function queueRows(all: DeskState, pieces: Piece[]) {
17
+ const planned = new Map(all.schedule.map((s) => [s.slug, s.publish_date]));
18
+ return pieces.map((a) => ({
19
+ slug: a.slug, date: a.date, planned: planned.get(a.slug),
20
+ staged: all.staged.filter((s) => s.slug === a.slug), approvals: all.approvals.filter((x) => x.slug === a.slug), posts: all.posts.filter((p) => p.slug === a.slug),
21
+ }));
22
+ }
23
+
24
+ /** A media file of a due post, with a short-lived public link when the desk has a media secret. */
25
+ const linked = async (d: DeskContext, x: MediaRef, base: string) =>
26
+ ({ ...x, url: d.o.mediaSecret ? await signMedia(x.key, d.o.mediaSecret, base, 3600, Date.now(), d.o.mediaPath ?? '/m') : null });
27
+
28
+ const queueItem = async (d: DeskContext, s: StagedRow, pieces: Piece[], base: string) => ({
29
+ slug: s.slug, channel: s.channel, content_sha: s.content_sha, post: s.post, article: d.o.pieceUrl(s.slug),
30
+ video: pieces.find((a) => a.slug === s.slug)?.video ?? 'short',
31
+ media: await Promise.all(s.post.media.map((x) => linked(d, x, base))),
32
+ });
33
+
34
+ /** What is approved and due now, with short-lived media links. Empty while posting is paused. */
35
+ export async function queue(d: DeskContext, origin: string) {
36
+ const all = await d.store.readAll(), t = d.o.today();
37
+ const pieces = await d.o.pieces();
38
+ const rows = queueRows(all, pieces);
39
+ const base = d.o.mediaOrigin || origin;
40
+ return { paused: all.paused, today: t, items: await Promise.all(due(rows, t, all.paused).map((s) => queueItem(d, s, pieces, base))) };
41
+ }
42
+
43
+ const validOutcome = (b: Record<string, string>) => Boolean(b.slug && isChannel(b.channel) && b.content_sha && OUTCOMES.includes(b.status));
44
+
45
+ export async function posted(d: DeskContext, caller: Caller, b: Record<string, string>) {
46
+ if (!validOutcome(b)) fail(400, 'slug, channel, content_sha and status are required');
47
+ await d.store.recordPost(caller.id, { slug: b.slug, channel: b.channel as Channel, content_sha: b.content_sha, status: b.status as 'posted', url: b.url, external_id: b.external_id, detail: b.detail?.slice(0, 2000), run: b.run });
48
+ return { ok: true };
49
+ }
50
+
51
+ /** One staged media file must sit under the piece and be uploaded with the same sha256. */
52
+ async function checkStagedMedia(d: DeskContext, slug: string, x: MediaRef) {
53
+ if (!validKey(x.key) || !x.key.startsWith(`${slug}/`)) fail(400, `Bad media key ${x.key}`);
54
+ const head = await d.media.head(x.key);
55
+ if (!head || head.sha256 !== x.sha256) fail(400, `${x.key} is not uploaded with that sha256`);
56
+ }
57
+
58
+ const validStaging = (b: { channel: string; post: StagedPost }) => isChannel(b.channel) && Boolean(b.post) && Array.isArray(b.post.media);
59
+
60
+ /** The post for one piece and channel, as it will go out. Every media file must already be uploaded, same sha256. */
61
+ export async function stage(d: DeskContext, caller: Caller, b: { slug: string; channel: string; post: StagedPost }) {
62
+ if (!(await d.slugs()).has(b.slug)) fail(400, `No piece "${b.slug}" in the index`);
63
+ if (!validStaging(b)) fail(400, 'channel and post.media are required');
64
+ for (const x of b.post.media) await checkStagedMedia(d, b.slug, x);
65
+ return { ok: true, content_sha: await d.store.stage(caller.id, b.slug, b.channel as Channel, b.post) };
66
+ }
67
+
68
+ export async function production(d: DeskContext, b: { items: { slug: string; script?: string; status: Production }[] }) {
69
+ const known = await d.slugs();
70
+ const items = (b.items ?? []).filter((it) => known.has(it.slug));
71
+ for (const it of items) await d.store.saveProduction(it.slug, (it.script ?? '').slice(0, 60000) || null, it.status ?? {});
72
+ return { ok: true, saved: items.length };
73
+ }
74
+
75
+ /** Dates set on the desk that differ from the build: the schedule job writes them into index.json. */
76
+ export async function schedule(d: DeskContext) {
77
+ const built = new Map((await d.o.pieces()).map((a) => [a.slug, a.date]));
78
+ return { changes: (await d.store.readSchedule()).filter((s) => built.has(s.slug) && built.get(s.slug) !== s.publish_date) };
79
+ }
80
+
81
+ export async function openRequests(d: DeskContext) {
82
+ return { requests: threaded(await d.store.readRequests(), (r) => r.status !== 'done') };
83
+ }
84
+
85
+ export async function answerRequest(d: DeskContext, caller: Caller, b: { id: number; reply?: string; status?: string }) {
86
+ const parent = (await d.store.readRequests()).find((r) => r.id === Number(b.id) && !r.parent);
87
+ if (!parent) fail(404, 'No such request');
88
+ if (b.reply) await d.store.addRequest(caller.id, parent!.slug, 'note', b.reply, parent!.id);
89
+ if (b.status && REQUEST_STATES.includes(b.status)) await d.store.setRequestStatus(caller.id, parent!.id, b.status);
90
+ return { ok: true };
91
+ }
92
+
93
+ const contentType = (obj: MediaObject) => obj.contentType ?? 'application/octet-stream';
94
+
95
+ export async function getMedia(d: DeskContext, key: string) {
96
+ if (!validKey(key)) fail(400, 'Bad key');
97
+ const obj = await d.media.get(key);
98
+ if (!obj) fail(404, 'Not found');
99
+ return new Response(obj!.body, { headers: { 'content-type': contentType(obj!), 'content-length': String(obj!.size), 'x-content-sha256': obj!.sha256 ?? '' } });
100
+ }
101
+
102
+ export async function putMedia(d: DeskContext, caller: Caller, key: string, request: Request) {
103
+ if (!validKey(key)) fail(400, 'Bad key: <slug>/<file>, lower-case');
104
+ const want = (request.headers.get('x-content-sha256') ?? '').toLowerCase();
105
+ const body = await request.arrayBuffer();
106
+ if (body.byteLength > MAX) fail(413, 'Too large');
107
+ const got = await sha256(body);
108
+ if (!want || got !== want) fail(400, `sha256 mismatch (got ${got})`);
109
+ await d.media.put(key, body, { contentType: TYPES[key.split('.').pop() ?? ''] ?? 'application/octet-stream', sha256: got });
110
+ await d.store.audit(caller.id, 'upload', key.split('/')[0], null, `${key} ${got.slice(0, 12)}`);
111
+ return { ok: true, key, sha256: got, bytes: body.byteLength };
112
+ }
113
+
114
+ /** A signed link is good only with a media secret, a valid key and an unexpired signature, checked in that order. */
115
+ const validLink = async (d: DeskContext, key: string, url: URL) =>
116
+ Boolean(d.o.mediaSecret) && validKey(key) && checkSignature(key, url.searchParams.get('exp') ?? '', url.searchParams.get('sig') ?? '', d.o.mediaSecret!);
117
+
118
+ /** /m/<key>?exp=…&sig=…: one media file, public only with a valid, unexpired signature. The bucket stays private. */
119
+ export async function signedMedia(d: DeskContext, key: string, url: URL): Promise<Response> {
120
+ const obj = (await validLink(d, key, url)) ? await d.media.get(key) : null;
121
+ if (!obj) return new Response('Not found', { status: 404 });
122
+ return new Response(obj.body, { headers: { 'content-type': contentType(obj), 'content-length': String(obj.size), 'cache-control': 'private, no-store', 'x-robots-tag': 'noindex' } });
123
+ }
@@ -0,0 +1,92 @@
1
+ // What a person does on the desk page: its data (plan) and its actions. Each action returns { ok } or { error } with a
2
+ // status; the page calls them from its own form handlers.
3
+ import { channelState, isChannel, makeNext as moveToNext, effectiveDates, type Channel, type Production, type RequestRow } from '../rules.js';
4
+ import type { Piece } from '../api.js';
5
+ import type { DeskState } from '../store.js';
6
+ import { threaded, type DeskContext } from './context.js';
7
+
8
+ const REQUEST_KINDS = ['generate', 'edit', 'note'];
9
+
10
+ /** One channel of one piece on the desk page. */
11
+ function channelRow(all: DeskState, slug: string, c: Channel) {
12
+ const staged = all.staged.find((s) => s.slug === slug && s.channel === c);
13
+ const posts = all.posts.filter((p) => p.slug === slug && p.channel === c);
14
+ return {
15
+ channel: c, state: channelState(staged, all.approvals.filter((x) => x.slug === slug && x.channel === c), posts),
16
+ staged: staged ?? null, url: posts.filter((p) => p.status === 'posted').at(-1)?.url ?? null, last: posts.at(-1) ?? null,
17
+ };
18
+ }
19
+
20
+ type ProductionRow = { slug: string; script: string | null; status: Production; updated_at: string };
21
+ interface PlanInputs { t: string; all: DeskState; prod: ProductionRow[]; requests: RequestRow[]; dates: Map<string, string> }
22
+
23
+ /** One piece on the desk page: its date (as set and as built), each channel's state, its production and requests. */
24
+ function pieceRow(d: DeskContext, a: Piece, { t, all, prod, requests, dates }: PlanInputs) {
25
+ const date = dates.get(a.slug)!;
26
+ const channels = d.expected(a).map((c) => channelRow(all, a.slug, c));
27
+ const p = prod.find((x) => x.slug === a.slug);
28
+ return {
29
+ ...a, date, built: a.date, moved: date !== a.date, live: a.date <= t, channels,
30
+ script: p?.script ?? null, status: p?.status ?? {}, reported: p?.updated_at ?? null,
31
+ requests: threaded(requests, (r) => r.slug === a.slug),
32
+ };
33
+ }
34
+
35
+ /** The desk page's data: every piece in date order with each channel's state, production and requests. */
36
+ export async function plan(d: DeskContext) {
37
+ const t = d.o.today(), all = await d.store.readAll(), prod = await d.store.readProduction(), requests = await d.store.readRequests();
38
+ const pieces = await d.o.pieces(), dates = effectiveDates(pieces, all.schedule);
39
+ const rows = pieces.map((a) => pieceRow(d, a, { t, all, prod, requests, dates }))
40
+ .sort((x, y) => x.date.localeCompare(y.date) || x.slug.localeCompare(y.slug));
41
+ return { today: t, paused: all.paused, plan: rows, next: rows.find((r) => r.date >= t && r.channels.some((c) => c.state !== 'posted')) ?? null, audit: await d.store.recentAudit() };
42
+ }
43
+
44
+ export async function approve(d: DeskContext, who: string, slug: string, items: string[]) {
45
+ let n = 0;
46
+ for (const item of items) { const [c, sha] = item.split(':'); if (isChannel(c) && (await d.store.approve(who, slug, c, sha))) n++; }
47
+ return n === items.length ? { ok: `Approved ${n}` } : { status: 409, error: `Approved ${n} of ${items.length}: the rest changed since this page loaded. Reload and check again.` };
48
+ }
49
+
50
+ export async function revoke(d: DeskContext, who: string, slug: string, channel: string) {
51
+ if (!isChannel(channel)) return { status: 400, error: 'Bad channel' };
52
+ await d.store.revoke(who, slug, channel);
53
+ return { ok: 'Approval withdrawn' };
54
+ }
55
+
56
+ export async function makeNext(d: DeskContext, who: string, slug: string) {
57
+ const all = await d.store.readAll();
58
+ const moved = moveToNext(effectiveDates(await d.o.pieces(), all.schedule), slug, d.o.today());
59
+ if (!moved.size) return { status: 400, error: 'That piece is already next, or already published.' };
60
+ await d.store.setDates(who, moved, `make next: ${slug}`);
61
+ return { ok: `Moved ${slug} to ${moved.get(slug)}; ${moved.size - 1} other piece(s) moved down one slot.` };
62
+ }
63
+
64
+ export async function request(d: DeskContext, who: string, slug: string, kind: string, body: string) {
65
+ if (!(await d.slugs()).has(slug)) return { status: 400, error: 'No such piece' };
66
+ if (!body.trim() && kind !== 'generate') return { status: 400, error: 'Say what to change' };
67
+ await d.store.addRequest(who, slug, REQUEST_KINDS.includes(kind) ? kind : 'edit', body.trim() || 'Generate the motion for this piece from its script.');
68
+ return { ok: 'Sent. Replies appear in the thread.' };
69
+ }
70
+
71
+ export async function reply(d: DeskContext, who: string, id: number, body: string, status?: string) {
72
+ const parent = (await d.store.readRequests()).find((r) => r.id === id && !r.parent);
73
+ if (!parent) return { status: 404, error: 'No such request' };
74
+ if (body.trim()) await d.store.addRequest(who, parent.slug, 'note', body.trim(), id);
75
+ if (status) await d.store.setRequestStatus(who, id, status);
76
+ return { ok: 'Saved' };
77
+ }
78
+
79
+ export async function pause(d: DeskContext, who: string) { await d.store.setPaused(who, true); return { ok: 'Posting paused' }; }
80
+ export async function resume(d: DeskContext, who: string) { await d.store.setPaused(who, false); return { ok: 'Posting resumed' }; }
81
+
82
+ /** The desk page's data and actions, bound to one desk. Methods (not function properties), as the API has always typed them. */
83
+ export interface DeskActions {
84
+ plan: () => ReturnType<typeof plan>;
85
+ approve(who: string, slug: string, items: string[]): ReturnType<typeof approve>;
86
+ revoke(who: string, slug: string, channel: string): ReturnType<typeof revoke>;
87
+ makeNext(who: string, slug: string): ReturnType<typeof makeNext>;
88
+ request(who: string, slug: string, kind: string, body: string): ReturnType<typeof request>;
89
+ reply(who: string, id: number, body: string, status?: string): ReturnType<typeof reply>;
90
+ pause(who: string): ReturnType<typeof pause>;
91
+ resume(who: string): ReturnType<typeof resume>;
92
+ }
package/src/store.ts CHANGED
@@ -38,61 +38,84 @@ export interface MediaStore {
38
38
 
39
39
  const now = () => new Date().toISOString();
40
40
 
41
+ type ProductionRow = { slug: string; script: string | null; status: Production; updated_at: string };
42
+ type RecordedPost = Parameters<PostingStore['recordPost']>[1];
43
+
44
+ /** Media files in a map. Its methods are own properties, so they work taken off the object. */
45
+ class MemoryMedia implements MediaStore {
46
+ #files = new Map<string, { bytes: ArrayBuffer; contentType: string; sha256: string }>();
47
+ get = async (key: string): Promise<MediaObject | null> => {
48
+ const f = this.#files.get(key);
49
+ return f ? { body: f.bytes, size: f.bytes.byteLength, contentType: f.contentType, sha256: f.sha256 } : null;
50
+ };
51
+ head = async (key: string) => {
52
+ const f = this.#files.get(key);
53
+ return f ? { size: f.bytes.byteLength, sha256: f.sha256 } : null;
54
+ };
55
+ put = async (key: string, bytes: ArrayBuffer, o: { contentType: string; sha256: string }) => { this.#files.set(key, { bytes, ...o }); };
56
+ }
57
+
58
+ /**
59
+ * The desk's rows in memory. Its methods are own properties (no private state shows), so they work taken off the
60
+ * object; each one audits through `this.audit`, the store's own. One id sequence numbers every row.
61
+ */
62
+ class MemoryStore implements PostingStore {
63
+ #s: DeskState = { staged: [], approvals: [], posts: [], paused: true, schedule: [] };
64
+ #log: AuditRow[] = [];
65
+ #production = new Map<string, ProductionRow>();
66
+ #requests: RequestRow[] = [];
67
+ #id = 0;
68
+
69
+ readAll = async () => structuredClone(this.#s);
70
+ recentAudit = async (n = 40) => this.#log.slice(-n).reverse();
71
+ audit = async (actor: string, action: string, slug: string | null = null, channel: string | null = null, detail?: string) => {
72
+ this.#log.push({ id: ++this.#id, at: now(), actor, action, slug, channel, detail: detail ?? null });
73
+ };
74
+ stage = async (actor: string, slug: string, channel: Channel, post: StagedPost) => {
75
+ const sha = await contentSha(channel, post);
76
+ this.#s.staged = this.#s.staged.filter((r) => !(r.slug === slug && r.channel === channel));
77
+ this.#s.staged.push({ slug, channel, post: structuredClone(post), content_sha: sha, staged_by: actor, staged_at: now() });
78
+ await this.audit(actor, 'stage', slug, channel, sha.slice(0, 12));
79
+ return sha;
80
+ };
81
+ approve = async (actor: string, slug: string, channel: Channel, seen: string) => {
82
+ const row = this.#s.staged.find((r) => r.slug === slug && r.channel === channel);
83
+ if (!row || row.content_sha !== seen) return false;
84
+ this.#s.approvals.push({ id: ++this.#id, slug, channel, content_sha: seen, approved_by: actor, approved_at: now(), revoked_at: null });
85
+ await this.audit(actor, 'approve', slug, channel, seen.slice(0, 12));
86
+ return true;
87
+ };
88
+ revoke = async (actor: string, slug: string, channel: Channel) => {
89
+ const live = this.#s.approvals.filter((a) => a.slug === slug && a.channel === channel && !a.revoked_at);
90
+ for (const a of live) a.revoked_at = now();
91
+ await this.audit(actor, 'revoke', slug, channel);
92
+ };
93
+ setPaused = async (actor: string, paused: boolean) => { this.#s.paused = paused; await this.audit(actor, paused ? 'pause' : 'resume'); };
94
+ recordPost = async (actor: string, p: RecordedPost) => {
95
+ this.#s.posts.push({ id: ++this.#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() });
96
+ await this.audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
97
+ };
98
+ readSchedule = async () => structuredClone(this.#s.schedule);
99
+ setDates = async (actor: string, moved: Map<string, string>, why: string) => {
100
+ if (!moved.size) return;
101
+ for (const [slug, d] of moved) { this.#s.schedule = this.#s.schedule.filter((x) => x.slug !== slug); this.#s.schedule.push({ slug, publish_date: d }); }
102
+ await this.audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([x, d]) => `${x}→${d}`).join(', ')}`);
103
+ };
104
+ readProduction = async () => [...this.#production.values()];
105
+ saveProduction = async (slug: string, script: string | null, status: Production) => { this.#production.set(slug, { slug, script, status, updated_at: now() }); };
106
+ readRequests = async (openOnly = false) => this.#requests.filter((r) => !openOnly || (!r.parent && r.status !== 'done'));
107
+ addRequest = async (actor: string, slug: string, kind: string, body: string, parent: number | null = null) => {
108
+ this.#requests.push({ id: ++this.#id, slug, kind, body: body.slice(0, 4000), author: actor, at: now(), status: 'open', parent });
109
+ await this.audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
110
+ };
111
+ setRequestStatus = async (actor: string, rid: number, status: string) => {
112
+ const r = this.#requests.find((x) => x.id === rid); if (r) r.status = status;
113
+ await this.audit(actor, `request:${status}`, null, null, `#${rid}`);
114
+ };
115
+ media: MediaStore = new MemoryMedia();
116
+ }
117
+
41
118
  /** Everything in memory. Starts paused, like the real one. */
42
119
  export function memoryStore(): PostingStore & { media: MediaStore } {
43
- const s: DeskState = { staged: [], approvals: [], posts: [], paused: true, schedule: [] };
44
- const log: AuditRow[] = [], production = new Map<string, { slug: string; script: string | null; status: Production; updated_at: string }>();
45
- const requests: RequestRow[] = [], files = new Map<string, { bytes: ArrayBuffer; contentType: string; sha256: string }>();
46
- let id = 0;
47
- const store: PostingStore & { media: MediaStore } = {
48
- async readAll() { return structuredClone(s); },
49
- async recentAudit(n = 40) { return log.slice(-n).reverse(); },
50
- async audit(actor, action, slug = null, channel = null, detail) { log.push({ id: ++id, at: now(), actor, action, slug, channel, detail: detail ?? null }); },
51
- async stage(actor, slug, channel, post) {
52
- const sha = await contentSha(channel, post);
53
- s.staged = s.staged.filter((r) => !(r.slug === slug && r.channel === channel));
54
- s.staged.push({ slug, channel, post: structuredClone(post), content_sha: sha, staged_by: actor, staged_at: now() });
55
- await store.audit(actor, 'stage', slug, channel, sha.slice(0, 12));
56
- return sha;
57
- },
58
- async approve(actor, slug, channel, seen) {
59
- const row = s.staged.find((r) => r.slug === slug && r.channel === channel);
60
- if (!row || row.content_sha !== seen) return false;
61
- s.approvals.push({ id: ++id, slug, channel, content_sha: seen, approved_by: actor, approved_at: now(), revoked_at: null });
62
- await store.audit(actor, 'approve', slug, channel, seen.slice(0, 12));
63
- return true;
64
- },
65
- async revoke(actor, slug, channel) {
66
- for (const a of s.approvals) if (a.slug === slug && a.channel === channel && !a.revoked_at) a.revoked_at = now();
67
- await store.audit(actor, 'revoke', slug, channel);
68
- },
69
- async setPaused(actor, paused) { s.paused = paused; await store.audit(actor, paused ? 'pause' : 'resume'); },
70
- async recordPost(actor, p) {
71
- 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() });
72
- await store.audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
73
- },
74
- async readSchedule() { return structuredClone(s.schedule); },
75
- async setDates(actor, moved, why) {
76
- if (!moved.size) return;
77
- for (const [slug, d] of moved) { s.schedule = s.schedule.filter((x) => x.slug !== slug); s.schedule.push({ slug, publish_date: d }); }
78
- await store.audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([x, d]) => `${x}→${d}`).join(', ')}`);
79
- },
80
- async readProduction() { return [...production.values()]; },
81
- async saveProduction(slug, script, status) { production.set(slug, { slug, script, status, updated_at: now() }); },
82
- async readRequests(openOnly = false) { return requests.filter((r) => !openOnly || (!r.parent && r.status !== 'done')); },
83
- async addRequest(actor, slug, kind, body, parent = null) {
84
- requests.push({ id: ++id, slug, kind, body: body.slice(0, 4000), author: actor, at: now(), status: 'open', parent });
85
- await store.audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
86
- },
87
- async setRequestStatus(actor, rid, status) {
88
- const r = requests.find((x) => x.id === rid); if (r) r.status = status;
89
- await store.audit(actor, `request:${status}`, null, null, `#${rid}`);
90
- },
91
- media: {
92
- async get(key) { const f = files.get(key); return f ? { body: f.bytes, size: f.bytes.byteLength, contentType: f.contentType, sha256: f.sha256 } : null; },
93
- async head(key) { const f = files.get(key); return f ? { size: f.bytes.byteLength, sha256: f.sha256 } : null; },
94
- async put(key, bytes, o) { files.set(key, { bytes, ...o }); },
95
- },
96
- };
97
- return store;
120
+ return new MemoryStore();
98
121
  }