SPB Git

Repository Public

FakeBackend.swift 61.5 KB 1,186 lines swift

1// SP Notes Core2// File: Sources/SPNotesTestSupport/FakeBackend.swift3// Description: In-memory fake of the notes backend for the sync tests, written from the route handlers of the real server4//              (branch native-sync): session cookie and Origin checks, idempotency keys, the change feed with one revision5//              sequence, pages, tags, conflict resolution, attachments (multipart), tasks, inbox triage — plus fault6//              injection (offline, scripted failures, lost acknowledgements, delays, held requests). Served through a7//              URLProtocol; one instance per test, routed by host name so that tests can run in parallel.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213// MARK: - Fault injection1415/// Blocks a request inside the fake until the test opens the gate (to act while a request is in flight).16public final class Gate: @unchecked Sendable {17    public init() {}18    let entered = DispatchSemaphore(value: 0)19    let released = DispatchSemaphore(value: 0)2021    /// Suspends until a request is being held.22    public func reached() async {23        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in24            DispatchQueue.global().async {25                self.entered.wait()26                continuation.resume()27            }28        }29    }3031    public func open() { released.signal() }3233    fileprivate func hold() {34        entered.signal()35        released.wait()36    }37}3839public enum Fault: Sendable {40    /// The request is not applied; the server answers this status (`{error, code}`).41    case status(Int, code: String? = nil)42    /// The request is not applied; the connection fails.43    case network(URLError.Code)44    /// The request IS applied, then the answer is lost (the client sees a broken connection).45    case dropResponse46    /// The request is applied after this delay.47    case delay(TimeInterval)48    /// The request waits for the gate, then is applied.49    case hold(Gate)50    /// The answer is replaced by this raw body (a misbehaving server); the request is not applied.51    case raw(status: Int, body: String)52}5354// MARK: - Rows5556struct FakePage: Sendable {57    var id: String58    var parentId: String?59    var databaseId: String?60    var type = "page"61    var section = "notes"62    var title = "Untitled"63    var icon: String?64    var cover: String?65    /// JSON bytes (key order is whatever JSONSerialization produced: never rely on it, like jsonb).66    var content: Data67    var properties: Data68    var position: Double = 169    var pinned = false70    var archived = false71    var version = 172    var createdAt: Date73    var updatedAt: Date74    var lastOpenedAt: Date?75    var deletedAt: Date?76    var inboxAt: Date?77    var captureKind: String?78    var rev: Int64 = 079    var tags: [String] = []8081    /// Every text node of the document, joined by a line feed.82    var text: String { FakeBackend.plainText(content) }83}8485struct FakeAttachment: Sendable {86    var id: String87    var pageId: String?88    var filename: String89    var mime: String90    var bytes: Data91    var createdAt: Date92    var deletedAt: Date?93    var rev: Int64 = 094}9596struct FakeVersion: Sendable {97    var version: Int98    var title: String99    var content: Data100    var properties: Data101    var reason: String102    var text: String { FakeBackend.plainText(content) }103}104105struct FakeTask: Sendable {106    var id: String107    var title: String108    var status = "todo"109    var priority = "medium"110    var dueAt: Date?111    var completedAt: Date?112    var pageId: String?113    var createdAt: Date114    var updatedAt: Date115    var deletedAt: Date?116    var blockId: String?117    var project: String?118    var rev: Int64 = 0119}120121/// A canvas row (3.0): one per page of type `canvas`, same id as the page.122struct FakeCanvas: Sendable {123    var pageId: String124    var data: Data125    var version = 1126    var createdAt: Date127    var updatedAt: Date128    var rev: Int64 = 0129}130131/// A row of one of the other entity kinds of the 3.0 feed (database, database_row, edge, reference, concept…): its132/// JSON object is opaque to the fake.133struct FakeEntity: Sendable {134    var kind: String135    var id: String136    var json: Data137    var deletedAt: Date?138    var rev: Int64 = 0139}140141struct FakeTombstone: Sendable {142    var id: String143    var kind: String144    var rev: Int64145    var deletedAt: Date146}147148public struct LoggedRequest: Sendable {149    public var device: String150    public var method: String151    public var path: String152    public var query: String153    public var status: Int        // 0 = the connection failed154    public var replay: Bool155    public var idempotencyKey: String?156}157158// MARK: - The fake159160public final class FakeBackend: @unchecked Sendable {161    /// Everything a database restore brings back.162    struct Snapshot: Sendable {163        fileprivate var pages: [String: FakePage]164        fileprivate var attachments: [String: FakeAttachment]165        fileprivate var tombstones: [String: FakeTombstone]166        fileprivate var versions: [String: [FakeVersion]]167        fileprivate var tasks: [String: FakeTask]168        fileprivate var tagNames: Set<String>169        fileprivate var rev: Int64170        fileprivate var canvases: [String: FakeCanvas] = [:]171        fileprivate var entities: [String: FakeEntity] = [:]172    }173174    struct Rule {175        var fault: Fault176        var method: String?177        var pattern: NSRegularExpression178        var device: String?179        var remaining: Int180    }181182    struct IdempotencyRecord {183        var method: String184        var path: String185        var status: Int186        var body: Data187    }188189    struct Reply {190        var status = 200191        var headers: [String: String] = ["Content-Type": "application/json"]192        var body = Data()193        var error: URLError.Code?194    }195196    struct HTTPFailure: Error, @unchecked Sendable {197        var status: Int198        var message: String199        var code: String?200        var extra: [String: Any] = [:]201    }202203    public let host: String204    let workspaceId = UUID().uuidString.lowercased()205    public var baseURL: URL { URL(string: "https://\(host)")! }206    public var origin: String { "https://\(host)" }207208    let lock = NSRecursiveLock()209    var pages: [String: FakePage] = [:]210    var attachments: [String: FakeAttachment] = [:]211    var tombstones: [String: FakeTombstone] = [:]212    var versions: [String: [FakeVersion]] = [:]213    var tasks: [String: FakeTask] = [:]214    var canvases: [String: FakeCanvas] = [:]215    /// Other entity kinds, keyed by "<kind>:<id>".216    var entities: [String: FakeEntity] = [:]217    /// API level served: 3 = Next Generation (meta, entity feed, tasks with client ids, canvases); 2 = a 2.x server218    /// (no `/api/meta`, `kinds` ignored, no 3.0 route).219    var apiLevel = FakeBackend.defaultAPILevel220    var customRoutes: [CustomRoute] = []221    var tagNames = Set<String>()222    var rev: Int64 = 0223    var tokens = Set<String>()224    var freshTokens = Set<String>()225    var idempotency: [String: IdempotencyRecord] = [:]226    var rules: [Rule] = []227    var offlineDevices = Set<String>()228    var offlineAll = false229    var log: [LoggedRequest] = []230    var lastMillis: Int64 = 0231    var purgeNeedsFresh = true232233    // MARK: registry (host → fake)234235    private static let registryLock = NSLock()236    nonisolated(unsafe) private static var registry: [String: FakeBackend] = [:]237238    fileprivate static func backend(forHost host: String?) -> FakeBackend? {239        guard let host else { return nil }240        return registryLock.withLock { registry[host] }241    }242243    public init(apiLevel: Int? = nil) {244        if let apiLevel { self.apiLevel = apiLevel }245        host = "fake-\(UUID().uuidString.lowercased().prefix(12)).test"246        Self.registryLock.withLock { Self.registry[host] = self }247    }248249    public func shutdown() {250        _ = Self.registryLock.withLock { Self.registry.removeValue(forKey: host) }251    }252253    /// A session configuration whose requests are answered by the fake registered for the request's host.254    public static func sessionConfiguration() -> URLSessionConfiguration {255        let configuration = URLSessionConfiguration.ephemeral256        configuration.protocolClasses = [FakeBackendProtocol.self]257        return configuration258    }259260    // MARK: sessions261262    public func issueToken(fresh: Bool = false) -> String {263        let token = "tok" + UUID().uuidString.replacingOccurrences(of: "-", with: "") + "12345678"264        lock.withLock {265            tokens.insert(token)266            if fresh { freshTokens.insert(token) }267        }268        return token269    }270271    public func revoke(token: String) { lock.withLock { _ = tokens.remove(token); _ = freshTokens.remove(token) } }272    public func revokeAllTokens() { lock.withLock { tokens.removeAll(); freshTokens.removeAll() } }273    public func setFresh(_ fresh: Bool, token: String) { lock.withLock { if fresh { freshTokens.insert(token) } else { freshTokens.remove(token) } } }274    /// Marks every session as freshly verified (or not).275    public func setAllFresh(_ fresh: Bool) { lock.withLock { freshTokens = fresh ? tokens : [] } }276    public func setPurgeNeedsFresh(_ needed: Bool) { lock.withLock { purgeNeedsFresh = needed } }277278    // MARK: faults279280    public func setOffline(_ offline: Bool, device: String? = nil) {281        lock.withLock {282            if let device { if offline { offlineDevices.insert(device) } else { offlineDevices.remove(device) } } else { offlineAll = offline }283        }284    }285286    /// The next `count` requests whose method and "path?query" match get the fault. `pattern` is a regular expression.287    public func inject(_ fault: Fault, method: String? = nil, path pattern: String, count: Int = 1, device: String? = nil) {288        let regex = try! NSRegularExpression(pattern: pattern)289        lock.withLock { rules.append(Rule(fault: fault, method: method, pattern: regex, device: device, remaining: count)) }290    }291292    public func clearFaults() { lock.withLock { rules.removeAll() } }293294    // MARK: inspection295296    public var requests: [LoggedRequest] { lock.withLock { log } }297    public func clearLog() { lock.withLock { log.removeAll() } }298    public func count(_ method: String, _ pattern: String, device: String? = nil) -> Int {299        let regex = try! NSRegularExpression(pattern: pattern)300        return requests.filter { $0.method == method && (device == nil || $0.device == device) && Self.matches(regex, $0.path + ($0.query.isEmpty ? "" : "?" + $0.query)) }.count301    }302303    func page(_ id: String) -> FakePage? { lock.withLock { pages[id] } }304    var allPages: [FakePage] { lock.withLock { pages.values.sorted { $0.rev < $1.rev } } }305    func attachment(_ id: String) -> FakeAttachment? { lock.withLock { attachments[id] } }306    var allAttachments: [FakeAttachment] { lock.withLock { Array(attachments.values) } }307    func history(_ id: String) -> [FakeVersion] { lock.withLock { versions[id] ?? [] } }308    var allTasks: [FakeTask] { lock.withLock { tasks.values.filter { $0.deletedAt == nil }.sorted { $0.createdAt < $1.createdAt } } }309    func task(_ id: String) -> FakeTask? { lock.withLock { tasks[id] } }310    var allTombstones: [FakeTombstone] { lock.withLock { Array(tombstones.values) } }311    public var head: Int64 { lock.withLock { computeHead() } }312313    // MARK: the web application (changes made by "another session" directly on the server)314315    @discardableResult316    public func webCreatePage(id: String? = nil, title: String, content: Data? = nil, parentId: String? = nil, section: String = "notes", properties: String = "{}",317                       inbox: Bool = false, databaseId: String? = nil, tags: [String] = []) -> String {318        lock.withLock {319            var page = makePage(id: id, title: title, parentId: parentId, section: section, type: "page", content: content.flatMap(Self.parse), icon: nil,320                                properties: (Self.parse(Data(properties.utf8)) as? [String: Any]) ?? [:])321            page.databaseId = databaseId322            if inbox { page.inboxAt = now(); page.captureKind = "note" }323            store(&page)324            if !tags.isEmpty { applyTags(page.id, tags) }325            return page.id326        }327    }328329    /// An edit from another session: versioned fields, applied on top of whatever is there (no base version).330    public func webEdit(_ id: String, title: String? = nil, content: Data? = nil, properties: String? = nil) {331        lock.withLock {332            var patch: [String: Any] = [:]333            if let title { patch["title"] = title }334            if let content, let parsed = Self.parse(content) { patch["content"] = parsed }335            if let properties, let parsed = Self.parse(Data(properties.utf8)) { patch["properties"] = parsed }336            _ = try? updatePage(id, patch: patch, baseVersion: nil, reason: nil)337        }338    }339340    public func webPatchMeta(_ id: String, _ patch: [String: Any]) { lock.withLock { _ = try? updatePage(id, patch: patch, baseVersion: nil, reason: nil) } }341    public func webTrash(_ id: String) { lock.withLock { _ = softDelete(id) } }342    public func webRestore(_ id: String) { lock.withLock { restore(id) } }343    public func webPurge(_ id: String) { lock.withLock { purge(id) } }344    public func webSetTags(_ id: String, _ tags: [String]) { lock.withLock { _ = applyTags(id, tags) } }345    public func webDeleteAttachment(_ id: String) { lock.withLock { softDeleteAttachment(id) } }346347    @discardableResult348    public func webAddAttachment(id: String? = nil, pageId: String?, filename: String, mime: String, bytes: Data) -> String {349        lock.withLock {350            var row = FakeAttachment(id: id ?? UUID().uuidString.lowercased(), pageId: pageId, filename: filename, mime: mime, bytes: bytes, createdAt: now())351            row.rev = nextRev()352            attachments[row.id] = row353            return row.id354        }355    }356357    // MARK: database restore358359    func snapshot() -> Snapshot {360        lock.withLock { Snapshot(pages: pages, attachments: attachments, tombstones: tombstones, versions: versions, tasks: tasks, tagNames: tagNames, rev: rev, canvases: canvases, entities: entities) }361    }362363    /// Puts the database back as it was (the revision sequence goes back too: the cursors of the clients are now ahead).364    func restore(_ snapshot: Snapshot) {365        lock.withLock {366            pages = snapshot.pages; attachments = snapshot.attachments; tombstones = snapshot.tombstones; versions = snapshot.versions367            tasks = snapshot.tasks; tagNames = snapshot.tagNames; rev = snapshot.rev368            canvases = snapshot.canvases; entities = snapshot.entities369        }370    }371372    // MARK: - Request entry point373374    fileprivate func respond(method: String, url: URL, headers: [String: String], body: Data) -> Reply {375        func header(_ name: String) -> String? { headers.first { $0.key.lowercased() == name.lowercased() }?.value }376        let device = header("User-Agent") ?? "-"377        let path = url.path378        let query = url.query ?? ""379        let target = path + (query.isEmpty ? "" : "?" + query)380        let key = header("Idempotency-Key")381382        // 1. connectivity and scripted faults383        let (offline, fault): (Bool, Fault?) = lock.withLock {384            if offlineAll || offlineDevices.contains(device) { return (true, nil) }385            for index in rules.indices where rules[index].remaining > 0 {386                let rule = rules[index]387                if let m = rule.method, m != method { continue }388                if let d = rule.device, d != device { continue }389                guard Self.matches(rule.pattern, target) else { continue }390                rules[index].remaining -= 1391                return (false, rule.fault)392            }393            return (false, nil)394        }395        func record(_ status: Int, replay: Bool = false) {396            lock.withLock { log.append(LoggedRequest(device: device, method: method, path: path, query: query, status: status, replay: replay, idempotencyKey: key)) }397        }398        if offline { record(0); return Reply(error: .notConnectedToInternet) }399        var dropAnswer = false400        switch fault {401        case .status(let status, let code)?:402            record(status)403            var object: [String: Any] = ["error": "Injected failure \(status)"]404            if let code { object["code"] = code }405            return Reply(status: status, body: Self.serialize(object))406        case .network(let code)?:407            record(0)408            return Reply(error: code)409        case .raw(let status, let text)?:410            record(status)411            return Reply(status: status, body: Data(text.utf8))412        case .delay(let seconds)?: Thread.sleep(forTimeInterval: seconds)413        case .hold(let gate)?: gate.hold()414        case .dropResponse?: dropAnswer = true415        case nil: break416        }417418        // 2. the request itself, as one "transaction"419        var replay = false420        let reply: Reply = lock.withLock {421            do {422                return try handle(method: method, path: path, url: url, header: header, body: body, replay: &replay)423            } catch let failure as HTTPFailure {424                var object: [String: Any] = ["error": failure.message]425                // 3.0 (integration hardening): every error body has a `code`, with a default by status426                if let code = failure.code { object["code"] = code }427                else if apiLevel >= 3, let fallback = [400: "bad_request", 404: "not_found", 409: "invalid_state", 413: "too_large", 502: "upstream_error", 500: "internal"][failure.status] { object["code"] = fallback }428                for (k, v) in failure.extra { object[k] = v }429                return Reply(status: failure.status, body: Self.serialize(object))430            } catch {431                return Reply(status: 500, body: Self.serialize(["error": "Internal error"]))432            }433        }434        if dropAnswer { record(0); return Reply(error: .networkConnectionLost) }435        record(reply.status, replay: replay)436        return reply437    }438439    func handle(method: String, path: String, url: URL, header: (String) -> String?, body: Data, replay: inout Bool) throws -> Reply {440        let mutating = ["POST", "PATCH", "PUT", "DELETE"].contains(method)441        if method == "GET", path == "/api/health" { return json(["ok": true, "db": true, "version": "fake"]) }442        // Same order as the server: same-origin check, then the session.443        if mutating, header("Origin") != origin { throw HTTPFailure(status: 403, message: "Cross-origin request refused", code: "csrf") }444        let cookie = header("Cookie") ?? ""445        let token = cookie.components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) }446            .first { $0.hasPrefix("__Host-note_session=") }.map { String($0.dropFirst("__Host-note_session=".count)) }447        guard let token, tokens.contains(token) else { throw HTTPFailure(status: 401, message: "Sign-in required", code: "unauthenticated") }448        let fresh = freshTokens.contains(token)449450        guard mutating, let key = header("Idempotency-Key") else {451            return try route(method: method, path: path, url: url, header: header, body: body, fresh: fresh)452        }453        guard key.range(of: "^[A-Za-z0-9_-]{8,100}$", options: .regularExpression) != nil else {454            throw HTTPFailure(status: 400, message: "Invalid Idempotency-Key", code: "bad_idempotency_key")455        }456        if let stored = idempotency[key] {457            // The key is matched on method and path only (not on the body), exactly like the server.458            guard stored.method == method, stored.path == path else {459                throw HTTPFailure(status: 422, message: "Idempotency-Key was used for a different request", code: "idempotency_mismatch")460            }461            replay = true462            return Reply(status: stored.status, headers: ["Content-Type": "application/json", "idempotent-replay": "true"], body: stored.body)463        }464        let reply = try route(method: method, path: path, url: url, header: header, body: body, fresh: fresh)465        if (200..<300).contains(reply.status), (reply.headers["Content-Type"] ?? "").contains("application/json") {466            idempotency[key] = IdempotencyRecord(method: method, path: path, status: reply.status, body: reply.body)467        }468        return reply469    }470471    // MARK: - Routes472473    func route(method: String, path: String, url: URL, header: (String) -> String?, body: Data, fresh: Bool) throws -> Reply {474        let parts = path.split(separator: "/").map(String.init)475        let query = Dictionary((URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []).map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })476        func bodyObject() throws -> [String: Any] {477            guard let object = Self.parse(body) as? [String: Any] else { throw HTTPFailure(status: 400, message: "Invalid JSON body") }478            return object479        }480        func uuid(_ text: String) throws -> String {481            guard Self.isUUID(text) else { throw HTTPFailure(status: 400, message: "Invalid id") }482            return text.lowercased()483        }484        guard parts.first == "api", parts.count >= 2 else { throw HTTPFailure(status: 404, message: "Not found") }485        if let reply = try customReply(method: method, path: path, query: query, body: body) { return reply }486        if let reply = try nextRoute(method: method, parts: parts, query: query, body: body) { return reply }487488        switch (method, parts[1], parts.count) {489        case ("GET", "sync", 2):490            return try feed(query: query)491492        case ("POST", "pages", 2):493            let b = try bodyObject()494            if let title = b["title"] as? String, title.count > 500 { throw HTTPFailure(status: 400, message: "Validation: title too long") }495            if let section = b["section"] as? String, !["notes", "documents", "databases", "projects", "research"].contains(section) { throw HTTPFailure(status: 400, message: "Validation: section") }496            if let content = b["content"], !(content is NSNull) { try assertDoc(content) }497            if let properties = b["properties"], !(properties is [String: Any]) { throw HTTPFailure(status: 400, message: "Validation: properties") }498            // The page types a 2.x server knows; `canvas` comes with 3.0.499            if let type = b["type"] as? String, !(["page", "database", "research"] + (apiLevel >= 3 ? ["canvas"] : [])).contains(type) { throw HTTPFailure(status: 400, message: "Validation: type Invalid option") }500            var given: String?501            if let id = b["id"] as? String {502                given = try uuid(id)503                if let existing = pages[given!] {504                    return json(pageRow(existing, full: true), status: 200, headers: ["x-existing": "1"])505                }506            }507            var parent = b["parentId"] as? String508            if let p = parent, pages[p] == nil { parent = nil }   // parent purged meanwhile: kept, at the top level509            var page = makePage(id: given, title: b["title"] as? String, parentId: parent, section: b["section"] as? String ?? "notes", type: b["type"] as? String ?? "page",510                                content: b["content"].flatMap { $0 is NSNull ? nil : $0 }, icon: b["icon"] as? String, properties: b["properties"] as? [String: Any] ?? [:])511            if apiLevel >= 3 {   // 3.0: a page can be created as a capture (`inboxAt` date or `inbox: true`, `captureKind`)512                if let at = (b["inboxAt"] as? String).flatMap({ Self.parseISO($0) }) { page.inboxAt = at } else if b["inbox"] as? Bool == true { page.inboxAt = now() }513                if let kind = b["captureKind"] as? String, !kind.isEmpty, kind.count <= 32 { page.captureKind = kind }514            }515            store(&page)516            if apiLevel >= 3, page.type == "canvas" { createCanvas(pageId: page.id) }517            return json(pageRow(page, full: true), status: 201)518519        case ("GET", "pages", 3):520            let id = try uuid(parts[2])521            guard let page = pages[id] else { throw HTTPFailure(status: 404, message: "Page not found") }522            if query["head"] == "1" { return json(["id": page.id, "version": page.version, "updatedAt": iso(page.updatedAt), "deletedAt": page.deletedAt.map(iso) ?? NSNull()]) }523            var row = pageRow(page, full: true)524            row["breadcrumb"] = [Any]()525            row["backlinks"] = [Any]()526            return json(row)527528        case ("PATCH", "pages", 3):529            let id = try uuid(parts[2])530            var b = try bodyObject()531            let reason = b.removeValue(forKey: "versionReason") as? String532            let base = (b.removeValue(forKey: "baseVersion") as? NSNumber)?.intValue533            if let content = b["content"] { try assertDoc(content) }534            if let properties = b["properties"], !(properties is [String: Any]) { throw HTTPFailure(status: 400, message: "Validation: properties") }535            let page = try updatePage(id, patch: b, baseVersion: base, reason: reason)536            return json(["id": page.id, "version": page.version, "updatedAt": iso(page.updatedAt), "title": page.title, "wordCount": Self.wordCount(page.content)])537538        case ("DELETE", "pages", 3):539            let id = try uuid(parts[2])540            if query["purge"] == "1" {541                if purgeNeedsFresh, !fresh { throw HTTPFailure(status: 403, message: "Confirm with your passkey to continue", code: "reauth_required") }542                purge(id)543                return json(["ok": true])544            }545            return json(["ok": true, "trashed": softDelete(id)])546547        case ("POST", "pages", 3):548            let id = try uuid(parts[2])549            if query["action"] == "restore" { restore(id); return json(["ok": true]) }550            if query["action"] == "duplicate" {551                guard let page = pages[id], page.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") }552                var copy = makePage(id: nil, title: page.title + " (copy)", parentId: page.parentId, section: page.section, type: page.type, content: Self.parse(page.content),553                                    icon: page.icon, properties: Self.parse(page.properties) as? [String: Any] ?? [:])554                store(&copy)555                return json(pageRow(copy, full: true))556            }557            throw HTTPFailure(status: 400, message: "Unknown action")558559        case ("POST", "pages", 4) where parts[3] == "resolve":560            return try resolve(id: try uuid(parts[2]), body: try bodyObject())561562        case ("GET", "pages", 4) where parts[3] == "tags":563            guard let page = pages[try uuid(parts[2])] else { throw HTTPFailure(status: 404, message: "Page not found") }564            return json(page.tags.sorted())565566        case ("PUT", "pages", 4) where parts[3] == "tags":567            let id = try uuid(parts[2])568            guard let names = try bodyObject()["tags"] as? [String], names.count <= 20, names.allSatisfy({ $0.count <= 60 }) else { throw HTTPFailure(status: 400, message: "Validation: tags") }569            guard let page = pages[id], page.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") }570            return json(applyTags(id, names))571572        case ("GET", "pages", 4) where parts[3] == "versions":573            let id = try uuid(parts[2])574            guard pages[id] != nil else { throw HTTPFailure(status: 404, message: "Page not found") }575            let list = (versions[id] ?? []).reversed().map { ["id": UUID().uuidString.lowercased(), "version": $0.version, "title": $0.title, "reason": $0.reason, "createdAt": iso(now()), "wordCount": 0] as [String: Any] }576            return json(Array(list))577578        case ("GET", "tags", 2):579            return json(tagNames.sorted().map { ["id": $0, "name": $0, "color": NSNull(), "pages": 0] as [String: Any] })580581        case ("POST", "attachments", 2):582            return try upload(contentType: header("Content-Type") ?? "", body: body)583584        case ("GET", "attachments", 2):585            let rows = attachments.values.filter { $0.deletedAt == nil && (query["pageId"] == nil || $0.pageId == query["pageId"]) }.sorted { $0.createdAt > $1.createdAt }586            return json(rows.map { ["id": $0.id, "filename": $0.filename, "mime": $0.mime, "size": $0.bytes.count, "pageId": $0.pageId ?? NSNull(), "pageCount": NSNull(),587                                    "createdAt": iso($0.createdAt), "hasText": false, "url": "/api/files/\($0.id)"] as [String: Any] })588589        case ("DELETE", "attachments", 2):590            softDeleteAttachment(query["id"] ?? "")591            return json(["ok": true])592593        case ("GET", "files", 3):594            let id = try uuid(parts[2])595            guard let row = attachments[id] else { throw HTTPFailure(status: 404, message: "Not found") }596            return Reply(status: 200, headers: ["Content-Type": row.mime, "Content-Length": String(row.bytes.count),597                                               "Content-Disposition": "attachment; filename*=UTF-8''\(row.filename.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "file")"], body: row.bytes)598599        case ("GET", "tasks", 2):600            if apiLevel >= 3, let since = query["since"].flatMap({ Int64($0) }) {601                return json(tasks.values.filter { $0.rev > since }.sorted { $0.rev < $1.rev }.map(taskRow))602            }603            let rows = tasks.values.filter { $0.deletedAt == nil && (query["done"] == "1" || $0.status != "done") && (query["pageId"] == nil || $0.pageId == query["pageId"]) }604                .sorted { $0.createdAt > $1.createdAt }605            return json(rows.map(taskRow))606607        case ("POST", "tasks", 2):608            let b = try bodyObject()609            guard let title = (b["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty, title.count <= 500 else { throw HTTPFailure(status: 400, message: "Validation: title") }610            if let pageId = b["pageId"] as? String, !Self.isUUID(pageId) { throw HTTPFailure(status: 400, message: "Validation: pageId") }611            var given = UUID().uuidString.lowercased()612            if apiLevel >= 3 {613                if let id = b["id"] as? String {614                    given = try uuid(id)615                    if let existing = tasks[given] { return json(taskRow(existing), status: 200, headers: ["x-existing": "1"]) }616                }617                if let pageId = b["pageId"] as? String, pages[pageId]?.deletedAt != nil || pages[pageId] == nil { throw HTTPFailure(status: 400, message: "Unknown page", code: "bad_page") }618            }619            let stamp = now()620            var task = FakeTask(id: given, title: title, priority: b["priority"] as? String ?? "medium", dueAt: try taskDue(b), pageId: b["pageId"] as? String,621                                createdAt: stamp, updatedAt: stamp)622            if apiLevel >= 3 {623                task.blockId = b["blockId"] as? String624                task.project = b["project"] as? String625                if let status = b["status"] as? String {626                    guard ["todo", "doing", "done"].contains(status) else { throw HTTPFailure(status: 400, message: "Validation: status") }627                    task.status = status628                    task.completedAt = status == "done" ? stamp : nil629                }630            }631            task.rev = nextRev()632            tasks[task.id] = task633            return json(taskRow(task), status: 201)634635        case ("PATCH", "tasks", 2):636            let b = try bodyObject()637            guard let id = b["id"] as? String, Self.isUUID(id) else { throw HTTPFailure(status: 400, message: "Validation: id") }638            guard var task = tasks[id], task.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Task not found") }639            if let title = b["title"] as? String {640                let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)641                guard !trimmed.isEmpty else { throw HTTPFailure(status: 400, message: "Validation: title") }642                task.title = trimmed643            }644            if b.keys.contains("dueAt") { task.dueAt = try date(b["dueAt"]) }645            if let status = b["status"] as? String {646                guard ["todo", "done"].contains(status) else { throw HTTPFailure(status: 400, message: "Validation: status") }647                task.status = status648                task.completedAt = status == "done" ? now() : nil649            }650            if b.keys.contains("pageId") { task.pageId = b["pageId"] as? String }651            task.updatedAt = now()652            task.rev = nextRev()653            tasks[id] = task654            return json(taskRow(task))655656        case ("DELETE", "tasks", 2):657            guard let id = query["id"], Self.isUUID(id) else { throw HTTPFailure(status: 400, message: "Invalid id") }658            guard var task = tasks[id] else { throw HTTPFailure(status: 404, message: "Task not found") }659            task.deletedAt = now()660            task.rev = nextRev()661            tasks[id] = task662            return json(["ok": true])663664        case ("GET", "inbox", 2):665            let rows = pages.values.filter { $0.inboxAt != nil && $0.deletedAt == nil }666            return json(rows.map { ["id": $0.id, "title": $0.title, "inboxAt": iso($0.inboxAt!)] as [String: Any] })667668        case ("POST", "inbox", 3):669            return try triage(id: try uuid(parts[2]), body: try bodyObject())670671        default:672            throw HTTPFailure(status: 404, message: "Not found")673        }674    }675676    // MARK: change feed677678    func computeHead(kinds: Set<String> = []) -> Int64 {679        var head = max(pages.values.map(\.rev).max() ?? 0, attachments.values.map(\.rev).max() ?? 0,680                       tombstones.values.filter { ["page", "attachment"].contains($0.kind) || kinds.contains($0.kind) }.map(\.rev).max() ?? 0)681        if kinds.contains("task") { head = max(head, tasks.values.map(\.rev).max() ?? 0) }682        if kinds.contains("canvas") { head = max(head, canvases.values.map(\.rev).max() ?? 0) }683        head = max(head, entities.values.filter { kinds.contains($0.kind) }.map(\.rev).max() ?? 0)684        return head685    }686687    func feed(query: [String: String]) throws -> Reply {688        let since = Int64(query["since"] ?? "0") ?? -1689        guard since >= 0 else { return Reply(status: 400, body: Self.serialize(["error": "since must be a non-negative integer", "code": "bad_cursor"])) }690        let limit = min(500, max(1, Int(query["limit"] ?? "200") ?? 200))691        // A 2.x server ignores the unknown `kinds` parameter.692        var kinds: [String] = []693        if apiLevel >= 3, let asked = query["kinds"], !asked.isEmpty {694            kinds = asked == "all" ? Self.entityKinds : asked.split(separator: ",").map(String.init)695            if let unknown = kinds.first(where: { !Self.entityKinds.contains($0) }) {696                throw HTTPFailure(status: 400, message: "Unknown kind: \(unknown)", code: "bad_kinds", extra: ["kinds": Self.entityKinds])697            }698            kinds = Self.entityKinds.filter(kinds.contains)699        }700        let head = computeHead(kinds: Set(kinds))701        let workspace: [String: Any] = ["id": workspaceId, "name": "Fake workspace"]702        if since > head {703            // Exactly the answer of the server: no `user` key in this branch.704            var answer: [String: Any] = ["reset": true, "cursor": 0, "head": head, "more": true, "pages": [Any](), "attachments": [Any](), "tombstones": [Any](), "tags": [Any](),705                                         "workspace": workspace, "serverTime": iso(now())]706            if !kinds.isEmpty { answer["entities"] = Dictionary(uniqueKeysWithValues: kinds.map { ($0, [Any]()) }) }707            return json(answer)708        }709        func window<T>(_ rows: [T], _ rev: (T) -> Int64) -> [T] { Array(rows.filter { rev($0) > since && rev($0) <= head }.sorted { rev($0) < rev($1) }.prefix(limit)) }710        var p = window(Array(pages.values), \.rev)711        var a = window(Array(attachments.values), \.rev)712        var t = window(tombstones.values.filter { ["page", "attachment"].contains($0.kind) || kinds.contains($0.kind) }, \.rev)713        var e: [String: [(rev: Int64, row: [String: Any])]] = [:]714        for kind in kinds {715            let rows: [(rev: Int64, row: [String: Any])]716            switch kind {717            case "task": rows = tasks.values.map { ($0.rev, feedTaskRow($0)) }718            case "canvas": rows = canvases.values.map { ($0.rev, canvasFeedRow($0)) }719            default: rows = entities.values.filter { $0.kind == kind }.map { ($0.rev, entityRow($0)) }720            }721            e[kind] = window(rows, \.rev)722        }723        var cuts: [Int64] = []724        if p.count == limit { cuts.append(p.last!.rev) }725        if a.count == limit { cuts.append(a.last!.rev) }726        if t.count == limit { cuts.append(t.last!.rev) }727        for rows in e.values where rows.count == limit { cuts.append(rows.last!.rev) }728        let more = !cuts.isEmpty729        let cursor = more ? cuts.min()! : head730        if more {731            p = p.filter { $0.rev <= cursor }; a = a.filter { $0.rev <= cursor }; t = t.filter { $0.rev <= cursor }732            e = e.mapValues { $0.filter { $0.rev <= cursor } }733        }734        var answer: [String: Any] = [735            "cursor": cursor, "head": head, "more": more, "reset": false, "serverTime": iso(now()), "workspace": workspace, "user": ["displayName": "Fake user"],736            "pages": p.map { pageRow($0, full: false) },737            "attachments": a.map { ["id": $0.id, "pageId": $0.pageId ?? NSNull(), "filename": $0.filename, "mime": $0.mime, "size": $0.bytes.count, "sha256": NSNull(), "pageCount": NSNull(),738                                    "createdAt": iso($0.createdAt), "deletedAt": $0.deletedAt.map(iso) ?? NSNull(), "rev": $0.rev] as [String: Any] },739            "tombstones": t.map { ["id": $0.id, "kind": $0.kind, "rev": $0.rev, "deletedAt": iso($0.deletedAt)] as [String: Any] },740            "tags": tagNames.sorted().map { ["name": $0, "color": NSNull()] as [String: Any] },741        ]742        if !kinds.isEmpty { answer["entities"] = e.mapValues { $0.map(\.row) } }743        return json(answer)744    }745746    // MARK: pages747748    func makePage(id: String?, title: String?, parentId: String?, section: String, type: String, content: Any?, icon: String?, properties: [String: Any]) -> FakePage {749        let siblings = pages.values.filter { $0.parentId == parentId }750        let stamp = now()751        let trimmed = (title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)752        let document = Self.ensureBlockIds(content ?? ["type": "doc", "content": [["type": "paragraph"]]])753        var page = FakePage(id: (id ?? UUID().uuidString).lowercased(), parentId: parentId, content: Self.serialize(document), properties: Self.serialize(properties), createdAt: stamp, updatedAt: stamp)754        page.type = type755        page.section = section756        page.title = trimmed.isEmpty ? "Untitled" : trimmed757        page.icon = icon758        page.position = (siblings.map(\.position).max() ?? 0) + 1759        return page760    }761762    /// Inserts or updates a row: every write takes the next revision (the database trigger).763    func store(_ page: inout FakePage) {764        if pages[page.id] == nil { tombstones["page:" + page.id] = nil; tombstones["canvas:" + page.id] = nil }765        page.rev = nextRev()766        pages[page.id] = page767    }768769    func conflictPayload(_ page: FakePage) -> [String: Any] {770        ["server": ["version": page.version, "title": page.title, "content": Self.parse(page.content) ?? NSNull(), "properties": Self.parse(page.properties) ?? [:], "updatedAt": iso(page.updatedAt)] as [String: Any]]771    }772773    /// `updatePage` of the server: trashed pages are not found; versioned fields bump the version and honour `baseVersion`.774    func updatePage(_ id: String, patch: [String: Any], baseVersion: Int?, reason: String?) throws -> FakePage {775        guard let previous = pages[id], previous.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") }776        if let parent = patch["parentId"] as? String, parent == id { throw HTTPFailure(status: 400, message: "A page cannot be its own parent") }777        let versioned = patch["title"] != nil || patch["content"] != nil || patch["properties"] != nil778        if versioned, let baseVersion, previous.version != baseVersion {779            throw HTTPFailure(status: 409, message: "This note was changed in another session", code: "conflict", extra: conflictPayload(previous))780        }781        var page = previous782        page.updatedAt = now()783        if let title = patch["title"] as? String {784            let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)785            page.title = trimmed.isEmpty ? "Untitled" : trimmed786        }787        if let content = patch["content"] { page.content = Self.serialize(Self.ensureBlockIds(content)) }788        if let properties = patch["properties"] as? [String: Any] { page.properties = Self.serialize(properties) }789        if patch.keys.contains("icon") { page.icon = patch["icon"] as? String }790        if patch.keys.contains("cover") { page.cover = patch["cover"] as? String }791        if patch.keys.contains("parentId") { page.parentId = patch["parentId"] as? String }792        if let section = patch["section"] as? String { page.section = section }793        if let position = patch["position"] as? NSNumber { page.position = position.doubleValue }794        if let pinned = patch["pinned"] as? Bool { page.pinned = pinned }795        if let archived = patch["archived"] as? Bool { page.archived = archived }796        if versioned { page.version += 1 }797        store(&page)798        if patch["content"] != nil || patch["title"] != nil {799            // The PREVIOUS state is snapshotted when there is no snapshot yet, an explicit reason, or 20 versions since the last one800            // (the 10-minute rule of the server never fires in a test).801            let last = (versions[id] ?? []).filter { $0.version > 0 }.map(\.version).max()802            if last == nil || reason != nil || previous.version - last! >= 20 { snapshot(previous, reason: reason ?? "autosave") }803        }804        return page805    }806807    func snapshot(_ page: FakePage, reason: String, version: Int? = nil) {808        let number = version ?? page.version809        guard !(versions[page.id] ?? []).contains(where: { $0.version == number }) else { return }   // idempotent per version number810        versions[page.id, default: []].append(FakeVersion(version: number, title: page.title, content: page.content, properties: page.properties, reason: reason))811    }812813    func descendants(of id: String, includeDeleted: Bool) -> [String] {814        var out: [String] = []815        var frontier = [id]816        while let current = frontier.popLast() {817            for child in pages.values where child.parentId == current && (includeDeleted || child.deletedAt == nil) && !out.contains(child.id) && child.id != id {818                out.append(child.id)819                frontier.append(child.id)820            }821        }822        return out823    }824825    func softDelete(_ id: String) -> Int {826        let ids = descendants(of: id, includeDeleted: false) + [id]827        let stamp = now()828        for pid in ids { if var page = pages[pid] { page.deletedAt = stamp; store(&page) } }829        return ids.count830    }831832    func restore(_ id: String) {833        for pid in descendants(of: id, includeDeleted: true) + [id] {834            if var page = pages[pid], page.deletedAt != nil { page.deletedAt = nil; store(&page) }835        }836    }837838    /// Permanent deletion of ONE row (the server does not cascade to child pages: `parent_id` has no foreign key).839    func purge(_ id: String) {840        guard pages.removeValue(forKey: id) != nil else { return }841        versions[id] = nil842        tombstones["page:" + id] = FakeTombstone(id: id, kind: "page", rev: nextRev(), deletedAt: now())843        for (aid, row) in attachments where row.pageId == id {   // ON DELETE SET NULL844            var changed = row845            changed.pageId = nil846            changed.rev = nextRev()847            attachments[aid] = changed848        }849        for (tid, task) in tasks where task.pageId == id { var changed = task; changed.pageId = nil; changed.blockId = nil; changed.rev = nextRev(); tasks[tid] = changed }850        if canvases.removeValue(forKey: id) != nil {851            tombstones["canvas:" + id] = FakeTombstone(id: id, kind: "canvas", rev: nextRev(), deletedAt: now())852        }853    }854855    @discardableResult856    func applyTags(_ id: String, _ names: [String]) -> [String] {857        var seen = Set<String>()858        var clean: [String] = []859        for name in names {860            var n = name.trimmingCharacters(in: .whitespacesAndNewlines)861            if n.hasPrefix("#") { n.removeFirst() }862            n = String(n.lowercased().prefix(40))863            if !n.isEmpty, seen.insert(n).inserted { clean.append(n) }864        }865        clean = Array(clean.prefix(20))866        tagNames.formUnion(clean)867        guard var page = pages[id] else { return clean.sorted() }868        page.tags = clean.sorted()869        store(&page)   // the page_tags trigger bumps the page revision870        return page.tags871    }872873    func resolve(id: String, body: [String: Any]) throws -> Reply {874        guard let choice = body["choice"] as? String, ["mine", "theirs", "both"].contains(choice), let serverVersion = (body["serverVersion"] as? NSNumber)?.intValue,875              let mine = body["mine"] as? [String: Any] else { throw HTTPFailure(status: 400, message: "Validation: resolve") }876        if let content = mine["content"] { try assertDoc(content) }877        guard let current = pages[id], current.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") }878        guard current.version == serverVersion else {879            throw HTTPFailure(status: 409, message: "The note changed again while you were deciding", code: "conflict", extra: conflictPayload(current))880        }881        let trimmed = (mine["title"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)882        let mineTitle = trimmed.isEmpty ? current.title : trimmed883        let mineContent: Any = mine["content"] ?? Self.parse(current.content) ?? NSNull()884        var page = current885        var copyId: String?886        switch choice {887        case "mine":888            snapshot(current, reason: "conflict · other session's copy")889            page = try updatePage(id, patch: ["title": mineTitle, "content": mineContent], baseVersion: current.version, reason: "conflict · other session's copy")890        case "theirs":891            let unapplied = -Int(Date().timeIntervalSince1970) - (versions[id]?.count ?? 0)892            versions[id, default: []].append(FakeVersion(version: unapplied, title: mineTitle, content: Self.serialize(mineContent), properties: current.properties,893                                                         reason: "conflict · this device's copy (not applied)"))894        default:895            var copy = makePage(id: nil, title: String((mineTitle + " (conflict copy)").prefix(500)), parentId: current.parentId, section: current.section, type: current.type,896                                content: mineContent, icon: current.icon, properties: [:])897            store(&copy)898            copyId = copy.id899        }900        return json(["id": page.id, "version": page.version, "title": page.title, "content": Self.parse(page.content) ?? NSNull(), "properties": Self.parse(page.properties) ?? [:],901                     "updatedAt": iso(page.updatedAt), "copyId": copyId ?? NSNull()])902    }903904    func triage(id: String, body: [String: Any]) throws -> Reply {905        guard let action = body["action"] as? String else { throw HTTPFailure(status: 400, message: "Validation: action") }906        guard var page = pages[id], page.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") }907        guard page.inboxAt != nil else { throw HTTPFailure(status: 409, message: "This item is no longer in the inbox", code: "not_in_inbox") }908        page.inboxAt = nil909        page.updatedAt = now()910        switch action {911        case "keep":912            let section = body["section"] as? String ?? "notes"913            guard ["notes", "documents", "projects", "research"].contains(section) else { throw HTTPFailure(status: 400, message: "Unknown section") }914            if let parent = body["parentId"] as? String { guard let p = pages[parent], p.deletedAt == nil else { throw HTTPFailure(status: 404, message: "Page not found") } }915            page.section = section916            page.parentId = body["parentId"] as? String917        case "archive":918            page.archived = true919        case "trash":920            _ = softDelete(id)921            page.deletedAt = pages[id]?.deletedAt922        default:923            throw HTTPFailure(status: 400, message: "Unsupported action in the fake")924        }925        store(&page)926        return json(["actionId": UUID().uuidString.lowercased(), "summary": "Done", "created": [String: Any]()])927    }928929    func pageRow(_ page: FakePage, full: Bool) -> [String: Any] {930        var row: [String: Any] = [931            "id": page.id, "parentId": page.parentId ?? NSNull(), "databaseId": page.databaseId ?? NSNull(), "type": page.type, "section": page.section, "title": page.title,932            "icon": page.icon ?? NSNull(), "cover": page.cover ?? NSNull(), "content": Self.parse(page.content) ?? NSNull(), "properties": Self.parse(page.properties) ?? [:],933            "position": page.position, "pinned": page.pinned, "archived": page.archived, "version": page.version, "wordCount": Self.wordCount(page.content),934            "createdAt": iso(page.createdAt), "updatedAt": iso(page.updatedAt), "lastOpenedAt": page.lastOpenedAt.map(iso) ?? NSNull(), "deletedAt": page.deletedAt.map(iso) ?? NSNull(),935            "inboxAt": page.inboxAt.map(iso) ?? NSNull(), "captureKind": page.captureKind ?? NSNull(), "rev": page.rev,936        ]937        if full { row["workspaceId"] = workspaceId; row["plainText"] = page.text } else { row["tags"] = page.tags.sorted() }938        return row939    }940941    // MARK: attachments942943    func softDeleteAttachment(_ id: String) {944        guard var row = attachments[id] else { return }945        row.deletedAt = now()946        row.rev = nextRev()947        attachments[id] = row948    }949950    func upload(contentType: String, body: Data) throws -> Reply {951        guard let range = contentType.range(of: "boundary=") else { throw HTTPFailure(status: 400, message: "file missing") }952        let boundary = String(contentType[range.upperBound...]).trimmingCharacters(in: CharacterSet(charactersIn: "\" "))953        var fields: [String: String] = [:]954        var file: (name: String, mime: String, bytes: Data)?955        for part in Self.multipartParts(body, boundary: boundary) {956            guard let name = part.name else { continue }957            if let filename = part.filename { if name == "file" { file = (filename, part.contentType ?? "application/octet-stream", part.data) } }958            else { fields[name] = String(decoding: part.data, as: UTF8.self) }959        }960        guard let file else { throw HTTPFailure(status: 400, message: "file missing") }961        let given = fields["id"].flatMap { $0.isEmpty ? nil : $0 }962        if let given {963            guard given.range(of: "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", options: [.regularExpression, .caseInsensitive]) != nil else { throw HTTPFailure(status: 400, message: "Invalid id") }964            if let existing = attachments[given.lowercased()] {965                return json(["id": existing.id, "url": "/api/files/\(existing.id)", "name": existing.filename, "size": existing.bytes.count, "mime": existing.mime, "hasText": false, "pages": NSNull()],966                            status: 200, headers: ["x-existing": "1"])967            }968        }969        let pageId = fields["pageId"].flatMap { $0.isEmpty ? nil : $0 }970        if let pageId, pageId.range(of: "^[0-9a-f-]{36}$", options: [.regularExpression, .caseInsensitive]) == nil { throw HTTPFailure(status: 400, message: "Invalid pageId") }971        if ["application/x-msdownload", "application/x-sh", "text/html", "application/javascript"].contains(file.mime) { throw HTTPFailure(status: 415, message: "File type not allowed") }972        var row = FakeAttachment(id: (given ?? UUID().uuidString).lowercased(), pageId: pageId.flatMap { pages[$0] != nil ? $0 : nil }, filename: String(file.name.prefix(255)), mime: file.mime,973                                 bytes: file.bytes, createdAt: now())974        row.rev = nextRev()975        tombstones["attachment:" + row.id] = nil976        attachments[row.id] = row977        return json(["id": row.id, "url": "/api/files/\(row.id)", "name": row.filename, "size": row.bytes.count, "mime": row.mime, "hasText": false, "pages": NSNull()], status: 201)978    }979980    struct Part {981        var name: String?982        var filename: String?983        var contentType: String?984        var data: Data985    }986987    /// Splits a multipart/form-data body (binary safe).988    static func multipartParts(_ body: Data, boundary: String) -> [Part] {989        let delimiter = Data("--\(boundary)".utf8)990        let crlf = Data("\r\n".utf8)991        let headerEnd = Data("\r\n\r\n".utf8)992        var parts: [Part] = []993        var cursor = body.startIndex994        var starts: [Data.Index] = []995        while let found = body.range(of: delimiter, in: cursor..<body.endIndex) {996            starts.append(found.lowerBound)997            cursor = found.upperBound998        }999        for (index, start) in starts.enumerated() where index + 1 < starts.count {1000            var from = start + delimiter.count1001            let to = starts[index + 1]1002            if body[from..<to].starts(with: crlf) { from += crlf.count }1003            guard let split = body.range(of: headerEnd, in: from..<to) else { continue }1004            let headerText = String(decoding: body[from..<split.lowerBound], as: UTF8.self)1005            var end = to1006            if end - crlf.count >= split.upperBound, body[(end - crlf.count)..<end] == crlf { end -= crlf.count }1007            var part = Part(data: Data(body[split.upperBound..<end]))1008            for line in headerText.components(separatedBy: "\r\n") {1009                let lower = line.lowercased()1010                if lower.hasPrefix("content-disposition:") {1011                    part.name = attribute("name", in: line)1012                    part.filename = attribute("filename", in: line)1013                } else if lower.hasPrefix("content-type:") {1014                    part.contentType = line.dropFirst("content-type:".count).trimmingCharacters(in: .whitespaces)1015                }1016            }1017            parts.append(part)1018        }1019        return parts1020    }10211022    static func attribute(_ name: String, in line: String) -> String? {1023        guard let range = line.range(of: "; \(name)=\"") else { return nil }1024        let tail = line[range.upperBound...]1025        guard let end = tail.firstIndex(of: "\"") else { return nil }1026        return String(tail[..<end])1027    }10281029    // MARK: tasks10301031    func taskRow(_ task: FakeTask) -> [String: Any] {1032        var row: [String: Any] = ["id": task.id, "title": task.title, "status": task.status, "priority": task.priority, "dueAt": task.dueAt.map(iso) ?? NSNull(),1033                                  "completedAt": task.completedAt.map(iso) ?? NSNull(), "project": task.project ?? NSNull(), "pageId": task.pageId ?? NSNull(),1034                                  "createdAt": iso(task.createdAt), "updatedAt": iso(task.updatedAt)]1035        if apiLevel >= 3 {1036            row["blockId"] = task.blockId ?? NSNull()1037            row["deletedAt"] = task.deletedAt.map(iso) ?? NSNull()1038            row["rev"] = task.rev1039        }1040        return row1041    }10421043    func date(_ value: Any?) throws -> Date? {1044        guard let value, !(value is NSNull) else { return nil }1045        guard let text = value as? String, let parsed = Self.parseISO(text) else { throw HTTPFailure(status: 400, message: "Validation: date") }1046        return parsed1047    }10481049    // MARK: helpers10501051    func nextRev() -> Int64 { rev += 1; return rev }10521053    /// Strictly increasing clock with millisecond resolution (two writes never share a timestamp).1054    func now() -> Date {1055        let real = Int64((Date().timeIntervalSince1970 * 1000).rounded())1056        lastMillis = max(real, lastMillis + 1)1057        return Date(timeIntervalSince1970: Double(lastMillis) / 1000)1058    }10591060    func json(_ object: Any, status: Int = 200, headers: [String: String] = [:]) -> Reply {1061        Reply(status: status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }, body: Self.serialize(object))1062    }10631064    func assertDoc(_ value: Any) throws {1065        guard let doc = value as? [String: Any], doc["type"] as? String == "doc", doc["content"] == nil || doc["content"] is [Any] else {1066            throw HTTPFailure(status: 400, message: "Invalid document", code: "bad_document")1067        }1068    }10691070    func iso(_ date: Date) -> String { Self.formatISO(date) }10711072    private static let isoLock = NSLock()1073    nonisolated(unsafe) private static let isoFormatter: ISO8601DateFormatter = {1074        let f = ISO8601DateFormatter()1075        f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]1076        return f1077    }()1078    static func formatISO(_ date: Date) -> String { isoLock.withLock { isoFormatter.string(from: date) } }1079    static func parseISO(_ text: String) -> Date? { isoLock.withLock { isoFormatter.date(from: text) } }10801081    static func isUUID(_ text: String) -> Bool {1082        text.range(of: "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", options: [.regularExpression, .caseInsensitive]) != nil1083    }10841085    static func matches(_ regex: NSRegularExpression, _ text: String) -> Bool {1086        regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil1087    }10881089    static func parse(_ data: Data) -> Any? { try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) }10901091    /// No sorted keys on purpose: like jsonb, the fake gives object keys back in an order of its own.1092    static func serialize(_ object: Any) -> Data { (try? JSONSerialization.data(withJSONObject: object, options: [.fragmentsAllowed])) ?? Data("null".utf8) }10931094    static func jsonEqual(_ a: Data, _ b: Data) -> Bool {1095        guard let x = parse(a) as? NSObject, let y = parse(b) as? NSObject else { return a == b }1096        return x == y1097    }10981099    static func plainText(_ content: Data) -> String {1100        var out: [String] = []1101        func walk(_ node: Any) {1102            guard let object = node as? [String: Any] else { return }1103            if let text = object["text"] as? String { out.append(text) }1104            for child in object["content"] as? [Any] ?? [] { walk(child) }1105        }1106        if let root = parse(content) { walk(root) }1107        return out.joined(separator: "\n")1108    }11091110    static func wordCount(_ content: Data) -> Int { plainText(content).split(whereSeparator: { $0 == " " || $0 == "\n" }).count }11111112    private static let idTypes: Set<String> = ["paragraph", "heading", "blockquote", "codeBlock", "bulletList", "orderedList", "taskList", "table", "callout", "details", "aiBlock", "blockMath", "image", "fileBlock"]11131114    /// `ensureBlockIds` of the server: a missing, empty or duplicated id is replaced by a fresh one.1115    static func ensureBlockIds(_ document: Any) -> Any {1116        var seen = Set<String>()1117        func rid() -> String {1118            let alphabet = Array("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")1119            return String((0..<10).map { _ in alphabet.randomElement()! })1120        }1121        func walk(_ node: Any) -> Any {1122            guard var object = node as? [String: Any] else { return node }1123            if let type = object["type"] as? String, idTypes.contains(type) {1124                var attrs = object["attrs"] as? [String: Any] ?? [:]1125                if let id = attrs["id"] as? String, !id.isEmpty, !seen.contains(id) { seen.insert(id) } else {1126                    let fresh = rid()1127                    seen.insert(fresh)1128                    attrs["id"] = fresh1129                    object["attrs"] = attrs1130                }1131            }1132            if let children = object["content"] as? [Any], !children.isEmpty { object["content"] = children.map(walk) }1133            return object1134        }1135        return walk(document)1136    }1137}11381139// MARK: - URLProtocol11401141public final class FakeBackendProtocol: URLProtocol, @unchecked Sendable {1142    private static let queue = DispatchQueue(label: "spn.fake-backend", attributes: .concurrent)1143    let stateLock = NSLock()1144    var stopped = false11451146    public override class func canInit(with request: URLRequest) -> Bool { FakeBackend.backend(forHost: request.url?.host) != nil }1147    public override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }11481149    public override func startLoading() {1150        var body = request.httpBody ?? Data()1151        if body.isEmpty, let stream = request.httpBodyStream {1152            stream.open()1153            var buffer = [UInt8](repeating: 0, count: 64 * 1024)1154            while true {1155                let n = stream.read(&buffer, maxLength: buffer.count)1156                if n <= 0 { break }1157                body.append(buffer, count: n)1158            }1159            stream.close()1160        }1161        let request = self.request1162        guard let url = request.url, let backend = FakeBackend.backend(forHost: url.host) else {1163            client?.urlProtocol(self, didFailWithError: URLError(.cannotFindHost))1164            return1165        }1166        let method = request.httpMethod ?? "GET"1167        let headers = request.allHTTPHeaderFields ?? [:]1168        let payload = body1169        // Answered from another queue so that delays and held requests never block the loading thread of the session.1170        Self.queue.async { [self] in1171            let reply = backend.respond(method: method, url: url, headers: headers, body: payload)1172            if stateLock.withLock({ stopped }) { return }1173            if let code = reply.error {1174                client?.urlProtocol(self, didFailWithError: URLError(code))1175                return1176            }1177            let response = HTTPURLResponse(url: url, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers)!1178            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)1179            if !reply.body.isEmpty { client?.urlProtocol(self, didLoad: reply.body) }1180            client?.urlProtocolDidFinishLoading(self)1181        }1182    }11831184    public override func stopLoading() { stateLock.withLock { stopped = true } }1185}1186
Files main
Menu

Theme