adoor 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +2 -2
  3. package/dist/adoor.mjs +105 -84
  4. package/native/LICENSE +662 -0
  5. package/native/README.md +12 -0
  6. package/native/darwin/ADoorService.app/Contents/Info.plist +57 -0
  7. package/native/darwin/ADoorService.app/Contents/MacOS/ADoorService +0 -0
  8. package/native/darwin/ADoorService.app/Contents/PkgInfo +1 -0
  9. package/native/darwin/ADoorService.app/Contents/_CodeSignature/CodeResources +123 -0
  10. package/native/darwin/ADoorService.app/Contents/embedded.provisionprofile +0 -0
  11. package/native/source/Package.swift +6 -0
  12. package/native/source/sdk/LICENSE +21 -0
  13. package/native/source/sdk/Package.swift +14 -0
  14. package/native/source/sdk/Sources/ADoor/AdoorClient.swift +270 -0
  15. package/native/source/sdk/Sources/ADoor/AdoorError.swift +60 -0
  16. package/native/source/sdk/Sources/ADoor/Changes.swift +202 -0
  17. package/native/source/sdk/Sources/ADoor/DesktopSessionState.swift +73 -0
  18. package/native/source/sdk/Sources/ADoor/DeviceFlow.swift +70 -0
  19. package/native/source/sdk/Sources/ADoor/FolderCatalog.swift +49 -0
  20. package/native/source/sdk/Sources/ADoor/JSONValue.swift +70 -0
  21. package/native/source/sdk/Sources/ADoor/LocalStore.swift +474 -0
  22. package/native/source/sdk/Sources/ADoor/Models.swift +146 -0
  23. package/native/source/sdk/Sources/ADoor/MountModel.swift +896 -0
  24. package/native/source/sdk/Sources/ADoor/OAuth.swift +225 -0
  25. package/native/source/sdk/Sources/ADoor/Provider.swift +211 -0
  26. package/native/source/sdk/Sources/ADoor/Storage.swift +41 -0
  27. package/native/source/sdk/Sources/ADoor/SyncTree.swift +501 -0
  28. package/native/source/sdk/Sources/ADoor/Trash.swift +283 -0
  29. package/native/source/sdk/Tests/ADoorTests/ADoorTests.swift +182 -0
  30. package/native/source/sdk/Tests/ADoorTests/DesktopSessionStateTests.swift +46 -0
  31. package/native/source/sdk/Tests/ADoorTests/MountTests.swift +560 -0
  32. package/native/source/sdk/Tests/ADoorTests/RegressionTests.swift +360 -0
  33. package/native/source/service/DesktopSession.swift +241 -0
  34. package/native/source/service/DeviceClient.swift +53 -0
  35. package/native/source/service/Domains.swift +182 -0
  36. package/native/source/service/FolderRefresh.swift +37 -0
  37. package/native/source/service/KeychainStore.swift +74 -0
  38. package/native/source/service/LocalSessionSocket.swift +142 -0
  39. package/native/source/service/ServiceMain.swift +14 -0
  40. package/native/source/service/ServiceMounts.swift +34 -0
  41. package/package.json +12 -3
