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,586 @@
1
+ require "digest"
2
+ require "etc"
3
+ require "fileutils"
4
+ require "json"
5
+ require "open3"
6
+ require "pathname"
7
+ require "rbconfig"
8
+ require "securerandom"
9
+ require_relative "entry_builder"
10
+ require_relative "kotlin_codegen"
11
+ require_relative "native_contracts"
12
+ require_relative "runner"
13
+ require_relative "swift_codegen"
14
+ require_relative "toolchain"
15
+ require_relative "wasm_build"
16
+
17
+ module InstantRecord
18
+ class Compiler
19
+ # Build the compiled app as a native static library (plus screenless host
20
+ # binary and Fiddle-loadable shared library for this machine, or
21
+ # cross-compiled libraries for iOS).
22
+ class NativeBuild
23
+ CACHE_SCHEMA_VERSION = 1
24
+ TARGETS = %w[iphonesimulator iphoneos].freeze
25
+ ENTRIES = (WasmBuild::REACTOR_EXPORTS.split(",").map { |name| name.split(".")[1] } + %w[render action open]).freeze
26
+ CFLAGS = %w[-O2 -Wno-all -ffp-contract=off -DSP_INT_OVERFLOW_MODE_RAISE].freeze
27
+ SQLITE_CFLAGS = %w[-O2 -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_ENABLE_FTS5].freeze
28
+ RUNTIME_CFLAGS = %w[-O2 -Wno-all -ffunction-sections -fdata-sections -ffp-contract=off].freeze
29
+ PACKAGES = WasmBuild::SPINEL_PACKAGES
30
+ IOS_MINIMUM = "17.0"
31
+
32
+ def self.shared_library_name
33
+ darwin? ? "libinstant_record_app.dylib" : "libinstant_record_app.so"
34
+ end
35
+
36
+ def self.darwin?
37
+ RbConfig::CONFIG["host_os"].to_s.match?(/darwin/i)
38
+ end
39
+
40
+ # Fields of a screen's node that Spinel did not type as a hash of strings.
41
+ # One loose hash anywhere in the app loosens the struct field for every screen.
42
+ def self.loose_node_fields(generated)
43
+ struct = generated[/^struct sp_InstantRecord__Native__Node_s \{(.*?)^\}/m, 1]
44
+ return [] unless struct
45
+
46
+ struct.scan(/(\w+) \* ?iv_(link_params|args|props);/).filter_map do |kind, name|
47
+ name unless kind == "sp_StrStrHash"
48
+ end
49
+ end
50
+
51
+ # Lines of app/screens where Spinel already knows a hash has the wrong type.
52
+ def self.certain_type_errors(generated)
53
+ found = []
54
+ place = ""
55
+ generated.each_line(chomp: true) do |line|
56
+ if line.start_with?("#line ")
57
+ place = line
58
+ elsif line.include?("(expected Hash)") && line.include?('sp_raise_cls("TypeError"')
59
+ match = place.match(/\A#line (\d+) "(?:app-src\/)?(app\/screens\/[^"]+)"/)
60
+ next unless match
61
+
62
+ location = "#{match[2]}:#{match[1]}"
63
+ found << location unless found.include?(location)
64
+ end
65
+ end
66
+ found
67
+ end
68
+
69
+ def self.makefile_list(spinel_home, name)
70
+ makefile = File.read(File.join(spinel_home, "Makefile"))
71
+ match = makefile.match(/^#{Regexp.escape(name)} = (.+)$/)
72
+ raise BuildError, "Spinel's Makefile has no #{name}" unless match
73
+
74
+ match[1].split
75
+ end
76
+
77
+ def initialize(
78
+ workspace:,
79
+ gem_root:,
80
+ toolchain:,
81
+ app_source: nil,
82
+ models: [],
83
+ sync_windows: nil,
84
+ endpoint: nil,
85
+ mount_path: nil,
86
+ target: nil,
87
+ baseline: nil,
88
+ migration_paths: nil,
89
+ island: nil,
90
+ overrides: nil,
91
+ swift_out: nil,
92
+ kotlin: false,
93
+ kotlin_out: nil,
94
+ kotlin_package: "dev.instantrecord.contracts",
95
+ out: $stdout
96
+ )
97
+ @workspace = File.expand_path(workspace.to_s)
98
+ @gem_root = File.expand_path(gem_root.to_s)
99
+ @pipeline_dir = File.join(@gem_root, "compiled/pipeline")
100
+ @toolchain = Toolchain.load(toolchain)
101
+ @app_source = app_source ? File.expand_path(app_source.to_s) : nil
102
+ @demo = @app_source.nil?
103
+ @source_root = @app_source || File.join(@gem_root, "demo")
104
+ @models = models
105
+ @sync_windows = sync_windows
106
+ @endpoint = (endpoint && !endpoint.to_s.empty?) ? endpoint.to_s.sub(%r{/+\z}, "") : nil
107
+ @mount_path = (mount_path && !mount_path.to_s.empty?) ? mount_path.to_s.sub(%r{/+\z}, "") : nil
108
+ @target = target.nil? || target.to_s.empty? ? nil : target.to_s
109
+ if @target && !TARGETS.include?(@target)
110
+ raise ArgumentError, "Unknown target #{@target}. Leave it out for this machine, or use #{TARGETS.join(' or ')}."
111
+ end
112
+ @build_dir = File.join(@workspace, *[".build-native", @target].compact)
113
+ @baseline = baseline
114
+ @migration_paths = migration_paths
115
+ @island = island
116
+ @overrides = overrides
117
+ @swift_out = swift_out ? File.expand_path(swift_out.to_s) : nil
118
+ @kotlin = !!kotlin || !kotlin_out.nil?
119
+ @kotlin_out = kotlin_out ? File.expand_path(kotlin_out.to_s) : nil
120
+ @kotlin_package = kotlin_package.to_s
121
+ @runner = Runner.new(build_dir: @build_dir)
122
+ @out = out
123
+ end
124
+
125
+ def run
126
+ @file_digests = {}
127
+ @dir_header_digests = {}
128
+ FileUtils.mkdir_p(@build_dir)
129
+ FileUtils.mkdir_p(object_cache_dir)
130
+
131
+ generate_contracts
132
+
133
+ spinel_home = @toolchain.fetch("SPINEL_HOME")
134
+ path_env = { "PATH" => [File.join(spinel_home, "bin"), ENV.fetch("PATH", "")].join(File::PATH_SEPARATOR) }
135
+ cc, toolchain_identity = resolve_compiler
136
+
137
+ wasm_build = WasmBuild.new(
138
+ workspace: @workspace,
139
+ gem_root: @gem_root,
140
+ toolchain: @toolchain,
141
+ app_source: @app_source,
142
+ models: @models,
143
+ sync_windows: @sync_windows,
144
+ endpoint: @endpoint,
145
+ mount_path: @mount_path,
146
+ baseline: @baseline,
147
+ migration_paths: @migration_paths,
148
+ island: @island,
149
+ overrides: @overrides,
150
+ build_dir: @build_dir,
151
+ out: @out
152
+ )
153
+ emitted = wasm_build.emit_tree(native: true)
154
+ app = emitted[:app]
155
+ tree = emitted[:tree]
156
+ plan = emitted[:plan]
157
+ manifest = emitted[:manifest]
158
+
159
+ screens = EntryBuilder.write_native_entry(
160
+ tree_dir: tree,
161
+ app_dir: app,
162
+ demo: @demo,
163
+ manifest: manifest,
164
+ models: @models,
165
+ sync_windows: @sync_windows,
166
+ endpoint: @endpoint,
167
+ mount_path: @mount_path,
168
+ migration_plan: plan,
169
+ shell_fingerprint: emitted[:shell_fingerprint]
170
+ )
171
+ @out.puts "wrote main_native.rb with screens: #{screens.empty? ? 'none' : screens.join(', ')}"
172
+
173
+ out_dir = File.join(tree, "build")
174
+ FileUtils.mkdir_p(out_dir)
175
+ app_c = File.join(out_dir, "app.c")
176
+ sqlite_src = @toolchain.fetch("SQLITE_SRC")
177
+
178
+ flags = @runner.run(["spin", "flags"], cwd: tree, env: path_env).split
179
+ @runner.run(
180
+ [
181
+ "spinel", "-c", "--force",
182
+ "--ext-init", "app_boot",
183
+ "--ext-entry", ENTRIES.map { |entry| "NativeBridge.#{entry}" }.join(","),
184
+ *flags, "main_native.rb", "-o", app_c
185
+ ],
186
+ cwd: tree,
187
+ env: path_env.merge("CPATH" => sqlite_src),
188
+ log: "spinel.log"
189
+ )
190
+
191
+ check_generated_c!(app_c)
192
+
193
+ includes = [
194
+ "-I#{File.join(spinel_home, 'lib')}",
195
+ "-I#{File.join(spinel_home, 'lib/regexp')}",
196
+ "-I#{sqlite_src}",
197
+ "-I#{out_dir}",
198
+ "-I#{File.join(@pipeline_dir, 'native')}"
199
+ ]
200
+
201
+ pic = @target ? [] : ["-fPIC"]
202
+ app_obj = File.join(out_dir, "app.o")
203
+ @runner.run([*cc, *self.class::CFLAGS, *pic, *includes, "-c", app_c, "-o", app_obj], log: "cc.log")
204
+
205
+ sqlite_headers = header_entries([File.join(sqlite_src, "sqlite3.h")])
206
+ native_shim_headers = header_entries([
207
+ File.join(@pipeline_dir, "native/instant_record_native.h"),
208
+ File.join(out_dir, "app.h")
209
+ ]) + [["spinel_lib_headers", directory_headers_digest(File.join(spinel_home, "lib"))]]
210
+
211
+ objects = [
212
+ app_obj,
213
+ cached_object(
214
+ name: "native_shim",
215
+ source: File.join(@pipeline_dir, "native_shim.c"),
216
+ cflags: self.class::CFLAGS + pic,
217
+ includes: includes,
218
+ cc: cc,
219
+ toolchain_identity: toolchain_identity,
220
+ extra_inputs: native_shim_headers
221
+ ),
222
+ cached_object(
223
+ name: "rh_shim",
224
+ source: File.join(@pipeline_dir, "sqlite/rh_shim.c"),
225
+ cflags: self.class::CFLAGS + pic,
226
+ includes: ["-I#{sqlite_src}"],
227
+ cc: cc,
228
+ toolchain_identity: toolchain_identity,
229
+ extra_inputs: sqlite_headers
230
+ ),
231
+ cached_object(
232
+ name: "sqlite3",
233
+ source: File.join(sqlite_src, "sqlite3.c"),
234
+ cflags: self.class::SQLITE_CFLAGS + pic,
235
+ includes: ["-I#{sqlite_src}"],
236
+ cc: cc,
237
+ toolchain_identity: toolchain_identity,
238
+ extra_inputs: sqlite_headers
239
+ )
240
+ ]
241
+
242
+ if @target
243
+ runtime = File.join(@build_dir, "libspinel_rt.a")
244
+ objects.concat(cross_runtime(cc, spinel_home, runtime, toolchain_identity))
245
+ else
246
+ objects.concat(PACKAGES.map { |name| File.join(spinel_home, "packages", name, "sp_#{name}.o") })
247
+ end
248
+
249
+ library = File.join(@build_dir, "libinstant_record_app.a")
250
+ File.delete(library) if File.exist?(library)
251
+ @runner.run(["ar", "rcs", library, *objects])
252
+
253
+ if @target
254
+ @out.puts "built #{library} and #{runtime} for #{@target}"
255
+ return Pathname(@build_dir)
256
+ end
257
+
258
+ host = File.join(@build_dir, "host")
259
+ @runner.run(
260
+ [
261
+ *cc, "-O2", *includes,
262
+ File.join(@pipeline_dir, "native/host.c"),
263
+ library,
264
+ File.join(spinel_home, "lib/libspinel_rt.a"),
265
+ "-lm", "-o", host
266
+ ],
267
+ log: "link.log"
268
+ )
269
+
270
+ shared = File.join(@build_dir, self.class.shared_library_name)
271
+ shared_args =
272
+ if self.class.darwin?
273
+ ["-dynamiclib", "-O2", "-Wl,-force_load,#{library}", File.join(spinel_home, "lib/libspinel_rt.a")]
274
+ else
275
+ ["-shared", "-O2", "-Wl,--whole-archive", library, "-Wl,--no-whole-archive", File.join(spinel_home, "lib/libspinel_rt.a")]
276
+ end
277
+ @runner.run([*cc, *shared_args, "-lm", "-o", shared], log: "link-shared.log")
278
+
279
+ @out.puts "built #{library}, #{shared} and #{host} (#{File.size(host)} bytes)"
280
+ Pathname(@build_dir)
281
+ end
282
+
283
+ def generate_contracts
284
+ screens_dir = File.join(@source_root, "app/screens")
285
+ contracts = NativeContracts.extract_dir(screens_dir)
286
+ return [] if contracts.empty?
287
+
288
+ generated_dir = File.join(@build_dir, "generated")
289
+ FileUtils.mkdir_p(generated_dir)
290
+
291
+ swift_source = SwiftCodegen.generate(contracts)
292
+ swift_path = File.join(generated_dir, "InstantRecordContracts.swift")
293
+ File.write(swift_path, swift_source)
294
+ if @swift_out && @swift_out != swift_path
295
+ FileUtils.mkdir_p(File.dirname(@swift_out))
296
+ File.write(@swift_out, swift_source)
297
+ end
298
+ @out.puts "wrote #{swift_path} (#{contracts.size} contracts)"
299
+
300
+ if @kotlin
301
+ kotlin_source = KotlinCodegen.generate(contracts, package: @kotlin_package)
302
+ kotlin_path = File.join(generated_dir, "InstantRecordContracts.kt")
303
+ File.write(kotlin_path, kotlin_source)
304
+ if @kotlin_out && @kotlin_out != kotlin_path
305
+ FileUtils.mkdir_p(File.dirname(@kotlin_out))
306
+ File.write(@kotlin_out, kotlin_source)
307
+ end
308
+ @out.puts "wrote #{kotlin_path} (#{contracts.size} contracts)"
309
+ end
310
+
311
+ contracts
312
+ end
313
+
314
+ private
315
+
316
+ def check_generated_c!(app_c)
317
+ generated = File.binread(app_c).force_encoding(Encoding::UTF_8).scrub
318
+ loose = self.class.loose_node_fields(generated)
319
+ unless loose.empty?
320
+ raise BuildError,
321
+ "Some screen gives params: or args: a hash that does not hold only strings (the compiler typed a node's " \
322
+ "#{loose.join(', ')} loosely). Call to_s on a value that comes from a record, and write Node.strings for an empty hash."
323
+ end
324
+
325
+ wrong = self.class.certain_type_errors(generated)
326
+ unless wrong.empty?
327
+ raise BuildError,
328
+ "A hash given to params: or args: must hold strings. Call to_s on a value that comes from a record:\n " \
329
+ "#{wrong.join("\n ")}"
330
+ end
331
+ end
332
+
333
+ def resolve_compiler
334
+ if @target
335
+ sdk = @runner.run(["xcrun", "--sdk", @target, "--show-sdk-path"]).strip
336
+ arch = Etc.uname[:machine]
337
+ triple = @target == "iphoneos" ? "arm64-apple-ios#{IOS_MINIMUM}" : "#{arch}-apple-ios#{IOS_MINIMUM}-simulator"
338
+ cc = ["xcrun", "--sdk", @target, "clang", "-target", triple, "-isysroot", sdk]
339
+ identity = {
340
+ "target" => @target,
341
+ "triple" => triple,
342
+ "sdk_path" => sdk,
343
+ "sdk_version" => probe_output(["xcrun", "--sdk", @target, "--show-sdk-version"], required: true),
344
+ "sdk_build_version" => probe_output(["xcrun", "--sdk", @target, "--show-sdk-build-version"], required: true),
345
+ "compiler_version" => probe_output(["xcrun", "--sdk", @target, "clang", "--version"], required: true)
346
+ }
347
+ [cc, identity]
348
+ else
349
+ cc_bin = ENV.fetch("CC", "cc")
350
+ identity = {
351
+ "target" => "host",
352
+ "platform" => "#{Etc.uname[:sysname]}-#{Etc.uname[:machine]}",
353
+ "cc" => Toolchain.which(cc_bin) || cc_bin,
354
+ "sdkroot" => ENV["SDKROOT"].to_s,
355
+ "deployment_target" => ENV["MACOSX_DEPLOYMENT_TARGET"].to_s,
356
+ "compiler_version" => probe_output([cc_bin, "--version"])
357
+ }
358
+ [[cc_bin], identity]
359
+ end
360
+ end
361
+
362
+ def probe_output(cmd, required: false)
363
+ argv = cmd.map(&:to_s)
364
+ stdout, stderr, status = Open3.capture3([argv.first, argv.first], *argv[1..])
365
+ unless status.success?
366
+ raise BuildError, "build step failed: #{argv.join(' ')}\n#{stderr.strip}" if required
367
+
368
+ return ""
369
+ end
370
+
371
+ out = stdout.strip
372
+ out.empty? ? stderr.strip : out
373
+ rescue Errno::ENOENT => e
374
+ raise BuildError, "build step failed: executable #{argv.first.inspect} not found (#{e.message})" if required
375
+
376
+ ""
377
+ end
378
+
379
+ def object_cache_dir
380
+ File.join(@toolchain.fetch("CACHE"), "native-objects")
381
+ end
382
+
383
+ def file_digest(path)
384
+ @file_digests ||= {}
385
+ @file_digests[path] ||= Digest::SHA256.file(path).hexdigest
386
+ end
387
+
388
+ def header_entries(paths)
389
+ paths.filter_map do |path|
390
+ next unless File.file?(path)
391
+
392
+ [File.basename(path), file_digest(path)]
393
+ end
394
+ end
395
+
396
+ def directory_headers_digest(dir, pattern: "**/*.{h,hh,hpp,inc,def}", exclude: [])
397
+ @dir_header_digests ||= {}
398
+ excluded = exclude.map { |path| File.expand_path(path) }.sort
399
+ @dir_header_digests[[dir, pattern, excluded]] ||= begin
400
+ digest = Digest::SHA256.new
401
+ if File.directory?(dir)
402
+ Dir.glob(pattern, base: dir).sort.each do |rel|
403
+ full = File.expand_path(rel, dir)
404
+ next if excluded.include?(full) || !File.file?(full)
405
+
406
+ digest.update(JSON.generate([rel, file_digest(full)]))
407
+ end
408
+ end
409
+ digest.hexdigest
410
+ end
411
+ end
412
+
413
+ def object_cache_key(name:, source:, cflags:, toolchain_identity:, extra_inputs: [])
414
+ payload = {
415
+ "schema" => CACHE_SCHEMA_VERSION,
416
+ "kind" => "object",
417
+ "name" => name.to_s,
418
+ "toolchain" => toolchain_identity,
419
+ "cflags" => cflags.map(&:to_s),
420
+ "source" => file_digest(source),
421
+ "extra_inputs" => extra_inputs
422
+ }
423
+ Digest::SHA256.hexdigest(JSON.generate(payload))
424
+ end
425
+
426
+ def archive_cache_key(name:, cflags:, toolchain_identity:, member_keys:)
427
+ payload = {
428
+ "schema" => CACHE_SCHEMA_VERSION,
429
+ "kind" => "archive",
430
+ "name" => name.to_s,
431
+ "toolchain" => toolchain_identity,
432
+ "cflags" => cflags.map(&:to_s),
433
+ "members" => member_keys
434
+ }
435
+ Digest::SHA256.hexdigest(JSON.generate(payload))
436
+ end
437
+
438
+ def cached_object(name:, source:, cflags:, includes:, cc:, toolchain_identity: nil, extra_inputs: [], key: nil)
439
+ digest = key || object_cache_key(
440
+ name: name,
441
+ source: source,
442
+ cflags: cflags,
443
+ toolchain_identity: toolchain_identity,
444
+ extra_inputs: extra_inputs
445
+ )
446
+ cached_path = File.join(object_cache_dir, "#{name}-#{digest}.o")
447
+ fetch_cached_file(cached_path) do |tmp_path|
448
+ @runner.run([*cc, *cflags, *includes, "-c", source, "-o", tmp_path], log: "cc.log")
449
+ end
450
+ end
451
+
452
+ def fetch_cached_file(cached_path, &block)
453
+ return cached_path if File.file?(cached_path) && !File.zero?(cached_path)
454
+
455
+ with_atomic_write(cached_path, &block)
456
+ end
457
+
458
+ def copy_atomically(src, dst)
459
+ with_atomic_write(dst) { |tmp_path| FileUtils.cp(src, tmp_path) }
460
+ end
461
+
462
+ def with_atomic_write(dest_path)
463
+ dir = File.dirname(dest_path)
464
+ FileUtils.mkdir_p(dir)
465
+ base = File.basename(dest_path)
466
+ ext = File.extname(base)
467
+ stem = File.basename(base, ext)
468
+ tmp_path = File.join(dir, ".#{stem}.#{Process.pid}.#{Thread.current.object_id}.#{SecureRandom.hex(6)}.tmp#{ext}")
469
+
470
+ begin
471
+ yield tmp_path
472
+ unless File.file?(tmp_path) && !File.zero?(tmp_path)
473
+ raise BuildError, "Expected build step to produce non-empty #{tmp_path}"
474
+ end
475
+ File.rename(tmp_path, dest_path)
476
+ ensure
477
+ FileUtils.rm_f(tmp_path) if File.exist?(tmp_path)
478
+ end
479
+
480
+ dest_path
481
+ end
482
+
483
+ def sanitize_cache_name(value)
484
+ value.to_s.gsub(/[^A-Za-z0-9_.-]+/, "_")
485
+ end
486
+
487
+ def runtime_member(name:, source:, cflags:, includes:, extra_inputs:, toolchain_identity:)
488
+ {
489
+ name: name,
490
+ source: source,
491
+ cflags: cflags,
492
+ includes: includes,
493
+ extra_inputs: extra_inputs,
494
+ key: object_cache_key(
495
+ name: name,
496
+ source: source,
497
+ cflags: cflags,
498
+ toolchain_identity: toolchain_identity,
499
+ extra_inputs: extra_inputs
500
+ )
501
+ }
502
+ end
503
+
504
+ def cross_runtime(cc, spinel_home, runtime, toolchain_identity)
505
+ lib = File.join(spinel_home, "lib")
506
+ regexp_dir = File.join(lib, "regexp")
507
+ regexp = ["-I#{regexp_dir}", "-I#{File.join(regexp_dir, 'shim')}"]
508
+ runtime_cflags = self.class::RUNTIME_CFLAGS
509
+ re_src_paths = self.class.makefile_list(spinel_home, "RE_SRC")
510
+ re_src_full = re_src_paths.map { |path| File.join(spinel_home, path) }
511
+
512
+ regexp_headers = [[
513
+ "spinel_regexp_headers",
514
+ directory_headers_digest(regexp_dir, pattern: "**/*.{c,h,hh,hpp,inc,def}", exclude: re_src_full)
515
+ ]]
516
+ lib_headers = [["spinel_lib_headers", directory_headers_digest(lib)]]
517
+
518
+ members = re_src_paths.map do |path|
519
+ runtime_member(
520
+ name: "re_#{sanitize_cache_name(path.delete_suffix('.c'))}",
521
+ source: File.join(spinel_home, path),
522
+ cflags: runtime_cflags,
523
+ includes: regexp,
524
+ extra_inputs: regexp_headers,
525
+ toolchain_identity: toolchain_identity
526
+ )
527
+ end
528
+
529
+ members.concat(
530
+ self.class.makefile_list(spinel_home, "RT_MEMBERS").map do |member|
531
+ runtime_member(
532
+ name: "rt_#{sanitize_cache_name(member)}",
533
+ source: File.join(lib, "#{member}.c"),
534
+ cflags: runtime_cflags,
535
+ includes: ["-I#{lib}", *regexp],
536
+ extra_inputs: lib_headers,
537
+ toolchain_identity: toolchain_identity
538
+ )
539
+ end
540
+ )
541
+
542
+ archive_key = archive_cache_key(
543
+ name: "libspinel_rt",
544
+ cflags: runtime_cflags,
545
+ toolchain_identity: toolchain_identity,
546
+ member_keys: members.map { |member| [member[:name], member[:key]] }
547
+ )
548
+ cached_archive = File.join(object_cache_dir, "libspinel_rt-#{archive_key}.a")
549
+
550
+ fetch_cached_file(cached_archive) do |tmp_archive|
551
+ objects = members.map do |member|
552
+ cached_object(
553
+ name: member[:name],
554
+ source: member[:source],
555
+ cflags: member[:cflags],
556
+ includes: member[:includes],
557
+ cc: cc,
558
+ key: member[:key]
559
+ )
560
+ end
561
+ @runner.run(["ar", "rcs", tmp_archive, *objects])
562
+ end
563
+
564
+ copy_atomically(cached_archive, runtime)
565
+
566
+ PACKAGES.map do |name|
567
+ folder = File.join(spinel_home, "packages", name)
568
+ source = File.join(folder, "sp_#{name}.c")
569
+ pkg_headers = lib_headers + [[
570
+ "package_#{name}_headers",
571
+ directory_headers_digest(folder, pattern: "**/*.{c,h,hh,hpp,inc,def}", exclude: [source])
572
+ ]]
573
+ cached_object(
574
+ name: "sp_#{sanitize_cache_name(name)}",
575
+ source: source,
576
+ cflags: runtime_cflags,
577
+ includes: ["-I#{lib}", "-I#{folder}"],
578
+ cc: cc,
579
+ toolchain_identity: toolchain_identity,
580
+ extra_inputs: pkg_headers
581
+ )
582
+ end
583
+ end
584
+ end
585
+ end
586
+ end