@jsb188/mday 1.1.2

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 (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -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 +22 -0
  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 +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,656 @@
1
+ import {
2
+ getSheetFormulaDateTimeValue,
3
+ getSheetFormulaNumericValue,
4
+ getSheetFormulaPureErrorResult,
5
+ isSheetFormulaBlankValue,
6
+ type SheetFormulaPureEvaluationResult,
7
+ } from './sheetFormulaEvaluation.ts';
8
+ import { getSheetSerialFromDateTime } from './sheetNumberFormat.ts';
9
+
10
+ /**
11
+ * Types
12
+ */
13
+
14
+ export type SheetFormulaCriterionOperator = '=' | '<>' | '<' | '<=' | '>' | '>=';
15
+
16
+ /* Bit-parallel NFA for one wildcard pattern: state j means "the first j
17
+ * pattern tokens matched". One bit per state, 32 states per word. */
18
+ type SheetFormulaWildcardProgram = {
19
+ acceptBit: number;
20
+ acceptWord: number;
21
+ anyMask: Uint32Array;
22
+ charMasks: Map<string, Uint32Array>;
23
+ starMask: Uint32Array;
24
+ wordCount: number;
25
+ };
26
+
27
+ /* One parsed wildcard pattern token: '?' (ANY), '*' (STAR) or one literal
28
+ * character (CHAR, including an escaped '*', '?' or '~'). */
29
+ type SheetFormulaWildcardToken = { kind: 'ANY' } | { kind: 'STAR' } | { char: string; kind: 'CHAR' };
30
+
31
+ /* One compiled Excel wildcard pattern (* any run, ? one character, ~ escape),
32
+ * matched case-insensitively. Without an active wildcard the pattern is a
33
+ * plain (unescaped, lowercase) literal. */
34
+ export type SheetFormulaWildcardPattern = {
35
+ literal: string;
36
+ program: SheetFormulaWildcardProgram | null;
37
+ };
38
+
39
+ /* One parsed COUNTIF/SUMIF-style criterion. NONE matches nothing (an ordering
40
+ * operator with an empty operand, such as "<"). */
41
+ export type SheetFormulaCriterion =
42
+ | { kind: 'BLANK' }
43
+ | { kind: 'NONBLANK' }
44
+ | { kind: 'NONE' }
45
+ | { kind: 'NUMBER'; operator: SheetFormulaCriterionOperator; value: number }
46
+ | { kind: 'DATE'; operator: SheetFormulaCriterionOperator; serial: number }
47
+ | { kind: 'BOOLEAN'; operator: '=' | '<>'; value: boolean }
48
+ | {
49
+ kind: 'TEXT';
50
+ operator: SheetFormulaCriterionOperator;
51
+ pattern: SheetFormulaWildcardPattern | null;
52
+ value: string;
53
+ };
54
+
55
+ export type SheetFormulaCriterionParseResult =
56
+ | { criterion: SheetFormulaCriterion; ok: true }
57
+ | { ok: false; result: SheetFormulaPureEvaluationResult };
58
+
59
+ /* Lookup type classes, ordered numbers < text < booleans as in Excel. */
60
+ export type SheetFormulaLookupValueClass = 'BLANK' | 'BOOLEAN' | 'NUMBER' | 'TEXT';
61
+
62
+ /* Exact-match test for one lookup key (wildcard or plain equality). */
63
+ export type SheetFormulaLookupMatcher = (value: unknown) => boolean;
64
+
65
+ export type SheetFormulaLookupMatcherResult =
66
+ | { matches: SheetFormulaLookupMatcher; ok: true }
67
+ | { ok: false; result: SheetFormulaPureEvaluationResult };
68
+
69
+ const FILE_CONSTANTS = {
70
+ booleanOperandPattern: /^(?:true|false)$/i,
71
+ criterionOperators: ['<=', '>=', '<>', '!=', '=', '<', '>'] as const,
72
+ isoDatePrefixPattern: /^\d{4}-\d{2}-\d{2}/,
73
+ lookupClassRank: {
74
+ BLANK: -1,
75
+ BOOLEAN: 2,
76
+ NUMBER: 0,
77
+ TEXT: 1,
78
+ } satisfies Record<SheetFormulaLookupValueClass, number>,
79
+ // Excel caps criteria and lookup keys at 255 characters; the cap also
80
+ // bounds the wildcard NFA to 8 words per text character
81
+ wildcardPatternMaxChars: 255,
82
+ wildcardSpecialCharPattern: /[*?~]/,
83
+ };
84
+
85
+ /*
86
+ * Return a wildcard program over parsed pattern tokens.
87
+ */
88
+ function buildSheetFormulaWildcardProgram(tokens: SheetFormulaWildcardToken[]): SheetFormulaWildcardProgram {
89
+ const wordCount = Math.ceil((tokens.length + 1) / 32);
90
+ const anyMask = new Uint32Array(wordCount);
91
+ const starMask = new Uint32Array(wordCount);
92
+ const charMasks = new Map<string, Uint32Array>();
93
+
94
+ tokens.forEach((token, index) => {
95
+ const word = index >>> 5;
96
+ const bit = 1 << (index & 31);
97
+ if (token.kind === 'ANY') {
98
+ anyMask[word] |= bit;
99
+ } else if (token.kind === 'STAR') {
100
+ starMask[word] |= bit;
101
+ } else {
102
+ const mask = charMasks.get(token.char) || new Uint32Array(wordCount);
103
+ mask[word] |= bit;
104
+ charMasks.set(token.char, mask);
105
+ }
106
+ });
107
+
108
+ return {
109
+ acceptBit: 1 << (tokens.length & 31),
110
+ acceptWord: tokens.length >>> 5,
111
+ anyMask,
112
+ charMasks,
113
+ starMask,
114
+ wordCount,
115
+ };
116
+ }
117
+
118
+ /*
119
+ * Parse already case-folded pattern characters into wildcard tokens: '*'
120
+ * matches any run of characters, '?' one character, and '~' escapes a
121
+ * following '*', '?' or '~' (any other '~' is literal). Consecutive stars
122
+ * collapse; `literal` is the unescaped text used when no wildcard is active.
123
+ */
124
+ function parseSheetFormulaWildcardTokens(characters: string[]) {
125
+ const tokens: SheetFormulaWildcardToken[] = [];
126
+ let literal = '';
127
+ let hasWildcard = false;
128
+
129
+ for (let index = 0; index < characters.length; index++) {
130
+ const character = characters[index];
131
+ const next = characters[index + 1];
132
+ if (character === '~' && (next === '*' || next === '?' || next === '~')) {
133
+ tokens.push({ char: next, kind: 'CHAR' });
134
+ literal += next;
135
+ index++;
136
+ } else if (character === '*') {
137
+ hasWildcard = true;
138
+ if (tokens[tokens.length - 1]?.kind !== 'STAR') {
139
+ tokens.push({ kind: 'STAR' });
140
+ }
141
+ } else if (character === '?') {
142
+ hasWildcard = true;
143
+ tokens.push({ kind: 'ANY' });
144
+ } else {
145
+ tokens.push({ char: character, kind: 'CHAR' });
146
+ literal += character;
147
+ }
148
+ }
149
+
150
+ return { hasWildcard, literal, tokens };
151
+ }
152
+
153
+ /*
154
+ * Compile one Excel wildcard pattern: '*' matches any run of characters, '?'
155
+ * one character, and '~' escapes a following '*', '?' or '~' (any other '~'
156
+ * is literal). Matching is case-insensitive. Consecutive stars collapse, and
157
+ * a pattern with no active wildcard compiles to a plain literal.
158
+ */
159
+ export function compileSheetFormulaWildcardPattern(text: string): SheetFormulaWildcardPattern {
160
+ const { hasWildcard, literal, tokens } = parseSheetFormulaWildcardTokens([...text.toLowerCase()]);
161
+
162
+ return {
163
+ literal,
164
+ program: hasWildcard ? buildSheetFormulaWildcardProgram(tokens) : null,
165
+ };
166
+ }
167
+
168
+ /*
169
+ * Apply the star epsilon moves in place: an active star state also activates
170
+ * the next state (the star matched nothing). Stars never repeat, so one pass
171
+ * is enough.
172
+ */
173
+ function closeSheetFormulaWildcardStates(program: SheetFormulaWildcardProgram, states: Uint32Array) {
174
+ let carry = 0;
175
+ for (let word = 0; word < program.wordCount; word++) {
176
+ const stars = states[word] & program.starMask[word];
177
+ states[word] = (states[word] | (stars << 1) | carry) >>> 0;
178
+ carry = stars >>> 31;
179
+ }
180
+ }
181
+
182
+ /*
183
+ * Return whether one compiled wildcard program matches the whole lowercase
184
+ * text. Bit-parallel NFA simulation: O(text length x words), no backtracking,
185
+ * so no pattern can make one cell test slow.
186
+ */
187
+ function sheetFormulaWildcardProgramMatches(program: SheetFormulaWildcardProgram, text: string) {
188
+ let current = new Uint32Array(program.wordCount);
189
+ let next = new Uint32Array(program.wordCount);
190
+ current[0] = 1;
191
+ closeSheetFormulaWildcardStates(program, current);
192
+
193
+ for (const character of text) {
194
+ const charMask = program.charMasks.get(character);
195
+ let carry = 0;
196
+ let active = 0;
197
+ for (let word = 0; word < program.wordCount; word++) {
198
+ const moving = current[word] & (program.anyMask[word] | (charMask?.[word] || 0));
199
+ next[word] = ((moving << 1) | carry | (current[word] & program.starMask[word])) >>> 0;
200
+ carry = moving >>> 31;
201
+ }
202
+
203
+ closeSheetFormulaWildcardStates(program, next);
204
+ for (let word = 0; word < program.wordCount; word++) {
205
+ active |= next[word];
206
+ }
207
+
208
+ if (!active) {
209
+ return false;
210
+ }
211
+
212
+ [current, next] = [next, current];
213
+ }
214
+
215
+ return (current[program.acceptWord] & program.acceptBit) !== 0;
216
+ }
217
+
218
+ /*
219
+ * Return whether one compiled wildcard pattern matches the whole text,
220
+ * case-insensitively.
221
+ */
222
+ export function sheetFormulaWildcardMatches(pattern: SheetFormulaWildcardPattern, text: string) {
223
+ const lowered = text.toLowerCase();
224
+ return pattern.program ? sheetFormulaWildcardProgramMatches(pattern.program, lowered) : lowered === pattern.literal;
225
+ }
226
+
227
+ /*
228
+ * Return the INVALID_VALUE result for a wildcard pattern above the length cap.
229
+ */
230
+ function getSheetFormulaWildcardTooLongResult() {
231
+ return getSheetFormulaPureErrorResult(
232
+ 'INVALID_VALUE',
233
+ `Formula text with wildcards (* or ?) must be ${FILE_CONSTANTS.wildcardPatternMaxChars} characters or fewer.`,
234
+ );
235
+ }
236
+
237
+ /*
238
+ * Compile a wildcard pattern with the length cap applied to patterns that use
239
+ * wildcards (plain literals are compared directly and need no cap).
240
+ */
241
+ function compileSheetFormulaCappedWildcardPattern(
242
+ text: string,
243
+ ): { ok: true; pattern: SheetFormulaWildcardPattern } | { ok: false; result: SheetFormulaPureEvaluationResult } {
244
+ const pattern = compileSheetFormulaWildcardPattern(text);
245
+ return pattern.program && text.length > FILE_CONSTANTS.wildcardPatternMaxChars
246
+ ? { ok: false, result: getSheetFormulaWildcardTooLongResult() }
247
+ : { ok: true, pattern };
248
+ }
249
+
250
+ /*
251
+ * Return one text lowercased code point by code point, keeping its UTF-16
252
+ * length (a code point whose lowercase form has another length is kept as
253
+ * is), so positions in the folded text are positions in the original.
254
+ */
255
+ function foldSheetFormulaSearchText(text: string) {
256
+ let folded = '';
257
+ for (const character of text) {
258
+ const lowered = character.toLowerCase();
259
+ folded += lowered.length === character.length ? lowered : character;
260
+ }
261
+
262
+ return folded;
263
+ }
264
+
265
+ /*
266
+ * Return the code-unit index where the leftmost match of a wildcard pattern
267
+ * starts, given the program of the pattern's REVERSED tokens. One linear
268
+ * unanchored NFA pass over the reversed text: a match of the reversed pattern
269
+ * ending b code units into the reversed text starts at length - b in the
270
+ * original, so the last accepting offset is the leftmost start. -1 when
271
+ * nothing matches.
272
+ */
273
+ function findSheetFormulaReversedWildcardIndex(program: SheetFormulaWildcardProgram, text: string) {
274
+ let current = new Uint32Array(program.wordCount);
275
+ let next = new Uint32Array(program.wordCount);
276
+ let consumed = 0;
277
+ let lastAcceptEnd = -1;
278
+ current[0] = 1;
279
+ closeSheetFormulaWildcardStates(program, current);
280
+ if (current[program.acceptWord] & program.acceptBit) {
281
+ lastAcceptEnd = 0;
282
+ }
283
+
284
+ for (const character of [...text].reverse()) {
285
+ const charMask = program.charMasks.get(character);
286
+ let carry = 0;
287
+ for (let word = 0; word < program.wordCount; word++) {
288
+ const moving = current[word] & (program.anyMask[word] | (charMask?.[word] || 0));
289
+ next[word] = ((moving << 1) | carry | (current[word] & program.starMask[word])) >>> 0;
290
+ carry = moving >>> 31;
291
+ }
292
+
293
+ // Unanchored: another match may start after every character
294
+ next[0] = (next[0] | 1) >>> 0;
295
+ closeSheetFormulaWildcardStates(program, next);
296
+ consumed += character.length;
297
+ if (next[program.acceptWord] & program.acceptBit) {
298
+ lastAcceptEnd = consumed;
299
+ }
300
+
301
+ [current, next] = [next, current];
302
+ }
303
+
304
+ return lastAcceptEnd < 0 ? -1 : text.length - lastAcceptEnd;
305
+ }
306
+
307
+ /*
308
+ * Return the zero-based code-unit index of the leftmost case-insensitive
309
+ * match of one SEARCH pattern in a text (Excel wildcards: * any run, ? one
310
+ * character, ~ escape), or -1 when there is none. Linear in the text length;
311
+ * patterns that use wildcards are capped at 255 characters (INVALID_VALUE).
312
+ */
313
+ export function findSheetFormulaWildcardTextIndex(
314
+ patternText: string,
315
+ text: string,
316
+ ): { index: number; ok: true } | { ok: false; result: SheetFormulaPureEvaluationResult } {
317
+ const { hasWildcard, literal, tokens } = parseSheetFormulaWildcardTokens([...foldSheetFormulaSearchText(patternText)]);
318
+ const foldedText = foldSheetFormulaSearchText(text);
319
+ if (!hasWildcard) {
320
+ return { index: foldedText.indexOf(literal), ok: true };
321
+ }
322
+
323
+ if (patternText.length > FILE_CONSTANTS.wildcardPatternMaxChars) {
324
+ return { ok: false, result: getSheetFormulaWildcardTooLongResult() };
325
+ }
326
+
327
+ return {
328
+ index: findSheetFormulaReversedWildcardIndex(buildSheetFormulaWildcardProgram(tokens.reverse()), foldedText),
329
+ ok: true,
330
+ };
331
+ }
332
+
333
+ /*
334
+ * Split a text criterion into its comparison operator ('=' when none) and
335
+ * operand; '!=' is accepted as '<>'.
336
+ */
337
+ function splitSheetFormulaCriterionOperator(text: string): {
338
+ operand: string;
339
+ operator: SheetFormulaCriterionOperator;
340
+ } {
341
+ for (const operator of FILE_CONSTANTS.criterionOperators) {
342
+ if (text.startsWith(operator)) {
343
+ return {
344
+ operand: text.slice(operator.length),
345
+ operator: operator === '!=' ? '<>' : operator,
346
+ };
347
+ }
348
+ }
349
+
350
+ return { operand: text, operator: '=' };
351
+ }
352
+
353
+ /*
354
+ * Return the organization-zoned serial of one ISO date or datetime string, or
355
+ * null when the value is not ISO date text (dates are compared by serial).
356
+ */
357
+ function getSheetFormulaCriterionDateSerial(value: unknown, timeZone: string) {
358
+ if (typeof value !== 'string' || !FILE_CONSTANTS.isoDatePrefixPattern.test(value.trim())) {
359
+ return null;
360
+ }
361
+
362
+ const dateTime = getSheetFormulaDateTimeValue(value, timeZone);
363
+ return dateTime ? getSheetSerialFromDateTime(dateTime) : null;
364
+ }
365
+
366
+ /*
367
+ * Return the number a criterion compares against: numbers and numeric text.
368
+ * Booleans are not numbers for criteria (COUNTIF(r, 1) never counts TRUE).
369
+ */
370
+ function getSheetFormulaCriterionNumber(value: unknown) {
371
+ return typeof value === 'boolean' || isSheetFormulaBlankValue(value) ? null : getSheetFormulaNumericValue(value);
372
+ }
373
+
374
+ /*
375
+ * Classify the operand of a text criterion into its typed criterion.
376
+ */
377
+ function getSheetFormulaTextCriterion(
378
+ operator: SheetFormulaCriterionOperator,
379
+ operand: string,
380
+ timeZone: string,
381
+ ): SheetFormulaCriterionParseResult {
382
+ if (operand === '') {
383
+ return {
384
+ criterion: operator === '=' ? { kind: 'BLANK' } : operator === '<>' ? { kind: 'NONBLANK' } : { kind: 'NONE' },
385
+ ok: true,
386
+ };
387
+ }
388
+
389
+ const trimmed = operand.trim();
390
+ const numberValue = getSheetFormulaNumericValue(trimmed);
391
+ if (numberValue !== null) {
392
+ return {
393
+ criterion: { kind: 'NUMBER', operator, value: numberValue },
394
+ ok: true,
395
+ };
396
+ }
397
+
398
+ if ((operator === '=' || operator === '<>') && FILE_CONSTANTS.booleanOperandPattern.test(trimmed)) {
399
+ return {
400
+ criterion: {
401
+ kind: 'BOOLEAN',
402
+ operator,
403
+ value: trimmed.toUpperCase() === 'TRUE',
404
+ },
405
+ ok: true,
406
+ };
407
+ }
408
+
409
+ const serial = getSheetFormulaCriterionDateSerial(trimmed, timeZone);
410
+ if (serial !== null) {
411
+ return { criterion: { kind: 'DATE', operator, serial }, ok: true };
412
+ }
413
+
414
+ if (operator !== '=' && operator !== '<>') {
415
+ return {
416
+ criterion: {
417
+ kind: 'TEXT',
418
+ operator,
419
+ pattern: null,
420
+ value: operand.toLowerCase(),
421
+ },
422
+ ok: true,
423
+ };
424
+ }
425
+
426
+ const compiled = compileSheetFormulaCappedWildcardPattern(operand);
427
+ return compiled.ok
428
+ ? {
429
+ criterion: {
430
+ kind: 'TEXT',
431
+ operator,
432
+ pattern: compiled.pattern,
433
+ value: compiled.pattern.literal,
434
+ },
435
+ ok: true,
436
+ }
437
+ : compiled;
438
+ }
439
+
440
+ /*
441
+ * Parse one COUNTIF/SUMIF-style criterion value. Numbers and booleans match
442
+ * by equality, blank matches blank cells, and text may start with an operator
443
+ * (= <> != < <= > >=) followed by a number, TRUE/FALSE, an ISO date (compared
444
+ * by serial in the organization time zone) or text (case-insensitive, with *
445
+ * and ? wildcards for = and <>).
446
+ */
447
+ export function parseSheetFormulaCriterion(value: unknown, timeZone: string): SheetFormulaCriterionParseResult {
448
+ if (isSheetFormulaBlankValue(value)) {
449
+ return { criterion: { kind: 'BLANK' }, ok: true };
450
+ }
451
+
452
+ if (typeof value === 'number') {
453
+ return {
454
+ criterion: { kind: 'NUMBER', operator: '=', value },
455
+ ok: true,
456
+ };
457
+ }
458
+
459
+ if (typeof value === 'boolean') {
460
+ return {
461
+ criterion: { kind: 'BOOLEAN', operator: '=', value },
462
+ ok: true,
463
+ };
464
+ }
465
+
466
+ const { operand, operator } = splitSheetFormulaCriterionOperator(String(value));
467
+ return getSheetFormulaTextCriterion(operator, operand, timeZone);
468
+ }
469
+
470
+ /*
471
+ * Compare two same-typed criterion values with one operator.
472
+ */
473
+ function compareSheetFormulaCriterionValues<T extends number | string>(left: T, right: T, operator: SheetFormulaCriterionOperator) {
474
+ switch (operator) {
475
+ case '=':
476
+ return left === right;
477
+ case '<>':
478
+ return left !== right;
479
+ case '<':
480
+ return left < right;
481
+ case '<=':
482
+ return left <= right;
483
+ case '>':
484
+ return left > right;
485
+ case '>=':
486
+ return left >= right;
487
+ default:
488
+ return false;
489
+ }
490
+ }
491
+
492
+ /*
493
+ * Return whether one cell value is text for criteria purposes (nonblank string).
494
+ */
495
+ function isSheetFormulaCriterionTextValue(value: unknown): value is string {
496
+ return typeof value === 'string' && value !== '';
497
+ }
498
+
499
+ /*
500
+ * Return whether one cell value satisfies a parsed criterion. A value of the
501
+ * wrong type never matches, except that '<>' matches every value of another
502
+ * type, blanks included (as in Excel).
503
+ */
504
+ export function sheetFormulaCriterionMatches(criterion: SheetFormulaCriterion, value: unknown, timeZone: string): boolean {
505
+ switch (criterion.kind) {
506
+ case 'BLANK':
507
+ return isSheetFormulaBlankValue(value);
508
+ case 'NONBLANK':
509
+ return !isSheetFormulaBlankValue(value);
510
+ case 'NONE':
511
+ return false;
512
+ case 'NUMBER': {
513
+ const numberValue = getSheetFormulaCriterionNumber(value);
514
+ return numberValue === null
515
+ ? criterion.operator === '<>'
516
+ : compareSheetFormulaCriterionValues(numberValue, criterion.value, criterion.operator);
517
+ }
518
+ case 'DATE': {
519
+ const serial = getSheetFormulaCriterionDateSerial(value, timeZone);
520
+ return serial === null
521
+ ? criterion.operator === '<>'
522
+ : compareSheetFormulaCriterionValues(serial, criterion.serial, criterion.operator);
523
+ }
524
+ case 'BOOLEAN':
525
+ return typeof value === 'boolean' ? (value === criterion.value) === (criterion.operator === '=') : criterion.operator === '<>';
526
+ case 'TEXT': {
527
+ if (!isSheetFormulaCriterionTextValue(value)) {
528
+ return criterion.operator === '<>';
529
+ }
530
+
531
+ if (criterion.pattern) {
532
+ const matched = sheetFormulaWildcardMatches(criterion.pattern, value);
533
+ return criterion.operator === '=' ? matched : !matched;
534
+ }
535
+
536
+ return compareSheetFormulaCriterionValues(value.toLowerCase(), criterion.value, criterion.operator);
537
+ }
538
+ default:
539
+ return false;
540
+ }
541
+ }
542
+
543
+ /*
544
+ * Return the lookup type class of one value: blank, number (numbers and
545
+ * numeric text, so 1 matches "1"), boolean, or text.
546
+ */
547
+ export function getSheetFormulaLookupValueClass(value: unknown): SheetFormulaLookupValueClass {
548
+ if (isSheetFormulaBlankValue(value)) {
549
+ return 'BLANK';
550
+ }
551
+
552
+ if (typeof value === 'boolean') {
553
+ return 'BOOLEAN';
554
+ }
555
+
556
+ return getSheetFormulaNumericValue(value) === null ? 'TEXT' : 'NUMBER';
557
+ }
558
+
559
+ /*
560
+ * Return the lowercase text form of one lookup text value.
561
+ */
562
+ function getSheetFormulaLookupText(value: unknown) {
563
+ return String(value).toLowerCase();
564
+ }
565
+
566
+ /*
567
+ * Return whether two lookup values are equal: same type class, numbers
568
+ * numerically, text case-insensitively. A blank key or cell never matches.
569
+ */
570
+ export function sheetFormulaLookupValuesEqual(left: unknown, right: unknown) {
571
+ const leftClass = getSheetFormulaLookupValueClass(left);
572
+ if (leftClass === 'BLANK' || leftClass !== getSheetFormulaLookupValueClass(right)) {
573
+ return false;
574
+ }
575
+
576
+ if (leftClass === 'NUMBER') {
577
+ return getSheetFormulaNumericValue(left) === getSheetFormulaNumericValue(right);
578
+ }
579
+
580
+ return leftClass === 'TEXT' ? getSheetFormulaLookupText(left) === getSheetFormulaLookupText(right) : left === right;
581
+ }
582
+
583
+ /*
584
+ * Compare two lookup values for approximate matching: numbers < text <
585
+ * booleans, then natural order within a class (text by lowercase code units,
586
+ * so ISO dates sort chronologically). Returns negative, zero or positive.
587
+ */
588
+ export function compareSheetFormulaLookupValues(left: unknown, right: unknown) {
589
+ const leftClass = getSheetFormulaLookupValueClass(left);
590
+ const rightClass = getSheetFormulaLookupValueClass(right);
591
+ if (leftClass !== rightClass) {
592
+ return FILE_CONSTANTS.lookupClassRank[leftClass] - FILE_CONSTANTS.lookupClassRank[rightClass];
593
+ }
594
+
595
+ if (leftClass === 'NUMBER') {
596
+ return (getSheetFormulaNumericValue(left) as number) - (getSheetFormulaNumericValue(right) as number);
597
+ }
598
+
599
+ if (leftClass === 'BOOLEAN') {
600
+ return Number(left) - Number(right);
601
+ }
602
+
603
+ const leftText = leftClass === 'TEXT' ? getSheetFormulaLookupText(left) : '';
604
+ const rightText = rightClass === 'TEXT' ? getSheetFormulaLookupText(right) : '';
605
+ return leftText < rightText ? -1 : leftText > rightText ? 1 : 0;
606
+ }
607
+
608
+ /*
609
+ * Return the exact-match test for one lookup key. With wildcards enabled, a
610
+ * text key containing *, ? or ~ is a case-insensitive wildcard pattern tested
611
+ * against text cells; otherwise the key matches by lookup equality.
612
+ */
613
+ export function getSheetFormulaLookupMatcher(key: unknown, wildcards: boolean): SheetFormulaLookupMatcherResult {
614
+ if (!wildcards || typeof key !== 'string' || !FILE_CONSTANTS.wildcardSpecialCharPattern.test(key)) {
615
+ return {
616
+ matches: (value) => sheetFormulaLookupValuesEqual(key, value),
617
+ ok: true,
618
+ };
619
+ }
620
+
621
+ const compiled = compileSheetFormulaCappedWildcardPattern(key);
622
+ if (!compiled.ok) {
623
+ return compiled;
624
+ }
625
+
626
+ return {
627
+ matches: (value) => typeof value === 'string' && value !== '' && sheetFormulaWildcardMatches(compiled.pattern, value),
628
+ ok: true,
629
+ };
630
+ }
631
+
632
+ /*
633
+ * Return whether a SWITCH expression equals one case value: lookup equality,
634
+ * except that a blank expression matches a blank case.
635
+ */
636
+ export function sheetFormulaSwitchValuesEqual(left: unknown, right: unknown) {
637
+ return isSheetFormulaBlankValue(left) && isSheetFormulaBlankValue(right) ? true : sheetFormulaLookupValuesEqual(left, right);
638
+ }
639
+
640
+ /*
641
+ * Return a hashable key for one value under lookup equality, so UNIQUE
642
+ * deduplicates in linear time ("Apple" and "apple", or 1 and "1", share a key).
643
+ */
644
+ export function getSheetFormulaLookupValueKey(value: unknown) {
645
+ const valueClass = getSheetFormulaLookupValueClass(value);
646
+ switch (valueClass) {
647
+ case 'BLANK':
648
+ return '';
649
+ case 'NUMBER':
650
+ return `n${getSheetFormulaNumericValue(value)}`;
651
+ case 'BOOLEAN':
652
+ return `b${value}`;
653
+ default:
654
+ return `t${getSheetFormulaLookupText(value)}`;
655
+ }
656
+ }