@@ -0,0 +1,896 @@
1
+ import Foundation
2
+
3
+ /// Inline file ceiling and slice size. They match the file layout the server already commits.
4
+ public enum MountLayout {
5
+ public static let inlineBytes = 32 * 1024
6
+ public static let sliceBytes = 4 * 1024 * 1024
7
+ public static let shardSlots = 256
8
+ }
9
+
10
+ /// Names that stay on this Mac. A component with one of these names is never sent to the server.
11
+ public enum MountExcludes {
12
+ public static let defaults: Set<String> = [".git", ".env", "node_modules"]
13
+
14
+ public static func excluded(_ relativePath: String, names: Set<String> = defaults) -> Bool {
15
+ let parts = relativePath.split(separator: "/").map(String.init)
16
+ return parts.contains { names.contains($0) }
17
+ }
18
+ }
19
+
20
+ public struct FolderAccess: Equatable, Sendable {
21
+ public let canRead: Bool
22
+ public let canWrite: Bool
23
+
24
+ public init(canRead: Bool, canWrite: Bool) {
25
+ self.canRead = canRead
26
+ self.canWrite = canWrite
27
+ }
28
+
29
+ /// Mode bits are a projection of this connection. They are not a grant.
30
+ public init(mode: Int) {
31
+ canRead = mode & 0o444 != 0
32
+ canWrite = mode & 0o222 != 0
33
+ }
34
+
35
+ public var token: String {
36
+ if canRead && canWrite { return "read-write" }
37
+ if canRead { return "read" }
38
+ return "none"
39
+ }
40
+
41
+ public var readLabel: String { canRead ? "Read" : "No read" }
42
+ public var writeLabel: String { canWrite ? "Write" : "No write" }
43
+
44
+ public var sentence: String {
45
+ if canRead && canWrite { return "You can read and write" }
46
+ if canRead { return "You can read" }
47
+ return "You cannot read this folder"
48
+ }
49
+ }
50
+
51
+ public enum NodeKind: String, Equatable, Sendable, Codable {
52
+ case file
53
+ case directory
54
+ case symlink
55
+ }
56
+
57
+ public struct NodeAttr: Equatable, Sendable, Identifiable {
58
+ public let id: UUID
59
+ public var name: String
60
+ public var kind: NodeKind
61
+ public var size: Int
62
+ public var generation: Int
63
+ public var mode: Int
64
+ public var mtime: Date
65
+ public var contentId: String?
66
+
67
+ public var parentID: UUID?
68
+
69
+ public var idString: String { id.uuidString.lowercased() }
70
+ public var access: FolderAccess { FolderAccess(mode: mode) }
71
+
72
+ public init(id: UUID, name: String, kind: NodeKind, size: Int, generation: Int, mode: Int, mtime: Date, contentId: String? = nil) {
73
+ self.id = id
74
+ self.name = name
75
+ self.kind = kind
76
+ self.size = size
77
+ self.generation = generation
78
+ self.mode = mode
79
+ self.mtime = mtime
80
+ self.contentId = contentId
81
+ self.parentID = nil
82
+ }
83
+ }
84
+
85
+ public struct RemotePage: Equatable, Sendable {
86
+ public var directoryId: UUID
87
+ public var entries: [NodeAttr]
88
+ public var nextCursor: String?
89
+ }
90
+
91
+ public struct RemoteFile: Equatable, Sendable {
92
+ public var node: NodeAttr
93
+ public var bytes: Data
94
+ }
95
+
96
+ public enum LeaseAnswer: Equatable, Sendable {
97
+ case unsupported
98
+ case held(id: String, ttl: TimeInterval)
99
+ case denied
100
+ }
101
+
102
+ /// `fs.lease` and `fs.resume` are not operations on main. Callers pass `.unsupported` until they are.
103
+ public struct LeaseMachine: Equatable, Sendable {
104
+ public enum Phase: Equatable, Sendable {
105
+ case idle
106
+ case localOnly
107
+ case held(id: String, renewAfter: Date)
108
+ case denied
109
+ }
110
+
111
+ public private(set) var phase: Phase
112
+
113
+ public init(phase: Phase = .idle) { self.phase = phase }
114
+
115
+ public mutating func begin(_ answer: LeaseAnswer, now: Date) {
116
+ phase = Self.apply(answer, now: now)
117
+ }
118
+
119
+ public mutating func resume(_ answer: LeaseAnswer, now: Date) {
120
+ phase = Self.apply(answer, now: now)
121
+ }
122
+
123
+ public func needsRenewal(now: Date) -> Bool {
124
+ if case .held(_, let renewAfter) = phase { return now >= renewAfter }
125
+ return false
126
+ }
127
+
128
+ private static func apply(_ answer: LeaseAnswer, now: Date) -> Phase {
129
+ switch answer {
130
+ case .unsupported: return .localOnly
131
+ case .denied: return .denied
132
+ case .held(let id, let ttl):
133
+ let seconds = max(1, ttl)
134
+ return .held(id: id, renewAfter: now.addingTimeInterval(seconds / 2))
135
+ }
136
+ }
137
+ }
138
+
139
+ public struct BlockCache: Sendable {
140
+ private var order: [String] = []
141
+ private var values: [String: Data] = [:]
142
+ private let capacity: Int
143
+
144
+ public init(capacity: Int) { self.capacity = max(1, capacity) }
145
+
146
+ public func get(_ key: String) -> Data? { values[key] }
147
+
148
+ public mutating func set(_ key: String, _ data: Data) {
149
+ if values[key] != nil { order.removeAll { $0 == key } }
150
+ values[key] = data
151
+ order.append(key)
152
+ while order.count > capacity {
153
+ let oldest = order.removeFirst()
154
+ values.removeValue(forKey: oldest)
155
+ }
156
+ }
157
+
158
+ public mutating func removeAll() {
159
+ order.removeAll()
160
+ values.removeAll()
161
+ }
162
+ }
163
+
164
+ public struct StatCache: Equatable, Sendable {
165
+ private var nodes: [String: Int] = [:]
166
+
167
+ public init() {}
168
+
169
+ public mutating func store(inodeId: String, generation: Int) { nodes[inodeId] = generation }
170
+
171
+ public func generation(inodeId: String) -> Int? { nodes[inodeId] }
172
+
173
+ /// A change for this inode drops the cached generation. The next read asks the server again.
174
+ public mutating func invalidate(inodeId: String) { nodes.removeValue(forKey: inodeId) }
175
+
176
+ public mutating func invalidateAll() { nodes.removeAll() }
177
+ }
178
+
179
+ public enum ConflictChoice: String, Equatable, Sendable {
180
+ case mine
181
+ case server
182
+ }
183
+
184
+ public struct ConflictCopy: Equatable, Sendable, Identifiable {
185
+ public let id: String
186
+ public let inodeId: String
187
+ public let baseGeneration: Int
188
+ public let originalName: String
189
+ public let copyName: String
190
+ public let localBytes: Data
191
+
192
+ public init(id: String, inodeId: String, baseGeneration: Int, originalName: String, copyName: String, localBytes: Data) {
193
+ self.id = id
194
+ self.inodeId = inodeId
195
+ self.baseGeneration = baseGeneration
196
+ self.originalName = originalName
197
+ self.copyName = copyName
198
+ self.localBytes = localBytes
199
+ }
200
+ }
201
+
202
+ public enum ConflictName {
203
+ public static func make(original: String, id: String) -> String {
204
+ let short = String(id.prefix(4))
205
+ guard let dot = original.lastIndex(of: "."), dot != original.startIndex else {
206
+ return "\(original) (conflict \(short))"
207
+ }
208
+ let base = original[..<dot]
209
+ let ext = original[dot...]
210
+ return "\(base) (conflict \(short))\(ext)"
211
+ }
212
+ }
213
+
214
+ public struct PackedFile: Equatable, Sendable {
215
+ public let contentSha: String
216
+ public let size: Int
217
+ public let manifestHex: String
218
+ public let objects: [(sha: String, body: Data)]
219
+
220
+ public static func == (lhs: PackedFile, rhs: PackedFile) -> Bool {
221
+ lhs.contentSha == rhs.contentSha && lhs.size == rhs.size && lhs.manifestHex == rhs.manifestHex
222
+ && lhs.objects.map(\.sha) == rhs.objects.map(\.sha)
223
+ }
224
+ }
225
+
226
+ public enum FilePacker {
227
+ public static func sha256Hex(_ data: Data) -> String {
228
+ SHA256.hash(data).map { String(format: "%02x", $0) }.joined()
229
+ }
230
+
231
+ /// Fixed 4 MiB slices and shards of 256 slice hashes. The root manifest is the shard hashes.
232
+ public static func pack(_ body: Data) -> PackedFile? {
233
+ guard body.count > MountLayout.inlineBytes else { return nil }
234
+ var slices: [(sha: String, body: Data)] = []
235
+ var offset = 0
236
+ while offset < body.count {
237
+ let end = min(body.count, offset + MountLayout.sliceBytes)
238
+ let part = body.subdata(in: offset..<end)
239
+ slices.append((sha256Hex(part), part))
240
+ offset = end
241
+ }
242
+ var shards: [(sha: String, body: Data)] = []
243
+ var index = 0
244
+ while index < slices.count {
245
+ let end = min(slices.count, index + MountLayout.shardSlots)
246
+ var packed = Data()
247
+ for slice in slices[index..<end] {
248
+ packed.append(Data(hex: slice.sha) ?? Data())
249
+ }
250
+ shards.append((sha256Hex(packed), packed))
251
+ index = end
252
+ }
253
+ var manifest = Data()
254
+ for shard in shards { manifest.append(Data(hex: shard.sha) ?? Data()) }
255
+ return PackedFile(
256
+ contentSha: sha256Hex(body), size: body.count, manifestHex: manifest.hex,
257
+ objects: slices + shards)
258
+ }
259
+ }
260
+
261
+ public enum TreeError: Error, Equatable {
262
+ case notFound
263
+ case access
264
+ case conflict
265
+ case readOnly
266
+ case notEmpty
267
+ case crossSpace
268
+ case unsupported
269
+ case noSpace
270
+ case unavailable(String)
271
+ case invalid
272
+ case stale
273
+ }
274
+
275
+ extension TreeError {
276
+ public init(adoor: AdoorError) {
277
+ switch adoor.code {
278
+ case "NOT_FOUND", "FILE_NOT_FOUND": self = .notFound
279
+ case "NO_MATCHING_GRANT", "FORBIDDEN", "INACTIVE_AUTHORITY", "UNAUTHORIZED": self = .access
280
+ case "CONFLICT": self = .conflict
281
+ case "NOT_EMPTY": self = .notEmpty
282
+ case "CROSS_SPACE": self = .crossSpace
283
+ case "UNSUPPORTED", "ENDPOINT_UNAVAILABLE": self = .unsupported
284
+ case "PAYLOAD_TOO_LARGE": self = .noSpace
285
+ default:
286
+ if adoor.status == 401 || adoor.status == 403 { self = .access }
287
+ else if adoor.status == 404 { self = .notFound }
288
+ else if adoor.status == 409 { self = .conflict }
289
+ else { self = .unavailable(adoor.code) }
290
+ }
291
+ }
292
+ }
293
+
294
+ public protocol FileRemote: Sendable {
295
+ func stat(spaceId: String, path: String?, inodeId: String?) async throws -> NodeAttr
296
+ func list(spaceId: String, inodeId: String, cursor: String?) async throws -> RemotePage
297
+ func readInline(spaceId: String, inodeId: String) async throws -> Data
298
+ func writeInline(
299
+ spaceId: String, path: String?, name: String?, inodeId: String?, bytes: Data,
300
+ expectedGeneration: Int?, idempotencyKey: String
301
+ ) async throws -> NodeAttr
302
+ func mkdir(spaceId: String, parentId: String, name: String) async throws -> NodeAttr
303
+ func rename(spaceId: String, inodeId: String, name: String, expectedGeneration: Int, parentId: String?) async throws -> NodeAttr
304
+ func remove(spaceId: String, inodeId: String, expectedGeneration: Int) async throws
305
+ func commitSlices(
306
+ spaceId: String, inodeId: String?, path: String?, name: String?, expectedGeneration: Int?, packed: PackedFile
307
+ ) async throws -> NodeAttr
308
+ }
309
+
310
+ public protocol FileBytePlane: Sendable {
311
+ func readRange(spaceId: String, inodeId: String, offset: Int, length: Int) async throws -> Data
312
+ func putSlice(spaceId: String, sha256: String, body: Data) async throws
313
+ }
314
+
315
+ public protocol MountLeasePlane: Sendable {
316
+ func acquire(spaceId: String, path: String) async throws -> LeaseAnswer
317
+ func resume(id: String) async throws -> LeaseAnswer
318
+ }
319
+
320
+ /// Long-poll `GET /api/changes/poll` is not on main. The live feed is `GET /api/changes/stream`.
321
+ public protocol ChangePoll: Sendable {
322
+ func poll(after: String) async throws -> [FileChange]
323
+ }
324
+
325
+ public struct UnavailableBytePlane: FileBytePlane {
326
+ public init() {}
327
+ public func readRange(spaceId: String, inodeId: String, offset: Int, length: Int) async throws -> Data {
328
+ throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "GET /api/fs/read is not on this server.", status: 501)
329
+ }
330
+ public func putSlice(spaceId: String, sha256: String, body: Data) async throws {
331
+ throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "PUT /api/fs/objects is not on this server.", status: 501)
332
+ }
333
+ }
334
+
335
+ public struct UnavailableLeasePlane: MountLeasePlane {
336
+ public init() {}
337
+ public func acquire(spaceId: String, path: String) async throws -> LeaseAnswer { .unsupported }
338
+ public func resume(id: String) async throws -> LeaseAnswer { .unsupported }
339
+ }
340
+
341
+ public struct UnavailableChangePoll: ChangePoll {
342
+ public init() {}
343
+ public func poll(after: String) async throws -> [FileChange] {
344
+ throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "GET /api/changes/poll is not on this server.", status: 501)
345
+ }
346
+ }
347
+
348
+ public struct FileChange: Equatable, Sendable {
349
+ public let cursor: String
350
+ public let inodeId: String
351
+ public let type: String
352
+
353
+ public init(cursor: String, inodeId: String, type: String) {
354
+ self.cursor = cursor
355
+ self.inodeId = inodeId
356
+ self.type = type
357
+ }
358
+
359
+ public init?(event: ChangeEvent) {
360
+ guard let inodeId = event.inodeId, !inodeId.isEmpty else { return nil }
361
+ self.cursor = event.cursor
362
+ self.inodeId = inodeId
363
+ self.type = event.type
364
+ }
365
+ }
366
+
367
+ public enum ServerOrigin {
368
+ public static func validate(_ url: URL) throws {
369
+ guard let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {
370
+ throw AdoorError(code: "INVALID_URL", message: "Use an HTTP or HTTPS server origin.", status: 400)
371
+ }
372
+ let loopback = host == "localhost" || host == "127.0.0.1" || host == "::1"
373
+ if scheme == "http" {
374
+ if !loopback {
375
+ throw AdoorError(code: "INVALID_URL", message: "Remote connections require HTTPS.", status: 400)
376
+ }
377
+ } else if scheme != "https" {
378
+ throw AdoorError(code: "INVALID_URL", message: "Use an HTTP or HTTPS server origin.", status: 400)
379
+ }
380
+ let path = url.path
381
+ if url.user != nil || url.password != nil || !(path.isEmpty || path == "/") || url.query != nil || url.fragment != nil {
382
+ throw AdoorError(code: "INVALID_URL", message: "Use a server origin without a path, password, query, or fragment.", status: 400)
383
+ }
384
+ }
385
+ }
386
+
387
+ public struct MountRecord: Codable, Equatable, Sendable, Identifiable {
388
+ public var id: String
389
+ public var server: String
390
+ public var workspace: String
391
+ public var space: String
392
+ public var remotePath: String
393
+ public var localPath: String
394
+ public var readOnly: Bool
395
+ public var access: String
396
+ public var state: String
397
+ public var sync: String
398
+ public var connectionId: String?
399
+ public var backend: String?
400
+ public var registeredWithFinder: Bool?
401
+
402
+ public init(
403
+ id: String, server: String, workspace: String, space: String, remotePath: String, localPath: String,
404
+ readOnly: Bool, access: String, state: String, sync: String, connectionId: String? = nil,
405
+ backend: String? = nil, registeredWithFinder: Bool? = nil
406
+ ) {
407
+ self.id = id
408
+ self.server = server
409
+ self.workspace = workspace
410
+ self.space = space
411
+ self.remotePath = remotePath
412
+ self.localPath = localPath
413
+ self.readOnly = readOnly
414
+ self.access = access
415
+ self.state = state
416
+ self.sync = sync
417
+ self.connectionId = connectionId
418
+ self.backend = backend
419
+ self.registeredWithFinder = registeredWithFinder
420
+ }
421
+ }
422
+
423
+ public struct MountBook: Codable, Equatable, Sendable {
424
+ public var version: Int
425
+ public var mounts: [MountRecord]
426
+
427
+ public init(version: Int = 1, mounts: [MountRecord]) {
428
+ self.version = version
429
+ self.mounts = mounts
430
+ }
431
+ }
432
+
433
+ public struct ActivityRecord: Codable, Equatable, Sendable, Identifiable {
434
+ public var id: String
435
+ public var title: String
436
+ public var detail: String
437
+ public var at: String
438
+ public var conflictId: String?
439
+ public var localPath: String?
440
+
441
+ public init(id: String, title: String, detail: String, at: String, conflictId: String? = nil, localPath: String? = nil) {
442
+ self.id = id
443
+ self.title = title
444
+ self.detail = detail
445
+ self.at = at
446
+ self.conflictId = conflictId
447
+ self.localPath = localPath
448
+ }
449
+ }
450
+
451
+ public struct ActivityBook: Codable, Equatable, Sendable {
452
+ public var version: Int
453
+ public var events: [ActivityRecord]
454
+ public init(version: Int = 1, events: [ActivityRecord]) {
455
+ self.version = version
456
+ self.events = events
457
+ }
458
+ }
459
+
460
+ public enum MountRegistry {
461
+ public static func encode(_ book: MountBook) throws -> Data {
462
+ guard book.version == 1 else { throw TreeError.invalid }
463
+ let encoder = JSONEncoder()
464
+ encoder.outputFormatting = [.sortedKeys]
465
+ return try encoder.encode(book)
466
+ }
467
+
468
+ public static func decode(_ data: Data) throws -> MountBook {
469
+ let book = try JSONDecoder().decode(MountBook.self, from: data)
470
+ guard book.version == 1 else { throw TreeError.invalid }
471
+ return book
472
+ }
473
+
474
+ public static func encodeActivity(_ book: ActivityBook) throws -> Data {
475
+ guard book.version == 1 else { throw TreeError.invalid }
476
+ let encoder = JSONEncoder()
477
+ encoder.outputFormatting = [.sortedKeys]
478
+ return try encoder.encode(book)
479
+ }
480
+
481
+ public static func decodeActivity(_ data: Data) throws -> ActivityBook {
482
+ let book = try JSONDecoder().decode(ActivityBook.self, from: data)
483
+ guard book.version == 1 else { throw TreeError.invalid }
484
+ return book
485
+ }
486
+ }
487
+
488
+ public enum MountPaths {
489
+ public static func registry(home: URL, platformDarwin: Bool, environment: [String: String] = ProcessInfo.processInfo.environment) -> URL {
490
+ if let override = environment["ADOOR_MOUNT_REGISTRY"], !override.isEmpty { return URL(fileURLWithPath: override) }
491
+ if platformDarwin { return home.appendingPathComponent("Library/Application Support/ADoor/mounts.json") }
492
+ let base = environment["XDG_DATA_HOME"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0) }
493
+ ?? home.appendingPathComponent(".local").appendingPathComponent("share")
494
+ return base.appendingPathComponent("adoor/mounts.json")
495
+ }
496
+
497
+ public static func activity(registry: URL) -> URL {
498
+ registry.deletingLastPathComponent().appendingPathComponent("activity.json")
499
+ }
500
+ }
501
+
502
+ public struct MountTarget: Equatable, Sendable {
503
+ public let space: String
504
+ public let remotePath: String
505
+
506
+ public init(space: String, remotePath: String) {
507
+ self.space = space
508
+ self.remotePath = remotePath
509
+ }
510
+
511
+ public static func parse(_ spec: String) throws -> MountTarget {
512
+ let trimmed = spec.trimmingCharacters(in: .whitespacesAndNewlines)
513
+ if trimmed.isEmpty || trimmed.hasPrefix("/") || trimmed.contains("\\") {
514
+ throw AdoorError(code: "INVALID_ARGUMENT", message: "Name a space, or a space and a folder.", status: 400)
515
+ }
516
+ let parts = trimmed.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
517
+ if parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) {
518
+ throw AdoorError(code: "INVALID_ARGUMENT", message: "Name a space, or a space and a folder.", status: 400)
519
+ }
520
+ let space = parts[0]
521
+ if parts.count == 1 { return MountTarget(space: space, remotePath: "/") }
522
+ return MountTarget(space: space, remotePath: "/" + parts.dropFirst().joined(separator: "/"))
523
+ }
524
+ }
525
+
526
+ public enum SyncWord: String, Equatable, Sendable {
527
+ case current
528
+ case syncing
529
+ case conflict
530
+ case offline
531
+ case unmounted
532
+
533
+ public var label: String {
534
+ switch self {
535
+ case .current: return "Up to date"
536
+ case .syncing: return "Syncing"
537
+ case .conflict: return "Needs a decision"
538
+ case .offline: return "Offline"
539
+ case .unmounted: return "Not mounted"
540
+ }
541
+ }
542
+ }
543
+
544
+ public struct WorkspaceRow: Equatable, Sendable, Identifiable {
545
+ public let id: String
546
+ public var name: String
547
+ public var slug: String
548
+ public var current: Bool
549
+
550
+ public init(id: String, name: String, slug: String, current: Bool = false) {
551
+ self.id = id
552
+ self.name = name
553
+ self.slug = slug
554
+ self.current = current
555
+ }
556
+ }
557
+
558
+ public struct SpaceRow: Equatable, Sendable, Identifiable {
559
+ public let id: String
560
+ public var name: String
561
+ public var slug: String
562
+ public var workspaceID: String
563
+
564
+ public init(id: String, name: String, slug: String, workspaceID: String) {
565
+ self.id = id
566
+ self.name = name
567
+ self.slug = slug
568
+ self.workspaceID = workspaceID
569
+ }
570
+ }
571
+
572
+ public struct FolderRow: Equatable, Sendable, Identifiable {
573
+ public let id: String
574
+ public var name: String
575
+ public var spaceID: String
576
+ public var access: FolderAccess
577
+ public var mounted: Bool
578
+ public var sync: SyncWord
579
+ public var localPath: String?
580
+
581
+ public init(
582
+ id: String, name: String, spaceID: String, access: FolderAccess, mounted: Bool, sync: SyncWord,
583
+ localPath: String? = nil
584
+ ) {
585
+ self.id = id
586
+ self.name = name
587
+ self.spaceID = spaceID
588
+ self.access = access
589
+ self.mounted = mounted
590
+ self.sync = sync
591
+ self.localPath = localPath
592
+ }
593
+ }
594
+
595
+ public struct ActivityRow: Equatable, Sendable, Identifiable {
596
+ public let id: String
597
+ public var title: String
598
+ public var detail: String
599
+ public var conflictId: String?
600
+ public var folderID: String?
601
+ public var inodeId: String?
602
+ public var baseGeneration: Int?
603
+ public var localBody: String?
604
+
605
+ public init(
606
+ id: String, title: String, detail: String, conflictId: String? = nil, folderID: String? = nil,
607
+ inodeId: String? = nil, baseGeneration: Int? = nil, localBody: String? = nil
608
+ ) {
609
+ self.id = id
610
+ self.title = title
611
+ self.detail = detail
612
+ self.conflictId = conflictId
613
+ self.folderID = folderID
614
+ self.inodeId = inodeId
615
+ self.baseGeneration = baseGeneration
616
+ self.localBody = localBody
617
+ }
618
+ }
619
+
620
+ public enum MenuStatus: Equatable, Sendable {
621
+ case signedOut
622
+ case current
623
+ case syncing
624
+ case conflict(Int)
625
+ case offline
626
+
627
+ public var label: String {
628
+ switch self {
629
+ case .signedOut: return "Sign in"
630
+ case .current: return "Up to date"
631
+ case .syncing: return "Syncing"
632
+ case .conflict(let count): return count == 1 ? "1 conflict" : "\(count) conflicts"
633
+ case .offline: return "Offline"
634
+ }
635
+ }
636
+
637
+ public var symbol: String {
638
+ switch self {
639
+ case .signedOut: return "door.left.hand.closed"
640
+ case .current: return "door.left.hand.open"
641
+ case .syncing: return "arrow.triangle.2.circlepath"
642
+ case .conflict: return "exclamationmark.triangle"
643
+ case .offline: return "icloud.slash"
644
+ }
645
+ }
646
+ }
647
+
648
+ public struct MountDesk: Equatable, Sendable {
649
+ public enum Phase: Equatable, Sendable {
650
+ case signedOut
651
+ case pending(userCode: String)
652
+ case ready
653
+ }
654
+
655
+ public var phase: Phase
656
+ public var server: String
657
+ public var workspaces: [WorkspaceRow]
658
+ public var selectedWorkspaceID: String?
659
+ public var spaces: [SpaceRow]
660
+ public var selectedSpaceID: String?
661
+ public var folders: [FolderRow]
662
+ public var selectedFolderID: String?
663
+ public var activity: [ActivityRow]
664
+ public var launchAtLogin: Bool
665
+ public var notifyConflicts: Bool
666
+ public var deleted: [DeletedRow]
667
+ public var selectedDeleted: Set<String>
668
+ public var showingDeleted: Bool
669
+ public var retentionDays: Int
670
+ public var deletedAccess: DeletedAccess
671
+
672
+ public init(
673
+ phase: Phase, server: String, workspaces: [WorkspaceRow], selectedWorkspaceID: String?, spaces: [SpaceRow],
674
+ selectedSpaceID: String?, folders: [FolderRow], selectedFolderID: String?, activity: [ActivityRow],
675
+ launchAtLogin: Bool, notifyConflicts: Bool, deleted: [DeletedRow] = [], selectedDeleted: Set<String> = [],
676
+ showingDeleted: Bool = false, retentionDays: Int = DeletedFolder.defaultRetentionDays,
677
+ deletedAccess: DeletedAccess = .unknown
678
+ ) {
679
+ self.phase = phase
680
+ self.server = server
681
+ self.workspaces = workspaces
682
+ self.selectedWorkspaceID = selectedWorkspaceID
683
+ self.spaces = spaces
684
+ self.selectedSpaceID = selectedSpaceID
685
+ self.folders = folders
686
+ self.selectedFolderID = selectedFolderID
687
+ self.activity = activity
688
+ self.launchAtLogin = launchAtLogin
689
+ self.notifyConflicts = notifyConflicts
690
+ self.deleted = deleted
691
+ self.selectedDeleted = selectedDeleted
692
+ self.showingDeleted = showingDeleted
693
+ self.retentionDays = retentionDays
694
+ self.deletedAccess = deletedAccess
695
+ }
696
+
697
+ public static func signIn(server: String) -> MountDesk {
698
+ MountDesk(
699
+ phase: .signedOut, server: server, workspaces: [], selectedWorkspaceID: nil, spaces: [],
700
+ selectedSpaceID: nil, folders: [], selectedFolderID: nil, activity: [], launchAtLogin: false,
701
+ notifyConflicts: true)
702
+ }
703
+
704
+ public static func demo() -> MountDesk {
705
+ let notes = FolderRow(
706
+ id: "notes", name: "Notes", spaceID: "field-notes", access: FolderAccess(canRead: true, canWrite: true),
707
+ mounted: true, sync: .conflict, localPath: "/Users/demo/ADoor/Notes")
708
+ let receipts = FolderRow(
709
+ id: "receipts", name: "Receipts", spaceID: "field-notes", access: FolderAccess(canRead: true, canWrite: false),
710
+ mounted: false, sync: .unmounted, localPath: nil)
711
+ let inbox = FolderRow(
712
+ id: "inbox", name: "Inbox", spaceID: "general-demo", access: FolderAccess(canRead: true, canWrite: true),
713
+ mounted: false, sync: .unmounted, localPath: nil)
714
+ let clips = FolderRow(
715
+ id: "clips", name: "Clips", spaceID: "studio-general", access: FolderAccess(canRead: true, canWrite: true),
716
+ mounted: false, sync: .unmounted, localPath: nil)
717
+ let conflict = ActivityRow(
718
+ id: "conflict-budget", title: "budget.txt", detail: "Changed on the server", conflictId: "conflict-budget", folderID: notes.id)
719
+ let saved = ActivityRow(id: "saved-monday", title: "monday.txt", detail: "Saved", folderID: notes.id)
720
+ let deletedAt = Date().addingTimeInterval(-2 * 86_400)
721
+ let purgeAfter = deletedAt.addingTimeInterval(TimeInterval(DeletedFolder.defaultRetentionDays * 86_400))
722
+ let deleted = [
723
+ DeletedRow(id: "old-budget", name: "old-budget.txt", who: "Ada Lovelace", deletedAt: deletedAt, purgeAfter: purgeAfter, kind: .file),
724
+ DeletedRow(
725
+ id: "scratch-note", name: "scratch.md", who: "This Mac", deletedAt: deletedAt.addingTimeInterval(86_400),
726
+ purgeAfter: purgeAfter.addingTimeInterval(86_400), kind: .file)
727
+ ]
728
+ return MountDesk(
729
+ phase: .ready, server: "https://files.example",
730
+ workspaces: [
731
+ WorkspaceRow(id: "demo", name: "Demo", slug: "demo", current: true),
732
+ WorkspaceRow(id: "studio", name: "Studio", slug: "studio")
733
+ ],
734
+ selectedWorkspaceID: "demo",
735
+ spaces: [
736
+ SpaceRow(id: "field-notes", name: "Field notes", slug: "field-notes", workspaceID: "demo"),
737
+ SpaceRow(id: "general-demo", name: "General", slug: "general", workspaceID: "demo"),
738
+ SpaceRow(id: "studio-general", name: "General", slug: "general", workspaceID: "studio")
739
+ ],
740
+ selectedSpaceID: "field-notes", folders: [notes, receipts, inbox, clips], selectedFolderID: "notes",
741
+ activity: [conflict, saved], launchAtLogin: false, notifyConflicts: true,
742
+ deleted: deleted, retentionDays: DeletedFolder.defaultRetentionDays, deletedAccess: .allowed)
743
+ }
744
+
745
+ public var workspaceName: String { workspaces.first { $0.id == selectedWorkspaceID }?.name ?? "" }
746
+
747
+ public var visibleSpaces: [SpaceRow] { spaces.filter { $0.workspaceID == selectedWorkspaceID } }
748
+
749
+ public var visibleFolders: [FolderRow] {
750
+ guard let selectedSpaceID else { return [] }
751
+ return folders.filter { $0.spaceID == selectedSpaceID }
752
+ }
753
+
754
+ public var selectedFolder: FolderRow? { folders.first { $0.id == selectedFolderID } }
755
+
756
+ public var selectedFolderActivity: [ActivityRow] { activity.filter { $0.folderID == nil || $0.folderID == selectedFolderID } }
757
+
758
+ public var menuStatus: MenuStatus {
759
+ if phase != .ready { return .signedOut }
760
+ let conflicts = activity.filter { $0.conflictId != nil }.count
761
+ if conflicts > 0 { return .conflict(conflicts) }
762
+ if folders.contains(where: { $0.sync == .offline }) { return .offline }
763
+ if folders.contains(where: { $0.sync == .syncing }) { return .syncing }
764
+ return .current
765
+ }
766
+
767
+ public mutating func beginSignIn(userCode: String) { phase = .pending(userCode: userCode) }
768
+
769
+ public mutating func failSignIn() { phase = .signedOut }
770
+
771
+ public mutating func approve(workspaces: [WorkspaceRow], spaces: [SpaceRow]) {
772
+ phase = .ready
773
+ self.workspaces = workspaces
774
+ self.spaces = spaces
775
+ selectedWorkspaceID = workspaces.first { $0.current }?.id ?? workspaces.first?.id
776
+ selectedSpaceID = visibleSpaces.first?.id
777
+ selectedFolderID = visibleFolders.first?.id
778
+ }
779
+
780
+ public mutating func select(workspace id: String) {
781
+ guard workspaces.contains(where: { $0.id == id }) else { return }
782
+ selectedWorkspaceID = id
783
+ if !visibleSpaces.contains(where: { $0.id == selectedSpaceID }) { selectedSpaceID = visibleSpaces.first?.id }
784
+ if !visibleFolders.contains(where: { $0.id == selectedFolderID }) { selectedFolderID = visibleFolders.first?.id }
785
+ showingDeleted = false
786
+ }
787
+
788
+ public mutating func select(space id: String) {
789
+ guard visibleSpaces.contains(where: { $0.id == id }) else { return }
790
+ selectedSpaceID = id
791
+ if !visibleFolders.contains(where: { $0.id == selectedFolderID }) { selectedFolderID = visibleFolders.first?.id }
792
+ showingDeleted = false
793
+ }
794
+
795
+ public mutating func select(folder id: String) {
796
+ guard visibleFolders.contains(where: { $0.id == id }) else { return }
797
+ selectedFolderID = id
798
+ }
799
+
800
+ public mutating func show(spaces: [SpaceRow], folders: [FolderRow]) {
801
+ self.spaces = spaces
802
+ self.folders = folders
803
+ if !visibleSpaces.contains(where: { $0.id == selectedSpaceID }) { selectedSpaceID = visibleSpaces.first?.id }
804
+ if !visibleFolders.contains(where: { $0.id == selectedFolderID }) { selectedFolderID = visibleFolders.first?.id }
805
+ }
806
+
807
+ public mutating func note(mounts: [MountRecord]) {
808
+ for index in folders.indices {
809
+ guard let space = spaces.first(where: { $0.id == folders[index].spaceID }),
810
+ let workspace = workspaces.first(where: { $0.id == space.workspaceID }) else { continue }
811
+ let path = "/" + folders[index].name
812
+ guard let mount = mounts.first(where: { $0.workspace == workspace.slug && $0.space == space.slug && $0.remotePath == path }) else {
813
+ continue
814
+ }
815
+ folders[index].mounted = mount.state == "mounted"
816
+ folders[index].localPath = mount.localPath
817
+ folders[index].sync = mount.state == "mounted" ? (SyncWord(rawValue: mount.sync) ?? .current) : .unmounted
818
+ }
819
+ }
820
+
821
+ public mutating func mountSelected(localPath: String) {
822
+ guard let index = folders.firstIndex(where: { $0.id == selectedFolderID }), folders[index].access.canRead else { return }
823
+ folders[index].mounted = true
824
+ folders[index].localPath = localPath
825
+ if folders[index].sync == .unmounted { folders[index].sync = .current }
826
+ }
827
+
828
+ public mutating func unmountSelected() {
829
+ guard let index = folders.firstIndex(where: { $0.id == selectedFolderID }) else { return }
830
+ folders[index].mounted = false
831
+ folders[index].localPath = nil
832
+ folders[index].sync = .unmounted
833
+ }
834
+
835
+ public mutating func resolve(conflictId: String, keep: ConflictChoice) {
836
+ guard let row = selectedFolderActivity.first(where: { $0.conflictId == conflictId }) else { return }
837
+ activity.removeAll { $0.conflictId == conflictId }
838
+ let detail = keep == .mine ? "Kept your copy" : "Kept the server copy"
839
+ activity.insert(ActivityRow(id: "resolved-\(conflictId)", title: row.title, detail: detail, folderID: row.folderID), at: 0)
840
+ if !selectedFolderActivity.contains(where: { $0.conflictId != nil }),
841
+ let index = folders.firstIndex(where: { $0.id == selectedFolderID && $0.sync == .conflict }) {
842
+ folders[index].sync = .current
843
+ }
844
+ }
845
+
846
+ public var recoveryNote: String { DeletedFolder.note(days: retentionDays) }
847
+
848
+ public mutating func showDeleted() { showingDeleted = true }
849
+
850
+ public mutating func hideDeleted() { showingDeleted = false }
851
+
852
+ public mutating func toggleDeleted(_ id: String) {
853
+ if selectedDeleted.contains(id) { selectedDeleted.remove(id) }
854
+ else { selectedDeleted.insert(id) }
855
+ }
856
+
857
+ public mutating func replaceDeleted(_ folder: DeletedFolder) {
858
+ deleted = folder.files
859
+ retentionDays = folder.retentionDays
860
+ deletedAccess = .allowed
861
+ selectedDeleted = Set(selectedDeleted.filter { id in folder.files.contains { $0.id == id } })
862
+ }
863
+
864
+ public mutating func markDeleted(_ access: DeletedAccess) {
865
+ deletedAccess = access
866
+ if access != .allowed { deleted = []; selectedDeleted = [] }
867
+ }
868
+
869
+ /// Removes the checked rows after the server has restored them.
870
+ public mutating func restored(_ ids: [String]) {
871
+ let chosen = deleted.filter { ids.contains($0.id) }
872
+ deleted.removeAll { ids.contains($0.id) }
873
+ selectedDeleted.subtract(ids)
874
+ guard !chosen.isEmpty else { return }
875
+ let title = chosen.count == 1 ? chosen[0].name : "\(chosen.count) files"
876
+ let stamp = chosen.map(\.id).joined(separator: "-")
877
+ activity.insert(ActivityRow(id: "restored-\(stamp)", title: title, detail: "Restored", folderID: selectedFolderID), at: 0)
878
+ }
879
+ }
880
+
881
+ extension Data {
882
+ var hex: String { map { String(format: "%02x", $0) }.joined() }
883
+
884
+ init?(hex: String) {
885
+ let chars = Array(hex)
886
+ guard chars.count.isMultiple(of: 2) else { return nil }
887
+ var out = Data()
888
+ var index = 0
889
+ while index < chars.count {
890
+ guard let byte = UInt8(String(chars[index...index + 1]), radix: 16) else { return nil }
891
+ out.append(byte)
892
+ index += 2
893
+ }
894
+ self = out
895
+ }
896
+ }