Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/ServiceModels.swift3// Description: Codable transfer objects of the attachment, session, passkey management, search, task, inbox, capture4// and health routes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Attachments1112/// Answer of `POST /api/attachments`.13public struct UploadedAttachment: Codable, Sendable, Equatable, Identifiable {14 public var id: String15 /// `/api/files/<id>` — the `src` to put in an image or file node.16 public var url: String17 public var name: String18 public var size: Int6419 public var mime: String20 public var hasText: Bool?21 /// Page count of a PDF.22 public var pages: Int?23}2425/// A row of `GET /api/attachments`.26public struct AttachmentInfo: Codable, Sendable, Equatable, Identifiable {27 public var id: String28 public var filename: String29 public var mime: String30 public var size: Int6431 public var pageId: String?32 public var pageCount: Int?33 public var createdAt: Date34 public var hasText: Bool?35 public var url: String?36}3738/// A finished download.39public struct DownloadedFile: Sendable, Equatable {40 public var fileURL: URL41 public var contentType: String?42 /// `Content-Length` announced by the server.43 public var expectedSize: Int64?44 /// File name of the `Content-Disposition` header, when present.45 public var suggestedFilename: String?46}4748// MARK: - Sessions4950/// Answer of `GET /api/auth/state`.51public struct AuthState: Codable, Sendable, Equatable {52 public var sessionId: String53 /// A passkey verification younger than `freshWindowMs` exists: sensitive operations are allowed.54 public var fresh: Bool55 public var verifiedAt: Date?56 public var freshWindowMs: Int?57 public var idleDays: Int?58 public var absoluteDays: Int?59 public var rpId: String?60 public var origins: [String]?61}6263public struct SessionInfo: Codable, Sendable, Equatable, Identifiable {64 public var id: String65 /// "SP Notes · iPhone", "Browser · Mac"…66 public var label: String?67 public var ip: String?68 public var createdAt: Date69 public var lastSeenAt: Date?70 public var expiresAt: Date?71 public var current: Bool72}7374public struct LoginResult: Codable, Sendable, Equatable {75 public var ok: Bool76 public var next: String?77}7879public struct ReauthResult: Codable, Sendable, Equatable {80 public var ok: Bool81 /// How long the session stays "fresh", in milliseconds.82 public var freshForMs: Int?83}8485public struct RevokeSessionsResult: Codable, Sendable, Equatable {86 public var ok: Bool87 public var revoked: Int?88}8990// MARK: - Passkey management9192public struct PasskeyInfo: Codable, Sendable, Equatable, Identifiable {93 public var id: String94 public var label: String?95 public var createdAt: Date?96 public var lastUsedAt: Date?97 public var synced: Bool?98 public var multiDevice: Bool?99 public var transports: [String]?100 /// The passkey that opened the current session.101 public var current: Bool?102}103104public struct PasskeyAdded: Codable, Sendable, Equatable {105 public var ok: Bool106 public var id: String107 public var label: String?108}109110// MARK: - Search111112public enum SearchMode: String, Sendable, CaseIterable {113 /// Title search, instant.114 case quick115 /// Keyword + semantic passages.116 case hybrid117}118119/// Parameters of `GET /api/search`.120public struct SearchQuery: Sendable, Equatable {121 public var text: String122 public var mode: SearchMode123 /// 1…60.124 public var limit: Int?125 /// `false` keeps the query on the server (no embedding provider call).126 public var semantic: Bool?127 public var section: PageSection?128 /// `YYYY-MM-DD`.129 public var since: String?130 /// `YYYY-MM-DD`.131 public var until: String?132 public var includeArchived: Bool133 /// Hybrid mode: restrict to these kinds (`SearchKind`: `page`, `entry`, `file`, `reference`). Set after `init`.134 public var kinds: [String]? = nil135 /// Hybrid mode: one hit per source (best passage, `SearchHit.more` = other matching passages) and matching136 /// bibliographic references appended. Set after `init`.137 public var group: Bool = false138139 public init(_ text: String, mode: SearchMode = .quick, limit: Int? = nil, semantic: Bool? = nil, section: PageSection? = nil, since: String? = nil, until: String? = nil, includeArchived: Bool = false) {140 self.text = text141 self.mode = mode142 self.limit = limit143 self.semantic = semantic144 self.section = section145 self.since = since146 self.until = until147 self.includeArchived = includeArchived148 }149}150151/// One search result. Quick mode fills `id`, `title`, `icon`, `type`, `section`, `updatedAt`; hybrid mode returns152/// passages (`pageId`, `heading`, `blockId`, `content`, `snippet`, `score`…). `raw` keeps the complete object.153public struct SearchHit: Decodable, Sendable, Equatable {154 /// Page id in quick mode.155 public var id: String?156 /// Page of the passage in hybrid mode.157 public var pageId: String?158 public var title: String?159 public var icon: String?160 public var type: String?161 public var section: String?162 public var kind: String?163 public var heading: String?164 public var blockId: String?165 public var content: String?166 /// Excerpt with matched terms between U+0001 and U+0002.167 public var snippet: String?168 public var score: Double?169 public var updatedAt: Date?170 public var raw: RawJSON171172 /// The page to open for this result.173 public var targetPageID: String? { pageId ?? id }174175 public init(from decoder: Decoder) throws {176 let value = try JSONValue(from: decoder)177 raw = value.raw()178 id = value["id"]?.stringValue179 pageId = value["pageId"]?.stringValue180 title = value["title"]?.stringValue181 icon = value["icon"]?.stringValue182 type = value["type"]?.stringValue183 section = value["section"]?.stringValue184 kind = value["kind"]?.stringValue185 heading = value["heading"]?.stringValue186 blockId = value["blockId"]?.stringValue187 content = value["content"]?.stringValue188 snippet = value["snippet"]?.stringValue189 score = value["score"]?.doubleValue190 updatedAt = value["updatedAt"]?.stringValue.flatMap(APIDate.parse)191 }192}193194// MARK: - Tasks195196public enum TaskPriority: String, Codable, Sendable, CaseIterable {197 case low, medium, high198}199200/// The priority of a server task under a name that collides with nothing (see `SPNotesDocument.TaskItemPriority`).201public typealias TaskRowPriority = TaskPriority202203public enum TaskStatus: String, Codable, Sendable, CaseIterable {204 /// `doing` is used by the research workspace (3.0).205 case todo, doing, done206}207208/// A task (reminder = a task with `pageId` and `dueAt`).209public struct TaskItem: Codable, Sendable, Equatable, Identifiable {210 public var id: String211 public var title: String212 /// `todo` or `done`.213 public var status: String214 /// `low`, `medium`, `high`.215 public var priority: String?216 public var dueAt: Date?217 public var completedAt: Date?218 public var project: String?219 public var pageId: String?220 public var createdAt: Date221 public var updatedAt: Date222 /// Only in the list.223 public var pageTitle: String?224 /// Only in the list.225 public var pageIcon: String?226 /// 3.0: block id of the `taskItem` the task is anchored to.227 public var blockId: String? = nil228 /// 3.0: soft-deleted tasks stay readable (`GET /api/tasks/<id>`, the feed, `?since=`).229 public var deletedAt: Date? = nil230 /// 3.0: change signal (see `SyncPage`).231 public var rev: Int64? = nil232233 public var isDone: Bool { status == TaskStatus.done.rawValue }234}235236/// Body of `POST /api/tasks`.237public struct TaskDraft: Encodable, Sendable, Equatable {238 public var title: String239 public var dueAt: Date?240 public var priority: TaskPriority?241 public var project: String?242 public var pageId: String?243 /// 3.0: client-chosen UUID; the creation is idempotent on it (`NotesAPI.createTaskIdempotent`).244 public var id: String?245 /// 3.0: block id of the `taskItem` the task is anchored to.246 public var blockId: String?247 /// 3.0: initial status (server default `todo`).248 public var status: TaskStatus?249 /// 3.0: a bare calendar day `YYYY-MM-DD`, sent as `due` (stored at 12:00 UTC); `dueAt` wins when both are set.250 public var due: String?251252 public init(title: String, dueAt: Date? = nil, priority: TaskPriority? = nil, project: String? = nil, pageId: String? = nil,253 id: String? = nil, blockId: String? = nil, status: TaskStatus? = nil, due: String? = nil) {254 self.title = title255 self.dueAt = dueAt256 self.priority = priority257 self.project = project258 self.pageId = pageId259 self.id = id260 self.blockId = blockId261 self.status = status262 self.due = due263 }264}265266/// Body of `PATCH /api/tasks`. Only the fields that are set are sent; `dueAt`, `project` and `pageId` can be cleared267/// with `.null`.268public struct TaskPatch: Encodable, Sendable, Equatable {269 public var id: String270 public var title: String?271 public var dueAt: PatchValue<Date>?272 public var status: TaskStatus?273 public var priority: TaskPriority?274 public var project: PatchValue<String>?275 public var pageId: PatchValue<String>?276277 public init(id: String, title: String? = nil, dueAt: PatchValue<Date>? = nil, status: TaskStatus? = nil, priority: TaskPriority? = nil, project: PatchValue<String>? = nil, pageId: PatchValue<String>? = nil) {278 self.id = id279 self.title = title280 self.dueAt = dueAt281 self.status = status282 self.priority = priority283 self.project = project284 self.pageId = pageId285 }286287 enum CodingKeys: String, CodingKey { case id, title, dueAt, status, priority, project, pageId }288289 public func encode(to encoder: Encoder) throws {290 var c = encoder.container(keyedBy: CodingKeys.self)291 try c.encode(id, forKey: .id)292 try c.encodeIfPresent(title, forKey: .title)293 try c.encodePatch(dueAt, forKey: .dueAt)294 try c.encodeIfPresent(status, forKey: .status)295 try c.encodeIfPresent(priority, forKey: .priority)296 try c.encodePatch(project, forKey: .project)297 try c.encodePatch(pageId, forKey: .pageId)298 }299}300301// MARK: - Inbox and capture302303/// A capture waiting in the inbox (`GET /api/inbox`).304public struct InboxItem: Codable, Sendable, Equatable, Identifiable {305 public var id: String306 public var title: String307 public var icon: String?308 public var kind: String?309 public var inboxAt: Date?310 public var updatedAt: Date?311 public var wordCount: Int?312 public var excerpt: String?313 public var tags: [String]?314 public var url: String?315 public var image: String?316 public var openTasks: Int?317}318319/// What to do with a capture (`POST /api/inbox/<id>`).320public enum InboxAction: Encodable, Sendable, Equatable {321 /// File it as a page (optionally in a section and under a parent).322 case keep(section: PageSection? = nil, parentId: PatchValue<String>? = nil)323 /// Turn it into a task.324 case task(dueAt: PatchValue<Date>? = nil, priority: TaskPriority? = nil)325 /// Add it as a row of a database.326 case database(databaseId: String)327 case reference328 case archive329 case trash330331 enum CodingKeys: String, CodingKey { case action, section, parentId, dueAt, priority, databaseId }332333 public func encode(to encoder: Encoder) throws {334 var c = encoder.container(keyedBy: CodingKeys.self)335 switch self {336 case .keep(let section, let parentId):337 try c.encode("keep", forKey: .action)338 try c.encodeIfPresent(section, forKey: .section)339 try c.encodePatch(parentId, forKey: .parentId)340 case .task(let dueAt, let priority):341 try c.encode("task", forKey: .action)342 try c.encodePatch(dueAt, forKey: .dueAt)343 try c.encodeIfPresent(priority, forKey: .priority)344 case .database(let databaseId):345 try c.encode("database", forKey: .action)346 try c.encode(databaseId, forKey: .databaseId)347 case .reference: try c.encode("reference", forKey: .action)348 case .archive: try c.encode("archive", forKey: .action)349 case .trash: try c.encode("trash", forKey: .action)350 }351 }352}353354public struct TriageResult: Codable, Sendable, Equatable {355 /// Give it to `undoInboxAction` to reverse the triage.356 public var actionId: String357 public var summary: String?358 /// What the action created (task id, row id…), as raw JSON.359 public var created: RawJSON?360}361362public struct UndoResult: Codable, Sendable, Equatable {363 public var ok: Bool364 /// The action had already been undone.365 public var already: Bool?366}367368public enum CaptureKind: String, Codable, Sendable, CaseIterable {369 case note, tasks, link, photo, file, audio370}371372/// Body of `POST /api/capture`.373public struct CaptureRequest: Encodable, Sendable, Equatable {374 public var kind: CaptureKind375 public var text: String?376 public var url: String?377 public var attachmentIds: [String]?378379 public init(kind: CaptureKind, text: String? = nil, url: String? = nil, attachmentIds: [String]? = nil) {380 self.kind = kind381 self.text = text382 self.url = url383 self.attachmentIds = attachmentIds384 }385}386387public struct CaptureResult: Codable, Sendable, Equatable, Identifiable {388 /// The page created in the inbox.389 public var id: String390 public var title: String391 public var kind: String392 public var inboxAt: Date?393}394395// MARK: - Health396397/// Answer of `GET /api/health` (public).398public struct Health: Codable, Sendable, Equatable {399 public var ok: Bool400 public var db: Bool?401 public var worker: Bool?402 public var passkeys: Bool?403 public var pgvector: Bool?404 public var version: String?405}406407extension TaskItem {408 /// True when the due date is a bare calendar day: the server stores those at 12:00:00 UTC.409 public var isBareDay: Bool {410 guard let dueAt else { return false }411 var utc = Calendar(identifier: .gregorian); utc.timeZone = TimeZone(identifier: "UTC")!412 let c = utc.dateComponents([.hour, .minute, .second, .nanosecond], from: dueAt)413 return c.hour == 12 && c.minute == 0 && c.second == 0 && (c.nanosecond ?? 0) < 1_000_000414 }415416 /// `YYYY-MM-DD` of the due day: the UTC date of a bare day, the day in `timeZone` of a date with a time; nil without a due date.417 public func dueDay(timeZone: TimeZone = .current) -> String? {418 guard let dueAt else { return nil }419 var calendar = Calendar(identifier: .gregorian); calendar.timeZone = isBareDay ? TimeZone(identifier: "UTC")! : timeZone420 let c = calendar.dateComponents([.year, .month, .day], from: dueAt)421 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 1, c.day ?? 1)422 }423}424