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,91 @@
1
+ // Declarative partition context resolution for the compiled browser runtime.
2
+ // Apps declare partitioned routes via VITE_SYNC_PARTITIONS (JSON array of rules),
3
+ // keeping worker.js and main.js free of app-specific URL or endpoint logic.
4
+ //
5
+ // Each rule may specify:
6
+ // path pathname prefix/match (e.g. "/email")
7
+ // partitionParam query param carrying the partition value (e.g. "inbox")
8
+ // partitionDefault default partition value when omitted
9
+ // partitionKey optional column/name prefix for X-Instant-Record-Partition (e.g. "mailbox_id")
10
+ // scopeParam optional secondary query param (e.g. "member")
11
+ // scopeDefault optional default for scopeParam
12
+ // scopeHeader optional header name for scopeParam (e.g. "X-Instant-Record-Member")
13
+ // valid optional regex string validating extracted values
14
+ // lookupParams optional query params whose values should be pre-fetched via /records?id=
15
+ // preloadBefore optional { idParam, atParam, type, limit } for deep-link page preloading
16
+ // shellPath optional path for prebuilt SQLite shell endpoint
17
+
18
+ export function parseRules(raw) {
19
+ if (Array.isArray(raw)) return raw;
20
+ if (typeof raw !== "string" || !raw.trim()) return [];
21
+ try {
22
+ const parsed = JSON.parse(raw);
23
+ return Array.isArray(parsed) ? parsed : [];
24
+ } catch {
25
+ return [];
26
+ }
27
+ }
28
+
29
+ export function resolveSyncContext(path, rules = parseRules(import.meta.env?.VITE_SYNC_PARTITIONS)) {
30
+ if (!rules.length) return null;
31
+ const url = new URL(path || "/", "https://sync-context.invalid");
32
+ const pathname = url.pathname.replace(/\/$/, "") || "/";
33
+ const rule = rules.find(entry => (entry.path || "").replace(/\/$/, "") === pathname);
34
+ if (!rule) return null;
35
+
36
+ const partitionValue = url.searchParams.get(rule.partitionParam) || rule.partitionDefault || "";
37
+ const scopeValue = rule.scopeParam ? (url.searchParams.get(rule.scopeParam) || rule.scopeDefault || "") : "";
38
+ const validator = rule.valid ? new RegExp(rule.valid) : null;
39
+ const checked = rule.scopeParam ? [scopeValue, partitionValue] : [partitionValue];
40
+ const valid = checked.every(value => value && (!validator || validator.test(value)));
41
+
42
+ if (!valid) {
43
+ return {
44
+ valid: false,
45
+ storageKey: "invalid",
46
+ partition: "",
47
+ partitionValue: "",
48
+ scopeValue: "",
49
+ headers: {},
50
+ lookupIds: [],
51
+ preloadBefore: null,
52
+ shellPath: null,
53
+ };
54
+ }
55
+
56
+ const partition = rule.partitionKey ? `${rule.partitionKey}:${partitionValue}` : partitionValue;
57
+ const storageKey = scopeValue ? `${scopeValue}/${partitionValue}` : partitionValue;
58
+ const headers = { "X-Instant-Record-Partition": partition };
59
+ if (rule.scopeHeader && scopeValue) headers[rule.scopeHeader] = scopeValue;
60
+
61
+ const lookupIds = [...new Set(
62
+ (Array.isArray(rule.lookupParams) ? rule.lookupParams : [])
63
+ .map(name => url.searchParams.get(name))
64
+ .filter(Boolean)
65
+ )];
66
+
67
+ let preloadBefore = null;
68
+ if (rule.preloadBefore) {
69
+ const id = url.searchParams.get(rule.preloadBefore.idParam);
70
+ const at = url.searchParams.get(rule.preloadBefore.atParam);
71
+ if (id && at) {
72
+ preloadBefore = {
73
+ type: rule.preloadBefore.type,
74
+ before: { id, created_at: at },
75
+ limit: rule.preloadBefore.limit || 50,
76
+ };
77
+ }
78
+ }
79
+
80
+ return {
81
+ valid: true,
82
+ storageKey,
83
+ partition,
84
+ partitionValue,
85
+ scopeValue,
86
+ headers,
87
+ lookupIds,
88
+ preloadBefore,
89
+ shellPath: rule.shellPath || null,
90
+ };
91
+ }
@@ -0,0 +1,104 @@
1
+ // Non-livelocking bounded outbox drain coordinator for the dedicated worker.
2
+ //
3
+ // Sends one bounded batch from syncPlan() outside IndexedDB locks, then merges
4
+ // the completed response into whatever is now in SQLite by mutation_id — never
5
+ // discarding completed acks when newer local edits or peer-tab writes landed
6
+ // while the network request was in flight.
7
+ export async function runDrain({
8
+ withSnapshot,
9
+ fetchReply,
10
+ getHost,
11
+ syncEndpoint,
12
+ initial = false,
13
+ early = null,
14
+ report = () => {},
15
+ setCursor = () => {},
16
+ onBootstrapFill = () => {},
17
+ onRecordsChanged = () => {},
18
+ onSyncNotices = () => {},
19
+ scheduleRetry,
20
+ scheduleHeld = () => {},
21
+ onIdle = () => {},
22
+ retryState,
23
+ }) {
24
+ const plan = await withSnapshot("readonly", () => getHost().syncPlan());
25
+ if (!plan.push && !plan.bootstrap) {
26
+ retryState.delayMs = retryState.baseMs;
27
+ const nextReleaseMs = plan.next_release_ms ?? null;
28
+ if (nextReleaseMs != null) scheduleHeld(Math.max(0, nextReleaseMs));
29
+ else onIdle();
30
+ return { changed: false, notified: false, pending: 0, nextReleaseMs };
31
+ }
32
+ const extra = plan.headers || {};
33
+ const push = plan.push ? await fetchReply("POST", "/mutations", plan.push, syncEndpoint, extra) : null;
34
+ const snapshot = plan.bootstrap ? (!plan.push && early?.status === 200 ? early : await fetchReply("GET", "/bootstrap", "", syncEndpoint, extra)) : null;
35
+
36
+ let bootstrapFill = null;
37
+ if (snapshot?.status === 200) {
38
+ try {
39
+ const parsed = JSON.parse(snapshot.text);
40
+ if (Array.isArray(parsed.fill) && parsed.fill.length > 0) bootstrapFill = parsed.fill[0];
41
+ } catch { /* ignore malformed JSON; Ruby handles it below */ }
42
+ }
43
+
44
+ const result = await withSnapshot("readwrite", (save, put) => {
45
+ const host = getHost();
46
+ const preparedPush = push
47
+ ? { status: push.status, body: push.text, mutation_ids: plan.mutation_ids || [] }
48
+ : null;
49
+ const preparedBootstrap = snapshot
50
+ ? { status: snapshot.status, body: snapshot.text }
51
+ : null;
52
+
53
+ const applied = host.applySync(syncEndpoint, {
54
+ push: preparedPush,
55
+ bootstrap: preparedBootstrap,
56
+ });
57
+ if (applied.fault || (applied.exit !== undefined && applied.exit !== 0)) {
58
+ scheduleRetry(retryState.delayMs);
59
+ retryState.delayMs = Math.min(retryState.delayMs * 2, retryState.capMs);
60
+ return applied;
61
+ }
62
+ let needsBootstrap = false;
63
+ if (plan.bootstrap) {
64
+ const state = host.syncState();
65
+ if (state.fault || (state.exit !== undefined && state.exit !== 0)) {
66
+ scheduleRetry(retryState.delayMs);
67
+ retryState.delayMs = Math.min(retryState.delayMs * 2, retryState.capMs);
68
+ return { ...applied, exit: state.exit, errors: state.errors, fault: state.fault };
69
+ }
70
+ needsBootstrap = !state.bootstrapped;
71
+ }
72
+ if (push || snapshot) report({ kind: "sync-pass", path: `${applied.pending} pending` });
73
+ // After a bootstrap the next poll reads the cursor and the identity afresh.
74
+ setCursor(plan.bootstrap ? null : applied.cursor);
75
+ const syncNotices = applied.notices?.length && typeof host.notices === "function"
76
+ ? host.notices({ action: "list" }).notices
77
+ : null;
78
+ if (bootstrapFill) onBootstrapFill(bootstrapFill, put);
79
+ if (applied.changed || applied.notified || bootstrapFill) {
80
+ save();
81
+ }
82
+
83
+ if (applied.pending > 0 || applied.pending < 0 || needsBootstrap) {
84
+ if (!applied.failed && applied.pending >= 0 && (applied.progressed || (!push && !snapshot))) {
85
+ retryState.delayMs = retryState.baseMs;
86
+ scheduleRetry(0);
87
+ } else {
88
+ scheduleRetry(retryState.delayMs);
89
+ retryState.delayMs = Math.min(retryState.delayMs * 2, retryState.capMs);
90
+ }
91
+ } else if (applied.nextReleaseMs != null) {
92
+ retryState.delayMs = retryState.baseMs;
93
+ scheduleHeld(Math.max(0, applied.nextReleaseMs));
94
+ } else {
95
+ retryState.delayMs = retryState.baseMs;
96
+ onIdle();
97
+ }
98
+ return { ...applied, syncNotices };
99
+ });
100
+
101
+ if (result.syncNotices) onSyncNotices(result.syncNotices);
102
+ if (!initial && result.notified && !result.fault) onRecordsChanged(result.changes);
103
+ return result;
104
+ }
@@ -0,0 +1,9 @@
1
+ // Decides how the worker schedules its next sync pass from local outbox state:
2
+ // matured pending writes or an unbootstrapped DB drain immediately (or with
3
+ // retry backoff), held writes wait cleanly until their earliest release_at
4
+ // without blocking inbound polls, and an empty outbox clears any held timer.
5
+ export function nextSyncAction({ pending = 0, bootstrapped = true, nextReleaseMs = null } = {}, immediateDelay = 0) {
6
+ if (pending > 0 || !bootstrapped) return { kind: "immediate", delay: immediateDelay };
7
+ if (nextReleaseMs != null) return { kind: "held", delay: Math.max(0, nextReleaseMs) };
8
+ return { kind: "idle" };
9
+ }
@@ -0,0 +1,275 @@
1
+ // Minimal pure-JS WASI preview1 implementation mirroring the subset of
2
+ // @bjorn3/browser_wasi_shim used by AppHost. Used as a Node fallback when
3
+ // compiled/web/node_modules is not installed (e.g. unit tests or standalone
4
+ // replay of minimal test WASM modules). Full compiled Rails apps should still
5
+ // use @bjorn3/browser_wasi_shim via WEB_NODE_MODULES.
6
+
7
+ const encoder = new TextEncoder();
8
+ const decoder = new TextDecoder();
9
+
10
+ const ESUCCESS = 0;
11
+ const EBADF = 8;
12
+ const EINVAL = 28;
13
+ const ENOENT = 44;
14
+ const ENOTDIR = 54;
15
+
16
+ export class File {
17
+ constructor(data = new Uint8Array()) {
18
+ this.data = data instanceof Uint8Array ? data : new Uint8Array(data);
19
+ }
20
+
21
+ path_open(oflags = 0) {
22
+ if (oflags & 8) this.data = new Uint8Array(); // OFLAGS_TRUNC
23
+ return { ret: ESUCCESS, fd_obj: new OpenFile(this) };
24
+ }
25
+ }
26
+
27
+ export class OpenFile {
28
+ constructor(file) {
29
+ this.file = file;
30
+ this.file_pos = 0;
31
+ }
32
+
33
+ fd_read(iovs, view) {
34
+ let total = 0;
35
+ for (const { buf, buf_len } of iovs) {
36
+ const avail = Math.max(0, this.file.data.length - this.file_pos);
37
+ const n = Math.min(buf_len, avail);
38
+ if (n > 0) {
39
+ new Uint8Array(view.buffer, buf, n).set(this.file.data.subarray(this.file_pos, this.file_pos + n));
40
+ this.file_pos += n;
41
+ total += n;
42
+ }
43
+ if (n < buf_len) break;
44
+ }
45
+ return { ret: ESUCCESS, nread: total };
46
+ }
47
+
48
+ fd_write(iovs, view) {
49
+ let total = 0;
50
+ const chunks = [];
51
+ for (const { buf, buf_len } of iovs) {
52
+ chunks.push(new Uint8Array(view.buffer, buf, buf_len).slice());
53
+ total += buf_len;
54
+ }
55
+ const end = this.file_pos + total;
56
+ const next = new Uint8Array(Math.max(this.file.data.length, end));
57
+ next.set(this.file.data);
58
+ let cursor = this.file_pos;
59
+ for (const chunk of chunks) {
60
+ next.set(chunk, cursor);
61
+ cursor += chunk.length;
62
+ }
63
+ this.file.data = next;
64
+ this.file_pos = cursor;
65
+ return { ret: ESUCCESS, nwritten: total };
66
+ }
67
+ }
68
+
69
+ export class ConsoleStdout {
70
+ constructor(writeFn) {
71
+ this.writeFn = writeFn;
72
+ }
73
+
74
+ static lineBuffered(onLine) {
75
+ let buffer = "";
76
+ return new ConsoleStdout((bytes) => {
77
+ buffer += decoder.decode(bytes, { stream: true });
78
+ const lines = buffer.split("\n");
79
+ buffer = lines.pop() ?? "";
80
+ for (const line of lines) onLine(line);
81
+ });
82
+ }
83
+
84
+ fd_write(iovs, view) {
85
+ let total = 0;
86
+ for (const { buf, buf_len } of iovs) {
87
+ this.writeFn(new Uint8Array(view.buffer, buf, buf_len).slice());
88
+ total += buf_len;
89
+ }
90
+ return { ret: ESUCCESS, nwritten: total };
91
+ }
92
+ }
93
+
94
+ export class Directory {
95
+ constructor(contents = new Map()) {
96
+ this.contents = contents instanceof Map ? contents : new Map(Object.entries(contents));
97
+ }
98
+ }
99
+
100
+ export class PreopenDirectory {
101
+ constructor(prestat_name, contents) {
102
+ this.prestat_name = prestat_name;
103
+ this.dir = contents instanceof Directory ? contents : new Directory(contents);
104
+ }
105
+ }
106
+
107
+ export class WASI {
108
+ constructor(args = [], env = [], fds = []) {
109
+ this.args = args.map((a) => encoder.encode(String(a) + "\0"));
110
+ this.env = env.map((e) => encoder.encode(String(e) + "\0"));
111
+ this.fds = fds.slice();
112
+ this.inst = null;
113
+ this.wasiImport = this.buildImports();
114
+ }
115
+
116
+ initialize(instance) {
117
+ this.inst = instance;
118
+ if (typeof instance.exports._initialize === "function") {
119
+ instance.exports._initialize();
120
+ }
121
+ }
122
+
123
+ memoryView() {
124
+ return new DataView(this.inst.exports.memory.buffer);
125
+ }
126
+
127
+ readIovs(iovsPtr, iovsLen) {
128
+ const view = this.memoryView();
129
+ const out = [];
130
+ for (let i = 0; i < iovsLen; i++) {
131
+ const base = iovsPtr + i * 8;
132
+ out.push({ buf: view.getUint32(base, true), buf_len: view.getUint32(base + 4, true) });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ resolvePath(dirFd, relPath) {
138
+ const entry = this.fds[dirFd];
139
+ if (!entry || !entry.dir) return { err: EBADF };
140
+ const parts = relPath.split("/").filter((p) => p && p !== ".");
141
+ if (parts.length === 0) return { parent: null, name: "", target: entry.dir };
142
+ let current = entry.dir;
143
+ for (let i = 0; i < parts.length - 1; i++) {
144
+ const next = current.contents.get(parts[i]);
145
+ if (!(next instanceof Directory)) return { err: next ? ENOTDIR : ENOENT };
146
+ current = next;
147
+ }
148
+ const name = parts[parts.length - 1];
149
+ return { parent: current, name, target: current.contents.get(name) };
150
+ }
151
+
152
+ buildImports() {
153
+ return {
154
+ args_sizes_get: (argcPtr, argvBufSizePtr) => {
155
+ const view = this.memoryView();
156
+ view.setUint32(argcPtr, this.args.length, true);
157
+ view.setUint32(argvBufSizePtr, this.args.reduce((s, a) => s + a.length, 0), true);
158
+ return ESUCCESS;
159
+ },
160
+ args_get: (argvPtr, argvBufPtr) => {
161
+ const view = this.memoryView();
162
+ const mem = new Uint8Array(view.buffer);
163
+ let buf = argvBufPtr;
164
+ for (let i = 0; i < this.args.length; i++) {
165
+ view.setUint32(argvPtr + i * 4, buf, true);
166
+ mem.set(this.args[i], buf);
167
+ buf += this.args[i].length;
168
+ }
169
+ return ESUCCESS;
170
+ },
171
+ environ_sizes_get: (countPtr, bufSizePtr) => {
172
+ const view = this.memoryView();
173
+ view.setUint32(countPtr, this.env.length, true);
174
+ view.setUint32(bufSizePtr, this.env.reduce((s, e) => s + e.length, 0), true);
175
+ return ESUCCESS;
176
+ },
177
+ environ_get: (envPtr, envBufPtr) => {
178
+ const view = this.memoryView();
179
+ const mem = new Uint8Array(view.buffer);
180
+ let buf = envBufPtr;
181
+ for (let i = 0; i < this.env.length; i++) {
182
+ view.setUint32(envPtr + i * 4, buf, true);
183
+ mem.set(this.env[i], buf);
184
+ buf += this.env[i].length;
185
+ }
186
+ return ESUCCESS;
187
+ },
188
+ fd_prestat_get: (fd, bufPtr) => {
189
+ const entry = this.fds[fd];
190
+ if (!(entry instanceof PreopenDirectory)) return EBADF;
191
+ const view = this.memoryView();
192
+ const nameBytes = encoder.encode(entry.prestat_name);
193
+ view.setUint8(bufPtr, 0); // PREOPENTYPE_DIR
194
+ view.setUint32(bufPtr + 4, nameBytes.length, true);
195
+ return ESUCCESS;
196
+ },
197
+ fd_prestat_dir_name: (fd, pathPtr, pathLen) => {
198
+ const entry = this.fds[fd];
199
+ if (!(entry instanceof PreopenDirectory)) return EBADF;
200
+ const nameBytes = encoder.encode(entry.prestat_name);
201
+ new Uint8Array(this.memoryView().buffer, pathPtr, Math.min(pathLen, nameBytes.length)).set(
202
+ nameBytes.subarray(0, pathLen),
203
+ );
204
+ return ESUCCESS;
205
+ },
206
+ path_open: (dirFd, _dirflags, pathPtr, pathLen, oflags, rightsBase, _rightsInheriting, fdFlags, openedFdPtr) => {
207
+ const view = this.memoryView();
208
+ const relPath = decoder.decode(new Uint8Array(view.buffer, pathPtr, pathLen));
209
+ const resolved = this.resolvePath(dirFd, relPath);
210
+ if (resolved.err) return resolved.err;
211
+ let file = resolved.target;
212
+ if (!file && (oflags & 1)) {
213
+ file = new File(new Uint8Array());
214
+ resolved.parent.contents.set(resolved.name, file);
215
+ }
216
+ if (!file || typeof file.path_open !== "function") return ENOENT;
217
+ const { ret, fd_obj } = file.path_open(oflags, rightsBase, fdFlags);
218
+ if (ret !== ESUCCESS) return ret;
219
+ let slot = this.fds.indexOf(null);
220
+ if (slot < 0) {
221
+ slot = this.fds.length;
222
+ this.fds.push(fd_obj);
223
+ } else {
224
+ this.fds[slot] = fd_obj;
225
+ }
226
+ view.setUint32(openedFdPtr, slot, true);
227
+ return ESUCCESS;
228
+ },
229
+ fd_read: (fd, iovsPtr, iovsLen, nreadPtr) => {
230
+ const entry = this.fds[fd];
231
+ if (!entry || typeof entry.fd_read !== "function") return EBADF;
232
+ const view = this.memoryView();
233
+ const { ret, nread } = entry.fd_read(this.readIovs(iovsPtr, iovsLen), view);
234
+ view.setUint32(nreadPtr, nread, true);
235
+ return ret;
236
+ },
237
+ fd_write: (fd, iovsPtr, iovsLen, nwrittenPtr) => {
238
+ const entry = this.fds[fd];
239
+ if (!entry || typeof entry.fd_write !== "function") return EBADF;
240
+ const view = this.memoryView();
241
+ const { ret, nwritten } = entry.fd_write(this.readIovs(iovsPtr, iovsLen), view);
242
+ view.setUint32(nwrittenPtr, nwritten, true);
243
+ return ret;
244
+ },
245
+ fd_close: (fd) => {
246
+ if (fd < 0 || fd >= this.fds.length || !this.fds[fd]) return EBADF;
247
+ this.fds[fd] = null;
248
+ return ESUCCESS;
249
+ },
250
+ fd_seek: (fd, offset, whence, newOffsetPtr) => {
251
+ const entry = this.fds[fd];
252
+ if (!entry || !entry.file) return EBADF;
253
+ const delta = Number(offset);
254
+ if (whence === 0) entry.file_pos = delta;
255
+ else if (whence === 1) entry.file_pos += delta;
256
+ else if (whence === 2) entry.file_pos = entry.file.data.length + delta;
257
+ else return EINVAL;
258
+ this.memoryView().setBigUint64(newOffsetPtr, BigInt(Math.max(0, entry.file_pos)), true);
259
+ return ESUCCESS;
260
+ },
261
+ clock_time_get: (_id, _precision, timePtr) => {
262
+ this.memoryView().setBigUint64(timePtr, BigInt(Date.now()) * 1000000n, true);
263
+ return ESUCCESS;
264
+ },
265
+ random_get: (bufPtr, bufLen) => {
266
+ const slice = new Uint8Array(this.memoryView().buffer, bufPtr, bufLen);
267
+ if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(slice);
268
+ return ESUCCESS;
269
+ },
270
+ proc_exit: (code) => {
271
+ throw new Error(`WASI proc_exit(${code})`);
272
+ },
273
+ };
274
+ }
275
+ }
@@ -0,0 +1,39 @@
1
+ // Dedicated worker: elects a single leader per (origin, partition) via navigator.locks.
2
+ // The leader mounts OPFS page-level WASI storage (PagedSyncOPFSFile) at
3
+ // /storage/development.sqlite3 (with clean IndexedDB fallback), runs the single hot
4
+ // AppHost, outbox drain, visibility-aware SSE change stream, server-directed background
5
+ // history fill, fail-loud WASM fault telemetry with a circuit breaker, bridged Ruby
6
+ // notifications, and an opt-in rolling `.irtrace` flight recorder, and serves peer tabs
7
+ // over dedicated channels with crash-safe failover.
8
+ import { AppHost } from "./app-host.js";
9
+ import { PagedSyncOPFSFile } from "./opfs-wasi-file.js";
10
+ import { createWorkerRuntime } from "./reactor-runtime.js";
11
+ import { openSnapshot, withFiles } from "./snapshot-store.js";
12
+
13
+ const runtime = createWorkerRuntime({
14
+ env: {
15
+ VITE_MANIFEST: import.meta.env.VITE_MANIFEST,
16
+ VITE_SYNC_ENDPOINT: import.meta.env.VITE_SYNC_ENDPOINT,
17
+ VITE_MOUNT_PATH: import.meta.env.VITE_MOUNT_PATH,
18
+ VITE_SCHEMA_VERSION: import.meta.env.VITE_SCHEMA_VERSION,
19
+ VITE_SCHEMA_BASELINE: import.meta.env.VITE_SCHEMA_BASELINE,
20
+ VITE_MIGRATION_HISTORY: import.meta.env.VITE_MIGRATION_HISTORY,
21
+ VITE_SCHEMA_DIGEST: import.meta.env.VITE_SCHEMA_DIGEST,
22
+ VITE_SHELL_FINGERPRINT: import.meta.env.VITE_SHELL_FINGERPRINT,
23
+ VITE_SHELL_SNAPSHOT: import.meta.env.VITE_SHELL_SNAPSHOT,
24
+ VITE_SOURCE_VERSION: import.meta.env.VITE_SOURCE_VERSION,
25
+ VITE_WASM_URL: import.meta.env.VITE_WASM_URL,
26
+ VITE_SYNC_PARTITIONS: import.meta.env.VITE_SYNC_PARTITIONS,
27
+ VITE_TRACE_SCHEMA: import.meta.env.VITE_TRACE_SCHEMA,
28
+ },
29
+ AppHost,
30
+ PagedSyncOPFSFile,
31
+ openSnapshot,
32
+ withFiles,
33
+ postMessage: msg => self.postMessage(msg),
34
+ origin: self.location.origin,
35
+ });
36
+
37
+ self.addEventListener("online", () => runtime.handleOnline());
38
+ self.addEventListener("offline", () => runtime.handleOffline());
39
+ self.onmessage = event => runtime.handleMessage(event);
@@ -0,0 +1,27 @@
1
+ import { defineConfig } from "vite";
2
+
3
+ // The built shell loads no module in the page: no module script and no modulepreload. It writes
4
+ // the app's own page into this document, and a browser that takes one import map only before
5
+ // the first module load (Firefox) would refuse the app's import map and fail on `import
6
+ // "application"`. The worker is a module in a scope of its own, which does not count.
7
+ const classicShell = {
8
+ name: "instant-record-classic-shell",
9
+ apply: "build",
10
+ transformIndexHtml: {
11
+ order: "post",
12
+ handler: html => html.replace(/<script type="module" crossorigin src=/g, "<script defer src="),
13
+ },
14
+ };
15
+
16
+ // The app's own assets live under /assets, so the harness builds into /harness.
17
+ export default defineConfig({
18
+ build: {
19
+ assetsDir: "harness",
20
+ target: "esnext",
21
+ sourcemap: false,
22
+ // strict: a module is strict by its nature, and the classic script has to say so.
23
+ rollupOptions: { output: { format: "iife", strict: true } },
24
+ },
25
+ worker: { format: "es" },
26
+ plugins: [classicShell],
27
+ });
data/config/routes.rb CHANGED
@@ -2,6 +2,31 @@ InstantRecord::Engine.routes.draw do
2
2
  post "mutations", to: "mutations#create"
3
3
  match "mutations", to: "mutations#preflight", via: :options
4
4
  get "events", to: "events#index"
5
+ match "events", to: "events#preflight", via: :options
5
6
  get "bootstrap", to: "bootstraps#show"
7
+ match "bootstrap", to: "bootstraps#preflight", via: :options
8
+ get "shell", to: "shells#show"
9
+ get "shell/file", to: "shells#file"
10
+ match "shell", to: "shells#preflight", via: :options
11
+ match "shell/file", to: "shells#preflight", via: :options
6
12
  get "records", to: "records#index"
13
+ match "records", to: "records#preflight", via: :options
14
+ # The bytes of a record that declares sync_file. A type may be namespaced
15
+ # and an id may hold a dot, so neither is cut at one.
16
+ constraints type: %r{[^/]+}, id: %r{[^/]+} do
17
+ get "files/:type/:id/upload", to: "files#progress"
18
+ get "files/:type/:id", to: "files#show"
19
+ put "files/:type/:id", to: "files#update"
20
+ match "files/:type/:id", to: "files#preflight", via: :options
21
+ end
22
+ # Quarantined conflict and rejection notices: list and resolve (retry, fork, dismiss).
23
+ get "sync_notices", to: "sync_notices#index"
24
+ post "sync_notices/:id/retry", to: "sync_notices#retry"
25
+ post "sync_notices/:id/fork", to: "sync_notices#fork"
26
+ post "sync_notices/:id/dismiss", to: "sync_notices#dismiss"
27
+ delete "sync_notices/:id", to: "sync_notices#dismiss"
28
+ # A native app's screens while developing. Answers 404 unless the app set
29
+ # config.instant_record.native_dev, in a local environment, to this machine.
30
+ post "native/render", to: "native_screens#show"
31
+ post "native/action", to: "native_screens#perform"
7
32
  end
@@ -0,0 +1,7 @@
1
+ class AddScopeToInstantRecordChanges < ActiveRecord::Migration[8.1]
2
+ # Whose change this is, for a model that declares sync_scope. NULL is a
3
+ # change every client may hear of.
4
+ def change
5
+ add_column :instant_record_changes, :scope, :string
6
+ end
7
+ end
@@ -0,0 +1,21 @@
1
+ class CreateInstantRecordSyncNotices < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :instant_record_sync_notices, id: :string do |t|
4
+ t.string :mutation_id
5
+ t.string :kind, null: false
6
+ t.string :record_type, null: false
7
+ t.string :record_id, null: false
8
+ t.string :operation, null: false
9
+ t.string :reason, null: false, default: ""
10
+ t.text :attempted_changes
11
+ t.text :server_attributes
12
+ t.integer :server_version, null: false, default: 0
13
+ t.datetime :dismissed_at
14
+ t.timestamps
15
+ end
16
+
17
+ add_index :instant_record_sync_notices, :mutation_id
18
+ add_index :instant_record_sync_notices, [:dismissed_at, :created_at]
19
+ add_index :instant_record_sync_notices, [:record_type, :record_id]
20
+ end
21
+ end
@@ -0,0 +1,8 @@
1
+ class AddPartitionToInstantRecordChanges < ActiveRecord::Migration[8.1]
2
+ # Which tenant/account partition this change belongs to, for models that
3
+ # declare `sync_partition`. NULL is an unpartitioned model's change.
4
+ def change
5
+ add_column :instant_record_changes, :partition, :string
6
+ add_index :instant_record_changes, [:partition, :id]
7
+ end
8
+ end
@@ -0,0 +1,10 @@
1
+ class AddDelayLineToInstantRecordOutbox < ActiveRecord::Migration[8.1]
2
+ # Optional delay-line fields for durable local undo windows: release_at holds
3
+ # an outbox mutation from draining until it matures, and rollback_payload keeps
4
+ # the pre-mutation local row snapshot for compensating restore on cancel.
5
+ def change
6
+ add_column :instant_record_outbox, :release_at, :datetime
7
+ add_column :instant_record_outbox, :rollback_payload, :text
8
+ add_index :instant_record_outbox, :release_at
9
+ end
10
+ end
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "instant_record/mcp"
5
+
6
+ exit InstantRecord::Mcp::Cli.run(ARGV)