Skip to content

Commit

Permalink
wip: okay actually add all updates to commit lol
Browse files Browse the repository at this point in the history
  • Loading branch information
ErrorErrorError committed Nov 22, 2023
1 parent d2e1998 commit db684fc
Show file tree
Hide file tree
Showing 53 changed files with 2,608 additions and 2,813 deletions.
5 changes: 3 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,6 @@ import Foundation
struct PlayerClient: _Client {
var dependencies: any Dependencies {
Architecture()
DatabaseClient()
ModuleClient()
SharedModels()
Styling()
Expand Down Expand Up @@ -888,7 +887,7 @@ extension _Client {

struct ComposableArchitecture: PackageDependency {
var dependency: Package.Dependency {
.package(url: "https://github.com/pointfreeco/swift-composable-architecture", exact: "1.2.0")
.package(url: "https://github.com/pointfreeco/swift-composable-architecture", exact: "1.4.2")
}
}
//
Expand Down Expand Up @@ -1075,6 +1074,7 @@ struct ContentCore: _Feature {
LoggerClient()
Tagged()
ComposableArchitecture()
Styling()
}
}
//
Expand Down Expand Up @@ -1450,6 +1450,7 @@ let package = Package {
Search()
Settings()
VideoPlayer()
ContentCore()

MochiApp()
} testTargets: {
Expand Down
1 change: 0 additions & 1 deletion Package/Sources/Clients/PlayerClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Foundation
struct PlayerClient: _Client {
var dependencies: any Dependencies {
Architecture()
DatabaseClient()
ModuleClient()
SharedModels()
Styling()
Expand Down
2 changes: 1 addition & 1 deletion Package/Sources/Dependencies/ComposableArchitecture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@

struct ComposableArchitecture: PackageDependency {
var dependency: Package.Dependency {
.package(url: "https://github.com/pointfreeco/swift-composable-architecture", exact: "1.2.0")
.package(url: "https://github.com/pointfreeco/swift-composable-architecture", exact: "1.4.2")
}
}
1 change: 1 addition & 0 deletions Package/Sources/Features/ContentCore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ struct ContentCore: _Feature {
LoggerClient()
Tagged()
ComposableArchitecture()
Styling()
}
}
1 change: 1 addition & 0 deletions Package/Sources/Index.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ let package = Package {
Search()
Settings()
VideoPlayer()
ContentCore()

MochiApp()
} testTargets: {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Clients/BuildClient/BuildClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import Semver
// MARK: - BuildClient

public struct BuildClient {
public let version: Semver
public let buildNumber: Int
public var version: Semver
public var buildNumber: Int
}

// MARK: TestDependencyKey
Expand Down
9 changes: 8 additions & 1 deletion Sources/Clients/DatabaseClient/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,20 @@ public struct DatabaseClient: Sendable {
public var insert: @Sendable (any Entity) async throws -> any Entity
public var update: @Sendable (any Entity) async throws -> any Entity
public var delete: @Sendable (any Entity) async throws -> Void
var fetch: @Sendable (any Entity.Type, Any) async throws -> [any Entity]
var fetch: @Sendable (any Entity.Type, any _Request) async throws -> [any Entity]
var observe: @Sendable (any Entity.Type, any _Request) -> AsyncStream<[any Entity]>
}

public extension DatabaseClient {
func fetch<T: Entity>(_ request: Request<T>) async throws -> [T] {
try await (fetch(T.self, request) as? [T]) ?? []
}

func observe<T: Entity>(_ request: Request<T>) -> AsyncStream<[T]> {
self.observe(T.self, request)
.compactMap { ($0 as? [T]) ?? [] }
.eraseToStream()
}
}

// MARK: DatabaseClient.Error
Expand Down
18 changes: 18 additions & 0 deletions Sources/Clients/DatabaseClient/Live.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ public extension DatabaseClient {
try await persistence.schedule { context in
try context.fetch(entityType, request).compactMap { try entityType.init(id: $0.objectID, context: context) }
}
} observe: { entityType, request in
.init { continuation in
Task.detached {
let fetchValues = {
try? await persistence.schedule { ctx in
try ctx.fetch(entityType, request).compactMap { try entityType.init(id: $0.objectID, context: ctx) }
}
}

await continuation.yield(fetchValues() ?? [])

let observe = NotificationCenter.default.notifications(named: NSManagedObjectContext.didSaveObjectsNotification)

for await _ in observe {
await continuation.yield(fetchValues() ?? [])
}
}
}
}
}()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,16 @@
import CoreData
import Foundation

protocol _Request {
associatedtype SomeEntity: Entity
var fetchLimit: Int? { get set }
var predicate: NSPredicate? { get set }
var sortDescriptors: [SortDescriptor] { get set }
}

// MARK: - Request

public struct Request<SomeEntity: Entity> {
public struct Request<SomeEntity: Entity>: _Request {
var fetchLimit: Int?
var predicate: NSPredicate?
var sortDescriptors: [SortDescriptor] = []
Expand Down
8 changes: 5 additions & 3 deletions Sources/Clients/ModuleClient/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ import XCTestDynamicOverlay

public struct ModuleClient: Sendable {
public var initialize: @Sendable () async throws -> Void
public var getModule: @Sendable (_ repoModuleID: RepoModuleID) async throws -> Self.Instance
public var removeModule: @Sendable (_ repoModuleID: RepoModuleID) async throws -> Void
public var getModule: @Sendable (_ repoModuleId: RepoModuleID) async throws -> Self.Instance
public var removeCachedModule: @Sendable (_ repoModuleId: RepoModuleID) async throws -> Void
public var removeCachedModules: @Sendable (_ repoID: Repo.ID) async throws -> Void
}

public extension ModuleClient {
Expand Down Expand Up @@ -67,7 +68,8 @@ extension ModuleClient: TestDependencyKey {
public static let testValue = Self(
initialize: unimplemented(),
getModule: unimplemented(),
removeModule: unimplemented()
removeCachedModule: unimplemented(),
removeCachedModules: unimplemented()
)
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Clients/ModuleClient/Extensions/JSContext+.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// File.swift
// JSContext+.swift
//
//
// Created by ErrorErrorError on 11/17/23.
Expand Down
67 changes: 66 additions & 1 deletion Sources/Clients/ModuleClient/Extensions/JSValue+.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,74 @@
//
// File.swift
// JSValue+.swift
//
//
// Created by ErrorErrorError on 11/17/23.
//
//

import Foundation
import JavaScriptCore

extension JSValue {
subscript(_ key: String) -> JSValue? {
guard !isOptional else {
return nil
}
guard let value = forProperty(key) else {
return nil
}
return !value.isOptional ? value : nil
}

var isOptional: Bool { isNull || isUndefined }

@discardableResult
func value(_ function: String) async throws -> JSValue {
try await withCheckedThrowingContinuation { continuation in
let onFufilled: @convention(block) (JSValue) -> Void = { value in
continuation.resume(returning: value)
}

let onRejected: @convention(block) (JSValue) -> Void = { value in
continuation.resume(throwing: value.toError(function))
}

self.invokeMethod(
"then",
withArguments: [
unsafeBitCast(onFufilled, to: JSValue.self),
unsafeBitCast(onRejected, to: JSValue.self)
]
)
}
}

func toError(_ functionName: String? = nil, stackTrace: Bool = true) -> JSValueError { .init(self, functionName) }
}

struct JSValueError: Error, LocalizedError, CustomStringConvertible {
var functionName: String?
var name: String?
var errorDescription: String?
var failureReason: String?
var stackTrace: String?

init(_ value: JSValue, _ functionName: String? = nil, stackTrace: Bool = true) {
self.functionName = functionName
self.name = value["name"]?.toString()
self.errorDescription = value["message"]?.toString()
self.failureReason = value["cause"]?.toString()
if stackTrace {
self.stackTrace = value["stack"]?.toString()
}
}

// TODO: Allow stack trace

Check warning on line 66 in Sources/Clients/ModuleClient/Extensions/JSValue+.swift

View workflow job for this annotation

GitHub Actions / run-swiftlint

TODOs should be resolved (Allow stack trace) (todo)
var description: String {
"""
Instance\(functionName.flatMap { ".\($0)" } ?? "") => \
\(name ?? "Error"): \(errorDescription ?? "No Message")
\(failureReason.flatMap { " \($0)" } ?? "\\")
"""
}
}
33 changes: 19 additions & 14 deletions Sources/Clients/ModuleClient/Instance.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import Foundation
import JavaScriptCore
import os
import SharedModels
import WebKit

public extension ModuleClient {
struct Instance {
Expand Down Expand Up @@ -39,7 +38,23 @@ public extension ModuleClient {
}
}

extension ModuleClient.Instance {
private func reportError<R>(_ callback: @autoclosure @escaping () async throws -> R) async rethrows -> R {
do {
return try await callback()
} catch {
self.logger.error("\(error)")
throw error
}
}
}

/// Available SourceModule Methods
public extension ModuleClient.Instance {
func searchFilters() async throws -> [SearchFilter] {
try await reportError(await runtime.searchFilters())
}

func search(_ query: SearchQuery) async throws -> Paging<Playlist> {
try await reportError(await runtime.search(query))
}
Expand All @@ -48,14 +63,13 @@ public extension ModuleClient.Instance {
try await reportError(await runtime.discoverListings(request))
}

func searchFilters() async throws -> [SearchFilter] {
try await reportError(await runtime.searchFilters())
}

func playlistDetails(_ id: Playlist.ID) async throws -> Playlist.Details {
try await reportError(await runtime.playlistDetails(id))
}
}

/// Available VideoContent Methods
public extension ModuleClient.Instance {
func playlistEpisodes(_ id: Playlist.ID, _ options: Playlist.ItemsRequestOptions?) async throws -> Playlist.ItemsResponse {
try await reportError(await runtime.playlistEpisodes(id, options))
}
Expand All @@ -67,13 +81,4 @@ public extension ModuleClient.Instance {
func playlistEpisodeServer(_ request: Playlist.EpisodeServerRequest) async throws -> Playlist.EpisodeServerResponse {
try await reportError(await runtime.playlistEpisodeServer(request))
}

private func reportError<R>(_ callback: @autoclosure @escaping () async throws -> R) async rethrows -> R {
do {
return try await callback()
} catch {
self.logger.error("\(error)")
throw error
}
}
}
32 changes: 31 additions & 1 deletion Sources/Clients/ModuleClient/JS+Bindings/JSContext+Console.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,39 @@
//
// File.swift
// JSContext+Console.swift
//
//
// Created by ErrorErrorError on 11/17/23.
//
//

import Foundation
import JavaScriptCore

extension JSContext {
func setConsoleBinding(_ logger: @escaping (MessageLog, String) -> Void) {
exceptionHandler = { _, exception in
guard let exception else {
return
}

logger(.error, exception.toError().description)
}

let console = JSValue(newObjectIn: self)

let logger = { (type: MessageLog) in {
guard let arguments = JSContext.currentArguments()?.compactMap({ $0 as? JSValue }) else {
return
}

let msg = arguments.compactMap { $0.toString() }
.joined(separator: " ")

logger(type, msg)
} as @convention(block) () -> Void }

MessageLog.allCases.forEach { console?.setObject(logger($0), forKeyedSubscript: $0.rawValue) }

setObject(console, forKeyedSubscript: "console" as NSString)
}
}
Loading

0 comments on commit db684fc

Please sign in to comment.