@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,1173 @@
1
+ import {
2
+ CAMPAIGN_REPLY_TO_AGENT_DOMAINS,
3
+ DISABLED_INBOXES,
4
+ DO_NOT_REPLY_EMAIL_DOMAINS,
5
+ DOMAIN_TO_INBOX,
6
+ OPERATION_INBOX_DOMAINS,
7
+ OUTBOUND_EMAIL_DOMAINS,
8
+ } from '@jsb188/app/constants/agent.ts';
9
+ import type { DraftSchema } from '@jsb188/app/utils/schema.ts';
10
+ import { isEmail } from '@jsb188/app/utils/string.ts';
11
+ import {
12
+ CAMPAIGN_CHOICE_ELEMENT_TYPES,
13
+ CAMPAIGN_DRAFT_KEY_PREFIX,
14
+ CAMPAIGN_ELEMENT_TYPES,
15
+ CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS,
16
+ CAMPAIGN_EMAIL_TEXT_LIMITS,
17
+ CAMPAIGN_FORM_BACKGROUND_FILL_STYLES,
18
+ CAMPAIGN_FORM_COLORS,
19
+ CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE,
20
+ CAMPAIGN_FORM_NEUTRAL_COLOR,
21
+ CAMPAIGN_INSTRUCTIONS_MAX_LENGTH,
22
+ CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH,
23
+ CAMPAIGN_PUBLISH_STATUS_ENUMS,
24
+ CAMPAIGN_RESPONSE_TEXT_ANSWERS_MAX_LENGTH,
25
+ CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH,
26
+ CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS,
27
+ } from '../constants/campaign.ts';
28
+ import { MAX_PUBLIC_FORM_GENERATION_FILES } from '../constants/storage.ts';
29
+ import type {
30
+ CampaignAnswerObj,
31
+ CampaignAnswersObj,
32
+ CampaignDefinitionSnapshotElementObj,
33
+ CampaignDefinitionSnapshotObj,
34
+ CampaignDraft,
35
+ CampaignElementData,
36
+ CampaignElementOptionObj,
37
+ CampaignElementSettingsGQL,
38
+ CampaignElementSettingsObj,
39
+ CampaignElementTypeEnum,
40
+ CampaignElementValidationObj,
41
+ CampaignElementVisibleWhenObj,
42
+ CampaignElementVisibleWhenOperatorEnum,
43
+ CampaignElementVisibleWhenValuesObj,
44
+ CampaignFormBackgroundFillStyleEnum,
45
+ CampaignKindEnum,
46
+ CampaignPublishStatusEnum,
47
+ CampaignStatusEnum,
48
+ CampaignTemplateType,
49
+ EmailCampaignSettingsObj,
50
+ FormCampaignSettingsObj,
51
+ } from '../types/campaign.d.ts';
52
+ import {
53
+ getCampaignEmailBlockStorageSettings,
54
+ getCampaignEmailDesignSettings,
55
+ getCampaignEmailRowStorageSettings,
56
+ } from './campaignEmail.ts';
57
+ import { getCampaignFormWithoutAIQuestions, isCampaignAIQuestion } from './campaignAI.ts';
58
+
59
+ export type CampaignFormPublicationErrorCode =
60
+ | 'EMPTY_CHOICE_OPTION'
61
+ | 'EMPTY_QUESTION_LABEL'
62
+ | 'EMPTY_SECTION'
63
+ | 'INSUFFICIENT_CHOICE_OPTIONS'
64
+ | 'INVALID_QUESTION_VALIDATION'
65
+ | 'NO_QUESTIONS'
66
+ | 'RESERVED_QUESTION_KEY'
67
+ | 'UNSUPPORTED_FILE_QUESTION';
68
+
69
+ export interface CampaignFormPublicationError {
70
+ code: CampaignFormPublicationErrorCode;
71
+ elementKey?: string;
72
+ sectionKey?: string;
73
+ }
74
+
75
+ /*
76
+ * Return whether one lifecycle state can be the source of a publish command.
77
+ */
78
+ export function isCampaignPublishStatus(status: CampaignStatusEnum): status is CampaignPublishStatusEnum {
79
+ return CAMPAIGN_PUBLISH_STATUS_ENUMS.some((publishStatus) => publishStatus === status);
80
+ }
81
+
82
+ /*
83
+ * Narrow one untrusted JSONB value to a non-array object before reading fields.
84
+ */
85
+ function isCampaignObjectRecord(value: unknown): value is Record<string, unknown> {
86
+ return !!value && typeof value === 'object' && !Array.isArray(value);
87
+ }
88
+
89
+ /*
90
+ * Check whether one value fits GraphQL's signed 32-bit Int scalar.
91
+ */
92
+ function isCampaignGraphQLInt(value: unknown): value is number {
93
+ return Number.isInteger(value) && (value as number) >= -2147483648 && (value as number) <= 2147483647;
94
+ }
95
+
96
+ /*
97
+ * Check whether one element collects an answer. "kind" is the structural role,
98
+ * so this is the only correct test - never infer it from "type" being set.
99
+ */
100
+
101
+ export function isCampaignQuestionElement(element?: Pick<CampaignElementData, 'kind'> | null): boolean {
102
+ return element?.kind === 'QUESTION';
103
+ }
104
+
105
+ /*
106
+ * Return whether one key is reserved for a fixed Web form results Sheet column.
107
+ */
108
+ export function isCampaignWebFormResultFixedColumnKey(key?: string | null): boolean {
109
+ return CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS.includes(
110
+ String(key || '') as (typeof CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS)[number],
111
+ );
112
+ }
113
+
114
+ /*
115
+ * Check whether one element's answer must be one of its declared options.
116
+ */
117
+
118
+ export function isCampaignChoiceElement(element?: Pick<CampaignElementData, 'type'> | null): boolean {
119
+ return !!element?.type && CAMPAIGN_CHOICE_ELEMENT_TYPES.includes(element.type);
120
+ }
121
+
122
+ /*
123
+ * Check whether one element accepts more than one answer value.
124
+ */
125
+
126
+ export function isCampaignMultiValueElement(element?: Pick<CampaignElementData, 'type'> | null): boolean {
127
+ return element?.type === 'MULTI_CHOICE' || element?.type === 'FILE';
128
+ }
129
+
130
+ /*
131
+ * Check whether one value is a supported element answer type.
132
+ */
133
+
134
+ export function isCampaignElementType(value?: string | null): value is CampaignElementTypeEnum {
135
+ return CAMPAIGN_ELEMENT_TYPES.includes(value as CampaignElementTypeEnum);
136
+ }
137
+
138
+ /*
139
+ * Remove unusable and duplicated choice rows while preserving the first
140
+ * canonical value-label pair for publication.
141
+ */
142
+ export function getCampaignPublishableOptions(options?: unknown): CampaignElementOptionObj[] {
143
+ if (!Array.isArray(options)) {
144
+ return [];
145
+ }
146
+
147
+ const labels = new Set<string>();
148
+ const values = new Set<string>();
149
+ const publishableOptions: CampaignElementOptionObj[] = [];
150
+
151
+ for (const option of options) {
152
+ if (!isCampaignObjectRecord(option) || typeof option.label !== 'string' || typeof option.value !== 'string') {
153
+ continue;
154
+ }
155
+
156
+ const label = option.label.trim();
157
+ const value = option.value.trim();
158
+ if (!label || !value || labels.has(label) || values.has(value)) {
159
+ continue;
160
+ }
161
+
162
+ labels.add(label);
163
+ values.add(value);
164
+ publishableOptions.push({ label, value });
165
+ }
166
+
167
+ return publishableOptions;
168
+ }
169
+
170
+ /*
171
+ * Clear one publication condition when option cleanup removed a value it
172
+ * depended on. Drafts retain the original condition until publication.
173
+ */
174
+ function getCampaignPublicationVisibleWhen(
175
+ element: CampaignDefinitionSnapshotElementObj,
176
+ elementsByKey: ReadonlyMap<string, CampaignDefinitionSnapshotElementObj>,
177
+ ): CampaignElementVisibleWhenObj | null {
178
+ const condition = getCampaignElementVisibleWhenValues(element.visibleWhen);
179
+ if (!condition) {
180
+ return null;
181
+ }
182
+
183
+ const referencedElement = elementsByKey.get(condition.elementKey);
184
+ if (
185
+ condition.elementKey === element.key ||
186
+ !referencedElement ||
187
+ referencedElement.kind !== 'QUESTION' ||
188
+ referencedElement.type === 'FILE'
189
+ ) {
190
+ return null;
191
+ }
192
+
193
+ if (
194
+ isCampaignChoiceElement(referencedElement) &&
195
+ condition.values.some((value) => !referencedElement.options?.some((option) => option.value === value))
196
+ ) {
197
+ return null;
198
+ }
199
+
200
+ return {
201
+ elementKey: condition.elementKey,
202
+ operator: condition.operator,
203
+ value: condition.values,
204
+ };
205
+ }
206
+
207
+ /*
208
+ * Build the respondent-facing definition at the publication boundary. Drafts
209
+ * may save invalid option rows; publishing is where blank and duplicated rows
210
+ * are deleted, and the remaining definition is validated before use.
211
+ */
212
+ export function getCampaignFormPublicationSnapshot(snapshot: CampaignDefinitionSnapshotObj): CampaignDefinitionSnapshotObj {
213
+ const sections = getCampaignFormWithoutAIQuestions(snapshot).sections.map((section) => ({
214
+ ...section,
215
+ elements: (section.elements || []).map((element) =>
216
+ isCampaignChoiceElement(element)
217
+ ? {
218
+ ...element,
219
+ options: getCampaignPublishableOptions(element.options),
220
+ }
221
+ : element,
222
+ ),
223
+ }));
224
+ const elementsByKey = new Map<string, CampaignDefinitionSnapshotElementObj>();
225
+ for (const section of sections) {
226
+ elementsByKey.set(section.key, section);
227
+ for (const element of section.elements) {
228
+ elementsByKey.set(element.key, element);
229
+ }
230
+ }
231
+
232
+ return {
233
+ ...snapshot,
234
+ sections: sections.map((section) => ({
235
+ ...section,
236
+ visibleWhen: getCampaignPublicationVisibleWhen(section, elementsByKey),
237
+ elements: section.elements.map((element) => ({
238
+ ...element,
239
+ visibleWhen: getCampaignPublicationVisibleWhen(element, elementsByKey),
240
+ })),
241
+ })),
242
+ };
243
+ }
244
+
245
+ /*
246
+ * Return one choice question's respondent-facing publication errors.
247
+ */
248
+ function getCampaignChoicePublicationErrors(element: CampaignDefinitionSnapshotElementObj): CampaignFormPublicationError[] {
249
+ if (!isCampaignChoiceElement(element)) {
250
+ return [];
251
+ }
252
+
253
+ const options = element.options || [];
254
+ const labels = new Set<string>();
255
+ const values = new Set<string>();
256
+ const invalidOption = options.some((option) => {
257
+ const label = option.label.trim();
258
+ const value = option.value.trim();
259
+ const invalid = !label || !value || labels.has(label) || values.has(value);
260
+ labels.add(label);
261
+ values.add(value);
262
+ return invalid;
263
+ });
264
+ const errors: CampaignFormPublicationError[] = [];
265
+
266
+ if (options.length < 2) {
267
+ errors.push({
268
+ code: 'INSUFFICIENT_CHOICE_OPTIONS',
269
+ elementKey: element.key,
270
+ });
271
+ }
272
+ if (invalidOption) {
273
+ errors.push({ code: 'EMPTY_CHOICE_OPTION', elementKey: element.key });
274
+ }
275
+
276
+ return errors;
277
+ }
278
+
279
+ /*
280
+ * Reject validation ranges that make a published question impossible to
281
+ * answer. Drafts may temporarily contain these values, but respondents must
282
+ * never receive a form whose minimum exceeds its maximum.
283
+ */
284
+ function isCampaignQuestionValidationInvalid(element: CampaignDefinitionSnapshotElementObj): boolean {
285
+ const validation = getCampaignElementValidation(element.validation);
286
+ if (!validation) {
287
+ return false;
288
+ }
289
+
290
+ if (element.type === 'SHORT_TEXT' || element.type === 'LONG_TEXT') {
291
+ const hardMaxLength = element.type === 'SHORT_TEXT' ? CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH : CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH;
292
+ return (
293
+ (validation.minLength != null && validation.minLength < 0) ||
294
+ (validation.maxLength != null && validation.maxLength < 1) ||
295
+ (validation.maxLength != null && validation.maxLength > hardMaxLength) ||
296
+ (validation.minLength != null && validation.minLength > hardMaxLength) ||
297
+ (validation.minLength != null && validation.maxLength != null && validation.minLength > validation.maxLength)
298
+ );
299
+ }
300
+
301
+ return element.type === 'NUMBER' && validation.min != null && validation.max != null && validation.min > validation.max;
302
+ }
303
+
304
+ /*
305
+ * Return every semantic issue that prevents one structurally safe form from being published.
306
+ */
307
+ export function getCampaignFormPublicationErrors(snapshot: CampaignDefinitionSnapshotObj): CampaignFormPublicationError[] {
308
+ const errors: CampaignFormPublicationError[] = [];
309
+ let questionCount = 0;
310
+
311
+ for (const [sectionIndex, section] of (snapshot.sections || []).entries()) {
312
+ const isImplicitFirstSection =
313
+ sectionIndex === 0 &&
314
+ !section.label?.trim() &&
315
+ !section.description?.trim() &&
316
+ !section.storageRels?.length &&
317
+ !section.settings;
318
+ if (!isImplicitFirstSection && !section.label?.trim()) {
319
+ errors.push({ code: 'EMPTY_SECTION', sectionKey: section.key });
320
+ }
321
+
322
+ for (const element of section.elements || []) {
323
+ if (element.kind !== 'QUESTION' || isCampaignAIQuestion(element)) {
324
+ continue;
325
+ }
326
+
327
+ questionCount += 1;
328
+ if (isCampaignWebFormResultFixedColumnKey(element.key)) {
329
+ errors.push({
330
+ code: 'RESERVED_QUESTION_KEY',
331
+ elementKey: element.key,
332
+ });
333
+ }
334
+ if (!element.label?.trim()) {
335
+ errors.push({
336
+ code: 'EMPTY_QUESTION_LABEL',
337
+ elementKey: element.key,
338
+ });
339
+ }
340
+ if (element.type === 'FILE') {
341
+ errors.push({
342
+ code: 'UNSUPPORTED_FILE_QUESTION',
343
+ elementKey: element.key,
344
+ });
345
+ }
346
+ if (isCampaignQuestionValidationInvalid(element)) {
347
+ errors.push({
348
+ code: 'INVALID_QUESTION_VALIDATION',
349
+ elementKey: element.key,
350
+ });
351
+ }
352
+ errors.push(...getCampaignChoicePublicationErrors(element));
353
+ }
354
+ }
355
+
356
+ if (!questionCount) {
357
+ errors.push({ code: 'NO_QUESTIONS' });
358
+ }
359
+
360
+ return errors;
361
+ }
362
+
363
+ /*
364
+ * Return whether one structurally safe form is complete enough for respondents.
365
+ */
366
+ export function isCampaignFormPublishable(snapshot: CampaignDefinitionSnapshotObj): boolean {
367
+ return getCampaignFormPublicationErrors(snapshot).length === 0;
368
+ }
369
+
370
+ /*
371
+ * Map one template route type to its campaign kind.
372
+ */
373
+
374
+ export function getCampaignKindFromTemplateType(templateType?: string | null): CampaignKindEnum | null {
375
+ switch (templateType as CampaignTemplateType) {
376
+ case 'forms':
377
+ return 'PUBLIC_FORM';
378
+ case 'emails':
379
+ return 'EMAIL';
380
+ default:
381
+ return null;
382
+ }
383
+ }
384
+
385
+ /*
386
+ * Check whether one value is a reply-to agent domain this app owns.
387
+ */
388
+
389
+ export function isCampaignReplyToAgentDomain(value?: string | null): boolean {
390
+ return CAMPAIGN_REPLY_TO_AGENT_DOMAINS.includes(
391
+ String(value || '')
392
+ .trim()
393
+ .toLowerCase(),
394
+ );
395
+ }
396
+
397
+ /*
398
+ * Return the app inbox domains available to one organization's operation.
399
+ */
400
+ export function getCampaignReplyToDomains(operation?: string | null): string[] {
401
+ const operationDomains = (OPERATION_INBOX_DOMAINS as Record<string, string[]>)[operation || ''] || OPERATION_INBOX_DOMAINS.DEFAULT;
402
+
403
+ return [...new Set([...operationDomains, ...DO_NOT_REPLY_EMAIL_DOMAINS])];
404
+ }
405
+
406
+ /*
407
+ * Check whether one app inbox domain can receive mail today. Domains of disabled inboxes are listed as campaign From
408
+ * options but cannot be chosen until their inbox launches.
409
+ */
410
+ export function isCampaignReplyToDomainEnabled(domain?: string | null): boolean {
411
+ const inbox = (DOMAIN_TO_INBOX as Record<string, string | undefined>)[
412
+ String(domain || '')
413
+ .trim()
414
+ .toLowerCase()
415
+ ];
416
+ return !inbox || !DISABLED_INBOXES.includes(inbox as (typeof DISABLED_INBOXES)[number]);
417
+ }
418
+
419
+ /*
420
+ * Return the app inbox domains one organization's operation can choose as a campaign From address today.
421
+ */
422
+ export function getEnabledCampaignReplyToDomains(operation?: string | null): string[] {
423
+ return getCampaignReplyToDomains(operation).filter(isCampaignReplyToDomainEnabled);
424
+ }
425
+
426
+ /*
427
+ * Build the Reply-To mailbox list shared by campaign sends and test emails.
428
+ * The manual address is additional when an agent inbox is configured; it must never replace that inbox.
429
+ * Replacing it sends replies only to the human mailbox, bypassing Postmark ingestion and AI order processing.
430
+ * Preserve the full agent address, including any recipient-specific token used to link replies to the sent campaign.
431
+ * Non-agent addresses (such as do-not-reply) use only the manual address when one is set.
432
+ */
433
+ export function getCampaignEmailReplyToAddress(fromInboxEmail: string, replyToEmail?: string | null): string {
434
+ const manualReplyTo = replyToEmail?.trim();
435
+ if (!manualReplyTo) return fromInboxEmail;
436
+ const inboxDomain = fromInboxEmail.trim().toLowerCase().split('@').at(-1) || '';
437
+ return Object.hasOwn(DOMAIN_TO_INBOX, inboxDomain) ? `${fromInboxEmail}, ${manualReplyTo}` : manualReplyTo;
438
+ }
439
+
440
+ /*
441
+ * Identify app inbox addresses, including legacy inboxes reserved for agent routing and the outbound sender domain.
442
+ */
443
+ export function isCampaignAppReplyToEmail(value?: string | null): boolean {
444
+ const domain =
445
+ String(value || '')
446
+ .trim()
447
+ .toLowerCase()
448
+ .split('@')
449
+ .at(-1) || '';
450
+ return isCampaignReplyToAgentDomain(domain) || OUTBOUND_EMAIL_DOMAINS.includes(domain) || Object.hasOwn(DOMAIN_TO_INBOX, domain);
451
+ }
452
+
453
+ /*
454
+ * Check whether one value is usable as a template's secondary reply-to address.
455
+ * The database also rejects uppercase and comma-bearing values.
456
+ */
457
+
458
+ export function isCampaignSecondaryReplyToEmail(value?: string | null): boolean {
459
+ const normalizedValue = String(value || '').trim();
460
+
461
+ return (
462
+ !!normalizedValue &&
463
+ normalizedValue.length <= CAMPAIGN_EMAIL_TEXT_LIMITS.secondaryReplyToEmail &&
464
+ normalizedValue === normalizedValue.toLowerCase() &&
465
+ !normalizedValue.includes(',') &&
466
+ isEmail(normalizedValue)
467
+ );
468
+ }
469
+
470
+ /*
471
+ * Normalize one list of campaign-skipped address ids from JSONB or client input:
472
+ * database ids travel as digit strings so BIGINT identities survive JSON, and
473
+ * the result is deduplicated and sorted so equal sets always serialize equally.
474
+ */
475
+
476
+ export function getCampaignAudienceExclusionIds(value: unknown): string[] {
477
+ if (!Array.isArray(value)) {
478
+ return [];
479
+ }
480
+
481
+ const ids = new Set<string>();
482
+ for (const item of value) {
483
+ const id = typeof item === 'bigint' ? item.toString() : String(item ?? '');
484
+ if (/^\d+$/.test(id)) {
485
+ ids.add(id);
486
+ }
487
+ }
488
+
489
+ return [...ids].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
490
+ }
491
+
492
+ /*
493
+ * Read one email settings object from campaign JSONB without trusting unknown
494
+ * stored values to have the expected scalar types.
495
+ */
496
+
497
+ export function getEmailCampaignSettings(settings?: unknown): EmailCampaignSettingsObj {
498
+ const values = isCampaignObjectRecord(settings) ? settings : {};
499
+
500
+ return {
501
+ subject: typeof values?.subject === 'string' ? values.subject : null,
502
+ preheader: typeof values?.preheader === 'string' ? values.preheader : null,
503
+ body: typeof values?.body === 'string' ? values.body : null,
504
+ aiAgentDomain: typeof values?.aiAgentDomain === 'string' ? values.aiAgentDomain : '',
505
+ secondaryReplyToEmail: typeof values?.secondaryReplyToEmail === 'string' ? values.secondaryReplyToEmail : null,
506
+ sendAt: typeof values?.sendAt === 'string' ? values.sendAt : null,
507
+ design: getCampaignEmailDesignSettings(values?.design),
508
+ trackOpens: values?.trackOpens !== false,
509
+ excludedEmailAddressIds: getCampaignAudienceExclusionIds(values?.excludedEmailAddressIds),
510
+ ...(Array.isArray(values.excludedEmails)
511
+ ? { excludedEmails: values.excludedEmails.filter((email): email is string => typeof email === 'string') }
512
+ : {}),
513
+ ...(Array.isArray(values.excludedOrganizationIds)
514
+ ? { excludedOrganizationIds: getCampaignAudienceExclusionIds(values.excludedOrganizationIds) }
515
+ : {}),
516
+ ...(values.networkPermissionPolicy === 'RELATIONSHIP' ? { networkPermissionPolicy: 'RELATIONSHIP' as const } : {}),
517
+ ...(isCampaignObjectRecord(values.emailReplyReport) &&
518
+ values.emailReplyReport.version === 1 &&
519
+ Array.isArray(values.emailReplyReport.fields)
520
+ ? { emailReplyReport: values.emailReplyReport as unknown as NonNullable<EmailCampaignSettingsObj['emailReplyReport']> }
521
+ : {}),
522
+ ...(isCampaignObjectRecord(values.emailListRecipientSummary)
523
+ ? { emailListRecipientSummary: values.emailListRecipientSummary }
524
+ : {}),
525
+ ...(isCampaignObjectRecord(values.networkRecipientSummary) ? { networkRecipientSummary: values.networkRecipientSummary } : {}),
526
+ ...(isCampaignObjectRecord(values.emailListSendInfo) &&
527
+ typeof values.emailListSendInfo.senderAddress === 'string' &&
528
+ typeof values.emailListSendInfo.replyAddress === 'string' &&
529
+ typeof values.emailListSendInfo.timeZone === 'string'
530
+ ? {
531
+ emailListSendInfo: {
532
+ senderAddress: values.emailListSendInfo.senderAddress,
533
+ replyAddress: values.emailListSendInfo.replyAddress,
534
+ timeZone: values.emailListSendInfo.timeZone,
535
+ },
536
+ }
537
+ : {}),
538
+ };
539
+ }
540
+
541
+ /*
542
+ * Read one form settings object from campaign JSONB without trusting unknown
543
+ * stored values to have the expected scalar types.
544
+ */
545
+
546
+ export function getFormCampaignSettings(settings?: unknown): FormCampaignSettingsObj {
547
+ const values = isCampaignObjectRecord(settings) ? settings : {};
548
+
549
+ return {
550
+ color: typeof values?.color === 'string' ? values.color : undefined,
551
+ backgroundFillStyle:
552
+ typeof values?.backgroundFillStyle === 'string' && isCampaignFormBackgroundFillStyle(values.backgroundFillStyle)
553
+ ? values.backgroundFillStyle
554
+ : undefined,
555
+ confirmationMessage: typeof values?.confirmationMessage === 'string' ? values.confirmationMessage : undefined,
556
+ };
557
+ }
558
+
559
+ /*
560
+ * Return one element's declared options in the canonical value-and-label
561
+ * shape. Invalid persisted JSON is ignored instead of being promoted into a
562
+ * second legacy contract.
563
+ */
564
+
565
+ export function getCampaignElementOptions(element?: unknown): CampaignElementOptionObj[] {
566
+ const options = isCampaignObjectRecord(element) ? element.options : null;
567
+
568
+ if (!Array.isArray(options)) {
569
+ return [];
570
+ }
571
+
572
+ return options.flatMap((option) => {
573
+ if (!isCampaignObjectRecord(option) || typeof option.value !== 'string' || typeof option.label !== 'string') {
574
+ return [];
575
+ }
576
+
577
+ const value = option.value.trim();
578
+ const label = option.label.trim();
579
+
580
+ return value ? [{ value, label }] : [];
581
+ });
582
+ }
583
+
584
+ /*
585
+ * Read one element validation object while dropping unknown or incorrectly
586
+ * typed JSONB values before they reach GraphQL or another editor save.
587
+ */
588
+
589
+ export function getCampaignElementValidation(validation?: unknown): CampaignElementValidationObj | null {
590
+ const values = isCampaignObjectRecord(validation) ? validation : {};
591
+ const normalized: CampaignElementValidationObj = {
592
+ minLength: isCampaignGraphQLInt(values?.minLength) ? values.minLength : undefined,
593
+ maxLength: isCampaignGraphQLInt(values?.maxLength) ? values.maxLength : undefined,
594
+ min: typeof values?.min === 'number' && Number.isFinite(values.min) ? values.min : undefined,
595
+ max: typeof values?.max === 'number' && Number.isFinite(values.max) ? values.max : undefined,
596
+ maxFiles: isCampaignGraphQLInt(values?.maxFiles) ? values.maxFiles : undefined,
597
+ acceptedContentTypes: Array.isArray(values?.acceptedContentTypes)
598
+ ? values.acceptedContentTypes.filter((value): value is string => typeof value === 'string')
599
+ : undefined,
600
+ };
601
+
602
+ return Object.values(normalized).some((value) => value !== undefined) ? normalized : null;
603
+ }
604
+
605
+ /*
606
+ * Check whether one value is a supported conditional-visibility operator.
607
+ */
608
+
609
+ export function isCampaignElementVisibleWhenOperator(value?: string | null): value is CampaignElementVisibleWhenOperatorEnum {
610
+ return CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS.includes(value as CampaignElementVisibleWhenOperatorEnum);
611
+ }
612
+
613
+ /*
614
+ * Normalize stored or mutation-input visibility into GraphQL's always-array
615
+ * values shape.
616
+ */
617
+
618
+ export function getCampaignElementVisibleWhenValues(visibleWhen?: unknown): CampaignElementVisibleWhenValuesObj | null {
619
+ const valuesObject = isCampaignObjectRecord(visibleWhen) ? visibleWhen : null;
620
+ const operator =
621
+ typeof valuesObject?.operator === 'string' && isCampaignElementVisibleWhenOperator(valuesObject.operator)
622
+ ? valuesObject.operator
623
+ : null;
624
+
625
+ if (typeof valuesObject?.elementKey !== 'string' || !operator) {
626
+ return null;
627
+ }
628
+
629
+ const rawValues = 'values' in valuesObject ? valuesObject.values : valuesObject.value;
630
+ const values =
631
+ rawValues == null
632
+ ? []
633
+ : (Array.isArray(rawValues) ? rawValues : [rawValues]).filter((value): value is string => typeof value === 'string');
634
+
635
+ return {
636
+ elementKey: valuesObject.elementKey,
637
+ operator,
638
+ values,
639
+ };
640
+ }
641
+
642
+ /*
643
+ * Convert GraphQL's visibility values list into the JSONB storage shape used
644
+ * by campaign definitions and snapshots.
645
+ */
646
+
647
+ export function getCampaignElementVisibleWhenStorageValue(
648
+ visibleWhen?: CampaignElementVisibleWhenObj | CampaignElementVisibleWhenValuesObj | null,
649
+ ): CampaignElementVisibleWhenObj | null {
650
+ const normalized = getCampaignElementVisibleWhenValues(visibleWhen);
651
+
652
+ return normalized
653
+ ? {
654
+ elementKey: normalized.elementKey,
655
+ operator: normalized.operator,
656
+ value: normalized.values,
657
+ }
658
+ : null;
659
+ }
660
+
661
+ /*
662
+ * Resolve sparse element presentation settings to GraphQL's explicit boolean
663
+ * fields.
664
+ */
665
+
666
+ export function getCampaignElementSettings(settings?: unknown): CampaignElementSettingsGQL {
667
+ const values = isCampaignObjectRecord(settings) ? settings : {};
668
+ const emailRow = getCampaignEmailRowStorageSettings(values.emailRow);
669
+ const emailBlock = getCampaignEmailBlockStorageSettings(values.emailBlock);
670
+
671
+ return {
672
+ numbered: values.numbered === true,
673
+ fullWidth: values.fullWidth === true,
674
+ ...(emailRow ? { emailRow } : {}),
675
+ ...(emailBlock ? { emailBlock } : {}),
676
+ };
677
+ }
678
+
679
+ /*
680
+ * Convert element presentation settings back to sparse JSONB, clearing the
681
+ * object when every flag is false.
682
+ */
683
+
684
+ export function getCampaignElementSettingsStorageValue(settings?: unknown): CampaignElementSettingsObj | null {
685
+ const values = isCampaignObjectRecord(settings) ? settings : {};
686
+ const emailRow = getCampaignEmailRowStorageSettings(values.emailRow);
687
+ const emailBlock = getCampaignEmailBlockStorageSettings(values.emailBlock);
688
+ const normalized: CampaignElementSettingsObj = {
689
+ ...(values.numbered === true ? { numbered: true } : {}),
690
+ ...(values.fullWidth === true ? { fullWidth: true } : {}),
691
+ ...(emailRow ? { emailRow } : {}),
692
+ ...(emailBlock ? { emailBlock } : {}),
693
+ };
694
+
695
+ return Object.keys(normalized).length ? normalized : null;
696
+ }
697
+
698
+ /*
699
+ * Return one answer's values as an array, so single- and multi-value elements
700
+ * can be validated and rendered through one code path.
701
+ */
702
+
703
+ export function getCampaignAnswerValues(answer?: CampaignAnswerObj | null): string[] {
704
+ if (answer?.value == null) {
705
+ return [];
706
+ }
707
+
708
+ const values = Array.isArray(answer.value) ? answer.value : [answer.value];
709
+ return values.map((value) => String(value).trim()).filter(Boolean);
710
+ }
711
+
712
+ /*
713
+ * Return answer display values using submission-time choice labels first and
714
+ * current element labels only as a fallback for legacy responses.
715
+ */
716
+
717
+ export function getCampaignAnswerDisplayValues(answer?: CampaignAnswerObj | null, element?: unknown): string[] {
718
+ const labelsByValue = new Map(getCampaignElementOptions(element).map((option) => [option.value, option.label]));
719
+
720
+ for (const option of answer?.selectedOptions || []) {
721
+ if (option && typeof option.value === 'string' && typeof option.label === 'string' && option.value.trim()) {
722
+ labelsByValue.set(option.value, option.label);
723
+ }
724
+ }
725
+
726
+ return getCampaignAnswerValues(answer).map((value) => labelsByValue.get(value) ?? value);
727
+ }
728
+
729
+ /*
730
+ * Check whether one answer holds nothing a respondent actually entered. FILE
731
+ * questions remain empty until an ownership-checked upload transport exists.
732
+ */
733
+
734
+ export function isCampaignAnswerEmpty(element: Pick<CampaignElementData, 'type'>, answer?: CampaignAnswerObj | null): boolean {
735
+ if (element.type === 'FILE') {
736
+ return true;
737
+ }
738
+ return !getCampaignAnswerValues(answer).length;
739
+ }
740
+
741
+ /*
742
+ * Decide whether one element is visible given the answers so far. An element
743
+ * with no condition is always visible; a condition naming an unknown element
744
+ * is treated as visible so a malformed rule can never hide a required
745
+ * question and deadlock the form.
746
+ */
747
+
748
+ export function isCampaignElementVisible(
749
+ element: Pick<CampaignElementData, 'visibleWhen'>,
750
+ answers: CampaignAnswersObj,
751
+ elementsByKey?: ReadonlyMap<string, unknown>,
752
+ ): boolean {
753
+ const condition = element.visibleWhen;
754
+ if (!condition?.elementKey) {
755
+ return true;
756
+ }
757
+
758
+ const target = elementsByKey?.get(condition.elementKey);
759
+ if (elementsByKey && !target) {
760
+ return true;
761
+ }
762
+
763
+ const values = getCampaignAnswerValues(answers[condition.elementKey]);
764
+ const expected = condition.value == null ? [] : Array.isArray(condition.value) ? condition.value : [condition.value];
765
+
766
+ switch (condition.operator) {
767
+ case 'IS_ANSWERED':
768
+ return values.length > 0;
769
+ case 'NOT_EQUALS':
770
+ return !expected.some((value) => values.includes(value));
771
+ case 'INCLUDES':
772
+ return expected.some((value) => values.includes(value));
773
+ case 'EQUALS':
774
+ return values.length === expected.length && expected.every((value) => values.includes(value));
775
+ default:
776
+ return true;
777
+ }
778
+ }
779
+
780
+ export interface CampaignVisibilityElementObj {
781
+ key: string;
782
+ parentKey?: string | null;
783
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
784
+ }
785
+
786
+ /*
787
+ * Flatten sections and their children into one visibility graph. A child
788
+ * carries its containing section as an upstream dependency in addition to its
789
+ * own visibleWhen condition.
790
+ */
791
+
792
+ export function getCampaignDefinitionVisibilityElements(
793
+ sections: Array<{
794
+ key: string;
795
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
796
+ elements?: Array<{
797
+ key: string;
798
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
799
+ }> | null;
800
+ }>,
801
+ ): CampaignVisibilityElementObj[] {
802
+ return sections.flatMap((section) => [
803
+ {
804
+ key: section.key,
805
+ visibleWhen: section.visibleWhen || null,
806
+ },
807
+ ...(section.elements || []).map((element) => ({
808
+ key: element.key,
809
+ parentKey: section.key,
810
+ visibleWhen: element.visibleWhen || null,
811
+ })),
812
+ ]);
813
+ }
814
+
815
+ /*
816
+ * Return the element keys whose own condition and every upstream dependency
817
+ * are visible. Recomputing from the complete definition keeps chained
818
+ * conditions correct even when an earlier answer hides several descendants.
819
+ */
820
+
821
+ export function getVisibleCampaignElementKeys(elements: CampaignVisibilityElementObj[], answers: CampaignAnswersObj): Set<string> {
822
+ const elementsByKey = new Map(elements.map((element) => [element.key, element]));
823
+ const visibleKeys = new Set(elementsByKey.keys());
824
+ let changed = true;
825
+
826
+ while (changed) {
827
+ changed = false;
828
+
829
+ for (const element of elements) {
830
+ if (!visibleKeys.has(element.key)) {
831
+ continue;
832
+ }
833
+
834
+ const dependencyKey = element.visibleWhen?.elementKey;
835
+ const parentIsHidden = !!element.parentKey && elementsByKey.has(element.parentKey) && !visibleKeys.has(element.parentKey);
836
+ const dependencyIsHidden = !!dependencyKey && elementsByKey.has(dependencyKey) && !visibleKeys.has(dependencyKey);
837
+ if (parentIsHidden || dependencyIsHidden || !isCampaignElementVisible(element, answers, elementsByKey)) {
838
+ visibleKeys.delete(element.key);
839
+ changed = true;
840
+ }
841
+ }
842
+ }
843
+
844
+ return visibleKeys;
845
+ }
846
+
847
+ /*
848
+ * Remove answers for questions a respondent can no longer see. The returned
849
+ * map has no object prototype so legacy reserved element keys remain ordinary
850
+ * serializable data until those publications are retired.
851
+ */
852
+
853
+ export function getVisibleCampaignAnswers(elements: CampaignVisibilityElementObj[], answers: CampaignAnswersObj): CampaignAnswersObj {
854
+ const visibleKeys = getVisibleCampaignElementKeys(elements, answers);
855
+ const visibleAnswers = Object.create(null) as CampaignAnswersObj;
856
+
857
+ for (const [elementKey, answer] of Object.entries(answers)) {
858
+ if (visibleKeys.has(elementKey)) {
859
+ visibleAnswers[elementKey] = answer;
860
+ }
861
+ }
862
+
863
+ return visibleAnswers;
864
+ }
865
+
866
+ /*
867
+ * Validate one respondent's answers against a template definition and return
868
+ * the element keys that failed, so the caller can reject the whole submission
869
+ * with a precise list. Shared by the public form UI and the server so both
870
+ * agree on what "valid" means.
871
+ *
872
+ * Hidden elements are skipped entirely: a required question behind an unmet
873
+ * condition must not block a submission.
874
+ */
875
+
876
+ export function getInvalidCampaignAnswerKeys(
877
+ elements: CampaignElementData[],
878
+ answers: CampaignAnswersObj,
879
+ options?: {
880
+ requireAnswers?: boolean;
881
+ visibilityElements?: CampaignVisibilityElementObj[];
882
+ },
883
+ ): string[] {
884
+ const questions = elements.filter((element) => isCampaignQuestionElement(element) && !isCampaignAIQuestion(element));
885
+ const elementsByKey = new Map(elements.map((element) => [element.key, element]));
886
+ const visibleKeys = getVisibleCampaignElementKeys(options?.visibilityElements || elements, answers);
887
+ const invalidKeys = new Set<string>();
888
+ const textAnswerKeys: string[] = [];
889
+ let totalTextAnswerLength = 0;
890
+
891
+ for (const element of questions) {
892
+ if (!visibleKeys.has(element.key)) {
893
+ continue;
894
+ }
895
+
896
+ const answer = answers[element.key];
897
+ const values = getCampaignAnswerValues(answer);
898
+ const isEmpty = isCampaignAnswerEmpty(element, answer);
899
+ if ((element.type === 'SHORT_TEXT' || element.type === 'LONG_TEXT') && values.length) {
900
+ textAnswerKeys.push(element.key);
901
+ totalTextAnswerLength += values.reduce((total, value) => total + value.length, 0);
902
+ }
903
+
904
+ if (isEmpty) {
905
+ // Drafts may be incomplete; only a submission enforces "required"
906
+ if (element.required && options?.requireAnswers) {
907
+ invalidKeys.add(element.key);
908
+ }
909
+ continue;
910
+ }
911
+
912
+ if (!isCampaignMultiValueElement(element) && values.length > 1) {
913
+ invalidKeys.add(element.key);
914
+ continue;
915
+ }
916
+
917
+ if (isCampaignChoiceElement(element)) {
918
+ const allowedValues = new Set(getCampaignElementOptions(element).map((option) => option.value));
919
+ if (values.some((value) => !allowedValues.has(value))) {
920
+ invalidKeys.add(element.key);
921
+ }
922
+ continue;
923
+ }
924
+
925
+ if (!isCampaignAnswerValueValidForType(element, values)) {
926
+ invalidKeys.add(element.key);
927
+ }
928
+ }
929
+ if (totalTextAnswerLength > CAMPAIGN_RESPONSE_TEXT_ANSWERS_MAX_LENGTH) {
930
+ for (const elementKey of textAnswerKeys) {
931
+ invalidKeys.add(elementKey);
932
+ }
933
+ }
934
+
935
+ // An answer naming an element the template does not have is always invalid
936
+ for (const answerKey of Object.keys(answers)) {
937
+ const element = elementsByKey.get(answerKey);
938
+ if (!element || !isCampaignQuestionElement(element)) {
939
+ invalidKeys.add(answerKey);
940
+ }
941
+ }
942
+
943
+ return [...invalidKeys];
944
+ }
945
+
946
+ /*
947
+ * Check one ISO-looking date by round-tripping its UTC calendar components.
948
+ */
949
+
950
+ function isStrictCampaignDate(value: string): boolean {
951
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
952
+ if (!match) {
953
+ return false;
954
+ }
955
+
956
+ const year = Number(match[1]);
957
+ const month = Number(match[2]);
958
+ const day = Number(match[3]);
959
+ const date = new Date(Date.UTC(year, month - 1, day));
960
+
961
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
962
+ }
963
+
964
+ /*
965
+ * Check one non-choice answer against its element's type and validation rules.
966
+ */
967
+
968
+ export function isCampaignAnswerValueValidForType(
969
+ element: Pick<CampaignElementData, 'type' | 'validation'>,
970
+ values: string[],
971
+ ): boolean {
972
+ const validation = element.validation || {};
973
+ const textMaxLength = getCampaignTextAnswerMaxLength(element);
974
+
975
+ return values.every((value) => {
976
+ switch (element.type) {
977
+ case 'NUMBER': {
978
+ const numberValue = Number(value);
979
+ if (!Number.isFinite(numberValue)) {
980
+ return false;
981
+ }
982
+ if (validation.min != null && numberValue < validation.min) {
983
+ return false;
984
+ }
985
+ return !(validation.max != null && numberValue > validation.max);
986
+ }
987
+ case 'DATE':
988
+ return isStrictCampaignDate(value);
989
+ case 'EMAIL':
990
+ return isEmail(value);
991
+ case 'PHONE':
992
+ return /^[+()\-.\s\d]{7,20}$/.test(value);
993
+ case 'SHORT_TEXT':
994
+ case 'LONG_TEXT': {
995
+ if (textMaxLength !== null && value.length > textMaxLength) {
996
+ return false;
997
+ }
998
+ if (validation.minLength != null && value.length < validation.minLength) {
999
+ return false;
1000
+ }
1001
+ if (validation.maxLength != null && value.length > validation.maxLength) {
1002
+ return false;
1003
+ }
1004
+ return true;
1005
+ }
1006
+ default:
1007
+ return true;
1008
+ }
1009
+ });
1010
+ }
1011
+
1012
+ /*
1013
+ * Return the hard public-form text cap, narrowed further by a valid
1014
+ * author-configured maximum when one exists.
1015
+ */
1016
+ export function getCampaignTextAnswerMaxLength(element: Pick<CampaignElementData, 'type' | 'validation'>): number | null {
1017
+ const hardMaxLength =
1018
+ element.type === 'SHORT_TEXT'
1019
+ ? CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH
1020
+ : element.type === 'LONG_TEXT'
1021
+ ? CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH
1022
+ : null;
1023
+ if (hardMaxLength === null) {
1024
+ return null;
1025
+ }
1026
+
1027
+ const configuredMaxLength = element.validation?.maxLength;
1028
+ return typeof configuredMaxLength === 'number' && Number.isSafeInteger(configuredMaxLength) && configuredMaxLength > 0
1029
+ ? Math.min(configuredMaxLength, hardMaxLength)
1030
+ : hardMaxLength;
1031
+ }
1032
+
1033
+ /*
1034
+ * Check whether one value is a supported form background fill style.
1035
+ */
1036
+
1037
+ export function isCampaignFormBackgroundFillStyle(value?: string | null): value is CampaignFormBackgroundFillStyleEnum {
1038
+ return CAMPAIGN_FORM_BACKGROUND_FILL_STYLES.includes(value as CampaignFormBackgroundFillStyleEnum);
1039
+ }
1040
+
1041
+ /*
1042
+ * Resolve a form color into one generated CSS palette name.
1043
+ */
1044
+
1045
+ export function normalizeCampaignFormColor(color?: string | null): string | null {
1046
+ const normalizedColor = String(color || '')
1047
+ .trim()
1048
+ .toLowerCase();
1049
+
1050
+ if (!normalizedColor) {
1051
+ return null;
1052
+ }
1053
+
1054
+ if (normalizedColor === 'gray' || normalizedColor === 'grey') {
1055
+ return CAMPAIGN_FORM_NEUTRAL_COLOR;
1056
+ }
1057
+
1058
+ return CAMPAIGN_FORM_COLORS.includes(normalizedColor) ? normalizedColor : null;
1059
+ }
1060
+
1061
+ /*
1062
+ * Resolve the form theme color; GRAYSCALE always renders neutral.
1063
+ */
1064
+
1065
+ export function getCampaignFormColor(settings?: FormCampaignSettingsObj | null): string | null {
1066
+ if (getCampaignFormBackgroundFillStyle(settings) === 'GRAYSCALE') {
1067
+ return CAMPAIGN_FORM_NEUTRAL_COLOR;
1068
+ }
1069
+
1070
+ return normalizeCampaignFormColor(settings?.color);
1071
+ }
1072
+
1073
+ /*
1074
+ * Resolve the form background fill style, falling back to the default.
1075
+ */
1076
+
1077
+ export function getCampaignFormBackgroundFillStyle(settings?: FormCampaignSettingsObj | null): CampaignFormBackgroundFillStyleEnum {
1078
+ const style = String(settings?.backgroundFillStyle || '')
1079
+ .trim()
1080
+ .toUpperCase();
1081
+
1082
+ return isCampaignFormBackgroundFillStyle(style) ? style : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
1083
+ }
1084
+
1085
+ /*
1086
+ * Resolve one form's body background colour to a CSS custom property.
1087
+ *
1088
+ * GRAYSCALE ignores the chosen colour entirely; every other fill style maps to
1089
+ * a shade of it. Unknown input falls back to the neutral palette rather than
1090
+ * emitting an undefined variable.
1091
+ */
1092
+
1093
+ export function getCampaignFormBackgroundColorValue(color?: string | null, backgroundFillStyle?: string | null): string {
1094
+ const style = String(backgroundFillStyle || '')
1095
+ .trim()
1096
+ .toUpperCase();
1097
+ const fillStyle = isCampaignFormBackgroundFillStyle(style) ? style : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
1098
+ const resolvedColor =
1099
+ fillStyle === 'GRAYSCALE' ? CAMPAIGN_FORM_NEUTRAL_COLOR : normalizeCampaignFormColor(color) || CAMPAIGN_FORM_NEUTRAL_COLOR;
1100
+
1101
+ switch (fillStyle) {
1102
+ case 'FADED':
1103
+ return `var(--color-${resolvedColor}-alt-fade)`;
1104
+ case 'LIGHT':
1105
+ return `var(--color-${resolvedColor}-alt-light)`;
1106
+ case 'GRAYSCALE':
1107
+ case 'MEDIUM':
1108
+ return `var(--color-${resolvedColor}-alt-medium)`;
1109
+ }
1110
+
1111
+ return `var(--color-${resolvedColor}-alt-medium)`;
1112
+ }
1113
+
1114
+ /*
1115
+ * Resolve one typed form settings object to its background colour.
1116
+ */
1117
+ export function getCampaignFormBackgroundColorValueFromSettings(settings?: FormCampaignSettingsObj | null): string {
1118
+ return getCampaignFormBackgroundColorValue(settings?.color, settings?.backgroundFillStyle);
1119
+ }
1120
+
1121
+ /**
1122
+ * Local draft shape for the create-campaign modal.
1123
+ *
1124
+ * Every persisted field is declared so a draft written by an older build is
1125
+ * rejected rather than half-read; the file list is capped at the same limit the
1126
+ * generation request enforces.
1127
+ */
1128
+
1129
+ export const CAMPAIGN_DRAFT_SCHEMA: DraftSchema = {
1130
+ files: {
1131
+ type: 'array',
1132
+ maxLength: MAX_PUBLIC_FORM_GENERATION_FILES,
1133
+ of: {
1134
+ contentType: 'string',
1135
+ fileKey: 'string',
1136
+ fileUri: 'string',
1137
+ name: 'string',
1138
+ storageId: 'string',
1139
+ uploadedAt: 'number',
1140
+ },
1141
+ },
1142
+ instructions: {
1143
+ EMAIL: { type: 'string', maxLength: CAMPAIGN_INSTRUCTIONS_MAX_LENGTH },
1144
+ PUBLIC_FORM: {
1145
+ type: 'string',
1146
+ maxLength: CAMPAIGN_INSTRUCTIONS_MAX_LENGTH,
1147
+ },
1148
+ },
1149
+ };
1150
+
1151
+ /*
1152
+ * Build the local draft key for one organization's create-campaign modal.
1153
+ * Drafts hold organization content, so the key is scoped per organization.
1154
+ */
1155
+
1156
+ export function getCampaignDraftKey(organizationId: string | number | bigint) {
1157
+ return `${CAMPAIGN_DRAFT_KEY_PREFIX}:${organizationId}`;
1158
+ }
1159
+
1160
+ /*
1161
+ * Build the empty create-campaign draft. Returned fresh each call so callers
1162
+ * can hold it in state without sharing one mutable object.
1163
+ */
1164
+
1165
+ export function getEmptyCampaignDraft(): CampaignDraft {
1166
+ return {
1167
+ files: [],
1168
+ instructions: {
1169
+ EMAIL: '',
1170
+ PUBLIC_FORM: '',
1171
+ },
1172
+ };
1173
+ }