SPB Git

Repository Public

Models.swift 22.1 KB 568 lines swift

1// SP Notes Core2// File: Sources/SPNotesStore/Models.swift3// Description: Public value types of the local store: pages, summaries, remote feed items, attachments, ops,4//              conflicts, local versions, reminders, search filters, change events and errors.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Errors1112public enum StoreError: Error, Sendable, Equatable, CustomStringConvertible {13    /// An SQLite error (extended result code, message, offending SQL when known).14    case sqlite(code: Int32, message: String, sql: String?)15    /// The row addressed by the call does not exist (the associated value says which).16    case notFound(String)17    /// An argument was rejected (the associated value says why).18    case invalid(String)19    /// `move` would make a page its own ancestor.20    case cycle21    /// A write was attempted on a read-only store.22    case readOnly23    /// The store was closed.24    case closed25    /// The file's schema cannot be used by this build (newer than supported, or older on a read-only connection).26    case schema(String)27    /// The copy of the database made before a migration could not be written; the migration was NOT attempted.28    case backup(String)2930    public var description: String {31        switch self {32        case .sqlite(let code, let message, let sql): return "SQLite error \(code): \(message)" + (sql.map { " [\($0)]" } ?? "")33        case .notFound(let what): return "not found: \(what)"34        case .invalid(let why): return "invalid argument: \(why)"35        case .cycle: return "a page cannot be moved into its own subtree"36        case .readOnly: return "the store is read-only"37        case .closed: return "the store is closed"38        case .schema(let why): return "schema: \(why)"39        case .backup(let why): return "pre-migration backup failed: \(why)"40        }41    }42}4344// MARK: - Pages4546public enum SyncState: String, Sendable, Codable, CaseIterable {47    case synced, pending, conflict, error48}4950/// Fields that the server does not guard with the page version; each is pushed independently.51public enum MetaField: String, Sendable, Codable, CaseIterable, Hashable {52    case parentId, section, position, pinned, archived, icon, cover, inboxAt53}5455/// A full local page row (server fields + local sync state + derived fields).56public struct PageRecord: Sendable, Equatable, Identifiable {57    public var id: String58    public var parentId: String?59    public var databaseId: String?60    public var type: String61    public var section: String62    public var title: String63    public var icon: String?64    public var cover: String?65    /// Opaque document JSON.66    public var content: Data67    /// JSON object.68    public var properties: Data69    public var position: Double70    public var pinned: Bool71    public var archived: Bool72    /// Last server version this row is based on. 0 = never on the server.73    public var serverVersion: Int74    public var wordCount: Int75    public var createdAt: Date76    public var updatedAt: Date77    public var lastOpenedAt: Date?78    public var deletedAt: Date?79    public var inboxAt: Date?80    public var captureKind: String?81    public var rev: Int6482    /// Sorted tag names.83    public var tags: [String]84    // Local sync state85    public var needsCreate: Bool86    public var dirtyContent: Bool87    public var dirtyMeta: Set<MetaField>88    public var tagsDirty: Bool89    public var editSeq: Int6490    public var syncState: SyncState91    public var syncError: String?92    // Derived93    public var plainText: String94    public var preview: String95    public var favorite: Bool96    public var isFolder: Bool97    public var localUpdatedAt: Date9899    /// True when something has to be pushed to the server.100    public var isDirty: Bool { needsCreate || dirtyContent || !dirtyMeta.isEmpty || tagsDirty }101}102103/// The last synced copy of the version-guarded fields of a page (ancestor of three-way merges).104public struct PageBase: Sendable, Equatable {105    public var title: String106    public var content: Data107    public var properties: Data108    public var version: Int109    public init(title: String, content: Data, properties: Data, version: Int) {110        self.title = title; self.content = content; self.properties = properties; self.version = version111    }112}113114/// The version-guarded fields as they were sent to the server by a push.115public struct PushedCopy: Sendable, Equatable {116    public var title: String117    public var content: Data118    public var properties: Data119    public init(title: String, content: Data, properties: Data) {120        self.title = title; self.content = content; self.properties = properties121    }122}123124/// A complete replacement of the version-guarded fields with their derived values.125public struct ContentCopy: Sendable, Equatable {126    public var title: String127    public var content: Data128    public var properties: Data129    public var plainText: String130    public var wordCount: Int131    public var preview: String132    public init(title: String, content: Data, properties: Data, plainText: String, wordCount: Int, preview: String) {133        self.title = title; self.content = content; self.properties = properties134        self.plainText = plainText; self.wordCount = wordCount; self.preview = preview135    }136}137138/// A page to push, with the base copy when one exists.139public struct PendingPage: Sendable, Equatable {140    public var page: PageRecord141    public var base: PageBase?142}143144/// A page for lists: everything but the content blob, the properties and the plain text.145public struct PageSummary: Sendable, Equatable, Identifiable {146    public var id: String147    public var title: String148    public var preview: String149    public var updatedAt: Date150    public var parentId: String?151    public var section: String152    public var pinned: Bool153    public var favorite: Bool154    public var isFolder: Bool155    public var icon: String?156    public var tags: [String]157    public var syncState: SyncState158    /// True when the page has at least one child that is not in the trash.159    public var hasChildren: Bool160    public var type: String161    public var position: Double162    public var archived: Bool163    public var wordCount: Int164    public var lastOpenedAt: Date?165    public var deletedAt: Date?166    public var inboxAt: Date?167168    public init(id: String, title: String, preview: String, updatedAt: Date, parentId: String? = nil, section: String, pinned: Bool = false, favorite: Bool = false, isFolder: Bool = false, icon: String? = nil, tags: [String] = [], syncState: SyncState, hasChildren: Bool = false, type: String, position: Double, archived: Bool = false, wordCount: Int, lastOpenedAt: Date? = nil, deletedAt: Date? = nil, inboxAt: Date? = nil) {169        self.id = id; self.title = title; self.preview = preview; self.updatedAt = updatedAt; self.parentId = parentId; self.section = section; self.pinned = pinned; self.favorite = favorite; self.isFolder = isFolder; self.icon = icon; self.tags = tags; self.syncState = syncState; self.hasChildren = hasChildren; self.type = type; self.position = position; self.archived = archived; self.wordCount = wordCount; self.lastOpenedAt = lastOpenedAt; self.deletedAt = deletedAt; self.inboxAt = inboxAt170    }171}172173/// Parameters of `createPage`.174public struct NewPage: Sendable, Equatable {175    public static let emptyDocument = Data(#"{"type":"doc","content":[{"type":"paragraph"}]}"#.utf8)176177    /// Lowercase UUID string; generated when nil.178    public var id: String?179    public var parentId: String?180    public var databaseId: String?181    public var type: String182    /// nil = the parent's section, or "notes" at the root.183    public var section: String?184    public var title: String185    public var icon: String?186    public var cover: String?187    public var content: Data188    /// JSON object.189    public var properties: Data190    /// nil = after the last sibling.191    public var position: Double?192    public var pinned: Bool193    public var plainText: String194    public var wordCount: Int195    public var preview: String196    public var tags: [String]197    public var inboxAt: Date?198    public var captureKind: String?199200    public init(id: String? = nil, parentId: String? = nil, databaseId: String? = nil, type: String = "page", section: String? = nil,201                title: String = "", icon: String? = nil, cover: String? = nil, content: Data = NewPage.emptyDocument,202                properties: Data = Data("{}".utf8), position: Double? = nil, pinned: Bool = false, plainText: String = "",203                wordCount: Int = 0, preview: String = "", tags: [String] = [], inboxAt: Date? = nil, captureKind: String? = nil) {204        self.id = id; self.parentId = parentId; self.databaseId = databaseId; self.type = type; self.section = section205        self.title = title; self.icon = icon; self.cover = cover; self.content = content; self.properties = properties206        self.position = position; self.pinned = pinned; self.plainText = plainText; self.wordCount = wordCount207        self.preview = preview; self.tags = tags; self.inboxAt = inboxAt; self.captureKind = captureKind208    }209}210211public enum SmartList: String, Sendable, CaseIterable {212    /// Not in the trash, not archived; newest `updatedAt` first.213    case all214    /// Same set as `all`, ordered by max(updatedAt, lastOpenedAt).215    case recent216    case pinned217    case favorites218    /// `inboxAt` set, not in the trash; newest capture first.219    case inbox220    /// Archived, not in the trash.221    case archived222    /// In the trash; most recently deleted first.223    case trash224}225226public struct ListCounts: Sendable, Equatable {227    public var all = 0228    public var pinned = 0229    public var favorites = 0230    public var inbox = 0231    public var archived = 0232    public var trash = 0233    /// Pages with something to push.234    public var pending = 0235    public var conflicts = 0236237    public init(all: Int = 0, pinned: Int = 0, favorites: Int = 0, inbox: Int = 0, archived: Int = 0, trash: Int = 0, pending: Int = 0, conflicts: Int = 0) {238        self.all = all; self.pinned = pinned; self.favorites = favorites; self.inbox = inbox239        self.archived = archived; self.trash = trash; self.pending = pending; self.conflicts = conflicts240    }241}242243public struct TagInfo: Sendable, Equatable, Identifiable {244    public var id: String { name }245    public var name: String246    public var color: String?247    /// Notes carrying the tag that are neither in the trash nor archived.248    public var count: Int249}250251// MARK: - Remote feed252253public struct RemotePage: Sendable, Equatable {254    public var id: String255    public var parentId: String?256    public var databaseId: String?257    public var type: String258    public var section: String259    public var title: String260    public var icon: String?261    public var cover: String?262    public var content: Data263    public var properties: Data264    public var position: Double265    public var pinned: Bool266    public var archived: Bool267    public var version: Int268    public var wordCount: Int269    public var createdAt: Date270    public var updatedAt: Date271    public var lastOpenedAt: Date?272    public var deletedAt: Date?273    public var inboxAt: Date?274    public var captureKind: String?275    public var rev: Int64276    public var tags: [String]277    /// Derived by the caller from `content` (this module does not parse documents).278    public var plainText: String279    public var preview: String280281    public init(id: String, parentId: String? = nil, databaseId: String? = nil, type: String = "page", section: String = "notes",282                title: String, icon: String? = nil, cover: String? = nil, content: Data, properties: Data = Data("{}".utf8),283                position: Double = 0, pinned: Bool = false, archived: Bool = false, version: Int, wordCount: Int = 0,284                createdAt: Date, updatedAt: Date, lastOpenedAt: Date? = nil, deletedAt: Date? = nil, inboxAt: Date? = nil,285                captureKind: String? = nil, rev: Int64 = 0, tags: [String] = [], plainText: String = "", preview: String = "") {286        self.id = id; self.parentId = parentId; self.databaseId = databaseId; self.type = type; self.section = section287        self.title = title; self.icon = icon; self.cover = cover; self.content = content; self.properties = properties288        self.position = position; self.pinned = pinned; self.archived = archived; self.version = version289        self.wordCount = wordCount; self.createdAt = createdAt; self.updatedAt = updatedAt; self.lastOpenedAt = lastOpenedAt290        self.deletedAt = deletedAt; self.inboxAt = inboxAt; self.captureKind = captureKind; self.rev = rev; self.tags = tags291        self.plainText = plainText; self.preview = preview292    }293}294295public struct RemoteAttachment: Sendable, Equatable {296    public var id: String297    public var pageId: String?298    public var filename: String299    public var mime: String300    public var size: Int64301    public var sha256: String?302    public var pageCount: Int?303    public var createdAt: Date304    public var deletedAt: Date?305    public var rev: Int64306    public init(id: String, pageId: String?, filename: String, mime: String, size: Int64, sha256: String? = nil, pageCount: Int? = nil,307                createdAt: Date, deletedAt: Date? = nil, rev: Int64 = 0) {308        self.id = id; self.pageId = pageId; self.filename = filename; self.mime = mime; self.size = size; self.sha256 = sha256309        self.pageCount = pageCount; self.createdAt = createdAt; self.deletedAt = deletedAt; self.rev = rev310    }311}312313public struct RemoteTag: Sendable, Equatable {314    public var name: String315    public var color: String?316    public init(name: String, color: String? = nil) { self.name = name; self.color = color }317}318319public struct Tombstone: Sendable, Equatable {320    public enum Kind: String, Sendable, Codable { case page, attachment }321    public var id: String322    public var kind: Kind323    public init(id: String, kind: Kind) { self.id = id; self.kind = kind }324}325326/// A page whose server copy moved on while local content edits are pending. Local content was not touched.327public struct DivergedPage: Sendable, Equatable {328    public var id: String329    public var remote: RemotePage330}331332/// What `applyRemote` did.333public struct ApplySummary: Sendable, Equatable {334    public var insertedPageIds: [String] = []335    public var updatedPageIds: [String] = []336    public var deletedPageIds: [String] = []337    /// Dirty pages whose server row was purged: kept, and flagged `needsCreate` again.338    public var resurrectedPageIds: [String] = []339    public var diverged: [DivergedPage] = []340    public var changedAttachmentIds: [String] = []341    public var deletedAttachmentIds: [String] = []342    /// Relative paths of local files whose attachment row was removed: the caller deletes the files.343    public var orphanedFiles: [String] = []344    public var tagsChanged = false345}346347// MARK: - Attachments348349public enum AttachmentState: String, Sendable, Codable, CaseIterable {350    /// Known from the server, file not on this device.351    case remote352    case downloading353    /// File on this device and on the server.354    case local355    case pendingUpload356    case uploading357    /// The upload failed; still listed by `pendingUploads` (see `uploadAttempts`).358    case failed359}360361public struct AttachmentRecord: Sendable, Equatable, Identifiable {362    public var id: String363    public var pageId: String?364    public var filename: String365    public var mime: String366    public var size: Int64367    public var sha256: String?368    public var pageCount: Int?369    public var createdAt: Date370    public var deletedAt: Date?371    public var rev: Int64372    public var state: AttachmentState373    /// Path relative to the attachments directory managed by the caller.374    public var localPath: String?375    public var keepOffline: Bool376    /// False until the server has the file.377    public var uploaded: Bool378    public var uploadAttempts: Int379    public var lastError: String?380    public var lastAccessedAt: Date?381}382383// MARK: - Ops queue384385public struct PendingOp: Sendable, Equatable, Identifiable {386    /// Queue sequence number (FIFO order).387    public var id: Int64388    public var kind: String389    public var targetId: String?390    public var payload: Data?391    public var idempotencyKey: String392    public var createdAt: Date393    public var attempts: Int394    public var nextAttemptAt: Date395    public var lastError: String?396}397398public enum OpKind {399    public static let trash = "trash"400    public static let restore = "restore"401    public static let purge = "purge"402    public static let deleteAttachment = "deleteAttachment"403    public static let createTask = "createTask"404    public static let updateTask = "updateTask"405    public static let deleteTask = "deleteTask"406    public static let triage = "triage"407}408409// MARK: - Conflicts410411/// The server's copy of a page, as returned by a 409 or by the feed.412public struct ServerCopy: Sendable, Equatable {413    public var version: Int414    public var title: String415    public var content: Data416    public var properties: Data417    public var updatedAt: Date418    public init(version: Int, title: String, content: Data, properties: Data, updatedAt: Date) {419        self.version = version; self.title = title; self.content = content; self.properties = properties; self.updatedAt = updatedAt420    }421}422423public struct ConflictRecord: Sendable, Equatable, Identifiable {424    public var id: String { pageId }425    public var pageId: String426    public var server: ServerCopy427    public var detectedAt: Date428}429430// MARK: - Local versions431432public struct LocalVersionInfo: Sendable, Equatable, Identifiable {433    public var id: String434    public var pageId: String435    public var createdAt: Date436    public var title: String437    public var wordCount: Int438    public var reason: String439}440441public struct LocalVersion: Sendable, Equatable, Identifiable {442    public var id: String443    public var pageId: String444    public var createdAt: Date445    public var title: String446    public var content: Data447    public var wordCount: Int448    public var reason: String449    public var plainText: String450    public var preview: String451}452453// MARK: - Reminders454455public struct ReminderRecord: Sendable, Equatable, Identifiable {456    public var id: String457    public var pageId: String?458    public var title: String459    public var dueAt: Date?460    public var done: Bool461    public var serverTaskId: String?462    public var dirty: Bool463    public var deleted: Bool464    /// Incremented on every local change (same role as `PageRecord.editSeq`).465    public var editSeq: Int64466    public var createdAt: Date467    public var updatedAt: Date468}469470// MARK: - Search471472public struct SearchFilters: Sendable, Equatable {473    public var section: String?474    /// A page id: restricts to its descendants (the page itself excluded).475    public var folderId: String?476    /// All of these tags (normalised like `setTags`).477    public var tags: [String]478    /// Inclusive bounds on `updatedAt`.479    public var updatedAfter: Date?480    public var updatedBefore: Date?481    public var favoritesOnly: Bool482    public var pinnedOnly: Bool483    public var includeArchived: Bool484    public var includeTrash: Bool485486    public init(section: String? = nil, folderId: String? = nil, tags: [String] = [], updatedAfter: Date? = nil, updatedBefore: Date? = nil,487                favoritesOnly: Bool = false, pinnedOnly: Bool = false, includeArchived: Bool = false, includeTrash: Bool = false) {488        self.section = section; self.folderId = folderId; self.tags = tags; self.updatedAfter = updatedAfter489        self.updatedBefore = updatedBefore; self.favoritesOnly = favoritesOnly; self.pinnedOnly = pinnedOnly490        self.includeArchived = includeArchived; self.includeTrash = includeTrash491    }492}493494public struct SearchHit: Sendable, Equatable, Identifiable {495    public var id: String { page.id }496    public var page: PageSummary497    /// Excerpt of the body around the match; matched terms are wrapped in `highlightStart` / `highlightEnd`.498    /// For an empty query this is the page preview, without markers.499    public var snippet: String500    /// The title with matched terms wrapped in the same markers.501    public var highlightedTitle: String502    /// bm25 score (lower is better); 0 for an empty query.503    public var score: Double504505    /// Private-use characters that never occur in note text.506    public static let highlightStart: Character = "\u{E000}"507    public static let highlightEnd: Character = "\u{E001}"508509    /// Splits a marked string into (text, isMatch) runs, for display.510    public static func segments(of marked: String) -> [(text: String, highlighted: Bool)] {511        var out: [(text: String, highlighted: Bool)] = []512        var current = ""513        var inside = false514        for character in marked {515            if character == highlightStart || character == highlightEnd {516                if !current.isEmpty { out.append((current, inside)) }517                current = ""518                inside = character == highlightStart519            } else {520                current.append(character)521            }522        }523        if !current.isEmpty { out.append((current, inside)) }524        return out525    }526527    /// Removes the highlight markers.528    public static func plain(_ marked: String) -> String {529        marked.filter { $0 != highlightStart && $0 != highlightEnd }530    }531}532533// MARK: - Change notification534535public enum StoreChange: Sendable, Equatable {536    /// Pages inserted, modified or removed (ids).537    case pages(Set<String>)538    /// The tag list, a tag colour or tag counts changed.539    case tags540    /// Attachment rows inserted, modified or removed (ids).541    case attachments(Set<String>)542    /// The ops queue changed.543    case queue544    case conflicts545    case reminders546    /// A meta key changed.547    case meta(String)548    /// Everything may have changed (wipe, or a change signalled from another process).549    case reset550    /// Rows of the generic `entities` table inserted, modified or removed (2.0).551    case entities(kind: String, ids: Set<String>)552    /// The entity outbox changed (2.0).553    case entityQueue554    /// Canvas rows changed (page ids) (2.0).555    case canvases(Set<String>)556    /// The cached events journal changed (2.0).557    case events558    /// A cached server read model changed (key) (2.0).559    case cache(String)560}561562/// Result of `purge`.563public struct PurgeResult: Sendable, Equatable {564    public var pageIds: [String] = []565    /// Relative paths of the attachment files of the purged pages: the caller deletes the files.566    public var orphanedFiles: [String] = []567}568
Files main
Menu

Theme