@jsb188/mday 1.1.8 → 1.1.11

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 (123) hide show
  1. package/package.json +105 -35
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +48 -0
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +44 -0
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/inboundContact.ts +8 -0
  13. package/src/constants/integration.ts +13 -0
  14. package/src/constants/log.ts +7 -366
  15. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  16. package/src/constants/logTaxonomy.generated.ts +1103 -0
  17. package/src/constants/noteDoc.ts +77 -0
  18. package/src/constants/organization.ts +18 -11
  19. package/src/constants/pageRoute.ts +23 -0
  20. package/src/constants/schedule.ts +220 -0
  21. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  22. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  23. package/src/constants/sheet.ts +168 -0
  24. package/src/constants/sheetRegionSources.generated.ts +578 -0
  25. package/src/constants/square.ts +16 -0
  26. package/src/constants/storage.ts +61 -0
  27. package/src/constants/usage.ts +79 -0
  28. package/src/schemas/editLogEntry.ts +1017 -738
  29. package/src/schemas/fieldDocsQuery.ts +12 -0
  30. package/src/schemas/inboundContact.ts +77 -0
  31. package/src/schemas/logsQuery.ts +57 -316
  32. package/src/schemas/organization.ts +53 -213
  33. package/src/types/account.d.ts +81 -0
  34. package/src/types/agentDoc.d.ts +64 -0
  35. package/src/types/agentMemory.d.ts +74 -0
  36. package/src/types/campaign.d.ts +683 -0
  37. package/src/types/dataTable.d.ts +366 -0
  38. package/src/types/docAccess.d.ts +96 -0
  39. package/src/types/email.d.ts +142 -0
  40. package/src/types/fieldDoc.d.ts +273 -0
  41. package/src/types/inboundContact.d.ts +57 -0
  42. package/src/types/integration.d.ts +42 -0
  43. package/src/types/log.d.ts +169 -190
  44. package/src/types/noteDoc.d.ts +86 -0
  45. package/src/types/organization.d.ts +175 -76
  46. package/src/types/pageRoute.d.ts +48 -0
  47. package/src/types/schedule.d.ts +391 -0
  48. package/src/types/sheet.d.ts +1130 -0
  49. package/src/types/storage.d.ts +242 -0
  50. package/src/types/usage.d.ts +106 -0
  51. package/src/types/workflow.d.ts +305 -0
  52. package/src/utils/agentDoc.ts +109 -0
  53. package/src/utils/aiChat.ts +26 -0
  54. package/src/utils/campaign.ts +741 -0
  55. package/src/utils/campaignFormEditor.ts +871 -0
  56. package/src/utils/dataTable.ts +849 -0
  57. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  58. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  59. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  60. package/src/utils/dataTableRowDocument.ts +508 -0
  61. package/src/utils/dataTableSource.ts +230 -0
  62. package/src/utils/docAccess.ts +383 -0
  63. package/src/utils/documentName.ts +53 -0
  64. package/src/utils/email.ts +172 -0
  65. package/src/utils/fieldDoc.ts +113 -0
  66. package/src/utils/log.ts +173 -778
  67. package/src/utils/logRegistryValue.ts +90 -0
  68. package/src/utils/logStoreRead.ts +266 -0
  69. package/src/utils/logTaxonomy.ts +76 -0
  70. package/src/utils/logTaxonomyDisplay.ts +439 -0
  71. package/src/utils/noteDoc.ts +827 -0
  72. package/src/utils/organization.ts +683 -81
  73. package/src/utils/pageRoute.ts +71 -0
  74. package/src/utils/schedule.ts +799 -0
  75. package/src/utils/scheduleEvaluation.ts +1994 -0
  76. package/src/utils/scheduleICS.ts +246 -0
  77. package/src/utils/scheduleRuleTemplates.ts +188 -0
  78. package/src/utils/sheet.ts +4973 -0
  79. package/src/utils/sheetAxisMove.ts +830 -0
  80. package/src/utils/sheetBootstrap.ts +1769 -0
  81. package/src/utils/sheetCommand.ts +423 -0
  82. package/src/utils/sheetExport.ts +238 -0
  83. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  84. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  85. package/src/utils/sheetJournal.ts +78 -0
  86. package/src/utils/sheetNumberFormat.ts +1211 -0
  87. package/src/utils/sheetRegion.ts +374 -0
  88. package/src/utils/sheetRegionFilter.ts +1259 -0
  89. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  90. package/src/utils/sheetSequence.ts +148 -0
  91. package/src/utils/sheetSnapshot.ts +992 -0
  92. package/src/utils/sheetStructureEdit.ts +1284 -0
  93. package/src/utils/square.ts +32 -0
  94. package/src/utils/storage.ts +152 -0
  95. package/src/utils/table-route.ts +262 -0
  96. package/src/utils/workflow.ts +380 -0
  97. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  98. package/tests/docAccess.test.ts +525 -0
  99. package/tests/editLogEntry.test.ts +112 -0
  100. package/tests/noteDoc.test.ts +669 -0
  101. package/tests/schedule.test.ts +693 -0
  102. package/tests/scheduleEvaluation.test.ts +1970 -0
  103. package/tests/scheduleICS.test.ts +208 -0
  104. package/tests/scheduleRuleTemplates.test.ts +176 -0
  105. package/tests/scheduleSweepInvariants.test.ts +428 -0
  106. package/tests/sheetAxisMove.test.ts +343 -0
  107. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  108. package/tests/sheetRegionFilter.test.ts +1135 -0
  109. package/tests/sheetSequence.test.ts +41 -0
  110. package/tests/sheetStructureEdit.test.ts +82 -0
  111. package/tsconfig.json +12 -0
  112. package/vitest.config.ts +8 -0
  113. package/src/constants/log-activityTexts.ts +0 -209
  114. package/src/constants/product.ts +0 -66
  115. package/src/constants/report.ts +0 -25
  116. package/src/schemas/childOrganizationsQuery.ts +0 -44
  117. package/src/schemas/productsQuery.ts +0 -145
  118. package/src/schemas/reportsQuery.ts +0 -107
  119. package/src/types/action.d.ts +0 -42
  120. package/src/types/product.d.ts +0 -173
  121. package/src/types/report.d.ts +0 -203
  122. package/src/utils/product-calEvent.ts +0 -508
  123. package/src/utils/route-helpers.ts +0 -583
