@chipmobilesdk/rn-local-db 0.1.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 (81) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +726 -0
  3. package/package.json +61 -0
  4. package/src/adapter/budgets.ts +67 -0
  5. package/src/adapter/collection.ts +298 -0
  6. package/src/adapter/deletion.ts +238 -0
  7. package/src/adapter/index.ts +68 -0
  8. package/src/adapter/lifecycle.ts +444 -0
  9. package/src/adapter/transaction.ts +65 -0
  10. package/src/artifacts/availability.ts +69 -0
  11. package/src/artifacts/cascade.ts +78 -0
  12. package/src/artifacts/paths.ts +29 -0
  13. package/src/artifacts/reconcile.ts +63 -0
  14. package/src/artifacts/store.ts +323 -0
  15. package/src/contract/adapter.ts +78 -0
  16. package/src/contract/attachment.ts +72 -0
  17. package/src/contract/backup.ts +28 -0
  18. package/src/contract/config.ts +54 -0
  19. package/src/contract/encryption.ts +34 -0
  20. package/src/contract/errors.ts +76 -0
  21. package/src/contract/migration.ts +40 -0
  22. package/src/contract/query.ts +81 -0
  23. package/src/contract/record.ts +42 -0
  24. package/src/contract/schema.ts +36 -0
  25. package/src/contract/scope.ts +36 -0
  26. package/src/contract/transaction.ts +46 -0
  27. package/src/crypto/chunked-cipher.ts +144 -0
  28. package/src/crypto/derive.ts +63 -0
  29. package/src/crypto/key-provider.ts +78 -0
  30. package/src/crypto/provider.ts +81 -0
  31. package/src/diagnostics/dev-log.ts +108 -0
  32. package/src/diagnostics/errors.ts +66 -0
  33. package/src/diagnostics/faults.ts +64 -0
  34. package/src/diagnostics/map-native.ts +106 -0
  35. package/src/diagnostics/redact.ts +141 -0
  36. package/src/index.ts +110 -0
  37. package/src/migration/executor.ts +136 -0
  38. package/src/migration/ledger.ts +97 -0
  39. package/src/migration/validate-chain.ts +65 -0
  40. package/src/platform/backup-android-verify.ts +88 -0
  41. package/src/platform/backup-ios.ts +48 -0
  42. package/src/platform/fs.ts +89 -0
  43. package/src/platform/location.ts +135 -0
  44. package/src/query/budgets.ts +57 -0
  45. package/src/query/compare.ts +91 -0
  46. package/src/query/cursor.ts +99 -0
  47. package/src/query/filter.ts +82 -0
  48. package/src/query/paginate.ts +51 -0
  49. package/src/query/sort.ts +56 -0
  50. package/src/query/validate.ts +171 -0
  51. package/src/schema/declare.ts +45 -0
  52. package/src/schema/validate-config.ts +158 -0
  53. package/src/scope/hash.ts +134 -0
  54. package/src/scope/normalize.ts +90 -0
  55. package/src/scope/validate.ts +83 -0
  56. package/src/sqlite/adapter.ts +26 -0
  57. package/src/sqlite/batch.ts +232 -0
  58. package/src/sqlite/catalog.ts +108 -0
  59. package/src/sqlite/connection.ts +205 -0
  60. package/src/sqlite/index-coverage.ts +53 -0
  61. package/src/sqlite/native.ts +83 -0
  62. package/src/sqlite/row-codec.ts +201 -0
  63. package/src/sqlite/sql-builder.ts +244 -0
  64. package/src/sqlite/transactions.ts +33 -0
  65. package/src/sqlite/values.ts +24 -0
  66. package/src/testing/conformance/attachments.ts +136 -0
  67. package/src/testing/conformance/encryption.ts +150 -0
  68. package/src/testing/conformance/index.ts +161 -0
  69. package/src/testing/conformance/lifecycle.ts +99 -0
  70. package/src/testing/conformance/migrations.ts +177 -0
  71. package/src/testing/conformance/queries.ts +167 -0
  72. package/src/testing/conformance/records.ts +169 -0
  73. package/src/testing/conformance/scopes.ts +88 -0
  74. package/src/testing/conformance/transactions.ts +149 -0
  75. package/src/testing/faults.ts +21 -0
  76. package/src/testing/index.ts +21 -0
  77. package/src/testing/memory-adapter/collection.ts +219 -0
  78. package/src/testing/memory-adapter/index.ts +388 -0
  79. package/src/testing/memory-adapter/migrations.ts +119 -0
  80. package/src/testing/memory-adapter/reset.ts +50 -0
  81. package/src/testing/memory-adapter/store.ts +134 -0
