@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,1211 @@
1
+ import { getCurrencySymbol } from '@jsb188/app/utils/number.ts';
2
+ import { DateTime } from 'luxon';
3
+ import {
4
+ SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS,
5
+ SHEET_NUMBER_FORMAT_PRESET_PATTERNS,
6
+ } from '../constants/sheet.ts';
7
+ import type {
8
+ SheetCellFormatObj,
9
+ SheetCellNumberFormatTypeEnum,
10
+ } from '../types/sheet.d.ts';
11
+
12
+ /*
13
+ * Google/Excel spreadsheet serial date epoch (1899-12-30T00:00:00 UTC).
14
+ * Serial values count wall-clock days since this epoch; the fraction is the
15
+ * time of day. Serials are zone-free by definition.
16
+ */
17
+ const SHEET_SERIAL_EPOCH_MS = Date.UTC(1899, 11, 30);
18
+
19
+ const MS_PER_DAY = 86400000;
20
+
21
+ // Numbers at or beyond this magnitude stringify in exponential notation and
22
+ // cannot round-trip through the digit-placeholder renderer
23
+ const SHEET_NUMBER_FORMAT_MAX_MAGNITUDE = 1e21;
24
+
25
+ // Parsed pattern cache; cleared whole when it hits the cap so long sessions
26
+ // with many custom patterns cannot grow it unbounded
27
+ const SHEET_NUMBER_FORMAT_PARSE_CACHE = new Map<
28
+ string,
29
+ SheetParsedNumberFormat | null
30
+ >();
31
+ const SHEET_NUMBER_FORMAT_PARSE_CACHE_MAX = 256;
32
+
33
+ const SHEET_NUMBER_FORMAT_COLOR_NAMES = [
34
+ 'black',
35
+ 'blue',
36
+ 'cyan',
37
+ 'green',
38
+ 'magenta',
39
+ 'red',
40
+ 'white',
41
+ 'yellow',
42
+ ];
43
+
44
+ export type SheetNumberFormatConditionOperator =
45
+ | '<'
46
+ | '<='
47
+ | '>'
48
+ | '>='
49
+ | '='
50
+ | '<>';
51
+
52
+ export type SheetNumberFormatToken =
53
+ | { kind: 'literal'; text: string }
54
+ | { kind: 'fill' }
55
+ | { kind: 'digit'; placeholder: '0' | '#' | '?' }
56
+ | { kind: 'decimal' }
57
+ | { kind: 'comma' }
58
+ | { kind: 'percent' }
59
+ | { kind: 'slash' }
60
+ | { kind: 'text' }
61
+ | { kind: 'exponent'; sign: '+' | '-'; digits: number }
62
+ | {
63
+ kind: 'date';
64
+ unit: 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second';
65
+ length: number;
66
+ }
67
+ | { kind: 'meridiem'; style: 'AM/PM' | 'am/pm' | 'A/P' | 'a/p' }
68
+ | { kind: 'fractionalSecond'; length: number }
69
+ | { kind: 'elapsed'; unit: 'hour' | 'minute' | 'second'; length: number };
70
+
71
+ export interface SheetNumberFormatSection {
72
+ kind: 'number' | 'date' | 'text';
73
+ tokens: SheetNumberFormatToken[];
74
+ condition?: {
75
+ operator: SheetNumberFormatConditionOperator;
76
+ value: number;
77
+ } | null;
78
+ color?: string | null;
79
+ /* Number-section layout facts precomputed at parse time */
80
+ intPlaceholders: string;
81
+ decPlaceholders: string;
82
+ percentCount: number;
83
+ scaleCommaCount: number;
84
+ grouping: boolean;
85
+ hasFraction: boolean;
86
+ hasExponent: boolean;
87
+ /* Date-section facts */
88
+ hasMeridiem: boolean;
89
+ hasElapsed: boolean;
90
+ hasElapsedHour: boolean;
91
+ hasElapsedMinute: boolean;
92
+ }
93
+
94
+ export interface SheetParsedNumberFormat {
95
+ sections: SheetNumberFormatSection[];
96
+ }
97
+
98
+ export interface SheetResolvedNumberFormat {
99
+ type: SheetCellNumberFormatTypeEnum;
100
+ pattern: string | null;
101
+ currency: string | null;
102
+ }
103
+
104
+ /*
105
+ * Minimal cell value shape the formatter reads; both SheetCellGQL and
106
+ * SheetCellData rows satisfy it structurally.
107
+ */
108
+ export interface SheetNumberFormatCellValues {
109
+ rawInput?: string | null;
110
+ formulaText?: string | null;
111
+ textValue?: string | null;
112
+ numberValue?: number | null;
113
+ booleanValue?: boolean | null;
114
+ dateValue?: Date | string | null;
115
+ datetimeValue?: Date | string | null;
116
+ }
117
+
118
+ /*
119
+ * Return whether a value is a supported number format type enum.
120
+ */
121
+ export function isSheetCellNumberFormatType(
122
+ value: unknown,
123
+ ): value is SheetCellNumberFormatTypeEnum {
124
+ return SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS.includes(
125
+ value as SheetCellNumberFormatTypeEnum,
126
+ );
127
+ }
128
+
129
+ /*
130
+ * Return the effective {type, pattern, currency} for one resolved cell format
131
+ * object, filling preset patterns from the type and substituting the locale
132
+ * currency symbol into currency-family presets. Null when the format object
133
+ * carries no usable number format.
134
+ */
135
+ export function resolveSheetCellNumberFormat(
136
+ format?: SheetCellFormatObj | null,
137
+ locale?: string | null,
138
+ ): SheetResolvedNumberFormat | null {
139
+ const numberFormat = format?.numberFormat;
140
+
141
+ if (
142
+ !numberFormat ||
143
+ typeof numberFormat !== 'object' ||
144
+ !isSheetCellNumberFormatType(numberFormat.type)
145
+ ) {
146
+ return null;
147
+ }
148
+
149
+ const currency =
150
+ typeof numberFormat.currency === 'string' && numberFormat.currency
151
+ ? numberFormat.currency
152
+ : null;
153
+ const explicitPattern =
154
+ typeof numberFormat.pattern === 'string' && numberFormat.pattern
155
+ ? numberFormat.pattern
156
+ : null;
157
+ let pattern =
158
+ explicitPattern || SHEET_NUMBER_FORMAT_PRESET_PATTERNS[numberFormat.type];
159
+
160
+ // Preset currency-family patterns carry a "$" literal that stands in for
161
+ // the resolved locale symbol; explicit custom patterns are left untouched
162
+ if (!explicitPattern && pattern && currency) {
163
+ let symbol = '';
164
+
165
+ try {
166
+ symbol = getCurrencySymbol(locale || 'en-US', currency);
167
+ } catch {
168
+ symbol = '';
169
+ }
170
+
171
+ if (symbol) {
172
+ pattern = pattern.replaceAll('"$"', `"${symbol.replaceAll('"', '')}"`);
173
+ }
174
+ }
175
+
176
+ return {
177
+ currency,
178
+ pattern: pattern || null,
179
+ type: numberFormat.type,
180
+ };
181
+ }
182
+
183
+ /*
184
+ * Split one pattern into top-level sections on ";", respecting quoted
185
+ * literals, escapes, and bracket blocks.
186
+ */
187
+ function splitSheetNumberFormatSections(pattern: string): string[] {
188
+ const sections: string[] = [];
189
+ let current = '';
190
+ let inQuote = false;
191
+ let inBracket = false;
192
+
193
+ for (let i = 0; i < pattern.length; i++) {
194
+ const char = pattern[i];
195
+
196
+ if (char === '\\' && !inQuote) {
197
+ current += char + (pattern[i + 1] || '');
198
+ i++;
199
+ continue;
200
+ }
201
+
202
+ if (char === '"') {
203
+ inQuote = !inQuote;
204
+ } else if (!inQuote && char === '[') {
205
+ inBracket = true;
206
+ } else if (!inQuote && char === ']') {
207
+ inBracket = false;
208
+ } else if (!inQuote && !inBracket && char === ';') {
209
+ sections.push(current);
210
+ current = '';
211
+ continue;
212
+ }
213
+
214
+ current += char;
215
+ }
216
+
217
+ sections.push(current);
218
+ return sections.slice(0, 4);
219
+ }
220
+
221
+ /*
222
+ * Return one parsed bracket block token/metadata for a section, or null when
223
+ * the block is unknown and should be ignored.
224
+ */
225
+ function parseSheetNumberFormatBracket(
226
+ content: string,
227
+ section: SheetNumberFormatSection,
228
+ ): SheetNumberFormatToken | null {
229
+ // Currency with optional locale id, e.g. [$€-407] or [$USD]
230
+ const currencyMatch = content.match(/^\$([^-\]]*)(?:-[^\]]*)?$/);
231
+ if (currencyMatch) {
232
+ return currencyMatch[1]
233
+ ? { kind: 'literal', text: currencyMatch[1] }
234
+ : null;
235
+ }
236
+
237
+ // Elapsed duration units, e.g. [h] [mm] [s]
238
+ const elapsedMatch = content.match(/^(h+|m+|s+)$/i);
239
+ if (elapsedMatch) {
240
+ const letter = elapsedMatch[1][0].toLowerCase();
241
+ const unit = letter === 'h' ? 'hour' : letter === 'm' ? 'minute' : 'second';
242
+ return { kind: 'elapsed', length: elapsedMatch[1].length, unit };
243
+ }
244
+
245
+ // Section condition, e.g. [>100] or [<=-5.5]
246
+ const conditionMatch = content.match(
247
+ /^(<=|>=|<>|<|>|=)\s*(-?\d+(?:\.\d+)?)$/,
248
+ );
249
+ if (conditionMatch) {
250
+ section.condition = {
251
+ operator: conditionMatch[1] as SheetNumberFormatConditionOperator,
252
+ value: Number(conditionMatch[2]),
253
+ };
254
+ return null;
255
+ }
256
+
257
+ // Color tags are parsed as metadata only; the canvas does not paint them yet
258
+ const lowerContent = content.toLowerCase();
259
+ if (
260
+ SHEET_NUMBER_FORMAT_COLOR_NAMES.includes(lowerContent) ||
261
+ /^color\s*\d+$/.test(lowerContent)
262
+ ) {
263
+ section.color = content;
264
+ return null;
265
+ }
266
+
267
+ return null;
268
+ }
269
+
270
+ /*
271
+ * Tokenize one pattern section into a raw token stream. Date-vs-minute and
272
+ * comma semantics are resolved afterwards in classifySheetNumberFormatSection.
273
+ */
274
+ function tokenizeSheetNumberFormatSection(
275
+ src: string,
276
+ ): SheetNumberFormatSection | null {
277
+ const section: SheetNumberFormatSection = {
278
+ condition: null,
279
+ color: null,
280
+ decPlaceholders: '',
281
+ grouping: false,
282
+ hasElapsed: false,
283
+ hasElapsedHour: false,
284
+ hasElapsedMinute: false,
285
+ hasExponent: false,
286
+ hasFraction: false,
287
+ hasMeridiem: false,
288
+ intPlaceholders: '',
289
+ kind: 'number',
290
+ percentCount: 0,
291
+ scaleCommaCount: 0,
292
+ tokens: [],
293
+ };
294
+ const tokens = section.tokens;
295
+
296
+ /*
297
+ * Append literal text, merging into a previous literal token.
298
+ */
299
+ const pushLiteral = (text: string) => {
300
+ if (!text) {
301
+ return;
302
+ }
303
+
304
+ const lastToken = tokens[tokens.length - 1];
305
+
306
+ if (lastToken?.kind === 'literal') {
307
+ lastToken.text += text;
308
+ } else {
309
+ tokens.push({ kind: 'literal', text });
310
+ }
311
+ };
312
+
313
+ for (let i = 0; i < src.length; i++) {
314
+ const char = src[i];
315
+
316
+ if (char === '"') {
317
+ const end = src.indexOf('"', i + 1);
318
+ if (end === -1) {
319
+ pushLiteral(src.slice(i + 1));
320
+ break;
321
+ }
322
+ pushLiteral(src.slice(i + 1, end));
323
+ i = end;
324
+ } else if (char === '\\') {
325
+ pushLiteral(src[i + 1] || '');
326
+ i++;
327
+ } else if (char === '_') {
328
+ // Skip-width placeholder renders as one space
329
+ pushLiteral(' ');
330
+ i++;
331
+ } else if (char === '*') {
332
+ tokens.push({ kind: 'fill' });
333
+ i++;
334
+ } else if (char === '[') {
335
+ const end = src.indexOf(']', i + 1);
336
+ if (end === -1) {
337
+ return null;
338
+ }
339
+ const bracketToken = parseSheetNumberFormatBracket(
340
+ src.slice(i + 1, end),
341
+ section,
342
+ );
343
+ if (bracketToken) {
344
+ tokens.push(bracketToken);
345
+ }
346
+ i = end;
347
+ } else if (char === '0' || char === '#' || char === '?') {
348
+ tokens.push({ kind: 'digit', placeholder: char });
349
+ } else if (char === '.') {
350
+ tokens.push({ kind: 'decimal' });
351
+ } else if (char === ',') {
352
+ tokens.push({ kind: 'comma' });
353
+ } else if (char === '%') {
354
+ tokens.push({ kind: 'percent' });
355
+ } else if (char === '/') {
356
+ tokens.push({ kind: 'slash' });
357
+ } else if (char === '@') {
358
+ tokens.push({ kind: 'text' });
359
+ } else if (
360
+ (char === 'E' || char === 'e') &&
361
+ (src[i + 1] === '+' || src[i + 1] === '-')
362
+ ) {
363
+ const sign = src[i + 1] as '+' | '-';
364
+ let digits = 0;
365
+ let j = i + 2;
366
+ while (
367
+ j < src.length &&
368
+ (src[j] === '0' || src[j] === '#' || src[j] === '?')
369
+ ) {
370
+ digits++;
371
+ j++;
372
+ }
373
+ tokens.push({ digits: Math.max(digits, 1), kind: 'exponent', sign });
374
+ i = j - 1;
375
+ } else if (/^(am\/pm|a\/p)/i.test(src.slice(i, i + 5))) {
376
+ const isLong = src.slice(i, i + 5).toLowerCase() === 'am/pm';
377
+ const isLower = char === 'a';
378
+ tokens.push({
379
+ kind: 'meridiem',
380
+ style: isLong ? (isLower ? 'am/pm' : 'AM/PM') : isLower ? 'a/p' : 'A/P',
381
+ });
382
+ i += isLong ? 4 : 2;
383
+ } else if (/[ymdhs]/i.test(char)) {
384
+ const letter = char.toLowerCase();
385
+ let length = 1;
386
+ while (src[i + 1]?.toLowerCase() === letter) {
387
+ length++;
388
+ i++;
389
+ }
390
+ const unit =
391
+ letter === 'y'
392
+ ? ('year' as const)
393
+ : letter === 'm'
394
+ ? ('month' as const)
395
+ : letter === 'd'
396
+ ? ('day' as const)
397
+ : letter === 'h'
398
+ ? ('hour' as const)
399
+ : ('second' as const);
400
+ tokens.push({ kind: 'date', length, unit });
401
+ } else {
402
+ pushLiteral(char);
403
+ }
404
+ }
405
+
406
+ return section;
407
+ }
408
+
409
+ /*
410
+ * Resolve token ambiguities and precompute section layout facts: classify the
411
+ * section kind, disambiguate month-vs-minute, fold date punctuation into
412
+ * literals, and derive digit placeholder/grouping/scaling info.
413
+ */
414
+ function classifySheetNumberFormatSection(
415
+ section: SheetNumberFormatSection,
416
+ ): SheetNumberFormatSection {
417
+ const tokens = section.tokens;
418
+ const hasDateTokens = tokens.some(
419
+ (token) =>
420
+ token.kind === 'date' ||
421
+ token.kind === 'elapsed' ||
422
+ token.kind === 'meridiem',
423
+ );
424
+ const hasTextToken = tokens.some((token) => token.kind === 'text');
425
+
426
+ if (hasDateTokens) {
427
+ section.kind = 'date';
428
+ section.hasMeridiem = tokens.some((token) => token.kind === 'meridiem');
429
+ section.hasElapsed = tokens.some((token) => token.kind === 'elapsed');
430
+ section.hasElapsedHour = tokens.some(
431
+ (token) => token.kind === 'elapsed' && token.unit === 'hour',
432
+ );
433
+ section.hasElapsedMinute = tokens.some(
434
+ (token) => token.kind === 'elapsed' && token.unit === 'minute',
435
+ );
436
+
437
+ // Month tokens mean minutes when preceded by an hour token or followed
438
+ // by a seconds token within the same section
439
+ let lastTimeUnit: string | null = null;
440
+ tokens.forEach((token, index) => {
441
+ if (token.kind === 'elapsed') {
442
+ lastTimeUnit = token.unit;
443
+ } else if (token.kind !== 'date') {
444
+ return;
445
+ } else if (token.unit === 'month' && token.length <= 2) {
446
+ const nextDateToken = tokens
447
+ .slice(index + 1)
448
+ .find((t) => t.kind === 'date' || t.kind === 'elapsed') as
449
+ | Extract<SheetNumberFormatToken, { kind: 'date' | 'elapsed' }>
450
+ | undefined;
451
+
452
+ if (lastTimeUnit === 'hour' || nextDateToken?.unit === 'second') {
453
+ token.unit = 'minute';
454
+ }
455
+ lastTimeUnit = token.unit;
456
+ } else {
457
+ lastTimeUnit = token.unit;
458
+ }
459
+ });
460
+
461
+ // Date punctuation renders literally; ".0" runs after seconds become
462
+ // fractional-second tokens
463
+ for (let i = 0; i < tokens.length; i++) {
464
+ const token = tokens[i];
465
+
466
+ if (token.kind === 'decimal') {
467
+ const prevToken = tokens[i - 1];
468
+ const nextToken = tokens[i + 1];
469
+ const followsSeconds =
470
+ (prevToken?.kind === 'date' && prevToken.unit === 'second') ||
471
+ (prevToken?.kind === 'elapsed' && prevToken.unit === 'second');
472
+
473
+ if (
474
+ followsSeconds &&
475
+ nextToken?.kind === 'digit' &&
476
+ nextToken.placeholder === '0'
477
+ ) {
478
+ let length = 0;
479
+ while (tokens[i + 1]?.kind === 'digit') {
480
+ tokens.splice(i + 1, 1);
481
+ length++;
482
+ }
483
+ tokens[i] = { kind: 'fractionalSecond', length };
484
+ } else {
485
+ tokens[i] = { kind: 'literal', text: '.' };
486
+ }
487
+ } else if (token.kind === 'comma') {
488
+ tokens[i] = { kind: 'literal', text: ',' };
489
+ } else if (token.kind === 'slash') {
490
+ tokens[i] = { kind: 'literal', text: '/' };
491
+ }
492
+ }
493
+
494
+ return section;
495
+ }
496
+
497
+ if (hasTextToken) {
498
+ section.kind = 'text';
499
+ return section;
500
+ }
501
+
502
+ section.kind = 'number';
503
+
504
+ const digitIndexes = tokens.reduce<number[]>((indexes, token, index) => {
505
+ if (token.kind === 'digit') {
506
+ indexes.push(index);
507
+ }
508
+ return indexes;
509
+ }, []);
510
+
511
+ if (!digitIndexes.length) {
512
+ return section;
513
+ }
514
+
515
+ const firstDigitIndex = digitIndexes[0];
516
+ const lastDigitIndex = digitIndexes[digitIndexes.length - 1];
517
+ const decimalIndex = tokens.findIndex((token) => token.kind === 'decimal');
518
+
519
+ section.hasExponent = tokens.some((token) => token.kind === 'exponent');
520
+ section.percentCount = tokens.filter(
521
+ (token) => token.kind === 'percent',
522
+ ).length;
523
+ section.hasFraction = tokens.some(
524
+ (token, index) =>
525
+ token.kind === 'slash' &&
526
+ digitIndexes.some((digitIndex) => digitIndex < index) &&
527
+ digitIndexes.some((digitIndex) => digitIndex > index),
528
+ );
529
+
530
+ // Commas between digit placeholders enable grouping; commas after the last
531
+ // digit placeholder scale the value by 1000 each; the rest are literals
532
+ tokens.forEach((token, index) => {
533
+ if (token.kind !== 'comma') {
534
+ return;
535
+ }
536
+
537
+ if (index > firstDigitIndex && index < lastDigitIndex) {
538
+ section.grouping = true;
539
+ } else if (index > lastDigitIndex) {
540
+ section.scaleCommaCount++;
541
+ } else {
542
+ tokens[index] = { kind: 'literal', text: ',' };
543
+ }
544
+ });
545
+
546
+ tokens.forEach((token, index) => {
547
+ if (token.kind !== 'digit') {
548
+ return;
549
+ }
550
+
551
+ if (decimalIndex !== -1 && index > decimalIndex) {
552
+ section.decPlaceholders += token.placeholder;
553
+ } else {
554
+ section.intPlaceholders += token.placeholder;
555
+ }
556
+ });
557
+
558
+ return section;
559
+ }
560
+
561
+ /*
562
+ * Parse one Google-Sheets-style number format pattern into render-ready
563
+ * sections. Results are cached by pattern; null means unusable pattern (the
564
+ * caller should fall back to raw display).
565
+ */
566
+ export function parseSheetNumberFormatPattern(
567
+ pattern: string,
568
+ ): SheetParsedNumberFormat | null {
569
+ if (typeof pattern !== 'string' || !pattern || pattern.length > 500) {
570
+ return null;
571
+ }
572
+
573
+ if (SHEET_NUMBER_FORMAT_PARSE_CACHE.has(pattern)) {
574
+ return SHEET_NUMBER_FORMAT_PARSE_CACHE.get(pattern) || null;
575
+ }
576
+
577
+ let parsed: SheetParsedNumberFormat | null = null;
578
+
579
+ try {
580
+ const sections = splitSheetNumberFormatSections(pattern).map((sectionSrc) =>
581
+ tokenizeSheetNumberFormatSection(sectionSrc),
582
+ );
583
+
584
+ if (!sections.some((section) => section === null) && sections.length) {
585
+ parsed = {
586
+ sections: (sections as SheetNumberFormatSection[]).map(
587
+ classifySheetNumberFormatSection,
588
+ ),
589
+ };
590
+ }
591
+ } catch {
592
+ parsed = null;
593
+ }
594
+
595
+ if (
596
+ SHEET_NUMBER_FORMAT_PARSE_CACHE.size >= SHEET_NUMBER_FORMAT_PARSE_CACHE_MAX
597
+ ) {
598
+ SHEET_NUMBER_FORMAT_PARSE_CACHE.clear();
599
+ }
600
+
601
+ SHEET_NUMBER_FORMAT_PARSE_CACHE.set(pattern, parsed);
602
+ return parsed;
603
+ }
604
+
605
+ /*
606
+ * Return the serial-day value for one Luxon date-time, reading its wall-clock
607
+ * components so the serial stays zone-free.
608
+ */
609
+ export function getSheetSerialFromDateTime(dateTime: DateTime): number {
610
+ const utcClock = DateTime.utc(
611
+ dateTime.year,
612
+ dateTime.month,
613
+ dateTime.day,
614
+ dateTime.hour,
615
+ dateTime.minute,
616
+ dateTime.second,
617
+ dateTime.millisecond,
618
+ );
619
+
620
+ return (utcClock.toMillis() - SHEET_SERIAL_EPOCH_MS) / MS_PER_DAY;
621
+ }
622
+
623
+ /*
624
+ * Return the UTC Luxon date-time represented by one serial-day value.
625
+ */
626
+ export function getSheetDateTimeFromSerial(serial: number): DateTime {
627
+ return DateTime.fromMillis(
628
+ SHEET_SERIAL_EPOCH_MS + Math.round(serial * MS_PER_DAY),
629
+ { zone: 'utc' },
630
+ );
631
+ }
632
+
633
+ /*
634
+ * Insert thousands separators into one plain digit string.
635
+ */
636
+ function addSheetNumberFormatGrouping(digits: string): string {
637
+ return digits.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
638
+ }
639
+
640
+ /*
641
+ * Render the integer digit region for one number section: pads missing
642
+ * leading positions per placeholder type and applies grouping.
643
+ */
644
+ function renderSheetNumberFormatIntegerPart(
645
+ intDigits: string,
646
+ placeholders: string,
647
+ grouping: boolean,
648
+ ): string {
649
+ let zeroPad = '';
650
+ let spacePad = '';
651
+ const missingCount = Math.max(placeholders.length - intDigits.length, 0);
652
+
653
+ for (let i = 0; i < missingCount; i++) {
654
+ if (placeholders[i] === '0') {
655
+ zeroPad += '0';
656
+ } else if (placeholders[i] === '?') {
657
+ spacePad += ' ';
658
+ }
659
+ }
660
+
661
+ const fullDigits = zeroPad + intDigits;
662
+
663
+ return (
664
+ spacePad +
665
+ (grouping && fullDigits
666
+ ? addSheetNumberFormatGrouping(fullDigits)
667
+ : fullDigits)
668
+ );
669
+ }
670
+
671
+ /*
672
+ * Render the decimal digit region for one number section: trims insignificant
673
+ * trailing zeros per placeholder type ("#" drops, "?" pads with space).
674
+ */
675
+ function renderSheetNumberFormatDecimalPart(
676
+ decDigits: string,
677
+ placeholders: string,
678
+ ): string {
679
+ const chars = decDigits.split('');
680
+
681
+ for (let i = chars.length - 1; i >= 0; i--) {
682
+ if (chars[i] !== '0' || placeholders[i] === '0') {
683
+ break;
684
+ }
685
+
686
+ if (placeholders[i] === '#') {
687
+ chars.pop();
688
+ } else if (placeholders[i] === '?') {
689
+ chars[i] = ' ';
690
+ }
691
+ }
692
+
693
+ return chars.join('');
694
+ }
695
+
696
+ /*
697
+ * Return {mantissa, exponent} for scientific rendering where the mantissa
698
+ * keeps as many integer digits as the section has integer placeholders.
699
+ */
700
+ function getSheetNumberFormatScientificParts(
701
+ absValue: number,
702
+ intPlaceholderCount: number,
703
+ decCount: number,
704
+ ) {
705
+ if (!absValue) {
706
+ return { exponent: 0, mantissa: 0 };
707
+ }
708
+
709
+ const digitCount = Math.max(intPlaceholderCount, 1);
710
+ let exponent = Math.floor(Math.log10(absValue)) - (digitCount - 1);
711
+ let mantissa = absValue / Math.pow(10, exponent);
712
+
713
+ // Rounding can push the mantissa past its digit budget (9.99 -> 10.0)
714
+ if (Number(mantissa.toFixed(decCount)) >= Math.pow(10, digitCount)) {
715
+ exponent += 1;
716
+ mantissa = absValue / Math.pow(10, exponent);
717
+ }
718
+
719
+ return { exponent, mantissa };
720
+ }
721
+
722
+ /*
723
+ * Render one non-negative number through one parsed number section's tokens.
724
+ */
725
+ function renderSheetNumberFormatSection(
726
+ section: SheetNumberFormatSection,
727
+ absValue: number,
728
+ ): string {
729
+ // Fraction patterns degrade to the plain decimal representation in v1
730
+ if (section.hasFraction) {
731
+ return String(absValue);
732
+ }
733
+
734
+ const decCount = section.decPlaceholders.length;
735
+ let intDigits = '';
736
+ let decDigits = '';
737
+ let exponentValue = 0;
738
+
739
+ if (section.hasExponent) {
740
+ const scientific = getSheetNumberFormatScientificParts(
741
+ absValue,
742
+ section.intPlaceholders.length,
743
+ decCount,
744
+ );
745
+ const fixedParts = scientific.mantissa.toFixed(decCount).split('.');
746
+ intDigits = fixedParts[0];
747
+ decDigits = fixedParts[1] || '';
748
+ exponentValue = scientific.exponent;
749
+ } else {
750
+ const fixedParts = absValue.toFixed(decCount).split('.');
751
+ intDigits = fixedParts[0];
752
+ decDigits = fixedParts[1] || '';
753
+ }
754
+
755
+ // A zero integer part yields no digits so "#" renders empty, "0" pads back
756
+ // to "0", and "?" pads to one space
757
+ if (intDigits === '0') {
758
+ intDigits = '';
759
+ }
760
+
761
+ const decOut = renderSheetNumberFormatDecimalPart(
762
+ decDigits,
763
+ section.decPlaceholders,
764
+ );
765
+ let out = '';
766
+ let intRendered = false;
767
+ let decRendered = false;
768
+ let passedDecimal = false;
769
+
770
+ for (const token of section.tokens) {
771
+ switch (token.kind) {
772
+ case 'literal':
773
+ out += token.text;
774
+ break;
775
+ case 'percent':
776
+ out += '%';
777
+ break;
778
+ case 'decimal':
779
+ passedDecimal = true;
780
+ if (decOut) {
781
+ out += '.';
782
+ }
783
+ break;
784
+ case 'digit':
785
+ // Each digit region renders whole at its first placeholder; the
786
+ // remaining placeholders emit nothing
787
+ if (!passedDecimal && !intRendered) {
788
+ out += renderSheetNumberFormatIntegerPart(
789
+ intDigits,
790
+ section.intPlaceholders,
791
+ section.grouping,
792
+ );
793
+ intRendered = true;
794
+ } else if (passedDecimal && !decRendered) {
795
+ out += decOut;
796
+ decRendered = true;
797
+ }
798
+ break;
799
+ case 'exponent': {
800
+ const absExponent = Math.abs(exponentValue);
801
+ const sign = exponentValue < 0 ? '-' : token.sign === '+' ? '+' : '';
802
+ out += `E${sign}${String(absExponent).padStart(token.digits, '0')}`;
803
+ break;
804
+ }
805
+ default:
806
+ // fill/slash/comma/text/date tokens render nothing in number sections
807
+ break;
808
+ }
809
+ }
810
+
811
+ return out;
812
+ }
813
+
814
+ /*
815
+ * Render one serial-day duration/date value through one parsed date section.
816
+ */
817
+ function renderSheetDateFormatSection(
818
+ section: SheetNumberFormatSection,
819
+ dateTime: DateTime,
820
+ serial: number,
821
+ locale?: string | null,
822
+ ): string | null {
823
+ if (!section.hasElapsed && (serial < 0 || !dateTime.isValid)) {
824
+ return null;
825
+ }
826
+
827
+ const localized = locale ? dateTime.setLocale(locale) : dateTime;
828
+ const totalSeconds = Math.round(Math.abs(serial) * 86400);
829
+ let out = section.hasElapsed && serial < 0 ? '-' : '';
830
+
831
+ for (const token of section.tokens) {
832
+ if (token.kind === 'literal') {
833
+ out += token.text;
834
+ continue;
835
+ }
836
+
837
+ if (token.kind === 'meridiem') {
838
+ const isPM = localized.hour >= 12;
839
+ const long =
840
+ token.style === 'AM/PM'
841
+ ? isPM
842
+ ? 'PM'
843
+ : 'AM'
844
+ : token.style === 'am/pm'
845
+ ? isPM
846
+ ? 'pm'
847
+ : 'am'
848
+ : null;
849
+ out +=
850
+ long ?? (token.style === 'A/P' ? (isPM ? 'P' : 'A') : isPM ? 'p' : 'a');
851
+ continue;
852
+ }
853
+
854
+ if (token.kind === 'elapsed') {
855
+ const total =
856
+ token.unit === 'hour'
857
+ ? Math.floor(totalSeconds / 3600)
858
+ : token.unit === 'minute'
859
+ ? Math.floor(totalSeconds / 60)
860
+ : totalSeconds;
861
+ out += String(total).padStart(token.length, '0');
862
+ continue;
863
+ }
864
+
865
+ if (token.kind === 'fractionalSecond') {
866
+ out +=
867
+ '.' +
868
+ String(
869
+ Math.floor(
870
+ (localized.millisecond * Math.pow(10, token.length)) / 1000,
871
+ ),
872
+ ).padStart(token.length, '0');
873
+ continue;
874
+ }
875
+
876
+ if (token.kind !== 'date') {
877
+ continue;
878
+ }
879
+
880
+ switch (token.unit) {
881
+ case 'year':
882
+ out +=
883
+ token.length >= 3
884
+ ? String(localized.year).padStart(4, '0')
885
+ : String(localized.year % 100).padStart(2, '0');
886
+ break;
887
+ case 'month':
888
+ out +=
889
+ token.length === 1
890
+ ? String(localized.month)
891
+ : token.length === 2
892
+ ? String(localized.month).padStart(2, '0')
893
+ : token.length === 3
894
+ ? localized.monthShort
895
+ : token.length === 4
896
+ ? localized.monthLong
897
+ : (localized.monthLong || '').slice(0, 1);
898
+ break;
899
+ case 'day':
900
+ out +=
901
+ token.length === 1
902
+ ? String(localized.day)
903
+ : token.length === 2
904
+ ? String(localized.day).padStart(2, '0')
905
+ : token.length === 3
906
+ ? localized.weekdayShort
907
+ : localized.weekdayLong;
908
+ break;
909
+ case 'hour': {
910
+ // Remainder hours under an elapsed-minute/second section make no
911
+ // sense; hours always come from the clock
912
+ const hourValue = section.hasMeridiem
913
+ ? localized.hour % 12 || 12
914
+ : localized.hour;
915
+ out +=
916
+ token.length >= 2
917
+ ? String(hourValue).padStart(2, '0')
918
+ : String(hourValue);
919
+ break;
920
+ }
921
+ case 'minute': {
922
+ const minuteValue = section.hasElapsedHour
923
+ ? Math.floor((totalSeconds % 3600) / 60)
924
+ : localized.minute;
925
+ out +=
926
+ token.length >= 2
927
+ ? String(minuteValue).padStart(2, '0')
928
+ : String(minuteValue);
929
+ break;
930
+ }
931
+ case 'second': {
932
+ const secondValue = section.hasElapsed
933
+ ? totalSeconds % 60
934
+ : localized.second;
935
+ out +=
936
+ token.length >= 2
937
+ ? String(secondValue).padStart(2, '0')
938
+ : String(secondValue);
939
+ break;
940
+ }
941
+ }
942
+ }
943
+
944
+ return out;
945
+ }
946
+
947
+ /*
948
+ * Render one text value through one parsed text section ("@" substitution).
949
+ */
950
+ function renderSheetTextFormatSection(
951
+ section: SheetNumberFormatSection,
952
+ text: string,
953
+ ): string {
954
+ return section.tokens.reduce((out, token) => {
955
+ if (token.kind === 'text') {
956
+ return out + text;
957
+ }
958
+
959
+ return token.kind === 'literal' ? out + token.text : out;
960
+ }, '');
961
+ }
962
+
963
+ /*
964
+ * Return whether one section condition matches a value.
965
+ */
966
+ function sheetNumberFormatConditionMatches(
967
+ condition: { operator: SheetNumberFormatConditionOperator; value: number },
968
+ value: number,
969
+ ): boolean {
970
+ switch (condition.operator) {
971
+ case '<':
972
+ return value < condition.value;
973
+ case '<=':
974
+ return value <= condition.value;
975
+ case '>':
976
+ return value > condition.value;
977
+ case '>=':
978
+ return value >= condition.value;
979
+ case '=':
980
+ return value === condition.value;
981
+ case '<>':
982
+ return value !== condition.value;
983
+ }
984
+ }
985
+
986
+ /*
987
+ * Pick the section for one numeric value: explicit conditions win, otherwise
988
+ * positional pos/neg/zero semantics with Google's round-before-choosing rule.
989
+ */
990
+ function pickSheetNumberFormatSection(
991
+ parsed: SheetParsedNumberFormat,
992
+ value: number,
993
+ ): { section: SheetNumberFormatSection; useAutoMinus: boolean } | null {
994
+ const sections = parsed.sections.filter(
995
+ (section) => section.kind !== 'text' || parsed.sections.length === 1,
996
+ );
997
+
998
+ if (!sections.length) {
999
+ return null;
1000
+ }
1001
+
1002
+ if (sections.some((section) => section.condition)) {
1003
+ const matched =
1004
+ sections.find(
1005
+ (section) =>
1006
+ section.condition &&
1007
+ sheetNumberFormatConditionMatches(section.condition, value),
1008
+ ) ||
1009
+ sections.find((section) => !section.condition) ||
1010
+ sections[sections.length - 1];
1011
+
1012
+ return { section: matched, useAutoMinus: value < 0 };
1013
+ }
1014
+
1015
+ const positive = sections[0];
1016
+ const negative = sections.length >= 2 ? sections[1] : null;
1017
+ const zero = sections.length >= 3 ? sections[2] : null;
1018
+
1019
+ // Round with the sign-picked section first so values like -0.004 with two
1020
+ // decimals land in the positive/zero section, not "(0.00)"
1021
+ const tentative = value < 0 && negative ? negative : positive;
1022
+ const scaled =
1023
+ (value * Math.pow(100, tentative.percentCount)) /
1024
+ Math.pow(1000, tentative.scaleCommaCount);
1025
+ const rounded =
1026
+ tentative.kind === 'number' && !tentative.hasExponent
1027
+ ? Number(Math.abs(scaled).toFixed(tentative.decPlaceholders.length))
1028
+ : Math.abs(scaled);
1029
+
1030
+ if (rounded === 0) {
1031
+ return { section: zero || positive, useAutoMinus: false };
1032
+ }
1033
+
1034
+ if (value < 0) {
1035
+ return negative
1036
+ ? { section: negative, useAutoMinus: false }
1037
+ : { section: positive, useAutoMinus: true };
1038
+ }
1039
+
1040
+ return { section: positive, useAutoMinus: false };
1041
+ }
1042
+
1043
+ /*
1044
+ * Format one numeric value with one parsed pattern, dispatching to date
1045
+ * rendering via serial conversion when the chosen section uses date tokens.
1046
+ */
1047
+ export function formatSheetNumberValue(
1048
+ value: number,
1049
+ parsed: SheetParsedNumberFormat,
1050
+ locale?: string | null,
1051
+ ): string | null {
1052
+ if (
1053
+ !Number.isFinite(value) ||
1054
+ Math.abs(value) >= SHEET_NUMBER_FORMAT_MAX_MAGNITUDE
1055
+ ) {
1056
+ return null;
1057
+ }
1058
+
1059
+ const picked = pickSheetNumberFormatSection(parsed, value);
1060
+
1061
+ if (!picked) {
1062
+ return null;
1063
+ }
1064
+
1065
+ if (picked.section.kind === 'date') {
1066
+ return renderSheetDateFormatSection(
1067
+ picked.section,
1068
+ getSheetDateTimeFromSerial(value),
1069
+ value,
1070
+ locale,
1071
+ );
1072
+ }
1073
+
1074
+ if (picked.section.kind === 'text') {
1075
+ return null;
1076
+ }
1077
+
1078
+ const scaled =
1079
+ (Math.abs(value) * Math.pow(100, picked.section.percentCount)) /
1080
+ Math.pow(1000, picked.section.scaleCommaCount);
1081
+ const rendered = renderSheetNumberFormatSection(picked.section, scaled);
1082
+ const roundedIsZero =
1083
+ !picked.section.hasExponent &&
1084
+ Number(scaled.toFixed(picked.section.decPlaceholders.length)) === 0;
1085
+
1086
+ return picked.useAutoMinus && !roundedIsZero ? `-${rendered}` : rendered;
1087
+ }
1088
+
1089
+ /*
1090
+ * Return the Luxon date-time for one cell's date-like value. Canonical typed
1091
+ * mirrors win; a strict ISO text mirror also supports current region facades.
1092
+ * Date-only values keep their wall clock, while datetimes shift by time zone.
1093
+ */
1094
+ function getSheetCellFormatDateTime(
1095
+ cell: SheetNumberFormatCellValues,
1096
+ timeZone?: string | null,
1097
+ ): DateTime | null {
1098
+ const isoTextValue =
1099
+ typeof cell.textValue === 'string' ? cell.textValue.trim() : '';
1100
+ const textDateValue = /^\d{4}-\d{2}-\d{2}$/.test(isoTextValue)
1101
+ ? isoTextValue
1102
+ : null;
1103
+ const textDateTimeValue = /^\d{4}-\d{2}-\d{2}T/.test(isoTextValue)
1104
+ ? isoTextValue
1105
+ : null;
1106
+ const dateValue = cell.dateValue || textDateValue;
1107
+ const datetimeValue = cell.datetimeValue || textDateTimeValue;
1108
+ const value = dateValue || datetimeValue;
1109
+
1110
+ if (!value) {
1111
+ return null;
1112
+ }
1113
+
1114
+ const dateTime =
1115
+ value instanceof Date
1116
+ ? DateTime.fromJSDate(value, { zone: 'utc' })
1117
+ : DateTime.fromISO(String(value), { setZone: true });
1118
+
1119
+ if (!dateTime.isValid) {
1120
+ return null;
1121
+ }
1122
+
1123
+ if (datetimeValue && !dateValue && timeZone) {
1124
+ const zoned = dateTime.setZone(timeZone);
1125
+ return zoned.isValid ? zoned : dateTime;
1126
+ }
1127
+
1128
+ return dateTime;
1129
+ }
1130
+
1131
+ /*
1132
+ * SINGLE SOURCE OF TRUTH for explicit sheet value formatting: return the
1133
+ * display string one resolved cell format produces for one cell's typed
1134
+ * values, or null when no explicit format applies so each caller can use its
1135
+ * own raw/default display. AUTOMATIC/TEXT and unformattable values return null.
1136
+ */
1137
+ export function getSheetCellFormattedDisplayValue(
1138
+ cell: SheetNumberFormatCellValues,
1139
+ format?: SheetCellFormatObj | null,
1140
+ timeZone?: string | null,
1141
+ ): string | null {
1142
+ return formatSheetCellValue(cell, format, timeZone);
1143
+ }
1144
+
1145
+ /*
1146
+ * MAIN ENTRY: return the display string for one cell under one resolved cell
1147
+ * format object, or null when the number format does not apply.
1148
+ */
1149
+ export function formatSheetCellValue(
1150
+ cell: SheetNumberFormatCellValues,
1151
+ format?: SheetCellFormatObj | null,
1152
+ timeZone?: string | null,
1153
+ locale?: string | null,
1154
+ ): string | null {
1155
+ const resolved = resolveSheetCellNumberFormat(format, locale);
1156
+
1157
+ // AUTOMATIC and TEXT render the raw value; CUSTOM without a pattern has
1158
+ // nothing to render with
1159
+ if (!resolved?.pattern || resolved.type === 'TEXT') {
1160
+ return null;
1161
+ }
1162
+
1163
+ const parsed = parseSheetNumberFormatPattern(resolved.pattern);
1164
+
1165
+ if (!parsed) {
1166
+ return null;
1167
+ }
1168
+
1169
+ try {
1170
+ if (typeof cell.numberValue === 'number') {
1171
+ return formatSheetNumberValue(cell.numberValue, parsed, locale);
1172
+ }
1173
+
1174
+ const dateTime = getSheetCellFormatDateTime(cell, timeZone);
1175
+
1176
+ if (dateTime) {
1177
+ const serial = getSheetSerialFromDateTime(dateTime);
1178
+ const picked = pickSheetNumberFormatSection(parsed, serial);
1179
+
1180
+ if (picked?.section.kind === 'date') {
1181
+ return renderSheetDateFormatSection(
1182
+ picked.section,
1183
+ dateTime,
1184
+ serial,
1185
+ locale,
1186
+ );
1187
+ }
1188
+
1189
+ return formatSheetNumberValue(serial, parsed, locale);
1190
+ }
1191
+
1192
+ // Text values only pick up an explicit "@" section: the 4th section of a
1193
+ // full pattern, or a single-section pure text pattern
1194
+ const textValue =
1195
+ typeof cell.textValue === 'string' ? cell.textValue : null;
1196
+ const textSection =
1197
+ parsed.sections.length === 4 && parsed.sections[3].kind === 'text'
1198
+ ? parsed.sections[3]
1199
+ : parsed.sections.length === 1 && parsed.sections[0].kind === 'text'
1200
+ ? parsed.sections[0]
1201
+ : null;
1202
+
1203
+ if (textValue !== null && textSection) {
1204
+ return renderSheetTextFormatSection(textSection, textValue);
1205
+ }
1206
+ } catch {
1207
+ return null;
1208
+ }
1209
+
1210
+ return null;
1211
+ }