@@ -0,0 +1,423 @@
1
+ import type {
2
+ SheetCommandResultGQL,
3
+ SheetCommandTabRevisionGQL,
4
+ SheetDesignCommandIntent,
5
+ SheetDesignObj,
6
+ SheetDesignOperationTargetType,
7
+ SheetDesignPatchInput,
8
+ SheetNamedRangeObj,
9
+ } from '../types/sheet.d.ts';
10
+
11
+ type SheetDesignRecord = Record<string, unknown>;
12
+
13
+ /*
14
+ * Return whether a value is a plain design record rather than an array.
15
+ */
16
+ function isSheetDesignRecord(value: unknown): value is SheetDesignRecord {
17
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value));
18
+ }
19
+
20
+ /*
21
+ * Parse one whole-map UI design field into a plain record.
22
+ */
23
+ function parseSheetDesignPatchRecord(value: string | null | undefined) {
24
+ if (typeof value !== 'string' || !value.trim()) {
25
+ return null;
26
+ }
27
+
28
+ try {
29
+ const parsed = JSON.parse(value);
30
+ return isSheetDesignRecord(parsed) ? parsed : null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /*
37
+ * Return one deterministic JSON signature for semantic design comparisons.
38
+ */
39
+ function getSheetDesignCommandValueSignature(value: unknown): string {
40
+ if (Array.isArray(value)) {
41
+ return `[${value.map(getSheetDesignCommandValueSignature).join(',')}]`;
42
+ }
43
+ if (isSheetDesignRecord(value)) {
44
+ return `{${Object.keys(value)
45
+ .sort()
46
+ .filter((key) => value[key] !== undefined)
47
+ .map(
48
+ (key) =>
49
+ `${JSON.stringify(key)}:${getSheetDesignCommandValueSignature(value[key])}`,
50
+ )
51
+ .join(',')}}`;
52
+ }
53
+
54
+ return JSON.stringify(value ?? null);
55
+ }
56
+
57
+ /*
58
+ * Return whether two design values have the same JSON semantics.
59
+ */
60
+ function sheetDesignCommandValuesAreEqual(a: unknown, b: unknown) {
61
+ return (
62
+ getSheetDesignCommandValueSignature(a) ===
63
+ getSheetDesignCommandValueSignature(b)
64
+ );
65
+ }
66
+
67
+ /*
68
+ * Append property-level intents that transform one keyed design record into another.
69
+ */
70
+ function appendSheetDesignRecordPropertyIntents(
71
+ operations: SheetDesignCommandIntent[],
72
+ params: {
73
+ before?: SheetDesignRecord | null;
74
+ after?: SheetDesignRecord | null;
75
+ targetKey: string;
76
+ targetType: SheetDesignOperationTargetType;
77
+ },
78
+ ) {
79
+ const before = params.before || {};
80
+ const after = params.after || {};
81
+ const propertyKeys = new Set([...Object.keys(before), ...Object.keys(after)]);
82
+
83
+ [...propertyKeys].sort().forEach((property) => {
84
+ const beforeValue = before[property];
85
+ const afterValue = after[property];
86
+ if (sheetDesignCommandValuesAreEqual(beforeValue, afterValue)) {
87
+ return;
88
+ }
89
+
90
+ operations.push({
91
+ operation:
92
+ afterValue === undefined || afterValue === null
93
+ ? 'DELETE_PROPERTY'
94
+ : 'SET_PROPERTY',
95
+ property,
96
+ targetKey: params.targetKey,
97
+ targetType: params.targetType,
98
+ ...(afterValue === undefined || afterValue === null
99
+ ? {}
100
+ : { value: afterValue }),
101
+ });
102
+ });
103
+ }
104
+
105
+ /*
106
+ * Append keyed row or column operations for one whole-map UI patch.
107
+ */
108
+ function appendSheetDesignAxisIntents(
109
+ operations: SheetDesignCommandIntent[],
110
+ params: {
111
+ before?: Record<string, SheetDesignRecord> | null;
112
+ after: SheetDesignRecord;
113
+ targetType: 'COLUMN' | 'ROW';
114
+ },
115
+ ) {
116
+ const before = params.before || {};
117
+ const axisKeys = new Set([
118
+ ...Object.keys(before),
119
+ ...Object.keys(params.after),
120
+ ]);
121
+
122
+ [...axisKeys]
123
+ .sort((a, b) => Number(a) - Number(b))
124
+ .forEach((targetKey) => {
125
+ const beforeEntity = before[targetKey];
126
+ const afterValue = params.after[targetKey];
127
+ const afterEntity = isSheetDesignRecord(afterValue) ? afterValue : null;
128
+ if (
129
+ !/^[1-9]\d*$/.test(targetKey) ||
130
+ (afterValue !== undefined && !afterEntity)
131
+ ) {
132
+ throw new Error('INVALID_SHEET_DESIGN_AXIS_PATCH');
133
+ }
134
+ if (afterValue === undefined) {
135
+ if (beforeEntity) {
136
+ operations.push({
137
+ operation: 'DELETE_ENTITY',
138
+ targetKey,
139
+ targetType: params.targetType,
140
+ });
141
+ }
142
+ return;
143
+ }
144
+
145
+ appendSheetDesignRecordPropertyIntents(operations, {
146
+ after: afterEntity,
147
+ before: beforeEntity,
148
+ targetKey,
149
+ targetType: params.targetType,
150
+ });
151
+ });
152
+ }
153
+
154
+ /*
155
+ * Return named ranges indexed by their stable name key.
156
+ */
157
+ function getSheetNamedRangesByName(
158
+ ranges: SheetNamedRangeObj[] | null | undefined,
159
+ ) {
160
+ const byName = new Map<string, SheetNamedRangeObj>();
161
+ for (const range of ranges || []) {
162
+ const name = String(range?.name || '').trim();
163
+ if (!name || byName.has(name)) {
164
+ throw new Error('INVALID_SHEET_NAMED_RANGE_PATCH');
165
+ }
166
+ byName.set(name, range);
167
+ }
168
+ return byName;
169
+ }
170
+
171
+ /*
172
+ * Append whole-entity named-range operations keyed by range name.
173
+ */
174
+ function appendSheetNamedRangeIntents(
175
+ operations: SheetDesignCommandIntent[],
176
+ beforeRanges: SheetNamedRangeObj[] | null | undefined,
177
+ afterRanges: SheetNamedRangeObj[],
178
+ ) {
179
+ const before = getSheetNamedRangesByName(beforeRanges);
180
+ const after = getSheetNamedRangesByName(afterRanges);
181
+ const names = new Set([...before.keys(), ...after.keys()]);
182
+
183
+ [...names].sort().forEach((targetKey) => {
184
+ const beforeRange = before.get(targetKey);
185
+ const afterRange = after.get(targetKey);
186
+ if (sheetDesignCommandValuesAreEqual(beforeRange, afterRange)) {
187
+ return;
188
+ }
189
+ operations.push({
190
+ operation: afterRange ? 'UPSERT_ENTITY' : 'DELETE_ENTITY',
191
+ targetKey,
192
+ targetType: 'NAMED_RANGE',
193
+ ...(afterRange ? { value: afterRange } : {}),
194
+ });
195
+ });
196
+ }
197
+
198
+ /*
199
+ * Create one opaque id at the user-gesture boundary and keep it through retries.
200
+ */
201
+ export function createSheetCommandId() {
202
+ return (
203
+ globalThis.crypto?.randomUUID?.() ||
204
+ `sc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
205
+ );
206
+ }
207
+
208
+ /*
209
+ * Return the stable scope used by tab-local sessions, queues, and history.
210
+ */
211
+ export function getSheetCommandScopeKey(sheetId: string, sheetTabId: string) {
212
+ return `sheet:${String(sheetId)}:tab:${String(sheetTabId)}`;
213
+ }
214
+
215
+ /*
216
+ * Return the canonical conflict key for one property-level design target.
217
+ */
218
+ export function getSheetDesignOperationTargetKey(
219
+ targetType: SheetDesignOperationTargetType,
220
+ targetKey: string | number,
221
+ property?: string | null,
222
+ ) {
223
+ return [targetType, String(targetKey).trim(), property?.trim() || '*'].join(
224
+ ':',
225
+ );
226
+ }
227
+
228
+ /*
229
+ * Return one intent with normalized string keys and no client-authored before state.
230
+ */
231
+ export function normalizeSheetDesignCommandIntent(
232
+ intent: SheetDesignCommandIntent,
233
+ ): SheetDesignCommandIntent {
234
+ return {
235
+ operation: intent.operation,
236
+ property: intent.property?.trim() || null,
237
+ targetKey: String(intent.targetKey).trim(),
238
+ targetType: intent.targetType,
239
+ ...(intent.operation === 'DELETE_PROPERTY' ||
240
+ intent.operation === 'DELETE_ENTITY'
241
+ ? {}
242
+ : { value: intent.value ?? null }),
243
+ };
244
+ }
245
+
246
+ /*
247
+ * Return whether a whole-map UI design patch can be represented by keyed
248
+ * design commands. Grid geometry stays on the structure-command path.
249
+ */
250
+ export function sheetDesignPatchSupportsDurableCommand(
251
+ patch: SheetDesignPatchInput,
252
+ ) {
253
+ if (
254
+ patch.grid &&
255
+ (Object.hasOwn(patch.grid, 'rowCount') ||
256
+ Object.hasOwn(patch.grid, 'columnCount'))
257
+ ) {
258
+ return false;
259
+ }
260
+
261
+ for (const value of [
262
+ patch.columns,
263
+ patch.defaultCellFormat,
264
+ patch.metadata,
265
+ patch.rows,
266
+ ]) {
267
+ if (
268
+ value !== undefined &&
269
+ value !== null &&
270
+ !parseSheetDesignPatchRecord(value)
271
+ ) {
272
+ return false;
273
+ }
274
+ }
275
+
276
+ try {
277
+ if (patch.namedRanges) {
278
+ getSheetNamedRangesByName(patch.namedRanges);
279
+ }
280
+ } catch {
281
+ return false;
282
+ }
283
+
284
+ return true;
285
+ }
286
+
287
+ /*
288
+ * Translate one whole-map UI design patch into property-keyed client
289
+ * intent. The supplied current design is used only to identify touched keys;
290
+ * the server still captures every authoritative before-state itself.
291
+ */
292
+ export function getSheetDesignCommandIntentsFromPatch(
293
+ currentDesign: SheetDesignObj,
294
+ patch: SheetDesignPatchInput,
295
+ ): SheetDesignCommandIntent[] | null {
296
+ if (!sheetDesignPatchSupportsDurableCommand(patch)) {
297
+ return null;
298
+ }
299
+
300
+ try {
301
+ const operations: SheetDesignCommandIntent[] = [];
302
+ if (typeof patch.columns === 'string') {
303
+ appendSheetDesignAxisIntents(operations, {
304
+ after: parseSheetDesignPatchRecord(patch.columns) || {},
305
+ before: currentDesign.columns as Record<string, SheetDesignRecord>,
306
+ targetType: 'COLUMN',
307
+ });
308
+ }
309
+ if (typeof patch.rows === 'string') {
310
+ appendSheetDesignAxisIntents(operations, {
311
+ after: parseSheetDesignPatchRecord(patch.rows) || {},
312
+ before: currentDesign.rows as Record<string, SheetDesignRecord>,
313
+ targetType: 'ROW',
314
+ });
315
+ }
316
+ if (patch.grid) {
317
+ for (const property of ['frozenColumns', 'frozenRows'] as const) {
318
+ if (
319
+ Object.hasOwn(patch.grid, property) &&
320
+ !sheetDesignCommandValuesAreEqual(
321
+ currentDesign.grid[property],
322
+ patch.grid[property],
323
+ )
324
+ ) {
325
+ operations.push({
326
+ operation: 'SET_PROPERTY',
327
+ property,
328
+ targetKey: 'grid',
329
+ targetType: 'GRID',
330
+ value: patch.grid[property] ?? 0,
331
+ });
332
+ }
333
+ }
334
+ }
335
+ if (patch.defaultCellStyle !== undefined) {
336
+ appendSheetDesignRecordPropertyIntents(operations, {
337
+ after: (patch.defaultCellStyle || {}) as SheetDesignRecord,
338
+ before: (currentDesign.defaultCellStyle || {}) as SheetDesignRecord,
339
+ targetKey: 'default',
340
+ targetType: 'DEFAULT_CELL_STYLE',
341
+ });
342
+ }
343
+ if (typeof patch.defaultCellFormat === 'string') {
344
+ appendSheetDesignRecordPropertyIntents(operations, {
345
+ after: parseSheetDesignPatchRecord(patch.defaultCellFormat) || {},
346
+ before: (currentDesign.defaultCellFormat || {}) as SheetDesignRecord,
347
+ targetKey: 'default',
348
+ targetType: 'DEFAULT_CELL_FORMAT',
349
+ });
350
+ }
351
+ if (typeof patch.metadata === 'string') {
352
+ appendSheetDesignRecordPropertyIntents(operations, {
353
+ after: parseSheetDesignPatchRecord(patch.metadata) || {},
354
+ before: currentDesign.metadata || {},
355
+ targetKey: 'metadata',
356
+ targetType: 'METADATA',
357
+ });
358
+ }
359
+ if (patch.namedRanges) {
360
+ appendSheetNamedRangeIntents(
361
+ operations,
362
+ currentDesign.namedRanges,
363
+ patch.namedRanges,
364
+ );
365
+ }
366
+
367
+ return operations.map(normalizeSheetDesignCommandIntent);
368
+ } catch {
369
+ return null;
370
+ }
371
+ }
372
+
373
+ /*
374
+ * Serialize intent values for the GraphQL String boundary without adding any
375
+ * client-authored before-state.
376
+ */
377
+ export function serializeSheetDesignCommandIntents(
378
+ intents: SheetDesignCommandIntent[],
379
+ ) {
380
+ return intents.map((intent) => {
381
+ const normalized = normalizeSheetDesignCommandIntent(intent);
382
+ const { value, ...withoutValue } = normalized;
383
+ return intent.operation === 'DELETE_ENTITY' ||
384
+ intent.operation === 'DELETE_PROPERTY'
385
+ ? withoutValue
386
+ : { ...withoutValue, value: JSON.stringify(value ?? null) };
387
+ });
388
+ }
389
+
390
+ /*
391
+ * Return the revision allocation for one tab in a command result.
392
+ */
393
+ export function getSheetCommandTabRevision(
394
+ result: SheetCommandResultGQL | null | undefined,
395
+ sheetTabId: string,
396
+ ): SheetCommandTabRevisionGQL | null {
397
+ return (
398
+ result?.tabRevisions?.find(
399
+ (revision) => String(revision.sheetTabId) === String(sheetTabId),
400
+ ) || null
401
+ );
402
+ }
403
+
404
+ /*
405
+ * Return whether authority accepted or idempotently replayed the command.
406
+ */
407
+ export function sheetCommandResultCommitted(
408
+ result: SheetCommandResultGQL | null | undefined,
409
+ ) {
410
+ return (
411
+ result?.commandStatus === 'COMMITTED' ||
412
+ result?.commandStatus === 'REPLAYED'
413
+ );
414
+ }
415
+
416
+ /*
417
+ * Return whether authority rejected the command due to an optimistic conflict.
418
+ */
419
+ export function sheetCommandResultConflicted(
420
+ result: SheetCommandResultGQL | null | undefined,
421
+ ) {
422
+ return result?.commandStatus === 'CONFLICTED' || Boolean(result?.conflict);
423
+ }
@@ -0,0 +1,238 @@
1
+ import type {
2
+ SheetCellFormatObj,
3
+ SheetExportFormatEnum,
4
+ } from '../types/sheet.d.ts';
5
+ import {
6
+ getSheetCellFormattedDisplayValue,
7
+ type SheetNumberFormatCellValues,
8
+ } from './sheetNumberFormat.ts';
9
+
10
+ const FILE_CONSTANTS = {
11
+ // Characters that break file names across OSes/browsers plus control chars
12
+ fileNameIllegalChars: /[\\/:*?"<>|\u0000-\u001F]/g,
13
+ // Characters Excel forbids inside worksheet (tab) names
14
+ tabNameIllegalChars: /[\\/:?*[\]]/g,
15
+ maxFileNameLength: 120,
16
+ // Hard Excel limit for worksheet names
17
+ maxTabNameLength: 31,
18
+ contentTypes: {
19
+ CSV: 'text/csv',
20
+ TSV: 'text/tab-separated-values',
21
+ XLSX: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
22
+ PDF: 'application/pdf',
23
+ } as Record<SheetExportFormatEnum, string>,
24
+ };
25
+
26
+ /*
27
+ * Minimal cell shape the export display logic reads; both SheetCellGQL rows
28
+ * (client) and raw sheet_cells DB rows (server) satisfy it structurally.
29
+ */
30
+ export interface SheetExportCellValues extends SheetNumberFormatCellValues {
31
+ value?: any;
32
+ }
33
+
34
+ /*
35
+ * Return a date-like cell value as an ISO string, mirroring what the client
36
+ * receives over GraphQL. DB rows carry JS Date objects; date-only values keep
37
+ * just the calendar date.
38
+ */
39
+ function getSheetExportRawDateString(
40
+ value: Date | string,
41
+ isDateOnly: boolean,
42
+ ): string {
43
+ if (value instanceof Date) {
44
+ const iso = value.toISOString();
45
+ return isDateOnly ? iso.slice(0, 10) : iso;
46
+ }
47
+
48
+ return String(value);
49
+ }
50
+
51
+ /*
52
+ * Return the raw display string for one sheet cell, mirroring the fallback
53
+ * order of the canvas renderer (getSheetCanvasCellRawDisplayValue in
54
+ * @jsb188/sheet libs/sheet-utils.ts) but tolerating raw DB rows.
55
+ */
56
+ function getSheetCellExportRawDisplayValue(
57
+ cell?: SheetExportCellValues | null,
58
+ ): string {
59
+ if (!cell) {
60
+ return '';
61
+ }
62
+
63
+ if (
64
+ !cell.formulaText &&
65
+ cell.rawInput !== null &&
66
+ cell.rawInput !== undefined
67
+ ) {
68
+ return String(cell.rawInput);
69
+ }
70
+
71
+ if (cell.textValue !== null && cell.textValue !== undefined) {
72
+ return String(cell.textValue);
73
+ }
74
+
75
+ if (cell.numberValue !== null && cell.numberValue !== undefined) {
76
+ return String(cell.numberValue);
77
+ }
78
+
79
+ if (cell.booleanValue !== null && cell.booleanValue !== undefined) {
80
+ return cell.booleanValue ? 'TRUE' : 'FALSE';
81
+ }
82
+
83
+ if (cell.dateValue) {
84
+ return getSheetExportRawDateString(cell.dateValue, true);
85
+ }
86
+
87
+ if (cell.datetimeValue) {
88
+ return getSheetExportRawDateString(cell.datetimeValue, false);
89
+ }
90
+
91
+ if (cell.value !== null && cell.value !== undefined) {
92
+ return typeof cell.value === 'string'
93
+ ? cell.value
94
+ : JSON.stringify(cell.value);
95
+ }
96
+
97
+ return '';
98
+ }
99
+
100
+ /*
101
+ * MAIN ENTRY: return the user-facing display string for one sheet cell for
102
+ * file exports, applying the shared explicit-format engine first and falling
103
+ * back to the same raw display order the canvas uses.
104
+ */
105
+ export function getSheetCellExportDisplayValue(
106
+ cell: SheetExportCellValues | null | undefined,
107
+ resolvedFormat?: SheetCellFormatObj | null,
108
+ timeZone?: string | null,
109
+ ): string {
110
+ const rawDisplayValue = getSheetCellExportRawDisplayValue(cell);
111
+
112
+ if (!cell) {
113
+ return rawDisplayValue;
114
+ }
115
+
116
+ return (
117
+ getSheetCellFormattedDisplayValue(cell, resolvedFormat, timeZone) ??
118
+ rawDisplayValue
119
+ );
120
+ }
121
+
122
+ /*
123
+ * Return one field quoted per RFC 4180 when it contains the delimiter, a
124
+ * quote, or a line break; embedded quotes are doubled.
125
+ */
126
+ function getSheetExportDelimitedField(
127
+ value: string,
128
+ delimiter: string,
129
+ ): string {
130
+ if (
131
+ value.includes(delimiter) ||
132
+ value.includes('"') ||
133
+ value.includes('\n') ||
134
+ value.includes('\r')
135
+ ) {
136
+ return `"${value.replaceAll('"', '""')}"`;
137
+ }
138
+
139
+ return value;
140
+ }
141
+
142
+ /*
143
+ * Serialize a dense display-value matrix into delimited text (CSV/TSV) with
144
+ * RFC 4180 quoting and CRLF line endings.
145
+ */
146
+ export function buildSheetDelimitedText(
147
+ matrix: string[][],
148
+ delimiter: ',' | '\t',
149
+ ): string {
150
+ return matrix
151
+ .map((row) =>
152
+ row
153
+ .map((value) => getSheetExportDelimitedField(value, delimiter))
154
+ .join(delimiter),
155
+ )
156
+ .join('\r\n');
157
+ }
158
+
159
+ /*
160
+ * Return the lowercase file extension for one export format.
161
+ */
162
+ export function getSheetExportFileExtension(
163
+ format: SheetExportFormatEnum,
164
+ ): string {
165
+ return format.toLowerCase();
166
+ }
167
+
168
+ /*
169
+ * Return the HTTP content type for one export format.
170
+ */
171
+ export function getSheetExportContentType(
172
+ format: SheetExportFormatEnum,
173
+ ): string {
174
+ return FILE_CONSTANTS.contentTypes[format];
175
+ }
176
+
177
+ /*
178
+ * Return a base name stripped of characters that are unsafe in download file
179
+ * names, collapsed and capped so Content-Disposition stays sane.
180
+ */
181
+ function getSheetExportSafeBaseName(name: string): string {
182
+ const safeName = name
183
+ .replace(FILE_CONSTANTS.fileNameIllegalChars, ' ')
184
+ .replace(/\s+/g, ' ')
185
+ .trim()
186
+ .slice(0, FILE_CONSTANTS.maxFileNameLength)
187
+ .trim();
188
+
189
+ return safeName || 'Sheet';
190
+ }
191
+
192
+ /*
193
+ * Return the download file name for one export: "Title.xlsx" for whole-workbook
194
+ * exports, "Title - TabName.csv|tsv|pdf" for single-tab exports.
195
+ */
196
+ export function getSheetExportFileName(
197
+ sheetTitle: string,
198
+ tabName: string | null | undefined,
199
+ format: SheetExportFormatEnum,
200
+ ): string {
201
+ const baseName =
202
+ format === 'XLSX' || !tabName ? sheetTitle : `${sheetTitle} - ${tabName}`;
203
+
204
+ return `${getSheetExportSafeBaseName(baseName)}.${getSheetExportFileExtension(format)}`;
205
+ }
206
+
207
+ /*
208
+ * Return an XLSX-legal worksheet name for one sheet tab: illegal characters
209
+ * removed, capped at 31 chars, non-empty, and deduped case-insensitively with
210
+ * " (2)"-style suffixes. Mutates usedNames so callers can loop over tabs.
211
+ */
212
+ export function getSheetExportTabName(
213
+ name: string | null | undefined,
214
+ usedNames: Set<string>,
215
+ ): string {
216
+ const safeName =
217
+ (name || '')
218
+ .replace(FILE_CONSTANTS.tabNameIllegalChars, ' ')
219
+ .replace(/\s+/g, ' ')
220
+ .trim()
221
+ .slice(0, FILE_CONSTANTS.maxTabNameLength)
222
+ .trim() || 'Sheet1';
223
+
224
+ let uniqueName = safeName;
225
+ let suffixNumber = 2;
226
+
227
+ while (usedNames.has(uniqueName.toLowerCase())) {
228
+ const suffix = ` (${suffixNumber})`;
229
+ uniqueName =
230
+ safeName
231
+ .slice(0, FILE_CONSTANTS.maxTabNameLength - suffix.length)
232
+ .trimEnd() + suffix;
233
+ suffixNumber += 1;
234
+ }
235
+
236
+ usedNames.add(uniqueName.toLowerCase());
237
+ return uniqueName;
238
+ }