-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathcontract.test.ts
More file actions
424 lines (376 loc) · 17.4 KB
/
contract.test.ts
File metadata and controls
424 lines (376 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import { describe, expect, it } from 'bun:test';
import { COMMAND_CATALOG, OPERATION_DESCRIPTION_MAP, OPERATION_EXPECTED_RESULT_MAP } from './command-catalog.js';
import { OPERATION_DEFINITIONS, type ReferenceGroupKey } from './operation-definitions.js';
import { DOCUMENT_API_MEMBER_PATHS, OPERATION_MEMBER_PATH_MAP, memberPathForOperation } from './operation-map.js';
import { OPERATION_REFERENCE_DOC_PATH_MAP, REFERENCE_OPERATION_GROUPS } from './reference-doc-map.js';
import { buildInternalContractSchemas } from './schemas.js';
import { PUBLIC_MUTATION_STEP_OP_IDS, STEP_OP_CATALOG } from './step-op-catalog.js';
import { OPERATION_IDS, PRE_APPLY_THROW_CODES, isValidOperationIdFormat } from './types.js';
import { Z_ORDER_RELATIVE_HEIGHT_MAX, Z_ORDER_RELATIVE_HEIGHT_MIN } from '../images/z-order.js';
describe('document-api contract catalog', () => {
it('keeps operation ids explicit and format-valid', () => {
expect([...new Set(OPERATION_IDS)]).toHaveLength(OPERATION_IDS.length);
for (const operationId of OPERATION_IDS) {
expect(isValidOperationIdFormat(operationId)).toBe(true);
}
});
it('keeps catalog key coverage in lockstep with operation ids', () => {
const catalogKeys = Object.keys(COMMAND_CATALOG).sort();
const operationIds = [...OPERATION_IDS].sort();
expect(catalogKeys).toEqual(operationIds);
});
it('derives member paths from operation ids with no duplicates', () => {
expect(new Set(DOCUMENT_API_MEMBER_PATHS).size).toBe(DOCUMENT_API_MEMBER_PATHS.length);
for (const operationId of OPERATION_IDS) {
expect(typeof memberPathForOperation(operationId)).toBe('string');
}
});
it('keeps reference-doc mappings explicit and coverage-complete', () => {
const operationIds = [...OPERATION_IDS].sort();
const docPathKeys = Object.keys(OPERATION_REFERENCE_DOC_PATH_MAP).sort();
expect(docPathKeys).toEqual(operationIds);
const grouped = REFERENCE_OPERATION_GROUPS.flatMap((group) => group.operations);
expect(grouped).toHaveLength(operationIds.length);
expect(new Set(grouped).size).toBe(grouped.length);
expect([...grouped].sort()).toEqual(operationIds);
});
it('enforces typed throw and post-apply policy metadata for mutation operations', () => {
const validPreApplyThrowCodes = new Set(PRE_APPLY_THROW_CODES);
for (const operationId of OPERATION_IDS) {
const metadata = COMMAND_CATALOG[operationId];
for (const throwCode of metadata.throws.preApply) {
expect(validPreApplyThrowCodes.has(throwCode)).toBe(true);
}
if (!metadata.mutates) continue;
expect(metadata.throws.postApplyForbidden).toBe(true);
}
});
it('includes CAPABILITY_UNAVAILABLE in throws.preApply for all mutation operations', () => {
for (const operationId of OPERATION_IDS) {
const metadata = COMMAND_CATALOG[operationId];
if (!metadata.mutates) continue;
expect(
metadata.throws.preApply,
`${operationId} should include CAPABILITY_UNAVAILABLE in throws.preApply`,
).toContain('CAPABILITY_UNAVAILABLE');
}
});
it('keeps input schemas closed for object-shaped payloads', () => {
const schemas = buildInternalContractSchemas();
for (const operationId of OPERATION_IDS) {
const inputSchema = schemas.operations[operationId].input as { type?: string; additionalProperties?: unknown };
if (inputSchema.type !== 'object') continue;
expect(inputSchema.additionalProperties).toBe(false);
}
});
it('declares insert input as a legacy-text or structural-content union', () => {
const schemas = buildInternalContractSchemas();
const insertInputSchema = schemas.operations.insert.input as {
oneOf?: Array<{
type?: string;
properties?: Record<string, unknown>;
required?: string[];
additionalProperties?: boolean;
}>;
};
expect(Array.isArray(insertInputSchema.oneOf)).toBe(true);
expect(insertInputSchema.oneOf).toHaveLength(2);
const [legacyVariant, structuralVariant] = insertInputSchema.oneOf!;
expect(legacyVariant.type).toBe('object');
expect(Object.keys(legacyVariant.properties!).sort()).toEqual(['target', 'type', 'value']);
expect(legacyVariant.required).toEqual(['value']);
expect(legacyVariant.additionalProperties).toBe(false);
expect((legacyVariant.properties!.target as { $ref?: string }).$ref).toBe('#/$defs/TextAddress');
expect(structuralVariant.type).toBe('object');
expect(Object.keys(structuralVariant.properties!).sort()).toEqual([
'content',
'nestingPolicy',
'placement',
'target',
]);
expect(structuralVariant.required).toEqual(['content']);
expect(structuralVariant.additionalProperties).toBe(false);
expect((structuralVariant.properties!.target as { $ref?: string }).$ref).toBe('#/$defs/BlockNodeAddress');
expect((structuralVariant.properties!.placement as { enum?: string[] }).enum).toEqual([
'before',
'after',
'insideStart',
'insideEnd',
]);
expect(
(
structuralVariant.properties!.nestingPolicy as {
properties?: { tables?: { enum?: string[] } };
}
).properties?.tables?.enum,
).toEqual(['forbid', 'allow']);
});
it('accepts both object and array SDFragment in structural insert content schema', () => {
const schemas = buildInternalContractSchemas();
const insertInput = schemas.operations.insert.input as { oneOf?: Array<{ properties?: Record<string, unknown> }> };
const structuralVariant = insertInput.oneOf![1];
const contentSchema = structuralVariant.properties!.content as { oneOf?: Array<{ type?: string }> };
expect(Array.isArray(contentSchema.oneOf)).toBe(true);
expect(contentSchema.oneOf).toHaveLength(2);
expect(contentSchema.oneOf![0].type).toBe('object');
expect(contentSchema.oneOf![1].type).toBe('array');
});
it('accepts both object and array SDFragment in structural replace content schema', () => {
const schemas = buildInternalContractSchemas();
const replaceInput = schemas.operations.replace.input as {
oneOf?: Array<{ oneOf?: Array<{ properties?: Record<string, unknown> }> }>;
};
// The structural branch is the second oneOf element
const structuralBranch = replaceInput.oneOf![1] as { oneOf?: Array<{ properties?: Record<string, unknown> }> };
for (const variant of structuralBranch.oneOf!) {
const contentSchema = variant.properties!.content as { oneOf?: Array<{ type?: string }> };
expect(Array.isArray(contentSchema.oneOf)).toBe(true);
expect(contentSchema.oneOf).toHaveLength(2);
expect(contentSchema.oneOf![0].type).toBe('object');
expect(contentSchema.oneOf![1].type).toBe('array');
}
});
it('declares UNSUPPORTED_ENVIRONMENT for insert metadata and generated failure schema', () => {
const schemas = buildInternalContractSchemas();
const insertFailureSchema = schemas.operations.insert.failure as {
properties?: {
failure?: {
properties?: {
code?: {
enum?: string[];
};
};
};
};
};
expect(COMMAND_CATALOG.insert.possibleFailureCodes).toContain('UNSUPPORTED_ENVIRONMENT');
expect(insertFailureSchema.properties?.failure?.properties?.code?.enum).toContain('UNSUPPORTED_ENVIRONMENT');
});
it('includes global.history in capabilities.get output schema', () => {
const schemas = buildInternalContractSchemas();
const capabilitiesOutput = schemas.operations['capabilities.get'].output as {
properties?: {
global?: {
properties?: Record<string, unknown>;
required?: string[];
};
};
};
expect(capabilitiesOutput.properties?.global?.properties).toHaveProperty('history');
expect(capabilitiesOutput.properties?.global?.required).toContain('history');
});
it('narrows table operation address schemas to table-specific refs', () => {
const schemas = buildInternalContractSchemas();
const tablesGetInput = schemas.operations['tables.get'].input as {
properties?: { target?: { $ref?: string } };
};
const tablesGetOutput = schemas.operations['tables.get'].output as {
properties?: { address?: { $ref?: string } };
};
const unmergeInput = schemas.operations['tables.unmergeCells'].input as {
oneOf?: Array<Record<string, unknown>>;
};
const setBorderInput = schemas.operations['tables.setBorder'].input as {
properties?: { target?: { $ref?: string } };
};
const insertRowSuccess = schemas.operations['tables.insertRow'].success as {
properties?: { table?: { $ref?: string } };
};
expect(tablesGetInput.properties?.target?.$ref).toBe('#/$defs/TableAddress');
expect(tablesGetOutput.properties?.address?.$ref).toBe('#/$defs/TableAddress');
// unmergeCells input is a oneOf: [cellLocator, tableScopedCellLocator (target), tableScopedCellLocator (nodeId)]
expect(unmergeInput.oneOf).toHaveLength(3);
const [cellBranch, tableTargetBranch, tableNodeIdBranch] = unmergeInput.oneOf as Array<{
properties?: { target?: { $ref?: string }; nodeId?: unknown; rowIndex?: unknown; columnIndex?: unknown };
required?: string[];
}>;
// First branch: direct cell locator (target.$ref → TableCellAddress)
expect(cellBranch.properties?.target?.$ref).toBe('#/$defs/TableCellAddress');
// Second branch: table-scoped with target (target.$ref → TableAddress + coordinates)
expect(tableTargetBranch.properties?.target?.$ref).toBe('#/$defs/TableAddress');
expect(tableTargetBranch.required).toContain('rowIndex');
expect(tableTargetBranch.required).toContain('columnIndex');
// Third branch: table-scoped with nodeId + coordinates
expect(tableNodeIdBranch.properties?.nodeId).toBeDefined();
expect(tableNodeIdBranch.required).toContain('nodeId');
expect(tableNodeIdBranch.required).toContain('rowIndex');
expect(tableNodeIdBranch.required).toContain('columnIndex');
expect(setBorderInput.properties?.target?.$ref).toBe('#/$defs/TableOrCellAddress');
expect(insertRowSuccess.properties?.table?.$ref).toBe('#/$defs/TableAddress');
});
it('preserves row-locator constraints in row operation schemas', () => {
const schemas = buildInternalContractSchemas();
const insertRowInput = schemas.operations['tables.insertRow'].input as {
oneOf?: Array<{
properties?: {
target?: { $ref?: string };
nodeId?: { type?: string };
rowIndex?: { type?: string; minimum?: number };
position?: { enum?: string[] };
};
required?: string[];
}>;
};
const deleteRowInput = schemas.operations['tables.deleteRow'].input as {
oneOf?: Array<{
properties?: {
target?: { $ref?: string };
nodeId?: { type?: string };
rowIndex?: { type?: string; minimum?: number };
};
required?: string[];
}>;
};
expect(insertRowInput.oneOf).toHaveLength(3);
expect(insertRowInput.oneOf?.[0]?.properties?.target?.$ref).toBe('#/$defs/TableRowAddress');
expect(insertRowInput.oneOf?.[0]?.required).toEqual(['target', 'position']);
expect(insertRowInput.oneOf?.[1]?.properties?.target?.$ref).toBe('#/$defs/TableAddress');
expect(insertRowInput.oneOf?.[1]?.required).toEqual(['target', 'rowIndex', 'position']);
expect(insertRowInput.oneOf?.[2]?.properties?.rowIndex).toEqual({ type: 'integer', minimum: 0 });
expect(insertRowInput.oneOf?.[2]?.required).toEqual(['nodeId', 'rowIndex', 'position']);
expect(deleteRowInput.oneOf).toHaveLength(3);
expect(deleteRowInput.oneOf?.[0]?.properties?.target?.$ref).toBe('#/$defs/TableRowAddress');
expect(deleteRowInput.oneOf?.[0]?.required).toEqual(['target']);
expect(deleteRowInput.oneOf?.[1]?.properties?.target?.$ref).toBe('#/$defs/TableAddress');
expect(deleteRowInput.oneOf?.[1]?.required).toEqual(['target', 'rowIndex']);
expect(deleteRowInput.oneOf?.[2]?.properties?.nodeId?.type).toBe('string');
expect(deleteRowInput.oneOf?.[2]?.properties?.rowIndex).toEqual({ type: 'integer', minimum: 0 });
expect(deleteRowInput.oneOf?.[2]?.required).toEqual(['nodeId', 'rowIndex']);
});
it('declares images.setZOrder.relativeHeight as unsigned 32-bit integer', () => {
const schemas = buildInternalContractSchemas();
const inputSchema = schemas.operations['images.setZOrder'].input as {
properties?: {
zOrder?: {
properties?: {
relativeHeight?: {
type?: string;
minimum?: number;
maximum?: number;
};
};
};
};
};
const relativeHeightSchema = inputSchema.properties?.zOrder?.properties?.relativeHeight;
expect(relativeHeightSchema?.type).toBe('integer');
expect(relativeHeightSchema?.minimum).toBe(Z_ORDER_RELATIVE_HEIGHT_MIN);
expect(relativeHeightSchema?.maximum).toBe(Z_ORDER_RELATIVE_HEIGHT_MAX);
});
it('derives OPERATION_IDS from OPERATION_DEFINITIONS keys', () => {
const definitionKeys = Object.keys(OPERATION_DEFINITIONS).sort();
const operationIds = [...OPERATION_IDS].sort();
expect(definitionKeys).toEqual(operationIds);
});
it('ensures every definition entry has a valid referenceGroup', () => {
const validGroups: readonly ReferenceGroupKey[] = [
'core',
'blocks',
'capabilities',
'create',
'sections',
'format',
'format.paragraph',
'styles',
'styles.paragraph',
'lists',
'comments',
'trackChanges',
'query',
'mutations',
'tables',
'history',
'toc',
'images',
'hyperlinks',
'headerFooters',
'contentControls',
'bookmarks',
'footnotes',
'crossRefs',
'index',
'captions',
'fields',
'citations',
'authorities',
'ranges',
'diff',
];
for (const id of OPERATION_IDS) {
expect(validGroups, `${id} has invalid referenceGroup`).toContain(OPERATION_DEFINITIONS[id].referenceGroup);
}
});
it('projects COMMAND_CATALOG metadata from the same objects in OPERATION_DEFINITIONS', () => {
for (const id of OPERATION_IDS) {
expect(COMMAND_CATALOG[id]).toBe(OPERATION_DEFINITIONS[id].metadata);
}
});
it('projects member paths that match OPERATION_DEFINITIONS', () => {
for (const id of OPERATION_IDS) {
expect(OPERATION_MEMBER_PATH_MAP[id]).toBe(OPERATION_DEFINITIONS[id].memberPath);
}
});
it('projects reference doc paths that match OPERATION_DEFINITIONS', () => {
for (const id of OPERATION_IDS) {
expect(OPERATION_REFERENCE_DOC_PATH_MAP[id]).toBe(OPERATION_DEFINITIONS[id].referenceDocPath);
}
});
it('projects descriptions that match OPERATION_DEFINITIONS', () => {
for (const id of OPERATION_IDS) {
expect(OPERATION_DESCRIPTION_MAP[id]).toBe(OPERATION_DEFINITIONS[id].description);
}
});
it('projects expected results that match OPERATION_DEFINITIONS', () => {
for (const id of OPERATION_IDS) {
expect(OPERATION_EXPECTED_RESULT_MAP[id]).toBe(OPERATION_DEFINITIONS[id].expectedResult);
}
});
it('ensures every operation has a non-empty expectedResult', () => {
for (const id of OPERATION_IDS) {
const expectedResult = OPERATION_DEFINITIONS[id].expectedResult;
expect(expectedResult, `${id} has empty expectedResult`).toBeTruthy();
expect(typeof expectedResult).toBe('string');
expect(expectedResult.length, `${id} expectedResult is too short`).toBeGreaterThan(10);
}
});
it('keeps public mutation step ops explicit and reference-valid', () => {
expect(PUBLIC_MUTATION_STEP_OP_IDS.length).toBeGreaterThan(0);
expect(new Set(PUBLIC_MUTATION_STEP_OP_IDS).size).toBe(PUBLIC_MUTATION_STEP_OP_IDS.length);
expect(PUBLIC_MUTATION_STEP_OP_IDS).not.toContain('domain.command');
expect(PUBLIC_MUTATION_STEP_OP_IDS).toContain('assert');
const validOperationIds = new Set<string>(OPERATION_IDS);
for (const stepOp of STEP_OP_CATALOG) {
if (!stepOp.referenceOperationId) continue;
expect(
validOperationIds.has(stepOp.referenceOperationId),
`${stepOp.opId} references unknown operation ${stepOp.referenceOperationId}`,
).toBe(true);
}
});
it('marks exactly the out-of-band mutation operations as historyUnsafe', () => {
const historyUnsafeOps = OPERATION_IDS.filter((id) => COMMAND_CATALOG[id].historyUnsafe === true).sort();
// styles.apply + all sections.set* / sections.clear* mutations
expect(historyUnsafeOps).toContain('styles.apply');
for (const id of historyUnsafeOps) {
expect(
id.startsWith('sections.') ||
id.startsWith('headerFooters.') ||
id === 'styles.apply' ||
id === 'tables.setDefaultStyle' ||
id === 'tables.clearDefaultStyle' ||
id === 'diff.apply',
`unexpected historyUnsafe: ${id}`,
).toBe(true);
}
// All section mutations (set*/clear*) should be marked
const sectionMutations = OPERATION_IDS.filter((id) => id.startsWith('sections.') && COMMAND_CATALOG[id].mutates);
for (const id of sectionMutations) {
expect(COMMAND_CATALOG[id].historyUnsafe, `${id} should be historyUnsafe`).toBe(true);
}
// Non-mutating and non-out-of-band operations should NOT be historyUnsafe
for (const id of OPERATION_IDS) {
if (!COMMAND_CATALOG[id].mutates || historyUnsafeOps.includes(id)) continue;
expect(COMMAND_CATALOG[id].historyUnsafe, `${id} should not be historyUnsafe`).toBeFalsy();
}
});
});