@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.
- package/dist/erasure.d.ts +1 -1
- package/dist/erasure.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/contracts.ts +160 -0
- package/src/durable-draft.test.ts +1214 -0
- package/src/durable-draft.ts +502 -0
- package/src/erasure.test.ts +229 -0
- package/src/erasure.ts +162 -0
- package/src/export.test.ts +167 -0
- package/src/export.ts +164 -0
- package/src/identity.test.ts +465 -0
- package/src/identity.ts +637 -0
- package/src/import-envelope.test.ts +290 -0
- package/src/import-envelope.ts +264 -0
- package/src/import-envelope.vitest.ts +115 -0
- package/src/index.ts +7 -0
- package/src/limits-policy.test.ts +145 -0
- package/src/limits.test.ts +170 -0
- package/src/limits.ts +329 -0
- package/src/memory.test.ts +49 -0
- package/src/memory.ts +375 -0
- package/src/revisioned-drafts.fixture.test.ts +247 -0
- package/src/revisioned-writes.test.ts +684 -0
- package/src/revisioned-writes.ts +374 -0
- package/src/vitest.ts +614 -0
- package/src/web-storage.test.ts +95 -0
- package/src/web-storage.ts +88 -0
package/src/export.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
export interface CsvNumericCell {
|
|
2
|
+
readonly numeric: string;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export type CsvCell = string | number | CsvNumericCell | null;
|
|
6
|
+
|
|
7
|
+
export interface EncodeCsvOptions {
|
|
8
|
+
readonly neutralizeFormulas?: boolean;
|
|
9
|
+
readonly byteOrderMark?: boolean;
|
|
10
|
+
/** Quotes every text and numeric cell. Null cells stay unquoted, so a reader can tell them from empty text. */
|
|
11
|
+
readonly quoteAllCells?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Written unquoted for a null cell; a text cell with the same content is quoted. Must be non-empty
|
|
14
|
+
* and free of double quotes, commas, CR, and LF.
|
|
15
|
+
*/
|
|
16
|
+
readonly nullMarker?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type CsvEncodeErrorCode = 'invalid_numeric_cell' | 'invalid_unicode' | 'unsupported_cell';
|
|
20
|
+
|
|
21
|
+
export class CsvEncodeError extends Error {
|
|
22
|
+
public override readonly name = 'CsvEncodeError';
|
|
23
|
+
public readonly code: CsvEncodeErrorCode;
|
|
24
|
+
public readonly rowIndex: number;
|
|
25
|
+
public readonly columnIndex: number;
|
|
26
|
+
|
|
27
|
+
public constructor(code: CsvEncodeErrorCode, rowIndex: number, columnIndex: number) {
|
|
28
|
+
super(`CSV cell rejected: ${code} at row ${String(rowIndex)}, column ${String(columnIndex)}`);
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.rowIndex = rowIndex;
|
|
31
|
+
this.columnIndex = columnIndex;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const SHARE_OUTCOMES = ['shared', 'saved', 'cancelled', 'unavailable', 'failed'] as const;
|
|
36
|
+
|
|
37
|
+
export type ShareOutcome = (typeof SHARE_OUTCOMES)[number];
|
|
38
|
+
|
|
39
|
+
const BYTE_ORDER_MARK_CODE_POINT = 0xfeff;
|
|
40
|
+
const BYTE_ORDER_MARK = String.fromCodePoint(BYTE_ORDER_MARK_CODE_POINT);
|
|
41
|
+
const RECORD_SEPARATOR = '\r\n';
|
|
42
|
+
const FORMULA_ESCAPE = "'";
|
|
43
|
+
const NUMERIC_PATTERN = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;
|
|
44
|
+
const QUOTE_REQUIRED_PATTERN = /[",\r\n]/;
|
|
45
|
+
const HIGH_SURROGATE_MIN = 0xd800;
|
|
46
|
+
const HIGH_SURROGATE_MAX = 0xdbff;
|
|
47
|
+
const LOW_SURROGATE_MIN = 0xdc00;
|
|
48
|
+
const LOW_SURROGATE_MAX = 0xdfff;
|
|
49
|
+
const LEADING_WHITESPACE_PATTERN = /^[ \t\r\n]*/;
|
|
50
|
+
const FORMULA_TRIGGERS = new Set(['=', '+', '-', '@']);
|
|
51
|
+
const CONTROL_TRIGGERS = new Set(['\t', '\r']);
|
|
52
|
+
|
|
53
|
+
type EncodedCell =
|
|
54
|
+
| { readonly kind: 'null' }
|
|
55
|
+
| { readonly kind: 'text'; readonly value: string }
|
|
56
|
+
| { readonly kind: 'numeric'; readonly value: string };
|
|
57
|
+
|
|
58
|
+
interface WritePolicy {
|
|
59
|
+
readonly neutralizeFormulas: boolean;
|
|
60
|
+
readonly quoteAllCells: boolean;
|
|
61
|
+
readonly nullMarker: string | undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function csvNumeric(value: string): CsvNumericCell {
|
|
65
|
+
return { numeric: value };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function encodeCsv(
|
|
69
|
+
rows: Iterable<readonly CsvCell[]>,
|
|
70
|
+
options: EncodeCsvOptions = {},
|
|
71
|
+
): string {
|
|
72
|
+
const policy = writePolicy(options);
|
|
73
|
+
let output = options.byteOrderMark === true ? BYTE_ORDER_MARK : '';
|
|
74
|
+
let rowIndex = 0;
|
|
75
|
+
for (const row of rows) {
|
|
76
|
+
output += encodeRecord(row, rowIndex, policy) + RECORD_SEPARATOR;
|
|
77
|
+
rowIndex += 1;
|
|
78
|
+
}
|
|
79
|
+
return output;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function writePolicy(options: EncodeCsvOptions): WritePolicy {
|
|
83
|
+
const { nullMarker } = options;
|
|
84
|
+
if (nullMarker !== undefined && (nullMarker === '' || QUOTE_REQUIRED_PATTERN.test(nullMarker))) {
|
|
85
|
+
throw new RangeError(
|
|
86
|
+
'CSV null marker must be non-empty and free of double quotes, commas, CR, and LF.',
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
neutralizeFormulas: options.neutralizeFormulas ?? true,
|
|
91
|
+
quoteAllCells: options.quoteAllCells ?? false,
|
|
92
|
+
nullMarker,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function encodeRecord(row: readonly CsvCell[], rowIndex: number, policy: WritePolicy): string {
|
|
97
|
+
const record = row
|
|
98
|
+
.map((cell, columnIndex) => writeCell(classifyCell(cell, rowIndex, columnIndex), policy))
|
|
99
|
+
.join(',');
|
|
100
|
+
return row.length === 1 && record === '' ? '""' : record;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function classifyCell(cell: CsvCell, rowIndex: number, columnIndex: number): EncodedCell {
|
|
104
|
+
if (cell === null) return { kind: 'null' };
|
|
105
|
+
if (typeof cell === 'string') {
|
|
106
|
+
if (hasUnpairedSurrogate(cell)) {
|
|
107
|
+
throw new CsvEncodeError('invalid_unicode', rowIndex, columnIndex);
|
|
108
|
+
}
|
|
109
|
+
return { kind: 'text', value: cell };
|
|
110
|
+
}
|
|
111
|
+
const numeric = numericText(cell);
|
|
112
|
+
if (numeric === undefined) throw new CsvEncodeError('unsupported_cell', rowIndex, columnIndex);
|
|
113
|
+
if (!NUMERIC_PATTERN.test(numeric)) {
|
|
114
|
+
throw new CsvEncodeError('invalid_numeric_cell', rowIndex, columnIndex);
|
|
115
|
+
}
|
|
116
|
+
return { kind: 'numeric', value: numeric };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function hasUnpairedSurrogate(value: string): boolean {
|
|
120
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
121
|
+
const unit = value.charCodeAt(index);
|
|
122
|
+
if (isInRange(unit, LOW_SURROGATE_MIN, LOW_SURROGATE_MAX)) return true;
|
|
123
|
+
if (!isInRange(unit, HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX)) continue;
|
|
124
|
+
if (!isInRange(value.charCodeAt(index + 1), LOW_SURROGATE_MIN, LOW_SURROGATE_MAX)) return true;
|
|
125
|
+
index += 1;
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function isInRange(value: number, min: number, max: number): boolean {
|
|
131
|
+
return value >= min && value <= max;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function numericText(cell: unknown): string | undefined {
|
|
135
|
+
if (typeof cell === 'number') return String(cell);
|
|
136
|
+
if (typeof cell !== 'object' || cell === null || !('numeric' in cell)) return undefined;
|
|
137
|
+
const { numeric } = cell;
|
|
138
|
+
return typeof numeric === 'string' ? numeric : undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function writeCell(cell: EncodedCell, policy: WritePolicy): string {
|
|
142
|
+
if (cell.kind === 'null') return policy.nullMarker ?? '';
|
|
143
|
+
if (cell.kind === 'numeric') return policy.quoteAllCells ? quote(cell.value) : cell.value;
|
|
144
|
+
const text =
|
|
145
|
+
policy.neutralizeFormulas && startsLikeFormula(cell.value)
|
|
146
|
+
? FORMULA_ESCAPE + cell.value
|
|
147
|
+
: cell.value;
|
|
148
|
+
return mustQuote(text, policy) ? quote(text) : text;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function mustQuote(text: string, policy: WritePolicy): boolean {
|
|
152
|
+
return policy.quoteAllCells || text === policy.nullMarker || QUOTE_REQUIRED_PATTERN.test(text);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function quote(text: string): string {
|
|
156
|
+
return `"${text.replaceAll('"', '""')}"`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function startsLikeFormula(value: string): boolean {
|
|
160
|
+
const first = value.charAt(0);
|
|
161
|
+
if (CONTROL_TRIGGERS.has(first)) return true;
|
|
162
|
+
const afterWhitespace = value.replace(LEADING_WHITESPACE_PATTERN, '');
|
|
163
|
+
return FORMULA_TRIGGERS.has(afterWhitespace.charAt(0));
|
|
164
|
+
}
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
InMemoryScopedPersistenceRegistryStore,
|
|
5
|
+
PersistenceIdentityMismatchError,
|
|
6
|
+
ScopedPersistenceLifecycle,
|
|
7
|
+
deriveScopedStoreName,
|
|
8
|
+
recheckServerSubjectBeforeSyncAdoption,
|
|
9
|
+
removeScopedPersistenceRegistryEntry,
|
|
10
|
+
resolveScopedStore,
|
|
11
|
+
} from './identity.js';
|
|
12
|
+
|
|
13
|
+
const digest = (value: string): Promise<string> =>
|
|
14
|
+
Promise.resolve(value.endsWith(':account-e') ? 'e'.repeat(64) : 'f'.repeat(64));
|
|
15
|
+
|
|
16
|
+
describe('scoped persistence registry', () => {
|
|
17
|
+
it('derives stable opaque names from an unambiguous namespace and subject encoding', async () => {
|
|
18
|
+
const first = await deriveScopedStoreName('example', 'account-e');
|
|
19
|
+
expect(first).toMatch(/^baukit-scoped-v1-[0-9a-f]{64}$/u);
|
|
20
|
+
await expect(deriveScopedStoreName('example', 'account-e')).resolves.toBe(first);
|
|
21
|
+
await expect(deriveScopedStoreName('exam', 'ple:account-e')).resolves.not.toBe(first);
|
|
22
|
+
await expect(deriveScopedStoreName('', 'account-e')).rejects.toBeInstanceOf(
|
|
23
|
+
PersistenceIdentityMismatchError,
|
|
24
|
+
);
|
|
25
|
+
await expect(deriveScopedStoreName('example', '', digest)).rejects.toMatchObject({
|
|
26
|
+
code: 'persistence_identity_mismatch',
|
|
27
|
+
});
|
|
28
|
+
await expect(
|
|
29
|
+
deriveScopedStoreName('example', 'account-e', () => Promise.resolve('not-sha256')),
|
|
30
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('keeps E -> F -> E mappings stable and serializes a one-time legacy claim', async () => {
|
|
34
|
+
const registry = new InMemoryScopedPersistenceRegistryStore();
|
|
35
|
+
const inspectLegacy = vi.fn(() =>
|
|
36
|
+
Promise.resolve({
|
|
37
|
+
exists: true,
|
|
38
|
+
ownership: 'claimable',
|
|
39
|
+
} as const),
|
|
40
|
+
);
|
|
41
|
+
const base = {
|
|
42
|
+
namespace: 'example',
|
|
43
|
+
registry,
|
|
44
|
+
digest,
|
|
45
|
+
legacyStoreName: 'legacy.db',
|
|
46
|
+
inspectLegacy,
|
|
47
|
+
} as const;
|
|
48
|
+
|
|
49
|
+
const [accountE, accountF] = await Promise.all([
|
|
50
|
+
resolveScopedStore({ ...base, subject: 'account-e' }),
|
|
51
|
+
resolveScopedStore({ ...base, subject: 'account-f' }),
|
|
52
|
+
]);
|
|
53
|
+
expect([accountE, accountF].filter((result) => result.claimedLegacy)).toHaveLength(1);
|
|
54
|
+
expect(new Set([accountE.storeName, accountF.storeName]).size).toBe(2);
|
|
55
|
+
await expect(resolveScopedStore({ ...base, subject: 'account-e' })).resolves.toEqual(accountE);
|
|
56
|
+
await expect(resolveScopedStore({ ...base, subject: 'account-f' })).resolves.toEqual(accountF);
|
|
57
|
+
expect(inspectLegacy).toHaveBeenCalledOnce();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it.each([
|
|
61
|
+
[{ exists: false } as const, false],
|
|
62
|
+
[{ exists: true, ownership: 'ambiguous' } as const, false],
|
|
63
|
+
[{ exists: true, ownership: 'other-subject' } as const, false],
|
|
64
|
+
[{ exists: true, ownership: 'claimable' } as const, true],
|
|
65
|
+
[{ exists: true, ownership: 'current-subject' } as const, true],
|
|
66
|
+
])('applies explicit legacy ownership rules to %j', async (inspection, claimedLegacy) => {
|
|
67
|
+
const result = await resolveScopedStore({
|
|
68
|
+
namespace: `legacy-${inspection.exists ? inspection.ownership : 'missing'}`,
|
|
69
|
+
subject: 'account-e',
|
|
70
|
+
registry: new InMemoryScopedPersistenceRegistryStore(),
|
|
71
|
+
digest,
|
|
72
|
+
legacyStoreName: 'legacy.db',
|
|
73
|
+
inspectLegacy: () => Promise.resolve(inspection),
|
|
74
|
+
});
|
|
75
|
+
expect(result.claimedLegacy).toBe(claimedLegacy);
|
|
76
|
+
expect(result.storeName === 'legacy.db').toBe(claimedLegacy);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it.each([
|
|
80
|
+
'{truncated',
|
|
81
|
+
JSON.stringify({ version: 2, namespaces: [] }),
|
|
82
|
+
JSON.stringify({ version: 1, namespaces: 'invalid' }),
|
|
83
|
+
JSON.stringify({
|
|
84
|
+
version: 1,
|
|
85
|
+
namespaces: [
|
|
86
|
+
{
|
|
87
|
+
namespace: 'example',
|
|
88
|
+
legacyClaimedBySubject: null,
|
|
89
|
+
subjects: [{ subject: 'account-e', storeName: 'legacy.db', claimedLegacy: true }],
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
}),
|
|
93
|
+
JSON.stringify({
|
|
94
|
+
version: 1,
|
|
95
|
+
namespaces: [
|
|
96
|
+
{
|
|
97
|
+
namespace: 'example',
|
|
98
|
+
legacyClaimedBySubject: null,
|
|
99
|
+
subjects: [
|
|
100
|
+
{
|
|
101
|
+
subject: 'account-e',
|
|
102
|
+
storeName: `baukit-scoped-v1-${'e'.repeat(64)}`,
|
|
103
|
+
claimedLegacy: false,
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
subject: 'account-f',
|
|
107
|
+
storeName: `baukit-scoped-v1-${'e'.repeat(64)}`,
|
|
108
|
+
claimedLegacy: false,
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
}),
|
|
114
|
+
])('fails closed for corrupt registry metadata', async (serialized) => {
|
|
115
|
+
const inspectLegacy = vi.fn();
|
|
116
|
+
await expect(
|
|
117
|
+
resolveScopedStore({
|
|
118
|
+
namespace: 'example',
|
|
119
|
+
subject: 'account-e',
|
|
120
|
+
registry: new InMemoryScopedPersistenceRegistryStore(serialized),
|
|
121
|
+
digest,
|
|
122
|
+
inspectLegacy,
|
|
123
|
+
legacyStoreName: 'legacy.db',
|
|
124
|
+
}),
|
|
125
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
126
|
+
expect(inspectLegacy).not.toHaveBeenCalled();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('rejects a claimed legacy mapping unless its configured name still matches', async () => {
|
|
130
|
+
const serialized = JSON.stringify({
|
|
131
|
+
version: 1,
|
|
132
|
+
namespaces: [
|
|
133
|
+
{
|
|
134
|
+
namespace: 'example',
|
|
135
|
+
legacyClaimedBySubject: 'account-e',
|
|
136
|
+
subjects: [{ subject: 'account-e', storeName: 'forged.db', claimedLegacy: true }],
|
|
137
|
+
},
|
|
138
|
+
],
|
|
139
|
+
});
|
|
140
|
+
const registry = new InMemoryScopedPersistenceRegistryStore(serialized);
|
|
141
|
+
|
|
142
|
+
await expect(
|
|
143
|
+
resolveScopedStore({ namespace: 'example', subject: 'account-e', registry, digest }),
|
|
144
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
145
|
+
await expect(
|
|
146
|
+
resolveScopedStore({
|
|
147
|
+
namespace: 'example',
|
|
148
|
+
subject: 'account-e',
|
|
149
|
+
registry,
|
|
150
|
+
digest,
|
|
151
|
+
legacyStoreName: 'legacy.db',
|
|
152
|
+
}),
|
|
153
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('rejects duplicate store ownership before recording a legacy claim', async () => {
|
|
157
|
+
const registry = new InMemoryScopedPersistenceRegistryStore();
|
|
158
|
+
const accountE = await resolveScopedStore({
|
|
159
|
+
namespace: 'example',
|
|
160
|
+
subject: 'account-e',
|
|
161
|
+
registry,
|
|
162
|
+
digest,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
await expect(
|
|
166
|
+
resolveScopedStore({
|
|
167
|
+
namespace: 'example',
|
|
168
|
+
subject: 'account-f',
|
|
169
|
+
registry,
|
|
170
|
+
digest,
|
|
171
|
+
legacyStoreName: accountE.storeName,
|
|
172
|
+
inspectLegacy: () => Promise.resolve({ exists: true, ownership: 'claimable' }),
|
|
173
|
+
}),
|
|
174
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('rejects duplicate store ownership across registry namespaces', async () => {
|
|
178
|
+
const serialized = JSON.stringify({
|
|
179
|
+
version: 1,
|
|
180
|
+
namespaces: [
|
|
181
|
+
{
|
|
182
|
+
namespace: 'first',
|
|
183
|
+
legacyClaimedBySubject: 'account-e',
|
|
184
|
+
subjects: [{ subject: 'account-e', storeName: 'legacy.db', claimedLegacy: true }],
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
namespace: 'second',
|
|
188
|
+
legacyClaimedBySubject: 'account-f',
|
|
189
|
+
subjects: [{ subject: 'account-f', storeName: 'legacy.db', claimedLegacy: true }],
|
|
190
|
+
},
|
|
191
|
+
],
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
await expect(
|
|
195
|
+
resolveScopedStore({
|
|
196
|
+
namespace: 'first',
|
|
197
|
+
subject: 'account-e',
|
|
198
|
+
registry: new InMemoryScopedPersistenceRegistryStore(serialized),
|
|
199
|
+
digest,
|
|
200
|
+
legacyStoreName: 'legacy.db',
|
|
201
|
+
}),
|
|
202
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
describe('scoped persistence lifecycle', () => {
|
|
207
|
+
it('closes, deletes, and unregisters the active partition in order', async () => {
|
|
208
|
+
const events: string[] = [];
|
|
209
|
+
const registry = new InMemoryScopedPersistenceRegistryStore();
|
|
210
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
211
|
+
namespace: 'example',
|
|
212
|
+
registry,
|
|
213
|
+
digest,
|
|
214
|
+
open: () =>
|
|
215
|
+
Promise.resolve({
|
|
216
|
+
close: () => {
|
|
217
|
+
events.push('close');
|
|
218
|
+
return Promise.resolve();
|
|
219
|
+
},
|
|
220
|
+
}),
|
|
221
|
+
erase: ({ subject, storeName }) => {
|
|
222
|
+
events.push(`erase:${subject}:${storeName}`);
|
|
223
|
+
return Promise.resolve();
|
|
224
|
+
},
|
|
225
|
+
resetUserScopedState: () => {
|
|
226
|
+
events.push('reset');
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
const partition = await lifecycle.selectSubject('account-e');
|
|
230
|
+
|
|
231
|
+
await expect(lifecycle.eraseActivePartition()).resolves.toBe(true);
|
|
232
|
+
|
|
233
|
+
expect(events).toEqual([
|
|
234
|
+
'reset',
|
|
235
|
+
'close',
|
|
236
|
+
'reset',
|
|
237
|
+
`erase:account-e:${partition?.storeName ?? ''}`,
|
|
238
|
+
]);
|
|
239
|
+
expect(lifecycle.current()).toBeUndefined();
|
|
240
|
+
expect(lifecycle.state).toEqual({ status: 'signed-out' });
|
|
241
|
+
await expect(registry.read()).resolves.toBe('{"version":1,"namespaces":[]}');
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it('treats active-partition erasure without an active partition as a safe no-op', async () => {
|
|
245
|
+
const erase = vi.fn(() => Promise.resolve());
|
|
246
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
247
|
+
namespace: 'example',
|
|
248
|
+
registry: new InMemoryScopedPersistenceRegistryStore(),
|
|
249
|
+
digest,
|
|
250
|
+
open: () => Promise.resolve({ close: () => Promise.resolve() }),
|
|
251
|
+
erase,
|
|
252
|
+
resetUserScopedState: () => undefined,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
await expect(lifecycle.eraseActivePartition()).resolves.toBe(false);
|
|
256
|
+
expect(erase).not.toHaveBeenCalled();
|
|
257
|
+
expect(lifecycle.state).toEqual({ status: 'signed-out' });
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('keeps registry ownership when physical partition deletion fails', async () => {
|
|
261
|
+
const registry = new InMemoryScopedPersistenceRegistryStore();
|
|
262
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
263
|
+
namespace: 'example',
|
|
264
|
+
registry,
|
|
265
|
+
digest,
|
|
266
|
+
open: () => Promise.resolve({ close: () => Promise.resolve() }),
|
|
267
|
+
erase: () => Promise.reject(new Error('delete failed')),
|
|
268
|
+
resetUserScopedState: () => undefined,
|
|
269
|
+
});
|
|
270
|
+
const partition = await lifecycle.selectSubject('account-e');
|
|
271
|
+
|
|
272
|
+
await expect(lifecycle.eraseActivePartition()).rejects.toThrow('delete failed');
|
|
273
|
+
await expect(
|
|
274
|
+
resolveScopedStore({ namespace: 'example', subject: 'account-e', registry, digest }),
|
|
275
|
+
).resolves.toEqual({ storeName: partition?.storeName, claimedLegacy: false });
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('keeps a legacy-claim tombstone after erasing the claiming subject', async () => {
|
|
279
|
+
const registry = new InMemoryScopedPersistenceRegistryStore();
|
|
280
|
+
const inspectLegacy = vi.fn(() =>
|
|
281
|
+
Promise.resolve({ exists: true, ownership: 'claimable' } as const),
|
|
282
|
+
);
|
|
283
|
+
const base = {
|
|
284
|
+
namespace: 'example',
|
|
285
|
+
registry,
|
|
286
|
+
digest,
|
|
287
|
+
legacyStoreName: 'legacy.db',
|
|
288
|
+
inspectLegacy,
|
|
289
|
+
};
|
|
290
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
291
|
+
...base,
|
|
292
|
+
open: () => Promise.resolve({ close: () => Promise.resolve() }),
|
|
293
|
+
erase: () => Promise.resolve(),
|
|
294
|
+
resetUserScopedState: () => undefined,
|
|
295
|
+
});
|
|
296
|
+
await expect(lifecycle.selectSubject('account-e')).resolves.toMatchObject({
|
|
297
|
+
storeName: 'legacy.db',
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
await expect(lifecycle.eraseActivePartition()).resolves.toBe(true);
|
|
301
|
+
await expect(
|
|
302
|
+
removeScopedPersistenceRegistryEntry({
|
|
303
|
+
namespace: 'example',
|
|
304
|
+
subject: 'account-e',
|
|
305
|
+
registry,
|
|
306
|
+
}),
|
|
307
|
+
).resolves.toBe(false);
|
|
308
|
+
|
|
309
|
+
await expect(resolveScopedStore({ ...base, subject: 'account-e' })).resolves.toEqual({
|
|
310
|
+
storeName: `baukit-scoped-v1-${'e'.repeat(64)}`,
|
|
311
|
+
claimedLegacy: false,
|
|
312
|
+
});
|
|
313
|
+
expect(inspectLegacy).toHaveBeenCalledOnce();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('fails closed when registry removal encounters corrupt metadata', async () => {
|
|
317
|
+
await expect(
|
|
318
|
+
removeScopedPersistenceRegistryEntry({
|
|
319
|
+
namespace: 'example',
|
|
320
|
+
subject: 'account-e',
|
|
321
|
+
registry: new InMemoryScopedPersistenceRegistryStore('{truncated'),
|
|
322
|
+
}),
|
|
323
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it('accepts a product compatibility resolver without weakening lifecycle ordering', async () => {
|
|
327
|
+
const persistence = { close: vi.fn(() => Promise.resolve()) };
|
|
328
|
+
const resolveStore = vi.fn(() =>
|
|
329
|
+
Promise.resolve({ storeName: 'pre-v0.6-account-e', claimedLegacy: false }),
|
|
330
|
+
);
|
|
331
|
+
const open = vi.fn(() => Promise.resolve(persistence));
|
|
332
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
333
|
+
namespace: 'example',
|
|
334
|
+
registry: new InMemoryScopedPersistenceRegistryStore('{corrupt'),
|
|
335
|
+
digest,
|
|
336
|
+
resolveStore,
|
|
337
|
+
open,
|
|
338
|
+
resetUserScopedState: () => undefined,
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
await expect(lifecycle.selectSubject('account-e')).resolves.toMatchObject({
|
|
342
|
+
storeName: 'pre-v0.6-account-e',
|
|
343
|
+
persistence,
|
|
344
|
+
});
|
|
345
|
+
expect(resolveStore).toHaveBeenCalledWith('account-e');
|
|
346
|
+
expect(open).toHaveBeenCalledWith({
|
|
347
|
+
subject: 'account-e',
|
|
348
|
+
storeName: 'pre-v0.6-account-e',
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it('does not publish a partition until open and hydration finish', async () => {
|
|
353
|
+
let finishOpen: (() => void) | undefined;
|
|
354
|
+
const opening = new Promise<void>((resolve) => {
|
|
355
|
+
finishOpen = resolve;
|
|
356
|
+
});
|
|
357
|
+
const persistence = { close: vi.fn(() => Promise.resolve()) };
|
|
358
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
359
|
+
namespace: 'example',
|
|
360
|
+
registry: new InMemoryScopedPersistenceRegistryStore(),
|
|
361
|
+
digest,
|
|
362
|
+
resetUserScopedState: () => undefined,
|
|
363
|
+
open: async () => {
|
|
364
|
+
await opening;
|
|
365
|
+
return persistence;
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
const selected = lifecycle.selectSubject('account-e');
|
|
370
|
+
expect(lifecycle.state).toEqual({ status: 'initializing', subject: 'account-e' });
|
|
371
|
+
expect(lifecycle.current()).toBeUndefined();
|
|
372
|
+
await Promise.resolve();
|
|
373
|
+
finishOpen?.();
|
|
374
|
+
await expect(selected).resolves.toMatchObject({ subject: 'account-e', persistence });
|
|
375
|
+
expect(lifecycle.state.status).toBe('ready');
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it('closes and blocks on terminal session expiry without selecting another subject', async () => {
|
|
379
|
+
const close = vi.fn(() => Promise.resolve());
|
|
380
|
+
const open = vi.fn(() => Promise.resolve({ close }));
|
|
381
|
+
const reset = vi.fn();
|
|
382
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
383
|
+
namespace: 'example',
|
|
384
|
+
registry: new InMemoryScopedPersistenceRegistryStore(),
|
|
385
|
+
digest,
|
|
386
|
+
open,
|
|
387
|
+
resetUserScopedState: reset,
|
|
388
|
+
});
|
|
389
|
+
await lifecycle.selectSubject('account-e');
|
|
390
|
+
|
|
391
|
+
await lifecycle.handleSessionExpired();
|
|
392
|
+
|
|
393
|
+
expect(close).toHaveBeenCalledOnce();
|
|
394
|
+
expect(reset).toHaveBeenCalledTimes(2);
|
|
395
|
+
expect(open).toHaveBeenCalledOnce();
|
|
396
|
+
expect(lifecycle.current()).toBeUndefined();
|
|
397
|
+
expect(lifecycle.state).toMatchObject({ status: 'blocked', reason: 'session-expired' });
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
it('serializes concurrent switches and only opens the latest requested subject', async () => {
|
|
401
|
+
let finishClose: (() => void) | undefined;
|
|
402
|
+
const closing = new Promise<void>((resolve) => {
|
|
403
|
+
finishClose = resolve;
|
|
404
|
+
});
|
|
405
|
+
const events: string[] = [];
|
|
406
|
+
let firstOpen = true;
|
|
407
|
+
const lifecycle = new ScopedPersistenceLifecycle({
|
|
408
|
+
namespace: 'example',
|
|
409
|
+
registry: new InMemoryScopedPersistenceRegistryStore(),
|
|
410
|
+
digest,
|
|
411
|
+
open: ({ subject }) => {
|
|
412
|
+
events.push(`open:${subject}`);
|
|
413
|
+
const waitForClose = firstOpen;
|
|
414
|
+
firstOpen = false;
|
|
415
|
+
return Promise.resolve({
|
|
416
|
+
close: async () => {
|
|
417
|
+
events.push(`close:start:${subject}`);
|
|
418
|
+
if (waitForClose) await closing;
|
|
419
|
+
events.push(`close:end:${subject}`);
|
|
420
|
+
},
|
|
421
|
+
});
|
|
422
|
+
},
|
|
423
|
+
resetUserScopedState: () => {
|
|
424
|
+
events.push('reset');
|
|
425
|
+
},
|
|
426
|
+
});
|
|
427
|
+
await lifecycle.selectSubject('account-e');
|
|
428
|
+
|
|
429
|
+
const selectF = lifecycle.selectSubject('account-f');
|
|
430
|
+
await vi.waitFor(() => {
|
|
431
|
+
expect(events).toContain('close:start:account-e');
|
|
432
|
+
});
|
|
433
|
+
const selectE = lifecycle.selectSubject('account-e');
|
|
434
|
+
expect(lifecycle.current()).toBeUndefined();
|
|
435
|
+
expect(lifecycle.state).toEqual({ status: 'initializing', subject: 'account-e' });
|
|
436
|
+
expect(events).not.toContain('open:account-f');
|
|
437
|
+
|
|
438
|
+
finishClose?.();
|
|
439
|
+
await expect(selectF).resolves.toBeUndefined();
|
|
440
|
+
await expect(selectE).resolves.toMatchObject({ subject: 'account-e' });
|
|
441
|
+
expect(events).not.toContain('open:account-f');
|
|
442
|
+
expect(events.indexOf('close:end:account-e')).toBeLessThan(
|
|
443
|
+
events.lastIndexOf('open:account-e'),
|
|
444
|
+
);
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
it('rechecks the exact server subject before adoption', async () => {
|
|
448
|
+
const adopt = vi.fn(() => 'adopted');
|
|
449
|
+
await expect(
|
|
450
|
+
recheckServerSubjectBeforeSyncAdoption({
|
|
451
|
+
partitionSubject: 'account-e',
|
|
452
|
+
readServerSubject: () => Promise.resolve('account-e'),
|
|
453
|
+
adopt,
|
|
454
|
+
}),
|
|
455
|
+
).resolves.toBe('adopted');
|
|
456
|
+
await expect(
|
|
457
|
+
recheckServerSubjectBeforeSyncAdoption({
|
|
458
|
+
partitionSubject: 'account-e',
|
|
459
|
+
readServerSubject: () => Promise.resolve('account-f'),
|
|
460
|
+
adopt,
|
|
461
|
+
}),
|
|
462
|
+
).rejects.toMatchObject({ code: 'persistence_identity_mismatch' });
|
|
463
|
+
expect(adopt).toHaveBeenCalledOnce();
|
|
464
|
+
});
|
|
465
|
+
});
|