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.
package/README.md CHANGED
@@ -1,25 +1,144 @@
1
1
  # inkwire-receiver-core
2
2
 
3
- Shared TypeScript core for building an [Inkwire](https://github.com/etugrand/inkwire) receiver: validate the incoming payload against the frozen schema, render+sanitize markdown to HTML, and upsert by `external_id` against a `PostStore` you provide.
3
+ The shared TypeScript core for an [Inkwire](../../SPEC.md) receiver (protocol v1: content with kinds, tags and categories, scheduling, media library, richer SEO, discovery, read-only keys). It owns everything the protocol decides (auth, validation, slugs, SEO Profile 1, sanitizing, ETag/If-Match, errors); an adapter owns only HTTP routing and where entries live.
4
+
5
+ One handler per endpoint. Each takes plain values and returns `{ status, headers, body }`; every response carries `Inkwire-Version: 1`, every error is `{ error: { code, message } }`.
6
+
7
+ ```ts
8
+ import { FileStore, handleUpsert, handleList, handleGet, handlePatch, handleDelete, handleTerms, handleMedia, handleMediaList, handleMediaUpdate, handleDiscovery, parseApiKeys } from "inkwire-receiver-core";
9
+
10
+ const keys = parseApiKeys(process.env.INKWIRE_API_KEYS); // "dev-key,audit-key:ro"
11
+ const store = new FileStore({ root: "./content", mediaUrlBase: "https://acme.com/media" });
12
+ const config = {
13
+ site: { name: "Acme", url: "https://acme.com", description: "Acme's blog", language: "en" },
14
+ kinds: ["post", "page"],
15
+ limits: { markdown_bytes: 1_000_000, media_bytes: 10_000_000 },
16
+ fetchMedia, // optional: your SSRF-guarded fetch, enables `POST /api/media {url}` (feature `media_url`)
17
+ schedule: true, // only if your site holds a future-dated published entry back (feature `schedule`)
18
+ };
19
+
20
+ // POST /api/content
21
+ const r = await handleUpsert({ authHeader: req.headers.authorization, rawBody, keys, store, config });
22
+ res.writeHead(r.status, r.headers).end(JSON.stringify(r.body));
23
+ ```
24
+
25
+ | Endpoint | Handler | Arguments (besides `authHeader`, `keys`) |
26
+ | --- | --- | --- |
27
+ | `POST /api/content` | `handleUpsert` | `rawBody`, `store`, `config` |
28
+ | `GET /api/content` | `handleList` | `query: URLSearchParams`, `store` |
29
+ | `GET /api/content/{id}` | `handleGet` | `id`, `store` |
30
+ | `PATCH /api/content/{id}` | `handlePatch` | `id`, `rawBody`, `ifMatchHeader`, `store`, `config` |
31
+ | `DELETE /api/content/{id}` | `handleDelete` | `id`, `ifMatchHeader`, `store` |
32
+ | `GET /api/terms` | `handleTerms` | `query`, `store` |
33
+ | `POST /api/media` | `handleMedia` | `contentType`, `rawBody` (Buffer), `store`, `config` |
34
+ | `GET /api/media` | `handleMediaList` | `query`, `store` |
35
+ | `PATCH /api/media/{id}` | `handleMediaUpdate` | `id`, `rawBody`, `store` |
36
+ | `GET /api/inkwire` | `handleDiscovery` (or `discoveryBody(config, store)`) | `config`, `store` |
37
+
38
+ Pass the request's `If-Match` header through as `ifMatchHeader`; the core puts a quoted `ETag` on every single-entry response (and on the upsert response). Discovery advertises what is true: the media features follow the store (`media` needs `saveMedia`, `media_list` needs `listMedia`, `media_update` needs `updateMedia`, `media_url` also needs `config.fetchMedia`), `schedule` follows `config.schedule`, and `terms` is always there (terms are derived from the entries, by paging `list`).
39
+
40
+ ## Keys
41
+
42
+ `parseApiKeys("dev-key,audit-key:ro")` -> `[{ key, ro, scope }]`. A `:ro` key may call every `GET` and gets `403 forbidden` on anything that writes (checked before the entry is looked up). All keys parsed together share one `scope`, which is what stores partition by; a multi-tenant adapter builds its own `ApiKey` objects with a scope per site.
43
+
44
+ ## Stores
45
+
46
+ A store is four methods, each scoped by `key` (the `ApiKey.scope`), plus optional media methods:
47
+
48
+ ```ts
49
+ interface ContentStore {
50
+ get(key, id): Promise<StoredContent | null>;
51
+ list(key, filter: ListFilter): Promise<{ items: StoredContent[]; next_cursor: string | null }>;
52
+ save(key, entry: SaveEntry): Promise<StoredContent>; // entry.id set = replace (even if kind/slug moved the address); finalizes `url` and `etag`
53
+ remove(key, id): Promise<boolean>;
54
+ saveMedia?(key, media): Promise<StoredMedia>; // absent = no `media` feature
55
+ listMedia?(key, filter): Promise<{ items: StoredMedia[]; next_cursor: string | null }>; // absent = no `media_list`
56
+ updateMedia?(key, id, { alt?, title? }): Promise<StoredMedia | null>; // `null` value clears; absent = no `media_update`
57
+ }
58
+ ```
59
+
60
+ The core finds an entry by `external_id`, and checks slug conflicts, with `list(key, { kind, external_id | slug, limit: 1 })`: make those filters cheap. `etag` is any opaque string that changes whenever the entry does. Handlers serialise writes per scope inside one process (`withLock`); a store shared by several processes needs its own conditional write.
61
+
62
+ Included:
63
+
64
+ - `MemoryStore`: tests and demos.
65
+ - `FileStore({ root, mediaUrlBase })`: `<root>/<kind>/<slug>.md`, YAML frontmatter + markdown, atomic writes. **Reads hand-written files too**: no/partial frontmatter is fine (title from the first `# ` heading, `external_id: null`, status `published`, kind from the folder, dates from frontmatter or the file). ETag = mtime + size + content hash, so an edit outside the API is noticed. Hugo, Astro and Jekyll spellings are understood (`draft: true`, `published: false`, `date`, `pubDate`, `lastmod`, `description`), and an edit changes only the keys it names: the file's other frontmatter keys, comments and field spellings survive; a file whose frontmatter is not valid YAML stays hidden and is never overwritten. Ids are `<kind>.<slug>`; file names must match `^[a-z0-9-]+$` (anything else is invisible and never opens a path). One FileStore is one site.
66
+ - `GitHubStore({ owner, repo, branch, dir, token, mediaUrlBase })`: the same files in a repo through the contents/trees REST API (raw `fetch`; the token is only ever sent as a bearer header). ETag = blob sha. Listing is ordered by path, not recency, and file bodies are read (and cached by sha) only for content filters and page items.
67
+
68
+ ## Backing it with a database
69
+
70
+ Most sites already have their posts in a database. You do not migrate them: you write a `ContentStore` over the table you have and mount the handlers on your own routes, behind your own authentication. [DadSEO](https://getdadseo.com) did exactly this for a Postgres + Drizzle blog (`DbStore`, about 200 lines, plus three small route files per endpoint family). The pattern, with the parts that matter:
4
71
 
5
72
  ```ts
6
- import { handlePost, MemoryStore } from "inkwire-receiver-core";
7
-
8
- const store = new MemoryStore(); // or your own PostStore-backed implementation
9
- const { status, body, headers } = await handlePost({
10
- authHeader: req.headers.get("authorization"),
11
- rawBody: await req.json(),
12
- apiKeys: ["your-api-key"],
13
- store,
73
+ import { decodeCursor, encodeCursor, recencyKey, InkwireError, renderMarkdown } from "inkwire-receiver-core";
74
+ import type { ContentStore, ListFilter, SaveEntry, StoredContent } from "inkwire-receiver-core";
75
+
76
+ export class DbStore implements ContentStore {
77
+ constructor(private siteUrl: string, private db: Db) {}
78
+
79
+ // 1. Map a row to StoredContent. Absent columns (NULL) become *absent keys*, never null or "":
80
+ // `if (row.excerpt != null) c.excerpt = row.excerpt`. `seo` is null when there are no overrides.
81
+ // `html` may be stored, or re-derived with renderMarkdown(row.markdown).
82
+ // etag: anything that changes on every write, e.g. `${row.id}-${row.version}`.
83
+ private toContent(key: string, row: Row): StoredContent { /* ... */ }
84
+
85
+ async get(key, id) { /* select ... where id = $1 */ }
86
+
87
+ // 2. list: newest first by updated_at, ties by id. Support the filters in ListFilter (status, kind,
88
+ // tag, category, search over title/excerpt/markdown, exact external_id and slug). The cursor is
89
+ // keyset: recencyKey(lastItem) is "<inverted updated_at>|<id>", an ascending string, so
90
+ // "the next page" is "rows older than the cursor's instant, or the same instant with a greater id".
91
+ // Fetch limit + 1 rows to know whether there is a next page.
92
+ async list(key, f: ListFilter) { /* ... */ }
93
+
94
+ // 3. save: entry.id set means replace that row (even when the slug changed); otherwise insert with a
95
+ // fresh opaque id. Bump nothing yourself: the core hands you `version` and `updated_at`.
96
+ async save(key, e: SaveEntry) { /* update ... returning / insert ... returning */ }
97
+
98
+ async remove(key, id) { /* delete ... returning id; return rows > 0 */ }
99
+
100
+ // 4. Optional: saveMedia / listMedia / updateMedia over a media table (DadSEO keeps the bytes in a
101
+ // bytea column and serves them from /blog-media/<id>/<name>; S3 or a CDN works as well).
102
+ }
103
+ ```
104
+
105
+ Then the routes call the handlers with your own authentication (the handlers only check that a key you pass is valid and writable, so give them `keys` built from *your* auth result, scoped as you like):
106
+
107
+ ```ts
108
+ // app/api/content/route.ts (Next.js)
109
+ export async function POST(req: Request) {
110
+ const keys = await myAuth(req); // [] or [{ key, ro: false, scope: "blog" }]
111
+ if (!keys) return refusal(401);
112
+ return toResponse(await handleUpsert({ authHeader: req.headers.get("authorization"), rawBody: await req.text(), keys, store, config }));
113
+ }
114
+ ```
115
+
116
+ Prove it with the store contract, then with the black-box suite against the running site:
117
+
118
+ ```ts
119
+ import { runStoreContract } from "inkwire-receiver-core/testing";
120
+ runStoreContract({ name: "DbStore", describe, test, create: async () => ({ store: new DbStore(SITE, await freshDb()), cleanup }),
121
+ scoped: false, // the table is one site
122
+ opaqueIds: true, // a slug change keeps the id
123
+ singleKind: true, // the table only holds posts
14
124
  });
15
125
  ```
16
126
 
17
- This package is the shared logic behind the [Express](https://github.com/etugrand/inkwire/tree/master/inkwire/receivers/node-express) and [Next.js](https://github.com/etugrand/inkwire/tree/master/inkwire/receivers/nextjs) reference receivers — see either for a full adapter example, and the [protocol spec](https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md) for the wire contract `handlePost` implements.
127
+ ```bash
128
+ npx inkwire-conformance https://staging.example.com --key <key> --seo
129
+ ```
130
+
131
+ Things a database store has to get right, all checked by the contract: absent fields come back absent; dates come back as the same ISO string they went in (ms precision); `list` pages never repeat or skip an entry when rows are added between pages; an update keeps the id and moves the etag; `list` with an unknown `kind` returns nothing (a single-kind table answers `kind: "page"` with an empty list, not an error). Add unique indexes on `slug` (per kind) and `external_id`: the core serialises writes inside one process, the database is what protects you across several. If your site hides future-dated entries from its pages, set `config.schedule: true`; the scheduling rule is just "published with a future `published_at`", no job needed.
132
+
133
+ ## Also exported
18
134
 
19
- ## Exports
135
+ `renderMarkdown` (the SPEC's canonical allowlist), `slugify` (fallback `entry`), `edits(markdown, [{ find, replace }])` (each `find` must occur exactly once, else `invalid_payload` `edit_not_found:`/`edit_ambiguous:`), `InkwireError`, `effectiveSeo`, the zod schemas, and the types `StoredContent`, `UpsertInput`, `PatchInput`, `ListFilter`, `SeoMetadata`, `InkwireConfig`.
20
136
 
21
- - `handlePost(input)` — the whole request lifecycle: auth, validation, slugging, sanitization, store upsert.
22
- - `type PostStore` — the interface your storage backend must implement (`findByExternalId`, `findBySlug`, `upsert`).
23
- - `MemoryStore` — an in-memory `PostStore` for local dev/testing.
24
- - `renderMarkdown`, `slugify` — the sanitization and slug-generation helpers `handlePost` uses internally.
25
- - `InkwireError` — typed error class mapping to the protocol's error codes.
137
+ ## Develop
138
+
139
+ ```bash
140
+ npm install
141
+ npm test # node --test
142
+ npm run typecheck
143
+ npm run conformance # builds, serves the handlers on node:http over a FileStore, runs ../../conformance (the `inkwire-conformance` suite)
144
+ ```
package/dist/auth.d.ts CHANGED
@@ -1 +1,18 @@
1
- export declare function authorize(authHeader: string | undefined, apiKeys: string[]): string;
1
+ /**
2
+ * A key the receiver accepts. `ro` keys may call every GET and get 403 on anything that writes.
3
+ * `scope` is what stores partition content by: every key parsed together belongs to one site and
4
+ * shares one scope, so a read-only audit key sees what the full key wrote. A multi-tenant adapter
5
+ * builds its own `ApiKey` objects with a per-site scope.
6
+ */
7
+ export interface ApiKey {
8
+ key: string;
9
+ ro: boolean;
10
+ scope: string;
11
+ }
12
+ export declare const DEFAULT_SCOPE = "default";
13
+ /** "dev-key,audit-key:ro" -> keys. Trims, skips empties; a key may contain ":" only as the trailing ":ro". */
14
+ export declare function parseApiKeys(raw: string | undefined | null, scope?: string): ApiKey[];
15
+ /** Returns the matching key, or throws `unauthorized`. Compares against every key (no early exit). */
16
+ export declare function authorize(authHeader: string | null | undefined, keys: ApiKey[]): ApiKey;
17
+ /** Throws `forbidden` for a read-only key. Call before any write. */
18
+ export declare function requireWrite(key: ApiKey): void;
package/dist/auth.js CHANGED
@@ -1,13 +1,39 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
- import { InkwireError } from "./errors";
2
+ import { InkwireError } from "./errors.js";
3
+ export const DEFAULT_SCOPE = "default";
4
+ /** "dev-key,audit-key:ro" -> keys. Trims, skips empties; a key may contain ":" only as the trailing ":ro". */
5
+ export function parseApiKeys(raw, scope = DEFAULT_SCOPE) {
6
+ const out = [];
7
+ for (const part of (raw ?? "").split(",")) {
8
+ const item = part.trim();
9
+ if (!item)
10
+ continue;
11
+ const ro = item.endsWith(":ro");
12
+ const key = ro ? item.slice(0, -3).trim() : item;
13
+ if (!key)
14
+ continue;
15
+ out.push({ key, ro, scope });
16
+ }
17
+ return out;
18
+ }
3
19
  function eq(a, b) {
4
- const ab = Buffer.from(a), bb = Buffer.from(b);
20
+ const ab = Buffer.from(a);
21
+ const bb = Buffer.from(b);
5
22
  return ab.length === bb.length && timingSafeEqual(ab, bb);
6
23
  }
7
- export function authorize(authHeader, apiKeys) {
8
- const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
9
- const match = apiKeys.find((k) => eq(k, token));
24
+ /** Returns the matching key, or throws `unauthorized`. Compares against every key (no early exit). */
25
+ export function authorize(authHeader, keys) {
26
+ const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7).trim() : "";
27
+ let match;
28
+ for (const k of keys)
29
+ if (token && eq(k.key, token) && !match)
30
+ match = k;
10
31
  if (!match)
11
32
  throw new InkwireError("unauthorized", "missing or invalid API key");
12
33
  return match;
13
34
  }
35
+ /** Throws `forbidden` for a read-only key. Call before any write. */
36
+ export function requireWrite(key) {
37
+ if (key.ro)
38
+ throw new InkwireError("forbidden", "this API key is read-only");
39
+ }
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type InkwireCode = "invalid_payload" | "unauthorized" | "conflict" | "rate_limited" | "internal";
1
+ export type InkwireCode = "invalid_payload" | "unauthorized" | "forbidden" | "not_found" | "conflict" | "stale" | "too_large" | "rate_limited" | "internal";
2
2
  export declare class InkwireError extends Error {
3
3
  code: InkwireCode;
4
4
  constructor(code: InkwireCode, message: string);
package/dist/errors.js CHANGED
@@ -1,11 +1,22 @@
1
1
  const HTTP = {
2
- invalid_payload: 400, unauthorized: 401, conflict: 409, rate_limited: 429, internal: 500,
2
+ invalid_payload: 400,
3
+ unauthorized: 401,
4
+ forbidden: 403,
5
+ not_found: 404,
6
+ conflict: 409,
7
+ stale: 412,
8
+ too_large: 413,
9
+ rate_limited: 429,
10
+ internal: 500,
3
11
  };
4
12
  export class InkwireError extends Error {
5
13
  code;
6
14
  constructor(code, message) {
7
15
  super(message);
8
16
  this.code = code;
17
+ this.name = "InkwireError";
18
+ }
19
+ get httpStatus() {
20
+ return HTTP[this.code];
9
21
  }
10
- get httpStatus() { return HTTP[this.code]; }
11
22
  }
@@ -0,0 +1,33 @@
1
+ import type { StoredContent } from "./store.js";
2
+ /** The on-disk shape shared by FileStore and GitHubStore: `<kind>/<slug>.md`, YAML frontmatter + markdown. */
3
+ export declare const KIND_RE: RegExp;
4
+ /** Filenames are slugs. Anything outside this never touches a path. */
5
+ export declare const SLUG_FILE_RE: RegExp;
6
+ /** `media` is the media folder, not a kind. */
7
+ export declare const RESERVED_KINDS: Set<string>;
8
+ /** An entry's id is its path: `<kind>.<slug>` (kinds hold no dot, slugs hold none either). */
9
+ export declare const idFor: (kind: string, slug: string) => string;
10
+ export declare function parseId(id: string): {
11
+ kind: string;
12
+ slug: string;
13
+ } | null;
14
+ export type Draft = Omit<StoredContent, "id" | "key" | "etag" | "url">;
15
+ export declare function serializeEntry(e: Draft): string;
16
+ /**
17
+ * Reads a file the API wrote or a person did. Missing frontmatter fields default: title from the
18
+ * first `# ` heading, external_id null, status published, kind from the folder, dates from the file.
19
+ * Returns null when the frontmatter is not valid YAML (the entry stays hidden rather than guessed at).
20
+ */
21
+ export declare function parseEntryFile(raw: string, where: {
22
+ kind: string;
23
+ slug: string;
24
+ mtimeIso: string;
25
+ }): Draft | null;
26
+ /**
27
+ * Saves an edit into an existing file without rewriting what it did not change: every frontmatter
28
+ * key the receiver does not manage (`layout`, `heroImage`, `weight`...), comments and key order all
29
+ * survive, and a field the file spells its own way (`date`, `lastmod`, `description`, `draft`) is
30
+ * updated under that spelling. `before` is what the file parsed to, `after` what to store.
31
+ * Returns null when the file has no usable frontmatter: the caller writes a fresh one.
32
+ */
33
+ export declare function updateEntryFile(previousRaw: string, before: Draft, after: Draft): string | null;
package/dist/files.js ADDED
@@ -0,0 +1,210 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { isMap, parse as parseYaml, parseDocument, stringify as stringifyYaml } from "yaml";
3
+ import { renderMarkdown } from "./render.js";
4
+ /** The on-disk shape shared by FileStore and GitHubStore: `<kind>/<slug>.md`, YAML frontmatter + markdown. */
5
+ export const KIND_RE = /^[a-z][a-z0-9_-]{0,63}$/;
6
+ /** Filenames are slugs. Anything outside this never touches a path. */
7
+ export const SLUG_FILE_RE = /^[a-z0-9-]+$/;
8
+ /** `media` is the media folder, not a kind. */
9
+ export const RESERVED_KINDS = new Set(["media"]);
10
+ /** An entry's id is its path: `<kind>.<slug>` (kinds hold no dot, slugs hold none either). */
11
+ export const idFor = (kind, slug) => `${kind}.${slug}`;
12
+ export function parseId(id) {
13
+ const dot = id.indexOf(".");
14
+ if (dot < 1 || id.length > 400)
15
+ return null;
16
+ const kind = id.slice(0, dot);
17
+ const slug = id.slice(dot + 1);
18
+ if (!KIND_RE.test(kind) || RESERVED_KINDS.has(kind) || !SLUG_FILE_RE.test(slug))
19
+ return null;
20
+ return { kind, slug };
21
+ }
22
+ /** A date as a full ISO-8601 timestamp with an offset: date-only and zone-less values are read as UTC. */
23
+ const iso = (v) => {
24
+ if (v instanceof Date && !Number.isNaN(v.getTime()))
25
+ return v.toISOString();
26
+ if (typeof v !== "string")
27
+ return undefined;
28
+ const t = v.trim();
29
+ if (!t)
30
+ return undefined;
31
+ let full = t;
32
+ if (/^\d{4}-\d{2}-\d{2}$/.test(t))
33
+ full = `${t}T00:00:00.000Z`;
34
+ else if (/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t))
35
+ full = `${t.replace(" ", "T")}Z`;
36
+ return Number.isNaN(Date.parse(full)) ? undefined : full;
37
+ };
38
+ const str = (v) => typeof v === "number" && Number.isFinite(v) ? String(v) : typeof v === "string" && v.trim() ? v : undefined;
39
+ const httpOnly = (v) => {
40
+ const s = str(v);
41
+ return s && /^https?:\/\//.test(s) ? s : undefined;
42
+ };
43
+ export function serializeEntry(e) {
44
+ const fm = {
45
+ title: e.title,
46
+ kind: e.kind,
47
+ slug: e.slug,
48
+ external_id: e.external_id,
49
+ status: e.status,
50
+ excerpt: e.excerpt,
51
+ tags: e.tags,
52
+ categories: e.categories,
53
+ cover_image_url: e.cover_image_url,
54
+ cover_image_alt: e.cover_image_alt,
55
+ canonical_url: e.canonical_url,
56
+ seo: e.seo && Object.keys(e.seo).length ? e.seo : undefined,
57
+ author: e.author,
58
+ published_at: e.published_at,
59
+ updated_at: e.updated_at,
60
+ version: e.version,
61
+ };
62
+ for (const k of Object.keys(fm))
63
+ if (fm[k] === undefined)
64
+ delete fm[k];
65
+ return `---\n${stringifyYaml(fm, { lineWidth: 0 })}---\n\n${e.markdown}\n`;
66
+ }
67
+ const FM = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
68
+ /**
69
+ * Reads a file the API wrote or a person did. Missing frontmatter fields default: title from the
70
+ * first `# ` heading, external_id null, status published, kind from the folder, dates from the file.
71
+ * Returns null when the frontmatter is not valid YAML (the entry stays hidden rather than guessed at).
72
+ */
73
+ export function parseEntryFile(raw, where) {
74
+ let fm = {};
75
+ let body = raw.replace(/^\uFEFF/, "");
76
+ const m = FM.exec(body);
77
+ if (m) {
78
+ try {
79
+ const parsed = parseYaml(m[1]);
80
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
81
+ fm = parsed;
82
+ else if (parsed != null)
83
+ return null;
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ body = body.slice(m[0].length);
89
+ }
90
+ body = body.replace(/^\r?\n/, "").replace(/\r?\n$/, "");
91
+ const heading = /^#[ \t]+(.+?)[ \t]*#*[ \t]*$/m.exec(body)?.[1];
92
+ const title = str(fm.title) ?? (heading ? heading.trim() : where.slug.replace(/-/g, " "));
93
+ const terms = (raw) => Array.isArray(raw)
94
+ ? raw.filter((t) => typeof t === "string" && t.trim() !== "").map((t) => t.slice(0, 64))
95
+ : typeof raw === "string"
96
+ ? raw.split(",").map((t) => t.trim()).filter(Boolean).map((t) => t.slice(0, 64))
97
+ : undefined;
98
+ const tags = terms(fm.tags);
99
+ const categories = terms(fm.categories ?? fm.category);
100
+ const seoRaw = fm.seo && typeof fm.seo === "object" && !Array.isArray(fm.seo) ? fm.seo : null;
101
+ const seo = {};
102
+ if (seoRaw) {
103
+ if (str(seoRaw.title))
104
+ seo.title = str(seoRaw.title);
105
+ if (str(seoRaw.description))
106
+ seo.description = str(seoRaw.description);
107
+ if (httpOnly(seoRaw.image_url))
108
+ seo.image_url = httpOnly(seoRaw.image_url);
109
+ if (typeof seoRaw.noindex === "boolean")
110
+ seo.noindex = seoRaw.noindex;
111
+ if (str(seoRaw.og_title))
112
+ seo.og_title = str(seoRaw.og_title);
113
+ if (str(seoRaw.og_description))
114
+ seo.og_description = str(seoRaw.og_description);
115
+ if (str(seoRaw.json_ld))
116
+ seo.json_ld = str(seoRaw.json_ld);
117
+ }
118
+ const authorRaw = fm.author;
119
+ const author = typeof authorRaw === "string" && authorRaw.trim()
120
+ ? { name: authorRaw.trim() }
121
+ : authorRaw && typeof authorRaw === "object" && !Array.isArray(authorRaw)
122
+ ? {
123
+ ...(str(authorRaw.name) ? { name: str(authorRaw.name) } : {}),
124
+ ...(str(authorRaw.email) ? { email: str(authorRaw.email) } : {}),
125
+ }
126
+ : undefined;
127
+ const excerpt = str(fm.excerpt) ?? str(fm.description);
128
+ const cover = httpOnly(fm.cover_image_url);
129
+ const coverAlt = str(fm.cover_image_alt);
130
+ const canonical = httpOnly(fm.canonical_url);
131
+ return {
132
+ external_id: str(fm.external_id) ?? null,
133
+ kind: where.kind,
134
+ title: title.slice(0, 512),
135
+ slug: where.slug,
136
+ markdown: body,
137
+ html: renderMarkdown(body),
138
+ ...(excerpt ? { excerpt: excerpt.slice(0, 1024) } : {}),
139
+ ...(tags && tags.length ? { tags } : {}),
140
+ ...(categories && categories.length ? { categories } : {}),
141
+ ...(cover ? { cover_image_url: cover } : {}),
142
+ ...(coverAlt ? { cover_image_alt: coverAlt.slice(0, 1024) } : {}),
143
+ ...(canonical ? { canonical_url: canonical } : {}),
144
+ seo: Object.keys(seo).length ? seo : null,
145
+ ...(author && Object.keys(author).length ? { author } : {}),
146
+ // Hugo, Astro and Jekyll mark drafts with `draft: true` or `published: false`.
147
+ status: fm.status === "draft" || fm.draft === true || fm.published === false ? "draft" : "published",
148
+ published_at: iso(fm.published_at) ?? iso(fm.date) ?? iso(fm.pubDate) ?? where.mtimeIso,
149
+ updated_at: iso(fm.updated_at) ?? iso(fm.lastmod) ?? where.mtimeIso,
150
+ version: typeof fm.version === "number" && Number.isInteger(fm.version) && fm.version >= 1 ? fm.version : 1,
151
+ };
152
+ }
153
+ /** Key names a hand-written file may use for a field, canonical first (the order `parseEntryFile` reads them). */
154
+ const ALIASES = {
155
+ excerpt: ["excerpt", "description"],
156
+ categories: ["categories", "category"],
157
+ published_at: ["published_at", "date", "pubDate"],
158
+ updated_at: ["updated_at", "lastmod"],
159
+ };
160
+ /**
161
+ * Saves an edit into an existing file without rewriting what it did not change: every frontmatter
162
+ * key the receiver does not manage (`layout`, `heroImage`, `weight`...), comments and key order all
163
+ * survive, and a field the file spells its own way (`date`, `lastmod`, `description`, `draft`) is
164
+ * updated under that spelling. `before` is what the file parsed to, `after` what to store.
165
+ * Returns null when the file has no usable frontmatter: the caller writes a fresh one.
166
+ */
167
+ export function updateEntryFile(previousRaw, before, after) {
168
+ const m = FM.exec(previousRaw.replace(/^\uFEFF/, ""));
169
+ if (!m)
170
+ return null;
171
+ const doc = parseDocument(m[1]);
172
+ if (doc.errors.length || !isMap(doc.contents))
173
+ return null;
174
+ const changed = (k) => !isDeepStrictEqual(before[k], after[k]);
175
+ const put = (k, v, aliases = [k]) => {
176
+ if (v === undefined || v === null)
177
+ for (const a of aliases)
178
+ doc.delete(a);
179
+ else
180
+ doc.set(aliases.find((a) => doc.has(a)) ?? k, v);
181
+ };
182
+ if (changed("title"))
183
+ doc.set("title", after.title);
184
+ if (changed("external_id"))
185
+ put("external_id", after.external_id);
186
+ if (changed("status")) {
187
+ const draft = after.status === "draft";
188
+ const own = ["draft", "published", "status"].filter((k) => doc.has(k));
189
+ if (own.length === 0)
190
+ own.push("status");
191
+ for (const k of own)
192
+ doc.set(k, k === "draft" ? draft : k === "published" ? !draft : after.status);
193
+ }
194
+ for (const k of ["tags", "cover_image_url", "cover_image_alt", "canonical_url", "author", "version"]) {
195
+ if (changed(k))
196
+ put(k, after[k]);
197
+ }
198
+ for (const k of ["excerpt", "categories", "published_at", "updated_at"]) {
199
+ if (changed(k))
200
+ put(k, after[k], ALIASES[k]);
201
+ }
202
+ if (changed("seo"))
203
+ put("seo", after.seo && Object.keys(after.seo).length ? after.seo : undefined);
204
+ // kind and slug come from the path; a file that spells them out keeps them true.
205
+ if (doc.has("slug") && changed("slug"))
206
+ doc.set("slug", after.slug);
207
+ if (doc.has("kind") && changed("kind"))
208
+ doc.set("kind", after.kind);
209
+ return `---\n${doc.toString({ lineWidth: 0 }).trimEnd()}\n---\n\n${after.markdown}\n`;
210
+ }
package/dist/handle.d.ts CHANGED
@@ -1,12 +1,137 @@
1
- import type { PostStore } from "./store";
2
- export type { PostStore } from "./store";
3
- export declare function handlePost(input: {
4
- authHeader?: string;
5
- rawBody: unknown;
6
- apiKeys: string[];
7
- store: PostStore;
8
- }): Promise<{
1
+ import { type ApiKey } from "./auth.js";
2
+ import type { ContentStore } from "./store.js";
3
+ export declare const INKWIRE_VERSION = "1";
4
+ export declare const MAX_PAGE = 100;
5
+ export declare const DEFAULT_PAGE = 20;
6
+ export interface FetchedMedia {
7
+ bytes: Buffer | Uint8Array;
8
+ contentType?: string;
9
+ filename?: string;
10
+ }
11
+ export interface InkwireConfig {
12
+ site: {
13
+ name: string;
14
+ url: string;
15
+ description?: string;
16
+ language?: string;
17
+ };
18
+ /** The kinds this receiver holds. */
19
+ kinds: string[];
20
+ limits?: {
21
+ markdown_bytes?: number;
22
+ media_bytes?: number;
23
+ };
24
+ /** What discovery advertises; derived from the store and this config when omitted. `upsert` is always added. */
25
+ features?: string[];
26
+ /**
27
+ * True when the site holds a `published` entry back until its `published_at` (it renders future-dated
28
+ * entries as not yet public). Advertises `schedule`; leave it off if the site would show them at once.
29
+ */
30
+ schedule?: boolean;
31
+ /**
32
+ * Fetches a URL for `POST /api/media` `{url}`. MUST be SSRF-guarded by whoever supplies it (public
33
+ * http(s) hosts only, redirects re-checked): the core only checks the URL is http(s).
34
+ */
35
+ fetchMedia?: (url: string) => Promise<FetchedMedia>;
36
+ }
37
+ export interface HandlerResult {
9
38
  status: number;
10
- body: object;
11
39
  headers: Record<string, string>;
12
- }>;
40
+ body: unknown;
41
+ }
42
+ export interface UpsertArgs {
43
+ authHeader: string | null | undefined;
44
+ rawBody: string | Buffer;
45
+ keys: ApiKey[];
46
+ store: ContentStore;
47
+ config: InkwireConfig;
48
+ }
49
+ export declare function handleUpsert({ authHeader, rawBody, keys, store, config }: UpsertArgs): Promise<HandlerResult>;
50
+ export interface ListArgs {
51
+ authHeader: string | null | undefined;
52
+ query: URLSearchParams;
53
+ keys: ApiKey[];
54
+ store: ContentStore;
55
+ config?: InkwireConfig;
56
+ }
57
+ export declare function handleList({ authHeader, query, keys, store }: ListArgs): Promise<HandlerResult>;
58
+ export interface GetArgs {
59
+ authHeader: string | null | undefined;
60
+ id: string;
61
+ keys: ApiKey[];
62
+ store: ContentStore;
63
+ }
64
+ export declare function handleGet({ authHeader, id, keys, store }: GetArgs): Promise<HandlerResult>;
65
+ export interface PatchArgs {
66
+ authHeader: string | null | undefined;
67
+ id: string;
68
+ rawBody: string | Buffer;
69
+ ifMatchHeader?: string | null;
70
+ keys: ApiKey[];
71
+ store: ContentStore;
72
+ config: InkwireConfig;
73
+ }
74
+ export declare function handlePatch({ authHeader, id, rawBody, ifMatchHeader, keys, store, config }: PatchArgs): Promise<HandlerResult>;
75
+ export interface DeleteArgs {
76
+ authHeader: string | null | undefined;
77
+ id: string;
78
+ ifMatchHeader?: string | null;
79
+ keys: ApiKey[];
80
+ store: ContentStore;
81
+ }
82
+ export declare function handleDelete({ authHeader, id, ifMatchHeader, keys, store }: DeleteArgs): Promise<HandlerResult>;
83
+ export interface MediaArgs {
84
+ authHeader: string | null | undefined;
85
+ contentType: string | null | undefined;
86
+ rawBody: string | Buffer | Uint8Array;
87
+ keys: ApiKey[];
88
+ config: InkwireConfig;
89
+ store: ContentStore;
90
+ }
91
+ export declare function handleMedia({ authHeader, contentType, rawBody, keys, config, store }: MediaArgs): Promise<HandlerResult>;
92
+ export interface MediaListArgs {
93
+ authHeader: string | null | undefined;
94
+ query: URLSearchParams;
95
+ keys: ApiKey[];
96
+ store: ContentStore;
97
+ }
98
+ export declare function handleMediaList({ authHeader, query, keys, store }: MediaListArgs): Promise<HandlerResult>;
99
+ export interface MediaUpdateArgs {
100
+ authHeader: string | null | undefined;
101
+ id: string;
102
+ rawBody: string | Buffer;
103
+ keys: ApiKey[];
104
+ store: ContentStore;
105
+ }
106
+ export declare function handleMediaUpdate({ authHeader, id, rawBody, keys, store }: MediaUpdateArgs): Promise<HandlerResult>;
107
+ export interface TermsArgs {
108
+ authHeader: string | null | undefined;
109
+ query: URLSearchParams;
110
+ keys: ApiKey[];
111
+ store: ContentStore;
112
+ }
113
+ export declare function handleTerms({ authHeader, query, keys, store }: TermsArgs): Promise<HandlerResult>;
114
+ export declare function discoveryBody(config: InkwireConfig, store?: ContentStore): {
115
+ inkwire: number;
116
+ site: {
117
+ name: string;
118
+ url: string;
119
+ description?: string;
120
+ language?: string;
121
+ };
122
+ features: string[];
123
+ kinds: string[];
124
+ limits: {
125
+ markdown_bytes: number;
126
+ media_bytes: number;
127
+ };
128
+ };
129
+ export interface DiscoveryArgs {
130
+ authHeader: string | null | undefined;
131
+ keys: ApiKey[];
132
+ config: InkwireConfig;
133
+ /** Lets discovery advertise the media features the store really has. */
134
+ store?: ContentStore;
135
+ }
136
+ /** The authenticated discovery response. Adapters may also call `discoveryBody` directly. */
137
+ export declare function handleDiscovery({ authHeader, keys, config, store }: DiscoveryArgs): Promise<HandlerResult>;