diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7cc657b..a947292 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,3 +39,28 @@ jobs: - name: Test (${{ matrix.platform }}) run: ${{ matrix.command }} + + docs: + name: Docs (warning-free) + runs-on: macos-26 + + steps: + - name: Checkout Code + uses: actions/checkout@v4 + + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Docs build (warning-free) + run: | + set -o pipefail + xcodebuild docbuild \ + -scheme StateManagement-Package \ + -destination 'platform=macOS' \ + 2>&1 | tee docbuild.log + if grep -q "warning:" docbuild.log; then + echo "::error::docbuild emitted warnings — see log above" + exit 1 + fi diff --git a/CONTEXT.md b/CONTEXT.md index 76f3904..4698be8 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -45,8 +45,8 @@ The name of a Value. Always into one Container. For an Atomic value, a key path. _Avoid_: ValueID, and calling the key path alone the Address of a Keyed value **`$` Address**: -The name of the AsyncStrategy seam for a Value declared with `@AsyncState`: the path to the `AsyncState` wrapper rather than to the Value, plus a key when Keyed. Kicks, inbound verbs, and the awaitable read take it. Watch and Operations take the Address. -_Avoid_: calling it a Value or a fourth shape, and using the Address on the strategy seam +An Address spelled with `$`, naming the wrapper rather than the Value it wraps, plus a key when Keyed. A `Computed` has only this Address; an `@AsyncState` has it as the AsyncStrategy seam, with its Value at the plain path. +_Avoid_: reading `$` as one wrapper kind, and using the plain Address on the strategy seam **Atomic value**: A Value that is the whole fact at one name in a Container. @@ -63,7 +63,7 @@ _Avoid_: derived state, selector, reducer ### AsyncStrategy **AsyncStrategy**: -Owns read, write, and external side effects for Addresses declared with `@AsyncState`. The Environment owns one instance per type and always holds the Value. `onRead`, `onWrite`, and `onDrop` take the `$` Address and a Policy value. +Owns read, write, and external side effects for Addresses declared with `@AsyncState`. The Environment owns one instance per type and always holds the Value. `onRead`, `onWrite`, and `onDrop` take the `$` Address and a Policy value, as do the inbound verbs and the awaitable read; Watch and Operations take the Value's plain Address. _Avoid_: Source, ExternalSource, Bridge, inbound Service, using Service for this, one instance per Address, persist Service as the write path **Policy**: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ff4f53d..155d375 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,6 +61,8 @@ Swift Package Index only *builds* the package (for the compatibility matrix) and //===----------------------------------------------------------------------===// ``` +- When linking an overloaded symbol, carry the full signature (``onRead(_:policy:current:)``). When two overloads differ only by type — DocC gives a readable disambiguator (``write(_:value:)-(_,Value)``) — use it. When overloads differ only by an `async`/`throws` effect (same erased parameter types), DocC's only disambiguator is an opaque hash (`-710qe`) — don't embed one; drop to a plain unlinked ``name`` instead. A hash breaks silently the next time the declaration changes and DocC recomputes it. + ## Pull requests - Branch off `main`. diff --git a/Sources/AsyncState/AsyncState.swift b/Sources/AsyncState/AsyncState.swift index 7cec0ab..8df0681 100644 --- a/Sources/AsyncState/AsyncState.swift +++ b/Sources/AsyncState/AsyncState.swift @@ -111,7 +111,7 @@ public final class AsyncState { self.init(wrappedValue: wrappedValue, policy: policy) } - /// Designated init. App call site is unlabeled ``init(wrappedValue:_:)``. + /// Designated init. App call site is unlabeled ``init(wrappedValue:_:)-(Value,S.Policy)``. /// A Satellite pins `S` by forwarding here; `S.Policy` does not reverse-infer `S`. @_disfavoredOverload public init(wrappedValue: Value, policy: S.Policy) @@ -138,7 +138,7 @@ public final class AsyncState { self.init(wrappedValue: wrappedValue, policy: policy) } - /// Designated keyed init. App call site is unlabeled ``init(wrappedValue:_:)``. + /// Designated keyed init. App call site is unlabeled ``init(wrappedValue:_:)-([Key:Entry],S.Policy)``. /// A Satellite pins `S` by forwarding here; `S.Policy` does not reverse-infer `S`. @_disfavoredOverload public init(wrappedValue: [Key: Entry], policy: S.Policy) diff --git a/Sources/AsyncState/AsyncStrategy.swift b/Sources/AsyncState/AsyncStrategy.swift index 116fce8..55c1c4f 100644 --- a/Sources/AsyncState/AsyncStrategy.swift +++ b/Sources/AsyncState/AsyncStrategy.swift @@ -31,7 +31,8 @@ import Foundation public protocol AsyncStrategy: AnyObject { /// Failure type for `$property.status`. Use `Never` if this strategy cannot fail. associatedtype Failure: Error - /// Per-Address value stored on ``AsyncState`` and passed to ``onRead``, ``onWrite``, and ``onDrop``. + /// Per-Address value stored on ``AsyncState`` and passed to ``onRead(_:policy:current:)``, + /// ``onWrite(_:policy:value:)``, and ``onDrop(_:policy:)``. /// /// Default `Void` keeps type-only `@AsyncState(SomeStrategy.self)` for mocks. A non-Void Policy /// requires a Policy value at the property wrapper. @@ -72,7 +73,7 @@ public protocol AsyncStrategy: AnyObject { ) /// The sourced Address died because this Address's Container dropped. Default is empty. - /// `policy` is the same value ``onRead`` received. + /// `policy` is the same value ``onRead(_:policy:current:)`` received. func onDrop( _ address: KeyPath>, policy: Policy diff --git a/Sources/AsyncState/AsyncStrategyEnvironment.swift b/Sources/AsyncState/AsyncStrategyEnvironment.swift index 4f332c6..e968231 100644 --- a/Sources/AsyncState/AsyncStrategyEnvironment.swift +++ b/Sources/AsyncState/AsyncStrategyEnvironment.swift @@ -23,7 +23,7 @@ private let strategyLogger = Logger( /// Restricted Environment for an AsyncStrategy. Standing for the Environment's lifetime. /// /// Inbound verbs are hidden Sync operations. No `write`. No `read`. No `spawnService`. -/// Nested ``perform`` has no `write`. Dead Environment: inbound verbs no-op. +/// Nested `perform` has no `write`. Dead Environment: inbound verbs no-op. /// /// > Important: A strategy retains this, never the ``SharedEnvironment``. The Environment owns the /// strategy, so holding it back is a cycle; this type holds the Environment weakly and answers diff --git a/Sources/Combine/SMPublished.swift b/Sources/Combine/SMPublished.swift index c3c6b90..7f83d3d 100644 --- a/Sources/Combine/SMPublished.swift +++ b/Sources/Combine/SMPublished.swift @@ -29,7 +29,7 @@ import Foundation /// It does not compose with ``AsyncState``: both are enclosing-instance wrappers over the same /// stored Value, and a property carries one wrapper. Publish a sourced Value by watching it. /// -/// The class must use the default ``ObservableObjectPublisher``. +/// The class must use the default `ObservableObjectPublisher`. /// /// - SeeAlso: @propertyWrapper diff --git a/Sources/Computation/Computed.swift b/Sources/Computation/Computed.swift index 3bb35e9..cfca866 100644 --- a/Sources/Computation/Computed.swift +++ b/Sources/Computation/Computed.swift @@ -50,6 +50,11 @@ A Computed is derived, not stored. Declare it with @Computed and reach it throug /// (`fatalError`). The cycle cannot be broken at runtime because the read is what would supply the /// value it is waiting for. /// +/// A Computed always runs, so reading one is never Optional — at a key just as much as atomically. +/// `Optional` marks what the framework knows may be missing, which a stored keyed entry is +/// (``StateContainer``) and a derivation is not. A genuinely partial derivation declares that +/// itself as `Computed` and returns `nil` for a key it declines. +/// /// In the following example `count` recomputes when `items` change; `isDone` /// recomputes when that id's `done` flag changes. /// ```swift @@ -62,7 +67,8 @@ A Computed is derived, not stored. Declare it with @Computed and reach it throug /// env.read(\ListContainer.items).count /// } /// -/// // Keyed computed: derived per item id. +/// // Keyed computed: derived per item id. `done` is stored, so its keyed read is Optional; +/// // picking `false` for an absent entry is the author's answer, not the framework's. /// @Computed var isDone = { env, id in /// env.read(\ListContainer.done, key: id) ?? false /// } diff --git a/Sources/Consumers/SwiftUI/Watch.swift b/Sources/Consumers/SwiftUI/Watch.swift index 46149e5..311b304 100644 --- a/Sources/Consumers/SwiftUI/Watch.swift +++ b/Sources/Consumers/SwiftUI/Watch.swift @@ -86,7 +86,7 @@ public struct Watch: DynamicProperty { /// Create a `SwiftUI.Binding` binding that mutates the value, by performing a generic sync operation - ``InlineValueMutation``. /// - /// - Parameter mutation: A closure like a ``SyncOperation/perform(in:)`` + /// - Parameter mutation: A closure like a `perform(in:)` /// - Returns: SwiftUI Binding (`SwiftUI.Binding`). public func binding( mutation: @escaping (Value, SyncOperationEnvironment) -> Void diff --git a/Sources/Operations/Write.swift b/Sources/Operations/Write.swift index 2bb9f0b..9825352 100644 --- a/Sources/Operations/Write.swift +++ b/Sources/Operations/Write.swift @@ -20,7 +20,7 @@ import Foundation /// /// Prefer named operations in production code. Use ``Write`` in previews and tests with /// ``SharedEnvironment/seeded(_:)``, ``SharedEnvironment/seed(_:)``, or -/// ``SwiftUI/View/seedEnvironment(_:)``. +/// `SwiftUI.View.seedEnvironment(_:)`. @MainActor public struct Write: SyncOperation { private let apply: (SyncOperationEnvironment) -> Void diff --git a/Sources/Seeding/SeedOperationsBuilder.swift b/Sources/Seeding/SeedOperationsBuilder.swift index b2d8369..155e220 100644 --- a/Sources/Seeding/SeedOperationsBuilder.swift +++ b/Sources/Seeding/SeedOperationsBuilder.swift @@ -16,7 +16,7 @@ import Foundation /// Collects ``SyncOperation``s for ``SharedEnvironment/seeded(_:)``, -/// ``SharedEnvironment/seed(_:)``, and ``SwiftUI/View/seedEnvironment(_:)``. +/// ``SharedEnvironment/seed(_:)``, and `SwiftUI.View.seedEnvironment(_:)`. @resultBuilder public enum SeedOperationsBuilder { public static func buildExpression(_ operation: any SyncOperation) -> [any SyncOperation] { diff --git a/Sources/Seeding/SharedEnvironment+Seeding.swift b/Sources/Seeding/SharedEnvironment+Seeding.swift index f1f0472..823492c 100644 --- a/Sources/Seeding/SharedEnvironment+Seeding.swift +++ b/Sources/Seeding/SharedEnvironment+Seeding.swift @@ -17,7 +17,7 @@ import Foundation extension SharedEnvironment { /// Creates a fresh ``SharedEnvironment`` and applies the builder’s operations in one - /// ``perform(_:file:line:)`` (single notify). Empty builders skip `perform`. + /// `perform(_:file:line:)` (single notify). Empty builders skip `perform`. /// /// DEBUG only. Use for previews and tests. public static func seeded( @@ -28,7 +28,7 @@ extension SharedEnvironment { return env } - /// Applies the builder’s operations to this Environment in one ``perform(_:file:line:)`` + /// Applies the builder’s operations to this Environment in one `perform(_:file:line:)` /// (single notify). Empty builders skip `perform`. /// /// DEBUG only. Use for previews and tests. ``seeded(_:)`` is the factory that creates a diff --git a/Sources/Telemetry/TraceContext.swift b/Sources/Telemetry/TraceContext.swift index 5da589a..ed43b40 100644 --- a/Sources/Telemetry/TraceContext.swift +++ b/Sources/Telemetry/TraceContext.swift @@ -133,6 +133,7 @@ public struct TraceContext: Sendable { /// - Parameters: /// - name: The human-readable name identifying the span operation. /// - kind: The categorization target of the span (e.g. user-facing or internal). + /// - valueDescription: A debug description of the value to attach to the span. Populated only when `TelemetryInternal` is enabled. /// - file: The source code file location. Defaults to caller `#fileID`. /// - line: The source code line number. Defaults to caller `#line`. /// - Returns: A non-copyable `Span` lifetime handle. @@ -250,6 +251,7 @@ extension TraceContext { /// - Parameters: /// - name: The human-readable name of the scope. /// - kind: The classification of the operation. + /// - valueDescription: A debug description of the value to attach to the span. Populated only when `TelemetryInternal` is enabled. /// - file: The source code file location. /// - line: The source code line. /// - operation: The execution block representing the span duration. diff --git a/TestingSupport/StateReader.swift b/TestingSupport/StateReader.swift index 6c3794d..54981ff 100644 --- a/TestingSupport/StateReader.swift +++ b/TestingSupport/StateReader.swift @@ -15,13 +15,13 @@ import Foundation import StateManagement -/// The sanctioned read for a test or a preview: a concrete ``EnvironmentService``, and therefore a +/// The sanctioned read for a test or a preview: a concrete `StateManagement.EnvironmentService`, and therefore a /// Restricted Environment, so its reads carry a known reader. /// /// It adds nothing. `read` for atomic, keyed, and computed Values is inherited, which is the point: /// out-of-package callers get the reads without the core exposing an identity-free one and without /// a Satellite reaching for `@testable` (ADR 0023). /// -/// Its reads subscribe, like any Service. Overriding ``serve()`` is not required; a reader that +/// Its reads subscribe, like any Service. Overriding `StateManagement.EnvironmentService.serve()` is not required; a reader that /// never reacts simply leaves the subscription unused. @MainActor public final class StateReader: EnvironmentService {} diff --git a/Tests/Computation/ComputedTests.swift b/Tests/Computation/ComputedTests.swift index 8194652..ed9e2d0 100644 --- a/Tests/Computation/ComputedTests.swift +++ b/Tests/Computation/ComputedTests.swift @@ -37,6 +37,16 @@ final class ComputedState: StateContainer { let e0 = env.read(\ComputedState.e, key: "0") ?? "" return "\(a)-\(b)-\(e0)" } + + // A partial derivation: nothing in the Container decides readiness for an untracked id, so the + // author declares `Output` Optional and answers `nil`. The framework never adds that Optional. + var trackedIDs: Set = [] + var readiness: [UUID: Bool] = [:] + + @Computed var isReady = { env, id in + guard env.read(\ComputedState.trackedIDs).contains(id) else { return nil } + return env.read(\ComputedState.readiness, key: id) ?? false + } } /// Service that reads the computation value on `serve` @@ -139,6 +149,26 @@ struct MutateUnrelated: SyncOperation { } } +/// Brings an id under the derivation's rule, so `isReady` stops declining it. +struct TrackID: SyncOperation { + let id: UUID + + func perform(in env: SyncOperationEnvironment) { + var tracked = env.read(\ComputedState.trackedIDs) + tracked.insert(id) + env.write(\ComputedState.trackedIDs, value: tracked) + } +} + +struct SetReadiness: SyncOperation { + let id: UUID + let isReady: Bool + + func perform(in env: SyncOperationEnvironment) { + env.write(\ComputedState.readiness, key: id, value: isReady) + } +} + struct ComputedTests { /// @@ -267,4 +297,32 @@ struct ComputedTests { #expect(service.lastComputationValue == initial) } + // MARK: - Optional Output + + /// A keyed Computed read is never Optional, because a Computed always runs. Partiality is the + /// author's to declare, so `nil` here is the closure's own answer and behaves like any other + /// output: cached per key, invalidated by the input that decided it. + @Test("A keyed Computed with Optional Output answers nil for a key it declines") + @MainActor func optionalOutputKeyedComputedDeclinesAKey() { + let env = SharedEnvironment() + let tracked = UUID() + let untracked = UUID() + env.perform(TrackID(id: tracked)) + env.perform(SetReadiness(id: tracked, isReady: true)) + + let declined = ValueObserverProbe + .watch(computedKeyed: \.$isReady, key: untracked, in: env) + let answered = ValueObserverProbe + .watch(computedKeyed: \.$isReady, key: tracked, in: env) + + declined.expect(value: nil) + answered.expect(value: true) + + // Tracking the declined id invalidates only its entry: the derivation reruns and now + // answers, which is what proves the earlier `nil` was a real output rather than a miss. + declined.perform(TrackID(id: untracked)) + declined.expect(updates: 1) + declined.expect(value: false) + answered.expect(value: true) + } } diff --git a/Tests/Consumers/WatchTests.swift b/Tests/Consumers/WatchTests.swift index 4cf5b9b..05c040a 100644 --- a/Tests/Consumers/WatchTests.swift +++ b/Tests/Consumers/WatchTests.swift @@ -54,6 +54,16 @@ final class TestWatchState: StateContainer { @Computed var boxKeyedComputed = { (env: ComputationEnvironment, key: String) -> Box in Box(n: env.read(\TestWatchState.counter) + key.count) } + + // Optional-Output keyed computed: nothing decides a state for an untracked row, so the author + // declares `Output` Optional and answers `nil`. A Watch binds that as `Bool?`, not `Bool??`. + var trackedRows: Set = [] + var rowFlags: [UUID: Bool] = [:] + + @Computed var rowState = { env, id in + guard env.read(\TestWatchState.trackedRows).contains(id) else { return nil } + return env.read(\TestWatchState.rowFlags, key: id) ?? false + } } struct UpdateValue: SyncOperation { @@ -99,6 +109,15 @@ struct SetBoxDict: SyncOperation { } } +struct TrackRow: SyncOperation { + let id: UUID + func perform(in env: SyncOperationEnvironment) { + var tracked = env.read(\TestWatchState.trackedRows) + tracked.insert(id) + env.write(\TestWatchState.trackedRows, value: tracked) + } +} + // MARK: - SwiftUI integration fixtures (host-only) #if canImport(AppKit) || canImport(UIKit) @@ -393,6 +412,31 @@ struct WatchTests { #expect(row7.lastValue == true) } + /// The consumer half of the keyed-optionality verdict. A Computed always runs, so the + /// framework adds no Optional of its own: an Optional `Output` reaches the watcher as + /// `Bool?` rather than `Bool??`, and `nil` diffs like any other output. + @Test("Watch binds an Optional Computed Output as-is and diffs nil like any value") + func keyedComputed_optionalOutputBindsAndDiffs() { + let env = SharedEnvironment() + let row = UUID() + let otherRow = UUID() + let probe = ValueObserverProbe + .watch(computedKeyed: \.$rowState, key: row, in: env) + + probe.expect(value: nil) + + // Tracking another row invalidates this one's entry too, but the derivation still declines + // it: an unchanged `nil` suppresses exactly as an unchanged non-Optional output would. + probe.perform(TrackRow(id: otherRow)) + probe.expect(updates: 0) + + probe.perform(TrackRow(id: row)) + probe.expect(updates: 1) + + let bound: Bool? = probe.render() + #expect(bound == false) + } + /// A suppressed keyed-computed notification must not drop the subscription. @Test func keyedComputed_suppressionDoesNotDropSubscription() { let env = SharedEnvironment()