@jsb188/mday 1.1.10 → 1.1.12

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 (210) hide show
  1. package/package.json +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -0,0 +1,1967 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { SHEET_MAX_COLUMN_COUNT, SHEET_MAX_ROW_COUNT } from '../src/constants/sheet.ts';
3
+ import type {
4
+ SheetBootstrapGQL,
5
+ SheetBootstrapSnapshotGQL,
6
+ SheetCellGQL,
7
+ SheetComputedCellGQL,
8
+ SheetDeletedCellCoordGQL,
9
+ SheetGQL,
10
+ SheetGridViewportObj,
11
+ SheetTabChangeGQL,
12
+ SheetTabGQL,
13
+ } from '../src/types/sheet.d.ts';
14
+ import {
15
+ applySheetBootstrap,
16
+ decodeVerifiedSheetBootstrapSnapshot,
17
+ getSheetBootstrapPayloadChecksum,
18
+ SHEET_BOOTSTRAP_CONTRACT_VERSION,
19
+ type SheetBootstrapReadyResult,
20
+ type SheetBootstrapSnapshotScope,
21
+ type SheetBootstrapValidationCode,
22
+ SheetBootstrapValidationError,
23
+ validateSheetBootstrapChanges,
24
+ validateSheetRealtimeCapability,
25
+ } from '../src/utils/sheetBootstrap.ts';
26
+ import {
27
+ SHEET_CELLS_JOURNAL_VERSION,
28
+ SHEET_COMPUTED_JOURNAL_VERSION,
29
+ SHEET_DESIGN_JOURNAL_VERSION,
30
+ SHEET_STRUCTURE_JOURNAL_VERSION,
31
+ } from '../src/utils/sheetJournal.ts';
32
+ import { encodeSheetSnapshot, SHEET_SNAPSHOT_ENCODING_VERSION } from '../src/utils/sheetSnapshot.ts';
33
+
34
+ const FILE_CONSTANTS = {
35
+ organizationId: 'organization-1',
36
+ sheetId: 'sheet-1',
37
+ sheetTabId: 'tab-1',
38
+ otherTabId: 'tab-2',
39
+
40
+ realtimeToken: 'test-sheet-realtime-token',
41
+ viewport: {
42
+ startRowIndex: 1,
43
+ startColumnIndex: 1,
44
+ rowCount: 3,
45
+ columnCount: 3,
46
+ } satisfies SheetGridViewportObj,
47
+ };
48
+
49
+ /*
50
+ * Build the test tab at one journal seq over a 3-column grid (3 rows unless a
51
+ * STRUCTURE row resized it).
52
+ */
53
+ function buildTestTab(
54
+ cellsRevision: string,
55
+ overrides: Partial<SheetTabGQL> = {},
56
+ rowCount = FILE_CONSTANTS.viewport.rowCount,
57
+ ): SheetTabGQL {
58
+ return {
59
+ id: FILE_CONSTANTS.sheetTabId,
60
+ organizationId: FILE_CONSTANTS.organizationId,
61
+ sheetId: FILE_CONSTANTS.sheetId,
62
+ name: 'tab_1',
63
+ position: 1,
64
+ hidden: false,
65
+ cellsRevision,
66
+ designRevision: '1',
67
+ design: {
68
+ id: FILE_CONSTANTS.sheetTabId,
69
+ version: 1,
70
+ grid: {
71
+ rowCount,
72
+ columnCount: FILE_CONSTANTS.viewport.columnCount,
73
+ frozenRows: 0,
74
+ frozenColumns: 0,
75
+ },
76
+ },
77
+ ...overrides,
78
+ };
79
+ }
80
+
81
+ /*
82
+ * Build the workbook row of the test sheet.
83
+ */
84
+ function buildTestWorkbook(): SheetGQL {
85
+ return {
86
+ id: FILE_CONSTANTS.sheetId,
87
+ organizationId: FILE_CONSTANTS.organizationId,
88
+ name: 'workbook',
89
+ title: 'Workbook',
90
+ manifestRevision: '0',
91
+ };
92
+ }
93
+
94
+ /*
95
+ * Build the embedded access facts of the test sheet (an editor by default).
96
+ */
97
+ function buildAccess(overrides: Record<string, unknown> = {}) {
98
+ return {
99
+ sheetId: FILE_CONSTANTS.sheetId,
100
+ organizationId: FILE_CONSTANTS.organizationId,
101
+ canView: true,
102
+ canEdit: true,
103
+ signInRequired: false,
104
+ ...overrides,
105
+ };
106
+ }
107
+
108
+ /*
109
+ * Build the access facts of a signed-out viewer the sheet is denied to.
110
+ */
111
+ function buildDeniedAccess() {
112
+ return buildAccess({ canView: false, canEdit: false, signInRequired: true });
113
+ }
114
+
115
+ /*
116
+ * Build one fully scoped USER cell of the test tab.
117
+ */
118
+ function buildTestCell(overrides: Partial<SheetCellGQL> = {}): SheetCellGQL {
119
+ return {
120
+ id: 'cell-1',
121
+ organizationId: FILE_CONSTANTS.organizationId,
122
+ sheetId: FILE_CONSTANTS.sheetId,
123
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
124
+ rowIndex: 1,
125
+ columnIndex: 1,
126
+ textValue: 'café 🌱',
127
+ revision: '1',
128
+
129
+ ...overrides,
130
+ };
131
+ }
132
+
133
+ /*
134
+ * Build one exact COMPUTED item for cell-1: every derived field, nothing else.
135
+ */
136
+ function buildTestComputedCell(overrides: Partial<SheetComputedCellGQL> = {}): SheetComputedCellGQL {
137
+ return {
138
+ booleanValue: null,
139
+ columnIndex: 1,
140
+ computedAt: '2026-09-04T00:00:00.000Z',
141
+ dateValue: null,
142
+ datetimeValue: null,
143
+ errorCode: null,
144
+ errorMessage: null,
145
+ id: 'cell-1',
146
+ numberValue: 2,
147
+ revision: '2',
148
+ rowIndex: 1,
149
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
150
+ textValue: '2',
151
+ value: '2',
152
+ ...overrides,
153
+ };
154
+ }
155
+
156
+ /*
157
+ * Build one deletion tombstone of the test tab (coordinate-only by default).
158
+ */
159
+ function buildTestTombstone(overrides: Partial<SheetDeletedCellCoordGQL> = {}): SheetDeletedCellCoordGQL {
160
+ return {
161
+ columnIndex: 1,
162
+ id: null,
163
+ revision: null,
164
+ rowIndex: 1,
165
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
166
+ ...overrides,
167
+ };
168
+ }
169
+
170
+ /*
171
+ * Build one journal row of the test tab carrying a JSON payload.
172
+ */
173
+ function buildTestChange(seq: string, kind: string, payload: unknown, overrides: Partial<SheetTabChangeGQL> = {}): SheetTabChangeGQL {
174
+ return {
175
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
176
+ seq,
177
+ kind,
178
+ payload: JSON.stringify(payload),
179
+ ...overrides,
180
+ };
181
+ }
182
+
183
+ /*
184
+ * Build one replayable v3 CELLS payload.
185
+ */
186
+ function buildCellsPayload(cells: unknown[] = [], deletedCellCoords: unknown[] = [], extra: Record<string, unknown> = {}) {
187
+ return { v: SHEET_CELLS_JOURNAL_VERSION, cells, deletedCellCoords, ...extra };
188
+ }
189
+
190
+ /*
191
+ * Build one CELLS row that changes nothing: a seq placeholder in a tail.
192
+ */
193
+ function buildEmptyCellsChange(seq: string): SheetTabChangeGQL {
194
+ return buildTestChange(seq, 'CELLS', buildCellsPayload());
195
+ }
196
+
197
+ /*
198
+ * Build one replayable v1 COMPUTED payload.
199
+ */
200
+ function buildComputedPayload(cells: unknown[]) {
201
+ return { v: SHEET_COMPUTED_JOURNAL_VERSION, cells };
202
+ }
203
+
204
+ /*
205
+ * Build one v2 DESIGN journal payload the way the server writes it: the tab
206
+ * image repeats the row's design revision; design commands carry the design,
207
+ * rename/reorder rows carry only name/position.
208
+ */
209
+ function buildDesignPayload(designRevision: string, tab: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) {
210
+ return {
211
+ v: SHEET_DESIGN_JOURNAL_VERSION,
212
+ requiresSnapshot: false,
213
+ designRevision,
214
+ tab: { ...tab, designRevision },
215
+ ...extra,
216
+ };
217
+ }
218
+
219
+ /*
220
+ * Build one v2 STRUCTURE journal payload; defaults describe a row insert above
221
+ * row 1 at seq 2 moving the design from revision 1 to 2.
222
+ */
223
+ function buildStructurePayload(overrides: Record<string, unknown> = {}, structureOp: Record<string, unknown> = {}) {
224
+ return {
225
+ v: SHEET_STRUCTURE_JOURNAL_VERSION,
226
+ requiresSnapshot: false,
227
+ baseDesignRevision: '1',
228
+ designRevision: '2',
229
+
230
+ structureOp: {
231
+ kind: 'INSERT_DELETE',
232
+ opId: 'command-1',
233
+ operation: 'INSERT_ROW_ABOVE',
234
+ index: 1,
235
+ structureSeq: '2',
236
+ ...structureOp,
237
+ },
238
+ axisMoveOps: null,
239
+ ...overrides,
240
+ };
241
+ }
242
+
243
+ /*
244
+ * Build one AXIS_MOVE STRUCTURE payload at seq 2 (design 1 → 2) carrying the
245
+ * server's full axis-move delta for `axisMove`.
246
+ */
247
+ function buildAxisMovePayload(axisMove: Record<string, unknown>, structureOp: Record<string, unknown> = {}) {
248
+ return buildStructurePayload(
249
+ {
250
+ axisMoveOps: [
251
+ {
252
+ ...axisMove,
253
+ baseDesignRevision: '1',
254
+ baseRevision: '1',
255
+ commandId: 'command-2',
256
+ resultDesignRevision: '2',
257
+ resultRevision: '2',
258
+ schemaVersion: 1,
259
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
260
+ },
261
+ ],
262
+ },
263
+ {
264
+ axisMove,
265
+ kind: 'AXIS_MOVE',
266
+ opId: 'command-2',
267
+ operation: 'MOVE_AXIS',
268
+ ...structureOp,
269
+ },
270
+ );
271
+ }
272
+
273
+ /*
274
+ * Build one verified snapshot record at `seq`: the encoded tab image and its
275
+ * SHA-256, plus (unless `lean`) the optional viewport/byte/cell metadata a
276
+ * server may still send. Contract 4 needs only seq, encodingVersion, checksum
277
+ * and payload.
278
+ */
279
+ async function buildTestSnapshot(
280
+ params: {
281
+ seq?: string;
282
+ cells?: SheetCellGQL[];
283
+
284
+ sheetTab?: SheetTabGQL;
285
+ lean?: boolean;
286
+ } = {},
287
+ ): Promise<SheetBootstrapSnapshotGQL> {
288
+ const seq = params.seq ?? '1';
289
+ const encoded = encodeSheetSnapshot({
290
+ sheetId: FILE_CONSTANTS.sheetId,
291
+ sheetTab: params.sheetTab ?? buildTestTab(seq),
292
+ cells: params.cells ?? [buildTestCell()],
293
+
294
+ pageInfo: { hasMoreRows: false, lastContentRowIndex: 1 },
295
+ viewport: FILE_CONSTANTS.viewport,
296
+ });
297
+ const snapshot = {
298
+ seq,
299
+ encodingVersion: encoded.encodingVersion,
300
+ checksum: await getSheetBootstrapPayloadChecksum(encoded.payload),
301
+ payload: encoded.payload,
302
+ };
303
+
304
+ return params.lean
305
+ ? snapshot
306
+ : {
307
+ ...snapshot,
308
+ viewport: FILE_CONSTANTS.viewport,
309
+ cellCount: encoded.cellCount,
310
+ payloadBytes: String(encoded.payloadBytes),
311
+ createdAt: '2026-09-24T00:00:00.000Z',
312
+ };
313
+ }
314
+
315
+ /*
316
+ * Build one READY openSheet answer (contract 4) at `currentSeq`: the workbook,
317
+ * its one-tab manifest, the selected tab and the journal rows. It carries no
318
+ * servedViewport: contract 4 derives it from the selected tab's grid.
319
+ */
320
+ function buildReadyBootstrap(params: {
321
+ mode: 'DELTA' | 'SNAPSHOT';
322
+ currentSeq: string;
323
+ changes?: SheetTabChangeGQL[];
324
+ snapshot?: SheetBootstrapSnapshotGQL | null;
325
+ selectedTab?: SheetTabGQL;
326
+ }): SheetBootstrapGQL {
327
+ return {
328
+ access: buildAccess(),
329
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
330
+ realtimeToken: FILE_CONSTANTS.realtimeToken,
331
+ status: 'READY',
332
+ unavailableReason: null,
333
+ sheet: buildTestWorkbook(),
334
+ tabs: [
335
+ {
336
+ id: FILE_CONSTANTS.sheetTabId,
337
+ name: 'Tab 1',
338
+ position: 1,
339
+ hidden: false,
340
+ currentSeq: params.currentSeq,
341
+ referencedTabIds: [],
342
+ },
343
+ ],
344
+ selectedTab: params.selectedTab ?? buildTestTab(params.currentSeq),
345
+ mode: params.mode,
346
+ currentSeq: params.currentSeq,
347
+ snapshot: params.snapshot ?? null,
348
+ changes: params.changes ?? [],
349
+ };
350
+ }
351
+
352
+ /*
353
+ * Build one READY SNAPSHOT answer: a fresh snapshot at `snapshotSeq` and its
354
+ * tail rows up to `currentSeq` (the selected tab's design revision may run
355
+ * ahead of the snapshot's).
356
+ */
357
+ async function buildSnapshotBootstrap(
358
+ params: {
359
+ currentSeq?: string;
360
+ snapshotSeq?: string;
361
+ cells?: SheetCellGQL[];
362
+
363
+ changes?: SheetTabChangeGQL[];
364
+ designRevision?: string;
365
+ lean?: boolean;
366
+ } = {},
367
+ ): Promise<SheetBootstrapGQL> {
368
+ const currentSeq = params.currentSeq ?? '1';
369
+
370
+ return buildReadyBootstrap({
371
+ mode: 'SNAPSHOT',
372
+ currentSeq,
373
+ changes: params.changes,
374
+ snapshot: await buildTestSnapshot({
375
+ seq: params.snapshotSeq ?? '1',
376
+ cells: params.cells,
377
+
378
+ lean: params.lean,
379
+ }),
380
+ selectedTab: buildTestTab(currentSeq, {
381
+ designRevision: params.designRevision ?? '1',
382
+ }),
383
+ });
384
+ }
385
+
386
+ /*
387
+ * Build one READY DELTA answer at `currentSeq` carrying the rows after the
388
+ * caller's applied seq: no snapshot and no base proof.
389
+ */
390
+ function buildDeltaBootstrap(currentSeq: string, changes: SheetTabChangeGQL[], designRevision = '1'): SheetBootstrapGQL {
391
+ return buildReadyBootstrap({
392
+ mode: 'DELTA',
393
+ currentSeq,
394
+ changes,
395
+ selectedTab: buildTestTab(currentSeq, { designRevision }),
396
+ });
397
+ }
398
+
399
+ /*
400
+ * Build one DELTA at seq 2 whose single row carries `payload` under `kind`
401
+ * (applied from sinceSeq 1).
402
+ */
403
+ function buildOneRowDelta(kind: string, payload: unknown): SheetBootstrapGQL {
404
+ return buildDeltaBootstrap('2', [buildTestChange('2', kind, payload)], '2');
405
+ }
406
+
407
+ /*
408
+ * Strip one READY answer to the lean syncSheetTab shape: no workbook, tab list
409
+ * or realtime token.
410
+ */
411
+ function toSyncTabBootstrap(bootstrap: SheetBootstrapGQL): SheetBootstrapGQL {
412
+ const lean = { ...bootstrap };
413
+ delete lean.sheet;
414
+ delete lean.tabs;
415
+ delete lean.realtimeToken;
416
+ return lean;
417
+ }
418
+
419
+ /*
420
+ * Build a direct-call validation scope of the test tab (3×3 viewport).
421
+ */
422
+ function buildTestScope(overrides: Partial<SheetBootstrapSnapshotScope> = {}): SheetBootstrapSnapshotScope {
423
+ return {
424
+ organizationId: FILE_CONSTANTS.organizationId,
425
+ sheetId: FILE_CONSTANTS.sheetId,
426
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
427
+ viewport: FILE_CONSTANTS.viewport,
428
+ ...overrides,
429
+ };
430
+ }
431
+
432
+ /*
433
+ * Validate journal rows directly (the shared server/client validator) after
434
+ * `afterSeq` against one scope.
435
+ */
436
+ function validateTestRows(value: unknown, afterSeq: string, currentSeq: string, scope = buildTestScope()) {
437
+ return validateSheetBootstrapChanges({ value, afterSeq, currentSeq, scope });
438
+ }
439
+
440
+ /*
441
+ * Decode and verify one snapshot record directly against one scope.
442
+ */
443
+ function decodeTestSnapshot(snapshot: unknown, currentSeq = '1', scope = buildTestScope()) {
444
+ return decodeVerifiedSheetBootstrapSnapshot({ snapshot, currentSeq, scope });
445
+ }
446
+
447
+ /*
448
+ * Apply one answer for the test sheet; `sinceSeq` is the caller's applied seq
449
+ * a DELTA answer extends.
450
+ */
451
+ function applyTestBootstrap(bootstrap: unknown, sinceSeq?: string | null) {
452
+ return applySheetBootstrap({
453
+ bootstrap,
454
+ expectedSheetId: FILE_CONSTANTS.sheetId,
455
+ sinceSeq,
456
+ });
457
+ }
458
+
459
+ /*
460
+ * Apply one answer and narrow it to READY, failing the test otherwise.
461
+ */
462
+ async function applyReadyBootstrap(bootstrap: unknown, sinceSeq?: string | null): Promise<SheetBootstrapReadyResult> {
463
+ const result = await applyTestBootstrap(bootstrap, sinceSeq);
464
+ if (result.status !== 'READY') {
465
+ throw new Error(`Expected a READY bootstrap, got ${result.status}.`);
466
+ }
467
+ return result;
468
+ }
469
+
470
+ /*
471
+ * Assert that one validator call (sync or async) fails closed with a typed
472
+ * SheetBootstrapValidationError carrying `code`.
473
+ */
474
+ async function expectValidationFailure(run: () => unknown, code: SheetBootstrapValidationCode, label: string = code) {
475
+ const error = await Promise.resolve()
476
+ .then(run)
477
+ .then(
478
+ () => null,
479
+ (reason: unknown) => reason,
480
+ );
481
+ expect(error, label).toBeInstanceOf(SheetBootstrapValidationError);
482
+ expect(error, label).toMatchObject({ code });
483
+ }
484
+
485
+ /*
486
+ * Assert that applying every answer fails closed with `code`.
487
+ */
488
+ async function expectBootstrapFailures(bootstraps: unknown[], code: SheetBootstrapValidationCode, sinceSeq?: string | null) {
489
+ for (const [index, bootstrap] of bootstraps.entries()) {
490
+ await expectValidationFailure(() => applyTestBootstrap(bootstrap, sinceSeq), code, `${code} case ${index}`);
491
+ }
492
+ }
493
+
494
+ /*
495
+ * SNAPSHOT answers: the verified image at the snapshot seq plus the typed tail
496
+ * rows after it. Nothing is replayed here; the client's tab reducer installs
497
+ * the image and applies the rows.
498
+ */
499
+ describe('sheet bootstrap SNAPSHOT answers (contract 4)', () => {
500
+ it('returns the decoded snapshot image and an empty tail at the snapshot seq', async () => {
501
+ const result = await applyReadyBootstrap(await buildSnapshotBootstrap({ currentSeq: '7', snapshotSeq: '7' }));
502
+
503
+ expect(result).toMatchObject({
504
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
505
+ currentSeq: '7',
506
+ mode: 'SNAPSHOT',
507
+ realtimeToken: FILE_CONSTANTS.realtimeToken,
508
+ rows: [],
509
+ rowsAfterSeq: '7',
510
+ servedViewport: FILE_CONSTANTS.viewport,
511
+ });
512
+ expect(result.sheet?.id).toBe(FILE_CONSTANTS.sheetId);
513
+ expect(result.tabs.map((tab) => tab.id)).toEqual([FILE_CONSTANTS.sheetTabId]);
514
+ expect(result.image).toMatchObject({
515
+ organizationId: FILE_CONSTANTS.organizationId,
516
+ pageInfo: { hasMoreRows: false, lastContentRowIndex: 1 },
517
+ seq: '7',
518
+ sheetId: FILE_CONSTANTS.sheetId,
519
+ sheetTab: {
520
+ cellsRevision: '7',
521
+ designRevision: '1',
522
+ id: FILE_CONSTANTS.sheetTabId,
523
+ name: 'tab_1',
524
+ },
525
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
526
+ });
527
+ expect(result.image?.cells).toEqual([
528
+ expect.objectContaining({
529
+ columnIndex: 1,
530
+ id: 'cell-1',
531
+ revision: '1',
532
+ rowIndex: 1,
533
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
534
+ textValue: 'café 🌱',
535
+ }),
536
+ ]);
537
+ });
538
+
539
+ it('returns the image at the snapshot seq and its CELLS tail rows after it, whatever sinceSeq the caller sent', async () => {
540
+ const update = buildTestCell({
541
+ revision: '3',
542
+ textValue: 'verified update',
543
+ });
544
+ const bootstrap = await buildSnapshotBootstrap({
545
+ currentSeq: '3',
546
+ snapshotSeq: '2',
547
+ changes: [
548
+ buildTestChange('3', 'CELLS', buildCellsPayload([update]), {
549
+ commandId: 'command-3',
550
+ }),
551
+ ],
552
+ });
553
+ const result = await applyReadyBootstrap(bootstrap, '1');
554
+
555
+ expect(result.image?.seq).toBe('2');
556
+ expect(result.rowsAfterSeq).toBe('2');
557
+ expect(result.image?.cells[0]?.textValue).toBe('café 🌱');
558
+ expect(result.rows).toEqual([
559
+ {
560
+ cells: [update],
561
+ commandId: 'command-3',
562
+ computedCells: [],
563
+ deletedCellCoords: [],
564
+ kind: 'CELLS',
565
+ seq: '3',
566
+ },
567
+ ]);
568
+ });
569
+
570
+ it('returns a COMPUTED tail row as a derived-only patch after the CELLS row that delivered its cell (invariant 15)', async () => {
571
+ const formulaCell = buildTestCell({
572
+ formulaText: '=1+1',
573
+ rawInput: '=1+1',
574
+ revision: '2',
575
+ textValue: null,
576
+ value: null,
577
+ });
578
+ const computed = buildTestComputedCell({ revision: '3' });
579
+ const result = await applyReadyBootstrap(
580
+ await buildSnapshotBootstrap({
581
+ currentSeq: '3',
582
+ changes: [
583
+ buildTestChange('2', 'CELLS', buildCellsPayload([formulaCell])),
584
+ buildTestChange('3', 'COMPUTED', buildComputedPayload([computed])),
585
+ ],
586
+ }),
587
+ );
588
+
589
+ expect(result.rows.map((row) => [row.seq, row.kind])).toEqual([
590
+ ['2', 'CELLS'],
591
+ ['3', 'COMPUTED'],
592
+ ]);
593
+ expect(result.rows[0]?.cells).toEqual([formulaCell]);
594
+ expect(result.rows[1]).toEqual({
595
+ cells: [],
596
+ commandId: null,
597
+ computedCells: [computed],
598
+ deletedCellCoords: [],
599
+ kind: 'COMPUTED',
600
+ seq: '3',
601
+ });
602
+ });
603
+
604
+ it('rejects checksum, byte-count, cell-count and tampered-payload mismatches when the metadata is present', async () => {
605
+ const valid = await buildSnapshotBootstrap();
606
+ const snapshot = valid.snapshot as SheetBootstrapSnapshotGQL;
607
+
608
+ await expectBootstrapFailures(
609
+ [
610
+ { ...valid, snapshot: { ...snapshot, checksum: '0'.repeat(64) } },
611
+ {
612
+ ...valid,
613
+ snapshot: {
614
+ ...snapshot,
615
+ checksum: snapshot.checksum?.toUpperCase(),
616
+ },
617
+ },
618
+ // The UTF-16 length of 'café 🌱' is not its UTF-8 byte count.
619
+ {
620
+ ...valid,
621
+ snapshot: {
622
+ ...snapshot,
623
+ payloadBytes: String(snapshot.payload?.length),
624
+ },
625
+ },
626
+ {
627
+ ...valid,
628
+ snapshot: { ...snapshot, payloadBytes: `0${snapshot.payloadBytes}` },
629
+ },
630
+ {
631
+ ...valid,
632
+ snapshot: {
633
+ ...snapshot,
634
+ payloadBytes: Number(snapshot.payloadBytes),
635
+ },
636
+ },
637
+ {
638
+ ...valid,
639
+ snapshot: {
640
+ ...snapshot,
641
+ cellCount: Number(snapshot.cellCount) + 1,
642
+ },
643
+ },
644
+ { ...valid, snapshot: { ...snapshot, cellCount: -1 } },
645
+ // Without byte metadata a tampered payload reaches the checksum.
646
+ {
647
+ ...valid,
648
+ snapshot: {
649
+ ...snapshot,
650
+ payload: `${snapshot.payload} `,
651
+ payloadBytes: null,
652
+ },
653
+ },
654
+ { ...valid, snapshot: { ...snapshot, payload: '' } },
655
+ ],
656
+ 'INVALID_SNAPSHOT',
657
+ );
658
+ await expectBootstrapFailures(
659
+ [
660
+ await buildSnapshotBootstrap({
661
+ cells: [buildTestCell({ revision: '0' })],
662
+ }),
663
+ { ...valid, snapshot: { ...snapshot, seq: '01' } },
664
+ ],
665
+ 'INVALID_SEQUENCE',
666
+ );
667
+ });
668
+
669
+ it('accepts a snapshot carrying only {seq, encodingVersion, checksum, payload} and defaults servedViewport to the selected tab grid', async () => {
670
+ const bootstrap = await buildSnapshotBootstrap({ lean: true });
671
+
672
+ expect(Object.keys(bootstrap.snapshot || {}).sort()).toEqual(['checksum', 'encodingVersion', 'payload', 'seq']);
673
+ expect(bootstrap.servedViewport).toBeUndefined();
674
+
675
+ const result = await applyReadyBootstrap(bootstrap);
676
+ expect(result.servedViewport).toEqual(FILE_CONSTANTS.viewport);
677
+ expect(result.image?.cells.map((cell) => cell.id)).toEqual(['cell-1']);
678
+ });
679
+
680
+ it('validates snapshot cells against the snapshot viewport when present and the selected tab grid otherwise', async () => {
681
+ const corner = await buildSnapshotBootstrap({
682
+ cells: [buildTestCell({ columnIndex: 3, id: 'cell-corner', rowIndex: 3 })],
683
+ });
684
+
685
+ await expect(applyReadyBootstrap(corner)).resolves.toMatchObject({
686
+ status: 'READY',
687
+ });
688
+ await expectBootstrapFailures(
689
+ [
690
+ {
691
+ ...corner,
692
+ snapshot: {
693
+ ...corner.snapshot,
694
+ viewport: {
695
+ ...FILE_CONSTANTS.viewport,
696
+ columnCount: 2,
697
+ rowCount: 2,
698
+ },
699
+ },
700
+ },
701
+ await buildSnapshotBootstrap({
702
+ cells: [buildTestCell({ rowIndex: 4 })],
703
+ lean: true,
704
+ }),
705
+ ],
706
+ 'INVALID_VIEWPORT',
707
+ );
708
+ });
709
+
710
+ // Regression: a snapshot without its own viewport was once validated
711
+ // against the selected tab's grid at currentSeq, so a tail that shrank the
712
+ // grid failed INVALID_VIEWPORT on the very cell the tail deletes.
713
+ it('validates a lean snapshot image against its own grid when a tail row shrank the grid', async () => {
714
+ const lastRowCell = buildTestCell({ id: 'cell-last', rowIndex: 3 });
715
+ const bootstrap = buildReadyBootstrap({
716
+ mode: 'SNAPSHOT',
717
+ currentSeq: '2',
718
+ snapshot: await buildTestSnapshot({
719
+ cells: [lastRowCell],
720
+ lean: true,
721
+ }),
722
+ changes: [buildTestChange('2', 'STRUCTURE', buildStructurePayload({}, { index: 3, operation: 'DELETE_ROW' }))],
723
+ selectedTab: buildTestTab('2', { designRevision: '2' }, 2),
724
+ });
725
+ const result = await applyReadyBootstrap(bootstrap);
726
+
727
+ expect(result.image?.cells.map((cell) => cell.id)).toEqual(['cell-last']);
728
+ expect(result.rows[0]?.structureOp?.op).toEqual({
729
+ index: 3,
730
+ kind: 'INSERT_DELETE',
731
+ operation: 'DELETE_ROW',
732
+ });
733
+ });
734
+
735
+ it('echoes a present servedViewport and fails INVALID_VIEWPORT on a malformed one', async () => {
736
+ const bootstrap = await buildSnapshotBootstrap();
737
+ const result = await applyReadyBootstrap({
738
+ ...bootstrap,
739
+ servedViewport: FILE_CONSTANTS.viewport,
740
+ });
741
+
742
+ expect(result.servedViewport).toEqual(FILE_CONSTANTS.viewport);
743
+ await expectBootstrapFailures(
744
+ [
745
+ {
746
+ ...bootstrap,
747
+ servedViewport: { ...FILE_CONSTANTS.viewport, rowCount: 0 },
748
+ },
749
+ {
750
+ ...bootstrap,
751
+ servedViewport: { ...FILE_CONSTANTS.viewport, startRowIndex: 1.5 },
752
+ },
753
+ { ...bootstrap, servedViewport: 'FULL_TAB' },
754
+ {
755
+ ...bootstrap,
756
+ snapshot: {
757
+ ...bootstrap.snapshot,
758
+ viewport: { ...FILE_CONSTANTS.viewport, columnCount: -1 },
759
+ },
760
+ },
761
+ ],
762
+ 'INVALID_VIEWPORT',
763
+ );
764
+ });
765
+
766
+ it('returns the snapshot tab image at the snapshot seq while the selected tab runs ahead', async () => {
767
+ const result = await applyReadyBootstrap(
768
+ await buildSnapshotBootstrap({
769
+ currentSeq: '2',
770
+ designRevision: '2',
771
+ changes: [buildTestChange('2', 'DESIGN', buildDesignPayload('2', { name: 'renamed' }))],
772
+ }),
773
+ );
774
+
775
+ expect(result.selectedTab).toMatchObject({
776
+ cellsRevision: '2',
777
+ designRevision: '2',
778
+ });
779
+ expect(result.image?.sheetTab).toMatchObject({
780
+ cellsRevision: '1',
781
+ designRevision: '1',
782
+ name: 'tab_1',
783
+ });
784
+ expect(result.rows[0]?.design).toEqual({
785
+ designRevision: '2',
786
+ tab: { designRevision: '2', name: 'renamed' },
787
+ });
788
+ });
789
+
790
+ it('fails INVALID_SEQUENCE on a snapshot ahead of currentSeq, a gap in its tail or a short tail', async () => {
791
+ await expectBootstrapFailures(
792
+ [
793
+ await buildSnapshotBootstrap({ currentSeq: '2', snapshotSeq: '3' }),
794
+ await buildSnapshotBootstrap({
795
+ currentSeq: '3',
796
+ changes: [buildEmptyCellsChange('3')],
797
+ }),
798
+ await buildSnapshotBootstrap({
799
+ currentSeq: '3',
800
+ changes: [buildEmptyCellsChange('2')],
801
+ }),
802
+ await buildSnapshotBootstrap({ currentSeq: '2' }),
803
+ ],
804
+ 'INVALID_SEQUENCE',
805
+ );
806
+ });
807
+
808
+ it('fails INVALID_SNAPSHOT on an unsupported encoding version or a payload that does not decode', async () => {
809
+ const valid = await buildSnapshotBootstrap({ lean: true });
810
+ const snapshot = valid.snapshot as SheetBootstrapSnapshotGQL;
811
+ const garbage = 'not a snapshot';
812
+
813
+ await expectBootstrapFailures(
814
+ [
815
+ {
816
+ ...valid,
817
+ snapshot: {
818
+ ...snapshot,
819
+ encodingVersion: SHEET_SNAPSHOT_ENCODING_VERSION + 1,
820
+ },
821
+ },
822
+ {
823
+ ...valid,
824
+ snapshot: {
825
+ ...snapshot,
826
+ encodingVersion: String(SHEET_SNAPSHOT_ENCODING_VERSION),
827
+ },
828
+ },
829
+ {
830
+ ...valid,
831
+ snapshot: {
832
+ ...snapshot,
833
+ checksum: await getSheetBootstrapPayloadChecksum(garbage),
834
+ payload: garbage,
835
+ },
836
+ },
837
+ { ...valid, snapshot: null },
838
+ { ...valid, snapshot: [snapshot] },
839
+ ],
840
+ 'INVALID_SNAPSHOT',
841
+ );
842
+ });
843
+ });
844
+
845
+ /*
846
+ * DELTA answers (DESIGN §0 D10): the rows after the caller's live applied
847
+ * seq, validated with no base-snapshot proof and returned without an image.
848
+ */
849
+ describe('sheet bootstrap DELTA answers via sinceSeq (contract 4)', () => {
850
+ it('needs no base-snapshot proof: returns the rows after sinceSeq and no image', async () => {
851
+ const update = buildTestCell({ revision: '5', textValue: 'delta update' });
852
+ const result = await applyReadyBootstrap(
853
+ buildDeltaBootstrap('5', [
854
+ buildTestChange('5', 'CELLS', buildCellsPayload([update]), {
855
+ commandId: 'command-5',
856
+ }),
857
+ ]),
858
+ '4',
859
+ );
860
+
861
+ expect(result).toMatchObject({
862
+ currentSeq: '5',
863
+ image: null,
864
+ mode: 'DELTA',
865
+ rowsAfterSeq: '4',
866
+ });
867
+ expect(result.rows).toEqual([
868
+ {
869
+ cells: [update],
870
+ commandId: 'command-5',
871
+ computedCells: [],
872
+ deletedCellCoords: [],
873
+ kind: 'CELLS',
874
+ seq: '5',
875
+ },
876
+ ]);
877
+ expect(result).not.toHaveProperty('state');
878
+ expect(result).not.toHaveProperty('tailTopology');
879
+ });
880
+
881
+ it('returns an empty DELTA when sinceSeq equals currentSeq and accepts a zero sinceSeq', async () => {
882
+ await expect(applyReadyBootstrap(buildDeltaBootstrap('6', []), '6')).resolves.toMatchObject({
883
+ currentSeq: '6',
884
+ image: null,
885
+ mode: 'DELTA',
886
+ rows: [],
887
+ rowsAfterSeq: '6',
888
+ });
889
+
890
+ const fromZero = await applyReadyBootstrap(buildDeltaBootstrap('1', [buildEmptyCellsChange('1')]), '0');
891
+ expect(fromZero.rowsAfterSeq).toBe('0');
892
+ expect(fromZero.rows.map((row) => row.seq)).toEqual(['1']);
893
+ });
894
+
895
+ it('fails INVALID_RESPONSE when a DELTA has no usable sinceSeq or carries a snapshot', async () => {
896
+ const delta = buildDeltaBootstrap('2', [buildEmptyCellsChange('2')]);
897
+
898
+ for (const sinceSeq of [undefined, null, '', '01', '-1', 'abc']) {
899
+ await expectValidationFailure(() => applyTestBootstrap(delta, sinceSeq), 'INVALID_RESPONSE', `sinceSeq ${String(sinceSeq)}`);
900
+ }
901
+ await expectBootstrapFailures([{ ...delta, snapshot: await buildTestSnapshot() }], 'INVALID_RESPONSE', '1');
902
+ });
903
+
904
+ it('fails INVALID_SEQUENCE on DELTA rows outside (sinceSeq, currentSeq]', async () => {
905
+ const cases: Array<[string, string[], string]> = [
906
+ ['4', ['4', '5', '6'], 'starts at sinceSeq instead of after it'],
907
+ ['4', ['5', '6', '7'], 'runs past currentSeq'],
908
+ ['4', ['5'], 'ends before currentSeq'],
909
+ ['4', ['6'], 'skips seq 5'],
910
+ ['4', ['6', '5'], 'out of order'],
911
+ ['4', [], 'empty although sinceSeq is behind'],
912
+ ['7', [], 'sinceSeq ahead of currentSeq'],
913
+ ];
914
+
915
+ for (const [sinceSeq, seqs, label] of cases) {
916
+ await expectValidationFailure(
917
+ () =>
918
+ applyTestBootstrap(
919
+ buildDeltaBootstrap(
920
+ '6',
921
+ seqs.map((seq) => buildEmptyCellsChange(seq)),
922
+ ),
923
+ sinceSeq,
924
+ ),
925
+ 'INVALID_SEQUENCE',
926
+ label,
927
+ );
928
+ }
929
+ await expectBootstrapFailures(
930
+ [
931
+ buildDeltaBootstrap('5', [buildEmptyCellsChange('05') as SheetTabChangeGQL]),
932
+ {
933
+ ...buildDeltaBootstrap('5', []),
934
+ changes: [{ ...buildEmptyCellsChange('5'), seq: 5 }],
935
+ },
936
+ ],
937
+ 'INVALID_SEQUENCE',
938
+ '4',
939
+ );
940
+ });
941
+
942
+ it('validates rows against the grid-cap replay scope, so a row written before a later row shrank the grid still validates', async () => {
943
+ const lastRowCell = buildTestCell({
944
+ id: 'cell-last',
945
+ revision: '2',
946
+ rowIndex: 3,
947
+ });
948
+ const capCell = buildTestCell({
949
+ columnIndex: SHEET_MAX_COLUMN_COUNT,
950
+ id: 'cell-cap',
951
+ revision: '4',
952
+ rowIndex: SHEET_MAX_ROW_COUNT,
953
+ });
954
+ const result = await applyReadyBootstrap(
955
+ buildReadyBootstrap({
956
+ mode: 'DELTA',
957
+ currentSeq: '4',
958
+ changes: [
959
+ buildTestChange('2', 'CELLS', buildCellsPayload([lastRowCell])),
960
+ buildTestChange('3', 'STRUCTURE', buildStructurePayload({}, { index: 3, operation: 'DELETE_ROW', structureSeq: '3' })),
961
+ buildTestChange('4', 'CELLS', buildCellsPayload([capCell])),
962
+ ],
963
+ selectedTab: buildTestTab('4', { designRevision: '2' }, 2),
964
+ }),
965
+ '1',
966
+ );
967
+
968
+ expect(result.servedViewport).toMatchObject({ rowCount: 2 });
969
+ expect(result.rows.map((row) => row.cells.map((cell) => cell.id))).toEqual([['cell-last'], [], ['cell-cap']]);
970
+
971
+ const snapshotTail = await applyReadyBootstrap(
972
+ await buildSnapshotBootstrap({
973
+ currentSeq: '2',
974
+ changes: [buildTestChange('2', 'CELLS', buildCellsPayload([capCell], [buildTestTombstone({ rowIndex: 4 })]))],
975
+ }),
976
+ );
977
+ expect(snapshotTail.rows[0]?.cells).toEqual([capCell]);
978
+
979
+ await expectBootstrapFailures(
980
+ [
981
+ buildOneRowDelta('CELLS', buildCellsPayload([buildTestCell({ revision: '2', rowIndex: SHEET_MAX_ROW_COUNT + 1 })])),
982
+ buildOneRowDelta(
983
+ 'CELLS',
984
+ buildCellsPayload([
985
+ buildTestCell({
986
+ columnIndex: SHEET_MAX_COLUMN_COUNT + 1,
987
+ revision: '2',
988
+ }),
989
+ ]),
990
+ ),
991
+ buildOneRowDelta('COMPUTED', buildComputedPayload([buildTestComputedCell({ rowIndex: SHEET_MAX_ROW_COUNT + 1 })])),
992
+ ],
993
+ 'INVALID_VIEWPORT',
994
+ '1',
995
+ );
996
+ });
997
+
998
+ it('returns a STRUCTURE row as a typed topology patch ahead of the CELLS row that lands on the shifted grid (no tailTopology)', async () => {
999
+ const result = await applyReadyBootstrap(
1000
+ buildDeltaBootstrap(
1001
+ '3',
1002
+ [
1003
+ buildTestChange('2', 'STRUCTURE', buildStructurePayload({}, { opId: 'peer-command-9' })),
1004
+ buildTestChange('3', 'CELLS', buildCellsPayload([buildTestCell({ id: 'cell-new', revision: '3' })])),
1005
+ ],
1006
+ '2',
1007
+ ),
1008
+ '1',
1009
+ );
1010
+
1011
+ expect(result.rowsAfterSeq).toBe('1');
1012
+ expect(result.rows.map((row) => [row.seq, row.kind])).toEqual([
1013
+ ['2', 'STRUCTURE'],
1014
+ ['3', 'CELLS'],
1015
+ ]);
1016
+ expect(result.rows[0]).toEqual({
1017
+ cells: [],
1018
+ commandId: 'peer-command-9',
1019
+ computedCells: [],
1020
+ deletedCellCoords: [],
1021
+ kind: 'STRUCTURE',
1022
+ seq: '2',
1023
+ structureOp: {
1024
+ baseDesignRevision: '1',
1025
+
1026
+ designRevision: '2',
1027
+ op: { index: 1, kind: 'INSERT_DELETE', operation: 'INSERT_ROW_ABOVE' },
1028
+ opId: 'peer-command-9',
1029
+ seq: '2',
1030
+ },
1031
+ });
1032
+ expect(result.rows[1]?.cells.map((cell) => cell.id)).toEqual(['cell-new']);
1033
+ expect(result).not.toHaveProperty('tailTopology');
1034
+ });
1035
+ });
1036
+
1037
+ /*
1038
+ * DESIGN and STRUCTURE rows become typed patches: the tab image of a DESIGN
1039
+ * row and the topology op of a STRUCTURE row. Design-revision chaining and
1040
+ * geometry are the tab reducer's job.
1041
+ */
1042
+ describe('sheet bootstrap DESIGN and STRUCTURE rows', () => {
1043
+ it('returns a DESIGN row as the tab image patch at its design revision', async () => {
1044
+ const tab = {
1045
+ design: {
1046
+ columns: { '1': { width: 240 } },
1047
+ grid: { columnCount: 3, frozenRows: 1, rowCount: 3 },
1048
+ version: 1,
1049
+ },
1050
+ name: 'tab_1',
1051
+ };
1052
+ const result = await applyReadyBootstrap(
1053
+ buildDeltaBootstrap(
1054
+ '2',
1055
+ [
1056
+ buildTestChange('2', 'DESIGN', buildDesignPayload('2', tab), {
1057
+ commandId: 'command-2',
1058
+ }),
1059
+ ],
1060
+ '2',
1061
+ ),
1062
+ '1',
1063
+ );
1064
+
1065
+ expect(result.rows).toEqual([
1066
+ {
1067
+ cells: [],
1068
+ commandId: 'command-2',
1069
+ computedCells: [],
1070
+ deletedCellCoords: [],
1071
+ design: { designRevision: '2', tab: { ...tab, designRevision: '2' } },
1072
+ kind: 'DESIGN',
1073
+ seq: '2',
1074
+ },
1075
+ ]);
1076
+ });
1077
+
1078
+ it('accepts rename/reorder DESIGN rows without a design image (TAB ordered targets included) and one whose revision does not move', async () => {
1079
+ const result = await applyReadyBootstrap(
1080
+ buildDeltaBootstrap(
1081
+ '3',
1082
+ [
1083
+ buildTestChange(
1084
+ '2',
1085
+ 'DESIGN',
1086
+ buildDesignPayload(
1087
+ '2',
1088
+ { position: 2 },
1089
+ {
1090
+ orderedTargetGroups: [
1091
+ {
1092
+ serverSeq: '2',
1093
+ targets: [['TAB', FILE_CONSTANTS.sheetTabId, 'position']],
1094
+ },
1095
+ ],
1096
+ },
1097
+ ),
1098
+ ),
1099
+ buildTestChange('3', 'DESIGN', buildDesignPayload('2', { name: 'renamed' })),
1100
+ ],
1101
+ '2',
1102
+ ),
1103
+ '1',
1104
+ );
1105
+
1106
+ expect(result.rows.map((row) => row.design)).toEqual([
1107
+ { designRevision: '2', tab: { designRevision: '2', position: 2 } },
1108
+ { designRevision: '2', tab: { designRevision: '2', name: 'renamed' } },
1109
+ ]);
1110
+ });
1111
+
1112
+ it('fails INVALID_CHANGE on DESIGN rows whose tab image is missing, disagrees with the row revision or carries a non-object design', async () => {
1113
+ await expectBootstrapFailures(
1114
+ [
1115
+ { ...buildDesignPayload('2'), tab: 'tab_1' },
1116
+ { ...buildDesignPayload('2'), tab: ['tab_1'] },
1117
+ { ...buildDesignPayload('2'), tab: { designRevision: '3' } },
1118
+ { ...buildDesignPayload('2'), designRevision: '02' },
1119
+ buildDesignPayload('2', { design: 'wide' }),
1120
+ buildDesignPayload('2', { design: [] }),
1121
+ { ...buildDesignPayload('2'), requiresSnapshot: true },
1122
+ { ...buildDesignPayload('2'), truncated: true },
1123
+ { ...buildDesignPayload('2'), v: SHEET_DESIGN_JOURNAL_VERSION + 1 },
1124
+ ].map((payload) => buildOneRowDelta('DESIGN', payload)),
1125
+ 'INVALID_CHANGE',
1126
+ '1',
1127
+ );
1128
+ });
1129
+
1130
+ it('returns STRUCTURE insert and delete rows as typed ops with their design fence and command id', async () => {
1131
+ const result = await applyReadyBootstrap(
1132
+ buildDeltaBootstrap(
1133
+ '4',
1134
+ [
1135
+ buildTestChange('2', 'STRUCTURE', buildStructurePayload({})),
1136
+ buildTestChange('3', 'CELLS', buildCellsPayload([buildTestCell({ id: 'cell-new', revision: '3' })])),
1137
+ buildTestChange(
1138
+ '4',
1139
+ 'STRUCTURE',
1140
+ buildStructurePayload(
1141
+ { baseDesignRevision: '2', designRevision: '3' },
1142
+ {
1143
+ index: 2,
1144
+ opId: null,
1145
+ operation: 'DELETE_COLUMN',
1146
+ structureSeq: '4',
1147
+ },
1148
+ ),
1149
+ { commandId: 'command-4' },
1150
+ ),
1151
+ ],
1152
+ '3',
1153
+ ),
1154
+ '1',
1155
+ );
1156
+
1157
+ // An anonymous row falls back to its opId; the row's commandId wins.
1158
+ expect(result.rows.map((row) => row.commandId)).toEqual(['command-1', null, 'command-4']);
1159
+ expect(result.rows[0]?.structureOp).toEqual({
1160
+ baseDesignRevision: '1',
1161
+
1162
+ designRevision: '2',
1163
+ op: { index: 1, kind: 'INSERT_DELETE', operation: 'INSERT_ROW_ABOVE' },
1164
+ opId: 'command-1',
1165
+ seq: '2',
1166
+ });
1167
+ expect(result.rows[2]?.structureOp).toEqual({
1168
+ baseDesignRevision: '2',
1169
+
1170
+ designRevision: '3',
1171
+ op: { index: 2, kind: 'INSERT_DELETE', operation: 'DELETE_COLUMN' },
1172
+ opId: null,
1173
+ seq: '4',
1174
+ });
1175
+ });
1176
+
1177
+ it('returns a STRUCTURE axis move as its axisMoveOps patch and leaves the fit against the grid to the reducer', async () => {
1178
+ const axisMove = {
1179
+ axis: 'ROW',
1180
+ sourceEndIndex: 1,
1181
+ sourceStartIndex: 1,
1182
+ targetStartIndex: 3,
1183
+ };
1184
+ const result = await applyReadyBootstrap(buildOneRowDelta('STRUCTURE', buildAxisMovePayload(axisMove)), '1');
1185
+
1186
+ expect(result.rows[0]).toMatchObject({
1187
+ commandId: 'command-2',
1188
+ kind: 'STRUCTURE',
1189
+ seq: '2',
1190
+ });
1191
+ // The server's fence fields stay out of the patch.
1192
+ expect(result.rows[0]?.structureOp).toEqual({
1193
+ baseDesignRevision: '1',
1194
+
1195
+ designRevision: '2',
1196
+ op: { axisMoveOps: [axisMove], kind: 'AXIS_MOVE' },
1197
+ opId: 'command-2',
1198
+ seq: '2',
1199
+ });
1200
+
1201
+ const pastGrid = await applyReadyBootstrap(
1202
+ buildOneRowDelta('STRUCTURE', buildAxisMovePayload({ ...axisMove, targetStartIndex: 4 })),
1203
+ '1',
1204
+ );
1205
+ expect(pastGrid.rows[0]?.structureOp?.op).toEqual({
1206
+ axisMoveOps: [{ ...axisMove, targetStartIndex: 4 }],
1207
+ kind: 'AXIS_MOVE',
1208
+ });
1209
+ });
1210
+
1211
+ it('fails INVALID_CHANGE on malformed axis moves', async () => {
1212
+ const axisMove = {
1213
+ axis: 'ROW',
1214
+ sourceEndIndex: 1,
1215
+ sourceStartIndex: 1,
1216
+ targetStartIndex: 3,
1217
+ };
1218
+
1219
+ await expectBootstrapFailures(
1220
+ [
1221
+ { ...buildAxisMovePayload(axisMove), axisMoveOps: null },
1222
+ { ...buildAxisMovePayload(axisMove), axisMoveOps: [] },
1223
+ { ...buildAxisMovePayload(axisMove), axisMoveOps: [null] },
1224
+ buildAxisMovePayload({ ...axisMove, axis: 'DIAGONAL' }),
1225
+ buildAxisMovePayload({ ...axisMove, sourceStartIndex: 0 }),
1226
+ buildAxisMovePayload({ ...axisMove, targetStartIndex: '3' }),
1227
+ buildAxisMovePayload(axisMove, { operation: 'INSERT_ROW_ABOVE' }),
1228
+ ].map((payload) => buildOneRowDelta('STRUCTURE', payload)),
1229
+ 'INVALID_CHANGE',
1230
+ '1',
1231
+ );
1232
+ });
1233
+
1234
+ it('fails INVALID_CHANGE on a restoring STRUCTURE row (requiresSnapshot: true) and on malformed STRUCTURE rows', async () => {
1235
+ await expectBootstrapFailures(
1236
+ [
1237
+ buildStructurePayload({ requiresSnapshot: true }),
1238
+ buildStructurePayload({}, { kind: 'REVERSE_ROWS' }),
1239
+ buildStructurePayload({}, { structureSeq: '9' }),
1240
+ buildStructurePayload({}, { operation: 'INSERT_ROW_BELOW' }),
1241
+ buildStructurePayload({}, { index: 0 }),
1242
+ buildStructurePayload({}, { opId: '' }),
1243
+
1244
+ buildStructurePayload({ structureOp: null }),
1245
+ buildStructurePayload({ baseDesignRevision: 1 }),
1246
+ buildStructurePayload({ designRevision: undefined }),
1247
+ buildStructurePayload({ truncated: true }),
1248
+ buildStructurePayload({ v: SHEET_STRUCTURE_JOURNAL_VERSION + 1 }),
1249
+ ].map((payload) => buildOneRowDelta('STRUCTURE', payload)),
1250
+ 'INVALID_CHANGE',
1251
+ '1',
1252
+ );
1253
+ });
1254
+ });
1255
+
1256
+ /*
1257
+ * Access, status and contract gates run before any scoped data is read.
1258
+ */
1259
+ describe('sheet bootstrap access, status and contract', () => {
1260
+ it('pins contract 4 and fails INVALID_CONTRACT on every other version, denied answers included', async () => {
1261
+ const valid = await buildSnapshotBootstrap();
1262
+
1263
+ expect(SHEET_BOOTSTRAP_CONTRACT_VERSION).toBe(4);
1264
+ await expectBootstrapFailures(
1265
+ [1, 2, 3, '4', null, undefined].map((contractVersion) => ({
1266
+ ...valid,
1267
+ contractVersion,
1268
+ })),
1269
+ 'INVALID_CONTRACT',
1270
+ );
1271
+ await expectBootstrapFailures([{ access: buildDeniedAccess(), contractVersion: 2, status: 'DENIED' }], 'INVALID_CONTRACT');
1272
+ });
1273
+
1274
+ it('returns denied access facts only', async () => {
1275
+ await expect(
1276
+ applyTestBootstrap({
1277
+ access: buildDeniedAccess(),
1278
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
1279
+
1280
+ status: 'DENIED',
1281
+ unavailableReason: null,
1282
+ }),
1283
+ ).resolves.toEqual({
1284
+ access: buildDeniedAccess(),
1285
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
1286
+ status: 'DENIED',
1287
+ });
1288
+ });
1289
+
1290
+ it('fails INVALID_ACCESS when a denied answer exposes any scoped data or an unavailable reason', async () => {
1291
+ const denied = {
1292
+ access: buildDeniedAccess(),
1293
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
1294
+ status: 'DENIED',
1295
+ };
1296
+
1297
+ await expectBootstrapFailures(
1298
+ [
1299
+ { ...denied, sheet: buildTestWorkbook() },
1300
+ { ...denied, tabs: [] },
1301
+ { ...denied, selectedTab: buildTestTab('1') },
1302
+ { ...denied, mode: 'DELTA' },
1303
+ { ...denied, currentSeq: '1' },
1304
+ { ...denied, servedViewport: FILE_CONSTANTS.viewport },
1305
+ { ...denied, snapshot: { seq: '1' } },
1306
+ { ...denied, changes: [] },
1307
+ { ...denied, realtimeToken: FILE_CONSTANTS.realtimeToken },
1308
+ { ...denied, unavailableReason: 'SIGN_IN_REQUIRED' },
1309
+ ],
1310
+ 'INVALID_ACCESS',
1311
+ );
1312
+ });
1313
+
1314
+ it('requires an explicit DENIED or reasoned RETRY status for a viewer without view access', async () => {
1315
+ const access = buildDeniedAccess();
1316
+ const contractVersion = SHEET_BOOTSTRAP_CONTRACT_VERSION;
1317
+
1318
+ await expect(
1319
+ applyTestBootstrap({
1320
+ access,
1321
+ contractVersion,
1322
+ status: 'RETRY',
1323
+ unavailableReason: 'ACCESS_CHANGING',
1324
+ }),
1325
+ ).resolves.toEqual({
1326
+ access,
1327
+ contractVersion,
1328
+
1329
+ selectedTab: null,
1330
+ sheet: null,
1331
+ status: 'RETRY',
1332
+ tabs: [],
1333
+ unavailableReason: 'ACCESS_CHANGING',
1334
+ });
1335
+ await expectBootstrapFailures(
1336
+ [
1337
+ { access, contractVersion },
1338
+ { access, contractVersion, status: 'READY' },
1339
+ {
1340
+ access,
1341
+ contractVersion,
1342
+ status: 'UNAVAILABLE',
1343
+ unavailableReason: 'ACCESS_CHANGING',
1344
+ },
1345
+ { access, contractVersion, status: 'RETRY' },
1346
+ { access, contractVersion, status: 'RETRY', unavailableReason: ' ' },
1347
+ ],
1348
+ 'INVALID_STATUS',
1349
+ );
1350
+ await expectBootstrapFailures([], 'INVALID_ACCESS');
1351
+ });
1352
+
1353
+ it('accepts minimal UNAVAILABLE and RETRY answers without workbook data and rejects a token or a missing reason', async () => {
1354
+ const access = buildAccess();
1355
+ const contractVersion = SHEET_BOOTSTRAP_CONTRACT_VERSION;
1356
+
1357
+ for (const status of ['UNAVAILABLE', 'RETRY'] as const) {
1358
+ await expect(
1359
+ applyTestBootstrap({
1360
+ access,
1361
+ contractVersion,
1362
+ status,
1363
+ unavailableReason: 'MINIMUM_REVISION_PENDING',
1364
+ }),
1365
+ ).resolves.toEqual({
1366
+ access,
1367
+ contractVersion,
1368
+
1369
+ selectedTab: null,
1370
+ sheet: null,
1371
+ status,
1372
+ tabs: [],
1373
+ unavailableReason: 'MINIMUM_REVISION_PENDING',
1374
+ });
1375
+ }
1376
+ await expectBootstrapFailures(
1377
+ [
1378
+ {
1379
+ access,
1380
+ contractVersion,
1381
+ realtimeToken: FILE_CONSTANTS.realtimeToken,
1382
+ status: 'UNAVAILABLE',
1383
+ unavailableReason: 'MINIMUM_REVISION_PENDING',
1384
+ },
1385
+ ],
1386
+ 'INVALID_ACCESS',
1387
+ );
1388
+ await expectBootstrapFailures(
1389
+ [
1390
+ { access, contractVersion, status: 'UNAVAILABLE' },
1391
+ { access, contractVersion, status: 'PENDING', unavailableReason: 'X' },
1392
+ { access, contractVersion, status: 'DENIED' },
1393
+ ],
1394
+ 'INVALID_STATUS',
1395
+ );
1396
+ });
1397
+
1398
+ it('returns READY syncSheetTab answers without a workbook, tab list or realtime token', async () => {
1399
+ const snapshotAnswer = await applyReadyBootstrap(
1400
+ toSyncTabBootstrap(
1401
+ await buildSnapshotBootstrap({
1402
+ currentSeq: '2',
1403
+ changes: [buildEmptyCellsChange('2')],
1404
+ }),
1405
+ ),
1406
+ );
1407
+
1408
+ expect(snapshotAnswer).toMatchObject({
1409
+ mode: 'SNAPSHOT',
1410
+ realtimeToken: '',
1411
+ rowsAfterSeq: '1',
1412
+ sheet: null,
1413
+ tabs: [],
1414
+ });
1415
+ expect(snapshotAnswer.image?.seq).toBe('1');
1416
+ expect(snapshotAnswer.rows.map((row) => row.seq)).toEqual(['2']);
1417
+
1418
+ const deltaAnswer = await applyReadyBootstrap(toSyncTabBootstrap(buildDeltaBootstrap('2', [buildEmptyCellsChange('2')])), '1');
1419
+ expect(deltaAnswer).toMatchObject({
1420
+ image: null,
1421
+ mode: 'DELTA',
1422
+ realtimeToken: '',
1423
+ rowsAfterSeq: '1',
1424
+ sheet: null,
1425
+ tabs: [],
1426
+ });
1427
+ expect(deltaAnswer.selectedTab?.id).toBe(FILE_CONSTANTS.sheetTabId);
1428
+ });
1429
+
1430
+ it('fails INVALID_SEQUENCE when the selected-tab cursors disagree with currentSeq', async () => {
1431
+ const bootstrap = await buildSnapshotBootstrap({
1432
+ currentSeq: '2',
1433
+ changes: [buildEmptyCellsChange('2')],
1434
+ });
1435
+
1436
+ await expectBootstrapFailures(
1437
+ [
1438
+ { ...bootstrap, selectedTab: buildTestTab('3') },
1439
+ {
1440
+ ...bootstrap,
1441
+ tabs: bootstrap.tabs?.map((tab) => ({ ...tab, currentSeq: '3' })),
1442
+ },
1443
+ {
1444
+ ...bootstrap,
1445
+ tabs: bootstrap.tabs?.map((tab) => ({ ...tab, currentSeq: null })),
1446
+ },
1447
+ { ...bootstrap, currentSeq: 2 },
1448
+ { ...bootstrap, currentSeq: '02' },
1449
+ toSyncTabBootstrap({ ...bootstrap, selectedTab: buildTestTab('1') }),
1450
+ ],
1451
+ 'INVALID_SEQUENCE',
1452
+ );
1453
+ });
1454
+
1455
+ it('fails SCOPE_MISMATCH or INVALID_ACCESS when the workbook, tabs or access belong elsewhere', async () => {
1456
+ const bootstrap = await buildSnapshotBootstrap();
1457
+
1458
+ await expectBootstrapFailures(
1459
+ [
1460
+ { ...bootstrap, sheet: { ...buildTestWorkbook(), id: 'sheet-2' } },
1461
+ {
1462
+ ...bootstrap,
1463
+ sheet: { ...buildTestWorkbook(), organizationId: 'organization-2' },
1464
+ },
1465
+ {
1466
+ ...bootstrap,
1467
+ selectedTab: buildTestTab('1', { organizationId: 'organization-2' }),
1468
+ },
1469
+ {
1470
+ ...bootstrap,
1471
+ selectedTab: buildTestTab('1', { id: FILE_CONSTANTS.otherTabId }),
1472
+ },
1473
+ {
1474
+ ...bootstrap,
1475
+ tabs: [...(bootstrap.tabs || []), ...(bootstrap.tabs || [])],
1476
+ },
1477
+ {
1478
+ ...bootstrap,
1479
+ tabs: bootstrap.tabs?.map((tab) => ({
1480
+ ...tab,
1481
+ referencedTabIds: [FILE_CONSTANTS.otherTabId],
1482
+ })),
1483
+ },
1484
+ ],
1485
+ 'SCOPE_MISMATCH',
1486
+ );
1487
+ await expectBootstrapFailures(
1488
+ [
1489
+ { ...bootstrap, access: buildAccess({ sheetId: 'sheet-2' }) },
1490
+ { ...bootstrap, access: buildAccess({ canView: false }) },
1491
+ { ...bootstrap, access: buildAccess({ canView: 'yes' }) },
1492
+ { ...bootstrap, access: buildAccess({ organizationId: null }) },
1493
+ { ...bootstrap, access: buildAccess({ signInRequired: true }) },
1494
+ { ...bootstrap, access: null },
1495
+ { ...bootstrap, realtimeToken: ' padded-token ' },
1496
+ { ...bootstrap, realtimeToken: '' },
1497
+ ],
1498
+ 'INVALID_ACCESS',
1499
+ );
1500
+ });
1501
+
1502
+ it('fails INVALID_STATUS or INVALID_RESPONSE on inconsistent READY answers', async () => {
1503
+ const bootstrap = await buildSnapshotBootstrap();
1504
+
1505
+ await expectBootstrapFailures(
1506
+ [
1507
+ { ...bootstrap, unavailableReason: 'MINIMUM_REVISION_PENDING' },
1508
+ { ...bootstrap, mode: 'FULL' },
1509
+ { ...bootstrap, mode: null },
1510
+ ],
1511
+ 'INVALID_STATUS',
1512
+ );
1513
+ await expectBootstrapFailures(
1514
+ [
1515
+ 'openSheet',
1516
+ [bootstrap],
1517
+
1518
+ { ...bootstrap, tabs: {} },
1519
+ {
1520
+ ...bootstrap,
1521
+ tabs: bootstrap.tabs?.map((tab) => ({ ...tab, name: ' Tab 1' })),
1522
+ },
1523
+ {
1524
+ ...bootstrap,
1525
+ tabs: bootstrap.tabs?.map((tab) => ({ ...tab, hidden: null })),
1526
+ },
1527
+ ],
1528
+ 'INVALID_RESPONSE',
1529
+ );
1530
+ await expectValidationFailure(() => applySheetBootstrap({ bootstrap, expectedSheetId: '' }), 'INVALID_RESPONSE');
1531
+ });
1532
+
1533
+ it('returns an empty-workbook READY answer and rejects an inconsistent one', async () => {
1534
+ const empty = {
1535
+ access: buildAccess(),
1536
+ changes: [],
1537
+ contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
1538
+ currentSeq: '0',
1539
+ mode: 'SNAPSHOT',
1540
+ realtimeToken: FILE_CONSTANTS.realtimeToken,
1541
+
1542
+ selectedTab: null,
1543
+ sheet: buildTestWorkbook(),
1544
+ snapshot: null,
1545
+ status: 'READY',
1546
+ tabs: [],
1547
+ };
1548
+
1549
+ await expect(applyReadyBootstrap(empty)).resolves.toMatchObject({
1550
+ image: null,
1551
+ mode: 'SNAPSHOT',
1552
+ rows: [],
1553
+ rowsAfterSeq: '0',
1554
+ selectedTab: null,
1555
+ servedViewport: {
1556
+ columnCount: 1,
1557
+ rowCount: 1,
1558
+ startColumnIndex: 1,
1559
+ startRowIndex: 1,
1560
+ },
1561
+ tabs: [],
1562
+ });
1563
+ await expectBootstrapFailures(
1564
+ [
1565
+ { ...empty, currentSeq: '1' },
1566
+ { ...empty, mode: 'DELTA' },
1567
+ { ...empty, changes: [buildEmptyCellsChange('1')] },
1568
+ { ...empty, changes: null },
1569
+ { ...empty, sheet: null },
1570
+ { ...empty, snapshot: await buildTestSnapshot() },
1571
+ {
1572
+ ...empty,
1573
+ tabs: [
1574
+ {
1575
+ currentSeq: '0',
1576
+ hidden: false,
1577
+ id: FILE_CONSTANTS.sheetTabId,
1578
+ name: 'Tab 1',
1579
+ referencedTabIds: [],
1580
+ },
1581
+ ],
1582
+ },
1583
+ ],
1584
+ 'INVALID_RESPONSE',
1585
+ );
1586
+ });
1587
+ });
1588
+
1589
+ /*
1590
+ * The shared journal-row validator the server calls directly: it enforces the
1591
+ * scope it is given (the client passes the grid-cap replay scope).
1592
+ */
1593
+ describe('validateSheetBootstrapChanges', () => {
1594
+ it('returns one typed patch per row in seq order and an empty list for an empty tail', () => {
1595
+ const rows = validateTestRows(
1596
+ [buildEmptyCellsChange('4'), buildTestChange('5', 'COMPUTED', buildComputedPayload([buildTestComputedCell({ revision: '5' })]))],
1597
+ '3',
1598
+ '5',
1599
+ );
1600
+
1601
+ expect(rows.map((row) => [row.seq, row.kind])).toEqual([
1602
+ ['4', 'CELLS'],
1603
+ ['5', 'COMPUTED'],
1604
+ ]);
1605
+ expect(validateTestRows([], '5', '5')).toEqual([]);
1606
+ });
1607
+
1608
+ it('accepts hard-NEW CELLS ordering metadata and returns the row command id or null', () => {
1609
+ const tombstone = buildTestTombstone({ id: 'cell-1', revision: '2' });
1610
+ const [ordered, anonymous] = validateTestRows(
1611
+ [
1612
+ buildTestChange(
1613
+ '2',
1614
+ 'CELLS',
1615
+ buildCellsPayload([buildTestCell({ revision: '2' })], [], {
1616
+ orderedTargetGroups: [{ serverSeq: '2', targets: [[1, 1, 1]] }],
1617
+ }),
1618
+ { commandId: 'command-2' },
1619
+ ),
1620
+ buildTestChange('3', 'CELLS', buildCellsPayload([], [tombstone]), {
1621
+ commandId: '',
1622
+ }),
1623
+ ],
1624
+ '1',
1625
+ '3',
1626
+ );
1627
+
1628
+ expect(ordered?.commandId).toBe('command-2');
1629
+ expect(anonymous).toMatchObject({
1630
+ commandId: null,
1631
+ deletedCellCoords: [tombstone],
1632
+ });
1633
+ });
1634
+
1635
+ it('enforces the viewport of the scope it is given', async () => {
1636
+ await expectValidationFailure(
1637
+ () =>
1638
+ validateTestRows(
1639
+ [buildTestChange('2', 'CELLS', buildCellsPayload([buildTestCell({ revision: '2', rowIndex: 4 })]))],
1640
+ '1',
1641
+ '2',
1642
+ ),
1643
+ 'INVALID_VIEWPORT',
1644
+ );
1645
+ });
1646
+
1647
+ it('fails SCOPE_MISMATCH on rows, cells or tombstones outside the scope and on unknown row kinds', async () => {
1648
+ const cases: Array<[string, SheetTabChangeGQL]> = [
1649
+ [
1650
+ 'other tab row',
1651
+ buildTestChange('2', 'CELLS', buildCellsPayload(), {
1652
+ sheetTabId: FILE_CONSTANTS.otherTabId,
1653
+ }),
1654
+ ],
1655
+ ['unknown kind', buildTestChange('2', 'PRESENCE', buildCellsPayload())],
1656
+ ['lowercase kind', buildTestChange('2', 'cells', buildCellsPayload())],
1657
+ [
1658
+ 'other organization cell',
1659
+ buildTestChange('2', 'CELLS', buildCellsPayload([buildTestCell({ organizationId: 'organization-2', revision: '2' })])),
1660
+ ],
1661
+ ['other sheet cell', buildTestChange('2', 'CELLS', buildCellsPayload([buildTestCell({ revision: '2', sheetId: 'sheet-2' })]))],
1662
+ [
1663
+ 'other tab tombstone',
1664
+ buildTestChange('2', 'CELLS', buildCellsPayload([], [buildTestTombstone({ sheetTabId: FILE_CONSTANTS.otherTabId })])),
1665
+ ],
1666
+ ];
1667
+
1668
+ for (const [label, change] of cases) {
1669
+ await expectValidationFailure(() => validateTestRows([change], '1', '2'), 'SCOPE_MISMATCH', label);
1670
+ }
1671
+ await expectValidationFailure(
1672
+ () => validateTestRows([buildEmptyCellsChange('2')], '1', '2', buildTestScope({ sheetTabId: FILE_CONSTANTS.otherTabId })),
1673
+ 'SCOPE_MISMATCH',
1674
+ 'scope of another tab',
1675
+ );
1676
+ });
1677
+
1678
+ it('fails INVALID_SEQUENCE on non-contiguous or short tails, a base ahead of currentSeq and non-positive revisions', async () => {
1679
+ const cases: Array<[string, unknown[], string, string]> = [
1680
+ ['gap', ['4', '6'].map(buildEmptyCellsChange), '3', '6'],
1681
+ ['short', ['4', '5'].map(buildEmptyCellsChange), '3', '6'],
1682
+ ['long', ['4', '5', '6', '7'].map(buildEmptyCellsChange), '3', '6'],
1683
+ ['starts at the base', ['3', '4'].map(buildEmptyCellsChange), '3', '4'],
1684
+ ['base ahead of currentSeq', [], '7', '6'],
1685
+ ['non-canonical row seq', [buildEmptyCellsChange('04')], '3', '4'],
1686
+ ['numeric row seq', [{ ...buildEmptyCellsChange('4'), seq: 4 }], '3', '4'],
1687
+ ['zero cell revision', [buildTestChange('4', 'CELLS', buildCellsPayload([buildTestCell({ revision: '0' })]))], '3', '4'],
1688
+ [
1689
+ 'id-stamped tombstone without a revision',
1690
+ [buildTestChange('4', 'CELLS', buildCellsPayload([], [buildTestTombstone({ id: 'cell-1' })]))],
1691
+ '3',
1692
+ '4',
1693
+ ],
1694
+ ];
1695
+
1696
+ for (const [label, value, afterSeq, currentSeq] of cases) {
1697
+ await expectValidationFailure(() => validateTestRows(value, afterSeq, currentSeq), 'INVALID_SEQUENCE', label);
1698
+ }
1699
+ });
1700
+
1701
+ it('fails INVALID_CHANGE on malformed rows and payloads', async () => {
1702
+ const change = buildEmptyCellsChange('2');
1703
+ const cell = buildTestCell({ revision: '2' });
1704
+ const cases: Array<[string, unknown]> = [
1705
+ ['changes not an array', null],
1706
+ ['row not an object', ['row']],
1707
+ ['row without a tab', [{ ...change, sheetTabId: undefined }]],
1708
+ ['payload object', [{ ...change, payload: { v: 3 } }]],
1709
+ ['payload empty', [{ ...change, payload: '' }]],
1710
+ ['payload invalid JSON', [{ ...change, payload: '{' }]],
1711
+ ['payload array', [{ ...change, payload: '[]' }]],
1712
+ ['payload null', [{ ...change, payload: 'null' }]],
1713
+ ['CELLS v2', [buildTestChange('2', 'CELLS', buildCellsPayload([], [], { v: 2 }))]],
1714
+ ['CELLS truncated', [buildTestChange('2', 'CELLS', buildCellsPayload([], [], { truncated: true }))]],
1715
+ ['CELLS requiresSnapshot', [buildTestChange('2', 'CELLS', buildCellsPayload([], [], { requiresSnapshot: true }))]],
1716
+ [
1717
+ 'CELLS without tombstones',
1718
+ [
1719
+ buildTestChange('2', 'CELLS', {
1720
+ cells: [],
1721
+ v: SHEET_CELLS_JOURNAL_VERSION,
1722
+ }),
1723
+ ],
1724
+ ],
1725
+ [
1726
+ 'CELLS with retired ordering metadata',
1727
+ [buildTestChange('2', 'CELLS', buildCellsPayload([], [], { orderedTargetGroups: [] }))],
1728
+ ],
1729
+ ['duplicate cell coordinates', [buildTestChange('2', 'CELLS', buildCellsPayload([cell, { ...cell, id: 'cell-2' }]))]],
1730
+ ['cell not an object', [buildTestChange('2', 'CELLS', buildCellsPayload(['cell-1']))]],
1731
+ ['cell without an id', [buildTestChange('2', 'CELLS', buildCellsPayload([{ ...cell, id: '' }]))]],
1732
+ [
1733
+ 'tombstone with a padded id',
1734
+ [buildTestChange('2', 'CELLS', buildCellsPayload([], [buildTestTombstone({ id: ' cell-1', revision: '1' })]))],
1735
+ ],
1736
+ [
1737
+ 'tombstone without an explicit null id',
1738
+ [buildTestChange('2', 'CELLS', buildCellsPayload([], [{ ...buildTestTombstone(), id: undefined }]))],
1739
+ ],
1740
+ ['COMPUTED v2', [buildTestChange('2', 'COMPUTED', { cells: [], v: 2 })]],
1741
+ [
1742
+ 'COMPUTED truncated',
1743
+ [
1744
+ buildTestChange('2', 'COMPUTED', {
1745
+ ...buildComputedPayload([]),
1746
+ truncated: true,
1747
+ }),
1748
+ ],
1749
+ ],
1750
+ ];
1751
+
1752
+ for (const [label, value] of cases) {
1753
+ await expectValidationFailure(() => validateTestRows(value, '1', '2'), 'INVALID_CHANGE', label);
1754
+ }
1755
+ });
1756
+
1757
+ it('fails INVALID_CHANGE on COMPUTED items that smuggle a user field, belong to another tab, miss a field or repeat a coordinate', async () => {
1758
+ const computed = buildTestComputedCell();
1759
+ const { computedAt: _computedAt, ...partial } = computed;
1760
+ const cases: Array<[string, unknown[]]> = [
1761
+ ['smuggled rawInput', [{ ...computed, rawInput: 'smuggled' }]],
1762
+ ['smuggled style', [{ ...computed, style: { bold: true } }]],
1763
+ ['other tab', [buildTestComputedCell({ sheetTabId: FILE_CONSTANTS.otherTabId })]],
1764
+ ['missing computedAt', [partial]],
1765
+ ['zero revision', [buildTestComputedCell({ revision: '0' })]],
1766
+ ['duplicate coordinate', [computed, computed]],
1767
+ ];
1768
+
1769
+ for (const [label, cells] of cases) {
1770
+ await expectValidationFailure(
1771
+ () => validateTestRows([buildTestChange('2', 'COMPUTED', buildComputedPayload(cells))], '1', '2'),
1772
+ 'INVALID_CHANGE',
1773
+ label,
1774
+ );
1775
+ }
1776
+ });
1777
+
1778
+ it('leaves matching a COMPUTED item to the cell it computes to the reducer', () => {
1779
+ const [row] = validateTestRows(
1780
+ [buildTestChange('2', 'COMPUTED', buildComputedPayload([buildTestComputedCell({ id: 'cell-9' })]))],
1781
+ '1',
1782
+ '2',
1783
+ );
1784
+
1785
+ expect(row?.computedCells.map((cell) => cell.id)).toEqual(['cell-9']);
1786
+ });
1787
+ });
1788
+
1789
+ /*
1790
+ * The shared snapshot decoder the server calls directly: it verifies every
1791
+ * integrity field and stamps the caller's scope ancestry onto the image.
1792
+ */
1793
+ describe('decodeVerifiedSheetBootstrapSnapshot', () => {
1794
+ it('decodes a verified snapshot into the caller scope ancestry', async () => {
1795
+ const snapshot = await buildTestSnapshot({ lean: true, seq: '3' });
1796
+ const decoded = await decodeTestSnapshot(snapshot, '5');
1797
+
1798
+ expect(decoded).toMatchObject({
1799
+ checksum: snapshot.checksum,
1800
+ encodingVersion: SHEET_SNAPSHOT_ENCODING_VERSION,
1801
+ seq: '3',
1802
+ });
1803
+ expect(decoded.data.cells).toEqual([
1804
+ expect.objectContaining({
1805
+ id: 'cell-1',
1806
+ organizationId: FILE_CONSTANTS.organizationId,
1807
+ revision: '1',
1808
+ sheetId: FILE_CONSTANTS.sheetId,
1809
+ sheetTabId: FILE_CONSTANTS.sheetTabId,
1810
+ }),
1811
+ ]);
1812
+ expect(decoded.data.sheetTab).toMatchObject({
1813
+ cellsRevision: '3',
1814
+ designRevision: '1',
1815
+ id: FILE_CONSTANTS.sheetTabId,
1816
+ });
1817
+ });
1818
+
1819
+ it('bounds a lean snapshot by its own grid, not by the caller scope: a cell outside the image grid fails INVALID_VIEWPORT', async () => {
1820
+ const snapshot = await buildTestSnapshot({
1821
+ cells: [buildTestCell({ columnIndex: 3, rowIndex: 3 })],
1822
+ lean: true,
1823
+ });
1824
+
1825
+ await expect(decodeTestSnapshot(snapshot)).resolves.toMatchObject({
1826
+ seq: '1',
1827
+ });
1828
+ // The selected tab lost a row after the snapshot seq: still valid.
1829
+ await expect(
1830
+ decodeTestSnapshot(
1831
+ snapshot,
1832
+ '1',
1833
+ buildTestScope({
1834
+ viewport: { ...FILE_CONSTANTS.viewport, rowCount: 2 },
1835
+ }),
1836
+ ),
1837
+ ).resolves.toMatchObject({ seq: '1' });
1838
+ await expectValidationFailure(
1839
+ async () =>
1840
+ decodeTestSnapshot(
1841
+ await buildTestSnapshot({
1842
+ cells: [buildTestCell({ columnIndex: 3, rowIndex: 3 })],
1843
+ lean: true,
1844
+ sheetTab: buildTestTab('1', {}, 2),
1845
+ }),
1846
+ ),
1847
+ 'INVALID_VIEWPORT',
1848
+ );
1849
+ });
1850
+
1851
+ it('fails INVALID_SEQUENCE on a snapshot ahead of currentSeq or a non-canonical seq', async () => {
1852
+ const snapshot = await buildTestSnapshot({ lean: true, seq: '3' });
1853
+
1854
+ for (const [label, value, currentSeq] of [
1855
+ ['ahead of currentSeq', snapshot, '2'],
1856
+ ['padded seq', { ...snapshot, seq: '03' }, '5'],
1857
+ ['numeric seq', { ...snapshot, seq: 3 }, '5'],
1858
+ ] as const) {
1859
+ await expectValidationFailure(() => decodeTestSnapshot(value, currentSeq), 'INVALID_SEQUENCE', label);
1860
+ }
1861
+ });
1862
+
1863
+ it('fails INVALID_SNAPSHOT on an unsupported encoding version', async () => {
1864
+ const snapshot = await buildTestSnapshot({ lean: true });
1865
+
1866
+ for (const encodingVersion of [SHEET_SNAPSHOT_ENCODING_VERSION + 1, String(SHEET_SNAPSHOT_ENCODING_VERSION), 0, null]) {
1867
+ await expectValidationFailure(
1868
+ () => decodeTestSnapshot({ ...snapshot, encodingVersion }),
1869
+ 'INVALID_SNAPSHOT',
1870
+ `encodingVersion ${String(encodingVersion)}`,
1871
+ );
1872
+ }
1873
+ });
1874
+
1875
+ it('fails INVALID_SNAPSHOT on duplicate cell coordinates', async () => {
1876
+ const snapshot = await buildTestSnapshot({
1877
+ cells: [buildTestCell(), buildTestCell({ id: 'cell-2' })],
1878
+ lean: true,
1879
+ });
1880
+
1881
+ await expectValidationFailure(() => decodeTestSnapshot(snapshot), 'INVALID_SNAPSHOT');
1882
+ });
1883
+
1884
+ it('verifies payloadBytes and cellCount only when present', async () => {
1885
+ const lean = await buildTestSnapshot({ lean: true });
1886
+ const full = await buildTestSnapshot();
1887
+
1888
+ await expect(decodeTestSnapshot(lean)).resolves.toMatchObject({ seq: '1' });
1889
+ await expect(decodeTestSnapshot(full)).resolves.toMatchObject({ seq: '1' });
1890
+ for (const [label, value] of [
1891
+ ['cellCount', { ...lean, cellCount: 2 }],
1892
+ ['fractional cellCount', { ...lean, cellCount: 1.5 }],
1893
+ ['payloadBytes', { ...lean, payloadBytes: '1' }],
1894
+ ['not a record', 'snapshot'],
1895
+ ] as const) {
1896
+ await expectValidationFailure(() => decodeTestSnapshot(value), 'INVALID_SNAPSHOT', label);
1897
+ }
1898
+ });
1899
+ });
1900
+
1901
+ /*
1902
+ * The payload checksum is the lowercase SHA-256 of the exact UTF-8 bytes.
1903
+ */
1904
+ describe('getSheetBootstrapPayloadChecksum', () => {
1905
+ it('returns the lowercase SHA-256 of the exact UTF-8 payload', async () => {
1906
+ expect(await getSheetBootstrapPayloadChecksum('')).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
1907
+ expect(await getSheetBootstrapPayloadChecksum('abc')).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
1908
+ expect(await getSheetBootstrapPayloadChecksum('café 🌱')).toBe('ef245b5b504b94982e0a48f6f38390132f01fc74bb5230055adeb9d6e026986f');
1909
+ });
1910
+ });
1911
+
1912
+ /*
1913
+ * Capability renewals carry tokens only when READY.
1914
+ */
1915
+ describe('validateSheetRealtimeCapability', () => {
1916
+ it('returns the READY sheet token and no token for other statuses', () => {
1917
+ expect(
1918
+ validateSheetRealtimeCapability(
1919
+ {
1920
+ access: buildAccess(),
1921
+ realtimeToken: 'sheet-token',
1922
+
1923
+ status: 'READY',
1924
+ },
1925
+ FILE_CONSTANTS.sheetId,
1926
+ ),
1927
+ ).toEqual({
1928
+ access: buildAccess(),
1929
+ realtimeToken: 'sheet-token',
1930
+
1931
+ status: 'READY',
1932
+ });
1933
+ expect(
1934
+ validateSheetRealtimeCapability(
1935
+ {
1936
+ access: buildDeniedAccess(),
1937
+
1938
+ status: 'DENIED',
1939
+ },
1940
+ FILE_CONSTANTS.sheetId,
1941
+ ),
1942
+ ).toEqual({
1943
+ access: buildDeniedAccess(),
1944
+ realtimeToken: null,
1945
+
1946
+ status: 'DENIED',
1947
+ });
1948
+ });
1949
+
1950
+ it('fails closed on a READY renewal without a token, view access or the correct sheet scope', async () => {
1951
+ const cases: Array<[string, unknown, SheetBootstrapValidationCode]> = [
1952
+ ['no token', { access: buildAccess(), status: 'READY' }, 'INVALID_ACCESS'],
1953
+ ['no view access', { access: buildDeniedAccess(), realtimeToken: 'sheet-token', status: 'READY' }, 'INVALID_ACCESS'],
1954
+ [
1955
+ 'another sheet',
1956
+ { access: buildAccess({ sheetId: 'sheet-2' }), realtimeToken: 'sheet-token', status: 'READY' },
1957
+ 'INVALID_ACCESS',
1958
+ ],
1959
+ ['unknown status', { access: buildAccess(), status: 'UNKNOWN' }, 'INVALID_STATUS'],
1960
+ ['not a record', null, 'INVALID_RESPONSE'],
1961
+ ];
1962
+
1963
+ for (const [label, capability, code] of cases) {
1964
+ await expectValidationFailure(() => validateSheetRealtimeCapability(capability, FILE_CONSTANTS.sheetId), code, label);
1965
+ }
1966
+ });
1967
+ });