SPB Git

Repository Public

NotesAPI+Research.swift 19.6 KB 316 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/NotesAPI+Research.swift3// Description: The research routes: references (client ids, extracts, links, DOI, BibTeX), experiments, research4//              tasks, working papers, overview, and the LaTeX export of the AI workstream.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NotesAPI {11    private static func ref(_ id: String, _ tail: String = "") -> String { "/api/research/references/\(segment(id))\(tail)" }1213    // MARK: - References1415    /// `GET /api/research/references[?pageId=]` — the references of a page, or the whole library (live ones).16    public func references(pageID: String? = nil) async throws -> [ResearchReference] {17        try await client.decode([ResearchReference].self, .get("/api/research/references", query: Self.item("pageId", pageID)))18    }1920    /// `GET /api/research/references?projectId=` — the references of a project: attached to any of its pages or21    /// cited in its text (AI workstream). **A server without the AI workstream ignores the parameter and answers the22    /// whole library.**23    public func references(projectID: String) async throws -> [ResearchReference] {24        try await client.decode([ResearchReference].self, .get("/api/research/references", query: [URLQueryItem(name: "projectId", value: projectID)]))25    }2627    /// `GET /api/research/references?ids=a,b` (≤ 200) — exactly those references, to resolve `citation` nodes; each28    /// gains `label` and `citation` (AI workstream). The answer is filtered to the ids asked for, so it is also29    /// right against a server that ignores `ids`. Errors: `400 bad_id | too_many_ids`.30    public func references(ids: [String]) async throws -> ReferenceLookup {31        guard !ids.isEmpty else { return ReferenceLookup(references: [], missingIDs: []) }32        let response = try await client.send(.get("/api/research/references", query: [URLQueryItem(name: "ids", value: ids.joined(separator: ","))]))33        let wanted = Set(ids.map { $0.lowercased() })34        let found = try response.decode([ResearchReference].self).filter { wanted.contains($0.id.lowercased()) }35        let missing: [String]36        if let header = response.header("x-missing-ids") {37            missing = header.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }38        } else {39            let have = Set(found.map { $0.id.lowercased() })40            missing = ids.filter { !have.contains($0.lowercased()) }41        }42        return ReferenceLookup(references: found, missingIDs: missing)43    }4445    /// `POST /api/research/references` → 201. Idempotent on `draft.id`: the stored reference comes back untouched46    /// (201 again, no `x-existing`), even when it was deleted meanwhile (`deletedAt` set — it is not resurrected).47    public func createReference(_ draft: ReferenceDraft, idempotencyKey: String? = nil) async throws -> ResearchReference {48        try await client.decode(ResearchReference.self, .json(.post, "/api/research/references", body: draft, idempotencyKey: idempotencyKey))49    }5051    /// `GET /api/research/references/<id>` — `404 not_found` for an unknown **or deleted** reference.52    public func reference(id: String) async throws -> ResearchReference {53        try await client.decode(ResearchReference.self, .get(Self.ref(id)))54    }5556    /// `PATCH /api/research/references/<id>`. A `citeKey` already used is silently de-duplicated by the server57    /// (read the key of the answer).58    public func updateReference(id: String, _ changes: ReferenceChanges, idempotencyKey: String? = nil) async throws -> ResearchReference {59        try await client.decode(ResearchReference.self, .json(.patch, Self.ref(id), body: changes, idempotencyKey: idempotencyKey))60    }6162    /// `DELETE /api/research/references/<id>` — soft delete, idempotent (200 again).63    @discardableResult64    public func deleteReference(id: String, idempotencyKey: String? = nil) async throws -> OKResult {65        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: Self.ref(id), idempotencyKey: idempotencyKey))66    }6768    private func referenceAction(_ id: String, _ action: String, body: Data? = nil, idempotencyKey: String? = nil) async throws -> ResearchReference {69        let request = HTTPRequest(method: .post, path: Self.ref(id), query: [URLQueryItem(name: "action", value: action)], body: body,70                                  contentType: body == nil ? nil : "application/json", idempotencyKey: idempotencyKey)71        return try await client.decode(ResearchReference.self, request)72    }7374    /// `POST /api/research/references/<id>?action=restore` — undo of a delete.75    public func restoreReference(id: String, idempotencyKey: String? = nil) async throws -> ResearchReference {76        try await referenceAction(id, "restore", idempotencyKey: idempotencyKey)77    }7879    private struct AttachBody: Encodable {80        var attachmentId: String?81        func encode(to encoder: Encoder) throws {82            var c = encoder.container(keyedBy: AnyKey.self)83            if let attachmentId { try c.encode(attachmentId, forKey: AnyKey("attachmentId")) } else { try c.encodeNil(forKey: AnyKey("attachmentId")) }84        }85    }8687    /// `POST /api/research/references/<id>?action=attach` `{ attachmentId | null }` — sets or removes the PDF.88    /// `404 not_found` for an unknown attachment.89    public func attachReferencePDF(id: String, attachmentID: String?, idempotencyKey: String? = nil) async throws -> ResearchReference {90        let body = try APIJSON.encoder().encode(AttachBody(attachmentId: attachmentID))91        return try await referenceAction(id, "attach", body: body, idempotencyKey: idempotencyKey)92    }9394    /// `POST /api/research/references/<id>?action=verify` — checks the reference against Crossref by its DOI95    /// (network, no model). `400 invalid_doi` without DOI; `doi_not_found`, `crossref_unreachable`.96    public func verifyReference(id: String) async throws -> ResearchReference {97        try await referenceAction(id, "verify")98    }99100    /// `GET /api/research/references/<id>/links` — the page it is attached to, the pages citing it, its PDF.101    public func referenceLinks(id: String) async throws -> ReferenceLinks {102        try await client.decode(ReferenceLinks.self, .get(Self.ref(id, "/links")))103    }104105    // MARK: - Extracts106107    /// `GET /api/research/references/<id>/extracts`.108    public func referenceExtracts(referenceID: String) async throws -> [ReferenceExtract] {109        try await client.decode([ReferenceExtract].self, .get(Self.ref(referenceID, "/extracts")))110    }111112    /// `POST /api/research/references/<id>/extracts` → 201. Idempotent on `draft.id`.113    public func addReferenceExtract(referenceID: String, _ draft: ReferenceExtractDraft, idempotencyKey: String? = nil) async throws -> ReferenceExtractChange {114        try await client.decode(ReferenceExtractChange.self, .json(.post, Self.ref(referenceID, "/extracts"), body: draft, idempotencyKey: idempotencyKey))115    }116117    private struct ExtractPatchBody: Encodable {118        var id: String119        var changes: ReferenceExtractChanges120        enum CodingKeys: String, CodingKey { case id, quote, page, note }121        func encode(to encoder: Encoder) throws {122            var c = encoder.container(keyedBy: CodingKeys.self)123            try c.encode(id, forKey: .id)124            try c.encodeIfPresent(changes.quote, forKey: .quote)125            try c.encodePatch(changes.page, forKey: .page)126            try c.encodePatch(changes.note, forKey: .note)127        }128    }129130    /// `PATCH /api/research/references/<id>/extracts` `{ id, quote?, page?, note? }`.131    public func updateReferenceExtract(referenceID: String, extractID: String, _ changes: ReferenceExtractChanges, idempotencyKey: String? = nil) async throws -> ReferenceExtractChange {132        try await client.decode(ReferenceExtractChange.self, .json(.patch, Self.ref(referenceID, "/extracts"), body: ExtractPatchBody(id: extractID, changes: changes), idempotencyKey: idempotencyKey))133    }134135    /// `DELETE /api/research/references/<id>/extracts?extractId=` — the removed extract comes back (`extract`), to136    /// offer an undo; `extract` is nil when there was nothing to remove.137    public func deleteReferenceExtract(referenceID: String, extractID: String, idempotencyKey: String? = nil) async throws -> ReferenceExtractChange {138        try await client.decode(ReferenceExtractChange.self, HTTPRequest(method: .delete, path: Self.ref(referenceID, "/extracts"), query: [URLQueryItem(name: "extractId", value: extractID)], idempotencyKey: idempotencyKey))139    }140141    private struct ExtractRestoreBody: Encodable { var extract: ReferenceExtract }142143    /// `POST /api/research/references/<id>/extracts?restore=1` `{ extract }` — puts a deleted extract back as it was.144    public func restoreReferenceExtract(referenceID: String, _ extract: ReferenceExtract, idempotencyKey: String? = nil) async throws -> ReferenceExtractChange {145        try await client.decode(ReferenceExtractChange.self, .json(.post, Self.ref(referenceID, "/extracts"), query: [URLQueryItem(name: "restore", value: "1")], body: ExtractRestoreBody(extract: extract), idempotencyKey: idempotencyKey))146    }147148    // MARK: - DOI149150    /// `GET /api/research/references/doi?doi=` — preview of a DOI through Crossref (network, no model; nothing is151    /// saved). Errors: `400 invalid_doi`, `404 doi_not_found`, `crossref_unreachable`.152    public func lookupDOI(_ doi: String) async throws -> DOILookup {153        try await client.decode(DOILookup.self, .get("/api/research/references/doi", query: [URLQueryItem(name: "doi", value: doi)]))154    }155156    private struct DOIBody: Encodable {157        var doi: String158        var pageId: String?159    }160161    /// `POST /api/research/references/doi` `{ doi, pageId? }` — adds the reference from Crossref (201), or returns162    /// the stored one when the DOI is already in the library (200, `duplicate`).163    public func addReferenceByDOI(_ doi: String, pageID: String? = nil, idempotencyKey: String? = nil) async throws -> DOIAddResult {164        try await client.decode(DOIAddResult.self, .json(.post, "/api/research/references/doi", body: DOIBody(doi: doi, pageId: pageID), idempotencyKey: idempotencyKey))165    }166167    // MARK: - BibTeX168169    private struct BibTeXBody: Encodable {170        var text: String171        var pageId: String?172        var dryRun: Bool?173    }174175    /// `POST /api/research/references/import-bibtex` `{ text, pageId?, dryRun? }` (≤ 20 MB). `dryRun` analyses176    /// without writing. `400 bibtex_empty`, `413 file_too_large`.177    public func importBibTeX(text: String, pageID: String? = nil, dryRun: Bool = false, idempotencyKey: String? = nil) async throws -> BibTeXImportResult {178        try await client.decode(BibTeXImportResult.self, .json(.post, "/api/research/references/import-bibtex", body: BibTeXBody(text: text, pageId: pageID, dryRun: dryRun ? true : nil), idempotencyKey: idempotencyKey))179    }180181    /// `POST /api/research/references/import-bibtex` (multipart `file`, ≤ 20 MB), streamed from disk.182    /// `415 type_mismatch` for a binary file.183    public func importBibTeX(fileURL: URL, pageID: String? = nil, dryRun: Bool = false) async throws -> BibTeXImportResult {184        let form = MultipartForm()185        var fields: [MultipartForm.Field] = []186        if let pageID { fields.append(.init("pageId", pageID)) }187        if dryRun { fields.append(.init("dryRun", "1")) }188        let body = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-bib-\(UUID().uuidString).multipart")189        defer { try? FileManager.default.removeItem(at: body) }190        try form.write(fields: fields, fileField: "file", filename: fileURL.lastPathComponent, mimeType: "application/x-bibtex", source: fileURL, to: body)191        let response = try await client.upload(HTTPRequest(method: .post, path: "/api/research/references/import-bibtex", contentType: form.contentType), fromFile: body)192        return try response.decode(BibTeXImportResult.self)193    }194195    /// `GET /api/research/references/export.bib[?pageId=|projectId=]&inline=1` — the references of a page, of a196    /// project (AI workstream; ignored by an older server, which then exports the whole library) or the library.197    public func exportBibTeX(pageID: String? = nil, projectID: String? = nil) async throws -> BibTeXExport {198        let query = Self.item("pageId", pageID) + Self.item("projectId", projectID)199        let (text, response) = try await text(.get("/api/research/references/export.bib", query: query), accept: "application/x-bibtex, text/plain")200        return BibTeXExport(text: text, count: response.header("x-export-count").flatMap(Int.init),201                            suggestedFilename: response.header("content-disposition").flatMap(Self.filename(fromContentDisposition:)))202    }203204    // MARK: - Experiments205206    /// `GET /api/research/experiments[?pageId=]`.207    public func experiments(pageID: String? = nil) async throws -> [ResearchExperiment] {208        try await client.decode([ResearchExperiment].self, .get("/api/research/experiments", query: Self.item("pageId", pageID)))209    }210211    /// `POST /api/research/experiments` → 201 (no client id: use an idempotency key for retries).212    public func createExperiment(_ draft: ExperimentDraft, idempotencyKey: String? = nil) async throws -> ResearchExperiment {213        try await client.decode(ResearchExperiment.self, .json(.post, "/api/research/experiments", body: draft, idempotencyKey: idempotencyKey))214    }215216    /// `PATCH /api/research/experiments/<id>` — `404` (no code) when unknown.217    public func updateExperiment(id: String, _ changes: ExperimentChanges, idempotencyKey: String? = nil) async throws -> ResearchExperiment {218        try await client.decode(ResearchExperiment.self, .json(.patch, "/api/research/experiments/\(Self.segment(id))", body: changes, idempotencyKey: idempotencyKey))219    }220221    /// `DELETE /api/research/experiments/<id>` — permanent; answers 200 even for an unknown id.222    @discardableResult223    public func deleteExperiment(id: String, idempotencyKey: String? = nil) async throws -> OKResult {224        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/research/experiments/\(Self.segment(id))", idempotencyKey: idempotencyKey))225    }226227    // MARK: - Research tasks228229    /// `GET /api/research/tasks?pageId=` — every live task of a research page (done ones included).230    public func researchTasks(pageID: String) async throws -> [TaskItem] {231        try await client.decode([TaskItem].self, .get("/api/research/tasks", query: [URLQueryItem(name: "pageId", value: pageID)]))232    }233234    private struct ResearchTaskBody: Encodable {235        var pageId: String236        var draft: ResearchTaskDraft237        enum CodingKeys: String, CodingKey { case pageId }238        func encode(to encoder: Encoder) throws {239            try draft.encode(to: encoder)240            var c = encoder.container(keyedBy: CodingKeys.self)241            try c.encode(pageId, forKey: .pageId)242        }243    }244245    /// `POST /api/research/tasks` `{ pageId, title, … }` → 201.246    public func createResearchTask(pageID: String, _ draft: ResearchTaskDraft, idempotencyKey: String? = nil) async throws -> TaskItem {247        try await client.decode(TaskItem.self, .json(.post, "/api/research/tasks", body: ResearchTaskBody(pageId: pageID, draft: draft), idempotencyKey: idempotencyKey))248    }249250    private struct ResearchTasksBody: Encodable {251        var pageId: String252        var items: [ResearchTaskDraft]253    }254255    /// `POST /api/research/tasks` `{ pageId, items }` (1…50) → 201 — e.g. the tasks accepted from an AI plan.256    public func createResearchTasks(pageID: String, _ drafts: [ResearchTaskDraft], idempotencyKey: String? = nil) async throws -> [TaskItem] {257        try await client.decode([TaskItem].self, .json(.post, "/api/research/tasks", body: ResearchTasksBody(pageId: pageID, items: drafts), idempotencyKey: idempotencyKey))258    }259260    /// `POST /api/research/tasks/<id>?action=restore` — undo of a task deletion (also for tasks deleted through261    /// `/api/tasks`: it is the only route that restores a task).262    public func restoreTask(id: String, idempotencyKey: String? = nil) async throws -> TaskItem {263        try await client.decode(TaskItem.self, HTTPRequest(method: .post, path: "/api/research/tasks/\(Self.segment(id))", query: [URLQueryItem(name: "action", value: "restore")], idempotencyKey: idempotencyKey))264    }265266    // MARK: - Working papers267268    private struct PaperBody: Encodable {269        var title: String?270        var status: String?271        var venue: String?272    }273274    /// `POST /api/research/papers` → 201 — a new research page with the working-paper template (`status` =275    /// `PaperStatus`, server default `planning`). The page has a server-chosen id: use an idempotency key for retries.276    public func createWorkingPaper(title: String? = nil, status: String? = nil, venue: String? = nil, idempotencyKey: String? = nil) async throws -> Page {277        try await client.decode(Page.self, .json(.post, "/api/research/papers", body: PaperBody(title: title, status: status, venue: venue), idempotencyKey: idempotencyKey))278    }279280    /// `GET /api/research/overview` — the working papers tracker: every research page with its counters.281    public func researchOverview() async throws -> [ResearchPaperOverview] {282        try await client.decode([ResearchPaperOverview].self, .get("/api/research/overview"))283    }284285    // MARK: - LaTeX export (API-NEXT-AI §8.1)286287    private static func texQuery(_ projectID: String, _ format: String?) -> [URLQueryItem] {288        [URLQueryItem(name: "projectId", value: projectID)] + item("format", format) + [URLQueryItem(name: "inline", value: "1")]289    }290291    /// `GET /api/research/export.tex?projectId=&inline=1` — the LaTeX skeleton of a project (the page and its292    /// descendants), with the export report. No model involved. A server without the AI workstream has no such293    /// route (`APIError.isRouteMissing`). Errors: `400 bad_id`, `404 not_found`.294    public func exportLaTeX(projectID: String) async throws -> LaTeXExport {295        let (tex, response) = try await text(.get("/api/research/export.tex", query: Self.texQuery(projectID, nil)), accept: "application/x-tex, text/plain")296        let report = response.header("x-export-report").flatMap { try? APIJSON.decoder().decode(LaTeXExportReport.self, from: Data($0.utf8)) }297        return LaTeXExport(tex: tex, report: report, bibURL: response.header("x-bib-url"),298                           suggestedFilename: response.header("content-disposition").flatMap(Self.filename(fromContentDisposition:)))299    }300301    /// `GET /api/research/export.tex?projectId=&format=json` — the export with its `.bib` and diagnostics.302    public func exportLaTeXBundle(projectID: String) async throws -> LaTeXExportBundle {303        try await client.decode(LaTeXExportBundle.self, .get("/api/research/export.tex", query: Self.texQuery(projectID, "json")))304    }305306    /// `GET /api/research/export.tex?projectId=&format=zip` — `main.tex`, `references.bib`, `figures/` and307    /// `export-report.json`, streamed to `destination`.308    public func downloadLaTeXArchive(projectID: String, to destination: URL, progress: TransferProgressHandler? = nil) async throws -> DownloadedFile {309        var request = HTTPRequest.get("/api/research/export.tex", query: [URLQueryItem(name: "projectId", value: projectID), URLQueryItem(name: "format", value: "zip")])310        request.accept = "application/zip"311        let response = try await client.download(request, to: destination, progress: progress)312        return DownloadedFile(fileURL: destination, contentType: response.contentType, expectedSize: response.header("content-length").flatMap(Int64.init),313                              suggestedFilename: response.header("content-disposition").flatMap(Self.filename(fromContentDisposition:)))314    }315}316
Files main
Menu

Theme