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,98 @@
1
+ // Synchronous SHA-256 and base64 helpers (zero external dependencies) so both
2
+ // browser workers and Node can compute deterministic DB/output digests inside
3
+ // synchronous AppHost calls.
4
+ const encoder = new TextEncoder();
5
+
6
+ const K = new Uint32Array([
7
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
9
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
10
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
11
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
12
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
13
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
14
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
15
+ ]);
16
+
17
+ const H0 = new Uint32Array([
18
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
19
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
20
+ ]);
21
+
22
+ export function sha256Hex(input) {
23
+ const bytes = typeof input === "string" ? encoder.encode(input) : input instanceof Uint8Array ? input : new Uint8Array(input);
24
+ const bitLen = bytes.length * 8;
25
+ const paddedLen = Math.ceil((bytes.length + 9) / 64) * 64;
26
+ const padded = new Uint8Array(paddedLen);
27
+ padded.set(bytes);
28
+ padded[bytes.length] = 0x80;
29
+ const view = new DataView(padded.buffer);
30
+ const hi = Math.floor(bitLen / 0x100000000);
31
+ const lo = bitLen >>> 0;
32
+ view.setUint32(paddedLen - 8, hi, false);
33
+ view.setUint32(paddedLen - 4, lo, false);
34
+
35
+ const H = new Uint32Array(H0);
36
+ const W = new Uint32Array(64);
37
+
38
+ for (let offset = 0; offset < paddedLen; offset += 64) {
39
+ for (let i = 0; i < 16; i++) W[i] = view.getUint32(offset + i * 4, false);
40
+ for (let i = 16; i < 64; i++) {
41
+ const w15 = W[i - 15];
42
+ const w2 = W[i - 2];
43
+ const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
44
+ const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
45
+ W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;
46
+ }
47
+
48
+ let [a, b, c, d, e, f, g, h] = H;
49
+ for (let i = 0; i < 64; i++) {
50
+ const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
51
+ const ch = (e & f) ^ (~e & g);
52
+ const t1 = (h + S1 + ch + K[i] + W[i]) >>> 0;
53
+ const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
54
+ const maj = (a & b) ^ (a & c) ^ (b & c);
55
+ const t2 = (S0 + maj) >>> 0;
56
+
57
+ h = g;
58
+ g = f;
59
+ f = e;
60
+ e = (d + t1) >>> 0;
61
+ d = c;
62
+ c = b;
63
+ b = a;
64
+ a = (t1 + t2) >>> 0;
65
+ }
66
+
67
+ H[0] = (H[0] + a) >>> 0;
68
+ H[1] = (H[1] + b) >>> 0;
69
+ H[2] = (H[2] + c) >>> 0;
70
+ H[3] = (H[3] + d) >>> 0;
71
+ H[4] = (H[4] + e) >>> 0;
72
+ H[5] = (H[5] + f) >>> 0;
73
+ H[6] = (H[6] + g) >>> 0;
74
+ H[7] = (H[7] + h) >>> 0;
75
+ }
76
+
77
+ let hex = "";
78
+ for (let i = 0; i < 8; i++) hex += H[i].toString(16).padStart(8, "0");
79
+ return hex;
80
+ }
81
+
82
+ export function bytesToBase64(bytes) {
83
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
84
+ const chunkSize = 0x8000;
85
+ let binary = "";
86
+ for (let i = 0; i < bytes.length; i += chunkSize) {
87
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
88
+ }
89
+ return btoa(binary);
90
+ }
91
+
92
+ export function base64ToBytes(base64) {
93
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(base64, "base64"));
94
+ const binary = atob(base64);
95
+ const bytes = new Uint8Array(binary.length);
96
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
97
+ return bytes;
98
+ }
@@ -0,0 +1,52 @@
1
+ // Cold-start SQLite shell helpers shared by worker.js and unit tests.
2
+
3
+ export const SQLITE_MAGIC = "SQLite format 3\0";
4
+
5
+ export function scopedUrl(url, syncScope) {
6
+ if (!syncScope) return url;
7
+ return url + (url.includes("?") ? "&" : "?") + "scope=" + encodeURIComponent(syncScope);
8
+ }
9
+
10
+ // A shell is fetched for any compiled app when a build enables shell snapshots
11
+ // (VITE_SHELL_SNAPSHOT=1) or the page opts in with ?shell=1.
12
+ export function shouldFetchShell({ path, fingerprint, always, offline, blocked = false }) {
13
+ if (blocked || offline || !fingerprint) return false;
14
+ if (always) return true;
15
+ try {
16
+ const url = new URL(path || "/", "https://instant-record.invalid");
17
+ return url.searchParams.get("shell") === "1";
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ export function parseShellGrant(text) {
24
+ try {
25
+ const parsed = JSON.parse(text);
26
+ if (!parsed || typeof parsed !== "object") return null;
27
+ const { path, cursor, identity, fill } = parsed;
28
+ if (typeof path !== "string" || !path.startsWith("/") || !path.includes("/shell/file")) return null;
29
+ if (!Number.isInteger(cursor) || cursor < 0) return null;
30
+ const grant = {
31
+ path,
32
+ cursor,
33
+ identity: typeof identity === "string" ? identity : "",
34
+ };
35
+ if (Array.isArray(fill) && fill.length > 0) grant.fill = fill[0];
36
+ return grant;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ export function isValidSqliteBytes(bytes) {
43
+ if (!(bytes instanceof Uint8Array) || bytes.length < SQLITE_MAGIC.length) return false;
44
+ return new TextDecoder().decode(bytes.subarray(0, SQLITE_MAGIC.length)) === SQLITE_MAGIC;
45
+ }
46
+
47
+ export function validateShellState(state, grant) {
48
+ if (!state || !grant) return false;
49
+ if (!state.bootstrapped || state.cursor !== grant.cursor) return false;
50
+ if (grant.identity && state.identity !== grant.identity) return false;
51
+ return true;
52
+ }
@@ -0,0 +1,38 @@
1
+ // Version 3 fences out older workers that do not check the persisted schema.
2
+ let opened;
3
+ export function openSnapshot(partitionKey) {
4
+ opened = new Promise((resolve, reject) => {
5
+ const name = partitionKey ? "instant-record-spinel/partition/" + partitionKey : "instant-record-spinel";
6
+ const request = indexedDB.open(name, 3);
7
+ request.onupgradeneeded = event => {
8
+ if (event.oldVersion === 0) request.result.createObjectStore("files");
9
+ };
10
+ request.onblocked = () => self.postMessage({ type: "storage_upgrade_blocked" });
11
+ request.onsuccess = () => resolve(request.result);
12
+ request.onerror = () => reject(request.error);
13
+ });
14
+ }
15
+
16
+ // IndexedDB serializes readwrite transactions across workers. Only await
17
+ // requests from this transaction inside the callback, never network I/O.
18
+ export async function withFiles(mode, operation) {
19
+ const db = await opened;
20
+ return new Promise((resolve, reject) => {
21
+ const tx = db.transaction("files", mode);
22
+ const files = tx.objectStore("files");
23
+ const get = key => new Promise((resolve, reject) => {
24
+ const req = files.get(key);
25
+ req.onsuccess = () => resolve(req.result);
26
+ req.onerror = () => reject(req.error);
27
+ });
28
+ let result, failure;
29
+ tx.oncomplete = () => resolve(result);
30
+ tx.onabort = () => reject(failure || tx.error || new Error("Snapshot transaction aborted"));
31
+ operation(get, (key, value) => files.put(value, key), key => files.delete(key)).then(value => {
32
+ result = value;
33
+ }, error => {
34
+ failure = error;
35
+ try { tx.abort(); } catch { reject(error); }
36
+ });
37
+ });
38
+ }
@@ -0,0 +1,111 @@
1
+ // Node-only schema-aware SQLite checkpoint redactor using Node's built-in
2
+ // `node:sqlite`. Redacts PII columns per table, redacts `changes_payload` JSON
3
+ // inside `instant_record_outbox` by `record_type`, redacts `identity` in
4
+ // `instant_record_sync_metadata`, and runs VACUUM so deleted raw PII bytes do
5
+ // not linger in SQLite freelist pages.
6
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { Redactor } from "./redactor.js";
11
+ import { sha256Hex } from "./sha256.js";
12
+
13
+ function quoteIdent(name) {
14
+ return `"${String(name).replaceAll('"', '""')}"`;
15
+ }
16
+
17
+ export function redactSqliteBytes(dbBytes, redactor = new Redactor()) {
18
+ const original = dbBytes instanceof Uint8Array ? dbBytes : new Uint8Array(dbBytes);
19
+ const originalDigest = sha256Hex(original);
20
+ const dir = mkdtempSync(join(tmpdir(), "irtrace-redact-"));
21
+ const file = join(dir, "checkpoint.sqlite3");
22
+ const redactedColumns = {};
23
+
24
+ try {
25
+ writeFileSync(file, original);
26
+ const db = new DatabaseSync(file);
27
+ try {
28
+ const tables = db
29
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
30
+ .all()
31
+ .map((row) => row.name);
32
+
33
+ for (const table of tables) {
34
+ if (table === "schema_migrations" || table === "ar_internal_metadata") continue;
35
+
36
+ if (table === "instant_record_sync_metadata") {
37
+ const rows = db.prepare(`SELECT key, value FROM ${quoteIdent(table)}`).all();
38
+ const update = db.prepare(`UPDATE ${quoteIdent(table)} SET value = ? WHERE key = ?`);
39
+ for (const row of rows) {
40
+ if (row.key === "identity" && row.value) {
41
+ const next = redactor.pseudonymize(row.value, "identity");
42
+ update.run(next, row.key);
43
+ redactor.noteRedactedColumn(table, "identity");
44
+ redactedColumns[table] ||= [];
45
+ if (!redactedColumns[table].includes("identity")) redactedColumns[table].push("identity");
46
+ }
47
+ }
48
+ continue;
49
+ }
50
+
51
+ if (table === "instant_record_outbox") {
52
+ const rows = db.prepare(`SELECT id, record_type, changes_payload FROM ${quoteIdent(table)}`).all();
53
+ const update = db.prepare(`UPDATE ${quoteIdent(table)} SET changes_payload = ? WHERE id = ?`);
54
+ for (const row of rows) {
55
+ if (!row.changes_payload) continue;
56
+ try {
57
+ const parsed = JSON.parse(row.changes_payload);
58
+ const redacted = redactor.redactRecordAttributes(row.record_type || "*", parsed);
59
+ const serialized = JSON.stringify(redacted);
60
+ if (serialized !== row.changes_payload) {
61
+ update.run(serialized, row.id);
62
+ redactedColumns[table] ||= [];
63
+ if (!redactedColumns[table].includes("changes_payload")) redactedColumns[table].push("changes_payload");
64
+ }
65
+ } catch {
66
+ // Non-JSON payload left untouched.
67
+ }
68
+ }
69
+ continue;
70
+ }
71
+
72
+ const columns = db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all();
73
+ const piiCols = columns
74
+ .map((col) => col.name)
75
+ .filter((name) => redactor.isPiiColumn(table, name));
76
+ if (piiCols.length === 0) continue;
77
+
78
+ const selectSql = `SELECT rowid AS __ir_rowid, ${piiCols.map(quoteIdent).join(", ")} FROM ${quoteIdent(table)}`;
79
+ const rows = db.prepare(selectSql).all();
80
+ const setClause = piiCols.map((col) => `${quoteIdent(col)} = ?`).join(", ");
81
+ const updateStmt = db.prepare(`UPDATE ${quoteIdent(table)} SET ${setClause} WHERE rowid = ?`);
82
+
83
+ for (const row of rows) {
84
+ const values = piiCols.map((col) => {
85
+ const val = row[col];
86
+ if (val === null || val === undefined || val === "") return val;
87
+ return redactor.pseudonymize(val, col);
88
+ });
89
+ updateStmt.run(...values, row.__ir_rowid);
90
+ }
91
+
92
+ redactedColumns[table] = piiCols.slice().sort();
93
+ for (const col of piiCols) redactor.noteRedactedColumn(table, col);
94
+ }
95
+
96
+ db.exec("VACUUM");
97
+ } finally {
98
+ db.close();
99
+ }
100
+
101
+ const bytes = new Uint8Array(readFileSync(file));
102
+ return {
103
+ bytes,
104
+ digest: sha256Hex(bytes),
105
+ originalDigest,
106
+ redactedColumns,
107
+ };
108
+ } finally {
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
111
+ }
@@ -0,0 +1,159 @@
1
+ // Storage backend for compiled browser workers:
2
+ // - Primary: OPFS page-level FileSystemSyncAccessHandle wrapped in PagedSyncOPFSFile
3
+ // so SQLite reads/writes 4 KB pages directly without whole-file serialization.
4
+ // - Fallback: IndexedDB whole-file snapshots (e.g., Safari Private Mode or browsers
5
+ // without FileSystemSyncAccessHandle).
6
+ //
7
+ // Small metadata (schema version, secret_key_base, migration history, schema digest,
8
+ // history fill edge, revision) stays in IndexedDB's v3 store so existing profiles
9
+ // upgrade in place and failed migrations roll back cleanly.
10
+
11
+ export const FILL_BUDGET_BYTES_IDB = 24 * 1024 * 1024;
12
+ export const FILL_BUDGET_BYTES_OPFS = Number.POSITIVE_INFINITY;
13
+ export const OPFS_ROOT_DIR = "instant-record-spinel";
14
+ export const OPFS_DB_FILENAME = "development.sqlite3";
15
+
16
+ const PERMANENT_UNAVAILABLE_ERRORS = new Set([
17
+ "SecurityError",
18
+ "NotAllowedError",
19
+ "NotSupportedError",
20
+ "TypeError",
21
+ ]);
22
+
23
+ export function opfsDirectorySegments(partitionKey) {
24
+ if (!partitionKey) return [OPFS_ROOT_DIR, "default"];
25
+ const parts = String(partitionKey)
26
+ .split("/")
27
+ .filter(Boolean)
28
+ .map(part => part.replace(/[^a-zA-Z0-9._-]/g, "_"));
29
+ return [OPFS_ROOT_DIR, "partition", ...parts];
30
+ }
31
+
32
+ function sleep(ms) {
33
+ return new Promise(resolve => setTimeout(resolve, ms));
34
+ }
35
+
36
+ async function ensureDirectory(root, segments) {
37
+ let dir = root;
38
+ for (const segment of segments) {
39
+ dir = await dir.getDirectoryHandle(segment, { create: true });
40
+ }
41
+ return dir;
42
+ }
43
+
44
+ async function openSyncHandleWithRetry(fileHandle, { maxAttempts = 6, baseDelayMs = 25, delay = sleep } = {}) {
45
+ let lastError;
46
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
47
+ try {
48
+ return await fileHandle.createSyncAccessHandle();
49
+ } catch (error) {
50
+ lastError = error;
51
+ // Another worker's handle may still be releasing during rapid leader failover.
52
+ if (error?.name !== "NoModificationAllowedError" || attempt === maxAttempts - 1) {
53
+ throw error;
54
+ }
55
+ await delay(baseDelayMs * (2 ** attempt));
56
+ }
57
+ }
58
+ throw lastError;
59
+ }
60
+
61
+ export function isPermanentOpfsError(error) {
62
+ if (!error) return false;
63
+ return PERMANENT_UNAVAILABLE_ERRORS.has(error.name);
64
+ }
65
+
66
+ // Open OPFS sync storage for `scope`, or return an IndexedDB fallback descriptor when
67
+ // OPFS sync handles are unavailable.
68
+ export async function openDatabaseStorage(scope, {
69
+ storage = globalThis.navigator?.storage,
70
+ createFile,
71
+ maxAttempts = 6,
72
+ baseDelayMs = 25,
73
+ delay = sleep,
74
+ } = {}) {
75
+ if (!storage || typeof storage.getDirectory !== "function") {
76
+ return createIndexedDbBackend(scope, "opfs-unsupported");
77
+ }
78
+ try {
79
+ const root = await storage.getDirectory();
80
+ const segments = opfsDirectorySegments(scope);
81
+ const dir = await ensureDirectory(root, segments);
82
+ const fileHandle = await dir.getFileHandle(OPFS_DB_FILENAME, { create: true });
83
+ if (typeof fileHandle.createSyncAccessHandle !== "function") {
84
+ return createIndexedDbBackend(scope, "sync-access-handle-unsupported");
85
+ }
86
+ const syncHandle = await openSyncHandleWithRetry(fileHandle, { maxAttempts, baseDelayMs, delay });
87
+ const file = createFile(syncHandle);
88
+
89
+ let closed = false;
90
+ return {
91
+ mode: "opfs",
92
+ fallbackReason: null,
93
+ fillBudgetBytes: FILL_BUDGET_BYTES_OPFS,
94
+ file,
95
+ hasDatabase() {
96
+ return !closed && file.byteLength() > 0;
97
+ },
98
+ databaseSize() {
99
+ return closed ? 0 : file.byteLength();
100
+ },
101
+ readAllBytes() {
102
+ return closed ? null : file.readAll();
103
+ },
104
+ writeAllBytes(bytes) {
105
+ if (closed) throw new Error("OPFS storage is closed");
106
+ file.writeAll(bytes);
107
+ },
108
+ truncate(size = 0) {
109
+ if (closed) throw new Error("OPFS storage is closed");
110
+ file.truncate(size);
111
+ },
112
+ flush() {
113
+ if (!closed) file.flush();
114
+ },
115
+ close() {
116
+ if (closed) return;
117
+ closed = true;
118
+ try { file.flush(); } catch {}
119
+ try { file.close(); } catch {}
120
+ },
121
+ async wipe() {
122
+ this.close();
123
+ try {
124
+ await dir.removeEntry(OPFS_DB_FILENAME);
125
+ } catch {
126
+ // Entry may already be removed.
127
+ }
128
+ },
129
+ };
130
+ } catch (error) {
131
+ // Safari Private Mode, restricted iframes, or exhausted transient lock contention
132
+ // degrade cleanly to whole-file IndexedDB snapshots.
133
+ const reason = isPermanentOpfsError(error) ? error.name : (error?.name || "opfs-open-failed");
134
+ return createIndexedDbBackend(scope, reason);
135
+ }
136
+ }
137
+
138
+ function createIndexedDbBackend(scope, fallbackReason) {
139
+ return {
140
+ mode: "indexeddb",
141
+ fallbackReason,
142
+ fillBudgetBytes: FILL_BUDGET_BYTES_IDB,
143
+ file: null,
144
+ hasDatabase() {
145
+ return false;
146
+ },
147
+ databaseSize() {
148
+ return 0;
149
+ },
150
+ readAllBytes() {
151
+ return null;
152
+ },
153
+ writeAllBytes() {},
154
+ truncate() {},
155
+ flush() {},
156
+ close() {},
157
+ async wipe() {},
158
+ };
159
+ }