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,610 @@
1
+ require "json"
2
+
3
+ module InstantRecord
4
+ # Lightweight table and partition read tracker for handle_request and render.
5
+ #
6
+ # Captures SELECT queries executed within a tracked block (via
7
+ # ActiveSupport::Notifications in CRuby, or direct record_sql calls from the
8
+ # compiled SQLite adapter), extracting referenced tables and sound outer-WHERE
9
+ # partition equality constraints.
10
+ #
11
+ # Soundness rule: a table is only narrowed to partition values when EVERY query
12
+ # touching that table in the tracked block constrains that partition column via
13
+ # top-level AND-ed `=` or `IN` predicates (with no top-level `OR`). Any query
14
+ # that reads a table without constraining a column drops that column from the
15
+ # table's partition filter, safely falling back to whole-table invalidation.
16
+ module ReadTracker
17
+ INTERNAL_TABLES = %w[
18
+ sqlite_master
19
+ sqlite_schema
20
+ sqlite_temp_master
21
+ sqlite_temp_schema
22
+ schema_migrations
23
+ ar_internal_metadata
24
+ instant_record_outbox
25
+ instant_record_sync_metadata
26
+ instant_record_changes
27
+ instant_record_applied_mutations
28
+ ].freeze
29
+
30
+ SQL_KEYWORDS = %w[
31
+ where join inner left right full cross outer on group order limit offset
32
+ having union intersect except set values into as
33
+ ].freeze
34
+
35
+ class << self
36
+ def tracking?
37
+ !!@tracking
38
+ end
39
+
40
+ def last_reads
41
+ @last_reads
42
+ end
43
+
44
+ # Run a block while tracking table/partition reads. Returns the finalized
45
+ # reads snapshot hash (and stores it in `last_reads`).
46
+ def track(&block)
47
+ _value, reads = capture(&block)
48
+ reads
49
+ end
50
+
51
+ # Run a block while tracking table/partition reads. Returns [block_value, reads].
52
+ def capture(&block)
53
+ previous_tracking = @tracking
54
+ previous_frame = @frame
55
+ @tracking = true
56
+ @frame = {}
57
+
58
+ value =
59
+ if defined?(ActiveSupport::Notifications) && ActiveSupport::Notifications.respond_to?(:subscribed)
60
+ callback = lambda do |_name, _start, _finish, _id, payload|
61
+ next if payload[:name] == "SCHEMA"
62
+
63
+ record_sql(payload[:sql], extract_binds(payload))
64
+ end
65
+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &block)
66
+ else
67
+ block.call
68
+ end
69
+
70
+ reads = finalize(@frame)
71
+ @last_reads = reads
72
+ [value, reads]
73
+ ensure
74
+ @tracking = previous_tracking
75
+ @frame = previous_frame
76
+ end
77
+
78
+ # Programmatically record a read of `table` with optional `partitions`
79
+ # hash (`{ "mailbox_id" => ["support"] }` or `{ "mailbox_id" => "support" }`).
80
+ # Passing nil or {} marks the table read without partition narrowing.
81
+ def record(table, partitions = nil)
82
+ return unless @tracking && @frame
83
+
84
+ name = normalize_identifier(table)
85
+ return if name.empty? || internal_table?(name)
86
+
87
+ normalized = {}
88
+ if partitions.is_a?(Hash)
89
+ partitions.each do |col, val|
90
+ key = normalize_identifier(col)
91
+ next if key.empty?
92
+
93
+ values = val.is_a?(Array) ? val : [val]
94
+ normalized[key] = values.compact.map(&:to_s).uniq.sort
95
+ end
96
+ end
97
+
98
+ merge_table_read(@frame, name, normalized)
99
+ end
100
+
101
+ # Parse a SQL query and record any referenced user tables and sound
102
+ # outer-WHERE partition constraints.
103
+ def record_sql(sql, binds = nil)
104
+ return unless @tracking && @frame
105
+
106
+ query = strip_leading_comments(sql.to_s)
107
+ return unless query.match?(/\A(?:SELECT|WITH)\b/i)
108
+
109
+ tables = extract_tables(query)
110
+ return if tables.empty?
111
+
112
+ where_partitions = extract_outer_partitions(query, tables, binds)
113
+ tables.each do |table|
114
+ merge_table_read(@frame, table, where_partitions[table] || {})
115
+ end
116
+ end
117
+
118
+ def serialize(reads)
119
+ return "" unless reads.is_a?(Hash)
120
+
121
+ JSON.generate(reads)
122
+ end
123
+
124
+ # Check whether a list of structured deltas (or nil wildcard) affects a
125
+ # tracked reads snapshot. Returns true conservatively when deltas or reads
126
+ # are unknown.
127
+ def affects?(deltas, reads)
128
+ return true if deltas.nil? || reads.nil?
129
+ return false if deltas.empty?
130
+
131
+ models = Array(reads["models"])
132
+ tables = Array(reads["tables"])
133
+ return false if models.empty? && tables.empty?
134
+
135
+ partitions = reads["partitions"].is_a?(Hash) ? reads["partitions"] : {}
136
+ deltas.any? do |delta|
137
+ type = (delta["type"] || delta[:type]).to_s
138
+ table = (delta["table"] || delta[:table]).to_s
139
+ matched_key =
140
+ if !type.empty? && models.include?(type)
141
+ type
142
+ elsif !table.empty? && tables.include?(table)
143
+ table
144
+ end
145
+ next false unless matched_key
146
+
147
+ constraints = partitions[matched_key] || (!table.empty? ? partitions[table] : nil)
148
+ next true unless constraints.is_a?(Hash) && !constraints.empty?
149
+
150
+ delta_matches_partitions?(delta, constraints)
151
+ end
152
+ end
153
+
154
+ private
155
+
156
+ def delta_matches_partitions?(delta, constraints)
157
+ attrs = delta["attrs"] || delta[:attrs]
158
+ op = (delta["op"] || delta[:op]).to_s
159
+ changed_cols = Array(delta["changed_columns"] || delta[:changed_columns]).map(&:to_s)
160
+ return true unless attrs.is_a?(Hash)
161
+
162
+ constraints.each do |col, allowed|
163
+ next if op == "update" && changed_cols.include?(col)
164
+ next unless attrs.key?(col) || attrs.key?(col.to_sym)
165
+
166
+ val = attrs.key?(col) ? attrs[col] : attrs[col.to_sym]
167
+ next if val.nil?
168
+ return false unless Array(allowed).include?(val.to_s)
169
+ end
170
+ true
171
+ end
172
+
173
+ def extract_binds(payload)
174
+ raw = payload[:type_casted_binds]
175
+ raw = raw.call if raw.respond_to?(:call)
176
+ return raw if raw.is_a?(Array)
177
+
178
+ binds = payload[:binds]
179
+ return nil unless binds.is_a?(Array)
180
+
181
+ binds.map { |bind| bind.respond_to?(:value_for_database) ? bind.value_for_database : bind }
182
+ end
183
+
184
+ def strip_leading_comments(sql)
185
+ text = sql.lstrip
186
+ loop do
187
+ if text.start_with?("--")
188
+ nl = text.index("\n")
189
+ text = nl ? text[(nl + 1)..].lstrip : ""
190
+ elsif text.start_with?("/*")
191
+ stop = text.index("*/")
192
+ text = stop ? text[(stop + 2)..].lstrip : ""
193
+ else
194
+ break
195
+ end
196
+ end
197
+ text
198
+ end
199
+
200
+ def normalize_identifier(raw)
201
+ str = raw.to_s.strip
202
+ str = str.split(".").last.to_s if str.include?(".")
203
+ str.delete('"`[]').downcase
204
+ end
205
+
206
+ def internal_table?(name)
207
+ INTERNAL_TABLES.include?(name) || name.start_with?("sqlite_")
208
+ end
209
+
210
+ def extract_tables(sql)
211
+ cleaned = mask_string_literals(sql)
212
+ found = []
213
+ cleaned.scan(/\b(?:FROM|JOIN)\s+([`"\[]?[A-Za-z_][A-Za-z0-9_]*[`"\]]?(?:\.[`"\[]?[A-Za-z_][A-Za-z0-9_]*[`"\]]?)?)/i) do |match|
214
+ name = normalize_identifier(match[0])
215
+ next if name.empty? || internal_table?(name) || SQL_KEYWORDS.include?(name)
216
+
217
+ found << name unless found.include?(name)
218
+ end
219
+ found
220
+ end
221
+
222
+ def extract_outer_partitions(sql, tables, binds)
223
+ result = {}
224
+ where_clause, where_offset = extract_outer_where(sql)
225
+ return result unless where_clause
226
+
227
+ # A top-level OR in the outer WHERE means any single branch can match
228
+ # rows outside the other branch's partition predicate.
229
+ return result if contains_top_level_keyword?(where_clause, "OR")
230
+
231
+ bind_index = count_placeholders(sql[0...where_offset])
232
+ partition_columns = known_partition_columns
233
+ primary_table = tables.length == 1 ? tables[0] : nil
234
+ aliases = extract_outer_aliases(sql)
235
+
236
+ split_top_level_and(where_clause).each do |part|
237
+ clause = part.strip
238
+ placeholders_in_clause = count_placeholders(clause)
239
+ current_bind = bind_index
240
+ bind_index += placeholders_in_clause
241
+
242
+ # Strip balanced outer parens around a single conjunct like (mailbox_id = 'support').
243
+ clause = unwrap_outer_parens(clause)
244
+ next if contains_top_level_keyword?(clause, "OR")
245
+
246
+ if (m = clause.match(/\A(?:([`"\[]?[A-Za-z_]\w*[`"\]]?)\.)?([`"\[]?[A-Za-z_]\w*[`"\]]?)\s*=\s*(.+)\z/i))
247
+ table = resolve_table(m[1], primary_table, aliases, tables)
248
+ col = normalize_identifier(m[2])
249
+ next unless table && partition_column?(col, partition_columns)
250
+
251
+ val = resolve_value(m[3].strip, binds, current_bind)
252
+ next if val.nil?
253
+
254
+ add_partition_value(result, table, col, val)
255
+ elsif (m = clause.match(/\A(?:([`"\[]?[A-Za-z_]\w*[`"\]]?)\.)?([`"\[]?[A-Za-z_]\w*[`"\]]?)\s+IN\s*\((.+)\)\z/i))
256
+ table = resolve_table(m[1], primary_table, aliases, tables)
257
+ col = normalize_identifier(m[2])
258
+ next unless table && partition_column?(col, partition_columns)
259
+
260
+ values = resolve_in_values(m[3], binds, current_bind)
261
+ next unless values && !values.empty?
262
+
263
+ values.each { |v| add_partition_value(result, table, col, v) }
264
+ end
265
+ end
266
+
267
+ result
268
+ end
269
+
270
+ def known_partition_columns
271
+ cols = {}
272
+ InstantRecord.syncable_models.each do |model|
273
+ window = model.respond_to?(:instant_record_sync_window) ? model.instant_record_sync_window : nil
274
+ cols[window.partition_by.to_s.downcase] = true if window && window.partition_by
275
+ scope_col = model.respond_to?(:instant_record_sync_scope) ? model.instant_record_sync_scope : nil
276
+ cols[scope_col.to_s.downcase] = true if scope_col
277
+ end
278
+ cols
279
+ end
280
+
281
+ def partition_column?(col, known)
282
+ col == "id" || col.end_with?("_id") || known.key?(col)
283
+ end
284
+
285
+ def resolve_table(qualifier, primary_table, aliases, tables)
286
+ if qualifier && !qualifier.empty?
287
+ q = normalize_identifier(qualifier)
288
+ return aliases[q] if aliases.key?(q)
289
+ return q if tables.include?(q)
290
+ return nil
291
+ end
292
+ primary_table
293
+ end
294
+
295
+ def extract_outer_aliases(sql)
296
+ aliases = {}
297
+ outer = top_level_text(sql)
298
+ outer.scan(/\b(?:FROM|JOIN)\s+([`"\[]?[A-Za-z_]\w*[`"\]]?(?:\.[`"\[]?[A-Za-z_]\w*[`"\]]?)?)(?:\s+(?:AS\s+)?([`"\[]?[A-Za-z_]\w*[`"\]]?))?/i) do |tbl, als|
299
+ table_name = normalize_identifier(tbl)
300
+ next if table_name.empty? || internal_table?(table_name)
301
+
302
+ aliases[table_name] = table_name
303
+ if als && !als.empty?
304
+ alias_name = normalize_identifier(als)
305
+ aliases[alias_name] = table_name unless SQL_KEYWORDS.include?(alias_name)
306
+ end
307
+ end
308
+ aliases
309
+ end
310
+
311
+ def add_partition_value(result, table, col, val)
312
+ entry = (result[table] ||= {})
313
+ list = (entry[col] ||= [])
314
+ str = val.to_s
315
+ list << str unless list.include?(str)
316
+ end
317
+
318
+ def resolve_value(expr, binds, bind_index)
319
+ if expr == "?"
320
+ return nil unless binds.is_a?(Array) && bind_index < binds.length
321
+
322
+ val = binds[bind_index]
323
+ val.nil? ? nil : val.to_s
324
+ elsif (m = expr.match(/\A\$(\d+)\z/))
325
+ idx = m[1].to_i - 1
326
+ return nil unless binds.is_a?(Array) && idx >= 0 && idx < binds.length
327
+
328
+ val = binds[idx]
329
+ val.nil? ? nil : val.to_s
330
+ elsif expr.start_with?("'") && expr.end_with?("'") && expr.length >= 2
331
+ inner = expr[1..-2]
332
+ # Ensure no unescaped quote inside (i.e. not `'a' OR 'b'`).
333
+ return nil if inner.gsub("''", "").include?("'")
334
+
335
+ inner.gsub("''", "'")
336
+ elsif expr.match?(/\A-?\d+(?:\.\d+)?\z/)
337
+ expr
338
+ else
339
+ nil
340
+ end
341
+ end
342
+
343
+ def resolve_in_values(list_sql, binds, start_bind)
344
+ items = split_top_level_commas(list_sql)
345
+ return nil if items.empty?
346
+
347
+ values = []
348
+ idx = start_bind
349
+ items.each do |item|
350
+ token = item.strip
351
+ val = resolve_value(token, binds, idx)
352
+ idx += count_placeholders(token)
353
+ return nil if val.nil?
354
+
355
+ values << val
356
+ end
357
+ values
358
+ end
359
+
360
+ def extract_outer_where(sql)
361
+ where_pos = find_top_level_keyword(sql, "WHERE")
362
+ return [nil, 0] unless where_pos
363
+
364
+ start = where_pos + 5
365
+ rest = sql[start..]
366
+ stop = rest.length
367
+ %w[GROUP ORDER LIMIT HAVING UNION INTERSECT EXCEPT].each do |kw|
368
+ pos = find_top_level_keyword(rest, kw)
369
+ stop = pos if pos && pos < stop
370
+ end
371
+ semi = find_top_level_char(rest, ";")
372
+ stop = semi if semi && semi < stop
373
+ [rest[0...stop].strip, start]
374
+ end
375
+
376
+ def top_level_text(sql)
377
+ out = +""
378
+ depth = 0
379
+ in_single = false
380
+ i = 0
381
+ len = sql.length
382
+ while i < len
383
+ ch = sql[i]
384
+ if in_single
385
+ if ch == "'"
386
+ if i + 1 < len && sql[i + 1] == "'"
387
+ i += 2
388
+ next
389
+ end
390
+ in_single = false
391
+ end
392
+ out << " "
393
+ elsif ch == "'"
394
+ in_single = true
395
+ out << " "
396
+ elsif ch == "("
397
+ depth += 1
398
+ out << " "
399
+ elsif ch == ")"
400
+ depth -= 1 if depth > 0
401
+ out << " "
402
+ else
403
+ out << (depth == 0 ? ch : " ")
404
+ end
405
+ i += 1
406
+ end
407
+ out
408
+ end
409
+
410
+ def mask_string_literals(sql)
411
+ out = +""
412
+ in_single = false
413
+ i = 0
414
+ len = sql.length
415
+ while i < len
416
+ ch = sql[i]
417
+ if in_single
418
+ if ch == "'"
419
+ if i + 1 < len && sql[i + 1] == "'"
420
+ out << " "
421
+ i += 2
422
+ next
423
+ end
424
+ in_single = false
425
+ end
426
+ out << " "
427
+ elsif ch == "'"
428
+ in_single = true
429
+ out << " "
430
+ else
431
+ out << ch
432
+ end
433
+ i += 1
434
+ end
435
+ out
436
+ end
437
+
438
+ def count_placeholders(sql)
439
+ count = 0
440
+ in_single = false
441
+ i = 0
442
+ len = sql.length
443
+ while i < len
444
+ ch = sql[i]
445
+ if in_single
446
+ if ch == "'"
447
+ if i + 1 < len && sql[i + 1] == "'"
448
+ i += 2
449
+ next
450
+ end
451
+ in_single = false
452
+ end
453
+ elsif ch == "'"
454
+ in_single = true
455
+ elsif ch == "?"
456
+ count += 1
457
+ end
458
+ i += 1
459
+ end
460
+ count
461
+ end
462
+
463
+ def find_top_level_keyword(sql, keyword)
464
+ masked = top_level_text(sql)
465
+ m = masked.match(/\b#{keyword}\b/i)
466
+ m ? m.begin(0) : nil
467
+ end
468
+
469
+ def contains_top_level_keyword?(sql, keyword)
470
+ !find_top_level_keyword(sql, keyword).nil?
471
+ end
472
+
473
+ def find_top_level_char(sql, target)
474
+ masked = top_level_text(sql)
475
+ masked.index(target)
476
+ end
477
+
478
+ def split_top_level_and(clause)
479
+ masked = top_level_text(clause)
480
+ parts = []
481
+ cursor = 0
482
+ masked.scan(/\bAND\b/i) do
483
+ pos = Regexp.last_match.begin(0)
484
+ parts << clause[cursor...pos]
485
+ cursor = Regexp.last_match.end(0)
486
+ end
487
+ parts << clause[cursor..]
488
+ parts
489
+ end
490
+
491
+ def split_top_level_commas(text)
492
+ masked = top_level_text(text)
493
+ parts = []
494
+ cursor = 0
495
+ i = 0
496
+ len = masked.length
497
+ while i < len
498
+ if masked[i] == ","
499
+ parts << text[cursor...i]
500
+ cursor = i + 1
501
+ end
502
+ i += 1
503
+ end
504
+ parts << text[cursor..]
505
+ parts
506
+ end
507
+
508
+ def unwrap_outer_parens(clause)
509
+ text = clause.strip
510
+ while text.start_with?("(") && text.end_with?(")")
511
+ # Verify the opening paren matches the final closing paren.
512
+ depth = 0
513
+ in_single = false
514
+ closes_early = false
515
+ i = 0
516
+ len = text.length
517
+ while i < len
518
+ ch = text[i]
519
+ if in_single
520
+ if ch == "'"
521
+ if i + 1 < len && text[i + 1] == "'"
522
+ i += 2
523
+ next
524
+ end
525
+ in_single = false
526
+ end
527
+ elsif ch == "'"
528
+ in_single = true
529
+ elsif ch == "("
530
+ depth += 1
531
+ elsif ch == ")"
532
+ depth -= 1
533
+ if depth == 0 && i < len - 1
534
+ closes_early = true
535
+ break
536
+ end
537
+ end
538
+ i += 1
539
+ end
540
+ break if closes_early
541
+
542
+ text = text[1..-2].strip
543
+ end
544
+ text
545
+ end
546
+
547
+ def merge_table_read(frame, table, new_partitions)
548
+ if !frame.key?(table)
549
+ frame[table] = new_partitions
550
+ return
551
+ end
552
+
553
+ existing = frame[table]
554
+ return if existing.empty?
555
+
556
+ if new_partitions.empty?
557
+ frame[table] = {}
558
+ return
559
+ end
560
+
561
+ intersected = {}
562
+ existing.each do |col, vals|
563
+ next unless new_partitions.key?(col)
564
+
565
+ merged = (vals + new_partitions[col]).uniq.sort
566
+ intersected[col] = merged
567
+ end
568
+ frame[table] = intersected
569
+ end
570
+
571
+ def finalize(frame)
572
+ tables = frame.keys.sort
573
+ table_to_models = {}
574
+ InstantRecord.syncable_models.each do |model|
575
+ tbl = model.table_name.to_s.downcase
576
+ next if tbl.empty?
577
+
578
+ list = (table_to_models[tbl] ||= [])
579
+ list << model.name unless list.include?(model.name)
580
+ end
581
+
582
+ models = []
583
+ partitions = {}
584
+
585
+ tables.each do |table|
586
+ matched = table_to_models[table] || []
587
+ matched.each { |name| models << name unless models.include?(name) }
588
+
589
+ constraints = frame[table]
590
+ next if constraints.nil? || constraints.empty?
591
+
592
+ sorted_constraints = {}
593
+ constraints.keys.sort.each { |col| sorted_constraints[col] = constraints[col].sort }
594
+
595
+ if matched.empty?
596
+ partitions[table] = sorted_constraints
597
+ else
598
+ matched.each { |name| partitions[name] = sorted_constraints }
599
+ end
600
+ end
601
+
602
+ {
603
+ "tables" => tables,
604
+ "models" => models.sort,
605
+ "partitions" => partitions
606
+ }
607
+ end
608
+ end
609
+ end
610
+ end
@@ -0,0 +1,33 @@
1
+ module InstantRecord
2
+ # Rails routing DSL extension for declaring local-first islands directly in
3
+ # config/routes.rb (and draw'n config/routes/*.rb files).
4
+ #
5
+ # On the Rails server, `local_first` yields transparently so every route draws
6
+ # and generates URL helpers identically. At compile time, the Prism route
7
+ # analyzer reads these blocks statically to stage only reachable controllers,
8
+ # models, views, helpers, and migrations.
9
+ #
10
+ # Rails.application.routes.draw do
11
+ # local_first do
12
+ # namespace :todo do
13
+ # resources :issues, only: [:create, :update, :destroy]
14
+ # root "issues#index"
15
+ # end
16
+ # end
17
+ # end
18
+ #
19
+ # Optional island name and explicit overrides for dynamic Ruby patterns:
20
+ #
21
+ # local_first(:inbox, include: { models: ["PriorityMail"], partials: ["shared/row"] }) do
22
+ # get "email", to: "email/mailboxes#index"
23
+ # end
24
+ module Routing
25
+ def local_first(_name = nil, include: nil, server_routes: nil, &block)
26
+ yield if block
27
+ end
28
+ end
29
+ end
30
+
31
+ if defined?(ActionDispatch::Routing::Mapper) && !ActionDispatch::Routing::Mapper.include?(InstantRecord::Routing)
32
+ ActionDispatch::Routing::Mapper.include(InstantRecord::Routing)
33
+ end
@@ -17,5 +17,9 @@ module InstantRecord
17
17
  def browser_only(&block)
18
18
  class_eval(&block) if InstantRecord.browser?
19
19
  end
20
+
21
+ # The same blocks by the name that fits a phone: the compiled app is the
22
+ # client there, and no browser is in sight.
23
+ alias_method :client_only, :browser_only
20
24
  end
21
25
  end