@baukit/data-contracts 0.7.1 → 0.7.3

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,229 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import receiptVectors from '../../../../fixtures/erasure/receipts-v1.json' with { type: 'json' };
4
+
5
+ import deletionOutcomeFixtures from '../../../../fixtures/product-experience/deletion-outcomes.json' with { type: 'json' };
6
+
7
+ import {
8
+ AmbiguousProductProfileErasureError,
9
+ type ErasureReceipt,
10
+ type ProductProfileErasureDependencies,
11
+ type ProductProfileErasureResult,
12
+ eraseProductProfile,
13
+ } from './erasure.js';
14
+
15
+ interface DeletionOutcomeFixture {
16
+ readonly name: string;
17
+ readonly serverRetry: 'not-required' | 'retry' | 'reconcile';
18
+ readonly sessionRetained: boolean;
19
+ readonly result: ProductProfileErasureResult;
20
+ }
21
+
22
+ const fixtures = deletionOutcomeFixtures as readonly DeletionOutcomeFixture[];
23
+
24
+ const receipt: ErasureReceipt = { operationId: 'erase-1', status: 'completed' };
25
+
26
+ function namedError(name: string): Error {
27
+ const error = new Error('email=user@example.test token=secret request body resource content');
28
+ error.name = name;
29
+ return error;
30
+ }
31
+
32
+ function expected(name: string): ProductProfileErasureResult {
33
+ const fixture = fixtures.find((candidate) => candidate.name === name);
34
+ if (fixture === undefined) throw new Error(`Missing deletion outcome fixture: ${name}`);
35
+ return fixture.result;
36
+ }
37
+
38
+ function dependencies(outcome: string, events: string[] = []): ProductProfileErasureDependencies {
39
+ return {
40
+ beforeServerErase:
41
+ outcome === 'warnings-only'
42
+ ? [
43
+ () => {
44
+ events.push('before');
45
+ return Promise.reject(namedError('SecretHookError'));
46
+ },
47
+ ]
48
+ : [],
49
+ eraseServerProfile: () => {
50
+ events.push('server');
51
+ if (outcome === 'server-failure') return Promise.reject(namedError('TypeError'));
52
+ if (outcome === 'ambiguous') {
53
+ return Promise.reject(new AmbiguousProductProfileErasureError(namedError('TimeoutError')));
54
+ }
55
+ return Promise.resolve(receipt);
56
+ },
57
+ eraseLocalPartition: () => {
58
+ events.push('local');
59
+ return outcome === 'local-failure'
60
+ ? Promise.reject(namedError('RangeError'))
61
+ : Promise.resolve();
62
+ },
63
+ signOut: () => {
64
+ events.push('sign-out');
65
+ return outcome === 'signout-failure'
66
+ ? Promise.reject(namedError('AbortError'))
67
+ : Promise.resolve();
68
+ },
69
+ };
70
+ }
71
+
72
+ describe('product-profile erasure', () => {
73
+ it.each(receiptVectors.cases)('handles the shared $name receipt', async (vector) => {
74
+ const local = vi.fn().mockResolvedValue(undefined);
75
+ const signOut = vi.fn().mockResolvedValue(undefined);
76
+ const result = await eraseProductProfile({
77
+ eraseServerProfile: (): Promise<ErasureReceipt> => {
78
+ const { status } = vector.receipt;
79
+ if (status !== 'pending' && status !== 'completed') {
80
+ return Promise.reject(new Error('Identity deletion failed'));
81
+ }
82
+ return Promise.resolve({ ...vector.receipt, status });
83
+ },
84
+ eraseLocalPartition: local,
85
+ signOut,
86
+ });
87
+ if (vector.clientOutcome === 'failed') {
88
+ expect(result.status).toBe('server-failure');
89
+ expect(local).not.toHaveBeenCalled();
90
+ expect(signOut).not.toHaveBeenCalled();
91
+ } else {
92
+ expect(result).toEqual({
93
+ status: vector.receipt.status === 'pending' ? 'pending' : 'erased',
94
+ receipt: vector.receipt,
95
+ warnings: [],
96
+ });
97
+ expect(local).toHaveBeenCalledTimes(1);
98
+ expect(signOut).toHaveBeenCalledTimes(1);
99
+ }
100
+ });
101
+
102
+ it.each(fixtures)('matches the shared $name outcome fixture', async (fixture) => {
103
+ await expect(eraseProductProfile(dependencies(fixture.name))).resolves.toEqual(fixture.result);
104
+ });
105
+
106
+ it.each(fixtures)('encodes retry and session expectations for $name', (fixture) => {
107
+ const status = fixture.result.status;
108
+ expect(fixture.serverRetry).toBe(
109
+ status === 'server-failure' ? 'retry' : status === 'ambiguous' ? 'reconcile' : 'not-required',
110
+ );
111
+ expect(fixture.sessionRetained).toBe(
112
+ status === 'server-failure' || status === 'ambiguous' || status === 'signout-failure',
113
+ );
114
+ });
115
+
116
+ it('continues after a failed pre-server hook and reports a safe warning', async () => {
117
+ const events: string[] = [];
118
+ const result = await eraseProductProfile(dependencies('warnings-only', events));
119
+
120
+ expect(result).toEqual(expected('warnings-only'));
121
+ expect(events).toEqual(['before', 'server', 'local', 'sign-out']);
122
+ expect(JSON.stringify(result)).not.toMatch(
123
+ /user@example|secret|request body|resource content/u,
124
+ );
125
+ });
126
+
127
+ it.each(['server-failure', 'ambiguous'])(
128
+ '%s preserves local data and the session',
129
+ async (name) => {
130
+ const events: string[] = [];
131
+
132
+ await expect(eraseProductProfile(dependencies(name, events))).resolves.toEqual(
133
+ expected(name),
134
+ );
135
+ expect(events).toEqual(['server']);
136
+ },
137
+ );
138
+
139
+ it.each([42, '', ' '])(
140
+ 'treats a pending receipt with operation ID %j as an ambiguous response',
141
+ async (operationId) => {
142
+ const events: string[] = [];
143
+ const malformedReceipt: ErasureReceipt = { operationId: 'erase-1', status: 'pending' };
144
+ Reflect.set(malformedReceipt, 'operationId', operationId);
145
+
146
+ await expect(
147
+ eraseProductProfile({
148
+ eraseServerProfile: () => {
149
+ events.push('server');
150
+ return Promise.resolve(malformedReceipt);
151
+ },
152
+ eraseLocalPartition: () => {
153
+ events.push('local');
154
+ return Promise.resolve();
155
+ },
156
+ signOut: () => {
157
+ events.push('sign-out');
158
+ return Promise.resolve();
159
+ },
160
+ }),
161
+ ).resolves.toEqual({
162
+ status: 'ambiguous',
163
+ error: { stage: 'server', cause: 'TypeError' },
164
+ warnings: [],
165
+ });
166
+ expect(events).toEqual(['server']);
167
+ },
168
+ );
169
+
170
+ it.each(['erase-1', null])(
171
+ 'clears local data and signs out for pending operation %j',
172
+ async (operationId) => {
173
+ const events: string[] = [];
174
+ const pending: ErasureReceipt = { operationId, status: 'pending' };
175
+ const result = await eraseProductProfile({
176
+ ...dependencies('success', events),
177
+ eraseServerProfile: () => {
178
+ events.push('server');
179
+ return Promise.resolve(pending);
180
+ },
181
+ });
182
+
183
+ expect(result).toEqual({ status: 'pending', receipt: pending, warnings: [] });
184
+ expect(events).toEqual(['server', 'local', 'sign-out']);
185
+ },
186
+ );
187
+
188
+ it.each(['local-failure', 'signout-failure'])(
189
+ 'keeps %s visible after a pending receipt',
190
+ async (outcome) => {
191
+ const events: string[] = [];
192
+ const pending: ErasureReceipt = { operationId: 'erase-1', status: 'pending' };
193
+ const result = await eraseProductProfile({
194
+ ...dependencies(outcome, events),
195
+ eraseServerProfile: () => {
196
+ events.push('server');
197
+ return Promise.resolve(pending);
198
+ },
199
+ });
200
+ expect(result).toMatchObject({ status: outcome, receipt: pending });
201
+ expect(events).toEqual(['server', 'local', 'sign-out']);
202
+ },
203
+ );
204
+
205
+ it('signs out after local deletion fails and keeps both failures visible', async () => {
206
+ const result = await eraseProductProfile({
207
+ ...dependencies('local-failure'),
208
+ signOut: () => Promise.reject(namedError('AbortError')),
209
+ });
210
+
211
+ expect(result).toEqual({
212
+ ...expected('local-failure'),
213
+ signOutError: { stage: 'sign-out', cause: 'AbortError' },
214
+ });
215
+ });
216
+
217
+ it('is safe to invoke repeatedly against idempotent dependencies', async () => {
218
+ const eraseServerProfile = vi.fn(() => Promise.resolve(receipt));
219
+ const eraseLocalPartition = vi.fn(() => Promise.resolve());
220
+ const signOut = vi.fn(() => Promise.resolve());
221
+ const deps = { eraseServerProfile, eraseLocalPartition, signOut };
222
+
223
+ await expect(eraseProductProfile(deps)).resolves.toEqual(expected('success'));
224
+ await expect(eraseProductProfile(deps)).resolves.toEqual(expected('success'));
225
+ expect(eraseServerProfile).toHaveBeenCalledTimes(2);
226
+ expect(eraseLocalPartition).toHaveBeenCalledTimes(2);
227
+ expect(signOut).toHaveBeenCalledTimes(2);
228
+ });
229
+ });
package/src/erasure.ts ADDED
@@ -0,0 +1,162 @@
1
+ /** Server receipt or local fence confirmation. Rust wire receipts always have an operation ID. */
2
+ export type ErasureReceipt =
3
+ | { readonly operationId: string | null; readonly status: 'completed' }
4
+ | { readonly operationId: string | null; readonly status: 'pending' };
5
+
6
+ /** Dependencies for the product-profile erasure sequence. */
7
+ export interface ProductProfileErasureDependencies {
8
+ readonly beforeServerErase?: readonly (() => Promise<void>)[];
9
+ readonly eraseServerProfile: () => Promise<ErasureReceipt>;
10
+ readonly eraseLocalPartition: () => Promise<void>;
11
+ readonly signOut: () => Promise<void>;
12
+ }
13
+
14
+ export type ProductProfileErasureStage = 'before-server' | 'server' | 'local' | 'sign-out';
15
+
16
+ /** Error detail safe to show in diagnostics without user or request content. */
17
+ export interface ProductProfileErasureIssue {
18
+ readonly stage: ProductProfileErasureStage;
19
+ readonly cause: string;
20
+ }
21
+
22
+ export type ProductProfileErasureResult =
23
+ | {
24
+ readonly status: 'erased' | 'pending';
25
+ readonly receipt: ErasureReceipt;
26
+ readonly warnings: readonly ProductProfileErasureIssue[];
27
+ }
28
+ | {
29
+ readonly status: 'server-failure' | 'ambiguous';
30
+ readonly error: ProductProfileErasureIssue;
31
+ readonly warnings: readonly ProductProfileErasureIssue[];
32
+ }
33
+ | {
34
+ readonly status: 'local-failure';
35
+ readonly receipt: ErasureReceipt;
36
+ readonly error: ProductProfileErasureIssue;
37
+ readonly signOutError: ProductProfileErasureIssue | null;
38
+ readonly warnings: readonly ProductProfileErasureIssue[];
39
+ }
40
+ | {
41
+ readonly status: 'signout-failure';
42
+ readonly receipt: ErasureReceipt;
43
+ readonly error: ProductProfileErasureIssue;
44
+ readonly warnings: readonly ProductProfileErasureIssue[];
45
+ };
46
+
47
+ /** Marks a server error whose commit status cannot be determined safely. */
48
+ export class AmbiguousProductProfileErasureError extends Error {
49
+ public override readonly name = 'AmbiguousProductProfileErasureError';
50
+ public readonly code = 'product_profile_erasure_ambiguous' as const;
51
+
52
+ public constructor(cause?: unknown) {
53
+ super('The server erasure outcome is unknown.', cause === undefined ? undefined : { cause });
54
+ }
55
+ }
56
+
57
+ const SAFE_CAUSE_NAMES = new Set([
58
+ 'AbortError',
59
+ 'AggregateError',
60
+ 'Error',
61
+ 'EvalError',
62
+ 'NetworkError',
63
+ 'RangeError',
64
+ 'ReferenceError',
65
+ 'SyntaxError',
66
+ 'TimeoutError',
67
+ 'TypeError',
68
+ 'URIError',
69
+ ]);
70
+
71
+ function causeName(cause: unknown): string {
72
+ if (!(cause instanceof Error)) return 'UnknownError';
73
+ return SAFE_CAUSE_NAMES.has(cause.name) ? cause.name : 'Error';
74
+ }
75
+
76
+ function issue(stage: ProductProfileErasureStage, cause: unknown): ProductProfileErasureIssue {
77
+ return { stage, cause: causeName(cause) };
78
+ }
79
+
80
+ function isAmbiguous(cause: unknown): boolean {
81
+ return (
82
+ cause instanceof AmbiguousProductProfileErasureError ||
83
+ (typeof cause === 'object' &&
84
+ cause !== null &&
85
+ Reflect.get(cause, 'code') === 'product_profile_erasure_ambiguous')
86
+ );
87
+ }
88
+
89
+ function ambiguousCause(cause: unknown): unknown {
90
+ if (cause instanceof Error && cause.cause !== undefined) return cause.cause;
91
+ return cause;
92
+ }
93
+
94
+ function validateErasureReceipt(receipt: unknown): asserts receipt is ErasureReceipt {
95
+ if (typeof receipt !== 'object' || receipt === null) {
96
+ throw new AmbiguousProductProfileErasureError(new TypeError('Invalid erasure receipt.'));
97
+ }
98
+ const operationId: unknown = Reflect.get(receipt, 'operationId');
99
+ const status: unknown = Reflect.get(receipt, 'status');
100
+ const hasOperationId = typeof operationId === 'string' && operationId.trim().length > 0;
101
+ if (
102
+ (status === 'completed' || status === 'pending') &&
103
+ (operationId === null || hasOperationId)
104
+ ) {
105
+ return;
106
+ }
107
+ throw new AmbiguousProductProfileErasureError(new TypeError('Invalid erasure receipt.'));
108
+ }
109
+
110
+ /** Erases a product profile while preserving retryability at the server boundary. */
111
+ export async function eraseProductProfile(
112
+ dependencies: ProductProfileErasureDependencies,
113
+ ): Promise<ProductProfileErasureResult> {
114
+ const warnings: ProductProfileErasureIssue[] = [];
115
+ for (const hook of dependencies.beforeServerErase ?? []) {
116
+ try {
117
+ await hook();
118
+ } catch (cause) {
119
+ warnings.push(issue('before-server', cause));
120
+ }
121
+ }
122
+
123
+ let receipt: ErasureReceipt;
124
+ try {
125
+ const candidate: unknown = await dependencies.eraseServerProfile();
126
+ validateErasureReceipt(candidate);
127
+ receipt = candidate;
128
+ } catch (cause) {
129
+ if (isAmbiguous(cause)) {
130
+ return { status: 'ambiguous', error: issue('server', ambiguousCause(cause)), warnings };
131
+ }
132
+ return { status: 'server-failure', error: issue('server', cause), warnings };
133
+ }
134
+
135
+ let localError: ProductProfileErasureIssue | undefined;
136
+ let signOutError: ProductProfileErasureIssue | undefined;
137
+ try {
138
+ await dependencies.eraseLocalPartition();
139
+ } catch (cause) {
140
+ localError = issue('local', cause);
141
+ } finally {
142
+ try {
143
+ await dependencies.signOut();
144
+ } catch (cause) {
145
+ signOutError = issue('sign-out', cause);
146
+ }
147
+ }
148
+
149
+ if (localError !== undefined) {
150
+ return {
151
+ status: 'local-failure',
152
+ receipt,
153
+ error: localError,
154
+ signOutError: signOutError ?? null,
155
+ warnings,
156
+ };
157
+ }
158
+ if (signOutError !== undefined) {
159
+ return { status: 'signout-failure', receipt, error: signOutError, warnings };
160
+ }
161
+ return { status: receipt.status === 'pending' ? 'pending' : 'erased', receipt, warnings };
162
+ }
@@ -0,0 +1,167 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import fixtureCorpus from '../../../../fixtures/export-csv/csv-encoding-v1.json' with { type: 'json' };
4
+
5
+ import {
6
+ CsvEncodeError,
7
+ SHARE_OUTCOMES,
8
+ type CsvCell,
9
+ type EncodeCsvOptions,
10
+ type ShareOutcome,
11
+ csvNumeric,
12
+ encodeCsv,
13
+ } from './export.js';
14
+
15
+ type FixtureCell = string | null | { readonly numeric: string };
16
+
17
+ interface FixtureCase {
18
+ readonly name: string;
19
+ readonly options?: EncodeCsvOptions;
20
+ readonly rows: readonly (readonly FixtureCell[])[];
21
+ }
22
+
23
+ interface FixtureCorpus {
24
+ readonly version: number;
25
+ readonly byteOrderMarkCodePoint: number;
26
+ readonly cases: readonly (FixtureCase & { readonly csv: string })[];
27
+ readonly rejections: readonly (FixtureCase & {
28
+ readonly error: {
29
+ readonly code: string;
30
+ readonly rowIndex: number;
31
+ readonly columnIndex: number;
32
+ };
33
+ })[];
34
+ }
35
+
36
+ const corpus = fixtureCorpus as FixtureCorpus;
37
+ const byteOrderMark = String.fromCodePoint(corpus.byteOrderMarkCodePoint);
38
+
39
+ function expectedOutput(csv: string, options: EncodeCsvOptions | undefined): string {
40
+ return options?.byteOrderMark === true ? byteOrderMark + csv : csv;
41
+ }
42
+
43
+ function rejection(rows: readonly (readonly CsvCell[])[]): CsvEncodeError {
44
+ try {
45
+ encodeCsv(rows);
46
+ } catch (error) {
47
+ if (error instanceof CsvEncodeError) return error;
48
+ throw error;
49
+ }
50
+ throw new Error('Expected encodeCsv to reject');
51
+ }
52
+
53
+ describe('shared CSV vectors', () => {
54
+ it('uses version 1 and covers every case group', () => {
55
+ expect(corpus.version).toBe(1);
56
+ expect(corpus.cases.length).toBeGreaterThan(0);
57
+ expect(corpus.rejections.length).toBeGreaterThan(0);
58
+ expect(corpus.byteOrderMarkCodePoint).toBe(0xfeff);
59
+ });
60
+
61
+ it.each(corpus.cases)('encodes $name', ({ rows, options, csv }) => {
62
+ expect(encodeCsv(rows, options)).toBe(expectedOutput(csv, options));
63
+ });
64
+
65
+ it('starts with U+FEFF only when the byte-order mark is requested', () => {
66
+ expect(encodeCsv([['a']], { byteOrderMark: true }).codePointAt(0)).toBe(0xfeff);
67
+ expect(encodeCsv([['a']]).codePointAt(0)).toBe('a'.codePointAt(0));
68
+ });
69
+
70
+ it.each(corpus.rejections)('rejects $name', ({ rows, options, error }) => {
71
+ expect(() => encodeCsv(rows, options)).toThrow(
72
+ expect.objectContaining({
73
+ name: 'CsvEncodeError',
74
+ code: error.code,
75
+ rowIndex: error.rowIndex,
76
+ columnIndex: error.columnIndex,
77
+ }),
78
+ );
79
+ });
80
+ });
81
+
82
+ describe('encodeCsv', () => {
83
+ it('writes finite numbers without formula neutralization', () => {
84
+ expect(encodeCsv([[-5, 0, -0, 1.5, 1e21, csvNumeric('-2.50')]])).toBe(
85
+ '-5,0,0,1.5,1e+21,-2.50\r\n',
86
+ );
87
+ });
88
+
89
+ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
90
+ 'rejects the non-finite number %s',
91
+ (value) => {
92
+ expect(rejection([['ok', value]])).toMatchObject({
93
+ code: 'invalid_numeric_cell',
94
+ rowIndex: 0,
95
+ columnIndex: 1,
96
+ });
97
+ },
98
+ );
99
+
100
+ const highSurrogate = String.fromCharCode(0xd800);
101
+ const lowSurrogate = String.fromCharCode(0xdc00);
102
+
103
+ it.each([
104
+ ['a lone high surrogate', `${highSurrogate}secret`],
105
+ ['a lone low surrogate', `secret${lowSurrogate}`],
106
+ ['a trailing high surrogate', `secret${highSurrogate}`],
107
+ ['reversed surrogates', `${lowSurrogate}${highSurrogate}secret`],
108
+ ])('rejects %s without echoing the cell value', (_label, value) => {
109
+ const error = rejection([['ok'], [value]]);
110
+ expect(error).toMatchObject({ code: 'invalid_unicode', rowIndex: 1, columnIndex: 0 });
111
+ expect(error.message).not.toContain('secret');
112
+ });
113
+
114
+ it('keeps paired surrogates', () => {
115
+ expect(encodeCsv([['😀']])).toBe('😀\r\n');
116
+ });
117
+
118
+ it.each([undefined, true, {}, { numeric: 5 }])(
119
+ 'rejects the unsupported runtime cell %s',
120
+ (value) => {
121
+ expect(rejection([[value as unknown as CsvCell]])).toMatchObject({
122
+ code: 'unsupported_cell',
123
+ });
124
+ },
125
+ );
126
+
127
+ it('does not echo rejected numeric text', () => {
128
+ expect(rejection([[csvNumeric('=secret()')]]).message).not.toContain('secret');
129
+ });
130
+
131
+ it.each(['', 'a,b', 'say "null"', 'line\n', 'line\r'])(
132
+ 'rejects the null marker %j before writing',
133
+ (nullMarker) => {
134
+ expect(() => encodeCsv([[null]], { nullMarker })).toThrow(RangeError);
135
+ },
136
+ );
137
+
138
+ it('quotes a neutralized cell that would read as the null marker', () => {
139
+ expect(encodeCsv([[null, '-']], { nullMarker: "'-" })).toBe(`'-,"'-"\r\n`);
140
+ });
141
+
142
+ it('accepts any iterable of rows', () => {
143
+ function* rows(): Generator<readonly CsvCell[]> {
144
+ yield ['id'];
145
+ yield ['=1'];
146
+ }
147
+ expect(encodeCsv(rows())).toBe("id\r\n'=1\r\n");
148
+ });
149
+ });
150
+
151
+ describe('share outcome', () => {
152
+ it('lists every outcome once', () => {
153
+ const outcomes: readonly ShareOutcome[] = SHARE_OUTCOMES;
154
+ expect(outcomes).toEqual(['shared', 'saved', 'cancelled', 'unavailable', 'failed']);
155
+ });
156
+ });
157
+
158
+ it('exports the encoder from the package root and the export entry point', async () => {
159
+ const [root, entry] = await Promise.all([
160
+ import('@baukit/data-contracts'),
161
+ import('@baukit/data-contracts/export'),
162
+ ]);
163
+ expect(root.encodeCsv).toBe(entry.encodeCsv);
164
+ expect(entry.CsvEncodeError).toBeTypeOf('function');
165
+ expect(entry.SHARE_OUTCOMES).toContain('cancelled');
166
+ expect(root.prepareImportEnvelope).toBeTypeOf('function');
167
+ });