feat(publish): illustrations travel inline (#34)
CI / ci (push) Canceled after 0s

A piece's assets/ ink-sketch images publish with it: Send as Draft
first uploads every referenced image to Micro.blog's media endpoint
(q=config discovery, one multipart file POST per FILE — duplicate
refs share an upload), then each ![alt](assets/…) ref REWRITES IN
PLACE with its uploaded URL in the wire content. The image renders
exactly where the writer placed it and the alt rides the markdown;
the piece on disk never changes.

The first shape attached uploads as a Micropub photo property with
mp-photo-alt — live dogfood (2026-11-01) showed the theme renders
properties at the bottom of the post, losing position. No property
ships at all now; inline refs are the only transport, which also
makes the parsed body ref the only way an image ships — the alt
floor at the illustration rail is therefore the only gate a photo
needs (G12: a whitespace-empty alt refuses naming the file before
anything touches the wire; the mentor is never consulted).

Pre-flight gates every payload: the endpoint's exact formats
(PNG/JPEG/GIF/WebP/SVG), path containment resolved through symlinks
(a planted link never uploads outside-file bytes under the writer's
token), all-or-nothing uploads. A URL carrying markdown-active
characters rides the angle form ![alt](<url>) — a plain-paren
destination would close at the first ) and smuggle a live link into
the published post; the frontmatter trust gate does not cover
markdown's grammar.

Finish-audit (three reviewers) drove the angle form, the symlink
containment, the per-file upload dedup, and four pins; all four
behavior guards flip-verified in one batch cycle. Suite 546 passed /
0 failed; swiftformat + swiftlint clean. Ingest UX (drop image onto
the editor) is #141, blocked by this issue.
This commit is contained in:
AlexKucera committed 2026-11-01 21:52:58 +01:00
1 parent 414f1392ef
commit 695ec27e11
10 files changed
+840 -19

No files matched your search

+106 -5
View File
@@ -8,6 +8,10 @@
// auth — no OAuth in v1; the token lives in the Keychain, entered
// once. Frontmatter `category:` is permitted but inert (v1 never
// sends it — the request carries name + content only).
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -56,14 +60,19 @@ nonisolated enum Micropub {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped). category: never sent in v1.
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
// illustration refs, which REWRITE to their uploaded URLs on
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
],
] as [String: Any],
], options: [.sortedKeys])
return request
}
@@ -85,7 +94,8 @@ nonisolated enum Micropub {
// MARK: The two steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content.
/// entry's name; the markdown body is the content; #34's uploaded
/// illustrations already rewrote their refs in the body.
static func sendDraft(
title: String,
body: String,
@@ -156,7 +166,9 @@ nonisolated enum Micropub {
return true
}
private static func decodeFailure(status: Int, body: Data) -> Outcome {
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
static func decodeFailure(status: Int, body: Data) -> Outcome {
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)"
if status == 401 || status == 403 {
@@ -263,9 +275,21 @@ extension PostsModel {
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
// #34 (S6.2): illustrations travel with it (the rail below
// owns the floor, the uploads, and the REWRITTEN wire body —
// G12: the mentor is never consulted about images).
var wireBody = body
if !Micropub.illustrations(in: body).isEmpty {
switch await uploadIllustrations(dir: dir, body: body, token: token, transport: transport) {
case let .ready(rewritten):
wireBody = rewritten
case let .blocked(outcome):
return outcome
}
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
body: body,
body: wireBody,
token: token,
transport: transport,
)
@@ -280,4 +304,81 @@ extension PostsModel {
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
/// and every send routes through here). Then one upload per PNG
/// (q=config → multipart → Location) and `ready`'s body is the
/// wire content with each ref REWRITTEN to its uploaded URL — the
/// image renders exactly where the writer placed it, alt travels
/// in the markdown (the piece on disk never changes). Style
/// judgment stays with the author.
private enum IllustrationRail {
case ready(String) // the rewritten wire body
case blocked(Micropub.Outcome)
}
private func uploadIllustrations(
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
let illustrations = Micropub.illustrations(in: body)
if let bare = illustrations.first(where: { $0.alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) {
return .blocked(.refused("\(bare.destination) has no alt text — a photo never ships without it."))
}
// Pre-flight: every file in hand (and inside this piece — a
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
guard let mimeType = Micropub.mimeType(forDestination: illustration.destination) else {
return .blocked(.refused("\(illustration.destination) is not a PNG/JPEG/GIF/WebP/SVG — Micro.blog can't host it."))
}
let fileURL = dir.appendingPathComponent(illustration.destination)
guard fileURL.resolvingSymlinksInPath().path.hasPrefix(root),
let data = try? Data(contentsOf: fileURL)
else {
return .blocked(.refused("Couldn't read \(illustration.destination) from this piece's assets."))
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
mediaEndpoint = named
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
mimeType: payload.mimeType,
data: payload.data,
token: token,
transport: transport,
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
}
}
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
}
}