instant_record 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,140 @@
1
+ import SwiftUI
2
+
3
+ /// How the app looks: its colours and the two faces its text is set in. The
4
+ /// renderer's stock elements use it, and a hand-written view reads it from
5
+ /// the environment (`@Environment(\.theme)`), so the screens Ruby draws and
6
+ /// the ones written in SwiftUI look like one app.
7
+ ///
8
+ /// AppView(host: host, theme: .cora)
9
+ ///
10
+ /// The default, `.system`, changes nothing: lists, bars and text are iOS's
11
+ /// own. Every size stays a system text style, so Dynamic Type works as before.
12
+ public struct Theme {
13
+ /// Behind a screen, and behind a list. Nil leaves the system's.
14
+ public var page: Color?
15
+ /// A list's rows, and a card. Nil leaves the system's.
16
+ public var surface: Color?
17
+ /// A quiet fill: a field, a bubble, the status line. Nil leaves the system's.
18
+ public var fill: Color?
19
+ /// The line between rows and around a field. Nil leaves the system's.
20
+ public var hairline: Color?
21
+ /// Text.
22
+ public var ink: Color = .primary
23
+ /// Quieter text: `tone: "secondary"`.
24
+ public var muted: Color = .secondary
25
+ /// Links, buttons and `tone: "accent"`.
26
+ public var tint: Color = .accentColor
27
+ /// A filled shape that stands out, such as a bubble of your own words.
28
+ public var accent: Color = .accentColor
29
+ /// Text on `accent`.
30
+ public var onAccent: Color = .white
31
+ /// The face of headlines, labels and controls.
32
+ public var ui: Font.Design = .default
33
+ /// The face of running text: a `text` with no style, a field, and
34
+ /// whatever a hand-written view sets in it, such as a message's subject
35
+ /// and body. A view sets a face on the text itself, with
36
+ /// `.fontDesign(theme.reading)` or `.fontDesign(theme.ui)`: set around
37
+ /// a whole screen, one face wins over every other inside it.
38
+ public var reading: Font.Design = .default
39
+
40
+ public init() {}
41
+
42
+ /// iOS as it comes.
43
+ public static let system = Theme()
44
+
45
+ /// Cora's look: warm paper, ink and one blue, flat, with hairlines and
46
+ /// no cool grey. Cora's own typefaces are licensed and are not here. The
47
+ /// system's rounded face stands in for headlines and controls, and its
48
+ /// serif for what is read. In the dark it is the same ramp from the
49
+ /// other end.
50
+ public static let cora: Theme = {
51
+ var theme = Theme()
52
+ theme.page = Color(Cora.page)
53
+ theme.surface = Color(Cora.surface)
54
+ theme.fill = Color(Cora.fill)
55
+ theme.hairline = Color(Cora.hairline)
56
+ theme.ink = Color(Cora.ink)
57
+ theme.muted = Color(Cora.muted)
58
+ theme.tint = Color(Cora.tint)
59
+ theme.accent = Color(Cora.accent)
60
+ theme.onAccent = Color(Cora.onAccent)
61
+ theme.ui = .rounded
62
+ theme.reading = .serif
63
+ return theme
64
+ }()
65
+
66
+ /// One colour as 0xRRGGBB, in the light and in the dark.
67
+ struct Shade {
68
+ let light: UInt32
69
+ let dark: UInt32
70
+ }
71
+
72
+ /// Cora's tokens. Light: page, white, stone ink, sky-600 for links and
73
+ /// sky-300 as a fill under dark text. Dark: stone-950 page, stone-900
74
+ /// surface, stone-100 ink, sky-300 for links and fills.
75
+ enum Cora {
76
+ static let page = Shade(light: 0xFBF8F2, dark: 0x221E1B)
77
+ static let surface = Shade(light: 0xFFFFFF, dark: 0x2D2824)
78
+ static let fill = Shade(light: 0xF0E9DE, dark: 0x3B3530)
79
+ static let hairline = Shade(light: 0xE2D9CC, dark: 0x4A433C)
80
+ static let ink = Shade(light: 0x302B26, dark: 0xF3EEE6)
81
+ static let muted = Shade(light: 0x6E6456, dark: 0xB8AD9E)
82
+ static let tint = Shade(light: 0x2F6CA3, dark: 0x86B2D9)
83
+ static let accent = Shade(light: 0x86B2D9, dark: 0x86B2D9)
84
+ static let onAccent = Shade(light: 0x221E1B, dark: 0x221E1B)
85
+ }
86
+
87
+ #if canImport(UIKit)
88
+ /// The navigation bar's titles are UIKit's to draw. Give them the
89
+ /// theme's face and ink. The system theme leaves them alone.
90
+ func styleBars() {
91
+ guard ui != .default else { return }
92
+ let design: UIFontDescriptor.SystemDesign = ui == .rounded ? .rounded : ui == .serif ? .serif : .default
93
+ func face(_ style: UIFont.TextStyle) -> UIFont {
94
+ let plain = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style).withSymbolicTraits(.traitBold)
95
+ return UIFont(descriptor: plain?.withDesign(design) ?? plain ?? .preferredFontDescriptor(withTextStyle: style), size: 0)
96
+ }
97
+ let bar = UINavigationBar.appearance()
98
+ bar.largeTitleTextAttributes = [.font: face(.largeTitle), .foregroundColor: UIColor(ink)]
99
+ bar.titleTextAttributes = [.font: face(.headline), .foregroundColor: UIColor(ink)]
100
+ }
101
+ #else
102
+ func styleBars() {}
103
+ #endif
104
+ }
105
+
106
+ extension Color {
107
+ /// A colour that follows the light and the dark appearance.
108
+ init(_ shade: Theme.Shade) {
109
+ #if canImport(UIKit)
110
+ self.init(uiColor: UIColor { $0.userInterfaceStyle == .dark ? UIColor(rgb: shade.dark) : UIColor(rgb: shade.light) })
111
+ #else
112
+ self.init(nsColor: NSColor(name: nil) { $0.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? NSColor(rgb: shade.dark) : NSColor(rgb: shade.light) })
113
+ #endif
114
+ }
115
+ }
116
+
117
+ #if canImport(UIKit)
118
+ private typealias PlatformColor = UIColor
119
+ #else
120
+ private typealias PlatformColor = NSColor
121
+ #endif
122
+
123
+ private extension PlatformColor {
124
+ convenience init(rgb: UInt32) {
125
+ self.init(red: CGFloat((rgb >> 16) & 0xFF) / 255, green: CGFloat((rgb >> 8) & 0xFF) / 255, blue: CGFloat(rgb & 0xFF) / 255, alpha: 1)
126
+ }
127
+ }
128
+
129
+ private struct ThemeKey: EnvironmentKey {
130
+ static let defaultValue = Theme.system
131
+ }
132
+
133
+ public extension EnvironmentValues {
134
+ /// The look the app was given. A hand-written view reads its colours and
135
+ /// faces from here.
136
+ var theme: Theme {
137
+ get { self[ThemeKey.self] }
138
+ set { self[ThemeKey.self] = newValue }
139
+ }
140
+ }
@@ -0,0 +1,108 @@
1
+ import Foundation
2
+
3
+ /// The network, for an app that never opens a connection itself. A request is
4
+ /// "METHOD URL\n" and then the body. The answer is the status on the first
5
+ /// line and then the response body, or "0\n" when the network failed.
6
+ ///
7
+ /// `prepare` sees every request before it goes: an app adds what says who is
8
+ /// asking there, such as an Authorization header.
9
+ public struct Transport {
10
+ public static let offline = "0\n"
11
+ let session: URLSession
12
+ private let prepare: (inout URLRequest) -> Void
13
+
14
+ public init(timeout: TimeInterval = 10, prepare: @escaping (inout URLRequest) -> Void = { _ in }) {
15
+ let configuration = URLSessionConfiguration.ephemeral
16
+ configuration.timeoutIntervalForRequest = timeout
17
+ configuration.waitsForConnectivity = false
18
+ session = URLSession(configuration: configuration)
19
+ self.prepare = prepare
20
+ }
21
+
22
+ /// Apply this transport's request preparation (for example Authorization
23
+ /// headers) to an outgoing request.
24
+ public func prepareRequest(_ request: inout URLRequest) {
25
+ prepare(&request)
26
+ }
27
+
28
+ /// The request as it goes out, or nil when it cannot be read.
29
+ /// Supports both "METHOD URL\n<body>" and "METHOD URL\nHeader: Value\n\n<body>".
30
+ func request(_ exchange: String) -> URLRequest? {
31
+ let parts = exchange.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: false)
32
+ let line = parts[0].split(separator: " ", maxSplits: 1)
33
+ guard line.count == 2, let url = URL(string: String(line[1])), url.scheme != nil else { return nil }
34
+ var call = URLRequest(url: url)
35
+ call.httpMethod = String(line[0])
36
+ var rest = parts.count > 1 ? String(parts[1]) : ""
37
+ if let boundary = rest.range(of: "\n\n") {
38
+ let candidate = rest[..<boundary.lowerBound].split(separator: "\n")
39
+ if !candidate.isEmpty, candidate.allSatisfy({ $0.contains(": ") }) {
40
+ for header in candidate {
41
+ if let colon = header.range(of: ": ") {
42
+ call.setValue(String(header[colon.upperBound...]), forHTTPHeaderField: String(header[..<colon.lowerBound]))
43
+ }
44
+ }
45
+ rest = String(rest[boundary.upperBound...])
46
+ }
47
+ }
48
+ if call.httpMethod != "GET" {
49
+ call.httpBody = Data(rest.utf8)
50
+ if call.value(forHTTPHeaderField: "Content-Type") == nil {
51
+ call.setValue("application/json", forHTTPHeaderField: "Content-Type")
52
+ }
53
+ }
54
+ prepare(&call)
55
+ return call
56
+ }
57
+
58
+ /// Blocks the calling thread until the answer is in. Never call it on the
59
+ /// main thread, or on the engine's: a tap would wait behind it.
60
+ public func exchange(_ exchange: String) -> String {
61
+ guard let call = request(exchange) else { return Transport.offline }
62
+ var answer = Transport.offline
63
+ let done = DispatchSemaphore(value: 0)
64
+ session.dataTask(with: call) { data, response, _ in
65
+ if let response = response as? HTTPURLResponse, let data {
66
+ answer = "\(response.statusCode)\n" + String(decoding: data, as: UTF8.self)
67
+ }
68
+ done.signal()
69
+ }.resume()
70
+ done.wait()
71
+ return answer
72
+ }
73
+
74
+ /// Downloads raw binary bytes (such as a prebuilt SQLite shell) without
75
+ /// UTF-8 decoding. Runs `prepare` so auth headers travel with the request,
76
+ /// and ignores caches so private shells are never reused across callers.
77
+ public func download(_ urlString: String) -> (status: Int, data: Data)? {
78
+ guard let url = URL(string: urlString), url.scheme != nil else { return nil }
79
+ var call = URLRequest(url: url)
80
+ call.httpMethod = "GET"
81
+ call.cachePolicy = .reloadIgnoringLocalCacheData
82
+ prepare(&call)
83
+ var result: (status: Int, data: Data)?
84
+ let done = DispatchSemaphore(value: 0)
85
+ session.dataTask(with: call) { data, response, _ in
86
+ if let response = response as? HTTPURLResponse, let data {
87
+ result = (response.statusCode, data)
88
+ }
89
+ done.signal()
90
+ }.resume()
91
+ done.wait()
92
+ return result
93
+ }
94
+ }
95
+
96
+ /// One answer from the network, read apart.
97
+ struct Reply {
98
+ let status: Int
99
+ let body: String
100
+
101
+ init(_ answer: String) {
102
+ let parts = answer.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: false)
103
+ status = Int(parts[0]) ?? 0
104
+ body = parts.count > 1 ? String(parts[1]) : ""
105
+ }
106
+
107
+ var ok: Bool { (200..<300).contains(status) }
108
+ }
@@ -0,0 +1,237 @@
1
+ import Foundation
2
+ import SwiftUI
3
+
4
+ /// A strongly typed action a native view can dispatch back to its Ruby screen.
5
+ /// Generated action enums conform to this protocol.
6
+ public protocol NativeAction: Sendable {
7
+ var actionName: String { get }
8
+ var actionArgs: [String: String] { get }
9
+ var actionValues: [String: String] { get }
10
+ }
11
+
12
+ /// Default action type for components that declare no actions.
13
+ public enum NoAction: NativeAction, Equatable, Sendable {
14
+ public var actionName: String { "" }
15
+ public var actionArgs: [String: String] { [:] }
16
+ public var actionValues: [String: String] { [:] }
17
+ }
18
+
19
+ /// A strongly typed `Codable` props contract generated from a Ruby screen's
20
+ /// `contract` declaration.
21
+ public protocol NativeProps: Decodable, Equatable, Sendable {
22
+ associatedtype Action: NativeAction = NoAction
23
+ static var componentName: String { get }
24
+ }
25
+
26
+ /// An `@Observable` state container backed by a `NativeProps` snapshot and
27
+ /// typed action dispatcher, preserving view identity across `AppHost` redraws.
28
+ public protocol NativePropsState: AnyObject {
29
+ associatedtype Props: NativeProps
30
+ init(props: Props, actions: TypedActions<Props.Action>)
31
+ func apply(_ props: Props)
32
+ }
33
+
34
+ /// Type-safe wrapper around `Actions` for dispatching generated `NativeAction`
35
+ /// cases (carrying both `args` and `values`) back to the Ruby screen.
36
+ public struct TypedActions<Action: NativeAction> {
37
+ public let raw: Actions
38
+
39
+ public init(_ actions: Actions) {
40
+ self.raw = actions
41
+ }
42
+
43
+ public func send(_ action: Action) {
44
+ raw.perform(action.actionName, action.actionArgs, values: action.actionValues)
45
+ }
46
+
47
+ public func callAsFunction(_ action: Action) {
48
+ send(action)
49
+ }
50
+ }
51
+
52
+ /// Canonical string encoding for non-string action parameters crossing into
53
+ /// the monomorphic `Hash[String, String]` Ruby bridge.
54
+ public enum NativeWire {
55
+ public static func encode(_ value: String) -> String { value }
56
+ public static func encode(_ value: Int) -> String { String(value) }
57
+ public static func encode(_ value: Double) -> String { String(value) }
58
+ public static func encode(_ value: Bool) -> String { value ? "true" : "false" }
59
+
60
+ public static func encode(_ value: Date) -> String {
61
+ let formatter = ISO8601DateFormatter()
62
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
63
+ return formatter.string(from: value)
64
+ }
65
+ }
66
+
67
+ /// Raised when a `Props` payload cannot be coerced to the target `Codable`
68
+ /// contract (for example, a malformed number or date string).
69
+ public enum PropsDecodingError: Error, LocalizedError, Equatable {
70
+ case invalidValue(name: String, expected: String, actual: String)
71
+
72
+ public var errorDescription: String? {
73
+ switch self {
74
+ case let .invalidValue(name, expected, actual):
75
+ "Prop \(name) expected \(expected), got \(actual)"
76
+ }
77
+ }
78
+ }
79
+
80
+ public extension Props {
81
+ /// Convert this typed `Props` tree into a canonical JSON object suitable
82
+ /// for decoding any generated `Codable` props struct.
83
+ func jsonObject() throws -> [String: Any] {
84
+ var object: [String: Any] = [:]
85
+
86
+ for (name, value) in values {
87
+ object[name] = try Self.wireValue(value, name: name)
88
+ }
89
+ for (name, nested) in nestedObjects {
90
+ object[name] = try nested.jsonObject()
91
+ }
92
+ for (name, records) in lists {
93
+ object[name] = try records.map { try $0.jsonObject() }
94
+ }
95
+ for (name, items) in scalarLists {
96
+ object[name] = try items.enumerated().map { index, item in
97
+ try Self.wireValue(item, name: "\(name)[\(index)]")
98
+ }
99
+ }
100
+
101
+ return object
102
+ }
103
+
104
+ /// Decode this `Props` tree into a strongly typed `Decodable` struct.
105
+ func decode<T: Decodable>(_ type: T.Type) throws -> T {
106
+ let object = try jsonObject()
107
+ let data = try JSONSerialization.data(withJSONObject: object, options: [])
108
+ let decoder = JSONDecoder()
109
+ decoder.dateDecodingStrategy = .custom { decoder in
110
+ let container = try decoder.singleValueContainer()
111
+ let raw = try container.decode(String.self)
112
+ guard let parsed = Moment.date(raw) else {
113
+ throw DecodingError.dataCorruptedError(
114
+ in: container,
115
+ debugDescription: "Invalid ISO 8601 date: \(raw)"
116
+ )
117
+ }
118
+ return parsed
119
+ }
120
+ return try decoder.decode(T.self, from: data)
121
+ }
122
+
123
+ private static func wireValue(_ value: Value, name: String) throws -> Any {
124
+ switch value.type {
125
+ case "bool":
126
+ if value.text == "true" { return true }
127
+ if value.text == "false" { return false }
128
+ throw PropsDecodingError.invalidValue(name: name, expected: "bool", actual: value.text)
129
+ case "int":
130
+ guard let parsed = Int(value.text) else {
131
+ throw PropsDecodingError.invalidValue(name: name, expected: "int", actual: value.text)
132
+ }
133
+ return parsed
134
+ case "float":
135
+ guard let parsed = Double(value.text), parsed.isFinite else {
136
+ throw PropsDecodingError.invalidValue(name: name, expected: "float", actual: value.text)
137
+ }
138
+ return parsed
139
+ case "date", "string", "":
140
+ return value.text
141
+ default:
142
+ return value.text
143
+ }
144
+ }
145
+ }
146
+
147
+ public extension Screens {
148
+ /// Register a SwiftUI view bound directly to a generated `NativeProps`
149
+ /// `Codable` struct and its typed `TypedActions` dispatcher.
150
+ mutating func register<P: NativeProps, Content: View>(
151
+ _ propsType: P.Type,
152
+ @ViewBuilder _ view: @escaping (P, TypedActions<P.Action>) -> Content
153
+ ) {
154
+ register(P.componentName) { props, actions in
155
+ TypedPropsView(props: props, actions: actions, propsType: propsType, content: view)
156
+ }
157
+ }
158
+
159
+ /// Register a SwiftUI view bound to a generated `@Observable`
160
+ /// `NativePropsState` store whose properties update in-place across redraws.
161
+ mutating func register<S: NativePropsState, Content: View>(
162
+ state stateType: S.Type,
163
+ @ViewBuilder _ view: @escaping (S) -> Content
164
+ ) {
165
+ register(S.Props.componentName) { props, actions in
166
+ TypedStateView(props: props, actions: actions, stateType: stateType, content: view)
167
+ }
168
+ }
169
+ }
170
+
171
+ private struct TypedPropsView<P: NativeProps, Content: View>: View {
172
+ let props: Props
173
+ let actions: Actions
174
+ let propsType: P.Type
175
+ let content: (P, TypedActions<P.Action>) -> Content
176
+
177
+ var body: some View {
178
+ switch decode() {
179
+ case let .success(decoded):
180
+ content(decoded, TypedActions(actions))
181
+ case let .failure(error):
182
+ ContractDecodeFailureView(component: P.componentName, error: error)
183
+ }
184
+ }
185
+
186
+ private func decode() -> Result<P, Error> {
187
+ Result { try props.decode(P.self) }
188
+ }
189
+ }
190
+
191
+ private struct TypedStateView<S: NativePropsState, Content: View>: View {
192
+ let props: Props
193
+ let actions: Actions
194
+ let stateType: S.Type
195
+ let content: (S) -> Content
196
+
197
+ var body: some View {
198
+ switch Result(catching: { try props.decode(S.Props.self) }) {
199
+ case let .success(decoded):
200
+ NativeStateHost(decoded: decoded, actions: TypedActions(actions), content: content)
201
+ .id(actions.route)
202
+ case let .failure(error):
203
+ ContractDecodeFailureView(component: S.Props.componentName, error: error)
204
+ }
205
+ }
206
+ }
207
+
208
+ /// Keeps the `@Observable` state instance alive in `@State` across redraws and
209
+ /// applies new decoded `NativeProps` snapshots in-place.
210
+ private struct NativeStateHost<S: NativePropsState, Content: View>: View {
211
+ let decoded: S.Props
212
+ let content: (S) -> Content
213
+ @State private var state: S
214
+
215
+ init(decoded: S.Props, actions: TypedActions<S.Props.Action>, content: @escaping (S) -> Content) {
216
+ self.decoded = decoded
217
+ self.content = content
218
+ _state = State(initialValue: S(props: decoded, actions: actions))
219
+ }
220
+
221
+ var body: some View {
222
+ content(state)
223
+ .onChange(of: decoded) { _, next in
224
+ state.apply(next)
225
+ }
226
+ }
227
+ }
228
+
229
+ private struct ContractDecodeFailureView: View {
230
+ let component: String
231
+ let error: Error
232
+
233
+ var body: some View {
234
+ Label("Could not decode \(component): \(error.localizedDescription)", systemImage: "exclamationmark.triangle")
235
+ .foregroundStyle(.orange)
236
+ }
237
+ }