inkwire-receiver-core 0.1.1 → 1.0.0

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,94 @@
1
+ import type { ContentStore, ListFilter, ListResult, MediaInput, MediaListFilter, MediaListResult, SaveEntry, StoredContent, StoredMedia } from "../store.js";
2
+ export interface GitHubStoreOptions {
3
+ owner: string;
4
+ repo: string;
5
+ branch: string;
6
+ /** Folder in the repo that holds `<kind>/<slug>.md` (and `media/`). Empty string = repo root. */
7
+ dir: string;
8
+ /** A token with contents read/write on the repo. Never logged, never put in an error message. */
9
+ token: string;
10
+ /** Public base of `<dir>/media`, no trailing slash. */
11
+ mediaUrlBase: string;
12
+ /** Public address of an entry. Default: the origin of `mediaUrlBase` + `/<kind>/<slug>`. */
13
+ urlFor?: (e: {
14
+ kind: string;
15
+ slug: string;
16
+ }) => string;
17
+ /** Default https://api.github.com (GitHub Enterprise, or a local stand-in in tests). */
18
+ apiBase?: string;
19
+ /** Default `globalThis.fetch`. */
20
+ fetch?: typeof fetch;
21
+ }
22
+ /**
23
+ * Entries as markdown files in a GitHub repo, through the contents/trees REST API (raw `fetch`).
24
+ * One store is one site. The ETag is the file's blob sha, so it changes exactly when the content does.
25
+ *
26
+ * Listing is ordered by path (kind, slug), not by recency: GitHub has no cheap per-file dates. A
27
+ * file with no dates in its frontmatter reports the epoch. Content filters (status, tag, search,
28
+ * external_id) read file bodies; they are cached by blob sha, so a warm process makes one request
29
+ * (the tree) and a cold one reads each candidate file once.
30
+ */
31
+ export declare class GitHubStore implements ContentStore {
32
+ private o;
33
+ private dir;
34
+ private mediaBase;
35
+ private fetchFn;
36
+ private api;
37
+ private urlFor;
38
+ private cache;
39
+ private metaCache;
40
+ constructor(opts: GitHubStoreOptions);
41
+ private prefix;
42
+ private pathFor;
43
+ private gh;
44
+ /** Maps a failed response to an InkwireError. The token never appears in the message. */
45
+ private failure;
46
+ private remember;
47
+ private parse;
48
+ private fetchFile;
49
+ private decode;
50
+ /** A file's current text and blob sha, or null when it does not exist. */
51
+ private rawAt;
52
+ get(key: string, id: string): Promise<{
53
+ key: string;
54
+ html: string;
55
+ title: string;
56
+ status: "draft" | "published";
57
+ external_id: string | null;
58
+ markdown: string;
59
+ kind: string;
60
+ slug: string;
61
+ excerpt?: string | undefined;
62
+ tags?: string[] | undefined;
63
+ categories?: string[] | undefined;
64
+ cover_image_url?: string | undefined;
65
+ cover_image_alt?: string | undefined;
66
+ canonical_url?: string | undefined;
67
+ seo: import("../store.js").SeoOverrides | null;
68
+ author?: {
69
+ name?: string;
70
+ email?: string;
71
+ } | undefined;
72
+ published_at: string;
73
+ url: string;
74
+ id: string;
75
+ etag: string;
76
+ updated_at: string;
77
+ version: number;
78
+ } | null>;
79
+ list(key: string, filter: ListFilter): Promise<ListResult>;
80
+ private shaAt;
81
+ save(key: string, entry: SaveEntry): Promise<StoredContent>;
82
+ private deleteAt;
83
+ remove(_key: string, id: string): Promise<boolean>;
84
+ private putFile;
85
+ saveMedia(_key: string, m: MediaInput): Promise<StoredMedia>;
86
+ /** Every uploaded image in the media folder, with the blob sha of its sidecar when it has one. */
87
+ private mediaFiles;
88
+ private readMeta;
89
+ listMedia(_key: string, filter: MediaListFilter): Promise<MediaListResult>;
90
+ updateMedia(_key: string, id: string, patch: {
91
+ alt?: string | null;
92
+ title?: string | null;
93
+ }): Promise<StoredMedia | null>;
94
+ }
@@ -0,0 +1,334 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { InkwireError } from "../errors.js";
3
+ import { KIND_RE, RESERVED_KINDS, SLUG_FILE_RE, idFor, parseEntryFile, parseId, serializeEntry, updateEntryFile } from "../files.js";
4
+ import { matches, pageMedia, pageOf, recencyKey } from "../list.js";
5
+ import { MEDIA_FILE_RE, MEDIA_ID_RE, META_SUFFIX, parseMeta, patchMeta, serializeMeta, toMedia } from "../media-meta.js";
6
+ const CACHE_MAX = 2000;
7
+ const CONCURRENCY = 8;
8
+ const EPOCH = "1970-01-01T00:00:00.000Z";
9
+ const b64 = (s) => Buffer.from(s).toString("base64");
10
+ const encodePath = (p) => p.split("/").map(encodeURIComponent).join("/");
11
+ /**
12
+ * Entries as markdown files in a GitHub repo, through the contents/trees REST API (raw `fetch`).
13
+ * One store is one site. The ETag is the file's blob sha, so it changes exactly when the content does.
14
+ *
15
+ * Listing is ordered by path (kind, slug), not by recency: GitHub has no cheap per-file dates. A
16
+ * file with no dates in its frontmatter reports the epoch. Content filters (status, tag, search,
17
+ * external_id) read file bodies; they are cached by blob sha, so a warm process makes one request
18
+ * (the tree) and a cold one reads each candidate file once.
19
+ */
20
+ export class GitHubStore {
21
+ o;
22
+ dir;
23
+ mediaBase;
24
+ fetchFn;
25
+ api;
26
+ urlFor;
27
+ cache = new Map(); // blob sha -> parsed entry
28
+ metaCache = new Map(); // blob sha of a media sidecar -> parsed
29
+ constructor(opts) {
30
+ if (!opts.token)
31
+ throw new Error("GitHubStore: token is required");
32
+ const dir = opts.dir.replace(/^\/+|\/+$/g, "");
33
+ if (dir.split("/").some((s) => s === ".." || s === "."))
34
+ throw new Error("GitHubStore: dir must not contain . or ..");
35
+ this.o = opts;
36
+ this.dir = dir;
37
+ this.mediaBase = opts.mediaUrlBase.replace(/\/+$/, "");
38
+ this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
39
+ this.api = (opts.apiBase ?? "https://api.github.com").replace(/\/+$/, "");
40
+ this.urlFor =
41
+ opts.urlFor ??
42
+ ((e) => {
43
+ let origin = this.mediaBase;
44
+ try {
45
+ origin = new URL(this.mediaBase).origin;
46
+ }
47
+ catch { }
48
+ return `${origin}/${e.kind}/${e.slug}`;
49
+ });
50
+ }
51
+ prefix() {
52
+ return this.dir ? `${this.dir}/` : "";
53
+ }
54
+ pathFor(kind, slug) {
55
+ if (!KIND_RE.test(kind) || RESERVED_KINDS.has(kind))
56
+ throw new InkwireError("invalid_payload", `kind "${kind}" cannot be stored as a folder`);
57
+ if (!SLUG_FILE_RE.test(slug))
58
+ throw new InkwireError("invalid_payload", `slug "${slug}" is not a valid filename`);
59
+ return `${this.prefix()}${kind}/${slug}.md`;
60
+ }
61
+ async gh(method, endpoint, body, accept = "application/vnd.github+json") {
62
+ const url = `${this.api}/repos/${encodeURIComponent(this.o.owner)}/${encodeURIComponent(this.o.repo)}${endpoint}`;
63
+ let res;
64
+ try {
65
+ res = await this.fetchFn(url, {
66
+ method,
67
+ headers: {
68
+ Authorization: `Bearer ${this.o.token}`,
69
+ Accept: accept,
70
+ "X-GitHub-Api-Version": "2022-11-28",
71
+ "User-Agent": "inkwire-receiver-core",
72
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
73
+ },
74
+ body: body !== undefined ? JSON.stringify(body) : undefined,
75
+ });
76
+ }
77
+ catch {
78
+ throw new InkwireError("internal", "could not reach GitHub");
79
+ }
80
+ return res;
81
+ }
82
+ /** Maps a failed response to an InkwireError. The token never appears in the message. */
83
+ async failure(res, what) {
84
+ const rateLimited = res.status === 429 || (res.status === 403 && res.headers.get("x-ratelimit-remaining") === "0");
85
+ if (rateLimited)
86
+ return new InkwireError("rate_limited", "GitHub rate limit reached; retry later");
87
+ if (res.status === 401 || res.status === 403)
88
+ return new InkwireError("internal", `GitHub refused the receiver's token while ${what}`);
89
+ if (res.status === 409 || res.status === 422)
90
+ return new InkwireError("stale", `the file changed in the repository while ${what}; read it again and retry`);
91
+ return new InkwireError("internal", `GitHub answered ${res.status} while ${what}`);
92
+ }
93
+ remember(sha, e) {
94
+ if (this.cache.size >= CACHE_MAX)
95
+ this.cache.delete(this.cache.keys().next().value);
96
+ this.cache.set(sha, e);
97
+ }
98
+ parse(raw, kind, slug, sha) {
99
+ const draft = parseEntryFile(raw, { kind, slug, mtimeIso: EPOCH });
100
+ const e = draft ? { ...draft, id: idFor(kind, slug), url: this.urlFor({ kind, slug }), etag: sha } : null;
101
+ this.remember(sha, e);
102
+ return e;
103
+ }
104
+ async fetchFile(kind, slug, knownSha) {
105
+ if (knownSha && this.cache.has(knownSha))
106
+ return this.cache.get(knownSha) ?? null;
107
+ const res = await this.gh("GET", `/contents/${encodePath(this.pathFor(kind, slug))}?ref=${encodeURIComponent(this.o.branch)}`);
108
+ if (res.status === 404)
109
+ return null;
110
+ if (!res.ok)
111
+ throw await this.failure(res, "reading an entry");
112
+ const json = (await res.json());
113
+ if (json.type && json.type !== "file")
114
+ return null;
115
+ const sha = json.sha ?? "";
116
+ if (sha && this.cache.has(sha))
117
+ return this.cache.get(sha) ?? null;
118
+ return this.parse(await this.decode(json), kind, slug, sha);
119
+ }
120
+ async decode(json) {
121
+ if (json.encoding === "base64" && typeof json.content === "string" && json.content !== "") {
122
+ return Buffer.from(json.content, "base64").toString("utf8");
123
+ }
124
+ // Files over 1 MB come back without content: read the blob instead.
125
+ const blob = await this.gh("GET", `/git/blobs/${encodeURIComponent(json.sha ?? "")}`, undefined, "application/vnd.github.raw+json");
126
+ if (!blob.ok)
127
+ throw await this.failure(blob, "reading an entry");
128
+ return blob.text();
129
+ }
130
+ /** A file's current text and blob sha, or null when it does not exist. */
131
+ async rawAt(filePath) {
132
+ const res = await this.gh("GET", `/contents/${encodePath(filePath)}?ref=${encodeURIComponent(this.o.branch)}`);
133
+ if (res.status === 404)
134
+ return null;
135
+ if (!res.ok)
136
+ throw await this.failure(res, "checking a file");
137
+ const json = (await res.json());
138
+ if (json.type && json.type !== "file")
139
+ return null;
140
+ return { sha: json.sha ?? "", raw: await this.decode(json) };
141
+ }
142
+ async get(key, id) {
143
+ const p = parseId(id);
144
+ if (!p)
145
+ return null;
146
+ const e = await this.fetchFile(p.kind, p.slug);
147
+ return e ? { ...e, key } : null;
148
+ }
149
+ async list(key, filter) {
150
+ const treeRes = await this.gh("GET", `/git/trees/${encodeURIComponent(this.o.branch)}?recursive=1`);
151
+ if (treeRes.status === 404)
152
+ return { items: [], next_cursor: null };
153
+ if (!treeRes.ok)
154
+ throw await this.failure(treeRes, "listing entries");
155
+ const tree = (await treeRes.json());
156
+ if (tree.truncated)
157
+ throw new InkwireError("internal", "the repository is too large to list through the trees API");
158
+ const prefix = this.prefix();
159
+ const re = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([a-z][a-z0-9_-]{0,63})/([a-z0-9-]+)\\.md$`);
160
+ const candidates = [];
161
+ for (const t of tree.tree ?? []) {
162
+ if (t.type !== "blob")
163
+ continue;
164
+ const m = re.exec(t.path);
165
+ if (!m || RESERVED_KINDS.has(m[1]))
166
+ continue;
167
+ if (filter.kind && m[1] !== filter.kind)
168
+ continue;
169
+ if (filter.slug && m[2] !== filter.slug)
170
+ continue;
171
+ candidates.push({ kind: m[1], slug: m[2], sha: t.sha, path: t.path });
172
+ }
173
+ // Newest first (SPEC: `updated_at` descending, ties by id), which needs every candidate read:
174
+ // a file's date is in its frontmatter and GitHub has no cheap mtime. Reads are cached by blob
175
+ // sha, so only files that changed since the last listing cost a request. A kind or slug
176
+ // filter narrows the candidates before any read.
177
+ const loaded = [];
178
+ for (let i = 0; i < candidates.length; i += CONCURRENCY) {
179
+ const chunk = candidates.slice(i, i + CONCURRENCY);
180
+ const entries = await Promise.all(chunk.map((c) => this.fetchFile(c.kind, c.slug, c.sha)));
181
+ for (const e of entries) {
182
+ if (!e)
183
+ continue;
184
+ const withKey = { ...e, key };
185
+ if (matches(withKey, filter))
186
+ loaded.push(withKey);
187
+ }
188
+ }
189
+ loaded.sort((a, b) => (recencyKey(a) < recencyKey(b) ? -1 : 1));
190
+ return pageOf(loaded, recencyKey, filter.limit, filter.cursor);
191
+ }
192
+ async shaAt(filePath) {
193
+ const res = await this.gh("GET", `/contents/${encodePath(filePath)}?ref=${encodeURIComponent(this.o.branch)}`);
194
+ if (res.status === 404)
195
+ return null;
196
+ if (!res.ok)
197
+ throw await this.failure(res, "checking a file");
198
+ const j = (await res.json());
199
+ return j.sha ?? null;
200
+ }
201
+ async save(key, entry) {
202
+ const filePath = this.pathFor(entry.kind, entry.slug);
203
+ const newId = idFor(entry.kind, entry.slug);
204
+ const existing = await this.rawAt(filePath);
205
+ if (existing && entry.id !== newId)
206
+ throw new InkwireError("conflict", `${entry.kind}/${entry.slug}.md already exists`);
207
+ // An edit of an existing file changes only what changed in it (its own frontmatter keys survive).
208
+ const old = entry.id ? parseId(entry.id) : null;
209
+ const previous = !old ? null : entry.id === newId ? existing : await this.rawAt(this.pathFor(old.kind, old.slug));
210
+ const before = previous && old ? this.parse(previous.raw, old.kind, old.slug, previous.sha) : null;
211
+ const text = (previous && before && updateEntryFile(previous.raw, before, entry)) || serializeEntry(entry);
212
+ const action = entry.id ? "update" : "create";
213
+ const res = await this.gh("PUT", `/contents/${encodePath(filePath)}`, {
214
+ message: `inkwire: ${action} ${entry.kind}/${entry.slug}`,
215
+ content: b64(text),
216
+ branch: this.o.branch,
217
+ ...(existing ? { sha: existing.sha } : {}),
218
+ });
219
+ if (!res.ok)
220
+ throw await this.failure(res, "saving an entry");
221
+ const j = (await res.json());
222
+ const sha = j.content?.sha ?? "";
223
+ if (entry.id && entry.id !== newId) {
224
+ const old = parseId(entry.id);
225
+ if (old)
226
+ await this.deleteAt(this.pathFor(old.kind, old.slug)).catch(() => false);
227
+ }
228
+ const { id: _id, ...rest } = entry;
229
+ const saved = { ...rest, id: newId, key, url: this.urlFor(entry), etag: sha };
230
+ const { key: _k, ...draft } = saved;
231
+ this.remember(sha, draft);
232
+ return saved;
233
+ }
234
+ async deleteAt(filePath) {
235
+ const sha = await this.shaAt(filePath);
236
+ if (!sha)
237
+ return false;
238
+ const res = await this.gh("DELETE", `/contents/${encodePath(filePath)}`, {
239
+ message: `inkwire: delete ${filePath.slice(this.prefix().length)}`,
240
+ sha,
241
+ branch: this.o.branch,
242
+ });
243
+ if (res.status === 404)
244
+ return false;
245
+ if (!res.ok)
246
+ throw await this.failure(res, "deleting an entry");
247
+ return true;
248
+ }
249
+ async remove(_key, id) {
250
+ const p = parseId(id);
251
+ if (!p)
252
+ return false;
253
+ return this.deleteAt(this.pathFor(p.kind, p.slug));
254
+ }
255
+ async putFile(filePath, content, message, sha) {
256
+ const res = await this.gh("PUT", `/contents/${encodePath(filePath)}`, {
257
+ message,
258
+ content: b64(content),
259
+ branch: this.o.branch,
260
+ ...(sha ? { sha } : {}),
261
+ });
262
+ if (!res.ok)
263
+ throw await this.failure(res, "saving media");
264
+ return (await res.json()).content?.sha ?? "";
265
+ }
266
+ async saveMedia(_key, m) {
267
+ const hex = randomBytes(8).toString("hex");
268
+ const name = `${hex}-${m.filename}`;
269
+ const meta = { ...(m.alt !== undefined ? { alt: m.alt } : {}), content_type: m.contentType, created_at: new Date().toISOString() };
270
+ await this.putFile(`${this.prefix()}media/${name}`, m.bytes, `inkwire: add media ${name}`);
271
+ await this.putFile(`${this.prefix()}media/${name}${META_SUFFIX}`, serializeMeta(meta), `inkwire: describe media ${name}`);
272
+ return toMedia(hex, `${this.mediaBase}/${name}`, meta);
273
+ }
274
+ /** Every uploaded image in the media folder, with the blob sha of its sidecar when it has one. */
275
+ async mediaFiles() {
276
+ const treeRes = await this.gh("GET", `/git/trees/${encodeURIComponent(this.o.branch)}?recursive=1`);
277
+ if (treeRes.status === 404)
278
+ return [];
279
+ if (!treeRes.ok)
280
+ throw await this.failure(treeRes, "listing media");
281
+ const tree = (await treeRes.json());
282
+ if (tree.truncated)
283
+ throw new InkwireError("internal", "the repository is too large to list through the trees API");
284
+ const base = `${this.prefix()}media/`;
285
+ const shas = new Map();
286
+ for (const t of tree.tree ?? [])
287
+ if (t.type === "blob" && t.path.startsWith(base) && !t.path.slice(base.length).includes("/"))
288
+ shas.set(t.path.slice(base.length), t.sha);
289
+ const out = [];
290
+ for (const [name] of shas) {
291
+ if (name.endsWith(META_SUFFIX) || !MEDIA_FILE_RE.test(name))
292
+ continue;
293
+ const metaSha = shas.get(`${name}${META_SUFFIX}`);
294
+ out.push({ name, ...(metaSha ? { metaSha } : {}) });
295
+ }
296
+ return out;
297
+ }
298
+ async readMeta(name, metaSha) {
299
+ if (!metaSha)
300
+ return parseMeta(null, name, EPOCH);
301
+ const hit = this.metaCache.get(metaSha);
302
+ if (hit)
303
+ return hit;
304
+ const blob = await this.gh("GET", `/git/blobs/${encodeURIComponent(metaSha)}`, undefined, "application/vnd.github.raw+json");
305
+ if (!blob.ok)
306
+ throw await this.failure(blob, "reading media");
307
+ const meta = parseMeta(await blob.text(), name, EPOCH);
308
+ if (this.metaCache.size >= CACHE_MAX)
309
+ this.metaCache.delete(this.metaCache.keys().next().value);
310
+ this.metaCache.set(metaSha, meta);
311
+ return meta;
312
+ }
313
+ async listMedia(_key, filter) {
314
+ const files = await this.mediaFiles();
315
+ const all = [];
316
+ for (let i = 0; i < files.length; i += CONCURRENCY) {
317
+ const chunk = files.slice(i, i + CONCURRENCY);
318
+ const metas = await Promise.all(chunk.map((f) => this.readMeta(f.name, f.metaSha)));
319
+ chunk.forEach((f, j) => all.push(toMedia(MEDIA_FILE_RE.exec(f.name)[1], `${this.mediaBase}/${f.name}`, metas[j])));
320
+ }
321
+ return pageMedia(all, filter);
322
+ }
323
+ async updateMedia(_key, id, patch) {
324
+ if (!MEDIA_ID_RE.test(id))
325
+ return null;
326
+ const file = (await this.mediaFiles()).find((f) => f.name.startsWith(`${id}-`));
327
+ if (!file)
328
+ return null;
329
+ const cur = await this.readMeta(file.name, file.metaSha);
330
+ const meta = patchMeta(cur, patch);
331
+ await this.putFile(`${this.prefix()}media/${file.name}${META_SUFFIX}`, serializeMeta(meta), `inkwire: describe media ${file.name}`, file.metaSha);
332
+ return toMedia(id, `${this.mediaBase}/${file.name}`, meta);
333
+ }
334
+ }
@@ -0,0 +1,27 @@
1
+ import type { ContentStore, ListFilter, ListResult, MediaInput, MediaListFilter, MediaListResult, SaveEntry, StoredContent, StoredMedia } from "../store.js";
2
+ export interface MemoryStoreOptions {
3
+ /** Public address of an entry. Default `https://example.test/<kind>/<slug>`. */
4
+ urlFor?: (e: {
5
+ kind: string;
6
+ slug: string;
7
+ }) => string;
8
+ mediaUrlBase?: string;
9
+ }
10
+ /** In-process store for tests and demos. Nothing survives a restart. Ids are opaque and survive a slug or kind change. */
11
+ export declare class MemoryStore implements ContentStore {
12
+ private opts;
13
+ private entries;
14
+ private media;
15
+ constructor(opts?: MemoryStoreOptions);
16
+ private scope;
17
+ get(key: string, id: string): Promise<StoredContent | null>;
18
+ list(key: string, filter: ListFilter): Promise<ListResult>;
19
+ save(key: string, entry: SaveEntry): Promise<StoredContent>;
20
+ remove(key: string, id: string): Promise<boolean>;
21
+ saveMedia(key: string, m: MediaInput): Promise<StoredMedia>;
22
+ listMedia(key: string, filter: MediaListFilter): Promise<MediaListResult>;
23
+ updateMedia(key: string, id: string, patch: {
24
+ alt?: string | null;
25
+ title?: string | null;
26
+ }): Promise<StoredMedia | null>;
27
+ }
@@ -0,0 +1,65 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { matches, pageMedia, pageOf, recencyKey } from "../list.js";
3
+ import { patchMeta, toMedia } from "../media-meta.js";
4
+ /** In-process store for tests and demos. Nothing survives a restart. Ids are opaque and survive a slug or kind change. */
5
+ export class MemoryStore {
6
+ opts;
7
+ entries = new Map();
8
+ media = new Map();
9
+ constructor(opts = {}) {
10
+ this.opts = opts;
11
+ }
12
+ scope(key) {
13
+ let m = this.entries.get(key);
14
+ if (!m)
15
+ this.entries.set(key, (m = new Map()));
16
+ return m;
17
+ }
18
+ async get(key, id) {
19
+ const e = this.scope(key).get(id);
20
+ return e ? structuredClone(e) : null;
21
+ }
22
+ async list(key, filter) {
23
+ const all = [...this.scope(key).values()].filter((e) => matches(e, filter));
24
+ all.sort((a, b) => (recencyKey(a) < recencyKey(b) ? -1 : 1));
25
+ const page = pageOf(all, recencyKey, filter.limit, filter.cursor);
26
+ return { items: page.items.map((e) => structuredClone(e)), next_cursor: page.next_cursor };
27
+ }
28
+ async save(key, entry) {
29
+ const scope = this.scope(key);
30
+ const id = entry.id ?? randomBytes(8).toString("hex");
31
+ const { id: _ignored, ...rest } = entry;
32
+ const url = this.opts.urlFor ? this.opts.urlFor(entry) : `https://example.test/${entry.kind}/${entry.slug}`;
33
+ const saved = { ...rest, id, key, url, etag: `${id}-${entry.version}` };
34
+ scope.set(id, structuredClone(saved));
35
+ return structuredClone(saved);
36
+ }
37
+ async remove(key, id) {
38
+ return this.scope(key).delete(id);
39
+ }
40
+ async saveMedia(key, m) {
41
+ const id = randomBytes(8).toString("hex");
42
+ const url = `${this.opts.mediaUrlBase ?? "https://example.test/media"}/${id}-${m.filename}`;
43
+ const saved = toMedia(id, url, { ...(m.alt !== undefined ? { alt: m.alt } : {}), content_type: m.contentType, created_at: new Date().toISOString() });
44
+ let bucket = this.media.get(key);
45
+ if (!bucket)
46
+ this.media.set(key, (bucket = new Map()));
47
+ bucket.set(id, { ...saved, bytes: m.bytes, contentType: m.contentType });
48
+ return saved;
49
+ }
50
+ async listMedia(key, filter) {
51
+ const all = [...(this.media.get(key)?.values() ?? [])].map(({ bytes: _b, contentType: _c, ...m }) => m);
52
+ return pageMedia(all, filter);
53
+ }
54
+ async updateMedia(key, id, patch) {
55
+ const cur = this.media.get(key)?.get(id);
56
+ if (!cur)
57
+ return null;
58
+ const meta = patchMeta({ ...(cur.alt !== undefined ? { alt: cur.alt } : {}), ...(cur.title !== undefined ? { title: cur.title } : {}), content_type: cur.mime_type, created_at: cur.created_at }, patch);
59
+ const { bytes, contentType } = cur;
60
+ const next = { ...toMedia(id, cur.url, meta), bytes, contentType };
61
+ this.media.get(key).set(id, next);
62
+ const { bytes: _b, contentType: _c, ...out } = next;
63
+ return out;
64
+ }
65
+ }
@@ -0,0 +1,49 @@
1
+ import type { ContentStore, SaveEntry } from "./store.js";
2
+ /**
3
+ * The store contract as a test suite, for anyone backing Inkwire with their own database.
4
+ *
5
+ * import { describe, test } from "node:test"; // or vitest's describe / it
6
+ * import { runStoreContract } from "inkwire-receiver-core/testing";
7
+ * runStoreContract({ name: "my store", describe, test, create: async () => ({ store: new MyStore(db), cleanup }) });
8
+ *
9
+ * `create` must hand back an EMPTY store each time it is called (a fresh schema, a truncated
10
+ * table, a new directory). The suite checks what the HTTP handlers rely on and what the black-box
11
+ * conformance run cannot see from outside: scope isolation, id stability across a slug or kind
12
+ * change, the etag moving on every write, optional fields coming back absent (not `null`),
13
+ * exact `external_id` and `slug` lookups, and paging that neither repeats nor skips an entry.
14
+ *
15
+ * Uniqueness under concurrent writers (one row per `external_id`, one per `kind` + `slug`) is a
16
+ * database constraint, not something a test can prove: add the unique indexes.
17
+ */
18
+ export interface StoreContractOptions {
19
+ name: string;
20
+ describe: (name: string, fn: () => void) => void;
21
+ test: (name: string, fn: () => Promise<void>) => void;
22
+ create: () => Promise<{
23
+ store: ContentStore;
24
+ cleanup?: () => Promise<void> | void;
25
+ }>;
26
+ /**
27
+ * False for a store that is one site, not one site per key (FileStore, GitHubStore stamp the key
28
+ * on what they return but do not partition by it). Default true: the scope isolation checks run.
29
+ */
30
+ scoped?: boolean;
31
+ /**
32
+ * False for a store whose id is derived from the entry's place (`<kind>.<slug>`): a slug or kind
33
+ * change then gives the entry a new id and the old one stops resolving. Default true: the id
34
+ * survives the change.
35
+ */
36
+ opaqueIds?: boolean;
37
+ /**
38
+ * True for a store that holds only `post` (a blog's table): the checks that move an entry to
39
+ * another kind, or list a second kind, are skipped; asking for any other kind must list nothing.
40
+ */
41
+ singleKind?: boolean;
42
+ /** Public address the store is expected to give an entry. Default: any non-empty string. */
43
+ expectUrl?: (e: {
44
+ kind: string;
45
+ slug: string;
46
+ }) => string;
47
+ }
48
+ export declare function entry(over?: Partial<SaveEntry>): SaveEntry;
49
+ export declare function runStoreContract(o: StoreContractOptions): void;