@@ -0,0 +1,388 @@
1
+ /**
2
+ * The in-memory adapter.
3
+ *
4
+ * Not a convenience: op-sqlite is native and unreachable from Jest, so this
5
+ * is the only way the package's own guarantees are testable in CI
6
+ * (research.md R8). Documented divergences are listed in the package README.
7
+ */
8
+
9
+ import type {
10
+ AttachmentInput,
11
+ AttachmentReference,
12
+ AttachmentOwner,
13
+ ByteRange,
14
+ DeletionOutcome,
15
+ ReconciliationReport,
16
+ } from '../../contract/attachment';
17
+ import type { EffectivePosture } from '../../contract/backup';
18
+ import type { DatabaseConfig, DatabaseTargetConfig, ScopeTargetConfig } from '../../contract/config';
19
+ import { DiagnosticCodes } from '../../contract/errors';
20
+ import type { IndexCoverageReport, Query } from '../../contract/query';
21
+ import type { StorableRecordData } from '../../contract/record';
22
+ import type { CollectionSchema } from '../../contract/schema';
23
+ import type { BatchOperation, BatchOutcome, CollectionOps, Transaction } from '../../contract/transaction';
24
+ import type { Attachments, DatabaseHandle, StorageAdapter } from '../../contract/adapter';
25
+ import { acquireKey } from '../../crypto/key-provider';
26
+ import { instrument } from '../../diagnostics/dev-log';
27
+ import { raise } from '../../diagnostics/errors';
28
+ import { assertValidAttachmentId } from '../../platform/location';
29
+ import { assertBatchWithinBudget, assertArtifactWithinBudget } from '../../query/budgets';
30
+ import { validateConfig } from '../../schema/validate-config';
31
+ import { resolveScope } from '../../scope/validate';
32
+ import { runMigrations } from './migrations';
33
+ import { createMemoryCollection } from './collection';
34
+ import {
35
+ collectionMap,
36
+ dropDatabase,
37
+ dropScope,
38
+ existingScopeStore,
39
+ scopeStoreFor,
40
+ type MemoryScopeStore,
41
+ } from './store';
42
+ import { throwIfFaulted } from '../faults';
43
+
44
+ export type MemoryAdapterOptions = {
45
+ /** Fixed clock, so timestamp assertions are deterministic. */
46
+ now?: () => number;
47
+ };
48
+
49
+ function schemaIndex(collections: CollectionSchema[]): Map<string, CollectionSchema> {
50
+ return new Map(collections.map(collection => [collection.name, collection]));
51
+ }
52
+
53
+ function cloneCollections(
54
+ store: MemoryScopeStore,
55
+ ): Map<string, Map<string, { id: string; payload: string; createdAt?: number; updatedAt?: number; deletedAt?: number | null }>> {
56
+ const copy = new Map<string, Map<string, never>>();
57
+ for (const [name, rows] of store.collections) {
58
+ copy.set(name, new Map([...rows].map(([id, row]) => [id, { ...row } as never])));
59
+ }
60
+ return copy as never;
61
+ }
62
+
63
+ export function createMemoryAdapter(options: MemoryAdapterOptions = {}): StorageAdapter {
64
+ const now = options.now ?? (() => Date.now());
65
+
66
+ async function open(config: DatabaseConfig): Promise<DatabaseHandle> {
67
+ validateConfig(config);
68
+ throwIfFaulted('open');
69
+
70
+ const scope = resolveScope(config.scope);
71
+ const existing = existingScopeStore(config.name, scope.key);
72
+ if (existing?.deletionState === 'deleting') {
73
+ // A deletion that was interrupted must never look complete.
74
+ raise(DiagnosticCodes.SCOPE_DELETED, {
75
+ message: 'scope deletion was interrupted',
76
+ detail: { scopeKey: scope.key },
77
+ });
78
+ }
79
+
80
+ const store = scopeStoreFor(config.name, scope.key);
81
+ const encryptionRequested = config.encryption?.enabled === true;
82
+
83
+ if (store.schemaVersion > 0 && store.encrypted !== encryptionRequested) {
84
+ raise(DiagnosticCodes.ENCRYPTION_MISMATCH, {
85
+ message: 'encryption posture does not match the stored database',
86
+ });
87
+ }
88
+ if (encryptionRequested) {
89
+ // The same acquisition path the on-device adapter uses, so a locked
90
+ // keychain and a provider returning nothing stay as distinguishable
91
+ // here as they are on a phone (SC-020b). Released immediately: the
92
+ // in-memory store has nothing to encrypt with it.
93
+ const key = await acquireKey(config.encryption!, scope);
94
+ key.release();
95
+ }
96
+ store.encrypted = encryptionRequested;
97
+ store.backupIncluded = config.backup?.includeInPlatformBackup === true;
98
+
99
+ const schemas = schemaIndex(config.collections);
100
+ for (const collection of config.collections) {
101
+ collectionMap(store, collection.name);
102
+ }
103
+
104
+ await runMigrations(store, config, now);
105
+
106
+ let closed = false;
107
+ const assertOpen = (): void => {
108
+ if (closed) {
109
+ raise(DiagnosticCodes.CLOSED_HANDLE, { message: 'handle is closed' });
110
+ }
111
+ if (store.deletionState === 'deleting') {
112
+ raise(DiagnosticCodes.SCOPE_DELETED, {
113
+ message: 'scope was deleted beneath this handle',
114
+ detail: { scopeKey: scope.key },
115
+ });
116
+ }
117
+ };
118
+
119
+ const collectionFor = <T extends StorableRecordData>(name: string): CollectionOps<T> => {
120
+ assertOpen();
121
+ const schema = schemas.get(name);
122
+ if (!schema) {
123
+ raise(DiagnosticCodes.CONFIG_INVALID, {
124
+ message: 'collection is not declared',
125
+ detail: { collection: name },
126
+ });
127
+ }
128
+ return instrument(
129
+ name,
130
+ 'memory',
131
+ createMemoryCollection<T>({ store, schema, now, assertOpen }) as unknown as Record<
132
+ string,
133
+ (...args: never[]) => unknown
134
+ >,
135
+ ) as unknown as CollectionOps<T>;
136
+ };
137
+
138
+ const backupPosture: EffectivePosture = {
139
+ requested: store.backupIncluded ? 'included' : 'excluded',
140
+ observed: store.backupIncluded ? 'included' : 'excluded',
141
+ enforcedBy: 'package',
142
+ };
143
+
144
+ const attachments: Attachments = {
145
+ async write(input: AttachmentInput): Promise<AttachmentReference> {
146
+ assertOpen();
147
+ throwIfFaulted('attachmentWrite');
148
+ assertValidAttachmentId(input.id);
149
+ const bytes = Buffer.from(input.content, 'base64');
150
+ assertArtifactWithinBudget(input.id, bytes.length);
151
+ const reference: AttachmentReference = {
152
+ id: input.id,
153
+ owner: input.owner,
154
+ contentType: input.contentType,
155
+ size: bytes.length,
156
+ createdAt: now(),
157
+ };
158
+ store.artifacts.set(input.id, input.content);
159
+ store.attachments.set(input.id, reference);
160
+ return reference;
161
+ },
162
+ async read(id: string, range?: ByteRange): Promise<string> {
163
+ assertOpen();
164
+ // No paths here to escape, but an id the device build would refuse
165
+ // has to be refused here too, or a consumer's passing tests stop
166
+ // predicting the device (FR-096).
167
+ assertValidAttachmentId(id);
168
+ const content = store.artifacts.get(id);
169
+ if (content === undefined) {
170
+ raise(DiagnosticCodes.ATTACHMENT_MISSING, {
171
+ message: 'artifact is missing',
172
+ detail: { attachmentId: id },
173
+ });
174
+ }
175
+ if (!range) {
176
+ return content;
177
+ }
178
+ const bytes = Buffer.from(content, 'base64');
179
+ return bytes.subarray(range.offset, range.offset + range.length).toString('base64');
180
+ },
181
+ async availability(id) {
182
+ assertOpen();
183
+ const reference = store.attachments.get(id);
184
+ if (!reference) {
185
+ return { id, state: 'missing' };
186
+ }
187
+ return store.artifacts.has(id)
188
+ ? { id, state: 'available', size: reference.size }
189
+ : { id, state: 'missing' };
190
+ },
191
+ async remove(id: string): Promise<DeletionOutcome> {
192
+ assertOpen();
193
+ assertValidAttachmentId(id);
194
+ const removed = store.artifacts.delete(id);
195
+ store.attachments.delete(id);
196
+ return {
197
+ removedRecords: 0,
198
+ removedArtifacts: removed ? [id] : [],
199
+ orphanedReferences: [],
200
+ failedRemovals: [],
201
+ };
202
+ },
203
+ async listFor(owner: AttachmentOwner): Promise<AttachmentReference[]> {
204
+ assertOpen();
205
+ return [...store.attachments.values()].filter(
206
+ reference =>
207
+ reference.owner?.collection === owner.collection &&
208
+ reference.owner?.id === owner.id,
209
+ );
210
+ },
211
+ async reconcile(reconcileOptions): Promise<ReconciliationReport> {
212
+ assertOpen();
213
+ const orphanedArtifacts = [...store.artifacts.keys()].filter(
214
+ id => !store.attachments.has(id),
215
+ );
216
+ const danglingReferences = [...store.attachments.keys()].filter(
217
+ id => !store.artifacts.has(id),
218
+ );
219
+ const removedArtifacts: string[] = [];
220
+ if (reconcileOptions?.removeOrphans) {
221
+ for (const id of orphanedArtifacts) {
222
+ store.artifacts.delete(id);
223
+ removedArtifacts.push(id);
224
+ }
225
+ }
226
+ return { orphanedArtifacts, danglingReferences, removedArtifacts };
227
+ },
228
+ };
229
+
230
+ const handle: DatabaseHandle = {
231
+ scopeKey: scope.key,
232
+ schemaVersion: store.schemaVersion,
233
+ backupPosture,
234
+ isEncrypted: store.encrypted,
235
+ collection: collectionFor,
236
+
237
+ async transaction<R>(fn: (tx: Transaction) => Promise<R>): Promise<R> {
238
+ assertOpen();
239
+ // Snapshot-and-restore rather than a write log: simpler to
240
+ // reason about, and rollback fidelity is what US4 tests.
241
+ const snapshot = cloneCollections(store);
242
+ const attachmentSnapshot = new Map(store.attachments);
243
+ let settled = false;
244
+
245
+ const tx: Transaction = {
246
+ collection: <T extends StorableRecordData>(name: string) => {
247
+ if (settled) {
248
+ raise(DiagnosticCodes.TRANSACTION_STATE, {
249
+ message: 'transaction already settled',
250
+ });
251
+ }
252
+ return collectionFor<T>(name);
253
+ },
254
+ async abort() {
255
+ if (settled) {
256
+ raise(DiagnosticCodes.TRANSACTION_STATE, {
257
+ message: 'transaction already settled',
258
+ });
259
+ }
260
+ settled = true;
261
+ store.collections = snapshot as never;
262
+ store.attachments = attachmentSnapshot;
263
+ },
264
+ };
265
+
266
+ try {
267
+ const result = await fn(tx);
268
+ if (!settled) {
269
+ throwIfFaulted('commit');
270
+ settled = true;
271
+ }
272
+ return result;
273
+ } catch (error) {
274
+ if (!settled) {
275
+ settled = true;
276
+ store.collections = snapshot as never;
277
+ store.attachments = attachmentSnapshot;
278
+ }
279
+ throw error;
280
+ }
281
+ },
282
+
283
+ async batch(operations: BatchOperation[]): Promise<BatchOutcome> {
284
+ assertOpen();
285
+ assertBatchWithinBudget(operations.length);
286
+ return handle.transaction(async (tx: Transaction) => {
287
+ const outcomes = [];
288
+ for (const operation of operations) {
289
+ const ops = tx.collection(operation.collection);
290
+ switch (operation.type) {
291
+ case 'insert':
292
+ outcomes.push(await ops.insert(operation.record));
293
+ break;
294
+ case 'update':
295
+ outcomes.push(await ops.update(operation.id, { data: operation.data }));
296
+ break;
297
+ case 'upsert':
298
+ outcomes.push(await ops.upsert(operation.record));
299
+ break;
300
+ case 'delete':
301
+ outcomes.push(await ops.delete(operation.id));
302
+ break;
303
+ case 'softDelete':
304
+ outcomes.push(await ops.softDelete(operation.id));
305
+ break;
306
+ default:
307
+ break;
308
+ }
309
+ }
310
+ return { applied: outcomes.length, outcomes };
311
+ });
312
+ },
313
+
314
+ attachments: () => attachments,
315
+
316
+ async explain(collection: string, _query?: Query): Promise<IndexCoverageReport> {
317
+ assertOpen();
318
+ // Documented divergence: index declarations are validated but
319
+ // have no performance effect in memory (FR-096).
320
+ return {
321
+ collection,
322
+ usesIndex: false,
323
+ detail: 'memory adapter does not use indexes',
324
+ };
325
+ },
326
+
327
+ async close(): Promise<void> {
328
+ closed = true;
329
+ },
330
+ };
331
+
332
+ return handle;
333
+ }
334
+
335
+ /**
336
+ * Backs both `deleteScopeData` and `resetScope`. They differ in intent and
337
+ * in what they let a consumer conclude, not in what they do to the store —
338
+ * keeping them as separate exported names is what makes the destructive one
339
+ * impossible to call by accident.
340
+ */
341
+ async function removeScope(config: ScopeTargetConfig): Promise<DeletionOutcome> {
342
+ const scope = resolveScope(config.scope);
343
+ const store = existingScopeStore(config.name, scope.key);
344
+ if (!store) {
345
+ // Deleting nothing is success, not an error (FR-062).
346
+ return {
347
+ scopeKey: scope.key,
348
+ removedRecords: 0,
349
+ removedArtifacts: [],
350
+ orphanedReferences: [],
351
+ failedRemovals: [],
352
+ };
353
+ }
354
+ store.deletionState = 'deleting';
355
+ let removedRecords = 0;
356
+ for (const rows of store.collections.values()) {
357
+ removedRecords += rows.size;
358
+ }
359
+ const removedArtifacts = [...store.artifacts.keys()];
360
+ dropScope(config.name, scope.key);
361
+ return {
362
+ scopeKey: scope.key,
363
+ removedRecords,
364
+ removedArtifacts,
365
+ orphanedReferences: [],
366
+ failedRemovals: [],
367
+ };
368
+ }
369
+
370
+ return {
371
+ name: 'memory',
372
+ open,
373
+ deleteScopeData: config => removeScope(config),
374
+ resetScope: config => removeScope(config),
375
+ async deleteDatabase(config: DatabaseTargetConfig): Promise<DeletionOutcome> {
376
+ dropDatabase(config.name);
377
+ return {
378
+ removedRecords: 0,
379
+ removedArtifacts: [],
380
+ orphanedReferences: [],
381
+ failedRemovals: [],
382
+ };
383
+ },
384
+ };
385
+ }
386
+
387
+ export { Budgets } from '../../contract/config';
388
+ export { activeFaults } from '../faults';
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Migration execution for the in-memory adapter.
3
+ *
4
+ * Mirrors the on-device rules exactly, because migration behaviour is the
5
+ * thing consumers most need to test without a device: ordered, at most once
6
+ * per scope, atomic per step, and loud on failure (FR-047 to FR-057).
7
+ */
8
+
9
+ import type { DatabaseConfig } from '../../contract/config';
10
+ import { DiagnosticCodes } from '../../contract/errors';
11
+ import type { MigrationContext } from '../../contract/migration';
12
+ import { raise } from '../../diagnostics/errors';
13
+ import { throwIfFaulted } from '../faults';
14
+ import type { MemoryScopeStore } from './store';
15
+
16
+ export async function runMigrations(
17
+ store: MemoryScopeStore,
18
+ config: DatabaseConfig,
19
+ now: () => number,
20
+ ): Promise<void> {
21
+ const migrations = [...(config.migrations ?? [])].sort((a, b) => a.version - b.version);
22
+
23
+ if (store.schemaVersion > config.schemaVersion) {
24
+ // Opening anyway would mean a newer database read by older code, which
25
+ // silently drops whatever the newer schema added.
26
+ raise(DiagnosticCodes.SCHEMA_DOWNGRADE, {
27
+ message: 'recorded schema version is newer than the declared one',
28
+ detail: {
29
+ recordedVersion: store.schemaVersion,
30
+ version: config.schemaVersion,
31
+ },
32
+ });
33
+ }
34
+
35
+ for (const migration of migrations) {
36
+ if (migration.version <= store.schemaVersion) {
37
+ continue;
38
+ }
39
+
40
+ const snapshot = new Map(
41
+ [...store.collections].map(([name, rows]) => [name, new Map(rows)]),
42
+ );
43
+
44
+ try {
45
+ throwIfFaulted('migration');
46
+ // A migration gets collection access but no handle-level surface:
47
+ // it must not open another scope or start a nested transaction.
48
+ const context = {
49
+ collection: (name: string) => {
50
+ if (!store.collections.has(name)) {
51
+ store.collections.set(name, new Map());
52
+ }
53
+ return migrationCollection(store, name);
54
+ },
55
+ abort: async () => {
56
+ throw new Error('migration aborted');
57
+ },
58
+ execute: async () => {
59
+ // The memory adapter has no SQL. Documented divergence.
60
+ },
61
+ } as unknown as MigrationContext;
62
+
63
+ await migration.migrate(context);
64
+
65
+ store.schemaVersion = migration.version;
66
+ store.ledger.set(migration.version, {
67
+ version: migration.version,
68
+ attemptedAt: now(),
69
+ outcome: 'applied',
70
+ });
71
+ } catch (error) {
72
+ // Leave the recorded version untouched so the next open retries
73
+ // from the same place rather than skipping ahead (FR-051).
74
+ store.collections = snapshot;
75
+ store.ledger.set(migration.version, {
76
+ version: migration.version,
77
+ attemptedAt: now(),
78
+ outcome: 'failed',
79
+ failureCode: (error as { code?: string }).code ?? DiagnosticCodes.MIGRATION_FAILED,
80
+ });
81
+ raise(DiagnosticCodes.MIGRATION_FAILED, {
82
+ message: 'migration failed',
83
+ migration: {
84
+ recordedVersion: store.schemaVersion,
85
+ failingVersion: migration.version,
86
+ outcome: 'failed',
87
+ },
88
+ cause: error,
89
+ });
90
+ }
91
+ }
92
+
93
+ if (migrations.length === 0) {
94
+ store.schemaVersion = config.schemaVersion;
95
+ }
96
+ }
97
+
98
+ function migrationCollection(store: MemoryScopeStore, name: string) {
99
+ const rows = store.collections.get(name)!;
100
+ return {
101
+ async insert(record: { id: string; data: Record<string, unknown> }) {
102
+ rows.set(record.id, { id: record.id, payload: JSON.stringify(record.data) });
103
+ return { operation: 'created' as const, id: record.id };
104
+ },
105
+ async upsert(record: { id: string; data: Record<string, unknown> }) {
106
+ const existed = rows.has(record.id);
107
+ rows.set(record.id, { id: record.id, payload: JSON.stringify(record.data) });
108
+ return { operation: existed ? ('updated' as const) : ('created' as const), id: record.id };
109
+ },
110
+ async delete(id: string) {
111
+ rows.delete(id);
112
+ return { operation: 'deleted' as const, id };
113
+ },
114
+ async find(id: string) {
115
+ const row = rows.get(id);
116
+ return row ? { id: row.id, data: JSON.parse(row.payload) } : null;
117
+ },
118
+ };
119
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Test lifecycle helpers.
3
+ *
4
+ * `seedRecords` deliberately goes through the same write operations
5
+ * production code uses (FR-094). Seeding by poking the store directly would
6
+ * skip budget checks and timestamp handling, so tests would pass against data
7
+ * the package would have refused to store.
8
+ */
9
+
10
+ import type { StorageAdapter } from '../../contract/adapter';
11
+ import type { DatabaseConfig } from '../../contract/config';
12
+ import type { RecordInput, StorableRecordData } from '../../contract/record';
13
+ import { clearFaults } from '../faults';
14
+ import { existingScopeStore, resetAllMemoryStores } from './store';
15
+
16
+ /**
17
+ * The conformance suite's "reach past the package" hooks, implemented for the
18
+ * in-memory store. On device the equivalent unlinks the file directly.
19
+ */
20
+ export const memoryConformanceHooks = {
21
+ async removeArtifactBehindTheScenes(scopeKey: string, attachmentId: string): Promise<void> {
22
+ existingScopeStore('conformance', scopeKey)?.artifacts.delete(attachmentId);
23
+ },
24
+ async removeReferenceBehindTheScenes(scopeKey: string, attachmentId: string): Promise<void> {
25
+ existingScopeStore('conformance', scopeKey)?.attachments.delete(attachmentId);
26
+ },
27
+ };
28
+
29
+ /** Return every in-memory database to a known-empty state (FR-093). */
30
+ export async function resetMemoryAdapter(_adapter?: StorageAdapter): Promise<void> {
31
+ resetAllMemoryStores();
32
+ clearFaults();
33
+ }
34
+
35
+ export async function seedRecords<T extends StorableRecordData>(
36
+ adapter: StorageAdapter,
37
+ config: DatabaseConfig,
38
+ collection: string,
39
+ records: RecordInput<T>[],
40
+ ): Promise<void> {
41
+ const handle = await adapter.open(config);
42
+ try {
43
+ const ops = handle.collection<T>(collection);
44
+ for (const record of records) {
45
+ await ops.upsert(record);
46
+ }
47
+ } finally {
48
+ await handle.close();
49
+ }
50
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The in-memory store behind the test adapter.
3
+ *
4
+ * Scope isolation is structural here for the same reason it is on device: one
5
+ * store per scope, held in a registry keyed by scope digest. A handle holds a
6
+ * reference to its own store and has no way to reach another (FR-011).
7
+ */
8
+
9
+ import type { AttachmentReference } from '../../contract/attachment';
10
+ import type { MigrationLedgerEntry } from '../../contract/migration';
11
+ import type { StorableRecordData, StoredRecord } from '../../contract/record';
12
+ import type { ScopeDeletionState } from '../../contract/scope';
13
+
14
+ export type MemoryRow = {
15
+ id: string;
16
+ /** Serialized on write, parsed on read — the same payload-as-truth rule
17
+ * the SQLite adapter follows, so a mutation after write cannot leak in. */
18
+ payload: string;
19
+ createdAt?: number;
20
+ updatedAt?: number;
21
+ deletedAt?: number | null;
22
+ };
23
+
24
+ export type MemoryScopeStore = {
25
+ scopeKey: string;
26
+ schemaVersion: number;
27
+ ledger: Map<number, MigrationLedgerEntry>;
28
+ collections: Map<string, Map<string, MemoryRow>>;
29
+ attachments: Map<string, AttachmentReference>;
30
+ artifacts: Map<string, string>;
31
+ deletionState: ScopeDeletionState;
32
+ encrypted: boolean;
33
+ backupIncluded: boolean;
34
+ };
35
+
36
+ export type MemoryDatabase = {
37
+ name: string;
38
+ scopes: Map<string, MemoryScopeStore>;
39
+ };
40
+
41
+ const databases = new Map<string, MemoryDatabase>();
42
+
43
+ export function databaseFor(name: string): MemoryDatabase {
44
+ let database = databases.get(name);
45
+ if (!database) {
46
+ database = { name, scopes: new Map() };
47
+ databases.set(name, database);
48
+ }
49
+ return database;
50
+ }
51
+
52
+ export function scopeStoreFor(name: string, scopeKey: string): MemoryScopeStore {
53
+ const database = databaseFor(name);
54
+ let store = database.scopes.get(scopeKey);
55
+ if (!store) {
56
+ store = {
57
+ scopeKey,
58
+ schemaVersion: 0,
59
+ ledger: new Map(),
60
+ collections: new Map(),
61
+ attachments: new Map(),
62
+ artifacts: new Map(),
63
+ deletionState: 'active',
64
+ encrypted: false,
65
+ backupIncluded: false,
66
+ };
67
+ database.scopes.set(scopeKey, store);
68
+ }
69
+ return store;
70
+ }
71
+
72
+ export function existingScopeStore(
73
+ name: string,
74
+ scopeKey: string,
75
+ ): MemoryScopeStore | undefined {
76
+ return databases.get(name)?.scopes.get(scopeKey);
77
+ }
78
+
79
+ export function dropScope(name: string, scopeKey: string): void {
80
+ databases.get(name)?.scopes.delete(scopeKey);
81
+ }
82
+
83
+ export function dropDatabase(name: string): void {
84
+ databases.delete(name);
85
+ }
86
+
87
+ /** Between tests (FR-093). */
88
+ export function resetAllMemoryStores(): void {
89
+ databases.clear();
90
+ }
91
+
92
+ export function collectionMap(
93
+ store: MemoryScopeStore,
94
+ collection: string,
95
+ ): Map<string, MemoryRow> {
96
+ let rows = store.collections.get(collection);
97
+ if (!rows) {
98
+ rows = new Map();
99
+ store.collections.set(collection, rows);
100
+ }
101
+ return rows;
102
+ }
103
+
104
+ /**
105
+ * Deep copy through serialization on the way in and out.
106
+ *
107
+ * The same discipline as the SQLite adapter's payload column: a consumer that
108
+ * mutates the object it handed us must not change what is stored (FR-022),
109
+ * and what we hand back must not be a live reference into the store.
110
+ */
111
+ export function encodePayload(data: StorableRecordData): string {
112
+ return JSON.stringify(data ?? {});
113
+ }
114
+
115
+ export function decodePayload<T extends StorableRecordData>(payload: string): T {
116
+ return JSON.parse(payload) as T;
117
+ }
118
+
119
+ export function toStoredRecord<T extends StorableRecordData>(row: MemoryRow): StoredRecord<T> {
120
+ const record: StoredRecord<T> = {
121
+ id: row.id,
122
+ data: decodePayload<T>(row.payload),
123
+ };
124
+ if (row.createdAt !== undefined) {
125
+ record.createdAt = row.createdAt;
126
+ }
127
+ if (row.updatedAt !== undefined) {
128
+ record.updatedAt = row.updatedAt;
129
+ }
130
+ if (row.deletedAt !== undefined) {
131
+ record.deletedAt = row.deletedAt;
132
+ }
133
+ return record;
134
+ }