From 1192dba436e41c6d630d2bd2e8053056aad07fcd Mon Sep 17 00:00:00 2001 From: Hydra Date: Sun, 4 Oct 2026 12:33:57 +0300 Subject: [PATCH] Add Oblien 2.8 API parity and saved desktop sessions --- .github/workflows/verify.yml | 2 +- README.md | 4 +- Sources/OblienKit/AccessAPI.swift | 153 ++ Sources/OblienKit/BillingAPI.swift | 39 + Sources/OblienKit/Configuration.swift | 6 +- Sources/OblienKit/DesktopAPI.swift | 40 +- Sources/OblienKit/DesktopSessions.swift | 139 ++ Sources/OblienKit/DisksAPI.swift | 82 +- Sources/OblienKit/HTTPRedirectPolicy.swift | 2 +- Sources/OblienKit/Models.swift | 70 +- Sources/OblienKit/NamespacesAPI.swift | 4 + Sources/OblienKit/OblienClient.swift | 10 + .../PlatformModels/AccountDomainModels.swift | 2 +- .../PlatformModels/AnalyticsModels.swift | 2 +- .../PlatformModels/BillingModels.swift | 1495 ++++++++++++++++- .../OblienKit/PlatformModels/CdnModels.swift | 2 +- .../PlatformModels/EdgeProxyModels.swift | 2 +- .../PlatformModels/EdgeTunnelModels.swift | 2 +- .../PlatformModels/NamespaceModels.swift | 133 +- .../PlatformModels/NotificationsModels.swift | 2 +- .../PlatformModels/PagesModels.swift | 2 +- .../PlatformModels/RuntimeModels.swift | 10 +- .../PlatformModels/WebhooksModels.swift | 18 +- Sources/OblienKit/RuntimeAPIs.swift | 27 + Sources/OblienKit/SSHAPI.swift | 8 + Sources/OblienKit/Transport.swift | 6 + Sources/OblienKit/WorkspaceOptions.swift | 4 +- Sources/OblienKit/WorkspacesAPI.swift | 3 + .../OblienKitTests/DesktopSessionsTests.swift | 259 +++ docs/TypeScriptCoverage.md | 10 +- scripts/audit-typescript-sdk.cjs | 9 +- scripts/generate-platform-models.cjs | 4 +- scripts/typescript-surface.json | 414 ++++- 33 files changed, 2874 insertions(+), 91 deletions(-) create mode 100644 Sources/OblienKit/AccessAPI.swift create mode 100644 Sources/OblienKit/DesktopSessions.swift create mode 100644 Tests/OblienKitTests/DesktopSessionsTests.swift diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index b3a6f53..b673936 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -22,7 +22,7 @@ jobs: shell: bash run: | audit_dir="$RUNNER_TEMP/oblien-sdk-audit" - npm install --prefix "$audit_dir" --ignore-scripts --no-audit --no-fund typescript@6.0.3 oblien@2.4.0 + npm install --prefix "$audit_dir" --ignore-scripts --no-audit --no-fund typescript@6.0.3 oblien@2.8.0 NODE_PATH="$audit_dir/node_modules" node scripts/audit-typescript-sdk.cjs "$audit_dir/node_modules/oblien/dist" NODE_PATH="$audit_dir/node_modules" node scripts/generate-platform-models.cjs "$audit_dir/node_modules/oblien/dist" git diff --exit-code -- Sources/OblienKit/PlatformModels diff --git a/README.md b/README.md index 1f04a53..02efcfb 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A Swift SDK for [Oblien](https://oblien.com), using Foundation, URLSession and async/await. Supports iOS 16+ and macOS 12+ without third-party dependencies. -The management and runtime APIs cover the portable surface of the TypeScript `oblien` SDK **2.4.0**. They also include the current disk and desktop installation APIs. See [TypeScript coverage](docs/TypeScriptCoverage.md) for the API mapping, native equivalents, verification, and platform boundaries. +The management and runtime APIs cover the portable surface of the TypeScript `oblien` SDK **2.8.0**. They also include the current disk and desktop installation APIs. See [TypeScript coverage](docs/TypeScriptCoverage.md) for the API mapping, native equivalents, verification, and platform boundaries. ## Install @@ -106,7 +106,7 @@ swift test NODE_PATH=/path/to/node_modules node scripts/audit-typescript-sdk.cjs /path/to/oblien/dist ``` -The audit compares declarations and the reviewed Swift method mapping with a checked-in 2.4.0 snapshot. Optional live tests require `OBLIEN_LIVE_TOKEN_FILE`; see the coverage document before running them. +The audit compares declarations and the reviewed Swift method mapping with a checked-in 2.8.0 snapshot. Optional live tests require `OBLIEN_LIVE_TOKEN_FILE`; see the coverage document before running them. ## License diff --git a/Sources/OblienKit/AccessAPI.swift b/Sources/OblienKit/AccessAPI.swift new file mode 100644 index 0000000..5538cad --- /dev/null +++ b/Sources/OblienKit/AccessAPI.swift @@ -0,0 +1,153 @@ +import Foundation + +public struct AccessResource: Codable, Sendable { + public var accountId: String + public var resourceType: String + public var resourceId: String? + public init(accountId: String, resourceType: String, resourceId: String? = nil) { + self.accountId = accountId; self.resourceType = resourceType; self.resourceId = resourceId + } +} +public struct AccountLabel: Codable, Sendable { + public let id: String + public let name: String + public var image: String? +} +public struct AccessibleAccount: Codable, Sendable { + public let id: String + public let name: String + public var image: String? + public let personal: Bool + public let role: String + public let permissions: [String] + public var membershipId: String? +} +public struct WorkspaceSharing: Codable, Sendable { + public let ownerId: String + public let actorId: String + public let role: String + public let permissions: [String] + public var owner: AccountLabel? + public var namespaceAccess: Bool? + public var namespaceId: String? +} +public struct AccessInvitation: Codable, Sendable, Identifiable { + public let id: String + public let owner: AccountLabel + public let resourceType: String + public let resourceId: String + public var resourceName: String? + public let role: String + public let expiresAt: String + public var accessExpiresAt: String? +} +public struct AccessMember: Codable, Sendable, Identifiable { + public let id: String + public let user: AccountLabel + public let role: String + public let version: String + public var expiresAt: String? +} +public struct AccessMembers: Codable, Sendable { + public let success: Bool + public let owner: AccessibleAccount + public let members: [AccessMember] + public let invitations: [AccessInvitation] +} +public struct SharedWorkspaceList: Codable, Sendable { + public let success: Bool + public let workspaces: [Workspace] + public var nextCursor: String? +} +public struct CreatedAccessInvitation: Codable, Sendable { + public let success: Bool + public let invitation: Invitation + public let invitationUrl: String + public struct Invitation: Codable, Sendable { + public let id: String + public let email: String + public let role: String + public let expiresAt: String + } +} +public struct AccessToken: Decodable, Sendable { + public let success: Bool + public let token: String + public let expiresAt: String + public let ttl: Int + public let scope: String + public let permissions: [String] +} +public struct AccessAudit: Codable, Sendable { + public let success: Bool + public let events: [Event] + public var nextCursor: String? + public struct Event: Codable, Sendable, Identifiable { + public let id: String + public let action: String + public let actorId: String + public let actorName: String + public let createdAt: String + } +} +public struct SharedSSHConnection: Decodable, Sendable { + public let success: Bool + public let delegated: Bool + public let expiresAt: String + public let ssh: DesktopSSHConnection.SSH +} + +/// Identity-based sharing. Tokens and invitation URLs are secrets; keep them out of logs. +public struct AccessAPI: Sendable { + let transport: Transport + private func request(_ method: String, _ path: String, query: [String: String?] = [:], body: Data? = nil) async throws -> T { + try OblienJSON.decode(T.self, await transport.request(method, "/access" + path, query: query, body: body)) + } + private func fields(_ resource: AccessResource) throws -> [String: JSONValue] { + try JSONDecoder().decode([String: JSONValue].self, from: OblienJSON.encode(resource)) + } + private func query(_ resource: AccessResource) -> [String: String?] { + ["account_id": resource.accountId, "resource_type": resource.resourceType, "resource_id": resource.resourceId] + } + public func accounts() async throws -> [AccessibleAccount] { + struct Result: Decodable { let accounts: [AccessibleAccount] } + let value: Result = try await request("GET", "/accounts"); return value.accounts + } + public func sharedWorkspaces(before: String? = nil, limit: Int? = nil) async throws -> SharedWorkspaceList { + try await request("GET", "/shared-workspaces", query: ["before": before, "limit": limit.map(String.init)]) + } + public func invitations() async throws -> [AccessInvitation] { + struct Result: Decodable { let invitations: [AccessInvitation] } + let value: Result = try await request("GET", "/invitations"); return value.invitations + } + public func invite(_ resource: AccessResource, email: String, role: String? = nil, expiresAt: String? = nil) async throws -> CreatedAccessInvitation { + var body = try fields(resource); body["email"] = .string(email) + body["role"] = role.map(JSONValue.string); body["expires_at"] = expiresAt.map(JSONValue.string) + return try await request("POST", "/invitations", body: OblienJSON.encode(body)) + } + public enum InvitationReference: Sendable { case id(String), token(String) } + public func accept(_ invitation: InvitationReference) async throws -> APIResponse { + let body: [String: String] + switch invitation { case .id(let id): body = ["id": id]; case .token(let token): body = ["token": token] } + return try await request("POST", "/invitations/accept", body: OblienJSON.encode(body)) + } + public func revokeInvitation(_ id: String) async throws -> APIResponse { try await request("DELETE", "/invitations/" + id.pathEscaped) } + public func members(_ resource: AccessResource) async throws -> AccessMembers { try await request("GET", "/members", query: query(resource)) } + public func updateMember(_ id: String, role: String, version: String? = nil, expiresAt: JSONField? = nil) async throws -> APIResponse { + struct Body: Encodable { let role: String; let version: String?; let expiresAt: JSONField? } + return try await request("PATCH", "/members/" + id.pathEscaped, body: OblienJSON.encode(Body(role: role, version: version, expiresAt: expiresAt))) + } + public func removeMember(_ id: String, version: String? = nil) async throws -> APIResponse { + try await request("DELETE", "/members/" + id.pathEscaped, body: OblienJSON.encode(["version": version])) + } + public func issueToken(_ resource: AccessResource, role: String? = nil, ttl: Int? = nil, label: String? = nil) async throws -> AccessToken { + var body = try fields(resource); body["role"] = role.map(JSONValue.string) + body["ttl"] = ttl.map { .number(Double($0)) }; body["label"] = label.map(JSONValue.string) + return try await request("POST", "/tokens", body: OblienJSON.encode(body)) + } + public func audit(_ resource: AccessResource, before: String? = nil) async throws -> AccessAudit { + var parameters = query(resource); parameters["before"] = before + return try await request("GET", "/audit", query: parameters) + } +} +extension OblienClient { public var access: AccessAPI { .init(transport: transport) } } diff --git a/Sources/OblienKit/BillingAPI.swift b/Sources/OblienKit/BillingAPI.swift index cd27015..2ca07d2 100644 --- a/Sources/OblienKit/BillingAPI.swift +++ b/Sources/OblienKit/BillingAPI.swift @@ -3,6 +3,33 @@ import Foundation /// Namespace billing. Mutations require an admin or billing-scoped credential. public struct BillingAPI: Sendable { let transport: Transport + public func capacityCatalog() async throws -> CapacityCatalog { try await transport.api("GET", "/billing/capacity/catalog") } + public func capacity(_ namespace: String) async throws -> CapacityResponse { + try await transport.api("GET", "/billing/capacity", query: ["namespace": namespace]) + } + public func previewCapacity(_ namespace: String, _ params: PreviewCapacityParams) async throws -> CapacityQuoteResponse { + try await transport.api("POST", "/billing/capacity/preview", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func confirmCapacity(_ namespace: String, _ params: ConfirmCapacityParams) async throws -> CapacityResponse { + try await transport.api("POST", "/billing/capacity/confirm", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func capacityCheckout(_ namespace: String, _ params: CapacityCheckoutParams) async throws -> CapacityCheckoutResponse { + try await transport.api("POST", "/billing/capacity/checkout", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func cancelCapacityChange(_ namespace: String, _ params: ConfirmCapacityParams) async throws -> CapacityResponse { + try await transport.api("POST", "/billing/capacity/change/cancel", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func setCapacityAutoRenew(_ namespace: String, autoRenew: Bool, idempotencyKey: String) async throws -> CapacityResponse { + struct Body: Encodable { let namespace: String; let autoRenew: Bool; let idempotencyKey: String } + return try await transport.api("POST", "/billing/capacity/renewal", body: APIJSON.encode(Body(namespace: namespace, autoRenew: autoRenew, idempotencyKey: idempotencyKey))) + } + public func previewNetworkTopup(_ namespace: String, unitAmount: Double, idempotencyKey: String) async throws -> CapacityQuoteResponse { + struct Body: Encodable { let namespace: String; let unitAmount: Double; let idempotencyKey: String } + return try await transport.api("POST", "/billing/capacity/network/preview", body: APIJSON.encode(Body(namespace: namespace, unitAmount: unitAmount, idempotencyKey: idempotencyKey))) + } + public func savings(namespace: String? = nil, workspaceId: String? = nil, month: String? = nil) async throws -> BillingSavings { + try await transport.api("GET", "/billing/savings", query: ["namespace": namespace, "workspaceId": workspaceId, "month": month]) + } public func catalog() async throws -> BillingCatalog { try await transport.api("GET", "/billing/catalog") } public func checkout(_ params: CheckoutParams) async throws -> CheckoutResponse { try await transport.api("POST", "/billing/checkout", body: APIJSON.encode(params), retrySafe: params.idempotencyKey?.isEmpty == false) @@ -19,6 +46,18 @@ public struct BillingAPI: Sendable { public func subscription(_ namespace: String) async throws -> BillingSubscriptionResponse { try await transport.api("GET", "/billing/subscription", query: ["namespace": namespace]) } + public func previewPlanChange(_ namespace: String, _ params: PreviewPlanChangeParams) async throws -> BillingPlanChangeQuoteResponse { + try await transport.api("POST", "/billing/subscription/changes/preview", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func changePlan(_ namespace: String, _ params: ChangePlanParams) async throws -> BillingPlanChangeResponse { + try await transport.api("POST", "/billing/subscription/changes", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } + public func planChange(_ namespace: String, changeId: String) async throws -> BillingPlanChangeResponse { + try await transport.api("GET", "/billing/subscription/changes/\(changeId.pathEscaped)", query: ["namespace": namespace]) + } + public func cancelPlanChange(_ namespace: String, changeId: String, _ params: CancelPlanChangeParams) async throws -> BillingPlanChangeResponse { + try await transport.api("POST", "/billing/subscription/changes/\(changeId.pathEscaped)/cancel", body: APIJSON.encode(params, merging: ["namespace": .string(namespace)])) + } public func cancelSubscription(_ namespace: String) async throws -> BillingSubscriptionResponse { try await transport.api("POST", "/billing/subscription/cancel", body: APIJSON.encode(["namespace": namespace])) } diff --git a/Sources/OblienKit/Configuration.swift b/Sources/OblienKit/Configuration.swift index 2bdf611..6084548 100644 --- a/Sources/OblienKit/Configuration.swift +++ b/Sources/OblienKit/Configuration.swift @@ -18,6 +18,8 @@ public struct OblienConfiguration: Sendable { /// CDN edge upload API; receives only a CDN-scoped token, never account credentials. public var cdnURL: URL public var auth: OblienAuth + /// Account context for a personal login. The server verifies membership. + public var accountId: String? public var maxRetries: Int /// Gateway (runtime) JWT cache lifetime. Docs are contradictory (1h vs 30d); 55m is safe. public var runtimeTokenTTL: TimeInterval @@ -28,9 +30,11 @@ public struct OblienConfiguration: Sendable { runtimeURL: URL = URL(string: "https://workspace.oblien.com")!, maxRetries: Int = 3, runtimeTokenTTL: TimeInterval = 55 * 60, - cdnURL: URL = URL(string: "https://cdn.oblien.com/api")! + cdnURL: URL = URL(string: "https://cdn.oblien.com/api")!, + accountId: String? = nil ) { self.auth = auth + self.accountId = accountId self.baseURL = baseURL self.runtimeURL = runtimeURL self.cdnURL = cdnURL diff --git a/Sources/OblienKit/DesktopAPI.swift b/Sources/OblienKit/DesktopAPI.swift index e03b3c3..b493fdc 100644 --- a/Sources/OblienKit/DesktopAPI.swift +++ b/Sources/OblienKit/DesktopAPI.swift @@ -8,24 +8,33 @@ public struct DesktopAPI: Sendable { private var base: String { "/workspace/\(workspaceId.pathEscaped)/desktop" } public func installation() async throws -> DesktopInstallation { - try OblienJSON.decode(DesktopInstallation.self, await transport.request("GET", base + "/installation")) + let value = try OblienJSON.decode(DesktopInstallation.self, await transport.request("GET", base + "/installation")) + if value.installed == true || value.phase == "installing" { await transport.invalidateRuntime(workspaceId) } + return value } /// Restarting a running workspace requires an explicit `restart: true` from the caller. public func install(desktop: String? = nil, restart: Bool = false) async throws -> DesktopInstallation { struct Body: Encodable { let desktop: String?; let restart: Bool } - return try OblienJSON.decode(DesktopInstallation.self, await transport.request("POST", base + "/install", - body: OblienJSON.encode(Body(desktop: desktop, restart: restart)))) + do { + let value = try OblienJSON.decode(DesktopInstallation.self, await transport.request("POST", base + "/install", + body: OblienJSON.encode(Body(desktop: desktop, restart: restart)))) + await transport.invalidateRuntime(workspaceId) + return value + } catch { await transport.invalidateRuntime(workspaceId); throw error } } /// Contains a temporary password; keep the grant in memory and never log or persist it. - public func sshConnection() async throws -> DesktopSSHConnection { - try OblienJSON.decode(DesktopSSHConnection.self, await transport.request("POST", base + "/ssh")) + public func sshConnection(sessionId: String? = nil) async throws -> DesktopSSHConnection { + if let sessionId { _ = try desktopSessionPath(sessionId) } + let body = try sessionId.map { try OblienJSON.encode(["session_id": $0]) } + return try OblienJSON.decode(DesktopSSHConnection.self, await transport.request("POST", base + "/ssh", body: body)) } } public struct RuntimeDesktopAPI: Sendable { let runtime: RuntimeClient - public func status() async throws -> DesktopStatus { - try OblienJSON.decode(DesktopStatus.self, await runtime.perform("GET", "/desktop/status", root: true)) + public func status(sessionId: String? = nil) async throws -> DesktopStatus { + let path = try sessionId.map { try desktopSessionPath($0) + "/status" } ?? "/desktop/status" + return try OblienJSON.decode(DesktopStatus.self, await runtime.perform("GET", path, root: true)) } @discardableResult public func enable() async throws -> DesktopStatus { try OblienJSON.decode(DesktopStatus.self, await runtime.perform("POST", "/desktop/enable", root: true)) @@ -39,9 +48,17 @@ public struct RuntimeDesktopAPI: Sendable { } /// Authenticated web viewer URL. Treat it as a credential and do not log or persist it. /// Native viewers should use the management API's SSH grant instead. - public func url() async throws -> URL { + public func url(sessionId: String? = nil) async throws -> URL { + if let sessionId { _ = try desktopSessionPath(sessionId) } var components = URLComponents(url: try await runtime.endpoint("/desktop", root: true), resolvingAgainstBaseURL: false)! - components.queryItems = [URLQueryItem(name: "token", value: try await runtime.token())] + let token = try await runtime.token() + var fragment = URLComponents() + fragment.queryItems = [URLQueryItem(name: "token", value: token)] + if let sessionId { fragment.queryItems?.append(.init(name: "session", value: sessionId)) } + components.percentEncodedFragment = fragment.percentEncodedQuery + if components.scheme != "https" || components.host != "workspace.oblien.com" || (components.port != nil && components.port != 443) { + components.queryItems = [.init(name: "token", value: token)] + } return components.url! } } @@ -54,11 +71,14 @@ public struct DesktopInstallation: Codable, Sendable { public var error: String? public var choices: [Choice]? public var workloadId: String? + public var selected: String? + public var success: Bool? public struct Choice: Codable, Sendable, Identifiable { public let id: String public let label: String public var description: String? public var minimumMemoryMb: Int? + public var prepared: Bool? } } @@ -68,6 +88,7 @@ public struct DesktopStatus: Codable, Sendable { public let available: Bool public var credentials: Bool? public var transports: [String]? + public var sessions: DesktopSessionCapabilities? } public struct DesktopCredentials: Codable, Sendable { public let username: String @@ -77,6 +98,7 @@ public struct DesktopSSHConnection: Codable, Sendable { public let expiresAt: String public let ssh: SSH public let vnc: VNC + public var sessionId: String? public struct SSH: Codable, Sendable { public let host: String public let port: Int diff --git a/Sources/OblienKit/DesktopSessions.swift b/Sources/OblienKit/DesktopSessions.swift new file mode 100644 index 0000000..faa99fc --- /dev/null +++ b/Sources/OblienKit/DesktopSessions.swift @@ -0,0 +1,139 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +public struct DesktopResolution: Codable, Sendable, Hashable { + public var width: Int + public var height: Int + public init(width: Int, height: Int) { self.width = width; self.height = height } +} + +public struct DesktopSessionCapabilities: Codable, Sendable { + /// `virtual` supports separate profiles; `console` is the OS's one display. + public let mode: String + public let maxSessions: Int + public let canCreate: Bool + public var resolution: ResolutionLimits? + public struct ResolutionLimits: Codable, Sendable { + public let min: DesktopResolution + public let max: DesktopResolution + public let `default`: DesktopResolution + } +} + +/// A saved provider desktop, distinct from a viewer connection or control lease. +public struct DesktopSession: Codable, Sendable, Identifiable { + public let id: String + public let name: String + public var resolution: DesktopResolution? + /// Preserves new states, including asynchronous `deleting`. + public let state: String + public let managed: Bool + public let available: Bool + public var canResize: Bool? + public var canDelete: Bool? + public var deletionPending: Bool? + public var mode: String? + public var createdAt: String? + public var updatedAt: String? + public var error: String? +} + +public struct CreateDesktopSession: Codable, Sendable { + public var name: String + /// Omit when adding an OS console. Virtual desktops accept the advertised range. + public var resolution: DesktopResolution? + public var idempotencyKey: String? + public init(name: String, resolution: DesktopResolution? = nil, idempotencyKey: String? = nil) { + self.name = name; self.resolution = resolution; self.idempotencyKey = idempotencyKey + } +} +public struct UpdateDesktopSession: Codable, Sendable { + public var name: String? + public var resolution: DesktopResolution? + public init(name: String? = nil, resolution: DesktopResolution? = nil) { self.name = name; self.resolution = resolution } +} +public struct DesktopSessionList: Codable, Sendable { + public let success: Bool + public let sessions: [DesktopSession] + public let capabilities: DesktopSessionCapabilities +} +public struct DesktopSessionResult: Codable, Sendable { + public let success: Bool + public let session: DesktopSession +} +public struct DesktopSessionDeletion: Codable, Sendable { + public let success: Bool + /// A virtual desktop may be deleting in the background after acceptance. + public var session: DesktopSession? +} + +func desktopSessionPath(_ id: String) throws -> String { + guard id.range(of: "^(console|ds_[a-f0-9]{16})$", options: .regularExpression) != nil else { + throw OblienError(kind: .validation, status: nil, code: nil, message: "Invalid desktop session ID.", details: nil) + } + return "/desktop/sessions/" + id +} + +/// Shared session operations for management and direct runtime clients. +public struct DesktopSessionsAPI: Sendable { + enum Endpoint: Sendable { case management(Transport, String), runtime(RuntimeClient) } + let endpoint: Endpoint + + private func request(_ method: String, _ suffix: String = "", body: Data? = nil, + retrySafe: Bool = false) async throws -> T { + let data: Data + switch endpoint { + case .management(let transport, let workspaceId): + data = try await transport.request(method, "/workspace/\(workspaceId.pathEscaped)/desktop/sessions" + suffix, + body: body, retrySafe: retrySafe) + case .runtime(let runtime): + data = try await runtime.perform(method, "/desktop/sessions" + suffix, body: body, root: true) + } + return try OblienJSON.decode(T.self, data) + } + private func suffix(_ id: String) throws -> String { _ = try desktopSessionPath(id); return "/" + id } + public func list() async throws -> DesktopSessionList { try await request("GET") } + public func create(_ params: CreateDesktopSession) async throws -> DesktopSessionResult { + try await request("POST", body: OblienJSON.encode(params), retrySafe: params.idempotencyKey?.isEmpty == false) + } + public func get(_ id: String) async throws -> DesktopSessionResult { try await request("GET", suffix(id)) } + public func update(_ id: String, _ params: UpdateDesktopSession) async throws -> DesktopSessionResult { + try await request("PATCH", suffix(id), body: OblienJSON.encode(params)) + } + public func start(_ id: String) async throws -> DesktopSessionResult { try await request("POST", suffix(id) + "/start") } + public func stop(_ id: String) async throws -> DesktopSessionResult { try await request("POST", suffix(id) + "/stop") } + @discardableResult public func delete(_ id: String) async throws -> DesktopSessionDeletion { try await request("DELETE", suffix(id)) } +} + +extension DesktopAPI { + public var sessions: DesktopSessionsAPI { .init(endpoint: .management(transport, workspaceId)) } + public func listSessions() async throws -> DesktopSessionList { try await sessions.list() } + public func createSession(_ params: CreateDesktopSession) async throws -> DesktopSessionResult { try await sessions.create(params) } + public func getSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.get(id) } + public func updateSession(_ id: String, _ params: UpdateDesktopSession) async throws -> DesktopSessionResult { try await sessions.update(id, params) } + public func startSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.start(id) } + public func stopSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.stop(id) } + @discardableResult public func deleteSession(_ id: String) async throws -> DesktopSessionDeletion { try await sessions.delete(id) } +} +extension RuntimeDesktopAPI { + public var sessions: DesktopSessionsAPI { .init(endpoint: .runtime(runtime)) } + public func listSessions() async throws -> DesktopSessionList { try await sessions.list() } + public func createSession(_ params: CreateDesktopSession) async throws -> DesktopSessionResult { try await sessions.create(params) } + public func getSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.get(id) } + public func updateSession(_ id: String, _ params: UpdateDesktopSession) async throws -> DesktopSessionResult { try await sessions.update(id, params) } + public func startSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.start(id) } + public func stopSession(_ id: String) async throws -> DesktopSessionResult { try await sessions.stop(id) } + @discardableResult public func deleteSession(_ id: String) async throws -> DesktopSessionDeletion { try await sessions.delete(id) } + /// Authenticates using a header, never a token in the WebSocket URL. + public func webSocketRequest(sessionId: String? = nil) async throws -> URLRequest { + let path = try sessionId.map { try desktopSessionPath($0) + "/ws" } ?? "/desktop/ws" + var url = URLComponents(url: try await runtime.endpoint(path, root: true), resolvingAgainstBaseURL: false)! + url.scheme = url.scheme == "https" ? "wss" : "ws" + var request = URLRequest(url: url.url!) + request.setValue("Bearer " + (try await runtime.token()), forHTTPHeaderField: "Authorization") + request.setValue("binary", forHTTPHeaderField: "Sec-WebSocket-Protocol") + return request + } +} diff --git a/Sources/OblienKit/DisksAPI.swift b/Sources/OblienKit/DisksAPI.swift index 5226f06..5e37bfc 100644 --- a/Sources/OblienKit/DisksAPI.swift +++ b/Sources/OblienKit/DisksAPI.swift @@ -67,7 +67,17 @@ public struct DisksAPI: Sendable { } public func retry(_ operationId: String, options: DiskOperationOptions = .init()) async throws -> DiskMutationResult { - try await mutate("POST", "/disks/operations/\(operationId.pathEscaped)/retry", EmptyParams(), options) + let data = try await transport.request("POST", "/disks/operations/\(operationId.pathEscaped)/retry") + var result = try OblienJSON.decode(DiskMutationResult.self, data) + if options.waitUntilReady, let operation = result.operation, operation.isPending { + result.operation = try await wait(operation.id, timeout: options.timeout) + } + if let operation = result.operation, operation.kind != "delete", let diskId = operation.diskId { + do { result.disk = try await get(diskId) } + catch is CancellationError { throw CancellationError() } + catch { result.refreshError = error.localizedDescription } + } + return result } /// Canceling or timing out this wait never cancels the remote operation. A failed operation @@ -132,6 +142,13 @@ public struct WorkspaceDisksAPI: Sendable { private var base: String { "/disks/workspace/\(workspaceId.pathEscaped)" } public func list() async throws -> DiskList { try await disks.read(DiskList.self, base) } + public func attach(_ id: String, mountPath: String? = nil, readOnly: Bool? = nil, role: String? = nil, + target: String? = nil, options: DiskOperationOptions = .init()) async throws -> DiskMutationResult { + try await disks.attach(id, .init(workspaceId: workspaceId, mountPath: mountPath, readOnly: readOnly, role: role, target: target), options: options) + } + public func detach(_ id: String, options: DiskOperationOptions = .init()) async throws -> DiskMutationResult { + try await disks.detach(id, workspaceId: workspaceId, options: options) + } public func retainRoot(name: String? = nil, options: DiskOperationOptions = .init()) async throws -> DiskMutationResult { try await disks.mutate("POST", base + "/root", DisksAPI.NameParams(name: name), options) } @@ -191,6 +208,10 @@ public struct ManagedDisk: Codable, Sendable, Identifiable { public var kind: String? public var format: String? public var sizeMb: Int? + public var allocatedBytes: Int64? + public var retain: Bool? + public var createdAt: String? + public var updatedAt: String? public var immutable: Bool? public var ownership: String? public var rootImage: String? @@ -206,6 +227,9 @@ public struct ManagedDisk: Codable, Sendable, Identifiable { public var role: String? public var target: String? public var readOnly: Bool? + public var deviceId: String? + public var generation: Int? + public var order: Int? } } @@ -220,17 +244,55 @@ public struct DiskOperation: Codable, Sendable, Identifiable { public var phase: String? public var error: String? public var diskId: String? + public var kind: String? + public var errorCode: String? + public var createdAt: String? + public var completedAt: String? + public var result: Result? public var isPending: Bool { state == "queued" || state == "running" } + + public struct Result: Codable, Sendable { + public var sizeMb: Int? + public var wasRunning: Bool? + public var relaunched: Bool? + public var warning: String? + } + enum CodingKeys: String, CodingKey { case id, state, phase, error, diskId, kind, createdAt, completedAt, result } + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + state = try c.decode(String.self, forKey: .state) + phase = try c.decodeIfPresent(String.self, forKey: .phase) + diskId = try c.decodeIfPresent(String.self, forKey: .diskId) + kind = try c.decodeIfPresent(String.self, forKey: .kind) + createdAt = try c.decodeIfPresent(String.self, forKey: .createdAt) + completedAt = try c.decodeIfPresent(String.self, forKey: .completedAt) + result = try c.decodeIfPresent(Result.self, forKey: .result) + if let raw = try c.decodeIfPresent(JSONValue.self, forKey: .error) { + error = raw.stringValue ?? raw["message"]?.stringValue + errorCode = raw["code"]?.stringValue + } + } + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(id, forKey: .id); try c.encode(state, forKey: .state) + try c.encodeIfPresent(phase, forKey: .phase); try c.encodeIfPresent(diskId, forKey: .diskId) + try c.encodeIfPresent(kind, forKey: .kind); try c.encodeIfPresent(createdAt, forKey: .createdAt) + try c.encodeIfPresent(completedAt, forKey: .completedAt); try c.encodeIfPresent(result, forKey: .result) + if let errorCode { try c.encode(["code": errorCode, "message": error ?? ""], forKey: .error) } + else { try c.encodeIfPresent(error, forKey: .error) } + } } public struct DiskMutationResult: Codable, Sendable { + public var success: Bool? public var accepted: Bool? public var disk: ManagedDisk? public var operation: DiskOperation? /// The operation completed but refreshing its disk failed. The operation ID and /// result remain available, so a failed read cannot turn success into a duplicate mutation. public var refreshError: String? - enum CodingKeys: String, CodingKey { case accepted, disk, operation } + enum CodingKeys: String, CodingKey { case success, accepted, disk, operation } } public struct SoftwareDisk: Codable, Sendable, Identifiable { @@ -243,10 +305,26 @@ public struct SoftwareDisk: Codable, Sendable, Identifiable { public var compatibleOs: JSONValue? public var attachment: Attachment? public var image: String? + public var logo: String? + public var ownership: String? + public var readOnly: Bool? + public var kind: String? + public var format: String? + public var presets: [Preset]? + public var compatibleOperatingSystems: [Image.BaseOS]? { + get { compatibleOs.flatMap { try? OblienJSON.decode([Image.BaseOS].self, OblienJSON.encode($0)) } } + set { compatibleOs = newValue.flatMap { try? OblienJSON.decode(JSONValue.self, OblienJSON.encode($0)) } } + } + public struct Preset: Codable, Sendable { + public let id: String + public let label: String + public let image: String + } public struct Attachment: Codable, Sendable { public var target: String? public var role: String? public var readOnly: Bool? + public var mountPath: String? } } diff --git a/Sources/OblienKit/HTTPRedirectPolicy.swift b/Sources/OblienKit/HTTPRedirectPolicy.swift index cb307d7..c4d9336 100644 --- a/Sources/OblienKit/HTTPRedirectPolicy.swift +++ b/Sources/OblienKit/HTTPRedirectPolicy.swift @@ -30,7 +30,7 @@ class HTTPRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendabl if response.url?.host != request.url?.host || response.url?.scheme != request.url?.scheme || response.url?.port != request.url?.port { // URLSession normally removes Authorization across origins. Explicitly remove // the custom Oblien headers too so a proxied redirect cannot leak credentials. - for field in ["Authorization", "X-Client-ID", "X-Client-Secret", "X-Oblien-Proxy-Target"] { + for field in ["Authorization", "X-Client-ID", "X-Client-Secret", "X-Oblien-Account", "X-Oblien-Proxy-Target"] { request.setValue(nil, forHTTPHeaderField: field) } } diff --git a/Sources/OblienKit/Models.swift b/Sources/OblienKit/Models.swift index 7d6fc0f..5e12615 100644 --- a/Sources/OblienKit/Models.swift +++ b/Sources/OblienKit/Models.swift @@ -162,18 +162,22 @@ public struct WorkspaceCreateParams: Codable, Sendable { public var cpus: Int? public var memoryMb: Int? public var diskSizeMb: Int? + public var rootDiskId: String? + public var disks: [WorkspaceDiskAttachment]? public var additionalProperties: [String: JSONValue] = [:] public init(image: String? = nil, name: String? = nil, slug: String? = nil, namespace: String? = nil, mode: WorkspaceMode? = nil, type: String? = nil, config: WorkspaceConfig? = nil, preset: String? = nil, waitReady: Bool? = nil, idempotencyKey: String? = nil, readyTimeoutSeconds: Int? = nil, cpus: Int? = nil, memoryMb: Int? = nil, - diskSizeMb: Int? = nil, additionalProperties: [String: JSONValue] = [:]) { + diskSizeMb: Int? = nil, rootDiskId: String? = nil, disks: [WorkspaceDiskAttachment]? = nil, + additionalProperties: [String: JSONValue] = [:]) { self.image = image; self.name = name; self.slug = slug; self.namespace = namespace self.mode = mode; self.type = type; self.config = config self.preset = preset; self.waitReady = waitReady; self.idempotencyKey = idempotencyKey self.readyTimeoutSeconds = readyTimeoutSeconds self.cpus = cpus; self.memoryMb = memoryMb; self.diskSizeMb = diskSizeMb + self.rootDiskId = rootDiskId; self.disks = disks self.additionalProperties = additionalProperties } @@ -193,6 +197,8 @@ public struct WorkspaceCreateParams: Codable, Sendable { cpus = try fields.take("cpus", as: Int.self) memoryMb = try fields.take("memory_mb", as: Int.self) diskSizeMb = try fields.take("disk_size_mb", as: Int.self) + rootDiskId = try fields.take("root_disk_id", as: String.self) + disks = try fields.take("disks", as: [WorkspaceDiskAttachment].self) additionalProperties = fields.values } @@ -212,6 +218,8 @@ public struct WorkspaceCreateParams: Codable, Sendable { try fields.set("cpus", cpus) try fields.set("memory_mb", memoryMb) try fields.set("disk_size_mb", diskSizeMb) + try fields.set("root_disk_id", rootDiskId) + try fields.set("disks", disks) try fields.encode(to: encoder) } } @@ -273,6 +281,10 @@ public struct Workspace: Codable, Sendable { public var createdAt: String? public var updatedAt: String? public var status: String? + public var owner: AccountLabel? + public var sharing: WorkspaceSharing? + public var baseOs: Image.BaseOS? + public var preset: WorkspacePreset? public var additionalProperties: [String: JSONValue] = [:] public struct Info: Codable, Sendable { @@ -341,6 +353,10 @@ public struct Workspace: Codable, Sendable { createdAt = try fields.take("created_at", as: String.self) updatedAt = try fields.take("updated_at", as: String.self) status = try fields.take("status", as: String.self) + owner = try fields.take("owner", as: AccountLabel.self) + sharing = try fields.take("sharing", as: WorkspaceSharing.self) + baseOs = try fields.take("base_os", as: Image.BaseOS.self) + preset = try fields.take("preset", as: WorkspacePreset.self) additionalProperties = fields.values } @@ -364,6 +380,10 @@ public struct Workspace: Codable, Sendable { try fields.set("created_at", createdAt) try fields.set("updated_at", updatedAt) try fields.set("status", status) + try fields.set("owner", owner) + try fields.set("sharing", sharing) + try fields.set("base_os", baseOs) + try fields.set("preset", preset) try fields.encode(to: encoder) } } @@ -623,6 +643,33 @@ public struct Image: Codable, Sendable { public var minimumResources: Resources? public var vmDefaults: WorkspaceConfig? public var software: [JSONValue]? + public var revision: String? + public var baseImage: String? + public var boot: Boot? + public var desktop: Desktop? + + /// Typed catalog software without changing the existing extensible representation. + public var softwareMetadata: [CatalogSoftware]? { + get { software.flatMap { try? OblienJSON.decode([CatalogSoftware].self, OblienJSON.encode($0)) } } + set { software = newValue.flatMap { try? OblienJSON.decode([JSONValue].self, OblienJSON.encode($0)) } } + } + public struct Boot: Codable, Sendable { + public var workloads: [[String: JSONValue]]? + public var readyCheck: [String: JSONValue]? + } + public struct Desktop: Codable, Sendable { + public var runtimeTarget: String? + public var installable: Bool? + public var prepared: Bool? + public var vmDefaults: Resources? + public var minimumResources: Resources? + public var env: [Environment]? + public struct Environment: Codable, Sendable { + public let key: String + public var desc: String? + public let required: Bool + } + } public struct DiskTarget: Codable, Sendable { public let id: String @@ -636,11 +683,30 @@ public struct Image: Codable, Sendable { } enum CodingKeys: String, CodingKey { - case id, label, category, image, logo, color, capabilities, diskTargets, baseOs, minimumMemoryMb, preset, minimumResources, vmDefaults, software + case id, label, category, image, logo, color, capabilities, diskTargets, baseOs, minimumMemoryMb, preset, minimumResources, vmDefaults, software, revision, baseImage, boot, desktop case description = "desc" } } +public struct CatalogSoftware: Codable, Sendable, Identifiable { + public let id: String + public let label: String + public let readOnly: Bool + public let sizeMb: Int + public var role: String? + public var target: String? +} + +public struct WorkspacePreset: Codable, Sendable { + public let id: String + public let revision: String + public let label: String + public let baseImage: String + public var logo: String? + public var color: String? + public let software: [CatalogSoftware] +} + public struct ImageCategory: Codable, Sendable { public let id: String public var label: String? diff --git a/Sources/OblienKit/NamespacesAPI.swift b/Sources/OblienKit/NamespacesAPI.swift index b0727d9..1f401b8 100644 --- a/Sources/OblienKit/NamespacesAPI.swift +++ b/Sources/OblienKit/NamespacesAPI.swift @@ -41,6 +41,10 @@ public struct NamespacesAPI: Sendable { public func usage(_ id: String, _ params: NamespaceUsageParams = .init()) async throws -> APIResponse { try await transport.api("GET", path(id) + "/usage", query: APIJSON.query(params)) } + public func usageData(_ id: String, _ params: NamespaceUsageParams = .init()) async throws -> NamespaceUsageData { + let response: APIDataResponse = try await transport.api("GET", path(id) + "/usage", query: APIJSON.query(params)) + return response.data + } public func usageUnits(_ id: String, _ params: NamespaceUsageUnitsParams = .init()) async throws -> NamespaceUsageUnits { let response: APIDataResponse = try await transport.api("GET", path(id) + "/usage-units", query: APIJSON.query(params)) return response.data diff --git a/Sources/OblienKit/OblienClient.swift b/Sources/OblienKit/OblienClient.swift index 8a5dc50..c8e42e2 100644 --- a/Sources/OblienKit/OblienClient.swift +++ b/Sources/OblienKit/OblienClient.swift @@ -42,6 +42,16 @@ public struct OblienClient: Sendable { public var tokens: TokensAPI { TokensAPI(transport: transport) } public var notifications: NotificationsAPI { NotificationsAPI(transport: transport) } + /// A new transport and runtime cache; existing handles retain their account. + public func withAccount(_ accountId: String) throws -> OblienClient { + guard accountId.range(of: "^[1-9][0-9]{0,14}$", options: .regularExpression) != nil else { + throw OblienError(kind: .validation, status: nil, code: nil, message: "Invalid account ID.", details: nil) + } + var configuration = config + configuration.accountId = accountId + return OblienClient(configuration, session: session) + } + /// Returns a separate client with new credentials and no shared runtime-token cache. /// Previously created handles retain their original identity (Swift value semantics). public func withToken(_ token: String) -> OblienClient { diff --git a/Sources/OblienKit/PlatformModels/AccountDomainModels.swift b/Sources/OblienKit/PlatformModels/AccountDomainModels.swift index 4c6d562..c0a94a6 100644 --- a/Sources/OblienKit/PlatformModels/AccountDomainModels.swift +++ b/Sources/OblienKit/PlatformModels/AccountDomainModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct CheckSlugParams: Codable, Sendable { diff --git a/Sources/OblienKit/PlatformModels/AnalyticsModels.swift b/Sources/OblienKit/PlatformModels/AnalyticsModels.swift index e29c22e..965992b 100644 --- a/Sources/OblienKit/PlatformModels/AnalyticsModels.swift +++ b/Sources/OblienKit/PlatformModels/AnalyticsModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct AnalyticsOverview: Codable, Sendable { diff --git a/Sources/OblienKit/PlatformModels/BillingModels.swift b/Sources/OblienKit/PlatformModels/BillingModels.swift index 25935ea..a40697f 100644 --- a/Sources/OblienKit/PlatformModels/BillingModels.swift +++ b/Sources/OblienKit/PlatformModels/BillingModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct BillingPlan: Codable, Sendable { @@ -85,51 +85,211 @@ public struct CreditPack: Codable, Sendable { } } +public struct BillingCatalogReseller: Codable, Sendable { + @APINumber public var `contractVersion`: Double + @APIBoolean public var `offerPolicy`: Bool + @APIBoolean public var `resourceLimits`: Bool + @APIOptionalBoolean public var `effectiveResourceLimits`: Bool? + @APIOptionalBoolean public var `aggregateResourceLimits`: Bool? + public var `requiredAccountTier`: String? + + public init(`contractVersion`: Double, + `offerPolicy`: Bool, + `resourceLimits`: Bool, + `effectiveResourceLimits`: Bool? = nil, + `aggregateResourceLimits`: Bool? = nil, + `requiredAccountTier`: String? = nil) { + self.`contractVersion` = `contractVersion` + self.`offerPolicy` = `offerPolicy` + self.`resourceLimits` = `resourceLimits` + self.`effectiveResourceLimits` = `effectiveResourceLimits` + self.`aggregateResourceLimits` = `aggregateResourceLimits` + self.`requiredAccountTier` = `requiredAccountTier` + } + + enum CodingKeys: String, CodingKey { + case `contractVersion` = "contractVersion" + case `offerPolicy` = "offerPolicy" + case `resourceLimits` = "resourceLimits" + case `effectiveResourceLimits` = "effectiveResourceLimits" + case `aggregateResourceLimits` = "aggregateResourceLimits" + case `requiredAccountTier` = "requiredAccountTier" + } +} + +public struct BillingCatalogPromotionsCustom: Codable, Sendable { + public var `issuer`: String + public var `customerEntry`: String + @APIBoolean public var `firstPaymentOnly`: Bool + @APIBoolean public var `scoped`: Bool + @APIBoolean public var `capped`: Bool + + public init(`issuer`: String = "oblien_admin", + `customerEntry`: String = "oblien_hosted", + `firstPaymentOnly`: Bool, + `scoped`: Bool, + `capped`: Bool) { + self.`issuer` = `issuer` + self.`customerEntry` = `customerEntry` + self.`firstPaymentOnly` = `firstPaymentOnly` + self.`scoped` = `scoped` + self.`capped` = `capped` + } + + enum CodingKeys: String, CodingKey { + case `issuer` = "issuer" + case `customerEntry` = "customerEntry" + case `firstPaymentOnly` = "firstPaymentOnly" + case `scoped` = "scoped" + case `capped` = "capped" + } +} + +public struct BillingCatalogPromotions: Codable, Sendable { + @APIBoolean public var `enabled`: Bool + /// Accepted values: 'stripe' | 'oblien_admin'. + public var `issuer`: String + /// Accepted values: 'stripe_hosted' | 'oblien_hosted'. + public var `customerEntry`: String + /// Accepted values: 'stripe' | 'oblien'. + public var `defaultCheckoutMode`: String? + public var `checkoutModes`: [String]? + @APIOptionalBoolean public var `firstPaymentOnly`: Bool? + @APIBoolean public var `canDisable`: Bool + @APIBoolean public var `preservesCredits`: Bool + @APIBoolean public var `namespaceOptIn`: Bool + public var `custom`: BillingCatalogPromotionsCustom? + + public init(`enabled`: Bool, + `issuer`: String, + `customerEntry`: String, + `defaultCheckoutMode`: String? = nil, + `checkoutModes`: [String]? = nil, + `firstPaymentOnly`: Bool? = nil, + `canDisable`: Bool, + `preservesCredits`: Bool, + `namespaceOptIn`: Bool, + `custom`: BillingCatalogPromotionsCustom? = nil) { + self.`enabled` = `enabled` + self.`issuer` = `issuer` + self.`customerEntry` = `customerEntry` + self.`defaultCheckoutMode` = `defaultCheckoutMode` + self.`checkoutModes` = `checkoutModes` + self.`firstPaymentOnly` = `firstPaymentOnly` + self.`canDisable` = `canDisable` + self.`preservesCredits` = `preservesCredits` + self.`namespaceOptIn` = `namespaceOptIn` + self.`custom` = `custom` + } + + enum CodingKeys: String, CodingKey { + case `enabled` = "enabled" + case `issuer` = "issuer" + case `customerEntry` = "customerEntry" + case `defaultCheckoutMode` = "defaultCheckoutMode" + case `checkoutModes` = "checkoutModes" + case `firstPaymentOnly` = "firstPaymentOnly" + case `canDisable` = "canDisable" + case `preservesCredits` = "preservesCredits" + case `namespaceOptIn` = "namespaceOptIn" + case `custom` = "custom" + } +} + public struct BillingCatalog: Codable, Sendable { public var `plans`: [BillingPlan] public var `creditPacks`: [CreditPack] + public var `reseller`: BillingCatalogReseller? + public var `promotions`: BillingCatalogPromotions? public init(`plans`: [BillingPlan], - `creditPacks`: [CreditPack]) { + `creditPacks`: [CreditPack], + `reseller`: BillingCatalogReseller? = nil, + `promotions`: BillingCatalogPromotions? = nil) { self.`plans` = `plans` self.`creditPacks` = `creditPacks` + self.`reseller` = `reseller` + self.`promotions` = `promotions` } enum CodingKeys: String, CodingKey { case `plans` = "plans" case `creditPacks` = "creditPacks" + case `reseller` = "reseller" + case `promotions` = "promotions" + } +} + +public struct BillingOfferPolicy: Codable, Sendable { + @APIOptionalNumber public var `overdraft`: Double? + @APIOptionalNumber public var `suspendThreshold`: Double? + /// Accepted values: 'stop_workspaces' | 'block'. + public var `onOverdraftAction`: String? + + public init(`overdraft`: Double? = nil, + `suspendThreshold`: Double? = nil, + `onOverdraftAction`: String? = nil) { + self.`overdraft` = `overdraft` + self.`suspendThreshold` = `suspendThreshold` + self.`onOverdraftAction` = `onOverdraftAction` + } + + enum CodingKeys: String, CodingKey { + case `overdraft` = "overdraft" + case `suspendThreshold` = "suspendThreshold" + case `onOverdraftAction` = "onOverdraftAction" } } public struct BillingOffer: Codable, Sendable { + public var `billingMode`: ComputeBillingMode? + public var `capacity`: WorkspaceCapacity? + public var `tariffId`: String? public var `reference`: String? public var `name`: String public var `description`: String? @APINumber public var `unitAmount`: Double public var `currency`: String? @APINumber public var `credits`: Double + public var `policy`: BillingOfferPolicy? + public var `resourceLimits`: NamespaceResourceLimits? - public init(`reference`: String? = nil, + public init(`billingMode`: ComputeBillingMode? = nil, + `capacity`: WorkspaceCapacity? = nil, + `tariffId`: String? = nil, + `reference`: String? = nil, `name`: String, `description`: String? = nil, `unitAmount`: Double, `currency`: String? = nil, - `credits`: Double) { + `credits`: Double, + `policy`: BillingOfferPolicy? = nil, + `resourceLimits`: NamespaceResourceLimits? = nil) { + self.`billingMode` = `billingMode` + self.`capacity` = `capacity` + self.`tariffId` = `tariffId` self.`reference` = `reference` self.`name` = `name` self.`description` = `description` self.`unitAmount` = `unitAmount` self.`currency` = `currency` self.`credits` = `credits` + self.`policy` = `policy` + self.`resourceLimits` = `resourceLimits` } enum CodingKeys: String, CodingKey { + case `billingMode` = "billingMode" + case `capacity` = "capacity" + case `tariffId` = "tariffId" case `reference` = "reference" case `name` = "name" case `description` = "description" case `unitAmount` = "unitAmount" case `currency` = "currency" case `credits` = "credits" + case `policy` = "policy" + case `resourceLimits` = "resourceLimits" } } @@ -163,6 +323,9 @@ public struct CheckoutParams: Codable, Sendable { public var `cancelUrl`: String? public var `idempotencyKey`: String? public var `customer`: CheckoutParamsCustomer? + /// Accepted values: 'stripe' | 'oblien'. + public var `checkoutMode`: String? + @APIOptionalBoolean public var `allowPromotionCodes`: Bool? public init(`namespace`: String, `kind`: String, @@ -174,7 +337,9 @@ public struct CheckoutParams: Codable, Sendable { `successUrl`: String? = nil, `cancelUrl`: String? = nil, `idempotencyKey`: String? = nil, - `customer`: CheckoutParamsCustomer? = nil) { + `customer`: CheckoutParamsCustomer? = nil, + `checkoutMode`: String? = nil, + `allowPromotionCodes`: Bool? = nil) { self.`namespace` = `namespace` self.`kind` = `kind` self.`planTierId` = `planTierId` @@ -186,6 +351,8 @@ public struct CheckoutParams: Codable, Sendable { self.`cancelUrl` = `cancelUrl` self.`idempotencyKey` = `idempotencyKey` self.`customer` = `customer` + self.`checkoutMode` = `checkoutMode` + self.`allowPromotionCodes` = `allowPromotionCodes` } enum CodingKeys: String, CodingKey { @@ -200,6 +367,8 @@ public struct CheckoutParams: Codable, Sendable { case `cancelUrl` = "cancelUrl" case `idempotencyKey` = "idempotencyKey" case `customer` = "customer" + case `checkoutMode` = "checkoutMode" + case `allowPromotionCodes` = "allowPromotionCodes" } } @@ -223,6 +392,30 @@ public struct CheckoutResponse: Codable, Sendable { } } +public struct BillingCheckoutPrice: Codable, Sendable { + @APINumber public var `subtotal`: Double + @APINumber public var `discount`: Int + @APINumber public var `total`: Int + public var `currency`: String + + public init(`subtotal`: Double, + `discount`: Int, + `total`: Int, + `currency`: String) { + self.`subtotal` = `subtotal` + self.`discount` = `discount` + self.`total` = `total` + self.`currency` = `currency` + } + + enum CodingKeys: String, CodingKey { + case `subtotal` = "subtotal" + case `discount` = "discount" + case `total` = "total" + case `currency` = "currency" + } +} + public struct BillingCheckout: Codable, Sendable { public var `id`: String /// Accepted values: 'subscription' | 'topup'. @@ -234,13 +427,17 @@ public struct BillingCheckout: Codable, Sendable { @APIBoolean public var `fulfilled`: Bool public var `offer`: BillingOffer public var `metadata`: [String: String] - /// Accepted values: 'pending' | 'completed' | 'partially_refunded' | 'refunded' | 'disputed' | 'expired' | 'failed'. + /// Accepted values: 'pending' | 'completed' | 'partially_refunded' | 'refunded' | 'disputed' | 'expired' | 'failed' | 'superseded' | 'reversed'. public var `fulfillmentStatus`: String @APINumber public var `walletCreditsGranted`: Double + @APIOptionalNumber public var `walletCreditsFunded`: Double? + @APIOptionalNumber public var `capacityCreditsCharged`: Double? + @APIOptionalNumber public var `walletCreditDelta`: Double? @APINumber public var `namespaceCreditsGranted`: Double /// Accepted values: 'monthly' | 'yearly' | null. public var `billingInterval`: String? public var `subscriptionId`: String? + public var `price`: BillingCheckoutPrice? public init(`id`: String, `kind`: String, @@ -251,9 +448,13 @@ public struct BillingCheckout: Codable, Sendable { `metadata`: [String: String], `fulfillmentStatus`: String, `walletCreditsGranted`: Double, + `walletCreditsFunded`: Double? = nil, + `capacityCreditsCharged`: Double? = nil, + `walletCreditDelta`: Double? = nil, `namespaceCreditsGranted`: Double, `billingInterval`: String? = nil, - `subscriptionId`: String? = nil) { + `subscriptionId`: String? = nil, + `price`: BillingCheckoutPrice? = nil) { self.`id` = `id` self.`kind` = `kind` self.`status` = `status` @@ -263,9 +464,13 @@ public struct BillingCheckout: Codable, Sendable { self.`metadata` = `metadata` self.`fulfillmentStatus` = `fulfillmentStatus` self.`walletCreditsGranted` = `walletCreditsGranted` + self.`walletCreditsFunded` = `walletCreditsFunded` + self.`capacityCreditsCharged` = `capacityCreditsCharged` + self.`walletCreditDelta` = `walletCreditDelta` self.`namespaceCreditsGranted` = `namespaceCreditsGranted` self.`billingInterval` = `billingInterval` self.`subscriptionId` = `subscriptionId` + self.`price` = `price` } enum CodingKeys: String, CodingKey { @@ -278,9 +483,13 @@ public struct BillingCheckout: Codable, Sendable { case `metadata` = "metadata" case `fulfillmentStatus` = "fulfillmentStatus" case `walletCreditsGranted` = "walletCreditsGranted" + case `walletCreditsFunded` = "walletCreditsFunded" + case `capacityCreditsCharged` = "capacityCreditsCharged" + case `walletCreditDelta` = "walletCreditDelta" case `namespaceCreditsGranted` = "namespaceCreditsGranted" case `billingInterval` = "billingInterval" case `subscriptionId` = "subscriptionId" + case `price` = "price" } } @@ -352,6 +561,7 @@ public struct BillingSubscription: Codable, Sendable { public var `canceledAt`: String? public var `offer`: BillingOffer? public var `metadata`: [String: String]? + public var `pendingChange`: BillingPlanChange? public init(`tierId`: String, `status`: String, @@ -361,7 +571,8 @@ public struct BillingSubscription: Codable, Sendable { `cancelAtPeriodEnd`: Bool, `canceledAt`: String? = nil, `offer`: BillingOffer? = nil, - `metadata`: [String: String]? = nil) { + `metadata`: [String: String]? = nil, + `pendingChange`: BillingPlanChange? = nil) { self.`tierId` = `tierId` self.`status` = `status` self.`billingInterval` = `billingInterval` @@ -371,6 +582,7 @@ public struct BillingSubscription: Codable, Sendable { self.`canceledAt` = `canceledAt` self.`offer` = `offer` self.`metadata` = `metadata` + self.`pendingChange` = `pendingChange` } enum CodingKeys: String, CodingKey { @@ -383,6 +595,7 @@ public struct BillingSubscription: Codable, Sendable { case `canceledAt` = "canceledAt" case `offer` = "offer" case `metadata` = "metadata" + case `pendingChange` = "pendingChange" } } @@ -406,6 +619,296 @@ public struct BillingSubscriptionResponse: Codable, Sendable { } } +public struct PreviewPlanChangeParams: Codable, Sendable { + public var `offer`: BillingOffer + public var `metadata`: [String: String]? + /// Accepted values: 'monthly' | 'yearly'. + public var `billingInterval`: String? + public var `idempotencyKey`: String + + public init(`offer`: BillingOffer, + `metadata`: [String: String]? = nil, + `billingInterval`: String? = nil, + `idempotencyKey`: String) { + self.`offer` = `offer` + self.`metadata` = `metadata` + self.`billingInterval` = `billingInterval` + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `offer` = "offer" + case `metadata` = "metadata" + case `billingInterval` = "billingInterval" + case `idempotencyKey` = "idempotencyKey" + } +} + +public struct BillingPlanChangeQuote: Codable, Sendable { + public var `id`: String + public var `namespace`: String + /// Accepted values: 'upgrade' | 'downgrade'. + public var `direction`: String + public var `expiresAt`: String + public var `effectiveAt`: String + /// Accepted values: 'monthly' | 'yearly'. + public var `billingInterval`: String + public var `current`: BillingOffer + public var `next`: BillingOffer + public var `currency`: String + @APINumber public var `unusedTimeCredit`: Double + @APINumber public var `remainingTimeCharge`: Double + @APINumber public var `amountDueNow`: Double + @APIOptionalNumber public var `nextInvoiceAmount`: Double? + @APINumber public var `includedCreditIncrease`: Double + @APIBoolean public var `preservesUsage`: Bool + @APIBoolean public var `preservesPurchasedCredits`: Bool + + public init(`id`: String, + `namespace`: String, + `direction`: String, + `expiresAt`: String, + `effectiveAt`: String, + `billingInterval`: String, + `current`: BillingOffer, + `next`: BillingOffer, + `currency`: String = "usd", + `unusedTimeCredit`: Double, + `remainingTimeCharge`: Double, + `amountDueNow`: Double, + `nextInvoiceAmount`: Double? = nil, + `includedCreditIncrease`: Double, + `preservesUsage`: Bool, + `preservesPurchasedCredits`: Bool) { + self.`id` = `id` + self.`namespace` = `namespace` + self.`direction` = `direction` + self.`expiresAt` = `expiresAt` + self.`effectiveAt` = `effectiveAt` + self.`billingInterval` = `billingInterval` + self.`current` = `current` + self.`next` = `next` + self.`currency` = `currency` + self.`unusedTimeCredit` = `unusedTimeCredit` + self.`remainingTimeCharge` = `remainingTimeCharge` + self.`amountDueNow` = `amountDueNow` + self.`nextInvoiceAmount` = `nextInvoiceAmount` + self.`includedCreditIncrease` = `includedCreditIncrease` + self.`preservesUsage` = `preservesUsage` + self.`preservesPurchasedCredits` = `preservesPurchasedCredits` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `namespace` = "namespace" + case `direction` = "direction" + case `expiresAt` = "expiresAt" + case `effectiveAt` = "effectiveAt" + case `billingInterval` = "billingInterval" + case `current` = "current" + case `next` = "next" + case `currency` = "currency" + case `unusedTimeCredit` = "unusedTimeCredit" + case `remainingTimeCharge` = "remainingTimeCharge" + case `amountDueNow` = "amountDueNow" + case `nextInvoiceAmount` = "nextInvoiceAmount" + case `includedCreditIncrease` = "includedCreditIncrease" + case `preservesUsage` = "preservesUsage" + case `preservesPurchasedCredits` = "preservesPurchasedCredits" + } +} + +public struct BillingPlanChangeQuoteResponse: Codable, Sendable { + @APIBoolean public var `success`: Bool + public var `namespace`: String + public var `quote`: BillingPlanChangeQuote + + public init(`success`: Bool, + `namespace`: String, + `quote`: BillingPlanChangeQuote) { + self.`success` = `success` + self.`namespace` = `namespace` + self.`quote` = `quote` + } + + enum CodingKeys: String, CodingKey { + case `success` = "success" + case `namespace` = "namespace" + case `quote` = "quote" + } +} + +public struct ChangePlanParams: Codable, Sendable { + public var `quoteId`: String + public var `idempotencyKey`: String + + public init(`quoteId`: String, + `idempotencyKey`: String) { + self.`quoteId` = `quoteId` + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `quoteId` = "quoteId" + case `idempotencyKey` = "idempotencyKey" + } +} + +/// Open string enum; preserves new server values. +public struct BillingPlanChangeStatus: RawRepresentable, Codable, Sendable, Hashable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + public init(from decoder: Decoder) throws { rawValue = try decoder.singleValueContainer().decode(String.self) } + public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) } + public static let `queued` = Self(rawValue: "queued") + public static let `dispatching` = Self(rawValue: "dispatching") + public static let `paymentPending` = Self(rawValue: "payment_pending") + public static let `scheduled` = Self(rawValue: "scheduled") + public static let `canceling` = Self(rawValue: "canceling") + public static let `reconciliationRequired` = Self(rawValue: "reconciliation_required") + public static let `applied` = Self(rawValue: "applied") + public static let `canceled` = Self(rawValue: "canceled") + public static let `expired` = Self(rawValue: "expired") + public static let `failed` = Self(rawValue: "failed") +} + +public struct BillingPlanChangePayment: Codable, Sendable { + public var `status`: String + public var `url`: String? + public var `expiresAt`: String? + + public init(`status`: String, + `url`: String? = nil, + `expiresAt`: String? = nil) { + self.`status` = `status` + self.`url` = `url` + self.`expiresAt` = `expiresAt` + } + + enum CodingKeys: String, CodingKey { + case `status` = "status" + case `url` = "url" + case `expiresAt` = "expiresAt" + } +} + +public struct BillingPlanChangeError: Codable, Sendable { + public var `code`: String + public var `message`: String + + public init(`code`: String, + `message`: String) { + self.`code` = `code` + self.`message` = `message` + } + + enum CodingKeys: String, CodingKey { + case `code` = "code" + case `message` = "message" + } +} + +public struct BillingPlanChange: Codable, Sendable { + public var `id`: String + public var `quoteId`: String + public var `namespace`: String + /// Accepted values: 'upgrade' | 'downgrade'. + public var `direction`: String + public var `status`: BillingPlanChangeStatus + public var `effectiveAt`: String + public var `current`: BillingOffer + public var `next`: BillingOffer + @APINumber public var `amountDueNow`: Double + public var `currency`: String + @APINumber public var `includedCreditIncrease`: Double + public var `payment`: BillingPlanChangePayment? + public var `error`: BillingPlanChangeError? + @APIBoolean public var `cancelable`: Bool + public var `appliedAt`: String? + + public init(`id`: String, + `quoteId`: String, + `namespace`: String, + `direction`: String, + `status`: BillingPlanChangeStatus, + `effectiveAt`: String, + `current`: BillingOffer, + `next`: BillingOffer, + `amountDueNow`: Double, + `currency`: String = "usd", + `includedCreditIncrease`: Double, + `payment`: BillingPlanChangePayment? = nil, + `error`: BillingPlanChangeError? = nil, + `cancelable`: Bool, + `appliedAt`: String? = nil) { + self.`id` = `id` + self.`quoteId` = `quoteId` + self.`namespace` = `namespace` + self.`direction` = `direction` + self.`status` = `status` + self.`effectiveAt` = `effectiveAt` + self.`current` = `current` + self.`next` = `next` + self.`amountDueNow` = `amountDueNow` + self.`currency` = `currency` + self.`includedCreditIncrease` = `includedCreditIncrease` + self.`payment` = `payment` + self.`error` = `error` + self.`cancelable` = `cancelable` + self.`appliedAt` = `appliedAt` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `quoteId` = "quoteId" + case `namespace` = "namespace" + case `direction` = "direction" + case `status` = "status" + case `effectiveAt` = "effectiveAt" + case `current` = "current" + case `next` = "next" + case `amountDueNow` = "amountDueNow" + case `currency` = "currency" + case `includedCreditIncrease` = "includedCreditIncrease" + case `payment` = "payment" + case `error` = "error" + case `cancelable` = "cancelable" + case `appliedAt` = "appliedAt" + } +} + +public struct BillingPlanChangeResponse: Codable, Sendable { + @APIBoolean public var `success`: Bool + public var `namespace`: String + public var `change`: BillingPlanChange + + public init(`success`: Bool, + `namespace`: String, + `change`: BillingPlanChange) { + self.`success` = `success` + self.`namespace` = `namespace` + self.`change` = `change` + } + + enum CodingKeys: String, CodingKey { + case `success` = "success" + case `namespace` = "namespace" + case `change` = "change" + } +} + +public struct CancelPlanChangeParams: Codable, Sendable { + public var `idempotencyKey`: String + + public init(`idempotencyKey`: String) { + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `idempotencyKey` = "idempotencyKey" + } +} + public struct ResetQuotaParams: Codable, Sendable { public var `periodEnd`: String @@ -451,21 +954,33 @@ public struct EntitlementStatus: RawRepresentable, Codable, Sendable, Hashable { } public struct EntitlementQuota: Codable, Sendable { + public var `alert`: NamespaceQuotaAlert? @APIOptionalNumber public var `limit`: Int? @APINumber public var `used`: Double + @APIOptionalNumber public var `overdraft`: Double? + @APIOptionalNumber public var `suspendThreshold`: Double? @APIOptionalNumber public var `balance`: Double? - public init(`limit`: Int? = nil, + public init(`alert`: NamespaceQuotaAlert? = nil, + `limit`: Int? = nil, `used`: Double, + `overdraft`: Double? = nil, + `suspendThreshold`: Double? = nil, `balance`: Double? = nil) { + self.`alert` = `alert` self.`limit` = `limit` self.`used` = `used` + self.`overdraft` = `overdraft` + self.`suspendThreshold` = `suspendThreshold` self.`balance` = `balance` } enum CodingKeys: String, CodingKey { + case `alert` = "alert" case `limit` = "limit" case `used` = "used" + case `overdraft` = "overdraft" + case `suspendThreshold` = "suspendThreshold" case `balance` = "balance" } } @@ -477,19 +992,28 @@ public struct Entitlement: Codable, Sendable { public var `periodStart`: String? public var `periodEnd`: String? public var `quota`: EntitlementQuota + public var `billingMode`: ComputeBillingMode? + @APIOptionalBoolean public var `computeCovered`: Bool? + public var `capacity`: NamespaceCapacity? public init(`namespace`: String, `tierId`: String, `status`: EntitlementStatus, `periodStart`: String? = nil, `periodEnd`: String? = nil, - `quota`: EntitlementQuota) { + `quota`: EntitlementQuota, + `billingMode`: ComputeBillingMode? = nil, + `computeCovered`: Bool? = nil, + `capacity`: NamespaceCapacity? = nil) { self.`namespace` = `namespace` self.`tierId` = `tierId` self.`status` = `status` self.`periodStart` = `periodStart` self.`periodEnd` = `periodEnd` self.`quota` = `quota` + self.`billingMode` = `billingMode` + self.`computeCovered` = `computeCovered` + self.`capacity` = `capacity` } enum CodingKeys: String, CodingKey { @@ -499,26 +1023,45 @@ public struct Entitlement: Codable, Sendable { case `periodStart` = "periodStart" case `periodEnd` = "periodEnd" case `quota` = "quota" + case `billingMode` = "billingMode" + case `computeCovered` = "computeCovered" + case `capacity` = "capacity" } } public struct BillingBalance: Codable, Sendable { + public var `alert`: NamespaceQuotaAlert? public var `namespace`: String @APIBoolean public var `blocking`: Bool @APIOptionalNumber public var `balance`: Double? + public var `billingMode`: ComputeBillingMode? + @APIOptionalBoolean public var `computeCovered`: Bool? + public var `paidThrough`: String? - public init(`namespace`: String, + public init(`alert`: NamespaceQuotaAlert? = nil, + `namespace`: String, `blocking`: Bool, - `balance`: Double? = nil) { + `balance`: Double? = nil, + `billingMode`: ComputeBillingMode? = nil, + `computeCovered`: Bool? = nil, + `paidThrough`: String? = nil) { + self.`alert` = `alert` self.`namespace` = `namespace` self.`blocking` = `blocking` self.`balance` = `balance` + self.`billingMode` = `billingMode` + self.`computeCovered` = `computeCovered` + self.`paidThrough` = `paidThrough` } enum CodingKeys: String, CodingKey { + case `alert` = "alert" case `namespace` = "namespace" case `blocking` = "blocking" case `balance` = "balance" + case `billingMode` = "billingMode" + case `computeCovered` = "computeCovered" + case `paidThrough` = "paidThrough" } } @@ -643,3 +1186,931 @@ public struct BillingDefaultsParams: Codable, Sendable { case `onOverdraftAction` = "onOverdraftAction" } } + +/// Open string enum; preserves new server values. +public struct ComputeBillingMode: RawRepresentable, Codable, Sendable, Hashable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + public init(from decoder: Decoder) throws { rawValue = try decoder.singleValueContainer().decode(String.self) } + public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) } + public static let `payg` = Self(rawValue: "payg") + public static let `monthly` = Self(rawValue: "monthly") +} + +public struct WorkspaceCapacity: Codable, Sendable { + @APINumber public var `vcpus`: Double + @APINumber public var `memoryMb`: Int + @APINumber public var `diskGb`: Int + @APINumber public var `workspaces`: Double + + public init(`vcpus`: Double, + `memoryMb`: Int, + `diskGb`: Int, + `workspaces`: Double) { + self.`vcpus` = `vcpus` + self.`memoryMb` = `memoryMb` + self.`diskGb` = `diskGb` + self.`workspaces` = `workspaces` + } + + enum CodingKeys: String, CodingKey { + case `vcpus` = "vcpus" + case `memoryMb` = "memoryMb" + case `diskGb` = "diskGb" + case `workspaces` = "workspaces" + } +} + +public struct CapacityTariffMonthly: Codable, Sendable { + @APINumber public var `vcpuCents`: Double + @APINumber public var `memoryGiBCents`: Double + @APINumber public var `diskGiBCents`: Double + @APINumber public var `minimumCents`: Double + + public init(`vcpuCents`: Double, + `memoryGiBCents`: Double, + `diskGiBCents`: Double, + `minimumCents`: Double) { + self.`vcpuCents` = `vcpuCents` + self.`memoryGiBCents` = `memoryGiBCents` + self.`diskGiBCents` = `diskGiBCents` + self.`minimumCents` = `minimumCents` + } + + enum CodingKeys: String, CodingKey { + case `vcpuCents` = "vcpuCents" + case `memoryGiBCents` = "memoryGiBCents" + case `diskGiBCents` = "diskGiBCents" + case `minimumCents` = "minimumCents" + } +} + +public struct CapacityTariffUsage: Codable, Sendable { + @APINumber public var `activeVcpuHourCents`: Double + @APINumber public var `reservedGiBHourCents`: Double + @APINumber public var `retainedGiBMonthCents`: Double + @APINumber public var `monthHours`: Double + + public init(`activeVcpuHourCents`: Double, + `reservedGiBHourCents`: Double, + `retainedGiBMonthCents`: Double, + `monthHours`: Double) { + self.`activeVcpuHourCents` = `activeVcpuHourCents` + self.`reservedGiBHourCents` = `reservedGiBHourCents` + self.`retainedGiBMonthCents` = `retainedGiBMonthCents` + self.`monthHours` = `monthHours` + } + + enum CodingKeys: String, CodingKey { + case `activeVcpuHourCents` = "activeVcpuHourCents" + case `reservedGiBHourCents` = "reservedGiBHourCents" + case `retainedGiBMonthCents` = "retainedGiBMonthCents" + case `monthHours` = "monthHours" + } +} + +public struct CapacityTariffNetwork: Codable, Sendable { + @APINumber public var `managedProxyGiBCents`: Double + @APINumber public var `minimumTopupCents`: Double + + public init(`managedProxyGiBCents`: Double, + `minimumTopupCents`: Double) { + self.`managedProxyGiBCents` = `managedProxyGiBCents` + self.`minimumTopupCents` = `minimumTopupCents` + } + + enum CodingKeys: String, CodingKey { + case `managedProxyGiBCents` = "managedProxyGiBCents" + case `minimumTopupCents` = "minimumTopupCents" + } +} + +public struct CapacityTariffTerms: Codable, Sendable { + public var `cpuClass`: String + @APIBoolean public var `networkIncluded`: Bool + @APIBoolean public var `backupsIncluded`: Bool + @APIBoolean public var `autoRenewDefault`: Bool + public var `calendar`: String + @APINumber public var `expiryGraceHours`: Double + @APINumber public var `retainedAfterExpiryDays`: Double + @APIBoolean public var `automaticDeletion`: Bool + public var `retentionBilling`: String + + public init(`cpuClass`: String = "shared", + `networkIncluded`: Bool, + `backupsIncluded`: Bool, + `autoRenewDefault`: Bool, + `calendar`: String = "subscription_anniversary", + `expiryGraceHours`: Double, + `retainedAfterExpiryDays`: Double, + `automaticDeletion`: Bool, + `retentionBilling`: String = "storage_until_deleted") { + self.`cpuClass` = `cpuClass` + self.`networkIncluded` = `networkIncluded` + self.`backupsIncluded` = `backupsIncluded` + self.`autoRenewDefault` = `autoRenewDefault` + self.`calendar` = `calendar` + self.`expiryGraceHours` = `expiryGraceHours` + self.`retainedAfterExpiryDays` = `retainedAfterExpiryDays` + self.`automaticDeletion` = `automaticDeletion` + self.`retentionBilling` = `retentionBilling` + } + + enum CodingKeys: String, CodingKey { + case `cpuClass` = "cpuClass" + case `networkIncluded` = "networkIncluded" + case `backupsIncluded` = "backupsIncluded" + case `autoRenewDefault` = "autoRenewDefault" + case `calendar` = "calendar" + case `expiryGraceHours` = "expiryGraceHours" + case `retainedAfterExpiryDays` = "retainedAfterExpiryDays" + case `automaticDeletion` = "automaticDeletion" + case `retentionBilling` = "retentionBilling" + } +} + +public struct CapacityTariff: Codable, Sendable { + public var `id`: String + public var `currency`: String + @APINumber public var `creditsPerDollar`: Double + public var `monthly`: CapacityTariffMonthly + @APINumber public var `paygCapPercent`: Int + public var `usage`: CapacityTariffUsage + public var `network`: CapacityTariffNetwork + @APINumber public var `requiredMeterVersion`: Double + public var `terms`: CapacityTariffTerms + + public init(`id`: String, + `currency`: String = "usd", + `creditsPerDollar`: Double, + `monthly`: CapacityTariffMonthly, + `paygCapPercent`: Int, + `usage`: CapacityTariffUsage, + `network`: CapacityTariffNetwork, + `requiredMeterVersion`: Double, + `terms`: CapacityTariffTerms) { + self.`id` = `id` + self.`currency` = `currency` + self.`creditsPerDollar` = `creditsPerDollar` + self.`monthly` = `monthly` + self.`paygCapPercent` = `paygCapPercent` + self.`usage` = `usage` + self.`network` = `network` + self.`requiredMeterVersion` = `requiredMeterVersion` + self.`terms` = `terms` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `currency` = "currency" + case `creditsPerDollar` = "creditsPerDollar" + case `monthly` = "monthly" + case `paygCapPercent` = "paygCapPercent" + case `usage` = "usage" + case `network` = "network" + case `requiredMeterVersion` = "requiredMeterVersion" + case `terms` = "terms" + } +} + +public struct CapacityCatalogPresetsItem: Codable, Sendable { + public var `id`: String + public var `capacity`: WorkspaceCapacity + @APINumber public var `monthlyAmount`: Double + @APINumber public var `paygCapAmount`: Double + public var `resourceLimits`: NamespaceResourceLimits + + public init(`id`: String, + `capacity`: WorkspaceCapacity, + `monthlyAmount`: Double, + `paygCapAmount`: Double, + `resourceLimits`: NamespaceResourceLimits) { + self.`id` = `id` + self.`capacity` = `capacity` + self.`monthlyAmount` = `monthlyAmount` + self.`paygCapAmount` = `paygCapAmount` + self.`resourceLimits` = `resourceLimits` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `capacity` = "capacity" + case `monthlyAmount` = "monthlyAmount" + case `paygCapAmount` = "paygCapAmount" + case `resourceLimits` = "resourceLimits" + } +} + +public struct CapacityCatalog: Codable, Sendable { + public var `currency`: String + public var `billingModes`: [ComputeBillingMode] + public var `tariffId`: String + public var `tariff`: CapacityTariff + public var `paymentSources`: [String: [String]] + public var `presets`: [CapacityCatalogPresetsItem] + + public init(`currency`: String = "usd", + `billingModes`: [ComputeBillingMode], + `tariffId`: String, + `tariff`: CapacityTariff, + `paymentSources`: [String: [String]], + `presets`: [CapacityCatalogPresetsItem]) { + self.`currency` = `currency` + self.`billingModes` = `billingModes` + self.`tariffId` = `tariffId` + self.`tariff` = `tariff` + self.`paymentSources` = `paymentSources` + self.`presets` = `presets` + } + + enum CodingKeys: String, CodingKey { + case `currency` = "currency" + case `billingModes` = "billingModes" + case `tariffId` = "tariffId" + case `tariff` = "tariff" + case `paymentSources` = "paymentSources" + case `presets` = "presets" + } +} + +public struct CapacityQuoteCurrent: Codable, Sendable { + public var `capacity`: WorkspaceCapacity + public var `billingMode`: ComputeBillingMode + @APINumber public var `monthlyAmount`: Double + + public init(`capacity`: WorkspaceCapacity, + `billingMode`: ComputeBillingMode, + `monthlyAmount`: Double) { + self.`capacity` = `capacity` + self.`billingMode` = `billingMode` + self.`monthlyAmount` = `monthlyAmount` + } + + enum CodingKeys: String, CodingKey { + case `capacity` = "capacity" + case `billingMode` = "billingMode" + case `monthlyAmount` = "monthlyAmount" + } +} + +public struct CapacityQuote: Codable, Sendable { + public var `id`: String + public var `namespace`: String + public var `status`: String + /// Accepted values: 'start' | 'upgrade' | 'scheduled' | 'network_topup'. + public var `action`: String + public var `expiresAt`: String + public var `effectiveAt`: String + public var `periodEnd`: String? + public var `billingMode`: ComputeBillingMode + /// Accepted values: 'wallet' | 'stripe'. + public var `paymentSource`: String + public var `currency`: String + public var `current`: CapacityQuoteCurrent? + public var `capacity`: WorkspaceCapacity? + public var `tariffId`: String + @APIOptionalNumber public var `monthlyAmount`: Double? + @APIOptionalNumber public var `paygCapAmount`: Double? + @APINumber public var `unusedTimeCredit`: Double + @APINumber public var `remainingTimeCharge`: Double + @APINumber public var `amountDueNow`: Double + @APINumber public var `walletCreditsRequired`: Double + @APINumber public var `retainedStorageAmountDue`: Double + @APIOptionalNumber public var `nextPaymentAmount`: Double? + @APIBoolean public var `autoRenew`: Bool + @APIBoolean public var `networkIncluded`: Bool + @APIOptionalNumber public var `networkBytes`: Int? + @APIBoolean public var `preservesUsage`: Bool + @APIBoolean public var `preservesPurchasedCredits`: Bool + + public init(`id`: String, + `namespace`: String, + `status`: String, + `action`: String, + `expiresAt`: String, + `effectiveAt`: String, + `periodEnd`: String? = nil, + `billingMode`: ComputeBillingMode, + `paymentSource`: String, + `currency`: String = "usd", + `current`: CapacityQuoteCurrent? = nil, + `capacity`: WorkspaceCapacity? = nil, + `tariffId`: String, + `monthlyAmount`: Double? = nil, + `paygCapAmount`: Double? = nil, + `unusedTimeCredit`: Double, + `remainingTimeCharge`: Double, + `amountDueNow`: Double, + `walletCreditsRequired`: Double, + `retainedStorageAmountDue`: Double, + `nextPaymentAmount`: Double? = nil, + `autoRenew`: Bool, + `networkIncluded`: Bool, + `networkBytes`: Int? = nil, + `preservesUsage`: Bool, + `preservesPurchasedCredits`: Bool) { + self.`id` = `id` + self.`namespace` = `namespace` + self.`status` = `status` + self.`action` = `action` + self.`expiresAt` = `expiresAt` + self.`effectiveAt` = `effectiveAt` + self.`periodEnd` = `periodEnd` + self.`billingMode` = `billingMode` + self.`paymentSource` = `paymentSource` + self.`currency` = `currency` + self.`current` = `current` + self.`capacity` = `capacity` + self.`tariffId` = `tariffId` + self.`monthlyAmount` = `monthlyAmount` + self.`paygCapAmount` = `paygCapAmount` + self.`unusedTimeCredit` = `unusedTimeCredit` + self.`remainingTimeCharge` = `remainingTimeCharge` + self.`amountDueNow` = `amountDueNow` + self.`walletCreditsRequired` = `walletCreditsRequired` + self.`retainedStorageAmountDue` = `retainedStorageAmountDue` + self.`nextPaymentAmount` = `nextPaymentAmount` + self.`autoRenew` = `autoRenew` + self.`networkIncluded` = `networkIncluded` + self.`networkBytes` = `networkBytes` + self.`preservesUsage` = `preservesUsage` + self.`preservesPurchasedCredits` = `preservesPurchasedCredits` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `namespace` = "namespace" + case `status` = "status" + case `action` = "action" + case `expiresAt` = "expiresAt" + case `effectiveAt` = "effectiveAt" + case `periodEnd` = "periodEnd" + case `billingMode` = "billingMode" + case `paymentSource` = "paymentSource" + case `currency` = "currency" + case `current` = "current" + case `capacity` = "capacity" + case `tariffId` = "tariffId" + case `monthlyAmount` = "monthlyAmount" + case `paygCapAmount` = "paygCapAmount" + case `unusedTimeCredit` = "unusedTimeCredit" + case `remainingTimeCharge` = "remainingTimeCharge" + case `amountDueNow` = "amountDueNow" + case `walletCreditsRequired` = "walletCreditsRequired" + case `retainedStorageAmountDue` = "retainedStorageAmountDue" + case `nextPaymentAmount` = "nextPaymentAmount" + case `autoRenew` = "autoRenew" + case `networkIncluded` = "networkIncluded" + case `networkBytes` = "networkBytes" + case `preservesUsage` = "preservesUsage" + case `preservesPurchasedCredits` = "preservesPurchasedCredits" + } +} + +public struct CapacitySavings: Codable, Sendable { + public var `currency`: String + public var `baseline`: String + @APINumber public var `usageBeforeCap`: Double + @APINumber public var `capDiscount`: Int + @APINumber public var `usageAfterCap`: Double + @APINumber public var `usageCharged`: Double + @APINumber public var `prepaidAmount`: Double + @APINumber public var `monthlyDifference`: Double + @APIBoolean public var `networkIncluded`: Bool + @APIBoolean public var `refundsIncluded`: Bool + + public init(`currency`: String = "usd", + `baseline`: String = "recorded_usage_at_saved_payg_rates", + `usageBeforeCap`: Double, + `capDiscount`: Int, + `usageAfterCap`: Double, + `usageCharged`: Double, + `prepaidAmount`: Double, + `monthlyDifference`: Double, + `networkIncluded`: Bool, + `refundsIncluded`: Bool) { + self.`currency` = `currency` + self.`baseline` = `baseline` + self.`usageBeforeCap` = `usageBeforeCap` + self.`capDiscount` = `capDiscount` + self.`usageAfterCap` = `usageAfterCap` + self.`usageCharged` = `usageCharged` + self.`prepaidAmount` = `prepaidAmount` + self.`monthlyDifference` = `monthlyDifference` + self.`networkIncluded` = `networkIncluded` + self.`refundsIncluded` = `refundsIncluded` + } + + enum CodingKeys: String, CodingKey { + case `currency` = "currency" + case `baseline` = "baseline" + case `usageBeforeCap` = "usageBeforeCap" + case `capDiscount` = "capDiscount" + case `usageAfterCap` = "usageAfterCap" + case `usageCharged` = "usageCharged" + case `prepaidAmount` = "prepaidAmount" + case `monthlyDifference` = "monthlyDifference" + case `networkIncluded` = "networkIncluded" + case `refundsIncluded` = "refundsIncluded" + } +} + +public struct NamespaceCapacityRetention: Codable, Sendable { + @APINumber public var `minimumDays`: Double + @APIBoolean public var `automaticDeletion`: Bool + public var `reviewAt`: String + @APINumber public var `storagePerGiBMonth`: Double + @APINumber public var `amountDue`: Double + public var `currency`: String + + public init(`minimumDays`: Double, + `automaticDeletion`: Bool, + `reviewAt`: String, + `storagePerGiBMonth`: Double, + `amountDue`: Double, + `currency`: String = "usd") { + self.`minimumDays` = `minimumDays` + self.`automaticDeletion` = `automaticDeletion` + self.`reviewAt` = `reviewAt` + self.`storagePerGiBMonth` = `storagePerGiBMonth` + self.`amountDue` = `amountDue` + self.`currency` = `currency` + } + + enum CodingKeys: String, CodingKey { + case `minimumDays` = "minimumDays" + case `automaticDeletion` = "automaticDeletion" + case `reviewAt` = "reviewAt" + case `storagePerGiBMonth` = "storagePerGiBMonth" + case `amountDue` = "amountDue" + case `currency` = "currency" + } +} + +public struct NamespaceCapacityPendingChange: Codable, Sendable { + public var `id`: String + public var `billingMode`: ComputeBillingMode + public var `capacity`: WorkspaceCapacity + @APINumber public var `monthlyAmount`: Double + public var `effectiveAt`: String + + public init(`id`: String, + `billingMode`: ComputeBillingMode, + `capacity`: WorkspaceCapacity, + `monthlyAmount`: Double, + `effectiveAt`: String) { + self.`id` = `id` + self.`billingMode` = `billingMode` + self.`capacity` = `capacity` + self.`monthlyAmount` = `monthlyAmount` + self.`effectiveAt` = `effectiveAt` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `billingMode` = "billingMode" + case `capacity` = "capacity" + case `monthlyAmount` = "monthlyAmount" + case `effectiveAt` = "effectiveAt" + } +} + +public struct NamespaceCapacityNetwork: Codable, Sendable { + public var `service`: String + @APIBoolean public var `included`: Bool + @APINumber public var `purchasedBytes`: Int + @APINumber public var `consumedBytes`: Int + @APINumber public var `reservedBytes`: Int + @APINumber public var `availableBytes`: Int + + public init(`service`: String = "managed_proxy_transfer", + `included`: Bool, + `purchasedBytes`: Int, + `consumedBytes`: Int, + `reservedBytes`: Int, + `availableBytes`: Int) { + self.`service` = `service` + self.`included` = `included` + self.`purchasedBytes` = `purchasedBytes` + self.`consumedBytes` = `consumedBytes` + self.`reservedBytes` = `reservedBytes` + self.`availableBytes` = `availableBytes` + } + + enum CodingKeys: String, CodingKey { + case `service` = "service" + case `included` = "included" + case `purchasedBytes` = "purchasedBytes" + case `consumedBytes` = "consumedBytes" + case `reservedBytes` = "reservedBytes" + case `availableBytes` = "availableBytes" + } +} + +public struct NamespaceCapacity: Codable, Sendable { + public var `id`: String + public var `namespace`: String + public var `billingMode`: ComputeBillingMode + /// Accepted values: 'active' | 'expired' | 'revoked' | 'payment_required' | 'storage_payment_required' | 'pending'. + public var `status`: String + /// Accepted values: 'wallet' | 'stripe'. + public var `provider`: String + public var `capacity`: WorkspaceCapacity + public var `tariffId`: String + public var `currency`: String + @APINumber public var `monthlyAmount`: Double + @APINumber public var `paygCapAmount`: Double + public var `periodStart`: String + public var `periodEnd`: String + @APIBoolean public var `autoRenew`: Bool + @APIBoolean public var `computeCovered`: Bool + public var `retention`: NamespaceCapacityRetention + public var `pendingChange`: NamespaceCapacityPendingChange? + public var `resourceLimits`: NamespaceResourceLimits + public var `savings`: CapacitySavings? + public var `network`: NamespaceCapacityNetwork + + public init(`id`: String, + `namespace`: String, + `billingMode`: ComputeBillingMode, + `status`: String, + `provider`: String, + `capacity`: WorkspaceCapacity, + `tariffId`: String, + `currency`: String = "usd", + `monthlyAmount`: Double, + `paygCapAmount`: Double, + `periodStart`: String, + `periodEnd`: String, + `autoRenew`: Bool, + `computeCovered`: Bool, + `retention`: NamespaceCapacityRetention, + `pendingChange`: NamespaceCapacityPendingChange? = nil, + `resourceLimits`: NamespaceResourceLimits, + `savings`: CapacitySavings? = nil, + `network`: NamespaceCapacityNetwork) { + self.`id` = `id` + self.`namespace` = `namespace` + self.`billingMode` = `billingMode` + self.`status` = `status` + self.`provider` = `provider` + self.`capacity` = `capacity` + self.`tariffId` = `tariffId` + self.`currency` = `currency` + self.`monthlyAmount` = `monthlyAmount` + self.`paygCapAmount` = `paygCapAmount` + self.`periodStart` = `periodStart` + self.`periodEnd` = `periodEnd` + self.`autoRenew` = `autoRenew` + self.`computeCovered` = `computeCovered` + self.`retention` = `retention` + self.`pendingChange` = `pendingChange` + self.`resourceLimits` = `resourceLimits` + self.`savings` = `savings` + self.`network` = `network` + } + + enum CodingKeys: String, CodingKey { + case `id` = "id" + case `namespace` = "namespace" + case `billingMode` = "billingMode" + case `status` = "status" + case `provider` = "provider" + case `capacity` = "capacity" + case `tariffId` = "tariffId" + case `currency` = "currency" + case `monthlyAmount` = "monthlyAmount" + case `paygCapAmount` = "paygCapAmount" + case `periodStart` = "periodStart" + case `periodEnd` = "periodEnd" + case `autoRenew` = "autoRenew" + case `computeCovered` = "computeCovered" + case `retention` = "retention" + case `pendingChange` = "pendingChange" + case `resourceLimits` = "resourceLimits" + case `savings` = "savings" + case `network` = "network" + } +} + +public struct CapacityResponsePendingCheckout: Codable, Sendable { + public var `quote`: CapacityQuote + public var `checkoutId`: String? + public var `url`: String? + + public init(`quote`: CapacityQuote, + `checkoutId`: String? = nil, + `url`: String? = nil) { + self.`quote` = `quote` + self.`checkoutId` = `checkoutId` + self.`url` = `url` + } + + enum CodingKeys: String, CodingKey { + case `quote` = "quote" + case `checkoutId` = "checkoutId" + case `url` = "url" + } +} + +public struct CapacityResponse: Codable, Sendable { + @APIBoolean public var `success`: Bool + public var `namespace`: String + public var `capacity`: NamespaceCapacity? + public var `catalog`: CapacityCatalog? + public var `pendingCheckout`: CapacityResponsePendingCheckout? + + public init(`success`: Bool, + `namespace`: String, + `capacity`: NamespaceCapacity? = nil, + `catalog`: CapacityCatalog? = nil, + `pendingCheckout`: CapacityResponsePendingCheckout? = nil) { + self.`success` = `success` + self.`namespace` = `namespace` + self.`capacity` = `capacity` + self.`catalog` = `catalog` + self.`pendingCheckout` = `pendingCheckout` + } + + enum CodingKeys: String, CodingKey { + case `success` = "success" + case `namespace` = "namespace" + case `capacity` = "capacity" + case `catalog` = "catalog" + case `pendingCheckout` = "pendingCheckout" + } +} + +public struct CapacityQuoteResponse: Codable, Sendable { + @APIBoolean public var `success`: Bool + public var `namespace`: String + public var `quote`: CapacityQuote + + public init(`success`: Bool, + `namespace`: String, + `quote`: CapacityQuote) { + self.`success` = `success` + self.`namespace` = `namespace` + self.`quote` = `quote` + } + + enum CodingKeys: String, CodingKey { + case `success` = "success" + case `namespace` = "namespace" + case `quote` = "quote" + } +} + +public struct PreviewCapacityParams: Codable, Sendable { + public var `capacity`: WorkspaceCapacity + public var `billingMode`: ComputeBillingMode + public var `tariffId`: String? + /// Accepted values: 'wallet' | 'stripe'. + public var `paymentSource`: String? + @APIOptionalBoolean public var `autoRenew`: Bool? + public var `idempotencyKey`: String + + public init(`capacity`: WorkspaceCapacity, + `billingMode`: ComputeBillingMode, + `tariffId`: String? = nil, + `paymentSource`: String? = nil, + `autoRenew`: Bool? = nil, + `idempotencyKey`: String) { + self.`capacity` = `capacity` + self.`billingMode` = `billingMode` + self.`tariffId` = `tariffId` + self.`paymentSource` = `paymentSource` + self.`autoRenew` = `autoRenew` + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `capacity` = "capacity" + case `billingMode` = "billingMode" + case `tariffId` = "tariffId" + case `paymentSource` = "paymentSource" + case `autoRenew` = "autoRenew" + case `idempotencyKey` = "idempotencyKey" + } +} + +public struct ConfirmCapacityParams: Codable, Sendable { + public var `quoteId`: String + public var `idempotencyKey`: String + + public init(`quoteId`: String, + `idempotencyKey`: String) { + self.`quoteId` = `quoteId` + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `quoteId` = "quoteId" + case `idempotencyKey` = "idempotencyKey" + } +} + +public struct CapacityCheckoutParamsCustomer: Codable, Sendable { + public var `email`: String? + public var `name`: String? + + public init(`email`: String? = nil, + `name`: String? = nil) { + self.`email` = `email` + self.`name` = `name` + } + + enum CodingKeys: String, CodingKey { + case `email` = "email" + case `name` = "name" + } +} + +public struct CapacityCheckoutParams: Codable, Sendable { + public var `successUrl`: String? + public var `cancelUrl`: String? + public var `customer`: CapacityCheckoutParamsCustomer? + @APIOptionalBoolean public var `allowPromotionCodes`: Bool? + /// Accepted values: 'stripe' | 'oblien'. + public var `checkoutMode`: String? + public var `quoteId`: String + public var `idempotencyKey`: String + + public init(`successUrl`: String? = nil, + `cancelUrl`: String? = nil, + `customer`: CapacityCheckoutParamsCustomer? = nil, + `allowPromotionCodes`: Bool? = nil, + `checkoutMode`: String? = nil, + `quoteId`: String, + `idempotencyKey`: String) { + self.`successUrl` = `successUrl` + self.`cancelUrl` = `cancelUrl` + self.`customer` = `customer` + self.`allowPromotionCodes` = `allowPromotionCodes` + self.`checkoutMode` = `checkoutMode` + self.`quoteId` = `quoteId` + self.`idempotencyKey` = `idempotencyKey` + } + + enum CodingKeys: String, CodingKey { + case `successUrl` = "successUrl" + case `cancelUrl` = "cancelUrl" + case `customer` = "customer" + case `allowPromotionCodes` = "allowPromotionCodes" + case `checkoutMode` = "checkoutMode" + case `quoteId` = "quoteId" + case `idempotencyKey` = "idempotencyKey" + } +} + +public struct CapacityCheckoutResponse: Codable, Sendable { + @APIBoolean public var `success`: Bool + public var `namespace`: String + public var `url`: String? + public var `checkoutId`: String? + public var `quote`: CapacityQuote? + + public init(`success`: Bool, + `namespace`: String, + `url`: String? = nil, + `checkoutId`: String? = nil, + `quote`: CapacityQuote? = nil) { + self.`success` = `success` + self.`namespace` = `namespace` + self.`url` = `url` + self.`checkoutId` = `checkoutId` + self.`quote` = `quote` + } + + enum CodingKeys: String, CodingKey { + case `success` = "success" + case `namespace` = "namespace" + case `url` = "url" + case `checkoutId` = "checkoutId" + case `quote` = "quote" + } +} + +public struct BillingSavingsPeriod: Codable, Sendable { + public var `month`: String + public var `start`: String + public var `end`: String + + public init(`month`: String, + `start`: String, + `end`: String) { + self.`month` = `month` + self.`start` = `start` + self.`end` = `end` + } + + enum CodingKeys: String, CodingKey { + case `month` = "month" + case `start` = "start" + case `end` = "end" + } +} + +public struct BillingSavingsTotals: Codable, Sendable { + @APINumber public var `beforeCaps`: Double + @APINumber public var `capDiscount`: Int + @APINumber public var `monthlyCoveredUsage`: Double + @APINumber public var `usageCharged`: Double + + public init(`beforeCaps`: Double, + `capDiscount`: Int, + `monthlyCoveredUsage`: Double, + `usageCharged`: Double) { + self.`beforeCaps` = `beforeCaps` + self.`capDiscount` = `capDiscount` + self.`monthlyCoveredUsage` = `monthlyCoveredUsage` + self.`usageCharged` = `usageCharged` + } + + enum CodingKeys: String, CodingKey { + case `beforeCaps` = "beforeCaps" + case `capDiscount` = "capDiscount" + case `monthlyCoveredUsage` = "monthlyCoveredUsage" + case `usageCharged` = "usageCharged" + } +} + +public struct BillingSavingsWorkspacesItem: Codable, Sendable { + public var `namespace`: String? + public var `workspaceId`: String? + @APINumber public var `windows`: Double + @APINumber public var `unavailableComponents`: Double + @APINumber public var `beforeCaps`: Double + @APINumber public var `capDiscount`: Int + @APINumber public var `monthlyCoveredUsage`: Double + @APINumber public var `usageCharged`: Double + + public init(`namespace`: String? = nil, + `workspaceId`: String? = nil, + `windows`: Double, + `unavailableComponents`: Double, + `beforeCaps`: Double, + `capDiscount`: Int, + `monthlyCoveredUsage`: Double, + `usageCharged`: Double) { + self.`namespace` = `namespace` + self.`workspaceId` = `workspaceId` + self.`windows` = `windows` + self.`unavailableComponents` = `unavailableComponents` + self.`beforeCaps` = `beforeCaps` + self.`capDiscount` = `capDiscount` + self.`monthlyCoveredUsage` = `monthlyCoveredUsage` + self.`usageCharged` = `usageCharged` + } + + enum CodingKeys: String, CodingKey { + case `namespace` = "namespace" + case `workspaceId` = "workspaceId" + case `windows` = "windows" + case `unavailableComponents` = "unavailableComponents" + case `beforeCaps` = "beforeCaps" + case `capDiscount` = "capDiscount" + case `monthlyCoveredUsage` = "monthlyCoveredUsage" + case `usageCharged` = "usageCharged" + } +} + +public struct BillingSavings: Codable, Sendable { + public var `currency`: String + public var `period`: BillingSavingsPeriod + public var `comparison`: String + @APIBoolean public var `complete`: Bool + @APIBoolean public var `monthlySubscriptionFeesIncluded`: Bool + @APIBoolean public var `refundsIncluded`: Bool + public var `totals`: BillingSavingsTotals + public var `workspaces`: [BillingSavingsWorkspacesItem] + + public init(`currency`: String = "usd", + `period`: BillingSavingsPeriod, + `comparison`: String = "saved_usage_rates_before_caps", + `complete`: Bool, + `monthlySubscriptionFeesIncluded`: Bool, + `refundsIncluded`: Bool, + `totals`: BillingSavingsTotals, + `workspaces`: [BillingSavingsWorkspacesItem]) { + self.`currency` = `currency` + self.`period` = `period` + self.`comparison` = `comparison` + self.`complete` = `complete` + self.`monthlySubscriptionFeesIncluded` = `monthlySubscriptionFeesIncluded` + self.`refundsIncluded` = `refundsIncluded` + self.`totals` = `totals` + self.`workspaces` = `workspaces` + } + + enum CodingKeys: String, CodingKey { + case `currency` = "currency" + case `period` = "period" + case `comparison` = "comparison" + case `complete` = "complete" + case `monthlySubscriptionFeesIncluded` = "monthlySubscriptionFeesIncluded" + case `refundsIncluded` = "refundsIncluded" + case `totals` = "totals" + case `workspaces` = "workspaces" + } +} diff --git a/Sources/OblienKit/PlatformModels/CdnModels.swift b/Sources/OblienKit/PlatformModels/CdnModels.swift index 892c245..156e619 100644 --- a/Sources/OblienKit/PlatformModels/CdnModels.swift +++ b/Sources/OblienKit/PlatformModels/CdnModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation /// Open string enum; preserves new server values. diff --git a/Sources/OblienKit/PlatformModels/EdgeProxyModels.swift b/Sources/OblienKit/PlatformModels/EdgeProxyModels.swift index 352fd26..db63375 100644 --- a/Sources/OblienKit/PlatformModels/EdgeProxyModels.swift +++ b/Sources/OblienKit/PlatformModels/EdgeProxyModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct EdgeProxyData: Codable, Sendable { diff --git a/Sources/OblienKit/PlatformModels/EdgeTunnelModels.swift b/Sources/OblienKit/PlatformModels/EdgeTunnelModels.swift index aa871af..6675127 100644 --- a/Sources/OblienKit/PlatformModels/EdgeTunnelModels.swift +++ b/Sources/OblienKit/PlatformModels/EdgeTunnelModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct EdgeTunnelSSLState: Codable, Sendable { diff --git a/Sources/OblienKit/PlatformModels/NamespaceModels.swift b/Sources/OblienKit/PlatformModels/NamespaceModels.swift index 0ee7f86..1fc9e63 100644 --- a/Sources/OblienKit/PlatformModels/NamespaceModels.swift +++ b/Sources/OblienKit/PlatformModels/NamespaceModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation /// Open string enum; preserves new server values. @@ -30,15 +30,24 @@ public struct NamespaceResourceLimits: Codable, Sendable { public var `maxVcpus`: JSONField? public var `maxRamMb`: JSONField? public var `maxDiskGb`: JSONField? + public var `maxTotalVcpus`: JSONField? + public var `maxTotalRamMb`: JSONField? + public var `maxTotalDiskGb`: JSONField? public init(`maxWorkspaces`: JSONField? = nil, `maxVcpus`: JSONField? = nil, `maxRamMb`: JSONField? = nil, - `maxDiskGb`: JSONField? = nil) { + `maxDiskGb`: JSONField? = nil, + `maxTotalVcpus`: JSONField? = nil, + `maxTotalRamMb`: JSONField? = nil, + `maxTotalDiskGb`: JSONField? = nil) { self.`maxWorkspaces` = `maxWorkspaces` self.`maxVcpus` = `maxVcpus` self.`maxRamMb` = `maxRamMb` self.`maxDiskGb` = `maxDiskGb` + self.`maxTotalVcpus` = `maxTotalVcpus` + self.`maxTotalRamMb` = `maxTotalRamMb` + self.`maxTotalDiskGb` = `maxTotalDiskGb` } enum CodingKeys: String, CodingKey { @@ -46,6 +55,37 @@ public struct NamespaceResourceLimits: Codable, Sendable { case `maxVcpus` = "max_vcpus" case `maxRamMb` = "max_ram_mb" case `maxDiskGb` = "max_disk_gb" + case `maxTotalVcpus` = "max_total_vcpus" + case `maxTotalRamMb` = "max_total_ram_mb" + case `maxTotalDiskGb` = "max_total_disk_gb" + } +} + +public struct NamespaceDataAllocatedResourceUsage: Codable, Sendable { + @APINumber public var `workspaces`: Double + @APINumber public var `vcpus`: Double + @APINumber public var `ramMb`: Int + @APINumber public var `diskGb`: Int + @APINumber public var `pendingUpdates`: Double + + public init(`workspaces`: Double, + `vcpus`: Double, + `ramMb`: Int, + `diskGb`: Int, + `pendingUpdates`: Double) { + self.`workspaces` = `workspaces` + self.`vcpus` = `vcpus` + self.`ramMb` = `ramMb` + self.`diskGb` = `diskGb` + self.`pendingUpdates` = `pendingUpdates` + } + + enum CodingKeys: String, CodingKey { + case `workspaces` = "workspaces" + case `vcpus` = "vcpus" + case `ramMb` = "ram_mb" + case `diskGb` = "disk_gb" + case `pendingUpdates` = "pending_updates" } } @@ -61,6 +101,8 @@ public struct NamespaceData: Codable, Sendable { public var `metadata`: [String: JSONValue]? public var `tags`: [String]? public var `resourceLimits`: NamespaceResourceLimits? + public var `effectiveResourceLimits`: NamespaceResourceLimits? + public var `allocatedResourceUsage`: NamespaceDataAllocatedResourceUsage? public var `createdAt`: String public var `updatedAt`: String public var `lastActiveAt`: String? @@ -76,6 +118,8 @@ public struct NamespaceData: Codable, Sendable { `metadata`: [String: JSONValue]? = nil, `tags`: [String]? = nil, `resourceLimits`: NamespaceResourceLimits? = nil, + `effectiveResourceLimits`: NamespaceResourceLimits? = nil, + `allocatedResourceUsage`: NamespaceDataAllocatedResourceUsage? = nil, `createdAt`: String, `updatedAt`: String, `lastActiveAt`: String? = nil) { @@ -90,6 +134,8 @@ public struct NamespaceData: Codable, Sendable { self.`metadata` = `metadata` self.`tags` = `tags` self.`resourceLimits` = `resourceLimits` + self.`effectiveResourceLimits` = `effectiveResourceLimits` + self.`allocatedResourceUsage` = `allocatedResourceUsage` self.`createdAt` = `createdAt` self.`updatedAt` = `updatedAt` self.`lastActiveAt` = `lastActiveAt` @@ -107,6 +153,8 @@ public struct NamespaceData: Codable, Sendable { case `metadata` = "metadata" case `tags` = "tags" case `resourceLimits` = "resource_limits" + case `effectiveResourceLimits` = "effective_resource_limits" + case `allocatedResourceUsage` = "allocated_resource_usage" case `createdAt` = "created_at" case `updatedAt` = "updated_at" case `lastActiveAt` = "last_active_at" @@ -575,6 +623,55 @@ public struct OverdraftAction: RawRepresentable, Codable, Sendable, Hashable { public static let `stopWorkspaces` = Self(rawValue: "stop_workspaces") } +public struct NamespaceQuotaAlert: Codable, Sendable { + /// Accepted values: 'ok' | 'low' | 'grace' | 'depleted' | 'unlimited' | 'disabled'. + public var `state`: String + public var `thresholds`: [Double] + @APIOptionalNumber public var `threshold`: Double? + @APIOptionalNumber public var `percent`: Int? + @APINumber public var `used`: Double + @APIOptionalNumber public var `limit`: Int? + @APIOptionalNumber public var `remaining`: Double? + @APIOptionalNumber public var `balance`: Double? + @APINumber public var `overdraft`: Double + @APIBoolean public var `blocking`: Bool + + public init(`state`: String, + `thresholds`: [Double], + `threshold`: Double? = nil, + `percent`: Int? = nil, + `used`: Double, + `limit`: Int? = nil, + `remaining`: Double? = nil, + `balance`: Double? = nil, + `overdraft`: Double, + `blocking`: Bool) { + self.`state` = `state` + self.`thresholds` = `thresholds` + self.`threshold` = `threshold` + self.`percent` = `percent` + self.`used` = `used` + self.`limit` = `limit` + self.`remaining` = `remaining` + self.`balance` = `balance` + self.`overdraft` = `overdraft` + self.`blocking` = `blocking` + } + + enum CodingKeys: String, CodingKey { + case `state` = "state" + case `thresholds` = "thresholds" + case `threshold` = "threshold" + case `percent` = "percent" + case `used` = "used" + case `limit` = "limit" + case `remaining` = "remaining" + case `balance` = "balance" + case `overdraft` = "overdraft" + case `blocking` = "blocking" + } +} + public struct NamespaceQuota: Codable, Sendable { @APINumber public var `id`: Int public var `clientId`: String @@ -582,6 +679,9 @@ public struct NamespaceQuota: Codable, Sendable { public var `service`: String @APIOptionalNumber public var `quotaLimit`: Double? @APINumber public var `quotaUsed`: Double + @APIOptionalNumber public var `purchasedCredits`: Double? + @APIOptionalNumber public var `suspendThreshold`: Double? + public var `alert`: NamespaceQuotaAlert? @APINumber public var `overdraft`: Double public var `onOverdraftAction`: OverdraftAction public var `notificationThresholds`: [Double]? @@ -596,6 +696,9 @@ public struct NamespaceQuota: Codable, Sendable { `service`: String, `quotaLimit`: Double? = nil, `quotaUsed`: Double, + `purchasedCredits`: Double? = nil, + `suspendThreshold`: Double? = nil, + `alert`: NamespaceQuotaAlert? = nil, `overdraft`: Double, `onOverdraftAction`: OverdraftAction, `notificationThresholds`: [Double]? = nil, @@ -609,6 +712,9 @@ public struct NamespaceQuota: Codable, Sendable { self.`service` = `service` self.`quotaLimit` = `quotaLimit` self.`quotaUsed` = `quotaUsed` + self.`purchasedCredits` = `purchasedCredits` + self.`suspendThreshold` = `suspendThreshold` + self.`alert` = `alert` self.`overdraft` = `overdraft` self.`onOverdraftAction` = `onOverdraftAction` self.`notificationThresholds` = `notificationThresholds` @@ -625,6 +731,9 @@ public struct NamespaceQuota: Codable, Sendable { case `service` = "service" case `quotaLimit` = "quota_limit" case `quotaUsed` = "quota_used" + case `purchasedCredits` = "purchased_credits" + case `suspendThreshold` = "suspend_threshold" + case `alert` = "alert" case `overdraft` = "overdraft" case `onOverdraftAction` = "on_overdraft_action" case `notificationThresholds` = "notification_thresholds" @@ -635,6 +744,26 @@ public struct NamespaceQuota: Codable, Sendable { } } +public struct NamespaceUsageData: Codable, Sendable { + public var `usage`: [[String: JSONValue]] + public var `summary`: [[String: JSONValue]] + public var `quotas`: [NamespaceQuota] + + public init(`usage`: [[String: JSONValue]], + `summary`: [[String: JSONValue]], + `quotas`: [NamespaceQuota]) { + self.`usage` = `usage` + self.`summary` = `summary` + self.`quotas` = `quotas` + } + + enum CodingKeys: String, CodingKey { + case `usage` = "usage" + case `summary` = "summary" + case `quotas` = "quotas" + } +} + public struct SetNamespaceQuotaParams: Codable, Sendable { public var `namespace`: String public var `service`: String diff --git a/Sources/OblienKit/PlatformModels/NotificationsModels.swift b/Sources/OblienKit/PlatformModels/NotificationsModels.swift index caa9fed..cd6b824 100644 --- a/Sources/OblienKit/PlatformModels/NotificationsModels.swift +++ b/Sources/OblienKit/PlatformModels/NotificationsModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation /// Open string enum; preserves new server values. diff --git a/Sources/OblienKit/PlatformModels/PagesModels.swift b/Sources/OblienKit/PlatformModels/PagesModels.swift index de1f30a..32800db 100644 --- a/Sources/OblienKit/PlatformModels/PagesModels.swift +++ b/Sources/OblienKit/PlatformModels/PagesModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct PageData: Codable, Sendable { diff --git a/Sources/OblienKit/PlatformModels/RuntimeModels.swift b/Sources/OblienKit/PlatformModels/RuntimeModels.swift index 53569cf..9a1a378 100644 --- a/Sources/OblienKit/PlatformModels/RuntimeModels.swift +++ b/Sources/OblienKit/PlatformModels/RuntimeModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation public struct RuntimeInfoBootSubsystem: Codable, Sendable { @@ -409,17 +409,23 @@ public struct TerminalScrollbackResponse: Codable, Sendable { @APIBoolean public var `success`: Bool public var `scrollback`: String @APINumber public var `size`: Int + @APIOptionalNumber public var `scrollbackSize`: Int? + @APIOptionalNumber public var `maxScrollbackSize`: Int? @APIBoolean public var `alive`: Bool @APINumber public var `exitCode`: Double public init(`success`: Bool, `scrollback`: String, `size`: Int, + `scrollbackSize`: Int? = nil, + `maxScrollbackSize`: Int? = nil, `alive`: Bool, `exitCode`: Double) { self.`success` = `success` self.`scrollback` = `scrollback` self.`size` = `size` + self.`scrollbackSize` = `scrollbackSize` + self.`maxScrollbackSize` = `maxScrollbackSize` self.`alive` = `alive` self.`exitCode` = `exitCode` } @@ -428,6 +434,8 @@ public struct TerminalScrollbackResponse: Codable, Sendable { case `success` = "success" case `scrollback` = "scrollback" case `size` = "size" + case `scrollbackSize` = "scrollback_size" + case `maxScrollbackSize` = "max_scrollback_size" case `alive` = "alive" case `exitCode` = "exit_code" } diff --git a/Sources/OblienKit/PlatformModels/WebhooksModels.swift b/Sources/OblienKit/PlatformModels/WebhooksModels.swift index c18defa..58647d3 100644 --- a/Sources/OblienKit/PlatformModels/WebhooksModels.swift +++ b/Sources/OblienKit/PlatformModels/WebhooksModels.swift @@ -1,4 +1,4 @@ -// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs. +// Models audited against oblien 2.8.0. Regenerate with scripts/generate-platform-models.cjs. import Foundation /// Open string enum; preserves new server values. @@ -20,11 +20,27 @@ public struct WebhookEvent: RawRepresentable, Codable, Sendable, Hashable { public static let `namespaceQuotaThreshold` = Self(rawValue: "namespace.quota.threshold") public static let `paymentSucceeded` = Self(rawValue: "payment.succeeded") public static let `subscriptionTierChanged` = Self(rawValue: "subscription.tier_changed") + public static let `subscriptionChangeScheduled` = Self(rawValue: "subscription.change.scheduled") + public static let `subscriptionChangeApplied` = Self(rawValue: "subscription.change.applied") + public static let `subscriptionChangeCanceled` = Self(rawValue: "subscription.change.canceled") + public static let `subscriptionChangePaymentRequired` = Self(rawValue: "subscription.change.payment_required") + public static let `subscriptionChangeFailed` = Self(rawValue: "subscription.change.failed") + public static let `subscriptionChangeExpired` = Self(rawValue: "subscription.change.expired") public static let `subscriptionRenewed` = Self(rawValue: "subscription.renewed") public static let `subscriptionPastDue` = Self(rawValue: "subscription.past_due") public static let `subscriptionCanceled` = Self(rawValue: "subscription.canceled") public static let `subscriptionUpdated` = Self(rawValue: "subscription.updated") public static let `entitlementChanged` = Self(rawValue: "entitlement.changed") + public static let `capacityChanged` = Self(rawValue: "capacity.changed") + public static let `capacityRenewed` = Self(rawValue: "capacity.renewed") + public static let `capacityExpired` = Self(rawValue: "capacity.expired") + public static let `capacityPaymentRequired` = Self(rawValue: "capacity.payment_required") + public static let `capacityRevoked` = Self(rawValue: "capacity.revoked") + public static let `networkTopupApplied` = Self(rawValue: "network.topup_applied") + public static let `networkAllowanceLow` = Self(rawValue: "network.allowance.low") + public static let `networkAllowanceDepleted` = Self(rawValue: "network.allowance.depleted") + public static let `storageRetentionPaymentRequired` = Self(rawValue: "storage.retention.payment_required") + public static let `storageRetentionPaid` = Self(rawValue: "storage.retention.paid") public static let `namespaceSuspended` = Self(rawValue: "namespace.suspended") public static let `namespaceRestored` = Self(rawValue: "namespace.restored") } diff --git a/Sources/OblienKit/RuntimeAPIs.swift b/Sources/OblienKit/RuntimeAPIs.swift index 04d066f..1f45cdb 100644 --- a/Sources/OblienKit/RuntimeAPIs.swift +++ b/Sources/OblienKit/RuntimeAPIs.swift @@ -144,6 +144,27 @@ public struct ExecAPI: Sendable { public struct TerminalAPI: Sendable { let runtime: RuntimeClient + /// Clears retained output without closing the shell or stopping its processes. + public func clearScrollback(_ id: String) async throws -> TerminalHistoryResult { + let data = try await runtime.perform("DELETE", "/terminals/\(id.pathEscaped)/scrollback") + let value = try OblienJSON.decode(TerminalHistoryResult.self, data) + guard value.success, value.terminalId == id, let size = value.scrollbackSize, + (1...262144).contains(size) else { throw Self.historyUnavailable() } + return value + } + public func configureScrollback(_ id: String, bytes: Int) async throws -> TerminalHistoryResult { + guard (0...262144).contains(bytes) else { throw OblienError(kind: .validation, status: nil, code: nil, message: "Use 0–262144 scrollback bytes.", details: nil) } + let data = try await runtime.perform("PATCH", "/terminals/\(id.pathEscaped)/scrollback", body: OblienJSON.encode(["scrollback_size": bytes])) + let value = try OblienJSON.decode(TerminalHistoryResult.self, data) + guard value.success, value.terminalId == id, value.scrollbackSize == (bytes == 0 ? 65536 : bytes) else { throw Self.historyUnavailable() } + return value + } + public func clearScrollback(_ id: Int) async throws -> TerminalHistoryResult { try await clearScrollback(String(id)) } + public func configureScrollback(_ id: Int, bytes: Int) async throws -> TerminalHistoryResult { try await configureScrollback(String(id), bytes: bytes) } + private static func historyUnavailable() -> OblienError { + .init(kind: .validation, status: nil, code: "runtime_upgrade_required", message: "Update the workspace runtime to manage terminal history.", details: nil) + } + public func create(cmd: [String]? = nil, cols: Int? = nil, rows: Int? = nil, shell: String? = nil, scrollbackSize: Int? = nil) async throws -> TerminalCreateResult { struct Body: Encodable { let cmd: [String]?; let cols: Int?; let rows: Int?; let scrollbackSize: Int? } @@ -156,6 +177,12 @@ public struct TerminalAPI: Sendable { } } +public struct TerminalHistoryResult: Codable, Sendable { + public let success: Bool + public var terminalId: String? + public var scrollbackSize: Int? +} + /// Runtime code search (`rt.search.*`). public struct SearchAPI: Sendable { let runtime: RuntimeClient diff --git a/Sources/OblienKit/SSHAPI.swift b/Sources/OblienKit/SSHAPI.swift index 8766b1c..85df1c4 100644 --- a/Sources/OblienKit/SSHAPI.swift +++ b/Sources/OblienKit/SSHAPI.swift @@ -19,6 +19,7 @@ public struct SSHStatus: Codable, Sendable { public var passwordAuthEnabled: Bool? public var passwordAffectsDesktop: Bool? public var sshKeySet: Bool? + public var requiresAccountAccess: Bool? public var connectionInfo: SSHConnectionInfo? { guard let connection else { return nil } @@ -42,6 +43,7 @@ public struct SSHStatus: Codable, Sendable { passwordAuthEnabled = try fields.take("password_auth_enabled", as: Bool.self) passwordAffectsDesktop = try fields.take("password_affects_desktop", as: Bool.self) sshKeySet = try fields.take("ssh_key_set", as: Bool.self) + requiresAccountAccess = try fields.take("requires_account_access", as: Bool.self) additionalProperties = fields.values } @@ -60,6 +62,7 @@ public struct SSHStatus: Codable, Sendable { try fields.set("password_auth_enabled", passwordAuthEnabled) try fields.set("password_affects_desktop", passwordAffectsDesktop) try fields.set("ssh_key_set", sshKeySet) + try fields.set("requires_account_access", requiresAccountAccess) try fields.encode(to: encoder) } } @@ -79,6 +82,11 @@ public struct SSHAPI: Sendable { let workspaceId: String private var base: String { "/workspace/\(workspaceId.pathEscaped)/ssh" } + /// Temporary, identity-bound SSH/SFTP grant for owners and collaborators. + public func connection() async throws -> SharedSSHConnection { + try OblienJSON.decode(SharedSSHConnection.self, await transport.request("POST", "/access/ssh/\(workspaceId.pathEscaped)", body: Data("{}".utf8))) + } + public func status() async throws -> SSHStatus { try OblienJSON.decode(SSHStatus.self, try await transport.request("GET", base)) } diff --git a/Sources/OblienKit/Transport.swift b/Sources/OblienKit/Transport.swift index 8c804c1..13836d7 100644 --- a/Sources/OblienKit/Transport.swift +++ b/Sources/OblienKit/Transport.swift @@ -228,6 +228,12 @@ actor Transport { var req = URLRequest(url: url) req.httpMethod = method for (key, value) in headers { req.setValue(value, forHTTPHeaderField: key) } + if case .management = host, let accountId = config.accountId { + guard accountId.range(of: "^[1-9][0-9]{0,14}$", options: .regularExpression) != nil else { + throw OblienError(kind: .validation, status: nil, code: nil, message: "Invalid account ID.", details: nil) + } + req.setValue(accountId, forHTTPHeaderField: "X-Oblien-Account") + } if req.value(forHTTPHeaderField: "Accept") == nil { req.setValue(accept, forHTTPHeaderField: "Accept") } if let body { req.httpBody = body diff --git a/Sources/OblienKit/WorkspaceOptions.swift b/Sources/OblienKit/WorkspaceOptions.swift index 9160768..e603f90 100644 --- a/Sources/OblienKit/WorkspaceOptions.swift +++ b/Sources/OblienKit/WorkspaceOptions.swift @@ -46,12 +46,14 @@ public struct MacOSBootConfig: Codable, Sendable { public var network: String? public var storage: String? public var diskCache: String? + public var warmBoot: String? public var bootArgs: String? public var ports: [Port]? public init(agent: String? = nil, network: String? = nil, storage: String? = nil, - diskCache: String? = nil, bootArgs: String? = nil, ports: [Port]? = nil) { + diskCache: String? = nil, bootArgs: String? = nil, ports: [Port]? = nil, warmBoot: String? = nil) { self.agent = agent; self.network = network; self.storage = storage self.diskCache = diskCache; self.bootArgs = bootArgs; self.ports = ports + self.warmBoot = warmBoot } public struct Port: Codable, Sendable { public var host: Int diff --git a/Sources/OblienKit/WorkspacesAPI.swift b/Sources/OblienKit/WorkspacesAPI.swift index a25fea2..cdbe4dd 100644 --- a/Sources/OblienKit/WorkspacesAPI.swift +++ b/Sources/OblienKit/WorkspacesAPI.swift @@ -16,8 +16,11 @@ public struct WorkspacesAPI: Sendable { if let cpus = request.cpus { config.cpus = cpus } if let memory = request.memoryMb { config.memoryMb = memory } if let disk = request.diskSizeMb { config.diskSizeMb = disk } + if let rootDiskId = request.rootDiskId { config.rootDiskId = rootDiskId } + if let disks = request.disks { config.disks = disks } request.config = config request.cpus = nil; request.memoryMb = nil; request.diskSizeMb = nil + request.rootDiskId = nil; request.disks = nil request.waitReady = false; request.readyTimeoutSeconds = nil let body = try OblienJSON.encode(request) let data = try await transport.request("POST", "/workspace", body: body, diff --git a/Tests/OblienKitTests/DesktopSessionsTests.swift b/Tests/OblienKitTests/DesktopSessionsTests.swift new file mode 100644 index 0000000..917e8c6 --- /dev/null +++ b/Tests/OblienKitTests/DesktopSessionsTests.swift @@ -0,0 +1,259 @@ +import XCTest +@testable import OblienKit +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +final class DesktopSessionsTests: XCTestCase { + private let id = "ds_0123456789abcdef" + private let sessionJSON = #"{"id":"ds_0123456789abcdef","name":"Project","state":"running","managed":true,"available":true,"resolution":{"width":1280,"height":800}}"# + override func tearDown() { SessionURLProtocol.handler = nil; super.tearDown() } + private func client(retries: Int = 0) -> OblienClient { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [SessionURLProtocol.self] + return OblienClient(.init(auth: .scopedToken("account-test"), baseURL: URL(string: "https://api.test")!, + runtimeURL: URL(string: "https://workspace.oblien.com")!, maxRetries: retries), session: URLSession(configuration: config)) + } + + func testSavedSessionLifecycleAndSessionBoundSSHGrant() async throws { + let store = SessionRequests() + let sessionJSON = sessionJSON + SessionURLProtocol.handler = { request in + store.append(request) + if request.url!.path.hasSuffix("/ssh") { + return .init(body: #"{"session_id":"ds_0123456789abcdef","expires_at":"2026-10-04T23:00:00Z","ssh":{"host":"ssh.oblien.com","port":22,"username":"desktop","password":"test-only","host_key_fingerprint":"SHA256:test"},"vnc":{"host":"127.0.0.1","port":5900,"authentication":"none"}}"#) + } + if request.httpMethod == "GET", request.url!.path.hasSuffix("/sessions") { + return .init(body: #"{"success":true,"sessions":[],"capabilities":{"mode":"virtual","max_sessions":10,"can_create":true,"resolution":{"min":{"width":640,"height":480},"max":{"width":3840,"height":2160},"default":{"width":1280,"height":800}}}}"#) + } + return .init(body: "{\"success\":true,\"session\":" + sessionJSON + "}") + } + let desktop = client().workspace("workspace1").desktop + let catalog = try await desktop.sessions.list() + XCTAssertEqual(catalog.capabilities.resolution?.default.width, 1280) + _ = try await desktop.createSession(.init(name: "Project", resolution: .init(width: 1280, height: 800), idempotencyKey: "project-key")) + _ = try await desktop.getSession(id) + _ = try await desktop.updateSession(id, .init(resolution: .init(width: 1440, height: 900))) + _ = try await desktop.startSession(id) + _ = try await desktop.stopSession(id) + let grant = try await desktop.sshConnection(sessionId: id) + XCTAssertEqual(grant.sessionId, id) + _ = try await desktop.deleteSession(id) + XCTAssertEqual(store.values.map { $0.httpMethod! }, ["GET", "POST", "GET", "PATCH", "POST", "POST", "POST", "DELETE"]) + XCTAssertEqual(store.values[4].url!.path, "/workspace/workspace1/desktop/sessions/\(id)/start") + XCTAssertEqual(try store.body(1)["idempotency_key"] as? String, "project-key") + XCTAssertEqual(try store.body(6)["session_id"] as? String, id) + XCTAssertEqual(store.values.filter { $0.httpMethod == "POST" && $0.url!.path.hasSuffix("/sessions") }.count, 1) + } + + func testAccountSelectionIsIsolatedAndNeverSentToRuntime() async throws { + let requests = SessionRequests() + SessionURLProtocol.handler = { request in + requests.append(request) + switch request.url!.path { + case "/workspace/workspace1/runtime-api-access/token": return .init(body: #"{"token":"runtime-test"}"#) + case "/workspace/workspace1/runtime-api-access": return .init(body: #"{"enabled":true}"#) + case "/desktop/status": return .init(body: #"{"supported":true,"enabled":true,"available":true,"credentials":false}"#) + default: return .init(body: #"{"workspaces":[]}"#) + } + } + let owner = client() + let shared = try owner.withAccount("123") + _ = try await shared.workspaces.list() + _ = try await owner.workspaces.list() + let runtime = try await shared.workspace("workspace1").runtime() + _ = try await runtime.desktop.status() + XCTAssertEqual(requests.values[0].value(forHTTPHeaderField: "X-Oblien-Account"), "123") + XCTAssertNil(requests.values[1].value(forHTTPHeaderField: "X-Oblien-Account")) + let last = try XCTUnwrap(requests.values.last) + XCTAssertNil(last.value(forHTTPHeaderField: "X-Oblien-Account")) + XCTAssertEqual(last.value(forHTTPHeaderField: "Authorization"), "Bearer runtime-test") + XCTAssertThrowsError(try owner.withAccount("../123")) + } + + func testRuntimeSessionsStayAtRootAndUseHeaderAuthForNativeVideo() async throws { + let requests = SessionRequests() + let sessionJSON = sessionJSON + SessionURLProtocol.handler = { request in + requests.append(request) + return .init(body: "{\"success\":true,\"session\":" + sessionJSON + "}") + } + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [SessionURLProtocol.self] + let runtime = try RuntimeClient(token: "a+b/c=", session: URLSession(configuration: config)).forTarget("linux") + _ = try await runtime.desktop.sessions.get(id) + XCTAssertEqual(requests.values[0].url!.path, "/desktop/sessions/\(id)") + let socket = try await runtime.desktop.webSocketRequest(sessionId: id) + XCTAssertEqual(socket.url!.path, "/desktop/sessions/\(id)/ws") + XCTAssertNil(socket.url!.query) + XCTAssertEqual(socket.value(forHTTPHeaderField: "Authorization"), "Bearer a+b/c=") + XCTAssertEqual(socket.value(forHTTPHeaderField: "Sec-WebSocket-Protocol"), "binary") + let viewer = try await runtime.desktop.url(sessionId: id) + XCTAssertNil(viewer.query) + var fragment = URLComponents(); fragment.percentEncodedQuery = viewer.fragment + XCTAssertEqual(fragment.queryItems?.first { $0.name == "token" }?.value, "a+b/c=") + XCTAssertEqual(fragment.queryItems?.first { $0.name == "session" }?.value, id) + do { _ = try await runtime.desktop.getSession("../../token"); XCTFail("Invalid ID accepted") } catch {} + XCTAssertEqual(requests.values.count, 1) + } + + func testConsoleCreationOmitsResolutionAndDeletionCanBeAsynchronous() async throws { + let requests = SessionRequests() + SessionURLProtocol.handler = { request in + requests.append(request) + return .init(body: #"{"success":true,"session":{"id":"console","name":"Mac","state":"deleting","available":false,"managed":false,"can_resize":false}}"#) + } + let desktop = client().workspace("workspace1").desktop + _ = try await desktop.createSession(.init(name: "Mac", idempotencyKey: "console-key")) + let result = try await desktop.deleteSession("console") + XCTAssertEqual(result.session?.state, "deleting") + XCTAssertEqual(result.session?.canResize, false) + XCTAssertNil(try requests.body(0)["resolution"]) + } + + func testTerminalHistoryRequiresRealAcknowledgment() async throws { + let requests = SessionRequests() + SessionURLProtocol.handler = { request in + requests.append(request) + if request.httpMethod == "DELETE" { return .init(body: #"{"success":true,"terminal_id":"7","scrollback_size":65536}"#) } + return .init(body: #"{"success":true,"terminal_id":"wrong","scrollback_size":65536}"#) + } + let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [SessionURLProtocol.self] + let runtime = RuntimeClient(token: "runtime", session: URLSession(configuration: config)) + _ = try await runtime.terminal.clearScrollback(7) + do { _ = try await runtime.terminal.configureScrollback(7, bytes: 0); XCTFail("Wrong terminal accepted") } + catch let error as OblienError { XCTAssertEqual(error.code, "runtime_upgrade_required") } + XCTAssertEqual(try requests.body(1)["scrollback_size"] as? Int, 0) + } + + func testNewDiskAndWorkspaceFieldsRoundTrip() throws { + let operation = try OblienJSON.decode(DiskOperation.self, Data(#"{"id":"op","state":"failed","kind":"resize","disk_id":"disk","error":{"code":"capacity","message":"No space"},"result":{"was_running":true,"relaunched":false,"warning":"kept files"}}"#.utf8)) + XCTAssertEqual(operation.error, "No space") + XCTAssertEqual(operation.errorCode, "capacity") + XCTAssertEqual(operation.result?.warning, "kept files") + XCTAssertEqual(try OblienJSON.decode(DiskOperation.self, OblienJSON.encode(operation)).errorCode, "capacity") + let workspace = try OblienJSON.decode(Workspace.self, Data(#"{"id":"w","owner":{"id":"1","name":"Owner"},"sharing":{"owner_id":"1","actor_id":"2","role":"developer","permissions":["desktop"]},"base_os":{"family":"linux","distribution":"ubuntu","version":"24.04"},"preset":{"id":"desktop","revision":"2","label":"Desktop","base_image":"ubuntu","software":[{"id":"gui","label":"GUI","read_only":true,"size_mb":100}]},"config":{"macos":{"warm_boot":"off"}}}"#.utf8)) + XCTAssertEqual(workspace.sharing?.role, "developer") + XCTAssertEqual(workspace.preset?.software.first?.readOnly, true) + XCTAssertEqual(workspace.baseOs?.distribution, "ubuntu") + XCTAssertEqual(try OblienJSON.decode(Workspace.self, OblienJSON.encode(workspace)).config?.macos?.warmBoot, "off") + } + + func testAccessMemberPatchSupportsExplicitExpiryRemoval() async throws { + let requests = SessionRequests() + SessionURLProtocol.handler = { request in requests.append(request); return .init(body: #"{"success":true}"#) } + _ = try await client().access.updateMember("member/1", role: "developer", version: "3", expiresAt: .null) + XCTAssertTrue(requests.values[0].url!.absoluteString.contains("member%2F1")) + let body = try requests.body(0) + XCTAssertTrue(body["expires_at"] is NSNull) + XCTAssertEqual(body["version"] as? String, "3") + } + + func testSavedDesktopRetriesKeepTheSameKeyAndBody() async throws { + let requests = SessionRequests() + let sessionJSON = sessionJSON + SessionURLProtocol.handler = { request in + requests.append(request) + if requests.values.count == 1 { return .init(status: 503, body: #"{"message":"Try again"}"#) } + return .init(body: "{\"success\":true,\"session\":" + sessionJSON + "}") + } + let desktop = client(retries: 1).workspace("workspace1").desktop + _ = try await desktop.createSession(.init(name: "Project", resolution: .init(width: 1280, height: 800), idempotencyKey: "same-create")) + XCTAssertEqual(requests.values.count, 2) + XCTAssertEqual(try requests.body(0) as NSDictionary, try requests.body(1) as NSDictionary) + + SessionURLProtocol.handler = { request in + requests.append(request) + return .init(status: 503, body: #"{"message":"Try again"}"#) + } + do { _ = try await desktop.createSession(.init(name: "Without a key")); XCTFail("Expected failure") } catch {} + XCTAssertEqual(requests.values.count, 3, "Unkeyed creation must not replay") + } + + func testCapacityBillingPreservesWireKeysAndFractionalCPU() async throws { + let requests = SessionRequests() + let quote = #"{"id":"q1","namespace":"team","status":"pending","action":"start","expiresAt":"2026-10-05T00:00:00Z","effectiveAt":"2026-10-04T00:00:00Z","periodEnd":null,"billingMode":"monthly","paymentSource":"wallet","currency":"usd","current":null,"capacity":{"vcpus":0.125,"memoryMb":512,"diskGb":10,"workspaces":1},"tariffId":"t1","monthlyAmount":125,"paygCapAmount":150,"unusedTimeCredit":0,"remainingTimeCharge":125,"amountDueNow":125,"walletCreditsRequired":12500,"retainedStorageAmountDue":0,"nextPaymentAmount":125,"autoRenew":false,"networkIncluded":false,"networkBytes":null,"preservesUsage":true,"preservesPurchasedCredits":true}"# + SessionURLProtocol.handler = { request in + requests.append(request) + if request.url!.path.hasSuffix("/preview") { + return .init(body: "{\"success\":true,\"namespace\":\"team\",\"quote\":" + quote + "}") + } + if request.url!.path.hasSuffix("/checkout") { + return .init(body: #"{"success":true,"namespace":"team","checkoutId":"checkout1","url":"https://pay.test"}"#) + } + return .init(body: #"{"success":true,"namespace":"team","capacity":null,"pendingCheckout":null}"#) + } + let billing = client().billing + let preview = try await billing.previewCapacity("team", .init(capacity: .init(vcpus: 0.125, memoryMb: 512, diskGb: 10, workspaces: 1), billingMode: .monthly, autoRenew: false, idempotencyKey: "preview-1")) + XCTAssertEqual(preview.quote.capacity?.vcpus, 0.125) + _ = try await billing.capacity("team") + _ = try await billing.confirmCapacity("team", .init(quoteId: "q1", idempotencyKey: "confirm-1")) + _ = try await billing.capacityCheckout("team", .init(successUrl: "https://return.test", allowPromotionCodes: false, quoteId: "q1", idempotencyKey: "checkout-1")) + _ = try await billing.cancelCapacityChange("team", .init(quoteId: "q1", idempotencyKey: "cancel-1")) + _ = try await billing.setCapacityAutoRenew("team", autoRenew: false, idempotencyKey: "renew-1") + _ = try await billing.previewNetworkTopup("team", unitAmount: 2.5, idempotencyKey: "network-1") + XCTAssertEqual(requests.values.map { $0.url!.path }, ["/billing/capacity/preview", "/billing/capacity", "/billing/capacity/confirm", "/billing/capacity/checkout", "/billing/capacity/change/cancel", "/billing/capacity/renewal", "/billing/capacity/network/preview"]) + let body = try requests.body(0) + XCTAssertEqual(body["namespace"] as? String, "team") + XCTAssertEqual((body["capacity"] as? [String: Any])?["vcpus"] as? Double, 0.125) + XCTAssertEqual(body["billingMode"] as? String, "monthly") + XCTAssertEqual(body["autoRenew"] as? Bool, false) + XCTAssertNil(body["idempotency_key"]) + XCTAssertEqual(try requests.body(2)["quoteId"] as? String, "q1") + XCTAssertEqual(try requests.body(3)["allowPromotionCodes"] as? Bool, false) + XCTAssertEqual(try requests.body(5)["idempotencyKey"] as? String, "renew-1") + XCTAssertEqual(try requests.body(6)["unitAmount"] as? Double, 2.5) + } + + func testAccountHeaderIsRemovedOnCrossOriginRedirects() throws { + let session = URLSession(configuration: .ephemeral) + defer { session.invalidateAndCancel() } + let origin = URL(string: "https://api.test/workspaces")! + let response = HTTPURLResponse(url: origin, statusCode: 302, httpVersion: nil, headerFields: nil)! + let delegate = HTTPRedirectDelegate(policy: .follow) + var request = URLRequest(url: URL(string: "https://elsewhere.test/workspaces")!) + request.setValue("123", forHTTPHeaderField: "X-Oblien-Account") + request.setValue("Bearer test", forHTTPHeaderField: "Authorization") + delegate.urlSession(session, task: session.dataTask(with: origin), willPerformHTTPRedirection: response, newRequest: request) { + XCTAssertNil($0?.value(forHTTPHeaderField: "X-Oblien-Account")) + XCTAssertNil($0?.value(forHTTPHeaderField: "Authorization")) + } + request.url = URL(string: "https://api.test/new-path")! + delegate.urlSession(session, task: session.dataTask(with: origin), willPerformHTTPRedirection: response, newRequest: request) { + XCTAssertEqual($0?.value(forHTTPHeaderField: "X-Oblien-Account"), "123") + } + } +} + +private final class SessionRequests: @unchecked Sendable { + private let lock = NSLock() + private var storage: [URLRequest] = [] + var values: [URLRequest] { lock.lock(); defer { lock.unlock() }; return storage } + func append(_ request: URLRequest) { lock.lock(); storage.append(request); lock.unlock() } + func body(_ index: Int) throws -> [String: Any] { + let request = values[index] + var data = request.httpBody ?? Data() + if data.isEmpty, let stream = request.httpBodyStream { + stream.open(); defer { stream.close() } + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { let n = stream.read(&buffer, maxLength: buffer.count); if n <= 0 { break }; data.append(contentsOf: buffer.prefix(n)) } + } + return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } +} +private final class SessionURLProtocol: URLProtocol, @unchecked Sendable { + struct Reply { var status = 200; var body: String } + static var handler: ((URLRequest) throws -> Reply)? + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + do { + let reply = try XCTUnwrap(Self.handler)(request) + let response = HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: ["Content-Type":"application/json"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(reply.body.utf8)) + client?.urlProtocolDidFinishLoading(self) + } catch { client?.urlProtocol(self, didFailWithError: error) } + } + override func stopLoading() {} +} diff --git a/docs/TypeScriptCoverage.md b/docs/TypeScriptCoverage.md index dff1a5b..245e5e8 100644 --- a/docs/TypeScriptCoverage.md +++ b/docs/TypeScriptCoverage.md @@ -1,6 +1,6 @@ # TypeScript SDK coverage -Reference: npm `oblien@2.4.0`, reviewed September 25, 2026. The checked-in inventory maps **297 portable methods/accessors** to Swift sources and identifies **two Node hosting helpers**. Declaration hashes include request/response types, nested options and event definitions so an upstream change requires another review. +Reference: npm `oblien@2.8.0`, reviewed October 4, 2026. The checked-in inventory maps **362 portable methods/accessors** to Swift sources and identifies **two Node hosting helpers**. Declaration hashes include request/response types, nested options and event definitions so an upstream change requires another review. This is API coverage, not a promise that every endpoint is enabled for every plan, credential scope, image or workspace runtime. UI clients should read capabilities and permissions, preserve durable operation IDs, and show the API's recoverable failure. @@ -31,7 +31,7 @@ This is API coverage, not a promise that every endpoint is enabled for every pla | cdn | `CDNAPI`, `CDNDomainsAPI` | Single/multiple uploads, remote URLs, processing variants/options, files/trash/restore, tags/stats/usage, quotas and domains | | notifications | `NotificationsAPI` | Workspace send-token lifecycle, send requests and per-provider delivery errors | -Current Oblien documentation additionally describes persistent disks/software and desktop preparation. `DisksAPI` covers create/get/list/delete/copy/save/fork/resize/attach/detach/move, root retention, saved execution discard, software library and durable operation polling/retry. These extensions are beyond the published 2.4.0 declaration snapshot. +The reviewed release includes persistent disks/software, desktop preparation, saved desktop sessions, account sharing, plan changes and terminal history controls. `DisksAPI` covers create/get/list/delete/copy/save/fork/resize/attach/detach/move, root retention, saved execution discard, software library and durable operation polling/retry. Saved desktops have independent IDs and lifecycles. Management and runtime clients share the same session API. Closing a viewer does not stop or delete its desktop. Console creation may omit resolution, and deletion may return a `deleting` session, as documented by the newer provider API. ## Native equivalents and boundaries @@ -59,7 +59,7 @@ Exec streams decode the actual JSON/base64 wire frames. Log following subscribes `swift test` runs wire-contract, retry, credentials, stream, log reconciliation, nullable model and lifecycle tests. The declaration audit is a drift check, not a network test: ```sh -npm pack oblien@2.4.0 +npm pack oblien@2.8.0 # Extract the package, then: NODE_PATH=/path/to/node_modules node scripts/audit-typescript-sdk.cjs /path/to/package/dist ``` @@ -79,3 +79,7 @@ swift test --filter 'WorkspaceControlLiveTests|PlatformReadLiveTests' `WorkspaceControlLiveTests` creates a disposable workspace and disks, writes an ID receipt for recovery, exercises runtime and infrastructure controls, and removes its fixtures. It incurs temporary resource usage. `PlatformReadLiveTests` performs account read groups. They do not alter existing workspaces or exercise destructive account/billing actions. The verified workspace image currently rejects workload log retention/clear with HTTP 409 when its Oblien runtime agent is too old. The methods and wire contracts are implemented; upgrading that runtime is required to use them. This is reported as an unavailable backend capability, not a passing live mutation. + +`withAccount` isolates management account headers and runtime caches. `access` supports invitations, member roles/expiry, shared workspaces, delegated SSH, token issuance and audit. `namespaces.usageData` exposes typed quota alerts while the older `usage` response remains available. Terminal scrollback changes require a matching server acknowledgment; an older runtime cannot silently report success. + +The audit is pinned to published npm `oblien@2.8.0`, including capacity billing, network top-ups, savings, desktop deletion/resize capabilities and deletion progress. diff --git a/scripts/audit-typescript-sdk.cjs b/scripts/audit-typescript-sdk.cjs index 7177fe6..32c4eb2 100644 --- a/scripts/audit-typescript-sdk.cjs +++ b/scripts/audit-typescript-sdk.cjs @@ -14,14 +14,16 @@ const snapshotPath = path.join(__dirname, 'typescript-surface.json'); const text = files => files.split(' ').map(file => fs.readFileSync(path.join(source, file + '.swift'), 'utf8')).join('\n'); // [Swift sources, method renames]. Swift binds resource IDs before calling methods. const modules = { + 'access.d.ts': ['AccessAPI'], 'analytics.d.ts': ['AnalyticsAPI'], 'billing.d.ts': ['BillingAPI'], 'cdn.d.ts': ['CDNAPI'], 'client.d.ts': ['OblienClient PagesAPI'], 'domain.d.ts': ['AccountDomainsAPI'], + 'disks.d.ts': ['DisksAPI'], 'edge-proxy.d.ts': ['EdgeAPI'], 'edge-tunnel.d.ts': ['EdgeAPI'], - 'namespace.d.ts': ['NamespacesAPI'], + 'namespace.d.ts': ['NamespacesAPI', { usage: 'usageData' }], 'notifications.d.ts': ['NotificationsAPI'], 'pages.d.ts': ['PagesAPI'], 'routes.d.ts': ['PagesAPI'], @@ -31,7 +33,7 @@ const modules = { 'workspace.d.ts': ['WorkspacesAPI WorkspaceHandle Extras', { setTokenTtl: 'setTokenTTL' }], 'workspace-handle.d.ts': ['WorkspaceHandle WorkspaceOptions'], 'resources/api-access.d.ts': ['SubAPIs'], - 'resources/desktop.d.ts': ['DesktopAPI'], + 'resources/desktop.d.ts': ['DesktopAPI DesktopSessions'], 'resources/domains.d.ts': ['DomainsAPI', { connect: 'set', disconnect: 'remove', checkDNS: 'check' }], 'resources/images.d.ts': ['WorkspacesAPI', { list: 'images' }], 'resources/lifecycle.d.ts': ['LifecycleAPI', { updateTtl: 'updateTTL' }], @@ -45,7 +47,7 @@ const modules = { 'resources/ssh.d.ts': ['SSHAPI'], 'resources/usage.d.ts': ['UsageAPI', { global: 'usageGlobal' }], 'resources/workloads.d.ts': ['WorkloadsAPI RuntimeOptions'], - 'runtime/desktop.d.ts': ['DesktopAPI'], + 'runtime/desktop.d.ts': ['DesktopAPI DesktopSessions'], 'runtime/exec.d.ts': ['RuntimeAPIs Extras Streaming'], 'runtime/files.d.ts': ['RuntimeAPIs Streaming'], 'runtime/proxy.d.ts': ['RuntimeAPIs', { ws: 'webSocket' }], @@ -72,6 +74,7 @@ for (const folder of ['', 'resources', 'runtime', 'types']) { for (const declaration of file.statements) { if (!ts.isClassDeclaration(declaration)) continue; for (const member of declaration.members) { + if (ts.getJSDocTags(member).some(tag => tag.tagName.text === 'internal')) continue; if (!member.name || member.name.getText(file).startsWith('_') || member.modifiers?.some(m => [ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword].includes(m.kind))) continue; if (!ts.isMethodDeclaration(member) && !ts.isGetAccessorDeclaration(member)) continue; const method = member.name.getText(file); diff --git a/scripts/generate-platform-models.cjs b/scripts/generate-platform-models.cjs index 5205459..1c93d87 100644 --- a/scripts/generate-platform-models.cjs +++ b/scripts/generate-platform-models.cjs @@ -7,6 +7,7 @@ const fs = require('fs'); const path = require('path'); const root = process.argv[2]; if (!root) throw new Error('Pass the extracted oblien package dist directory'); +const version = JSON.parse(fs.readFileSync(path.join(root, '../package.json'), 'utf8')).version; const groups = ['namespace', 'pages', 'edge-proxy', 'edge-tunnel', 'webhooks', 'analytics', 'billing', 'cdn', 'notifications']; const extra = ['CheckSlugParams', 'CheckSlugResponse', 'VerifyDomainParams', 'VerifyDomainResponse', 'DomainListParams', 'DomainRoute', 'DomainRoutesResponse', 'SslCertificate', 'SslListResponse', 'SslAutoRenewResponse']; @@ -39,6 +40,7 @@ function numberType(key) { function isNull(node) { return node.kind === ts.SyntaxKind.NullKeyword || (ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.NullKeyword); } function renderType(node, name, key) { if (!node) throw new Error('Missing type: ' + name); + if (ts.isImportTypeNode(node) && node.qualifier && declarations.has(node.qualifier.getText())) return node.qualifier.getText(); if (ts.isParenthesizedTypeNode(node)) return renderType(node.type, name, key); if (node.kind === ts.SyntaxKind.StringKeyword) return 'String'; if (node.kind === ts.SyntaxKind.NumberKeyword) return numberType(key); @@ -148,6 +150,6 @@ for (const group of [...groups, 'workspace-resources', 'runtime']) { if (ts.isTypeAliasDeclaration(node)) renderAlias(node.name.text, node); } const filename = group === 'workspace-resources' ? 'AccountDomainModels' : group.split('-').map(upper).join('') + 'Models'; - fs.writeFileSync(path.join(outDir, filename + '.swift'), '// Models audited against oblien 2.4.0. Regenerate with scripts/generate-platform-models.cjs.\nimport Foundation\n\n' + blocks.join('\n')); + fs.writeFileSync(path.join(outDir, filename + '.swift'), '// Models audited against oblien ' + version + '. Regenerate with scripts/generate-platform-models.cjs.\nimport Foundation\n\n' + blocks.join('\n')); } console.log('Generated ' + rendered.size + ' platform models with explicit wire keys.'); diff --git a/scripts/typescript-surface.json b/scripts/typescript-surface.json index fcbf9a1..baaa383 100644 --- a/scripts/typescript-surface.json +++ b/scripts/typescript-surface.json @@ -1,6 +1,61 @@ { - "version": "2.4.0", + "version": "2.8.0", "methods": { + "access.d.ts:Access.accounts": { + "signature": "accounts(): Promise<{ success: true; accounts: AccessibleAccount[]; }>;", + "swift": "accounts", + "sources": "AccessAPI" + }, + "access.d.ts:Access.sharedWorkspaces": { + "signature": "sharedWorkspaces(params?: { before?: string; limit?: number; }): Promise;", + "swift": "sharedWorkspaces", + "sources": "AccessAPI" + }, + "access.d.ts:Access.invitations": { + "signature": "invitations(): Promise<{ success: true; invitations: AccessInvitation[]; }>;", + "swift": "invitations", + "sources": "AccessAPI" + }, + "access.d.ts:Access.invite": { + "signature": "invite(params: AccessResource & { email: string; role?: AccessRole; expires_at?: string; }): Promise<{ success: true; invitation: { id: string; email: string; role: AccessRole; expires_at: string; }; invitation_url: string; }>;", + "swift": "invite", + "sources": "AccessAPI" + }, + "access.d.ts:Access.accept": { + "signature": "accept(params: { id: string; } | { token: string; }): Promise;", + "swift": "accept", + "sources": "AccessAPI" + }, + "access.d.ts:Access.revokeInvitation": { + "signature": "revokeInvitation(id: string): Promise;", + "swift": "revokeInvitation", + "sources": "AccessAPI" + }, + "access.d.ts:Access.members": { + "signature": "members(resource: AccessResource): Promise<{ success: true; owner: AccessibleAccount; members: AccessMember[]; invitations: AccessInvitation[]; }>;", + "swift": "members", + "sources": "AccessAPI" + }, + "access.d.ts:Access.updateMember": { + "signature": "updateMember(id: string, params: { role: AccessRole; version?: string; expires_at?: string | null; }): Promise;", + "swift": "updateMember", + "sources": "AccessAPI" + }, + "access.d.ts:Access.removeMember": { + "signature": "removeMember(id: string, version?: string): Promise;", + "swift": "removeMember", + "sources": "AccessAPI" + }, + "access.d.ts:Access.issueToken": { + "signature": "issueToken(params: AccessResource & { role?: AccessRole; ttl?: number; label?: string; }): Promise<{ success: true; token: string; expiresAt: string; ttl: number; scope: string; permissions: string[]; }>;", + "swift": "issueToken", + "sources": "AccessAPI" + }, + "access.d.ts:Access.audit": { + "signature": "audit(resource: AccessResource & { before?: string; }): Promise<{ success: true; events: { id: string; action: string; actor_id: string; actor_name: string; created_at: string; }[]; next_cursor: string | null; }>;", + "swift": "audit", + "sources": "AccessAPI" + }, "analytics.d.ts:Analytics.home": { "signature": "home(params?: { namespace?: string; }): Promise;", "swift": "home", @@ -31,6 +86,51 @@ "swift": "streamToken", "sources": "AnalyticsAPI" }, + "billing.d.ts:Billing.capacityCatalog": { + "signature": "capacityCatalog(): Promise;", + "swift": "capacityCatalog", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.capacity": { + "signature": "capacity(namespace: string): Promise;", + "swift": "capacity", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.previewCapacity": { + "signature": "previewCapacity(namespace: string, params: PreviewCapacityParams): Promise;", + "swift": "previewCapacity", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.confirmCapacity": { + "signature": "confirmCapacity(namespace: string, params: ConfirmCapacityParams): Promise;", + "swift": "confirmCapacity", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.capacityCheckout": { + "signature": "capacityCheckout(namespace: string, params: CapacityCheckoutParams): Promise;", + "swift": "capacityCheckout", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.cancelCapacityChange": { + "signature": "cancelCapacityChange(namespace: string, params: ConfirmCapacityParams): Promise;", + "swift": "cancelCapacityChange", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.setCapacityAutoRenew": { + "signature": "setCapacityAutoRenew(namespace: string, params: { autoRenew: boolean; idempotencyKey: string; }): Promise;", + "swift": "setCapacityAutoRenew", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.previewNetworkTopup": { + "signature": "previewNetworkTopup(namespace: string, params: { unitAmount: number; idempotencyKey: string; }): Promise;", + "swift": "previewNetworkTopup", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.savings": { + "signature": "savings(params?: { namespace?: string; workspaceId?: string; month?: string; }): Promise;", + "swift": "savings", + "sources": "BillingAPI" + }, "billing.d.ts:Billing.catalog": { "signature": "catalog(): Promise;", "swift": "catalog", @@ -56,6 +156,26 @@ "swift": "subscription", "sources": "BillingAPI" }, + "billing.d.ts:Billing.previewPlanChange": { + "signature": "previewPlanChange(namespace: string, params: PreviewPlanChangeParams): Promise;", + "swift": "previewPlanChange", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.changePlan": { + "signature": "changePlan(namespace: string, params: ChangePlanParams): Promise;", + "swift": "changePlan", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.planChange": { + "signature": "planChange(namespace: string, changeId: string): Promise;", + "swift": "planChange", + "sources": "BillingAPI" + }, + "billing.d.ts:Billing.cancelPlanChange": { + "signature": "cancelPlanChange(namespace: string, changeId: string, params: CancelPlanChangeParams): Promise;", + "swift": "cancelPlanChange", + "sources": "BillingAPI" + }, "billing.d.ts:Billing.cancelSubscription": { "signature": "cancelSubscription(namespace: string): Promise;", "swift": "cancelSubscription", @@ -216,6 +336,11 @@ "swift": "sites", "sources": "OblienClient PagesAPI" }, + "client.d.ts:Oblien.withAccount": { + "signature": "withAccount(accountId: string): Oblien;", + "swift": "withAccount", + "sources": "OblienClient PagesAPI" + }, "client.d.ts:Oblien.setToken": { "signature": "setToken(token: string): void;", "swift": "setToken", @@ -231,6 +356,111 @@ "swift": "workspace", "sources": "OblienClient PagesAPI" }, + "disks.d.ts:Disks.list": { + "signature": "list(params?: { namespace?: string; }): Promise;", + "swift": "list", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.get": { + "signature": "get(id: string): Promise;", + "swift": "get", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.listSoftware": { + "signature": "listSoftware(params?: { workspace_id?: string; }): Promise;", + "swift": "listSoftware", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.attachSoftware": { + "signature": "attachSoftware(id: string, params: SoftwareAttachParams, options?: DiskWaitOptions): Promise;", + "swift": "attachSoftware", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.create": { + "signature": "create(params: DiskCreateParams, options?: DiskWaitOptions): Promise;", + "swift": "create", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.clone": { + "signature": "clone(id: string, params?: DiskCopyParams, options?: DiskWaitOptions): Promise;", + "swift": "clone", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.save": { + "signature": "save(id: string, params?: DiskCopyParams, options?: DiskWaitOptions): Promise;", + "swift": "save", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.fork": { + "signature": "fork(id: string, params: DiskForkParams, options?: DiskWaitOptions): Promise;", + "swift": "fork", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.resize": { + "signature": "resize(id: string, params: DiskResizeParams, options?: DiskWaitOptions): Promise;", + "swift": "resize", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.delete": { + "signature": "delete(id: string, params?: DiskMutationParams, options?: DiskWaitOptions): Promise;", + "swift": "delete", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.attach": { + "signature": "attach(id: string, params: DiskAttachParams, options?: DiskWaitOptions): Promise;", + "swift": "attach", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.detach": { + "signature": "detach(id: string, params: DiskDetachParams, options?: DiskWaitOptions): Promise;", + "swift": "detach", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.move": { + "signature": "move(id: string, params: DiskMoveParams, options?: DiskWaitOptions): Promise;", + "swift": "move", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.operation": { + "signature": "operation(id: string): Promise;", + "swift": "operation", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.retry": { + "signature": "retry(id: string, params?: Pick, options?: DiskWaitOptions): Promise;", + "swift": "retry", + "sources": "DisksAPI" + }, + "disks.d.ts:Disks.wait": { + "signature": "wait(id: string, options?: DiskWaitOptions): Promise;", + "swift": "wait", + "sources": "DisksAPI" + }, + "disks.d.ts:WorkspaceDisksResource.list": { + "signature": "list(workspaceId: string): Promise;", + "swift": "list", + "sources": "DisksAPI" + }, + "disks.d.ts:WorkspaceDisksResource.retainRoot": { + "signature": "retainRoot(workspaceId: string, params?: DiskCopyParams, options?: DiskWaitOptions): Promise;", + "swift": "retainRoot", + "sources": "DisksAPI" + }, + "disks.d.ts:WorkspaceDisksResource.attach": { + "signature": "attach(workspaceId: string, id: string, params?: Omit, options?: DiskWaitOptions): Promise;", + "swift": "attach", + "sources": "DisksAPI" + }, + "disks.d.ts:WorkspaceDisksResource.detach": { + "signature": "detach(workspaceId: string, id: string, params?: DiskMutationParams, options?: DiskWaitOptions): Promise;", + "swift": "detach", + "sources": "DisksAPI" + }, + "disks.d.ts:WorkspaceDisksResource.discardSavedExecution": { + "signature": "discardSavedExecution(workspaceId: string): Promise<{ success: boolean; }>;", + "swift": "discardSavedExecution", + "sources": "DisksAPI" + }, "domain.d.ts:Domain.checkSlug": { "signature": "checkSlug(params: CheckSlugParams): Promise;", "swift": "checkSlug", @@ -416,8 +646,8 @@ "sources": "NamespacesAPI" }, "namespace.d.ts:Namespace.usage": { - "signature": "usage(id: string, params?: NamespaceUsageParams): Promise;", - "swift": "usage", + "signature": "usage(id: string, params?: NamespaceUsageParams): Promise;", + "swift": "usageData", "sources": "NamespacesAPI" }, "namespace.d.ts:Namespace.usageUnits": { @@ -866,19 +1096,54 @@ "sources": "SubAPIs" }, "resources/desktop.d.ts:DesktopResource.install": { - "signature": "install(workspaceId: string): Promise;", + "signature": "install(workspaceId: string, options?: { desktop?: string; restart?: boolean; }): Promise;", "swift": "install", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "resources/desktop.d.ts:DesktopResource.installation": { "signature": "installation(workspaceId: string): Promise;", "swift": "installation", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "resources/desktop.d.ts:DesktopResource.sshConnection": { - "signature": "sshConnection(workspaceId: string): Promise;", + "signature": "sshConnection(workspaceId: string, options?: { session_id?: string; }): Promise;", "swift": "sshConnection", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.listSessions": { + "signature": "listSessions(workspaceId: string): Promise;", + "swift": "listSessions", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.createSession": { + "signature": "createSession(workspaceId: string, body: CreateDesktopSession): Promise;", + "swift": "createSession", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.getSession": { + "signature": "getSession(workspaceId: string, id: string): Promise;", + "swift": "getSession", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.updateSession": { + "signature": "updateSession(workspaceId: string, id: string, body: UpdateDesktopSession): Promise;", + "swift": "updateSession", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.startSession": { + "signature": "startSession(workspaceId: string, id: string): Promise;", + "swift": "startSession", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.stopSession": { + "signature": "stopSession(workspaceId: string, id: string): Promise;", + "swift": "stopSession", + "sources": "DesktopAPI DesktopSessions" + }, + "resources/desktop.d.ts:DesktopResource.deleteSession": { + "signature": "deleteSession(workspaceId: string, id: string): Promise<{ success: true; }>;", + "swift": "deleteSession", + "sources": "DesktopAPI DesktopSessions" }, "resources/domains.d.ts:DomainsResource.get": { "signature": "get(workspaceId: string): Promise;", @@ -946,7 +1211,7 @@ "sources": "LifecycleAPI" }, "resources/logs.d.ts:LogsResource.get": { - "signature": "get(workspaceId: string, params?: LogsParams): Promise;", + "signature": "get(workspaceId: string, params?: LogsParams, options?: { signal?: AbortSignal; }): Promise;", "swift": "get", "sources": "LogsAPI Streaming LogEvents" }, @@ -966,12 +1231,12 @@ "sources": "LogsAPI Streaming LogEvents" }, "resources/logs.d.ts:LogsResource.streamBoot": { - "signature": "streamBoot(workspaceId: string, params?: { tail_lines?: number; }): AsyncGenerator;", + "signature": "streamBoot(workspaceId: string, params?: { tail_lines?: number; signal?: AbortSignal; }): AsyncGenerator;", "swift": "streamBoot", "sources": "LogsAPI Streaming LogEvents" }, "resources/logs.d.ts:LogsResource.streamCmd": { - "signature": "streamCmd(workspaceId: string, params?: { tail_lines?: number; }): AsyncGenerator;", + "signature": "streamCmd(workspaceId: string, params?: { tail_lines?: number; signal?: AbortSignal; }): AsyncGenerator;", "swift": "streamCmd", "sources": "LogsAPI Streaming LogEvents" }, @@ -1105,6 +1370,11 @@ "swift": "deleteAllArchives", "sources": "SnapshotsAPI" }, + "resources/ssh.d.ts:SshResource.connection": { + "signature": "connection(workspaceId: string): Promise;", + "swift": "connection", + "sources": "SSHAPI" + }, "resources/ssh.d.ts:SshResource.status": { "signature": "status(workspaceId: string): Promise;", "swift": "status", @@ -1221,10 +1491,20 @@ "sources": "WorkloadsAPI RuntimeOptions" }, "resources/workloads.d.ts:WorkloadsResource.logs": { - "signature": "logs(workspaceId: string, workloadId: string): Promise;", + "signature": "logs(workspaceId: string, workloadId: string, params?: { tail?: number; signal?: AbortSignal; }): Promise;", "swift": "logs", "sources": "WorkloadsAPI RuntimeOptions" }, + "resources/workloads.d.ts:WorkloadsResource.clearLogs": { + "signature": "clearLogs(workspaceId: string, workloadId: string): Promise;", + "swift": "clearLogs", + "sources": "WorkloadsAPI RuntimeOptions" + }, + "resources/workloads.d.ts:WorkloadsResource.logConfig": { + "signature": "logConfig(workspaceId: string, workloadId: string): Promise;", + "swift": "logConfig", + "sources": "WorkloadsAPI RuntimeOptions" + }, "resources/workloads.d.ts:WorkloadsResource.stats": { "signature": "stats(workspaceId: string, workloadId: string): Promise;", "swift": "stats", @@ -1236,7 +1516,7 @@ "sources": "WorkloadsAPI RuntimeOptions" }, "resources/workloads.d.ts:WorkloadsResource.logsStream": { - "signature": "logsStream(workspaceId: string, workloadId: string): AsyncGenerator;", + "signature": "logsStream(workspaceId: string, workloadId: string, options?: { signal?: AbortSignal; }): AsyncGenerator;", "swift": "logsStream", "sources": "WorkloadsAPI RuntimeOptions" }, @@ -1246,32 +1526,67 @@ "sources": "WorkloadsAPI RuntimeOptions" }, "runtime/desktop.d.ts:DesktopResource.status": { - "signature": "status(): Promise;", + "signature": "status(sessionId?: string): Promise;", "swift": "status", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.listSessions": { + "signature": "listSessions(): Promise;", + "swift": "listSessions", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.createSession": { + "signature": "createSession(body: CreateDesktopSession): Promise;", + "swift": "createSession", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.getSession": { + "signature": "getSession(id: string): Promise;", + "swift": "getSession", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.updateSession": { + "signature": "updateSession(id: string, body: UpdateDesktopSession): Promise;", + "swift": "updateSession", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.startSession": { + "signature": "startSession(id: string): Promise;", + "swift": "startSession", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.stopSession": { + "signature": "stopSession(id: string): Promise;", + "swift": "stopSession", + "sources": "DesktopAPI DesktopSessions" + }, + "runtime/desktop.d.ts:DesktopResource.deleteSession": { + "signature": "deleteSession(id: string): Promise<{ success: true; }>;", + "swift": "deleteSession", + "sources": "DesktopAPI DesktopSessions" }, "runtime/desktop.d.ts:DesktopResource.enable": { "signature": "enable(): Promise;", "swift": "enable", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "runtime/desktop.d.ts:DesktopResource.disable": { "signature": "disable(): Promise;", "swift": "disable", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "runtime/desktop.d.ts:DesktopResource.credentials": { "signature": "credentials(): Promise<{ username: string; password: string; }>;", "swift": "credentials", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "runtime/desktop.d.ts:DesktopResource.url": { - "signature": "url(): string;", + "signature": "url(options?: { sessionId?: string; }): string;", "swift": "url", - "sources": "DesktopAPI" + "sources": "DesktopAPI DesktopSessions" }, "runtime/desktop.d.ts:DesktopResource.tunnel": { - "signature": "tunnel(options?: { port?: number; onError?: (error: Error) => void; }): Promise;", + "signature": "tunnel(options?: { sessionId?: string; port?: number; onError?: (error: Error) => void; }): Promise;", "boundary": "Node localhost WebSocket proxy server; native clients use DesktopAPI.sshConnection and SSH/VNC." }, "runtime/exec.d.ts:ExecResource.run": { @@ -1399,6 +1714,16 @@ "swift": "scrollback", "sources": "RuntimeAPIs Extras RuntimeOptions" }, + "runtime/terminal.d.ts:TerminalResource.clearScrollback": { + "signature": "clearScrollback(sessionId: string): Promise<{ success: boolean; terminal_id: string; }>;", + "swift": "clearScrollback", + "sources": "RuntimeAPIs Extras RuntimeOptions" + }, + "runtime/terminal.d.ts:TerminalResource.configureScrollback": { + "signature": "configureScrollback(sessionId: string, bytes: number): Promise<{ success: boolean; scrollback_size: number; }>;", + "swift": "configureScrollback", + "sources": "RuntimeAPIs Extras RuntimeOptions" + }, "runtime/transfer.d.ts:TransferResource.download": { "signature": "download(params: TransferDownloadParams): Promise;", "swift": "download", @@ -1496,63 +1821,68 @@ } }, "declarations": { + "access.d.ts": "d43ea6e7b67fc9a0ec436aa19774e107a74cc2667ecb60112392ddf0da8bbb78", "analytics.d.ts": "b75fb423f4c36672a418a6f62958c97d9769ddf3401989312ced34304bc72beb", - "billing.d.ts": "95c62cf08867156c1e0252c23117fa3d2714547e2280884b5bddb5b0d35f3aa9", + "billing.d.ts": "0d2c13fb72f0a689381d70544f70b1c247ab746620bb26da4ca1031094b7fbb2", "cdn.d.ts": "3a3907763ecf7d4041cd140b6de5ab2e5fc4062f15f05c9cdad6ff1d2e95bb62", - "client.d.ts": "8e414442d2f4fc9f1bba2029f98f28e931efd6a1c49556b29d8e1edc928b60be", + "client.d.ts": "86b4bc94c059b662e528ccfd0b1eb664e481b17fdfe247c523890f0efecc5f12", + "disks.d.ts": "192f351d147353069d5e63993fed9f6ed0563d115716c835635c7b559fc1ddec", "domain.d.ts": "6a113546a82000a2d224018e61c86a6af6da04d2c60ed7ad40fc8bfd2a4aac8d", "edge-proxy.d.ts": "a3011cdd73a39398d1bab60c0083fb5f849167637f0407c2934fad1717928fd7", "edge-tunnel.d.ts": "d3bc14e2a9d3470f1951b1906b0b43bb47ef7b5f5e15230ee17ef659e6d4a903", - "namespace.d.ts": "0b1c0b348de40c4d6f7606217420d47e6a3dd312bccfabb4d3363e5f36811d53", + "namespace.d.ts": "b4b1024db4e07c04a4272d4c5b6874e95735dacd62f9b00fd8e01a4c6a5fa628", "notifications.d.ts": "3521b63d147cf8964d216a5cb2be478dc99fb8e968d2c19384d23b072468564a", "pages.d.ts": "80bb3cca7087808b39f5caa9e869a35a6fb7c27f44e13db09adffd5ae6ac06d3", "routes.d.ts": "5181d8525ba54a74e9e0f058a06520c30affabcc17fbb8d4709bfe02004715e4", - "runtime.d.ts": "7e17afe9837bbc68229f3be45696762804e3b22e93853efe7a299f91f828b95d", + "runtime.d.ts": "5bbf460b12965f8ef01fb9ce8562b02fd30d49d49de248e132a9f3957eb098c7", "tokens.d.ts": "259041d9cdc47fcd0406e276b53e8a135b688abdfc923eda7862091a94050c44", "webhooks.d.ts": "4c236be1810ab095288a8093908e5bd6371595763877d2ef50b5c42223e93f3c", - "workspace-handle.d.ts": "cd5b24dfdec05ad72399feed3b28bb69559d322254391e5b5c8833c5a740389c", - "workspace.d.ts": "8e3f37a5e19f072557194f28a9d2e42e7b413e6f17c13b72f4369d79be3f4f65", + "workspace-handle.d.ts": "6a7fc4248b5209f4809885c471293793fcf611670fe521d4bf6f76ca3c77cb32", + "workspace.d.ts": "aac8e7b9b7e4d108c6826ebf48324a2b811b0bbdaecb54bbc847f91636ce373b", "resources/api-access.d.ts": "ff469369cc509224e605b6c528b399c3a049ba08962e70b718b2abe02ed9fe91", - "resources/desktop.d.ts": "3a16263fa441808a3252e86b01901e6bb06b002bd011dc3b57882759b530ed09", + "resources/desktop.d.ts": "78af205caf17936a4d70d68d93fbeb1b6f714cc596a8f918ab30e94000c7c50c", "resources/domains.d.ts": "5c924b9f11f1e4da459a77be2bf7bee6789cf3a339b4824fdbcbe60cb7effbcc", - "resources/images.d.ts": "cb4c1d235283fdef326bb52b53b576bb4dd7347db4bbaec6194909c7eaec0ffa", + "resources/images.d.ts": "98e4cc602d616f6ec5a3955b9e852320da178731f8d2671ffbda8df1689bc618", "resources/lifecycle.d.ts": "c0119b687ce8e4b99ae1ab11ffe0f0f0fd7e531d7491cd5a250afd04a3e742d9", - "resources/logs.d.ts": "3f6d8d8c52b7ef2cb2e7ae7355b419b1cff115498ace4ddb0822ae70e3409e6d", + "resources/logs.d.ts": "26471995c505cf6da784db9bf2710f3542715838a941fd1270bf910e61a85af5", "resources/metadata.d.ts": "f77f7c4d97a33be210659dc23867cc3a05dd290bf1b07649e2cd511902826247", "resources/metrics.d.ts": "7131ef7d4ec658a806f934f03073cfdabf3589fd230dc07896ef1aaf39ff82a9", "resources/network.d.ts": "746dfa7b41c676328c521dde350de2411998220498f8a2f2337228587c452764", "resources/public-access.d.ts": "d912d369033a3fae58527e86e1393755d968d6fba73f4283be1db1e6aeb0fbcb", "resources/resources.d.ts": "f3d0ceb05489059038dbe1cf90a2b4b12124cea9e5dd7bc27f09417368975c45", "resources/snapshots.d.ts": "0b49af562dbf1fde77daad19c5534aa998bba55cb66e0495d74d6bb6f9acbdee", - "resources/ssh.d.ts": "a609bc52e3aa0a924ce35447b2ecc2a9490733904d62924bee9b1130cd79ac48", + "resources/ssh.d.ts": "40e643d9f5c27f7ec9224ef0495fec844f1a707505f25391c36263075ec68f57", "resources/usage.d.ts": "f8b506bb9e4dac044d4e7b70c95b65d7ed4d21228f810b692fb380070d5b7a33", - "resources/workloads.d.ts": "029ccb919e80dabacd498c472ef0cbfcca85aa703d445559fce4eef942c725f6", - "runtime/desktop-tunnel.d.ts": "e7b2f57682e294d7da58c4d7bc9f1144848c60e3b1768a39b48cd407ddefc5fe", - "runtime/desktop.d.ts": "fd59e56cfeda31b8f282e2233124e971ec9405e5f1e613d8281cdf072e00bb23", + "resources/workloads.d.ts": "b845a69c9472735a966130c4234d6c425c33e7a3710b6fb36da7220666d5d6e6", + "runtime/desktop-tunnel.d.ts": "caa12f5645f30c598f8a6215768a10b2faba816ca41429cf4e12d49fdfb64ea5", + "runtime/desktop.d.ts": "108ea593f00342647093330d535067c76d2a81705aaba6262b7695a3f4d96514", "runtime/exec.d.ts": "3a189eb996fc5ff77369fabadb3593753df335e8521f2e65b9aec5c3e3000eb1", "runtime/files.d.ts": "ef8053442daaf8bff8aa3138a47a55700a71b7a8abb87dca9932a131b1b15e14", "runtime/proxy.d.ts": "a95afad25306e1d50f9bb5f516a183e4c64064239187870653e89e1cad7243e6", "runtime/search.d.ts": "45555ed282bdfbd05d830dae81f104fb8c4e5dda1297998d031851f5cdf2474a", - "runtime/terminal.d.ts": "20d2919360dc18fa3e986d22a7cc743e93f499b44a7d62beee69e7c5f5acff24", + "runtime/terminal.d.ts": "613602c4b6f1e03c9e2d98bef348dfa6915bffdee0c8e30238e1caea1c9a94e7", "runtime/transfer.d.ts": "3ad77e80490ad7d43b375e18cbecd05bdd8e28581cc83b051a6ddc3aabb967af", "runtime/watcher.d.ts": "3f53ce21e102191222df4df30f87b08dc5bda6c7f97e274915bcb390aea23a70", "runtime/ws.d.ts": "54661e56556ba6ec3a0f117f0e89739140456ccec397d06f66e45caa0a50cd4b", + "types/access.d.ts": "48b1609f12c0cdc6ee47c29fecbb173c692c943042db980773b1d08384d2b23f", "types/analytics.d.ts": "1e13344f77ded8ca988c3247a6efb1d9a8150531908b121f2f94490e36cff2ab", - "types/billing.d.ts": "1c654f58d952a2e5708f524bd43e69dd8d8ba4e32781b84438c63c0de82dd8f1", + "types/billing.d.ts": "fa09c04b60798ad26a62f11403d35031a75581a10d99d5e30051dfbdfd9dcc87", "types/cdn.d.ts": "df1191f12d183d07d8273ebd576e6b85129341eaab5e4bea72e0f518f1be2a87", - "types/client.d.ts": "6ed081c3d0b9f85909c0c952227f2add4a0be5ad5554f7d30641159f84c184d6", + "types/client.d.ts": "52347eb9d2e1c02150683754e5f25eefdf93b27135a6d9a67e3c1a5cdf25abb5", "types/common.d.ts": "e808006a6cb70d577d299248b13935aed6a391271124bda7b858951ce355d0c9", + "types/desktop.d.ts": "49caef7dc8a6680cb8e11ceff13d6ad5f09b2199c0e410fdef851b3bae9f2f7a", + "types/disks.d.ts": "24a49380dd263e7b1876e48c012a4ca935b4698a69cfd4c3352d53f4b27d4322", "types/edge-proxy.d.ts": "6d90537fe8967b93d86d1ea0703c180b3397af62e9c0ecf6d410447877ee00a4", "types/edge-tunnel.d.ts": "76bf25ec18d9b27cabfe80397bf2c3dd60b8b4a983ba899a8155b8d7d3671eb3", - "types/namespace.d.ts": "37231c9c969b5948e801f85fe9c55b4b0119634e0c00ada0419608162320eb8b", + "types/namespace.d.ts": "93429a951c5d23fe63c668efb43b0d391f528fc17cf74aaee963dfde4db83103", "types/network.d.ts": "ffeeaa86548299a20dd494cf76caf32db454198efe14e14b3242d5329ed41814", "types/notifications.d.ts": "7af066ad9adcf5df6327c22d80eb21a45dc3e628e88eb6d9c9f010e9628b2c6f", "types/pages.d.ts": "b37dd4fc7f8c4091055bfab77c32af7c75b0010d0b34fa849f65eeb54923f19d", "types/resources.d.ts": "ab27737f8ecc3320272a3d4d3f626de2acccb02469b072e83f1f4c7ac3b52116", - "types/runtime.d.ts": "cccb4094e908cbc70de1e19de6bc17744afc191c51693b8000ffdb175514d791", + "types/runtime.d.ts": "080f2bde78f731b58520620f56d1f931b0dd699517c008e4d11bc8e3ccbcdb87", "types/tokens.d.ts": "1c3a631896ab12d162c630333e594f688dfed661e41927dcfc6d4bb6f5487ca9", - "types/webhooks.d.ts": "fda0f68955fb502511cd2e7e56f9fed255ec472d18143ef0f2c63aa189b116fb", - "types/workspace-resources.d.ts": "9e76cf86397a53e2dd3372b965021ca3ef3015e2e6ee02b5cbd764d62bf17a48", - "types/workspace.d.ts": "199525ab080dc0414de5d758b632dcd6c9787029c818348b27ae697a5cca00ab" + "types/webhooks.d.ts": "20fbcb4780e62333f8e8ad9927c6dfadff84c00d638c8848bedea35de17b3d74", + "types/workspace-resources.d.ts": "25890166b4e25ea55757cb0d8745b2edac67b5201ae64d0c37e21de78844f9e2", + "types/workspace.d.ts": "cf8cf37f2ea577ad5e7497741b6b8479add9ca02fcb745148cfd5f7bb240dbb5" } }