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,704 @@
1
+ require "digest"
2
+ require "fileutils"
3
+ require "json"
4
+ require "pathname"
5
+ require_relative "app_stage"
6
+ require_relative "browser_migrations"
7
+ require_relative "entry_builder"
8
+ require_relative "gem_vendor"
9
+ require_relative "manifest"
10
+ require_relative "runner"
11
+ require_relative "schema_lock"
12
+ require_relative "source_pages"
13
+ require_relative "static_linter"
14
+ require_relative "toolchain"
15
+ require_relative "wasm_tree"
16
+ require_relative "../shell"
17
+ require_relative "../trace/schema_extractor"
18
+
19
+ module InstantRecord
20
+ class Compiler
21
+ # Build the compiled browser app: Rails source -> seams -> Roundhouse -> Spinel -> wasm -> web/dist.
22
+ class WasmBuild
23
+ WASM_OPT_LEVEL = "-Oz"
24
+ WASM_OPT_PASS = "-Oz"
25
+ SHELL_FORMAT = InstantRecord::Shell::FORMAT
26
+ DEFAULT_SYNC_ENDPOINT = "http://127.0.0.1:3210/instant_record"
27
+ SPINEL_PACKAGES = %w[json stringio zlib].freeze
28
+ HOTWIRE_ASSETS = %w[turbo.min.js stimulus.min.js stimulus-loading.js].freeze
29
+ CORE_PRELOAD_STYLES = %w[base ui mail].freeze
30
+
31
+ REACTOR_EXPORTS = [
32
+ "WasmBridge.handle_request",
33
+ "WasmBridge.handle_sync",
34
+ "WasmBridge.sync_plan",
35
+ "WasmBridge.handle_stream",
36
+ "WasmBridge.cursor",
37
+ "WasmBridge.history",
38
+ "WasmBridge.export_outbox",
39
+ "WasmBridge.import_outbox",
40
+ "WasmBridge.notices",
41
+ "WasmBridge.branch_outbox",
42
+ "WasmBridge.branch_replay"
43
+ ].join(",").freeze
44
+
45
+ SQLITE_CFLAGS = %w[
46
+ -Oz -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_OMIT_SHARED_CACHE -DSQLITE_OMIT_WAL
47
+ -DSQLITE_MAX_MMAP_SIZE=0 -DSQLITE_DEFAULT_SYNCHRONOUS=0 -DSQLITE_OMIT_DEPRECATED
48
+ -DSQLITE_OMIT_PROGRESS_CALLBACK -DSQLITE_TEMP_STORE=2
49
+ -DSQLITE_OMIT_UTF16 -DSQLITE_OMIT_AUTHORIZATION -DSQLITE_OMIT_COMPLETE
50
+ -DSQLITE_OMIT_TRACE -DSQLITE_OMIT_TCL_VARIABLE -DSQLITE_OMIT_COMPILEOPTION_DIAGS
51
+ -DSQLITE_OMIT_AUTOVACUUM -DSQLITE_OMIT_BLOB_LITERAL
52
+ -DSQLITE_ENABLE_FTS5
53
+ ].freeze
54
+
55
+ WASI_CFLAGS = %w[
56
+ --target=wasm32-wasip1
57
+ -ffunction-sections
58
+ -fdata-sections
59
+ -D_WASI_EMULATED_MMAN
60
+ -D_WASI_EMULATED_SIGNAL
61
+ -D_WASI_EMULATED_PROCESS_CLOCKS
62
+ -D_WASI_EMULATED_GETPID
63
+ ].freeze
64
+
65
+ WASM_OPT_FEATURES = %w[
66
+ --enable-exception-handling
67
+ --enable-bulk-memory
68
+ --enable-nontrapping-float-to-int
69
+ --enable-sign-ext
70
+ --enable-mutable-globals
71
+ --enable-reference-types
72
+ ].freeze
73
+
74
+ DEMO_MIGRATION_PLAN = {
75
+ "version" => 1,
76
+ "baseline" => 0,
77
+ "migrations" => {},
78
+ "history" => { "1" => "add-mail-tables" }
79
+ }.freeze
80
+
81
+ DEMO_SYNC_PARTITIONS = [
82
+ {
83
+ "path" => "/email",
84
+ "partitionParam" => "inbox",
85
+ "partitionDefault" => "support",
86
+ "partitionKey" => "mailbox_id",
87
+ "scopeParam" => "member",
88
+ "scopeDefault" => "maya",
89
+ "scopeHeader" => "X-Instant-Record-Member",
90
+ "valid" => "^[a-z]{1,32}$",
91
+ "lookupParams" => %w[before thread],
92
+ "preloadBefore" => { "idParam" => "before", "atParam" => "at", "type" => "MailEntry", "limit" => 50 },
93
+ "shellPath" => "/email/shell"
94
+ }
95
+ ].freeze
96
+
97
+ attr_reader :workspace, :gem_root, :pipeline_dir, :build_dir, :toolchain, :runner
98
+
99
+ def initialize(
100
+ workspace:,
101
+ gem_root:,
102
+ toolchain:,
103
+ app_source: nil,
104
+ models: [],
105
+ sync_windows: nil,
106
+ endpoint: nil,
107
+ mount_path: nil,
108
+ baseline: nil,
109
+ migration_paths: nil,
110
+ island: nil,
111
+ overrides: nil,
112
+ shell_snapshot: nil,
113
+ build_dir: nil,
114
+ out: $stdout
115
+ )
116
+ @workspace = File.expand_path(workspace.to_s)
117
+ @gem_root = File.expand_path(gem_root.to_s)
118
+ @pipeline_dir = File.join(@gem_root, "compiled/pipeline")
119
+ @build_dir = File.expand_path((build_dir || File.join(@workspace, ".build")).to_s)
120
+ @toolchain = Toolchain.load(toolchain)
121
+ @app_source = app_source ? File.expand_path(app_source.to_s) : nil
122
+ @demo = @app_source.nil?
123
+ @source_root = @app_source || File.join(@gem_root, "demo")
124
+ @models = models
125
+ @sync_windows = sync_windows
126
+ @endpoint = (endpoint || ENV.fetch("SYNC_ENDPOINT", DEFAULT_SYNC_ENDPOINT)).to_s.sub(%r{/+\z}, "")
127
+ @mount_path = (mount_path && !mount_path.to_s.empty?) ? mount_path.to_s.sub(%r{/+\z}, "") : "/instant_record"
128
+ @baseline = baseline
129
+ @migration_paths = migration_paths
130
+ @island = island
131
+ @overrides = overrides
132
+ @shell_snapshot = shell_snapshot.nil? ? ENV.fetch("INSTANT_RECORD_SHELL_SNAPSHOT", "") : shell_snapshot.to_s
133
+ @runner = Runner.new(build_dir: @build_dir)
134
+ @out = out
135
+ end
136
+
137
+ def run
138
+ FileUtils.mkdir_p(@build_dir)
139
+ FileUtils.mkdir_p(@toolchain.fetch("CACHE"))
140
+
141
+ if !@demo && !File.file?(SchemaLock.path(@app_source))
142
+ SchemaLock.write!(
143
+ root: @app_source,
144
+ baseline: @baseline,
145
+ migration_paths: @migration_paths
146
+ )
147
+ end
148
+
149
+ stamp = File.join(@build_dir, "stamp")
150
+ wanted = input_digest
151
+ output = File.join(@workspace, "web/dist")
152
+ if File.file?(stamp) && File.read(stamp) == wanted && File.file?(File.join(output, "index.html"))
153
+ @out.puts "build is current"
154
+ return Pathname(output)
155
+ end
156
+ File.delete(stamp) if File.exist?(stamp)
157
+
158
+ path_env = {
159
+ "PATH" => [@toolchain.join("SPINEL_HOME", "bin"), ENV.fetch("PATH", "")].join(File::PATH_SEPARATOR),
160
+ "WASI_SDK" => @toolchain.fetch("WASI_SDK")
161
+ }
162
+
163
+ emitted = emit_tree(native: false)
164
+ sqlite = sqlite_library
165
+ flags = @runner.run(["spin", "flags"], cwd: emitted[:tree], env: path_env).split
166
+ wasm = compile_reactor(emitted[:tree], flags, sqlite, path_env)
167
+ final = optimize_wasm(emitted[:tree], wasm)
168
+
169
+ dist, digest = build_web_site(emitted, final, wanted)
170
+ swap_dist(dist, output)
171
+
172
+ @out.puts "built web/dist with app-#{digest}.wasm (#{File.size(final)} bytes)"
173
+ File.write(stamp, wanted)
174
+ Pathname(output)
175
+ end
176
+
177
+ # Steps 1 to 3, shared with NativeBuild: staged app, Roundhouse emit, and
178
+ # single-threaded tree with its Wasm reactor entry.
179
+ def emit_tree(native: false)
180
+ FileUtils.mkdir_p(@build_dir)
181
+ app = File.join(@build_dir, "app-src")
182
+ manifest_path = File.join(@build_dir, Manifest::FILENAME)
183
+
184
+ stage = AppStage.stage(
185
+ source: @source_root,
186
+ target: app,
187
+ native: native,
188
+ island: @island,
189
+ overrides: @overrides,
190
+ models: @demo ? nil : @models,
191
+ migration_paths: @migration_paths,
192
+ overlay_dir: @demo ? File.join(@pipeline_dir, "demo") : nil,
193
+ manifest_path: manifest_path
194
+ )
195
+ manifest = stage.manifest
196
+
197
+ if @demo
198
+ plan = DEMO_MIGRATION_PLAN
199
+ else
200
+ if File.file?(SchemaLock.path(@app_source))
201
+ lock_report = SchemaLock.verify(
202
+ root: @app_source,
203
+ baseline: @baseline,
204
+ migration_paths: @migration_paths,
205
+ models: @models
206
+ )
207
+ raise BuildError, "Schema lockfile verification failed:\n#{lock_report}" unless lock_report.ok?
208
+ end
209
+ plan = BrowserMigrations.plan(
210
+ root: @app_source,
211
+ baseline: @baseline,
212
+ migration_paths: @migration_paths,
213
+ only_files: manifest.island? ? stage.trace.migrations : nil
214
+ )
215
+ File.write(File.join(@build_dir, "browser-migrations.json"), JSON.generate(plan))
216
+ end
217
+
218
+ vendor = GemVendor.new(
219
+ gem_src: @gem_root,
220
+ app_dir: app,
221
+ demo: @demo,
222
+ target: native ? :native : :wasm
223
+ )
224
+ vendor.run
225
+ StaticLinter.check!(app, staged: true, server_only_constants: vendor.server_only_constants)
226
+
227
+ emit = File.join(@build_dir, "emit")
228
+ clean(emit)
229
+ @runner.run([@toolchain.fetch("ROUNDHOUSE_BIN"), "--target", "spinel", "-o", emit, app], log: "emit.log")
230
+
231
+ version_controller_urls(app, emit)
232
+ disable_jemalloc(emit)
233
+
234
+ shell_fingerprint = InstantRecord::Shell.fingerprint(
235
+ models: EntryBuilder.app_models(manifest: manifest, models: @models),
236
+ schema_path: File.join(app, "db/schema.rb")
237
+ )
238
+
239
+ tree = File.join(@build_dir, "wasm-tree")
240
+ clean(tree)
241
+ EntryBuilder.write_wasm_entry(
242
+ emit_dir: emit,
243
+ demo: @demo,
244
+ manifest: manifest,
245
+ models: @models,
246
+ sync_windows: @sync_windows,
247
+ endpoint: @endpoint,
248
+ mount_path: @mount_path,
249
+ migration_plan: plan,
250
+ pipeline_dir: @pipeline_dir,
251
+ app_dir: app,
252
+ shell_fingerprint: shell_fingerprint
253
+ )
254
+ WasmTree.build(source: emit, target: tree, demo: @demo)
255
+
256
+ { app: app, emit: emit, tree: tree, plan: plan, manifest: manifest, shell_fingerprint: shell_fingerprint }
257
+ end
258
+
259
+ def input_digest
260
+ digest = Digest::SHA256.new
261
+ paths = [
262
+ @toolchain.path,
263
+ File.join(@workspace, "web/index.html"),
264
+ File.join(@workspace, "web/vite.config.js"),
265
+ File.join(@workspace, "web/package.json"),
266
+ File.join(@workspace, "web/package-lock.json"),
267
+ File.join(@gem_root, "lib/instant_record.rb"),
268
+ File.join(@gem_root, "sig/instant_record/native.rbs"),
269
+ File.join(@gem_root, "sig/instant_record/inertia.rbs")
270
+ ].select { |p| File.file?(p) }
271
+
272
+ inputs = [
273
+ [@pipeline_dir, ["."]],
274
+ [@workspace, ["web/src"]],
275
+ [@gem_root, ["lib/instant_record", "app/models/instant_record"]],
276
+ [@source_root, ["app", "config/routes", "config/locales"]]
277
+ ]
278
+
279
+ unless @demo
280
+ lock_file = SchemaLock.path(@source_root)
281
+ paths << lock_file if File.file?(lock_file)
282
+ inputs << [@source_root, ["db/browser_migrate"]]
283
+ Array(@migration_paths || [File.join(@source_root, "db/migrate")]).each do |dir|
284
+ inputs << [dir, ["."]]
285
+ end
286
+ digest.update(@baseline.to_s)
287
+ end
288
+
289
+ (AppStage::FILES + [Manifest::CONFIG_FILE]).each do |name|
290
+ candidate = File.join(@source_root, name)
291
+ paths << candidate if File.file?(candidate)
292
+ end
293
+
294
+ config_overrides = Manifest.merge_overrides(
295
+ Manifest.load_config(@source_root, island: @island),
296
+ @overrides
297
+ )
298
+ config_overrides[:include]["files"].each do |rel|
299
+ candidate = File.expand_path(rel.delete_prefix("/"), @source_root)
300
+ paths << candidate if candidate.start_with?("#{@source_root}#{File::SEPARATOR}") && File.file?(candidate)
301
+ end
302
+
303
+ digest.update(@demo ? "" : JSON.generate(Array(@models)))
304
+ digest.update("\0")
305
+ digest.update(JSON.generate(@sync_windows || {}))
306
+ digest.update("\0")
307
+ digest.update(@mount_path)
308
+ digest.update("\0")
309
+ digest.update(@island.to_s)
310
+ digest.update("\0")
311
+ digest.update(JSON.generate(@overrides || {}))
312
+ digest.update("\0")
313
+ digest.update(@shell_snapshot)
314
+ digest.update("\0")
315
+
316
+ inputs.each do |base_root, folders|
317
+ folders.each do |folder|
318
+ full = folder == "." ? base_root : File.join(base_root, folder)
319
+ next unless File.directory?(full)
320
+
321
+ Dir.glob("**/*", File::FNM_DOTMATCH, base: full).each do |rel|
322
+ entry = File.join(full, rel)
323
+ paths << entry if File.file?(entry) && !entry.end_with?(".pyc")
324
+ end
325
+ end
326
+ end
327
+
328
+ gem_pathname = Pathname(@gem_root)
329
+ paths.map { |p| File.expand_path(p) }.uniq.sort.each do |path|
330
+ rel = Pathname(path).relative_path_from(gem_pathname).to_s
331
+ digest.update(rel)
332
+ digest.update(File.binread(path))
333
+ end
334
+ digest.update(@endpoint)
335
+ digest.hexdigest
336
+ end
337
+
338
+ def outside_stylesheets(app_root)
339
+ layouts = File.join(app_root, "app/views/layouts")
340
+ return [] unless File.directory?(layouts)
341
+
342
+ links = []
343
+ Dir.children(layouts).sort.each do |name|
344
+ full = File.join(layouts, name)
345
+ next unless File.file?(full)
346
+
347
+ File.read(full).scan(/<link\b[^>]*>/).each do |tag|
348
+ href = tag[/href="(https:\/\/[^"<]+)"/, 1]
349
+ next unless href
350
+
351
+ if tag.include?('rel="preconnect"') && !links.include?(" #{tag}")
352
+ links << " #{tag}"
353
+ end
354
+ if tag.include?('rel="stylesheet"') && !tag.include?("crossorigin")
355
+ links << %( <link rel="preload" as="style" href="#{href}">)
356
+ end
357
+ end
358
+ end
359
+ links
360
+ end
361
+
362
+ def warm_scripts(assets_dir, deferred_css: [])
363
+ urls = []
364
+ seen = Digest::SHA256.new
365
+ deferred_css.each do |name|
366
+ path = File.join(assets_dir, name)
367
+ next unless File.file?(path)
368
+
369
+ digest = Digest::SHA256.file(path).hexdigest[0, 10]
370
+ seen.update(name + digest)
371
+ urls << "/assets/#{name}"
372
+ end
373
+ [
374
+ [assets_dir, "/assets/"],
375
+ [File.join(assets_dir, "controllers"), "/assets/controllers/"]
376
+ ].each do |folder, prefix|
377
+ next unless File.directory?(folder)
378
+
379
+ Dir.children(folder).sort.each do |name|
380
+ path = File.join(folder, name)
381
+ next unless name.end_with?(".js") && File.file?(path)
382
+
383
+ digest = Digest::SHA256.file(path).hexdigest[0, 10]
384
+ seen.update(name + digest)
385
+ versioned = prefix.end_with?("controllers/") || (name == "inbox.js" && @demo)
386
+ urls << prefix + name + (versioned ? "?v=#{digest}" : "")
387
+ end
388
+ end
389
+ return [] if urls.empty?
390
+
391
+ tag = seen.hexdigest[0, 12]
392
+ [
393
+ %( <script>try { if (localStorage.getItem("instant_record.warmed") !== "#{tag}") {) +
394
+ %( localStorage.setItem("instant_record.warmed", "#{tag}");) +
395
+ %( for (const url of #{JSON.generate(urls)}) fetch(url, { priority: "low" }).catch(function () {}); } } catch (error) {}</script>)
396
+ ]
397
+ end
398
+
399
+ def inject_preloads(dist, app_root)
400
+ links = app_root ? outside_stylesheets(app_root) : []
401
+ harness_dir = File.join(dist, "harness")
402
+ if File.directory?(harness_dir)
403
+ Dir.children(harness_dir).sort.each do |name|
404
+ if name.start_with?("worker-") && name.end_with?(".js")
405
+ # Started here, not preloaded: a modulepreload is a module load in the page, after
406
+ # which Firefox refuses the import map of the app's own page (compiled/web/vite.config.js).
407
+ links << %( <script>try { window.__worker = new Worker("/harness/#{name}", { type: "module" }); } catch (error) {}</script>)
408
+ end
409
+ end
410
+ end
411
+
412
+ assets_dir = File.join(dist, "assets")
413
+ deferred_css = []
414
+ if File.directory?(assets_dir)
415
+ css_files = Dir.children(assets_dir).sort.select { |name| name.end_with?(".css") }
416
+ css_files.each do |name|
417
+ stem = File.basename(name, ".css").sub(/-[0-9a-f]{8,}\z/, "")
418
+ if css_files.length <= 3 || CORE_PRELOAD_STYLES.include?(stem)
419
+ links << %( <link rel="preload" as="style" fetchpriority="low" href="/assets/#{name}">)
420
+ else
421
+ deferred_css << name
422
+ end
423
+ end
424
+ end
425
+
426
+ links.concat(warm_scripts(assets_dir, deferred_css: deferred_css))
427
+ return if links.empty?
428
+
429
+ index_path = File.join(dist, "index.html")
430
+ html = File.read(index_path)
431
+ File.write(index_path, html.sub(" </head>") { "#{links.join("\n")}\n </head>" })
432
+ end
433
+
434
+ private
435
+
436
+ def clean(path)
437
+ expanded = File.expand_path(path)
438
+ raise BuildError, "Refusing to clean outside #{@build_dir}: #{expanded}" unless expanded.start_with?("#{@build_dir}#{File::SEPARATOR}")
439
+
440
+ FileUtils.rm_rf(expanded)
441
+ end
442
+
443
+ def version_controller_urls(app, emit)
444
+ controller_dir = File.join(app, "app/javascript/controllers")
445
+ return unless File.directory?(controller_dir)
446
+
447
+ versions = {}
448
+ Dir.children(controller_dir).sort.each do |name|
449
+ file = File.join(controller_dir, name)
450
+ next unless name.end_with?(".js") && File.file?(file)
451
+
452
+ versions[name] = Digest::SHA256.file(file).hexdigest[0, 10]
453
+ end
454
+ return if versions.empty?
455
+
456
+ %w[config/importmap.rb config/application.rb].each do |config|
457
+ path = File.join(emit, config)
458
+ next unless File.file?(path)
459
+
460
+ source = File.read(path)
461
+ updated = source
462
+ versions.each do |name, version|
463
+ asset = "/assets/controllers/#{name}"
464
+ updated = updated.gsub(asset, "#{asset}?v=#{version}")
465
+ end
466
+ File.write(path, updated) if updated != source
467
+ end
468
+ end
469
+
470
+ def disable_jemalloc(emit)
471
+ toml = File.join(emit, "spin.toml")
472
+ return unless File.file?(toml)
473
+
474
+ config = File.read(toml)
475
+ File.write(toml, config.gsub("\nallocator = \"jemalloc\"", "\n# allocator = \"jemalloc\" (wasm build: no jemalloc)"))
476
+ end
477
+
478
+ def sqlite_library
479
+ shim = File.join(@pipeline_dir, "sqlite/rh_shim.c")
480
+ key = Digest::SHA256.hexdigest(SQLITE_CFLAGS.join(" ") + File.read(shim))[0, 16]
481
+ out = File.join(@toolchain.fetch("CACHE"), "sqlite-#{key}")
482
+ archive = File.join(out, "libsqlite3.a")
483
+
484
+ unless File.exist?(archive)
485
+ FileUtils.mkdir_p(out)
486
+ clang = @toolchain.join("WASI_SDK", "bin/clang")
487
+ sqlite_src = @toolchain.fetch("SQLITE_SRC")
488
+ @runner.run([clang, *WASI_CFLAGS, *SQLITE_CFLAGS, "-c", File.join(sqlite_src, "sqlite3.c"), "-o", File.join(out, "sqlite3.o")])
489
+ @runner.run([clang, *WASI_CFLAGS, WASM_OPT_LEVEL, "-I#{sqlite_src}", "-c", shim, "-o", File.join(out, "rh_shim.o")])
490
+ @runner.run([@toolchain.join("WASI_SDK", "bin/llvm-ar"), "rcs", archive, File.join(out, "sqlite3.o"), File.join(out, "rh_shim.o")])
491
+ end
492
+
493
+ out
494
+ end
495
+
496
+ def compile_reactor(tree, flags, sqlite, path_env)
497
+ build_subdir = File.join(tree, "build")
498
+ FileUtils.mkdir_p(build_subdir)
499
+ app_c = File.join(build_subdir, "app.c")
500
+ wasm = File.join(build_subdir, "app.wasm")
501
+ shim_c = File.join(@pipeline_dir, "reactor_shim.c")
502
+ sqlite_src = @toolchain.fetch("SQLITE_SRC")
503
+
504
+ @runner.run(
505
+ [
506
+ "spinel", "--target=wasm32-wasi", "-c",
507
+ "--ext-init", "app_boot",
508
+ "--ext-entry", REACTOR_EXPORTS,
509
+ *flags,
510
+ "main_wasm.rb", "-o", app_c
511
+ ],
512
+ cwd: tree,
513
+ env: path_env.merge("CPATH" => sqlite_src),
514
+ log: "spinel.log"
515
+ )
516
+
517
+ spinel_home = @toolchain.fetch("SPINEL_HOME")
518
+ clang = @toolchain.join("WASI_SDK", "bin/clang")
519
+ pkg_objs = SPINEL_PACKAGES.map { |pkg| File.join(spinel_home, "packages", pkg, "sp_#{pkg}_wasi.o") }
520
+
521
+ @runner.run(
522
+ [
523
+ clang, *WASI_CFLAGS, "-mexec-model=reactor", WASM_OPT_LEVEL,
524
+ "-Wno-all", "-ffp-contract=off",
525
+ "-DSP_INT_OVERFLOW_MODE_RAISE",
526
+ "-I#{File.join(spinel_home, 'lib')}",
527
+ "-I#{File.join(spinel_home, 'lib/regexp')}",
528
+ "-I#{File.join(spinel_home, 'lib/wasi')}",
529
+ "-I#{sqlite_src}",
530
+ "-I#{build_subdir}",
531
+ "-mllvm", "-wasm-enable-sjlj",
532
+ "-mllvm", "-wasm-use-legacy-eh=false",
533
+ app_c, shim_c,
534
+ *pkg_objs,
535
+ File.join(spinel_home, "lib/wasm32-wasi/libspinel_rt.a"),
536
+ "-L#{sqlite}", "-lsqlite3",
537
+ "-lm", "-lsetjmp",
538
+ "-lwasi-emulated-signal", "-lwasi-emulated-process-clocks",
539
+ "-lwasi-emulated-getpid", "-lwasi-emulated-mman",
540
+ "-Wl,-z,stack-size=8388608", "-Wl,--gc-sections",
541
+ "-o", wasm
542
+ ],
543
+ cwd: tree,
544
+ env: path_env,
545
+ log: "clang.log"
546
+ )
547
+ wasm
548
+ end
549
+
550
+ def optimize_wasm(tree, wasm)
551
+ stripped = File.join(tree, "build/app.stripped.wasm")
552
+ @runner.run([@toolchain.join("WASI_SDK", "bin/llvm-strip"), "-o", stripped, wasm])
553
+ final = stripped
554
+
555
+ wasm_opt = Toolchain.which("wasm-opt")
556
+ if wasm_opt
557
+ opted = File.join(tree, "build/app.opt.wasm")
558
+ @runner.run([wasm_opt, WASM_OPT_PASS, *WASM_OPT_FEATURES, final, "-o", opted], cwd: tree, log: "wasm-opt.log")
559
+ final = opted
560
+ end
561
+ final
562
+ end
563
+
564
+ def ensure_web_node_modules(web)
565
+ modules = File.join(web, "node_modules")
566
+ configured = @toolchain["WEB_NODE_MODULES"]
567
+ if File.symlink?(modules)
568
+ if configured && !configured.empty? && File.readlink(modules) != configured
569
+ unless File.directory?(configured)
570
+ raise BuildError, "WEB_NODE_MODULES does not exist at #{configured}. Install the web dependencies with `npm ci` and run `bin/rails instant_record:doctor`."
571
+ end
572
+ File.delete(modules)
573
+ File.symlink(configured, modules)
574
+ end
575
+ unless File.directory?(modules)
576
+ raise BuildError, "WEB_NODE_MODULES symlink target does not exist (#{File.readlink(modules)}). Install the web dependencies with `npm ci` and run `bin/rails instant_record:doctor`."
577
+ end
578
+ elsif !File.exist?(modules)
579
+ if configured.nil? || configured.empty? || !File.directory?(configured)
580
+ raise BuildError, "WEB_NODE_MODULES is missing (#{configured || 'unset'}). Install the web dependencies from compiled/web/package.json with `npm ci` and set WEB_NODE_MODULES in #{@toolchain.path}."
581
+ end
582
+ File.symlink(configured, modules)
583
+ end
584
+ end
585
+
586
+ def build_web_site(emitted, final_wasm, wanted)
587
+ app = emitted[:app]
588
+ emit = emitted[:emit]
589
+ plan = emitted[:plan]
590
+ manifest = emitted[:manifest]
591
+
592
+ web = File.join(@workspace, "web")
593
+ ensure_web_node_modules(web)
594
+
595
+ digest = Digest::SHA256.file(final_wasm).hexdigest[0, 10]
596
+ dist = File.join(@build_dir, "site")
597
+
598
+ shell_fingerprint = emitted[:shell_fingerprint]
599
+ schema_source = File.read(File.join(app, "db/schema.rb"))
600
+ trace_schema = InstantRecord::Trace::SchemaExtractor.from_schema_rb(schema_source)
601
+ schema_digest = Digest::SHA256.file(File.join(emit, "config/schema.rb")).hexdigest
602
+
603
+ @runner.run(
604
+ ["npx", "vite", "build", "--outDir", dist, "--emptyOutDir"],
605
+ cwd: web,
606
+ env: {
607
+ "VITE_WASM_URL" => "/app-#{digest}.wasm",
608
+ "VITE_SHELL_FINGERPRINT" => shell_fingerprint,
609
+ "VITE_SHELL_SNAPSHOT" => @shell_snapshot,
610
+ "VITE_SYNC_PARTITIONS" => @demo ? JSON.generate(DEMO_SYNC_PARTITIONS) : "[]",
611
+ "VITE_SYNC_ENDPOINT" => @endpoint,
612
+ "VITE_MOUNT_PATH" => @mount_path,
613
+ "VITE_SOURCE_VERSION" => wanted[0, 12],
614
+ "VITE_SCHEMA_VERSION" => plan["version"].to_s,
615
+ "VITE_SCHEMA_BASELINE" => plan["baseline"].nil? ? "" : plan["baseline"].to_s,
616
+ "VITE_MIGRATION_HISTORY" => JSON.generate(plan["history"] || {}),
617
+ "VITE_SCHEMA_DIGEST" => schema_digest,
618
+ "VITE_MANIFEST" => manifest ? manifest.to_compact_json : "{}",
619
+ "VITE_TRACE_SCHEMA" => JSON.generate(trace_schema)
620
+ },
621
+ log: "vite.log"
622
+ )
623
+
624
+ File.write(File.join(dist, "instant-record-release.json"), JSON.generate("version" => wanted))
625
+ File.write(File.join(dist, Manifest::FILENAME), manifest.to_json) if manifest
626
+ FileUtils.cp(final_wasm, File.join(dist, "app-#{digest}.wasm"))
627
+
628
+ assets = File.join(dist, "assets")
629
+ FileUtils.mkdir_p(File.join(assets, "controllers"))
630
+ [
631
+ File.join(app, "app/assets/stylesheets"),
632
+ File.join(app, "app/assets/images"),
633
+ File.join(app, "app/assets/builds"),
634
+ File.join(emit, "static/assets"),
635
+ File.join(app, "app/javascript")
636
+ ].each do |asset_dir|
637
+ FileCopy.copy_tree(asset_dir, assets) if File.directory?(asset_dir)
638
+ end
639
+
640
+ copy_hotwire_assets(assets)
641
+
642
+ if @demo
643
+ SourcePages.write(
644
+ app_dir: app,
645
+ dist_dir: dist,
646
+ version: wanted[0, 12],
647
+ demo_dir: @source_root,
648
+ pipeline_dir: @pipeline_dir
649
+ )
650
+ end
651
+
652
+ shell_worker = File.join(@source_root, "app/views/pwa/service-worker.js")
653
+ FileUtils.cp(shell_worker, File.join(dist, "service-worker.js")) if File.file?(shell_worker)
654
+
655
+ inject_preloads(dist, app)
656
+ [dist, digest]
657
+ end
658
+
659
+ def copy_hotwire_assets(assets)
660
+ found = {}
661
+ pattern = "**/{#{HOTWIRE_ASSETS.join(',')}}"
662
+
663
+ rails_gems = @toolchain["RAILS_GEMS"]
664
+ if rails_gems && File.directory?(rails_gems)
665
+ Dir.glob(pattern, base: rails_gems).sort.each do |rel|
666
+ name = File.basename(rel)
667
+ found[name] ||= File.join(rails_gems, rel)
668
+ end
669
+ end
670
+
671
+ missing = HOTWIRE_ASSETS - found.keys
672
+ unless missing.empty?
673
+ missing_pattern = "**/{#{missing.join(',')}}"
674
+ %w[turbo-rails stimulus-rails].each do |gem_name|
675
+ spec = Gem.loaded_specs[gem_name]
676
+ next unless spec && File.directory?(spec.full_gem_path)
677
+
678
+ Dir.glob(missing_pattern, base: spec.full_gem_path).sort.each do |rel|
679
+ name = File.basename(rel)
680
+ found[name] ||= File.join(spec.full_gem_path, rel)
681
+ end
682
+ end
683
+ end
684
+
685
+ HOTWIRE_ASSETS.each do |name|
686
+ FileUtils.cp(found[name], assets) if found[name]
687
+ end
688
+ end
689
+
690
+ def swap_dist(dist, output)
691
+ previous = File.join(@build_dir, "previous-site")
692
+ clean(previous)
693
+ File.rename(output, previous) if File.directory?(output)
694
+ begin
695
+ File.rename(dist, output)
696
+ rescue SystemCallError
697
+ File.rename(previous, output) if File.directory?(previous) && !File.exist?(output)
698
+ raise
699
+ end
700
+ clean(previous)
701
+ end
702
+ end
703
+ end
704
+ end