@jsb188/mday 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/package.json +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -0,0 +1,997 @@
1
+ import { chainMaybePromise, isPromiseLike, type MaybePromise } from '@jsb188/app/utils/promise.ts';
2
+ import { DEFAULT_TIMEZONE, isValidTimeZone } from '@jsb188/app/utils/timeZone.ts';
3
+ import type { SheetFormulaErrorObj, SheetFormulaReferenceObj } from '../types/sheet.d.ts';
4
+ import { getSheetFormulaSyntaxErrorMessage, parseSheetFormulaExpression } from './sheetFormulaParser.ts';
5
+ import type { SheetFormulaASTNode } from './sheetFormulaSyntax.ts';
6
+ import { SHEET_CELL_TEXT_MAX_CHARS } from '../constants/sheet.ts';
7
+ import {
8
+ getSheetFormulaBuiltinFunctionName,
9
+ getSheetFormulaDateTimeShorthandKeyValue,
10
+ getSheetFormulaDateTimeShorthandValue,
11
+ getSheetFormulaErrorCodeDisplayValue,
12
+ getSheetFormulaLogicalBooleanValue,
13
+ getSheetFormulaNumericValue,
14
+ getSheetFormulaPowerResult,
15
+ getSheetFormulaStringValue,
16
+ getSheetFormulaTextValue,
17
+ isSheetFormulaConditionalFunctionName,
18
+ isSheetFormulaNotFoundError,
19
+ isSheetFormulaRangeLikeValue,
20
+ sheetFormulaRangeIncludesValue,
21
+ } from './sheetFormulaEvaluation.ts';
22
+ import { sheetFormulaSwitchValuesEqual } from './sheetFormulaCriteria.ts';
23
+ import { evaluateSheetFormulaEagerBuiltinFunction } from './sheetFormulaFunctionHandlers.ts';
24
+ import { evaluateSheetFormulaInfoFunction } from './sheetFormulaLogical.ts';
25
+ import { searchSheetFormulaXLookup } from './sheetFormulaLookup.ts';
26
+ import { getSheetFormulaRangeBounds, withSheetFormulaRangeShape } from './sheetFormulaRange.ts';
27
+
28
+ /**
29
+ * Types
30
+ */
31
+
32
+ /* Unified evaluation result. `loading` is only ever produced by resolvers that
33
+ * support partial data (client); `references` is only meaningfully populated by
34
+ * resolvers that synthesize dependency metadata (server). */
35
+ export interface SheetFormulaEvaluatorResult {
36
+ error?: SheetFormulaErrorObj | null;
37
+ keyValue?: unknown;
38
+ loading?: boolean;
39
+ references: SheetFormulaReferenceObj[];
40
+ value: unknown;
41
+ }
42
+
43
+ /* Range value produced by range resolvers; `reference` is server-only extra.
44
+ * Resolvers return dense row-major values over the clamped rectangle
45
+ * (getSheetFormulaRangeBounds); the core stamps rowCount/columnCount. */
46
+ export interface SheetFormulaEvaluatorRangeValue {
47
+ columnCount?: number;
48
+ kind: 'SHEET_RANGE_VALUE';
49
+ reference?: SheetFormulaReferenceObj;
50
+ rowCount?: number;
51
+ source?: 'ARRAY' | 'RANGE';
52
+ values: unknown[];
53
+ }
54
+
55
+ /* The injected reference resolver. TContext is opaque to the core: the client
56
+ * threads {cell, cellsByCoord, crossTab, referencesById, stack}; the server
57
+ * threads {cache, columnIndex, rowIndex, organizationId, sheetId, sheetTabId,
58
+ * sheetTabByName}. */
59
+ export interface SheetFormulaReferenceResolver<TContext> {
60
+ resolveCellReference(
61
+ context: TContext,
62
+ node: Extract<SheetFormulaASTNode, { kind: 'CELL_REFERENCE' }>,
63
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
64
+ ): MaybePromise<SheetFormulaEvaluatorResult>;
65
+ resolveRangeReference(
66
+ context: TContext,
67
+ node: Extract<SheetFormulaASTNode, { kind: 'RANGE_REFERENCE' }>,
68
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
69
+ ): MaybePromise<SheetFormulaEvaluatorResult>;
70
+ }
71
+
72
+ /* Constant per-evaluation runtime handed to the core and to resolvers (so
73
+ * resolvers can recurse back into the core, e.g. client cell-chain recursion). */
74
+ export interface SheetFormulaEvaluatorRuntime<TContext> {
75
+ context: TContext;
76
+ now: Date;
77
+ resolver: SheetFormulaReferenceResolver<TContext>;
78
+ timeZone: string;
79
+ }
80
+
81
+ /* Params for one full-expression evaluation via any of the drivers. */
82
+ export interface SheetFormulaEvaluatorExpressionParams<TContext> {
83
+ expression: string;
84
+ /* Pre-parsed AST of the expression (stored-AST fast path); the expression
85
+ * is parsed only when this is absent */
86
+ node?: SheetFormulaASTNode | null;
87
+ now?: Date | null;
88
+ resolver: SheetFormulaReferenceResolver<TContext>;
89
+ resolverContext: TContext;
90
+ timeZone?: string | null;
91
+ }
92
+
93
+ type SheetFormulaFunctionArgsResult =
94
+ | SheetFormulaEvaluatorResult
95
+ | {
96
+ references: SheetFormulaReferenceObj[];
97
+ values: unknown[];
98
+ };
99
+
100
+ const FILE_CONSTANTS = {
101
+ arrayRootMessage: 'UNIQUE returns several values; wrap it in a function such as COUNTA, INDEX, TEXTJOIN, or SUM.',
102
+ comparisonOperators: ['=', '!=', '<>', '<', '<=', '>', '>='],
103
+ syncResolverViolationCode: 'SHEET_FORMULA_SYNC_RESOLVER_VIOLATION',
104
+ textTooLongMessage: `Formula text result is longer than ${SHEET_CELL_TEXT_MAX_CHARS} characters.`,
105
+ };
106
+
107
+ /*
108
+ * Return a stable formula error object for runtime formula metadata.
109
+ */
110
+ function getSheetFormulaError(code: string, message: string): SheetFormulaErrorObj {
111
+ return {
112
+ code,
113
+ message,
114
+ };
115
+ }
116
+
117
+ /*
118
+ * Build a normalized error result whose value is the shared display token for
119
+ * the code (#N/A, #VALUE!, #REF!, #NUM!, #DIV/0!, or #ERROR!).
120
+ */
121
+ export function buildSheetFormulaErrorResult(
122
+ code: string,
123
+ message: string,
124
+ references: SheetFormulaReferenceObj[] = [],
125
+ ): SheetFormulaEvaluatorResult {
126
+ const error = getSheetFormulaError(code, message);
127
+
128
+ return {
129
+ error,
130
+ references,
131
+ value: getSheetFormulaErrorCodeDisplayValue(error.code),
132
+ };
133
+ }
134
+
135
+ /*
136
+ * Return whether one evaluated value is a range value.
137
+ */
138
+ export function isSheetFormulaRangeEvalValue(value: unknown): value is SheetFormulaEvaluatorRangeValue {
139
+ return isSheetFormulaRangeLikeValue(value);
140
+ }
141
+
142
+ /*
143
+ * Return an invalid-arity result for one formula function.
144
+ */
145
+ function buildSheetFormulaFunctionArityErrorResult(name: string, expectedText: string, references: SheetFormulaReferenceObj[] = []) {
146
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', `${name} requires ${expectedText}.`, references);
147
+ }
148
+
149
+ /*
150
+ * Evaluate the argument nodes at the listed indexes in order, stopping at the
151
+ * first error or loading result, and recurse into the next position so a
152
+ * fully-synchronous resolver never allocates a promise.
153
+ */
154
+ function evaluateSheetFormulaFunctionArgListAt<TContext>(
155
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
156
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
157
+ argIndexes: number[],
158
+ position: number,
159
+ references: SheetFormulaReferenceObj[],
160
+ values: unknown[],
161
+ ): MaybePromise<SheetFormulaFunctionArgsResult> {
162
+ if (position >= argIndexes.length) {
163
+ return {
164
+ references,
165
+ values,
166
+ };
167
+ }
168
+
169
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[argIndexes[position]]), (result) => {
170
+ references.push(...result.references);
171
+ if (result.loading || result.error) {
172
+ return {
173
+ ...result,
174
+ references,
175
+ };
176
+ }
177
+
178
+ values.push(result.value);
179
+ return evaluateSheetFormulaFunctionArgListAt(runtime, node, argIndexes, position + 1, references, values);
180
+ });
181
+ }
182
+
183
+ /*
184
+ * Evaluate the argument nodes at the listed indexes (eagerly, in order).
185
+ */
186
+ function evaluateSheetFormulaFunctionArgIndexes<TContext>(
187
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
188
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
189
+ argIndexes: number[],
190
+ ): MaybePromise<SheetFormulaFunctionArgsResult> {
191
+ return evaluateSheetFormulaFunctionArgListAt(runtime, node, argIndexes, 0, [], []);
192
+ }
193
+
194
+ /*
195
+ * Evaluate all argument nodes for one eager formula function.
196
+ */
197
+ function evaluateSheetFormulaFunctionArgs<TContext>(
198
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
199
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
200
+ ): MaybePromise<SheetFormulaFunctionArgsResult> {
201
+ return evaluateSheetFormulaFunctionArgIndexes(runtime, node, Array.from(node.args.keys()));
202
+ }
203
+
204
+ /*
205
+ * Return one lazily evaluated branch result with the references of every
206
+ * argument evaluated before it.
207
+ */
208
+ function getSheetFormulaBranchResult(
209
+ references: SheetFormulaReferenceObj[],
210
+ branch: SheetFormulaEvaluatorResult,
211
+ ): SheetFormulaEvaluatorResult {
212
+ return {
213
+ error: branch.error,
214
+ keyValue: branch.keyValue,
215
+ loading: branch.loading,
216
+ references: [...references, ...branch.references],
217
+ value: branch.value,
218
+ };
219
+ }
220
+
221
+ /*
222
+ * Evaluate an IF formula function lazily.
223
+ */
224
+ function evaluateSheetFormulaIfFunction<TContext>(
225
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
226
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
227
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
228
+ if (node.args.length !== 3) {
229
+ return buildSheetFormulaFunctionArityErrorResult('IF', 'three arguments');
230
+ }
231
+
232
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[0]), (condition) => {
233
+ if (condition.loading || condition.error) {
234
+ return condition;
235
+ }
236
+
237
+ if (isSheetFormulaRangeEvalValue(condition.value)) {
238
+ return buildSheetFormulaErrorResult(
239
+ 'INVALID_FORMULA',
240
+ 'IF condition requires a scalar boolean-compatible value.',
241
+ condition.references,
242
+ );
243
+ }
244
+
245
+ const conditionValue = getSheetFormulaLogicalBooleanValue(condition.value);
246
+ if (conditionValue === null) {
247
+ return buildSheetFormulaErrorResult(
248
+ 'INVALID_FORMULA',
249
+ 'IF condition requires a boolean-compatible value.',
250
+ condition.references,
251
+ );
252
+ }
253
+
254
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[conditionValue ? 1 : 2]), (branch) => {
255
+ return {
256
+ error: branch.error,
257
+ keyValue: branch.keyValue,
258
+ loading: branch.loading,
259
+ references: [...condition.references, ...branch.references],
260
+ value: branch.value,
261
+ };
262
+ });
263
+ });
264
+ }
265
+
266
+ /*
267
+ * Evaluate an IFNA or IFERROR formula function lazily.
268
+ */
269
+ function evaluateSheetFormulaErrorFallbackFunction<TContext>(
270
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
271
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
272
+ name: 'IFERROR' | 'IFNA',
273
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
274
+ if (node.args.length !== 2) {
275
+ return buildSheetFormulaFunctionArityErrorResult(name, 'two arguments');
276
+ }
277
+
278
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[0]), (valueResult) => {
279
+ if (valueResult.loading) {
280
+ return valueResult;
281
+ }
282
+
283
+ const shouldUseFallback = valueResult.error && (name === 'IFERROR' || isSheetFormulaNotFoundError(valueResult.error));
284
+ if (!shouldUseFallback) {
285
+ return valueResult;
286
+ }
287
+
288
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[1]), (fallbackResult) => {
289
+ return {
290
+ error: fallbackResult.error,
291
+ keyValue: fallbackResult.keyValue,
292
+ loading: fallbackResult.loading,
293
+ references: [...valueResult.references, ...fallbackResult.references],
294
+ value: fallbackResult.value,
295
+ };
296
+ });
297
+ });
298
+ }
299
+
300
+ /*
301
+ * Evaluate an INCLUDES formula function lazily: INCLUDES(needle, range) returns
302
+ * a boolean; INCLUDES(needle, range, if_true, if_false) evaluates only the
303
+ * taken branch. The range's cells are already resolved scalars, so membership
304
+ * works over literal values and formula results alike.
305
+ */
306
+ function evaluateSheetFormulaIncludesFunction<TContext>(
307
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
308
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
309
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
310
+ if (node.args.length !== 2 && node.args.length !== 4) {
311
+ return buildSheetFormulaFunctionArityErrorResult('INCLUDES', 'two or four arguments');
312
+ }
313
+
314
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[0]), (needle) => {
315
+ if (needle.loading || needle.error) {
316
+ return needle;
317
+ }
318
+
319
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[1]), (range) => {
320
+ const references = [...needle.references, ...range.references];
321
+ if (range.loading) {
322
+ return {
323
+ ...range,
324
+ references,
325
+ };
326
+ }
327
+
328
+ if (range.error) {
329
+ return {
330
+ error: range.error,
331
+ references,
332
+ value: range.value,
333
+ };
334
+ }
335
+
336
+ if (!isSheetFormulaRangeEvalValue(range.value)) {
337
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', 'INCLUDES requires a cell range as its second argument.', references);
338
+ }
339
+
340
+ const included = sheetFormulaRangeIncludesValue(range.value, needle.value);
341
+ if (node.args.length === 2) {
342
+ return {
343
+ references,
344
+ value: included,
345
+ };
346
+ }
347
+
348
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[included ? 2 : 3]), (branch) => {
349
+ return {
350
+ error: branch.error,
351
+ keyValue: branch.keyValue,
352
+ loading: branch.loading,
353
+ references: [...references, ...branch.references],
354
+ value: branch.value,
355
+ };
356
+ });
357
+ });
358
+ });
359
+ }
360
+
361
+ /*
362
+ * Evaluate the IFS condition/value pair at one pair index, recursing into the
363
+ * next pair only while conditions are FALSE, so later branches never run.
364
+ */
365
+ function evaluateSheetFormulaIfsPairAt<TContext>(
366
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
367
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
368
+ pairIndex: number,
369
+ references: SheetFormulaReferenceObj[],
370
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
371
+ if (pairIndex * 2 >= node.args.length) {
372
+ return buildSheetFormulaErrorResult('NOT_FOUND', 'IFS found no TRUE condition.', references);
373
+ }
374
+
375
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[pairIndex * 2]), (condition) => {
376
+ const conditionReferences = [...references, ...condition.references];
377
+ if (condition.loading || condition.error) {
378
+ return { ...condition, references: conditionReferences };
379
+ }
380
+
381
+ const conditionValue = isSheetFormulaRangeEvalValue(condition.value) ? null : getSheetFormulaLogicalBooleanValue(condition.value);
382
+ if (conditionValue === null) {
383
+ return buildSheetFormulaErrorResult(
384
+ 'INVALID_VALUE',
385
+ 'IFS conditions must each be a single TRUE/FALSE value.',
386
+ conditionReferences,
387
+ );
388
+ }
389
+
390
+ if (!conditionValue) {
391
+ return evaluateSheetFormulaIfsPairAt(runtime, node, pairIndex + 1, conditionReferences);
392
+ }
393
+
394
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[pairIndex * 2 + 1]), (branch) =>
395
+ getSheetFormulaBranchResult(conditionReferences, branch),
396
+ );
397
+ });
398
+ }
399
+
400
+ /*
401
+ * Evaluate IFS(condition1, value1, ...) lazily: the value of the first TRUE
402
+ * condition, or NOT_FOUND (#N/A) when none is TRUE.
403
+ */
404
+ function evaluateSheetFormulaIfsFunction<TContext>(
405
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
406
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
407
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
408
+ if (node.args.length < 2 || node.args.length % 2 !== 0) {
409
+ return buildSheetFormulaFunctionArityErrorResult('IFS', 'condition and value pairs');
410
+ }
411
+
412
+ return evaluateSheetFormulaIfsPairAt(runtime, node, 0, []);
413
+ }
414
+
415
+ /*
416
+ * Evaluate the SWITCH case at one argument index against the already
417
+ * evaluated expression: a match evaluates its value, a lone trailing
418
+ * argument is the default, and no match without a default is NOT_FOUND.
419
+ */
420
+ function evaluateSheetFormulaSwitchCaseAt<TContext>(
421
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
422
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
423
+ expressionValue: unknown,
424
+ argIndex: number,
425
+ references: SheetFormulaReferenceObj[],
426
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
427
+ const remaining = node.args.length - argIndex;
428
+ if (remaining === 0) {
429
+ return buildSheetFormulaErrorResult('NOT_FOUND', 'SWITCH found no matching case.', references);
430
+ }
431
+
432
+ if (remaining === 1) {
433
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[argIndex]), (fallback) =>
434
+ getSheetFormulaBranchResult(references, fallback),
435
+ );
436
+ }
437
+
438
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[argIndex]), (caseResult) => {
439
+ const caseReferences = [...references, ...caseResult.references];
440
+ if (caseResult.loading || caseResult.error) {
441
+ return { ...caseResult, references: caseReferences };
442
+ }
443
+
444
+ if (isSheetFormulaRangeEvalValue(caseResult.value)) {
445
+ return buildSheetFormulaErrorResult('INVALID_VALUE', 'SWITCH cases must be single values, not ranges.', caseReferences);
446
+ }
447
+
448
+ if (!sheetFormulaSwitchValuesEqual(expressionValue, caseResult.value)) {
449
+ return evaluateSheetFormulaSwitchCaseAt(runtime, node, expressionValue, argIndex + 2, caseReferences);
450
+ }
451
+
452
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[argIndex + 1]), (branch) =>
453
+ getSheetFormulaBranchResult(caseReferences, branch),
454
+ );
455
+ });
456
+ }
457
+
458
+ /*
459
+ * Evaluate SWITCH(expression, case1, value1, ..., [default]) lazily: the
460
+ * expression once, then cases in order until one equals it (lookup equality:
461
+ * case-insensitive text, 1 equals "1"), evaluating only the chosen value.
462
+ */
463
+ function evaluateSheetFormulaSwitchFunction<TContext>(
464
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
465
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
466
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
467
+ if (node.args.length < 3) {
468
+ return buildSheetFormulaFunctionArityErrorResult('SWITCH', 'an expression and at least one case and value pair');
469
+ }
470
+
471
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[0]), (expression) => {
472
+ if (expression.loading || expression.error) {
473
+ return expression;
474
+ }
475
+
476
+ if (isSheetFormulaRangeEvalValue(expression.value)) {
477
+ return buildSheetFormulaErrorResult(
478
+ 'INVALID_VALUE',
479
+ 'SWITCH expression must be a single value, not a range.',
480
+ expression.references,
481
+ );
482
+ }
483
+
484
+ return evaluateSheetFormulaSwitchCaseAt(runtime, node, expression.value, 1, expression.references);
485
+ });
486
+ }
487
+
488
+ /*
489
+ * Evaluate XLOOKUP(key, lookup_range, result_range, [if_not_found],
490
+ * [match_mode], [search_mode]): every argument except if_not_found is
491
+ * evaluated first, and if_not_found only on a miss.
492
+ */
493
+ function evaluateSheetFormulaXLookupFunction<TContext>(
494
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
495
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
496
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
497
+ const argCount = node.args.length;
498
+ if (argCount < 3 || argCount > 6) {
499
+ return buildSheetFormulaFunctionArityErrorResult(
500
+ 'XLOOKUP',
501
+ 'a search key, a lookup range, a result range, and optional if_not_found, match_mode and search_mode arguments',
502
+ );
503
+ }
504
+
505
+ return chainMaybePromise(
506
+ evaluateSheetFormulaFunctionArgIndexes(
507
+ runtime,
508
+ node,
509
+ [0, 1, 2, 4, 5].filter((index) => index < argCount),
510
+ ),
511
+ (argsResult) => {
512
+ if (!('values' in argsResult)) {
513
+ return argsResult;
514
+ }
515
+
516
+ const { references, values } = argsResult;
517
+ const search = searchSheetFormulaXLookup({
518
+ key: values[0],
519
+ lookupRange: values[1],
520
+ matchMode: argCount > 4 ? values[3] : undefined,
521
+ resultRange: values[2],
522
+ searchMode: argCount > 5 ? values[4] : undefined,
523
+ });
524
+ if (!search.ok) {
525
+ return buildSheetFormulaErrorResult(
526
+ search.result.error?.code || 'INVALID_VALUE',
527
+ search.result.error?.message || 'XLOOKUP arguments are invalid.',
528
+ references,
529
+ );
530
+ }
531
+
532
+ if (search.found) {
533
+ return { references, value: search.value };
534
+ }
535
+
536
+ if (argCount < 4) {
537
+ return buildSheetFormulaErrorResult('NOT_FOUND', 'XLOOKUP did not find the search key.', references);
538
+ }
539
+
540
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[3]), (fallback) =>
541
+ getSheetFormulaBranchResult(references, fallback),
542
+ );
543
+ },
544
+ );
545
+ }
546
+
547
+ /*
548
+ * Evaluate ISBLANK, ISERROR, ISNA, ISNUMBER or ISTEXT: the single argument is
549
+ * evaluated and its error, if any, becomes the TRUE/FALSE answer instead of
550
+ * propagating (so ISNUMBER(SEARCH("x", A1)) is FALSE when nothing is found).
551
+ */
552
+ function evaluateSheetFormulaInfoFunctionNode<TContext>(
553
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
554
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
555
+ name: 'ISBLANK' | 'ISERROR' | 'ISNA' | 'ISNUMBER' | 'ISTEXT',
556
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
557
+ if (node.args.length !== 1) {
558
+ return buildSheetFormulaFunctionArityErrorResult(name, 'one value');
559
+ }
560
+
561
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.args[0]), (argument) => {
562
+ if (argument.loading) {
563
+ return argument;
564
+ }
565
+
566
+ const result = evaluateSheetFormulaInfoFunction(name, argument);
567
+ return {
568
+ error: result.error,
569
+ references: argument.references,
570
+ value: result.value,
571
+ };
572
+ });
573
+ }
574
+
575
+ /*
576
+ * Evaluate a lazy builtin formula function that controls argument evaluation.
577
+ */
578
+ function evaluateSheetFormulaConditionalFunction<TContext>(
579
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
580
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
581
+ name: string,
582
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
583
+ if (name === 'IF') {
584
+ return evaluateSheetFormulaIfFunction(runtime, node);
585
+ }
586
+
587
+ if (name === 'IFERROR' || name === 'IFNA') {
588
+ return evaluateSheetFormulaErrorFallbackFunction(runtime, node, name);
589
+ }
590
+
591
+ if (name === 'INCLUDES') {
592
+ return evaluateSheetFormulaIncludesFunction(runtime, node);
593
+ }
594
+
595
+ if (name === 'IFS') {
596
+ return evaluateSheetFormulaIfsFunction(runtime, node);
597
+ }
598
+
599
+ if (name === 'SWITCH') {
600
+ return evaluateSheetFormulaSwitchFunction(runtime, node);
601
+ }
602
+
603
+ if (name === 'XLOOKUP') {
604
+ return evaluateSheetFormulaXLookupFunction(runtime, node);
605
+ }
606
+
607
+ if (name === 'ISBLANK' || name === 'ISERROR' || name === 'ISNA' || name === 'ISNUMBER' || name === 'ISTEXT') {
608
+ return evaluateSheetFormulaInfoFunctionNode(runtime, node, name);
609
+ }
610
+
611
+ return buildSheetFormulaErrorResult('UNKNOWN_FUNCTION', 'Formula function is not supported.');
612
+ }
613
+
614
+ /*
615
+ * Evaluate one formula function call node: builtin names win first (including
616
+ * '@'-prefixed spellings of builtins, matching server semantics), then the
617
+ * resolver's data-table path; a null resolver result is an unknown function.
618
+ */
619
+ function evaluateSheetFormulaFunctionCallNode<TContext>(
620
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
621
+ node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
622
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
623
+ const builtinName = getSheetFormulaBuiltinFunctionName(node.name);
624
+ if (builtinName) {
625
+ if (isSheetFormulaConditionalFunctionName(builtinName)) {
626
+ return evaluateSheetFormulaConditionalFunction(runtime, node, builtinName);
627
+ }
628
+
629
+ return chainMaybePromise(evaluateSheetFormulaFunctionArgs(runtime, node), (argsResult) => {
630
+ if (!('values' in argsResult)) {
631
+ return argsResult;
632
+ }
633
+
634
+ const result = evaluateSheetFormulaEagerBuiltinFunction(builtinName, argsResult.values, runtime.timeZone, runtime.now);
635
+ return {
636
+ error: result.error,
637
+ references: argsResult.references,
638
+ value: result.value,
639
+ };
640
+ });
641
+ }
642
+
643
+ return buildSheetFormulaErrorResult('UNKNOWN_FUNCTION', 'Formula function is not supported.');
644
+ }
645
+
646
+ /*
647
+ * Evaluate one unary formula expression node.
648
+ */
649
+ function evaluateSheetFormulaUnaryNode<TContext>(
650
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
651
+ node: Extract<SheetFormulaASTNode, { kind: 'UNARY_EXPRESSION' }>,
652
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
653
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.value), (result) => {
654
+ if (result.loading || result.error) {
655
+ return result;
656
+ }
657
+
658
+ if (isSheetFormulaRangeEvalValue(result.value)) {
659
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', 'Formula arithmetic cannot use a range directly.', result.references);
660
+ }
661
+
662
+ const numberValue = getSheetFormulaNumericValue(result.value);
663
+ if (numberValue === null) {
664
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', 'Formula arithmetic requires numeric values.', result.references);
665
+ }
666
+
667
+ return {
668
+ references: result.references,
669
+ value: node.operator === '-' ? -numberValue : numberValue,
670
+ };
671
+ });
672
+ }
673
+
674
+ /*
675
+ * Compare two scalar formula values.
676
+ */
677
+ function compareSheetFormulaScalarValues(leftValue: unknown, rightValue: unknown, operator: string) {
678
+ const leftNumber = getSheetFormulaNumericValue(leftValue);
679
+ const rightNumber = getSheetFormulaNumericValue(rightValue);
680
+ const useNumbers = leftNumber !== null && rightNumber !== null;
681
+ const left = useNumbers ? leftNumber : getSheetFormulaStringValue(leftValue);
682
+ const right = useNumbers ? rightNumber : getSheetFormulaStringValue(rightValue);
683
+
684
+ switch (operator) {
685
+ case '=':
686
+ return left === right;
687
+ case '!=':
688
+ case '<>':
689
+ return left !== right;
690
+ case '<':
691
+ return left < right;
692
+ case '<=':
693
+ return left <= right;
694
+ case '>':
695
+ return left > right;
696
+ case '>=':
697
+ return left >= right;
698
+ default:
699
+ return false;
700
+ }
701
+ }
702
+
703
+ /*
704
+ * Return a text operator result, or INVALID_VALUE when the joined text would
705
+ * exceed the per-cell text cap (keeps chains such as A2=A1&A1, A3=A2&A2, ...
706
+ * from growing without bound).
707
+ */
708
+ function getSheetFormulaJoinedTextResult(text: string): SheetFormulaEvaluatorResult {
709
+ return text.length > SHEET_CELL_TEXT_MAX_CHARS
710
+ ? buildSheetFormulaErrorResult('INVALID_VALUE', FILE_CONSTANTS.textTooLongMessage)
711
+ : {
712
+ references: [],
713
+ value: text,
714
+ };
715
+ }
716
+
717
+ /*
718
+ * Return one numeric operator result, or INVALID_NUMBER when it overflowed to
719
+ * a non-finite value.
720
+ */
721
+ function getSheetFormulaFiniteNumberResult(value: number): SheetFormulaEvaluatorResult {
722
+ return Number.isFinite(value)
723
+ ? {
724
+ references: [],
725
+ value,
726
+ }
727
+ : buildSheetFormulaErrorResult('INVALID_NUMBER', 'Formula arithmetic result is not a finite number.');
728
+ }
729
+
730
+ /*
731
+ * Evaluate the + operator: numeric addition when both sides coerce to
732
+ * numbers, otherwise the dialect's legacy string join (lowercase true/false).
733
+ */
734
+ function evaluateSheetFormulaAdditionValues(leftValue: unknown, rightValue: unknown): SheetFormulaEvaluatorResult {
735
+ const leftNumber = getSheetFormulaNumericValue(leftValue);
736
+ const rightNumber = getSheetFormulaNumericValue(rightValue);
737
+ if (leftNumber !== null && rightNumber !== null) {
738
+ return getSheetFormulaFiniteNumberResult(leftNumber + rightNumber);
739
+ }
740
+
741
+ return getSheetFormulaJoinedTextResult(getSheetFormulaStringValue(leftValue) + getSheetFormulaStringValue(rightValue));
742
+ }
743
+
744
+ /*
745
+ * Evaluate one numeric binary operator (-, *, /, ^) over coerced operands.
746
+ * Every operator is dispatched explicitly; an operator this build does not
747
+ * know is an INVALID_FORMULA error, never a silent division.
748
+ */
749
+ function evaluateSheetFormulaNumericOperatorValues(
750
+ leftNumber: number,
751
+ rightNumber: number,
752
+ operator: string,
753
+ ): SheetFormulaEvaluatorResult {
754
+ switch (operator) {
755
+ case '-':
756
+ return getSheetFormulaFiniteNumberResult(leftNumber - rightNumber);
757
+ case '*':
758
+ return getSheetFormulaFiniteNumberResult(leftNumber * rightNumber);
759
+ case '/':
760
+ return rightNumber === 0
761
+ ? buildSheetFormulaErrorResult('DIVIDE_BY_ZERO', 'Formula cannot divide by zero.')
762
+ : getSheetFormulaFiniteNumberResult(leftNumber / rightNumber);
763
+ case '^': {
764
+ const result = getSheetFormulaPowerResult(leftNumber, rightNumber);
765
+ return result.error
766
+ ? buildSheetFormulaErrorResult(result.error.code, result.error.message)
767
+ : { references: [], value: result.value };
768
+ }
769
+ default:
770
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', `Formula operator "${operator}" is not supported.`);
771
+ }
772
+ }
773
+
774
+ /*
775
+ * Evaluate an arithmetic or text binary formula expression over two scalars.
776
+ */
777
+ function evaluateSheetFormulaArithmeticValues(leftValue: unknown, rightValue: unknown, operator: string): SheetFormulaEvaluatorResult {
778
+ if (operator === '&') {
779
+ return getSheetFormulaJoinedTextResult(getSheetFormulaTextValue(leftValue) + getSheetFormulaTextValue(rightValue));
780
+ }
781
+
782
+ if (operator === '+') {
783
+ return evaluateSheetFormulaAdditionValues(leftValue, rightValue);
784
+ }
785
+
786
+ const leftNumber = getSheetFormulaNumericValue(leftValue);
787
+ const rightNumber = getSheetFormulaNumericValue(rightValue);
788
+ if (leftNumber === null || rightNumber === null) {
789
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', 'Formula arithmetic requires numeric values.');
790
+ }
791
+
792
+ return evaluateSheetFormulaNumericOperatorValues(leftNumber, rightNumber, operator);
793
+ }
794
+
795
+ /*
796
+ * Evaluate one binary formula expression node.
797
+ */
798
+ function evaluateSheetFormulaBinaryNode<TContext>(
799
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
800
+ node: Extract<SheetFormulaASTNode, { kind: 'BINARY_EXPRESSION' }>,
801
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
802
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.left), (left) => {
803
+ if (left.loading || left.error) {
804
+ return left;
805
+ }
806
+
807
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, node.right), (right) => {
808
+ const references = [...left.references, ...right.references];
809
+ if (right.loading) {
810
+ return {
811
+ ...right,
812
+ references,
813
+ };
814
+ }
815
+
816
+ if (right.error) {
817
+ return {
818
+ error: right.error,
819
+ references,
820
+ value: right.value,
821
+ };
822
+ }
823
+
824
+ if (isSheetFormulaRangeEvalValue(left.value) || isSheetFormulaRangeEvalValue(right.value)) {
825
+ return node.operator === '&'
826
+ ? buildSheetFormulaErrorResult('INVALID_VALUE', 'Concatenation (&) needs single values, not a range.', references)
827
+ : buildSheetFormulaErrorResult('INVALID_FORMULA', 'Formula arithmetic cannot use a range directly.', references);
828
+ }
829
+
830
+ if (FILE_CONSTANTS.comparisonOperators.includes(node.operator)) {
831
+ return {
832
+ references,
833
+ value: compareSheetFormulaScalarValues(left.value, right.value, node.operator),
834
+ };
835
+ }
836
+
837
+ const result = evaluateSheetFormulaArithmeticValues(left.value, right.value, node.operator);
838
+ return {
839
+ error: result.error,
840
+ references,
841
+ value: result.value,
842
+ };
843
+ });
844
+ });
845
+ }
846
+
847
+ /*
848
+ * Evaluate one date/time shorthand formula node.
849
+ */
850
+ function evaluateSheetFormulaDateTimeShorthandNode<TContext>(
851
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
852
+ node: Extract<SheetFormulaASTNode, { kind: 'DATE_TIME_SHORTHAND' }>,
853
+ ): SheetFormulaEvaluatorResult {
854
+ return {
855
+ keyValue: getSheetFormulaDateTimeShorthandKeyValue(node.name, runtime.now, runtime.timeZone),
856
+ references: [],
857
+ value: getSheetFormulaDateTimeShorthandValue(node.name, runtime.now, runtime.timeZone),
858
+ };
859
+ }
860
+
861
+ /*
862
+ * Return one resolved range result with its shape stamped from the reference
863
+ * node (clamped to the sheet caps), so positional functions can rely on
864
+ * rowCount/columnCount whatever resolver produced the values.
865
+ */
866
+ function withSheetFormulaRangeResultShape(
867
+ result: SheetFormulaEvaluatorResult,
868
+ node: Extract<SheetFormulaASTNode, { kind: 'RANGE_REFERENCE' }>,
869
+ ): SheetFormulaEvaluatorResult {
870
+ if (result.error || result.loading || !isSheetFormulaRangeEvalValue(result.value)) {
871
+ return result;
872
+ }
873
+
874
+ return {
875
+ ...result,
876
+ value: withSheetFormulaRangeShape(result.value, getSheetFormulaRangeBounds(node.reference)),
877
+ };
878
+ }
879
+
880
+ /*
881
+ * Evaluate one error literal node such as #REF! into its formula error.
882
+ */
883
+ function evaluateSheetFormulaErrorLiteralNode(
884
+ node: Extract<SheetFormulaASTNode, { kind: 'ERROR_LITERAL' }>,
885
+ ): SheetFormulaEvaluatorResult {
886
+ return buildSheetFormulaErrorResult(node.code, `Formula contains ${node.text}: it refers to a cell or range that no longer exists.`);
887
+ }
888
+
889
+ /*
890
+ * Evaluate one AST node (maybe-promise).
891
+ */
892
+ export function evaluateSheetFormulaNodeGeneric<TContext>(
893
+ runtime: SheetFormulaEvaluatorRuntime<TContext>,
894
+ node: SheetFormulaASTNode,
895
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
896
+ switch (node.kind) {
897
+ case 'BOOLEAN_LITERAL':
898
+ case 'NUMBER_LITERAL':
899
+ case 'STRING_LITERAL':
900
+ return {
901
+ references: [],
902
+ value: node.value,
903
+ };
904
+ case 'DATE_TIME_SHORTHAND':
905
+ return evaluateSheetFormulaDateTimeShorthandNode(runtime, node);
906
+ case 'CELL_REFERENCE':
907
+ return runtime.resolver.resolveCellReference(runtime.context, node, runtime);
908
+ case 'RANGE_REFERENCE':
909
+ return chainMaybePromise(runtime.resolver.resolveRangeReference(runtime.context, node, runtime), (result) =>
910
+ withSheetFormulaRangeResultShape(result, node),
911
+ );
912
+ case 'ERROR_LITERAL':
913
+ return evaluateSheetFormulaErrorLiteralNode(node);
914
+ case 'FUNCTION_CALL':
915
+ return evaluateSheetFormulaFunctionCallNode(runtime, node);
916
+ case 'UNARY_EXPRESSION':
917
+ return evaluateSheetFormulaUnaryNode(runtime, node);
918
+ case 'BINARY_EXPRESSION':
919
+ return evaluateSheetFormulaBinaryNode(runtime, node);
920
+ default:
921
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', 'Formula syntax is not supported.');
922
+ }
923
+ }
924
+
925
+ /*
926
+ * Evaluate one full expression: optional pre-parsed node, parse fallback,
927
+ * root-range rejection.
928
+ */
929
+ export function evaluateSheetFormulaExpressionGeneric<TContext>(
930
+ params: SheetFormulaEvaluatorExpressionParams<TContext>,
931
+ ): MaybePromise<SheetFormulaEvaluatorResult> {
932
+ // Stored ASTs are a cache only. Parse canonical formula text whenever the
933
+ // caller cannot supply a trustworthy current tree.
934
+ const rootNode = params.node || parseSheetFormulaExpression(params.expression);
935
+ if (!rootNode) {
936
+ return buildSheetFormulaErrorResult('INVALID_FORMULA', getSheetFormulaSyntaxErrorMessage(params.expression));
937
+ }
938
+
939
+ const runtime: SheetFormulaEvaluatorRuntime<TContext> = {
940
+ context: params.resolverContext,
941
+ now: params.now || new Date(),
942
+ resolver: params.resolver,
943
+ timeZone: isValidTimeZone(params.timeZone) ? params.timeZone || DEFAULT_TIMEZONE : DEFAULT_TIMEZONE,
944
+ };
945
+
946
+ return chainMaybePromise(evaluateSheetFormulaNodeGeneric(runtime, rootNode), (result) => {
947
+ if (!result.error && isSheetFormulaRangeEvalValue(result.value)) {
948
+ return buildSheetFormulaErrorResult(
949
+ 'INVALID_FORMULA',
950
+ result.value.source === 'ARRAY' ? FILE_CONSTANTS.arrayRootMessage : 'Formula cannot return a range directly.',
951
+ result.references,
952
+ );
953
+ }
954
+
955
+ return result;
956
+ });
957
+ }
958
+
959
+ /*
960
+ * Sync driver: identical to the generic entry, but a resolver that leaks a
961
+ * promise degrades to a formula ERROR result (never a crash): the guard
962
+ * console.error's and the cell renders an error value instead of
963
+ * '[object Promise]'.
964
+ */
965
+ export function evaluateSheetFormulaExpressionSync<TContext>(
966
+ params: SheetFormulaEvaluatorExpressionParams<TContext>,
967
+ ): SheetFormulaEvaluatorResult {
968
+ const result = evaluateSheetFormulaExpressionGeneric(params);
969
+ if (isPromiseLike(result)) {
970
+ // Detach the leaked promise so a later rejection never surfaces as an
971
+ // unhandled rejection from the sync driver.
972
+ result.then(
973
+ () => null,
974
+ () => null,
975
+ );
976
+ console.error(
977
+ '[sheetFormulaEvaluator]',
978
+ FILE_CONSTANTS.syncResolverViolationCode,
979
+ 'Synchronous formula evaluation received a promise from its resolver.',
980
+ );
981
+ return buildSheetFormulaErrorResult(
982
+ FILE_CONSTANTS.syncResolverViolationCode,
983
+ 'Formula evaluation expected synchronous resolver values.',
984
+ );
985
+ }
986
+
987
+ return result;
988
+ }
989
+
990
+ /*
991
+ * Async driver: Promise-typed convenience wrapper for the server.
992
+ */
993
+ export async function evaluateSheetFormulaExpressionAsync<TContext>(
994
+ params: SheetFormulaEvaluatorExpressionParams<TContext>,
995
+ ): Promise<SheetFormulaEvaluatorResult> {
996
+ return await evaluateSheetFormulaExpressionGeneric(params);
997
+ }