@baukit/data-contracts 0.7.2 → 0.7.4

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.
@@ -0,0 +1,637 @@
1
+ import type { MaybePromise } from './contracts.js';
2
+
3
+ const REGISTRY_VERSION = 1;
4
+ const SCOPED_STORE_PREFIX = 'baukit-scoped-v1-';
5
+ const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/u;
6
+
7
+ /** Product-selected behavior for a partition after logout. */
8
+ export type LocalDataRetention = 'retain' | 'delete' | 'quarantine';
9
+
10
+ /** Registry persistence kept outside the user-owned domain database. */
11
+ export interface ScopedPersistenceRegistryStore {
12
+ read(): Promise<string | null>;
13
+ write(serialized: string): Promise<void>;
14
+ }
15
+
16
+ /** A digest seam for runtimes that install their Web Crypto implementation explicitly. */
17
+ export type ScopedPersistenceDigest = (value: string) => Promise<string>;
18
+
19
+ export type LegacyStoreOwnership = 'claimable' | 'current-subject' | 'other-subject' | 'ambiguous';
20
+
21
+ export type LegacyStoreInspection =
22
+ { readonly exists: false } | { readonly exists: true; readonly ownership: LegacyStoreOwnership };
23
+
24
+ export interface ResolveScopedStoreOptions {
25
+ readonly namespace: string;
26
+ readonly subject: string;
27
+ readonly registry: ScopedPersistenceRegistryStore;
28
+ readonly digest?: ScopedPersistenceDigest;
29
+ readonly inspectLegacy?: (subject: string) => Promise<LegacyStoreInspection>;
30
+ readonly legacyStoreName?: string;
31
+ }
32
+
33
+ export interface ResolvedScopedStore {
34
+ readonly storeName: string;
35
+ readonly claimedLegacy: boolean;
36
+ }
37
+
38
+ /** Product compatibility resolver used when older ownership metadata already exists. */
39
+ export type ScopedPersistenceResolver = (subject: string) => MaybePromise<ResolvedScopedStore>;
40
+
41
+ /** Stable blocking failure for corrupt ownership metadata or a subject mismatch. */
42
+ export class PersistenceIdentityMismatchError extends Error {
43
+ public override readonly name = 'PersistenceIdentityMismatchError';
44
+ public readonly code = 'persistence_identity_mismatch' as const;
45
+
46
+ public constructor(
47
+ message = 'Local data belongs to a different authenticated identity.',
48
+ options?: ErrorOptions,
49
+ ) {
50
+ super(message, options);
51
+ }
52
+ }
53
+
54
+ export function isPersistenceIdentityMismatchError(
55
+ cause: unknown,
56
+ ): cause is PersistenceIdentityMismatchError {
57
+ return (
58
+ cause instanceof PersistenceIdentityMismatchError ||
59
+ (typeof cause === 'object' &&
60
+ cause !== null &&
61
+ Reflect.get(cause, 'code') === 'persistence_identity_mismatch')
62
+ );
63
+ }
64
+
65
+ interface RegistryEntry {
66
+ readonly subject: string;
67
+ readonly storeName: string;
68
+ readonly claimedLegacy: boolean;
69
+ }
70
+
71
+ interface RegistryNamespace {
72
+ readonly namespace: string;
73
+ legacyClaimedBySubject: string | null;
74
+ readonly subjects: RegistryEntry[];
75
+ }
76
+
77
+ interface PersistenceRegistry {
78
+ readonly version: typeof REGISTRY_VERSION;
79
+ readonly namespaces: RegistryNamespace[];
80
+ }
81
+
82
+ /** Small deterministic registry adapter for tests and non-persistent products. */
83
+ export class InMemoryScopedPersistenceRegistryStore implements ScopedPersistenceRegistryStore {
84
+ public constructor(private serialized: string | null = null) {}
85
+
86
+ public read(): Promise<string | null> {
87
+ return Promise.resolve(this.serialized);
88
+ }
89
+
90
+ public write(serialized: string): Promise<void> {
91
+ this.serialized = serialized;
92
+ return Promise.resolve();
93
+ }
94
+ }
95
+
96
+ interface SubtleCryptoLike {
97
+ digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer>;
98
+ }
99
+
100
+ function webCryptoSubtle(): SubtleCryptoLike {
101
+ const cryptoValue: unknown = Reflect.get(globalThis, 'crypto');
102
+ const subtle: unknown =
103
+ typeof cryptoValue === 'object' && cryptoValue !== null
104
+ ? Reflect.get(cryptoValue, 'subtle')
105
+ : undefined;
106
+ if (
107
+ typeof subtle !== 'object' ||
108
+ subtle === null ||
109
+ typeof Reflect.get(subtle, 'digest') !== 'function'
110
+ ) {
111
+ throw new PersistenceIdentityMismatchError(
112
+ 'A Web Crypto SHA-256 implementation is required before local data can be opened.',
113
+ );
114
+ }
115
+ return subtle as SubtleCryptoLike;
116
+ }
117
+
118
+ function utf8(value: string): Uint8Array {
119
+ const bytes: number[] = [];
120
+ for (const character of value) {
121
+ const codePoint = character.codePointAt(0);
122
+ if (codePoint === undefined) continue;
123
+ if (codePoint <= 0x7f) {
124
+ bytes.push(codePoint);
125
+ } else if (codePoint <= 0x7ff) {
126
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
127
+ } else if (codePoint <= 0xffff) {
128
+ bytes.push(
129
+ 0xe0 | (codePoint >> 12),
130
+ 0x80 | ((codePoint >> 6) & 0x3f),
131
+ 0x80 | (codePoint & 0x3f),
132
+ );
133
+ } else {
134
+ bytes.push(
135
+ 0xf0 | (codePoint >> 18),
136
+ 0x80 | ((codePoint >> 12) & 0x3f),
137
+ 0x80 | ((codePoint >> 6) & 0x3f),
138
+ 0x80 | (codePoint & 0x3f),
139
+ );
140
+ }
141
+ }
142
+ return new Uint8Array(bytes);
143
+ }
144
+
145
+ function hexadecimal(bytes: Uint8Array): string {
146
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
147
+ }
148
+
149
+ async function sha256(value: string): Promise<string> {
150
+ const digest = await webCryptoSubtle().digest('SHA-256', utf8(value));
151
+ return hexadecimal(new Uint8Array(digest));
152
+ }
153
+
154
+ function requiredIdentityPart(value: string, label: string): string {
155
+ if (value.trim().length === 0) {
156
+ throw new PersistenceIdentityMismatchError(`${label} must not be empty.`);
157
+ }
158
+ return value;
159
+ }
160
+
161
+ function canonicalIdentity(namespace: string, subject: string): string {
162
+ const namespaceBytes = utf8(namespace).byteLength;
163
+ const subjectBytes = utf8(subject).byteLength;
164
+ return `baukit-scoped-persistence:v1:${String(namespaceBytes)}:${namespace}:${String(subjectBytes)}:${subject}`;
165
+ }
166
+
167
+ /** Derives an opaque, stable name without disclosing the namespace or OIDC subject. */
168
+ export async function deriveScopedStoreName(
169
+ namespace: string,
170
+ subject: string,
171
+ digest: ScopedPersistenceDigest = sha256,
172
+ ): Promise<string> {
173
+ requiredIdentityPart(namespace, 'Persistence namespace');
174
+ requiredIdentityPart(subject, 'Authenticated subject');
175
+ let hash: string;
176
+ try {
177
+ hash = (await digest(canonicalIdentity(namespace, subject))).toLowerCase();
178
+ } catch (cause) {
179
+ if (isPersistenceIdentityMismatchError(cause)) throw cause;
180
+ throw new PersistenceIdentityMismatchError('The local-data identity digest failed.', { cause });
181
+ }
182
+ if (!SHA256_HEX_PATTERN.test(hash)) {
183
+ throw new PersistenceIdentityMismatchError('The local-data identity digest is invalid.');
184
+ }
185
+ return `${SCOPED_STORE_PREFIX}${hash}`;
186
+ }
187
+
188
+ function emptyRegistry(): PersistenceRegistry {
189
+ return { version: REGISTRY_VERSION, namespaces: [] };
190
+ }
191
+
192
+ function corruptRegistry(cause?: unknown): PersistenceIdentityMismatchError {
193
+ return new PersistenceIdentityMismatchError(
194
+ 'Local account ownership metadata is invalid; local data was not opened.',
195
+ cause === undefined ? undefined : { cause },
196
+ );
197
+ }
198
+
199
+ function parseRegistry(serialized: string | null): PersistenceRegistry {
200
+ if (serialized === null) return emptyRegistry();
201
+ try {
202
+ const value: unknown = JSON.parse(serialized);
203
+ if (
204
+ typeof value !== 'object' ||
205
+ value === null ||
206
+ Reflect.get(value, 'version') !== REGISTRY_VERSION ||
207
+ !Array.isArray(Reflect.get(value, 'namespaces'))
208
+ ) {
209
+ throw new TypeError('invalid registry root');
210
+ }
211
+ const namespaces = Reflect.get(value, 'namespaces') as unknown[];
212
+ const namespaceNames = new Set<string>();
213
+ const storeNames = new Set<string>();
214
+ for (const candidate of namespaces) {
215
+ validateRegistryNamespace(candidate, namespaceNames, storeNames);
216
+ }
217
+ return value as PersistenceRegistry;
218
+ } catch (cause) {
219
+ if (isPersistenceIdentityMismatchError(cause)) throw cause;
220
+ throw corruptRegistry(cause);
221
+ }
222
+ }
223
+
224
+ function validateRegistryNamespace(
225
+ candidate: unknown,
226
+ names: Set<string>,
227
+ storeNames: Set<string>,
228
+ ): void {
229
+ if (typeof candidate !== 'object' || candidate === null) {
230
+ throw new TypeError('invalid namespace entry');
231
+ }
232
+ const namespace: unknown = Reflect.get(candidate, 'namespace');
233
+ const legacyClaimedBySubject: unknown = Reflect.get(candidate, 'legacyClaimedBySubject');
234
+ const subjects: unknown = Reflect.get(candidate, 'subjects');
235
+ if (
236
+ typeof namespace !== 'string' ||
237
+ namespace.trim().length === 0 ||
238
+ names.has(namespace) ||
239
+ (legacyClaimedBySubject !== null &&
240
+ (typeof legacyClaimedBySubject !== 'string' || legacyClaimedBySubject.trim().length === 0)) ||
241
+ !Array.isArray(subjects)
242
+ ) {
243
+ throw new TypeError('invalid namespace metadata');
244
+ }
245
+ names.add(namespace);
246
+
247
+ const subjectNames = new Set<string>();
248
+ const claimed: RegistryEntry[] = [];
249
+ for (const entry of subjects) {
250
+ if (typeof entry !== 'object' || entry === null) {
251
+ throw new TypeError('invalid subject entry');
252
+ }
253
+ const subject: unknown = Reflect.get(entry, 'subject');
254
+ const storeName: unknown = Reflect.get(entry, 'storeName');
255
+ const claimedLegacy: unknown = Reflect.get(entry, 'claimedLegacy');
256
+ if (
257
+ typeof subject !== 'string' ||
258
+ subject.trim().length === 0 ||
259
+ subjectNames.has(subject) ||
260
+ typeof storeName !== 'string' ||
261
+ storeName.trim().length === 0 ||
262
+ typeof claimedLegacy !== 'boolean' ||
263
+ storeNames.has(storeName)
264
+ ) {
265
+ throw new TypeError('invalid subject metadata');
266
+ }
267
+ subjectNames.add(subject);
268
+ storeNames.add(storeName);
269
+ if (claimedLegacy) claimed.push(entry as RegistryEntry);
270
+ }
271
+ if (
272
+ (legacyClaimedBySubject === null && claimed.length !== 0) ||
273
+ (legacyClaimedBySubject !== null &&
274
+ (claimed.length > 1 ||
275
+ (claimed.length === 1 && claimed[0]?.subject !== legacyClaimedBySubject)))
276
+ ) {
277
+ throw new TypeError('inconsistent legacy ownership metadata');
278
+ }
279
+ }
280
+
281
+ const registryQueues = new WeakMap<object, Promise<void>>();
282
+
283
+ function withRegistryLock<TResult>(
284
+ registry: ScopedPersistenceRegistryStore,
285
+ operation: () => Promise<TResult>,
286
+ ): Promise<TResult> {
287
+ const previous = registryQueues.get(registry) ?? Promise.resolve();
288
+ const result = previous.then(operation);
289
+ registryQueues.set(
290
+ registry,
291
+ result.then(
292
+ () => undefined,
293
+ () => undefined,
294
+ ),
295
+ );
296
+ return result;
297
+ }
298
+
299
+ function findNamespace(
300
+ registry: PersistenceRegistry,
301
+ namespace: string,
302
+ ): RegistryNamespace | undefined {
303
+ return registry.namespaces.find((candidate) => candidate.namespace === namespace);
304
+ }
305
+
306
+ function canClaimLegacy(inspection: LegacyStoreInspection): boolean {
307
+ return (
308
+ inspection.exists &&
309
+ (inspection.ownership === 'claimable' || inspection.ownership === 'current-subject')
310
+ );
311
+ }
312
+
313
+ async function resolveScopedStoreLocked(
314
+ options: ResolveScopedStoreOptions,
315
+ ): Promise<ResolvedScopedStore> {
316
+ const namespaceName = requiredIdentityPart(options.namespace, 'Persistence namespace');
317
+ const subject = requiredIdentityPart(options.subject, 'Authenticated subject');
318
+ const registry = parseRegistry(await options.registry.read());
319
+ let namespace = findNamespace(registry, namespaceName);
320
+ const existing = namespace?.subjects.find((entry) => entry.subject === subject);
321
+ if (existing !== undefined) {
322
+ if (existing.claimedLegacy) {
323
+ if (options.legacyStoreName === undefined || existing.storeName !== options.legacyStoreName) {
324
+ throw corruptRegistry();
325
+ }
326
+ } else if (
327
+ existing.storeName !==
328
+ (await deriveScopedStoreName(namespaceName, subject, options.digest ?? sha256))
329
+ ) {
330
+ throw corruptRegistry();
331
+ }
332
+ return { storeName: existing.storeName, claimedLegacy: existing.claimedLegacy };
333
+ }
334
+
335
+ if (namespace === undefined) {
336
+ namespace = { namespace: namespaceName, legacyClaimedBySubject: null, subjects: [] };
337
+ registry.namespaces.push(namespace);
338
+ }
339
+
340
+ let storeName = await deriveScopedStoreName(namespaceName, subject, options.digest ?? sha256);
341
+ let claimedLegacy = false;
342
+ if (
343
+ namespace.legacyClaimedBySubject === null &&
344
+ options.legacyStoreName !== undefined &&
345
+ options.inspectLegacy !== undefined
346
+ ) {
347
+ requiredIdentityPart(options.legacyStoreName, 'Legacy store name');
348
+ const inspection = await options.inspectLegacy(subject);
349
+ if (canClaimLegacy(inspection)) {
350
+ storeName = options.legacyStoreName;
351
+ claimedLegacy = true;
352
+ namespace.legacyClaimedBySubject = subject;
353
+ }
354
+ }
355
+
356
+ const storeAlreadyRegistered = registry.namespaces.some((candidate) =>
357
+ candidate.subjects.some((entry) => entry.storeName === storeName),
358
+ );
359
+ if (storeAlreadyRegistered) throw corruptRegistry();
360
+
361
+ namespace.subjects.push({ subject, storeName, claimedLegacy });
362
+ await options.registry.write(JSON.stringify(registry));
363
+ return { storeName, claimedLegacy };
364
+ }
365
+
366
+ /** Resolves or atomically records one authenticated subject's local partition. */
367
+ export function resolveScopedStore(
368
+ options: ResolveScopedStoreOptions,
369
+ ): Promise<ResolvedScopedStore> {
370
+ return withRegistryLock(options.registry, () => resolveScopedStoreLocked(options));
371
+ }
372
+
373
+ export interface RemoveScopedPersistenceRegistryEntryOptions {
374
+ readonly namespace: string;
375
+ readonly subject: string;
376
+ readonly registry: ScopedPersistenceRegistryStore;
377
+ }
378
+
379
+ async function removeScopedPersistenceRegistryEntryLocked(
380
+ options: RemoveScopedPersistenceRegistryEntryOptions,
381
+ ): Promise<boolean> {
382
+ const namespaceName = requiredIdentityPart(options.namespace, 'Persistence namespace');
383
+ const subject = requiredIdentityPart(options.subject, 'Authenticated subject');
384
+ const registry = parseRegistry(await options.registry.read());
385
+ const namespace = findNamespace(registry, namespaceName);
386
+ if (namespace === undefined) return false;
387
+
388
+ const entryIndex = namespace.subjects.findIndex((entry) => entry.subject === subject);
389
+ if (entryIndex === -1) return false;
390
+ namespace.subjects.splice(entryIndex, 1);
391
+ if (namespace.subjects.length === 0 && namespace.legacyClaimedBySubject === null) {
392
+ const namespaceIndex = registry.namespaces.indexOf(namespace);
393
+ registry.namespaces.splice(namespaceIndex, 1);
394
+ }
395
+ await options.registry.write(JSON.stringify(registry));
396
+ return true;
397
+ }
398
+
399
+ /** Removes one subject mapping without exposing serialized registry metadata. */
400
+ export function removeScopedPersistenceRegistryEntry(
401
+ options: RemoveScopedPersistenceRegistryEntryOptions,
402
+ ): Promise<boolean> {
403
+ return withRegistryLock(options.registry, () =>
404
+ removeScopedPersistenceRegistryEntryLocked(options),
405
+ );
406
+ }
407
+
408
+ export interface ClosableScopedPersistence {
409
+ close(): Promise<void>;
410
+ }
411
+
412
+ export interface OpenScopedPersistenceContext {
413
+ readonly subject: string;
414
+ readonly storeName: string;
415
+ }
416
+
417
+ export interface ScopedPersistencePartition<
418
+ TPersistence extends ClosableScopedPersistence,
419
+ > extends OpenScopedPersistenceContext {
420
+ readonly persistence: TPersistence;
421
+ }
422
+
423
+ export type ScopedPersistenceLifecycleState<TPersistence extends ClosableScopedPersistence> =
424
+ | { readonly status: 'signed-out' }
425
+ | { readonly status: 'initializing'; readonly subject: string }
426
+ | {
427
+ readonly status: 'ready';
428
+ readonly partition: ScopedPersistencePartition<TPersistence>;
429
+ }
430
+ | {
431
+ readonly status: 'blocked';
432
+ readonly reason: 'identity-mismatch' | 'initialization-failed' | 'session-expired';
433
+ readonly error: Error;
434
+ };
435
+
436
+ export interface ScopedPersistenceLifecycleOptions<
437
+ TPersistence extends ClosableScopedPersistence,
438
+ > extends Omit<ResolveScopedStoreOptions, 'subject'> {
439
+ /** Overrides registry resolution while retaining lifecycle transition guarantees. */
440
+ readonly resolveStore?: ScopedPersistenceResolver;
441
+ readonly open: (context: OpenScopedPersistenceContext) => Promise<TPersistence>;
442
+ /** Deletes a closed persistence partition. Required by eraseActivePartition. */
443
+ readonly erase?: (context: OpenScopedPersistenceContext) => Promise<void>;
444
+ readonly resetUserScopedState: () => MaybePromise<void>;
445
+ }
446
+
447
+ /**
448
+ * Serializes identity transitions, hides stale handles immediately, and only
449
+ * publishes a partition after the product's open/migrate/hydrate hook resolves.
450
+ */
451
+ export class ScopedPersistenceLifecycle<TPersistence extends ClosableScopedPersistence> {
452
+ private activePartition: ScopedPersistencePartition<TPersistence> | undefined;
453
+ private transitionTail: Promise<void> = Promise.resolve();
454
+ private revision = 0;
455
+ private lifecycleState: ScopedPersistenceLifecycleState<TPersistence> = {
456
+ status: 'signed-out',
457
+ };
458
+
459
+ public constructor(private readonly options: ScopedPersistenceLifecycleOptions<TPersistence>) {}
460
+
461
+ public get state(): ScopedPersistenceLifecycleState<TPersistence> {
462
+ return this.lifecycleState;
463
+ }
464
+
465
+ /** Returns no persistence while a transition is pending or blocked. */
466
+ public current(): ScopedPersistencePartition<TPersistence> | undefined {
467
+ return this.lifecycleState.status === 'ready' ? this.activePartition : undefined;
468
+ }
469
+
470
+ public selectSubject(
471
+ subject: string,
472
+ ): Promise<ScopedPersistencePartition<TPersistence> | undefined> {
473
+ requiredIdentityPart(subject, 'Authenticated subject');
474
+ if (this.lifecycleState.status === 'ready' && this.activePartition?.subject === subject) {
475
+ return Promise.resolve(this.activePartition);
476
+ }
477
+ const revision = ++this.revision;
478
+ this.lifecycleState = { status: 'initializing', subject };
479
+ return this.enqueue(() => this.selectSubjectLocked(subject, revision));
480
+ }
481
+
482
+ public clear(): Promise<void> {
483
+ const revision = ++this.revision;
484
+ this.lifecycleState = { status: 'signed-out' };
485
+ return this.enqueue(async () => {
486
+ await this.closeAndReset();
487
+ if (revision === this.revision) this.lifecycleState = { status: 'signed-out' };
488
+ });
489
+ }
490
+
491
+ /** Closes and deletes the active partition, then removes its registry mapping. */
492
+ public eraseActivePartition(): Promise<boolean> {
493
+ const partition = this.current();
494
+ if (partition === undefined) return Promise.resolve(false);
495
+ const erase = this.options.erase;
496
+ if (erase === undefined) {
497
+ return Promise.reject(
498
+ new Error('Active partition erasure requires a configured persistence erase hook.'),
499
+ );
500
+ }
501
+
502
+ const revision = ++this.revision;
503
+ this.activePartition = undefined;
504
+ this.lifecycleState = { status: 'signed-out' };
505
+ return this.enqueue(async () => {
506
+ await this.closePartitionAndReset(partition);
507
+ await erase({ subject: partition.subject, storeName: partition.storeName });
508
+ await removeScopedPersistenceRegistryEntry({
509
+ namespace: this.options.namespace,
510
+ subject: partition.subject,
511
+ registry: this.options.registry,
512
+ });
513
+ if (revision === this.revision) this.lifecycleState = { status: 'signed-out' };
514
+ return true;
515
+ });
516
+ }
517
+
518
+ /** Terminal auth expiry closes the current partition and remains blocked. */
519
+ public handleSessionExpired(): Promise<void> {
520
+ const revision = ++this.revision;
521
+ const error = new Error('The authenticated session expired; sign in again to continue.');
522
+ this.lifecycleState = { status: 'blocked', reason: 'session-expired', error };
523
+ return this.enqueue(async () => {
524
+ await this.closeAndReset();
525
+ if (revision === this.revision) {
526
+ this.lifecycleState = { status: 'blocked', reason: 'session-expired', error };
527
+ }
528
+ });
529
+ }
530
+
531
+ /** Blocks an already-open partition after a server subject recheck fails. */
532
+ public blockIdentityMismatch(error: PersistenceIdentityMismatchError): Promise<void> {
533
+ const revision = ++this.revision;
534
+ this.lifecycleState = { status: 'blocked', reason: 'identity-mismatch', error };
535
+ return this.enqueue(async () => {
536
+ await this.closeAndReset();
537
+ if (revision === this.revision) {
538
+ this.lifecycleState = { status: 'blocked', reason: 'identity-mismatch', error };
539
+ }
540
+ });
541
+ }
542
+
543
+ private enqueue<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
544
+ const result = this.transitionTail.then(operation);
545
+ this.transitionTail = result.then(
546
+ () => undefined,
547
+ () => undefined,
548
+ );
549
+ return result;
550
+ }
551
+
552
+ private async selectSubjectLocked(
553
+ subject: string,
554
+ revision: number,
555
+ ): Promise<ScopedPersistencePartition<TPersistence> | undefined> {
556
+ try {
557
+ await this.closeAndReset();
558
+ if (revision !== this.revision) return undefined;
559
+ const resolved =
560
+ this.options.resolveStore === undefined
561
+ ? await resolveScopedStore({ ...this.options, subject })
562
+ : await this.options.resolveStore(subject);
563
+ requiredIdentityPart(resolved.storeName, 'Resolved persistence store name');
564
+ if (revision !== this.revision) return undefined;
565
+ const persistence = await this.options.open({
566
+ subject,
567
+ storeName: resolved.storeName,
568
+ });
569
+ if (revision !== this.revision) {
570
+ await persistence.close();
571
+ await this.options.resetUserScopedState();
572
+ return undefined;
573
+ }
574
+ const partition = { subject, storeName: resolved.storeName, persistence };
575
+ this.activePartition = partition;
576
+ this.lifecycleState = { status: 'ready', partition };
577
+ return partition;
578
+ } catch (cause) {
579
+ if (revision === this.revision) {
580
+ const error =
581
+ cause instanceof Error ? cause : new Error('Local data initialization failed.');
582
+ this.lifecycleState = {
583
+ status: 'blocked',
584
+ reason: isPersistenceIdentityMismatchError(cause)
585
+ ? 'identity-mismatch'
586
+ : 'initialization-failed',
587
+ error,
588
+ };
589
+ }
590
+ throw cause;
591
+ }
592
+ }
593
+
594
+ private async closeAndReset(): Promise<void> {
595
+ const partition = this.activePartition;
596
+ this.activePartition = undefined;
597
+ await this.closePartitionAndReset(partition);
598
+ }
599
+
600
+ private async closePartitionAndReset(
601
+ partition: ScopedPersistencePartition<TPersistence> | undefined,
602
+ ): Promise<void> {
603
+ let closeFailure: unknown;
604
+ try {
605
+ await partition?.persistence.close();
606
+ } catch (cause) {
607
+ closeFailure = cause;
608
+ } finally {
609
+ await this.options.resetUserScopedState();
610
+ }
611
+ if (closeFailure !== undefined) {
612
+ throw closeFailure instanceof Error
613
+ ? closeFailure
614
+ : new Error('Closing the active local-data partition failed.');
615
+ }
616
+ }
617
+ }
618
+
619
+ export interface RecheckServerSubjectOptions<TResult> {
620
+ readonly partitionSubject: string;
621
+ readonly readServerSubject: () => Promise<string>;
622
+ readonly adopt: () => MaybePromise<TResult>;
623
+ }
624
+
625
+ /** Performs the final subject check before sync adoption or an outbox push. */
626
+ export async function recheckServerSubjectBeforeSyncAdoption<TResult>(
627
+ options: RecheckServerSubjectOptions<TResult>,
628
+ ): Promise<TResult> {
629
+ requiredIdentityPart(options.partitionSubject, 'Partition subject');
630
+ const serverSubject = await options.readServerSubject();
631
+ if (serverSubject.trim().length === 0 || serverSubject !== options.partitionSubject) {
632
+ throw new PersistenceIdentityMismatchError(
633
+ 'The server identity does not match the active local-data partition.',
634
+ );
635
+ }
636
+ return options.adopt();
637
+ }