@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,80 @@
1
+ import { type Production, type StagedPost } from '../rules.js';
2
+ import type { Caller } from '../access.js';
3
+ import { type DeskContext } from './context.js';
4
+ /** What is approved and due now, with short-lived media links. Empty while posting is paused. */
5
+ export declare function queue(d: DeskContext, origin: string): Promise<{
6
+ paused: boolean;
7
+ today: string;
8
+ items: {
9
+ slug: string;
10
+ channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
11
+ content_sha: string;
12
+ post: StagedPost;
13
+ article: string;
14
+ video: string;
15
+ media: {
16
+ url: string | null;
17
+ key: string;
18
+ sha256: string;
19
+ type: string;
20
+ }[];
21
+ }[];
22
+ }>;
23
+ export declare function posted(d: DeskContext, caller: Caller, b: Record<string, string>): Promise<{
24
+ ok: boolean;
25
+ }>;
26
+ /** The post for one piece and channel, as it will go out. Every media file must already be uploaded, same sha256. */
27
+ export declare function stage(d: DeskContext, caller: Caller, b: {
28
+ slug: string;
29
+ channel: string;
30
+ post: StagedPost;
31
+ }): Promise<{
32
+ ok: boolean;
33
+ content_sha: string;
34
+ }>;
35
+ export declare function production(d: DeskContext, b: {
36
+ items: {
37
+ slug: string;
38
+ script?: string;
39
+ status: Production;
40
+ }[];
41
+ }): Promise<{
42
+ ok: boolean;
43
+ saved: number;
44
+ }>;
45
+ /** Dates set on the desk that differ from the build: the schedule job writes them into index.json. */
46
+ export declare function schedule(d: DeskContext): Promise<{
47
+ changes: {
48
+ slug: string;
49
+ publish_date: string;
50
+ }[];
51
+ }>;
52
+ export declare function openRequests(d: DeskContext): Promise<{
53
+ requests: {
54
+ thread: import("../rules.js").RequestRow[];
55
+ id: number;
56
+ slug: string;
57
+ kind: string;
58
+ body: string;
59
+ author: string;
60
+ at: string;
61
+ status: string;
62
+ parent: number | null;
63
+ }[];
64
+ }>;
65
+ export declare function answerRequest(d: DeskContext, caller: Caller, b: {
66
+ id: number;
67
+ reply?: string;
68
+ status?: string;
69
+ }): Promise<{
70
+ ok: boolean;
71
+ }>;
72
+ export declare function getMedia(d: DeskContext, key: string): Promise<Response>;
73
+ export declare function putMedia(d: DeskContext, caller: Caller, key: string, request: Request): Promise<{
74
+ ok: boolean;
75
+ key: string;
76
+ sha256: string;
77
+ bytes: number;
78
+ }>;
79
+ /** /m/<key>?exp=…&sig=…: one media file, public only with a valid, unexpired signature. The bucket stays private. */
80
+ export declare function signedMedia(d: DeskContext, key: string, url: URL): Promise<Response>;
@@ -0,0 +1,115 @@
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 } from '../rules.js';
4
+ import { threaded } from './context.js';
5
+ import { fail } from './http.js';
6
+ const TYPES = { mp4: 'video/mp4', jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', srt: 'text/plain; charset=utf-8', vtt: 'text/vtt' };
7
+ const MAX = 95 * 1024 * 1024; // under the Workers request-body limit
8
+ const OUTCOMES = ['posted', 'dry-run', 'failed'];
9
+ const REQUEST_STATES = ['open', 'working', 'done'];
10
+ /** Each piece with what the desk holds for it, as due() reads it. */
11
+ function queueRows(all, pieces) {
12
+ const planned = new Map(all.schedule.map((s) => [s.slug, s.publish_date]));
13
+ return pieces.map((a) => ({
14
+ slug: a.slug, date: a.date, planned: planned.get(a.slug),
15
+ 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),
16
+ }));
17
+ }
18
+ /** A media file of a due post, with a short-lived public link when the desk has a media secret. */
19
+ const linked = async (d, x, base) => ({ ...x, url: d.o.mediaSecret ? await signMedia(x.key, d.o.mediaSecret, base, 3600, Date.now(), d.o.mediaPath ?? '/m') : null });
20
+ const queueItem = async (d, s, pieces, base) => ({
21
+ slug: s.slug, channel: s.channel, content_sha: s.content_sha, post: s.post, article: d.o.pieceUrl(s.slug),
22
+ video: pieces.find((a) => a.slug === s.slug)?.video ?? 'short',
23
+ media: await Promise.all(s.post.media.map((x) => linked(d, x, base))),
24
+ });
25
+ /** What is approved and due now, with short-lived media links. Empty while posting is paused. */
26
+ export async function queue(d, origin) {
27
+ const all = await d.store.readAll(), t = d.o.today();
28
+ const pieces = await d.o.pieces();
29
+ const rows = queueRows(all, pieces);
30
+ const base = d.o.mediaOrigin || origin;
31
+ return { paused: all.paused, today: t, items: await Promise.all(due(rows, t, all.paused).map((s) => queueItem(d, s, pieces, base))) };
32
+ }
33
+ const validOutcome = (b) => Boolean(b.slug && isChannel(b.channel) && b.content_sha && OUTCOMES.includes(b.status));
34
+ export async function posted(d, caller, b) {
35
+ if (!validOutcome(b))
36
+ fail(400, 'slug, channel, content_sha and status are required');
37
+ await d.store.recordPost(caller.id, { slug: b.slug, channel: b.channel, content_sha: b.content_sha, status: b.status, url: b.url, external_id: b.external_id, detail: b.detail?.slice(0, 2000), run: b.run });
38
+ return { ok: true };
39
+ }
40
+ /** One staged media file must sit under the piece and be uploaded with the same sha256. */
41
+ async function checkStagedMedia(d, slug, x) {
42
+ if (!validKey(x.key) || !x.key.startsWith(`${slug}/`))
43
+ fail(400, `Bad media key ${x.key}`);
44
+ const head = await d.media.head(x.key);
45
+ if (!head || head.sha256 !== x.sha256)
46
+ fail(400, `${x.key} is not uploaded with that sha256`);
47
+ }
48
+ const validStaging = (b) => isChannel(b.channel) && Boolean(b.post) && Array.isArray(b.post.media);
49
+ /** The post for one piece and channel, as it will go out. Every media file must already be uploaded, same sha256. */
50
+ export async function stage(d, caller, b) {
51
+ if (!(await d.slugs()).has(b.slug))
52
+ fail(400, `No piece "${b.slug}" in the index`);
53
+ if (!validStaging(b))
54
+ fail(400, 'channel and post.media are required');
55
+ for (const x of b.post.media)
56
+ await checkStagedMedia(d, b.slug, x);
57
+ return { ok: true, content_sha: await d.store.stage(caller.id, b.slug, b.channel, b.post) };
58
+ }
59
+ export async function production(d, b) {
60
+ const known = await d.slugs();
61
+ const items = (b.items ?? []).filter((it) => known.has(it.slug));
62
+ for (const it of items)
63
+ await d.store.saveProduction(it.slug, (it.script ?? '').slice(0, 60000) || null, it.status ?? {});
64
+ return { ok: true, saved: items.length };
65
+ }
66
+ /** Dates set on the desk that differ from the build: the schedule job writes them into index.json. */
67
+ export async function schedule(d) {
68
+ const built = new Map((await d.o.pieces()).map((a) => [a.slug, a.date]));
69
+ return { changes: (await d.store.readSchedule()).filter((s) => built.has(s.slug) && built.get(s.slug) !== s.publish_date) };
70
+ }
71
+ export async function openRequests(d) {
72
+ return { requests: threaded(await d.store.readRequests(), (r) => r.status !== 'done') };
73
+ }
74
+ export async function answerRequest(d, caller, b) {
75
+ const parent = (await d.store.readRequests()).find((r) => r.id === Number(b.id) && !r.parent);
76
+ if (!parent)
77
+ fail(404, 'No such request');
78
+ if (b.reply)
79
+ await d.store.addRequest(caller.id, parent.slug, 'note', b.reply, parent.id);
80
+ if (b.status && REQUEST_STATES.includes(b.status))
81
+ await d.store.setRequestStatus(caller.id, parent.id, b.status);
82
+ return { ok: true };
83
+ }
84
+ const contentType = (obj) => obj.contentType ?? 'application/octet-stream';
85
+ export async function getMedia(d, key) {
86
+ if (!validKey(key))
87
+ fail(400, 'Bad key');
88
+ const obj = await d.media.get(key);
89
+ if (!obj)
90
+ fail(404, 'Not found');
91
+ return new Response(obj.body, { headers: { 'content-type': contentType(obj), 'content-length': String(obj.size), 'x-content-sha256': obj.sha256 ?? '' } });
92
+ }
93
+ export async function putMedia(d, caller, key, request) {
94
+ if (!validKey(key))
95
+ fail(400, 'Bad key: <slug>/<file>, lower-case');
96
+ const want = (request.headers.get('x-content-sha256') ?? '').toLowerCase();
97
+ const body = await request.arrayBuffer();
98
+ if (body.byteLength > MAX)
99
+ fail(413, 'Too large');
100
+ const got = await sha256(body);
101
+ if (!want || got !== want)
102
+ fail(400, `sha256 mismatch (got ${got})`);
103
+ await d.media.put(key, body, { contentType: TYPES[key.split('.').pop() ?? ''] ?? 'application/octet-stream', sha256: got });
104
+ await d.store.audit(caller.id, 'upload', key.split('/')[0], null, `${key} ${got.slice(0, 12)}`);
105
+ return { ok: true, key, sha256: got, bytes: body.byteLength };
106
+ }
107
+ /** A signed link is good only with a media secret, a valid key and an unexpired signature, checked in that order. */
108
+ const validLink = async (d, key, url) => Boolean(d.o.mediaSecret) && validKey(key) && checkSignature(key, url.searchParams.get('exp') ?? '', url.searchParams.get('sig') ?? '', d.o.mediaSecret);
109
+ /** /m/<key>?exp=…&sig=…: one media file, public only with a valid, unexpired signature. The bucket stays private. */
110
+ export async function signedMedia(d, key, url) {
111
+ const obj = (await validLink(d, key, url)) ? await d.media.get(key) : null;
112
+ if (!obj)
113
+ return new Response('Not found', { status: 404 });
114
+ return new Response(obj.body, { headers: { 'content-type': contentType(obj), 'content-length': String(obj.size), 'cache-control': 'private, no-store', 'x-robots-tag': 'noindex' } });
115
+ }
@@ -0,0 +1,130 @@
1
+ import { type Production, type RequestRow } from '../rules.js';
2
+ import { type DeskContext } from './context.js';
3
+ /** The desk page's data: every piece in date order with each channel's state, production and requests. */
4
+ export declare function plan(d: DeskContext): Promise<{
5
+ today: string;
6
+ paused: boolean;
7
+ plan: {
8
+ date: string;
9
+ built: string;
10
+ moved: boolean;
11
+ live: boolean;
12
+ channels: {
13
+ channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
14
+ state: import("../rules.js").ChannelState;
15
+ staged: import("../rules.js").StagedRow | null;
16
+ url: string | null;
17
+ last: import("../rules.js").PostRow | null;
18
+ }[];
19
+ script: string | null;
20
+ status: Production;
21
+ reported: string | null;
22
+ requests: {
23
+ thread: RequestRow[];
24
+ id: number;
25
+ slug: string;
26
+ kind: string;
27
+ body: string;
28
+ author: string;
29
+ at: string;
30
+ status: string;
31
+ parent: number | null;
32
+ }[];
33
+ slug: string;
34
+ title?: string;
35
+ video?: "short" | "wide" | string;
36
+ }[];
37
+ next: {
38
+ date: string;
39
+ built: string;
40
+ moved: boolean;
41
+ live: boolean;
42
+ channels: {
43
+ channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
44
+ state: import("../rules.js").ChannelState;
45
+ staged: import("../rules.js").StagedRow | null;
46
+ url: string | null;
47
+ last: import("../rules.js").PostRow | null;
48
+ }[];
49
+ script: string | null;
50
+ status: Production;
51
+ reported: string | null;
52
+ requests: {
53
+ thread: RequestRow[];
54
+ id: number;
55
+ slug: string;
56
+ kind: string;
57
+ body: string;
58
+ author: string;
59
+ at: string;
60
+ status: string;
61
+ parent: number | null;
62
+ }[];
63
+ slug: string;
64
+ title?: string;
65
+ video?: "short" | "wide" | string;
66
+ } | null;
67
+ audit: import("../rules.js").AuditRow[];
68
+ }>;
69
+ export declare function approve(d: DeskContext, who: string, slug: string, items: string[]): Promise<{
70
+ ok: string;
71
+ status?: undefined;
72
+ error?: undefined;
73
+ } | {
74
+ status: number;
75
+ error: string;
76
+ ok?: undefined;
77
+ }>;
78
+ export declare function revoke(d: DeskContext, who: string, slug: string, channel: string): Promise<{
79
+ status: number;
80
+ error: string;
81
+ ok?: undefined;
82
+ } | {
83
+ ok: string;
84
+ status?: undefined;
85
+ error?: undefined;
86
+ }>;
87
+ export declare function makeNext(d: DeskContext, who: string, slug: string): Promise<{
88
+ status: number;
89
+ error: string;
90
+ ok?: undefined;
91
+ } | {
92
+ ok: string;
93
+ status?: undefined;
94
+ error?: undefined;
95
+ }>;
96
+ export declare function request(d: DeskContext, who: string, slug: string, kind: string, body: string): Promise<{
97
+ status: number;
98
+ error: string;
99
+ ok?: undefined;
100
+ } | {
101
+ ok: string;
102
+ status?: undefined;
103
+ error?: undefined;
104
+ }>;
105
+ export declare function reply(d: DeskContext, who: string, id: number, body: string, status?: string): Promise<{
106
+ status: number;
107
+ error: string;
108
+ ok?: undefined;
109
+ } | {
110
+ ok: string;
111
+ status?: undefined;
112
+ error?: undefined;
113
+ }>;
114
+ export declare function pause(d: DeskContext, who: string): Promise<{
115
+ ok: string;
116
+ }>;
117
+ export declare function resume(d: DeskContext, who: string): Promise<{
118
+ ok: string;
119
+ }>;
120
+ /** The desk page's data and actions, bound to one desk. Methods (not function properties), as the API has always typed them. */
121
+ export interface DeskActions {
122
+ plan: () => ReturnType<typeof plan>;
123
+ approve(who: string, slug: string, items: string[]): ReturnType<typeof approve>;
124
+ revoke(who: string, slug: string, channel: string): ReturnType<typeof revoke>;
125
+ makeNext(who: string, slug: string): ReturnType<typeof makeNext>;
126
+ request(who: string, slug: string, kind: string, body: string): ReturnType<typeof request>;
127
+ reply(who: string, id: number, body: string, status?: string): ReturnType<typeof reply>;
128
+ pause(who: string): ReturnType<typeof pause>;
129
+ resume(who: string): ReturnType<typeof resume>;
130
+ }
@@ -0,0 +1,76 @@
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 } from '../rules.js';
4
+ import { threaded } from './context.js';
5
+ const REQUEST_KINDS = ['generate', 'edit', 'note'];
6
+ /** One channel of one piece on the desk page. */
7
+ function channelRow(all, slug, c) {
8
+ const staged = all.staged.find((s) => s.slug === slug && s.channel === c);
9
+ const posts = all.posts.filter((p) => p.slug === slug && p.channel === c);
10
+ return {
11
+ channel: c, state: channelState(staged, all.approvals.filter((x) => x.slug === slug && x.channel === c), posts),
12
+ staged: staged ?? null, url: posts.filter((p) => p.status === 'posted').at(-1)?.url ?? null, last: posts.at(-1) ?? null,
13
+ };
14
+ }
15
+ /** One piece on the desk page: its date (as set and as built), each channel's state, its production and requests. */
16
+ function pieceRow(d, a, { t, all, prod, requests, dates }) {
17
+ const date = dates.get(a.slug);
18
+ const channels = d.expected(a).map((c) => channelRow(all, a.slug, c));
19
+ const p = prod.find((x) => x.slug === a.slug);
20
+ return {
21
+ ...a, date, built: a.date, moved: date !== a.date, live: a.date <= t, channels,
22
+ script: p?.script ?? null, status: p?.status ?? {}, reported: p?.updated_at ?? null,
23
+ requests: threaded(requests, (r) => r.slug === a.slug),
24
+ };
25
+ }
26
+ /** The desk page's data: every piece in date order with each channel's state, production and requests. */
27
+ export async function plan(d) {
28
+ const t = d.o.today(), all = await d.store.readAll(), prod = await d.store.readProduction(), requests = await d.store.readRequests();
29
+ const pieces = await d.o.pieces(), dates = effectiveDates(pieces, all.schedule);
30
+ const rows = pieces.map((a) => pieceRow(d, a, { t, all, prod, requests, dates }))
31
+ .sort((x, y) => x.date.localeCompare(y.date) || x.slug.localeCompare(y.slug));
32
+ 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() };
33
+ }
34
+ export async function approve(d, who, slug, items) {
35
+ let n = 0;
36
+ for (const item of items) {
37
+ const [c, sha] = item.split(':');
38
+ if (isChannel(c) && (await d.store.approve(who, slug, c, sha)))
39
+ n++;
40
+ }
41
+ 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.` };
42
+ }
43
+ export async function revoke(d, who, slug, channel) {
44
+ if (!isChannel(channel))
45
+ return { status: 400, error: 'Bad channel' };
46
+ await d.store.revoke(who, slug, channel);
47
+ return { ok: 'Approval withdrawn' };
48
+ }
49
+ export async function makeNext(d, who, slug) {
50
+ const all = await d.store.readAll();
51
+ const moved = moveToNext(effectiveDates(await d.o.pieces(), all.schedule), slug, d.o.today());
52
+ if (!moved.size)
53
+ return { status: 400, error: 'That piece is already next, or already published.' };
54
+ await d.store.setDates(who, moved, `make next: ${slug}`);
55
+ return { ok: `Moved ${slug} to ${moved.get(slug)}; ${moved.size - 1} other piece(s) moved down one slot.` };
56
+ }
57
+ export async function request(d, who, slug, kind, body) {
58
+ if (!(await d.slugs()).has(slug))
59
+ return { status: 400, error: 'No such piece' };
60
+ if (!body.trim() && kind !== 'generate')
61
+ return { status: 400, error: 'Say what to change' };
62
+ await d.store.addRequest(who, slug, REQUEST_KINDS.includes(kind) ? kind : 'edit', body.trim() || 'Generate the motion for this piece from its script.');
63
+ return { ok: 'Sent. Replies appear in the thread.' };
64
+ }
65
+ export async function reply(d, who, id, body, status) {
66
+ const parent = (await d.store.readRequests()).find((r) => r.id === id && !r.parent);
67
+ if (!parent)
68
+ return { status: 404, error: 'No such request' };
69
+ if (body.trim())
70
+ await d.store.addRequest(who, parent.slug, 'note', body.trim(), id);
71
+ if (status)
72
+ await d.store.setRequestStatus(who, id, status);
73
+ return { ok: 'Saved' };
74
+ }
75
+ export async function pause(d, who) { await d.store.setPaused(who, true); return { ok: 'Posting paused' }; }
76
+ export async function resume(d, who) { await d.store.setPaused(who, false); return { ok: 'Posting resumed' }; }
package/dist/store.js CHANGED
@@ -3,70 +3,86 @@
3
3
  // database (Postgres, SQLite, KV) only needs these methods.
4
4
  import { contentSha } from './rules.js';
5
5
  const now = () => new Date().toISOString();
6
+ /** Media files in a map. Its methods are own properties, so they work taken off the object. */
7
+ class MemoryMedia {
8
+ #files = new Map();
9
+ get = async (key) => {
10
+ const f = this.#files.get(key);
11
+ return f ? { body: f.bytes, size: f.bytes.byteLength, contentType: f.contentType, sha256: f.sha256 } : null;
12
+ };
13
+ head = async (key) => {
14
+ const f = this.#files.get(key);
15
+ return f ? { size: f.bytes.byteLength, sha256: f.sha256 } : null;
16
+ };
17
+ put = async (key, bytes, o) => { this.#files.set(key, { bytes, ...o }); };
18
+ }
19
+ /**
20
+ * The desk's rows in memory. Its methods are own properties (no private state shows), so they work taken off the
21
+ * object; each one audits through `this.audit`, the store's own. One id sequence numbers every row.
22
+ */
23
+ class MemoryStore {
24
+ #s = { staged: [], approvals: [], posts: [], paused: true, schedule: [] };
25
+ #log = [];
26
+ #production = new Map();
27
+ #requests = [];
28
+ #id = 0;
29
+ readAll = async () => structuredClone(this.#s);
30
+ recentAudit = async (n = 40) => this.#log.slice(-n).reverse();
31
+ audit = async (actor, action, slug = null, channel = null, detail) => {
32
+ this.#log.push({ id: ++this.#id, at: now(), actor, action, slug, channel, detail: detail ?? null });
33
+ };
34
+ stage = async (actor, slug, channel, post) => {
35
+ const sha = await contentSha(channel, post);
36
+ this.#s.staged = this.#s.staged.filter((r) => !(r.slug === slug && r.channel === channel));
37
+ this.#s.staged.push({ slug, channel, post: structuredClone(post), content_sha: sha, staged_by: actor, staged_at: now() });
38
+ await this.audit(actor, 'stage', slug, channel, sha.slice(0, 12));
39
+ return sha;
40
+ };
41
+ approve = async (actor, slug, channel, seen) => {
42
+ const row = this.#s.staged.find((r) => r.slug === slug && r.channel === channel);
43
+ if (!row || row.content_sha !== seen)
44
+ return false;
45
+ this.#s.approvals.push({ id: ++this.#id, slug, channel, content_sha: seen, approved_by: actor, approved_at: now(), revoked_at: null });
46
+ await this.audit(actor, 'approve', slug, channel, seen.slice(0, 12));
47
+ return true;
48
+ };
49
+ revoke = async (actor, slug, channel) => {
50
+ const live = this.#s.approvals.filter((a) => a.slug === slug && a.channel === channel && !a.revoked_at);
51
+ for (const a of live)
52
+ a.revoked_at = now();
53
+ await this.audit(actor, 'revoke', slug, channel);
54
+ };
55
+ setPaused = async (actor, paused) => { this.#s.paused = paused; await this.audit(actor, paused ? 'pause' : 'resume'); };
56
+ recordPost = async (actor, p) => {
57
+ 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() });
58
+ await this.audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
59
+ };
60
+ readSchedule = async () => structuredClone(this.#s.schedule);
61
+ setDates = async (actor, moved, why) => {
62
+ if (!moved.size)
63
+ return;
64
+ for (const [slug, d] of moved) {
65
+ this.#s.schedule = this.#s.schedule.filter((x) => x.slug !== slug);
66
+ this.#s.schedule.push({ slug, publish_date: d });
67
+ }
68
+ await this.audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([x, d]) => `${x}→${d}`).join(', ')}`);
69
+ };
70
+ readProduction = async () => [...this.#production.values()];
71
+ saveProduction = async (slug, script, status) => { this.#production.set(slug, { slug, script, status, updated_at: now() }); };
72
+ readRequests = async (openOnly = false) => this.#requests.filter((r) => !openOnly || (!r.parent && r.status !== 'done'));
73
+ addRequest = async (actor, slug, kind, body, parent = null) => {
74
+ this.#requests.push({ id: ++this.#id, slug, kind, body: body.slice(0, 4000), author: actor, at: now(), status: 'open', parent });
75
+ await this.audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
76
+ };
77
+ setRequestStatus = async (actor, rid, status) => {
78
+ const r = this.#requests.find((x) => x.id === rid);
79
+ if (r)
80
+ r.status = status;
81
+ await this.audit(actor, `request:${status}`, null, null, `#${rid}`);
82
+ };
83
+ media = new MemoryMedia();
84
+ }
6
85
  /** Everything in memory. Starts paused, like the real one. */
7
86
  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;
87
+ return new MemoryStore();
72
88
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senseihq/emaki-posting",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "The motion stories posting desk: stage, approve exactly what was staged, post on schedule. Framework-free core with Cloudflare (D1/R2/Access) and SvelteKit adapters.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/poster/net.py ADDED
@@ -0,0 +1,22 @@
1
+ """HTTP for the poster: stdlib only, and every HTTP error raised as Failed so one post's failure is reported, not fatal."""
2
+ import json
3
+ import urllib.request
4
+
5
+
6
+ class Failed(Exception):
7
+ pass
8
+
9
+
10
+ def http(method, url, body=None, headers=None, timeout=600):
11
+ req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
12
+ try:
13
+ with urllib.request.urlopen(req, timeout=timeout) as r:
14
+ return r.status, dict(r.headers), r.read()
15
+ except urllib.error.HTTPError as err:
16
+ raise Failed(f'{method} {url.split("?")[0]} → {err.code}: {err.read()[:400].decode(errors="replace")}')
17
+
18
+
19
+ def jhttp(method, url, data=None, headers=None):
20
+ body = json.dumps(data).encode() if data is not None else None
21
+ _, _, b = http(method, url, body, {**({'content-type': 'application/json'} if body else {}), **(headers or {})})
22
+ return json.loads(b or b'{}')