SPB Git

Repository Public

DeepLinks.swift 9.3 KB 214 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteCore/DeepLinks.swift10// Module           : ClaudeRemoteCore11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteModels89import Foundation9091/// A destination inside the app. Both platforms map it to their own navigation.92public enum Route: Hashable, Sendable {93    case home94    case sessions95    /// The terminal of a session (`/terminal/?s=<id>`).96    case terminal(sessionId: String)97    case projects98    /// Files of a project, optionally at a path (`/files/?p=<id>&path=<rel>`).99    case files(projectId: String?, path: String?)100    case tasks101    case task(id: String)102    case cluster103    case clusterNode(id: String)104    case clusterApps105    case skills106    case mcp107    case system108    case settings109    case notifications110}111112/// Maps web links (notification `link`s, universal links under `/open/…`) and the custom URL113/// schemes `clauderemote://` / `codexremote://` to a `Route`, and back.114public struct DeepLinkRouter: Sendable {115    public let profile: AgentProfile116117    public init(profile: AgentProfile) { self.profile = profile }118119    /// A notification link or any web path with its query, e.g. `/terminal/?s=<id>`.120    public func route(forWebPath link: String) -> Route? {121        guard let components = URLComponents(string: link.hasPrefix("/") ? link : "/" + link) else { return nil }122        return route(path: components.path, query: components.queryItems ?? [])123    }124125    /// A custom-scheme URL of this product, or an `https` URL of its instance. URLs of the other126    /// product (or of any other host) are refused.127    public func route(for url: URL) -> Route? {128        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let scheme = components.scheme?.lowercased() else { return nil }129        if scheme == profile.urlScheme {130            // clauderemote://terminal/?s=… → host "terminal", path "/"131            let path = "/" + (components.host ?? "") + components.path132            return route(path: path, query: components.queryItems ?? [])133        }134        if scheme == "https" || scheme == "http", components.host?.lowercased() == profile.relyingPartyID.lowercased() {135            return route(path: components.path, query: components.queryItems ?? [])136        }137        return nil138    }139140    /// Route carried by a push or local notification (`userInfo["cr"]["link"]` or `userInfo["link"]`).141    public func route(forNotificationUserInfo userInfo: [AnyHashable: Any]) -> Route? {142        let link = ((userInfo["cr"] as? [AnyHashable: Any])?["link"] as? String) ?? (userInfo["link"] as? String)143        return link.flatMap(route(forWebPath:))144    }145146    private func route(path rawPath: String, query: [URLQueryItem]) -> Route? {147        var parts = rawPath.split(separator: "/").map(String.init)148        if parts.first == "open" { parts.removeFirst() } // universal links: /open/*149        func q(_ name: String) -> String? {150            query.first { $0.name == name }?.value.flatMap { $0.isEmpty ? nil : $0 }151        }152        func id(_ value: String?) -> String? {153            // ids are UUIDs or node aliases: refuse anything that could be a path or an option154            guard let value, value.range(of: #"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"#, options: .regularExpression) != nil else { return nil }155            return value156        }157        switch parts.first?.lowercased() {158        case nil, "home": return .home159        case "sessions": return .sessions160        case "terminal": return id(q("s") ?? parts.dropFirst().first).map { .terminal(sessionId: $0) } ?? .sessions161        case "projects": return .projects162        case "files":163            let path = q("path").flatMap { $0.contains("..") || $0.hasPrefix("/") ? nil : $0 }164            return .files(projectId: id(q("p")), path: path)165        case "tasks": return id(q("t") ?? parts.dropFirst().first).map { .task(id: $0) } ?? .tasks166        case "cluster":167            if let node = id(q("n")) { return .clusterNode(id: node) }168            return q("view") == "apps" ? .clusterApps : .cluster169        case "skills": return .skills170        case "mcp": return .mcp171        case "system": return .system172        case "settings": return .settings173        case "notifications": return .notifications174        default: return nil175        }176    }177178    /// Web path of a route (same shape as the web application's URLs).179    public func webPath(for route: Route) -> String {180        func enc(_ s: String) -> String { s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(.init(charactersIn: "-._~/"))) ?? s }181        switch route {182        case .home: return "/home/"183        case .sessions: return "/sessions/"184        case .terminal(let id): return "/terminal/?s=\(enc(id))"185        case .projects: return "/projects/"186        case .files(let projectId, let path):187            var items: [String] = []188            if let projectId { items.append("p=\(enc(projectId))") }189            if let path, !path.isEmpty { items.append("path=\(enc(path))") }190            return "/files/" + (items.isEmpty ? "" : "?" + items.joined(separator: "&"))191        case .tasks: return "/tasks/"192        case .task(let id): return "/tasks/?t=\(enc(id))"193        case .cluster: return "/cluster/"194        case .clusterNode(let id): return "/cluster/?n=\(enc(id))"195        case .clusterApps: return "/cluster/?view=apps"196        case .skills: return "/skills/"197        case .mcp: return "/mcp/"198        case .system: return "/system/"199        case .settings: return "/settings/"200        case .notifications: return "/notifications/"201        }202    }203204    /// `clauderemote://terminal/?s=…` — for widgets, Shortcuts and local notifications.205    public func appURL(for route: Route) -> URL {206        URL(string: "\(profile.urlScheme):/\(webPath(for: route))")!207    }208209    /// The same destination in the web application.210    public func webURL(for route: Route) -> URL {211        URL(string: profile.baseURL.absoluteString + webPath(for: route))!212    }213}214
Files main
Menu

Theme