@jsb188/mday 1.1.11 → 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 +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,11 +1,5 @@
1
- import type {
2
- SheetCellFormatObj,
3
- SheetExportFormatEnum,
4
- } from '../types/sheet.d.ts';
5
- import {
6
- getSheetCellFormattedDisplayValue,
7
- type SheetNumberFormatCellValues,
8
- } from './sheetNumberFormat.ts';
1
+ import type { SheetCellFormatObj, SheetExportFormatEnum } from '../types/sheet.d.ts';
2
+ import { getSheetCellFormattedDisplayValue, type SheetNumberFormatCellValues } from './sheetNumberFormat.ts';
9
3
 
10
4
  const FILE_CONSTANTS = {
11
5
  // Characters that break file names across OSes/browsers plus control chars
@@ -36,10 +30,7 @@ export interface SheetExportCellValues extends SheetNumberFormatCellValues {
36
30
  * receives over GraphQL. DB rows carry JS Date objects; date-only values keep
37
31
  * just the calendar date.
38
32
  */
39
- function getSheetExportRawDateString(
40
- value: Date | string,
41
- isDateOnly: boolean,
42
- ): string {
33
+ function getSheetExportRawDateString(value: Date | string, isDateOnly: boolean): string {
43
34
  if (value instanceof Date) {
44
35
  const iso = value.toISOString();
45
36
  return isDateOnly ? iso.slice(0, 10) : iso;
@@ -53,18 +44,12 @@ function getSheetExportRawDateString(
53
44
  * order of the canvas renderer (getSheetCanvasCellRawDisplayValue in
54
45
  * @jsb188/sheet libs/sheet-utils.ts) but tolerating raw DB rows.
55
46
  */
56
- function getSheetCellExportRawDisplayValue(
57
- cell?: SheetExportCellValues | null,
58
- ): string {
47
+ function getSheetCellExportRawDisplayValue(cell?: SheetExportCellValues | null): string {
59
48
  if (!cell) {
60
49
  return '';
61
50
  }
62
51
 
63
- if (
64
- !cell.formulaText &&
65
- cell.rawInput !== null &&
66
- cell.rawInput !== undefined
67
- ) {
52
+ if (!cell.formulaText && cell.rawInput !== null && cell.rawInput !== undefined) {
68
53
  return String(cell.rawInput);
69
54
  }
70
55
 
@@ -89,9 +74,7 @@ function getSheetCellExportRawDisplayValue(
89
74
  }
90
75
 
91
76
  if (cell.value !== null && cell.value !== undefined) {
92
- return typeof cell.value === 'string'
93
- ? cell.value
94
- : JSON.stringify(cell.value);
77
+ return typeof cell.value === 'string' ? cell.value : JSON.stringify(cell.value);
95
78
  }
96
79
 
97
80
  return '';
@@ -113,26 +96,15 @@ export function getSheetCellExportDisplayValue(
113
96
  return rawDisplayValue;
114
97
  }
115
98
 
116
- return (
117
- getSheetCellFormattedDisplayValue(cell, resolvedFormat, timeZone) ??
118
- rawDisplayValue
119
- );
99
+ return getSheetCellFormattedDisplayValue(cell, resolvedFormat, timeZone) ?? rawDisplayValue;
120
100
  }
121
101
 
122
102
  /*
123
103
  * Return one field quoted per RFC 4180 when it contains the delimiter, a
124
104
  * quote, or a line break; embedded quotes are doubled.
125
105
  */
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
- ) {
106
+ function getSheetExportDelimitedField(value: string, delimiter: string): string {
107
+ if (value.includes(delimiter) || value.includes('"') || value.includes('\n') || value.includes('\r')) {
136
108
  return `"${value.replaceAll('"', '""')}"`;
137
109
  }
138
110
 
@@ -143,34 +115,21 @@ function getSheetExportDelimitedField(
143
115
  * Serialize a dense display-value matrix into delimited text (CSV/TSV) with
144
116
  * RFC 4180 quoting and CRLF line endings.
145
117
  */
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');
118
+ export function buildSheetDelimitedText(matrix: string[][], delimiter: ',' | '\t'): string {
119
+ return matrix.map((row) => row.map((value) => getSheetExportDelimitedField(value, delimiter)).join(delimiter)).join('\r\n');
157
120
  }
158
121
 
159
122
  /*
160
123
  * Return the lowercase file extension for one export format.
161
124
  */
162
- export function getSheetExportFileExtension(
163
- format: SheetExportFormatEnum,
164
- ): string {
125
+ export function getSheetExportFileExtension(format: SheetExportFormatEnum): string {
165
126
  return format.toLowerCase();
166
127
  }
167
128
 
168
129
  /*
169
130
  * Return the HTTP content type for one export format.
170
131
  */
171
- export function getSheetExportContentType(
172
- format: SheetExportFormatEnum,
173
- ): string {
132
+ export function getSheetExportContentType(format: SheetExportFormatEnum): string {
174
133
  return FILE_CONSTANTS.contentTypes[format];
175
134
  }
176
135
 
@@ -193,13 +152,8 @@ function getSheetExportSafeBaseName(name: string): string {
193
152
  * Return the download file name for one export: "Title.xlsx" for whole-workbook
194
153
  * exports, "Title - TabName.csv|tsv|pdf" for single-tab exports.
195
154
  */
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}`;
155
+ export function getSheetExportFileName(sheetTitle: string, tabName: string | null | undefined, format: SheetExportFormatEnum): string {
156
+ const baseName = format === 'XLSX' || !tabName ? sheetTitle : `${sheetTitle} - ${tabName}`;
203
157
 
204
158
  return `${getSheetExportSafeBaseName(baseName)}.${getSheetExportFileExtension(format)}`;
205
159
  }
@@ -209,10 +163,7 @@ export function getSheetExportFileName(
209
163
  * removed, capped at 31 chars, non-empty, and deduped case-insensitively with
210
164
  * " (2)"-style suffixes. Mutates usedNames so callers can loop over tabs.
211
165
  */
212
- export function getSheetExportTabName(
213
- name: string | null | undefined,
214
- usedNames: Set<string>,
215
- ): string {
166
+ export function getSheetExportTabName(name: string | null | undefined, usedNames: Set<string>): string {
216
167
  const safeName =
217
168
  (name || '')
218
169
  .replace(FILE_CONSTANTS.tabNameIllegalChars, ' ')
@@ -226,10 +177,7 @@ export function getSheetExportTabName(
226
177
 
227
178
  while (usedNames.has(uniqueName.toLowerCase())) {
228
179
  const suffix = ` (${suffixNumber})`;
229
- uniqueName =
230
- safeName
231
- .slice(0, FILE_CONSTANTS.maxTabNameLength - suffix.length)
232
- .trimEnd() + suffix;
180
+ uniqueName = safeName.slice(0, FILE_CONSTANTS.maxTabNameLength - suffix.length).trimEnd() + suffix;
233
181
  suffixNumber += 1;
234
182
  }
235
183
 
@@ -0,0 +1,183 @@
1
+ import {
2
+ SHEET_CELL_NOTE_MAX_CHARS,
3
+ SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS,
4
+ SHEET_CELL_TEXT_MAX_CHARS,
5
+ SHEET_DEFAULT_COLUMN_COUNT,
6
+ SHEET_DEFAULT_ROW_COUNT,
7
+ SHEET_MAX_COLUMN_COUNT,
8
+ SHEET_MAX_ROW_COUNT,
9
+ } from '../constants/sheet.ts';
10
+
11
+ export type SheetFeatureReferenceTopicId = 'references' | 'layout' | 'calculation';
12
+
13
+ export interface SheetFeatureReferenceExample {
14
+ description: string;
15
+ expression?: string;
16
+ value?: unknown;
17
+ }
18
+
19
+ export interface SheetFeatureReferenceTopic {
20
+ id: SheetFeatureReferenceTopicId;
21
+ title: string;
22
+ summary: string;
23
+ engineSupported: readonly string[];
24
+ syntax: readonly string[];
25
+ examples: readonly SheetFeatureReferenceExample[];
26
+ rules: readonly string[];
27
+ limits: Readonly<Record<string, string | number>>;
28
+ }
29
+
30
+ /* Engine reference shared by product help and agent discovery. Tool availability belongs to the caller. */
31
+ export const SHEET_FEATURE_REFERENCE: Readonly<Record<SheetFeatureReferenceTopicId, SheetFeatureReferenceTopic>> = {
32
+ references: {
33
+ id: 'references',
34
+ title: 'Sheet cell and range references',
35
+ summary:
36
+ 'Formulas support A1 cells, closed rectangles, absolute $ anchors, same-workbook tab references and an open ending row such as C3:C.',
37
+ engineSupported: [
38
+ 'Read relative, absolute and mixed row/column references.',
39
+ 'Reference another tab in the same spreadsheet and pass rectangular ranges to supported functions.',
40
+ ],
41
+ syntax: ['A1', '$A$1', '$A1', 'A$1', 'tab_name!B6', "'tab_name'!B6", 'A2:D20', 'C3:C'],
42
+ examples: [
43
+ {
44
+ description: 'Keep the multiplier fixed when a formula is copied.',
45
+ expression: '=A2 * $B$1',
46
+ },
47
+ {
48
+ description: 'Read another tab in this spreadsheet.',
49
+ expression: '=season_attendance!B6',
50
+ },
51
+ {
52
+ description: 'Sum a range on the tab created as "Sales Plan", which is stored as sales_plan.',
53
+ expression: '=SUM(sales_plan!C3:C20)',
54
+ },
55
+ {
56
+ description: 'Sum from row 3 to the shared sheet row limit.',
57
+ expression: '=SUM(C3:C)',
58
+ },
59
+ ],
60
+ rules: [
61
+ 'Rows and columns are one-based. $ fixes the marked row or column during relative-copy transformations; it is not a read/write permission.',
62
+ 'Tab references resolve within the current workbook. They do not address another spreadsheet or an external workbook URL.',
63
+ 'Tab names are stored lowercase snake_case ([a-z0-9_]): a tab created or renamed as "Q3 Sales" is saved as q3_sales. Put that stored name before !, as in q3_sales!B2, and read it from view_sheet or the tab tool results. A name with spaces or other characters outside [a-z0-9_] never resolves; quote a stored name that starts with a digit, as in \'2026_01\'!B2 (unquoted 2026_01!B2 does not parse). Quoting any stored name is allowed.',
64
+ 'An open ending row needs a starting cell, as in C3:C or C3:F. Whole-column C:C, whole-row 3:3 and open ending columns are not this range grammar.',
65
+ 'A range is a collection of cell values. Use a supported range-consuming function when a scalar result is needed. Lookup and criteria functions (VLOOKUP, INDEX, SUMIFS, ...) use its row/column shape, so ranges passed together must be the same size.',
66
+ 'A range reads at most the sheet caps (row 500, column 256); any part past them is empty. Prefer bounded ranges.',
67
+ 'A directly referenced error cell passes its error on (IFERROR/IFNA can catch it). Error cells inside a range read as blank, except cells in a circular reference chain, which make the whole range an error.',
68
+ 'Named ranges can be saved in layout metadata, but formula identifiers do not currently resolve named-range aliases. Use A1 coordinates in formulas.',
69
+ 'Prefer <> for not-equal comparisons after cell references; ! also introduces tab-reference syntax.',
70
+ ],
71
+ limits: {
72
+ openRangeEndRow: SHEET_MAX_ROW_COUNT,
73
+ workbookRows: SHEET_MAX_ROW_COUNT,
74
+ workbookColumns: SHEET_MAX_COLUMN_COUNT,
75
+ },
76
+ },
77
+
78
+ layout: {
79
+ id: 'layout',
80
+ title: 'Sheet layout and formatting',
81
+ summary:
82
+ 'The sheet design stores dimensions, frozen/hidden axes, defaults, cell presentation, merged ranges and named-range metadata separately from cell contents.',
83
+ engineSupported: [
84
+ 'Apply text/fill colors, font size, emphasis, alignment, wrapping and per-edge borders.',
85
+ 'Apply number, currency, percent, date/time and custom number-format patterns without changing underlying values.',
86
+ 'Configure row heights, column widths, visibility, frozen axes, rectangular merges and named-range metadata.',
87
+ ],
88
+ syntax: [
89
+ 'Style: {bold,textColor,fillColor,textAlign,verticalAlign,textWrap,...}',
90
+ 'Format: {numberFormat:{type,pattern?,currency?}}',
91
+ 'Named range: {name,startRowIndex,startColumnIndex,endRowIndex,endColumnIndex}',
92
+ ],
93
+ examples: [
94
+ {
95
+ description: 'Give a header a solid fill and bold centered text.',
96
+ value: {
97
+ bold: true,
98
+ fillColor: '#17324D',
99
+ textColor: '#FFFFFF',
100
+ textAlign: 'CENTER',
101
+ },
102
+ },
103
+ {
104
+ description: 'Display a numeric fraction as a percentage.',
105
+ value: { numberFormat: { type: 'PERCENT' } },
106
+ },
107
+ {
108
+ description: 'Save a bounded named range as design metadata.',
109
+ value: {
110
+ name: 'Revenue',
111
+ startRowIndex: 2,
112
+ startColumnIndex: 3,
113
+ endRowIndex: 20,
114
+ endColumnIndex: 3,
115
+ },
116
+ },
117
+ ],
118
+ rules: [
119
+ `Number format types: ${SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS.join(
120
+ ', ',
121
+ )}. CUSTOM requires a pattern; currency-family formats can specify an ISO currency code.`,
122
+ 'Formatting controls display and does not convert text into a number, date or formula. Keep stored typing separate from presentation.',
123
+ 'Merged cells display their anchor value. Preserve relevant content when changing a merge.',
124
+ 'Named ranges are stored as bounded design entities, but are not currently accepted as formula reference aliases.',
125
+ 'Grid edits, structure changes and cell content edits are separate command families. A content-only write must not be treated as an implicit resize or presentation edit.',
126
+ 'Inserting, deleting or moving rows and columns rewrites formula references on every tab and named ranges like a spreadsheet: a range grows when lines are inserted inside it and shrinks when lines inside it are deleted, and a reference to a deleted cell or fully deleted range (or one pushed past the grid limit) becomes #REF!.',
127
+ 'This reference does not define chart, pivot-table, conditional-formatting or arbitrary script APIs.',
128
+ ],
129
+ limits: {
130
+ defaultRows: SHEET_DEFAULT_ROW_COUNT,
131
+ defaultColumns: SHEET_DEFAULT_COLUMN_COUNT,
132
+ maximumRows: SHEET_MAX_ROW_COUNT,
133
+ maximumColumns: SHEET_MAX_COLUMN_COUNT,
134
+ noteCharacters: SHEET_CELL_NOTE_MAX_CHARS,
135
+ },
136
+ },
137
+ calculation: {
138
+ id: 'calculation',
139
+ title: 'Saved values, calculation and previews',
140
+ summary:
141
+ 'Authored content, computed formula results and formatted display values are distinct. A committed edit or preview image alone does not prove every dependent calculation or projection has finished.',
142
+ engineSupported: [
143
+ 'Compile and evaluate supported formulas, track dependencies and publish computed changes through sheet journals.',
144
+ 'Produce bounded read-only formula previews over pending literal edits, without persisting those edits.',
145
+ 'Read committed sheet rectangles and optionally render a version-matched image.',
146
+ ],
147
+ syntax: [
148
+ 'Authored formula: rawInput beginning with = without an explicit TEXT literal type.',
149
+ 'Literal text: {rawInput:"=A1",literalType:"TEXT"}',
150
+ 'Closed preview rectangle: C2:G10',
151
+ ],
152
+ examples: [
153
+ {
154
+ description: 'Calculate a scalar from a known rectangle.',
155
+ expression: '=SUM(C2:C10)',
156
+ },
157
+ {
158
+ description: 'Store formula-looking text without executing it.',
159
+ value: { rawInput: '=SUM(C2:C10)', literalType: 'TEXT' },
160
+ },
161
+ ],
162
+ rules: [
163
+ 'Keep rawInput/formula text, typed values, computed result, display text and errors distinct. Formatting or an image is not the authoritative underlying value.',
164
+ 'Saved commands return calculation status; pending work may require a subsequent current read.',
165
+ 'The existing formula-preview service evaluates saved formulas with a bounded overlay of pending literal changes. It is not a general validator for newly invented formulas.',
166
+ 'Clock-dependent or errored formula evaluations are not eligible for ordinary short result reuse. TODAY/NOW behavior uses the evaluator clock and organization timezone.',
167
+ 'Operators: + - * / ^ (power, left-associative: 2^3^2 is 64, -2^2 is 4), & (joins text: TRUE/FALSE, numbers at 15 significant digits) and comparisons = <> != < <= > >=. + joins text only when a side is not numeric, so use & for text.',
168
+ 'Formula errors display #N/A (not found), #VALUE! (wrong kind of value), #REF! (a reference to a deleted cell or range), #NUM! (invalid or non-finite number), #DIV/0! (division by zero) or #ERROR! (any other failure, including circular references). IFERROR catches every error; IFNA catches only #N/A.',
169
+ 'Committed image previews accept a single closed A1 rectangle, not open formula ranges or cross-tab references. Large overviews are truncated; use explicit ranges for more detail.',
170
+ 'Image previews fail or must be retried if versions change or linked projections are unpublished. A stale thumbnail or unavailable image must not be used as proof of current cell contents.',
171
+ ],
172
+ // These service-local bounds mirror sheetOps-formulaPreview.helpers.ts and sheetOps-previewSnapshot.helpers.ts.
173
+ limits: {
174
+ pendingLiteralInputs: 1000,
175
+ formulaPreviewCells: 1000,
176
+ formulaPreviewSnapshotCells: 10000,
177
+ imagePreviewRows: 100,
178
+ imagePreviewColumns: 100,
179
+ imagePreviewCells: 10000,
180
+ formulaTextCharacters: SHEET_CELL_TEXT_MAX_CHARS,
181
+ },
182
+ },
183
+ };
@@ -0,0 +1,168 @@
1
+ import type { DateTime } from 'luxon';
2
+ import { SHEET_CELL_TEXT_MAX_CHARS } from '../constants/sheet.ts';
3
+ import {
4
+ getSheetFormulaDateTimeValue,
5
+ getSheetFormulaLogicalBooleanValue,
6
+ getSheetFormulaNumericValue,
7
+ getSheetFormulaPureErrorResult,
8
+ getSheetFormulaTextValue,
9
+ isSheetFormulaBlankValue,
10
+ isSheetFormulaRangeLikeValue,
11
+ type SheetFormulaPureEvaluationResult,
12
+ } from './sheetFormulaEvaluation.ts';
13
+
14
+ /**
15
+ * Types
16
+ */
17
+
18
+ /* One validated scalar builtin argument, or the error result to return. */
19
+ export type SheetFormulaArgResult<T> = { ok: true; value: T } | { ok: false; result: SheetFormulaPureEvaluationResult };
20
+
21
+ /*
22
+ * Return a failed argument result with an INVALID_VALUE (#VALUE!) error.
23
+ */
24
+ export function getSheetFormulaInvalidArgResult(message: string): {
25
+ ok: false;
26
+ result: SheetFormulaPureEvaluationResult;
27
+ } {
28
+ return {
29
+ ok: false,
30
+ result: getSheetFormulaPureErrorResult('INVALID_VALUE', message),
31
+ };
32
+ }
33
+
34
+ /*
35
+ * Return the INVALID_VALUE argument result for a range passed where a single
36
+ * value is required.
37
+ */
38
+ function getSheetFormulaRangeArgResult(name: string, label: string) {
39
+ return getSheetFormulaInvalidArgResult(`${name} requires a single value for ${label}, not a range.`);
40
+ }
41
+
42
+ /*
43
+ * Return one numeric argument: numbers, booleans (TRUE = 1) and numeric text,
44
+ * with a blank argument read as 0 (as in Excel). Ranges and other text are
45
+ * INVALID_VALUE.
46
+ */
47
+ export function getSheetFormulaNumberArg(name: string, value: unknown, label: string): SheetFormulaArgResult<number> {
48
+ if (isSheetFormulaRangeLikeValue(value)) {
49
+ return getSheetFormulaRangeArgResult(name, label);
50
+ }
51
+
52
+ const numberValue = isSheetFormulaBlankValue(value) ? 0 : getSheetFormulaNumericValue(value);
53
+ return numberValue === null
54
+ ? getSheetFormulaInvalidArgResult(`${name} requires a number for ${label}.`)
55
+ : { ok: true, value: numberValue };
56
+ }
57
+
58
+ /*
59
+ * Return one whole-number argument (numbers truncate toward zero), with an
60
+ * optional minimum; below the minimum is INVALID_VALUE.
61
+ */
62
+ export function getSheetFormulaIntegerArg(
63
+ name: string,
64
+ value: unknown,
65
+ label: string,
66
+ min = Number.NEGATIVE_INFINITY,
67
+ ): SheetFormulaArgResult<number> {
68
+ const numberArg = getSheetFormulaNumberArg(name, value, label);
69
+ if (!numberArg.ok) {
70
+ return numberArg;
71
+ }
72
+
73
+ const integer = Math.trunc(numberArg.value);
74
+ return integer < min
75
+ ? getSheetFormulaInvalidArgResult(`${name} requires ${label} of at least ${min}.`)
76
+ : { ok: true, value: integer };
77
+ }
78
+
79
+ /*
80
+ * Return one text argument in its spreadsheet text form (blank is '',
81
+ * TRUE/FALSE, numbers at 15 significant digits); a range is INVALID_VALUE.
82
+ */
83
+ export function getSheetFormulaTextArg(name: string, value: unknown, label: string): SheetFormulaArgResult<string> {
84
+ return isSheetFormulaRangeLikeValue(value)
85
+ ? getSheetFormulaRangeArgResult(name, label)
86
+ : { ok: true, value: getSheetFormulaTextValue(value) };
87
+ }
88
+
89
+ /*
90
+ * Return one TRUE/FALSE argument (blank is FALSE); a range or text other than
91
+ * TRUE/FALSE is INVALID_VALUE.
92
+ */
93
+ export function getSheetFormulaBooleanArg(name: string, value: unknown, label: string): SheetFormulaArgResult<boolean> {
94
+ if (isSheetFormulaRangeLikeValue(value)) {
95
+ return getSheetFormulaRangeArgResult(name, label);
96
+ }
97
+
98
+ const booleanValue = getSheetFormulaLogicalBooleanValue(value);
99
+ return booleanValue === null
100
+ ? getSheetFormulaInvalidArgResult(`${name} requires TRUE or FALSE for ${label}.`)
101
+ : { ok: true, value: booleanValue };
102
+ }
103
+
104
+ /*
105
+ * Return one date argument as the start of its calendar day in the
106
+ * organization time zone. Text must start with a full yyyy-MM-dd date (an ISO
107
+ * date or datetime); numeric serials, blanks, partial ISO text such as "2026"
108
+ * or a bare time (which would read as today) are INVALID_VALUE.
109
+ */
110
+ export function getSheetFormulaDateArg(
111
+ name: string,
112
+ value: unknown,
113
+ label: string,
114
+ timeZone: string,
115
+ ): SheetFormulaArgResult<DateTime> {
116
+ if (isSheetFormulaRangeLikeValue(value)) {
117
+ return getSheetFormulaRangeArgResult(name, label);
118
+ }
119
+
120
+ const dateTime =
121
+ typeof value === 'string' && /^\s*\d{4}-\d{2}-\d{2}/.test(value) ? getSheetFormulaDateTimeValue(value, timeZone) : null;
122
+ return dateTime
123
+ ? { ok: true, value: dateTime.startOf('day') }
124
+ : getSheetFormulaInvalidArgResult(`${name} requires an ISO date such as "2026-01-31" for ${label}.`);
125
+ }
126
+
127
+ /*
128
+ * Return the scalar entries of builtin arguments with ranges and arrays
129
+ * flattened row-major.
130
+ */
131
+ export function flattenSheetFormulaArgValues(values: unknown[]) {
132
+ return values.flatMap((value) => (isSheetFormulaRangeLikeValue(value) ? value.values : [value]));
133
+ }
134
+
135
+ /*
136
+ * Return the INVALID_VALUE result for a text result over the per-cell cap.
137
+ */
138
+ export function getSheetFormulaTextTooLongResult(name: string) {
139
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', `${name} result is longer than ${SHEET_CELL_TEXT_MAX_CHARS} characters.`);
140
+ }
141
+
142
+ /*
143
+ * Return a text result, or INVALID_VALUE when it is longer than the per-cell
144
+ * text cap.
145
+ */
146
+ export function getSheetFormulaTextResult(name: string, text: string): SheetFormulaPureEvaluationResult {
147
+ return text.length > SHEET_CELL_TEXT_MAX_CHARS ? getSheetFormulaTextTooLongResult(name) : { value: text };
148
+ }
149
+
150
+ /*
151
+ * Join text pieces with a delimiter, or return INVALID_VALUE as soon as the
152
+ * running length passes the per-cell text cap, so a join over a large range
153
+ * never builds an oversized string.
154
+ */
155
+ export function joinSheetFormulaTextPieces(name: string, pieces: Iterable<string>, delimiter = ''): SheetFormulaPureEvaluationResult {
156
+ const kept: string[] = [];
157
+ let length = 0;
158
+ for (const piece of pieces) {
159
+ length += piece.length + (kept.length ? delimiter.length : 0);
160
+ if (length > SHEET_CELL_TEXT_MAX_CHARS) {
161
+ return getSheetFormulaTextTooLongResult(name);
162
+ }
163
+
164
+ kept.push(piece);
165
+ }
166
+
167
+ return { value: kept.join(delimiter) };
168
+ }