import Foundation import RastrilloApple /// Delete… (spec 2026-11-22 §1): POST /d/{sqid}/delete, and what its answer /// means. The rule also covers version skew and lost answers: /// - A 2xx JSON `{"ok":true}` is deleted (the server from S2b on). /// - Anything else, including an older or lagged server's 303 to the list /// (sent after the delete committed) and a 404 (a non-owner gets 404 with /// nothing deleted, and so does a retry after a lost answer), is checked /// with a GET of /d/{sqid} as JSON: 404 is deleted, 200 is not (nothing /// is removed), and anything else is not known, so nothing is removed and /// the person may try again. /// - The request never reaching the server is not known either. /// /// Only `.deleted` lets the caller drop the document's outbox lane and /// replica. enum DocsDeletion { enum Outcome: Equatable, Sendable { case deleted /// The server still has the document: the delete did not happen. case stillThere /// Neither answer said: nothing is removed, and it may be tried again. case unknown } static func run(sqid: String, transport: NativeTransport) async -> Outcome { let path = "/d/\(sqid)" do { let reply = try await transport.responseDetails(path + "/delete", method: "POST", body: Data(), contentType: "application/x-www-form-urlencoded", maxBytes: 64 * 1024) if (200..<300).contains(reply.status), isOK(reply) { return .deleted } } catch { // Offline, or the answer was lost: the GET below may still say. } do { let check = try await transport.responseDetails(path, maxBytes: 1024 * 1024) switch check.status { // A 404 here is read as deleted, though not every 404 is one: a // request that lands on a server mid-deploy, or after this // person lost their membership, answers 404 for a document that // still exists. That is safe to act on. Delete… is refused with // anything unsent, so the dropped outbox lane is empty and no // change is lost; the replica and metadata dropped with it are a // cache. If the document does still exist, the next list reload // shows it again, and opening it downloads it afresh. case 404: return .deleted case 200..<300: return .stillThere default: return .unknown } } catch { return .unknown } } /// `{"ok":true}`, and nothing a redirect target or a page could be. private static func isOK(_ reply: NativeResponse) -> Bool { guard reply.header("Content-Type")?.lowercased().hasPrefix("application/json") != false, let object = try? JSONSerialization.jsonObject(with: reply.data) as? [String: Any] else { return false } return object["ok"] as? Bool == true } }