@10x-media/form-builder 0.1.0-beta.9 → 4.0.0-alpha.1

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 (365) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/README.md +11 -3
  3. package/dist/actions/assertNoBlockCollision.js +18 -0
  4. package/dist/actions/assertNoBlockCollision.js.map +1 -0
  5. package/dist/actions/body/serializeBody.d.ts +16 -14
  6. package/dist/actions/body/serializeBody.js +5 -8
  7. package/dist/actions/body/serializeBody.js.map +1 -1
  8. package/dist/actions/builtin/confirmation.js +2 -1
  9. package/dist/actions/builtin/confirmation.js.map +1 -1
  10. package/dist/actions/builtin/emailAction.d.ts +15 -3
  11. package/dist/actions/builtin/emailAction.js +72 -20
  12. package/dist/actions/builtin/emailAction.js.map +1 -1
  13. package/dist/actions/builtin/emailTeam.js +11 -5
  14. package/dist/actions/builtin/emailTeam.js.map +1 -1
  15. package/dist/actions/defineAction.d.ts +37 -6
  16. package/dist/actions/defineAction.js +14 -1
  17. package/dist/actions/defineAction.js.map +1 -1
  18. package/dist/actions/dispatch.d.ts +12 -0
  19. package/dist/actions/dispatch.js +103 -30
  20. package/dist/actions/dispatch.js.map +1 -1
  21. package/dist/actions/dispatchContext.js +19 -0
  22. package/dist/actions/dispatchContext.js.map +1 -0
  23. package/dist/actions/emailRecipients.js +38 -8
  24. package/dist/actions/emailRecipients.js.map +1 -1
  25. package/dist/actions/emailRender.d.ts +27 -0
  26. package/dist/actions/fromAddresses.d.ts +19 -1
  27. package/dist/actions/fromAddresses.js +66 -9
  28. package/dist/actions/fromAddresses.js.map +1 -1
  29. package/dist/actions/recipientSources.d.ts +23 -0
  30. package/dist/actions/recipientSources.js +11 -0
  31. package/dist/actions/recipientSources.js.map +1 -0
  32. package/dist/actions/registry.js +3 -1
  33. package/dist/actions/registry.js.map +1 -1
  34. package/dist/actions/runActions.d.ts +2 -0
  35. package/dist/actions/runActions.js +13 -8
  36. package/dist/actions/runActions.js.map +1 -1
  37. package/dist/actions/sign.js.map +1 -1
  38. package/dist/actions/submissionContext.d.ts +34 -0
  39. package/dist/actions/task.js +43 -16
  40. package/dist/actions/task.js.map +1 -1
  41. package/dist/aggregation/aggregateResponses.js +3 -4
  42. package/dist/aggregation/aggregateResponses.js.map +1 -1
  43. package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
  44. package/dist/aggregation/resolveResultsRequest.js +69 -26
  45. package/dist/aggregation/resolveResultsRequest.js.map +1 -1
  46. package/dist/calc/computeCalcFields.d.ts +5 -3
  47. package/dist/calc/computeCalcFields.js +4 -3
  48. package/dist/calc/computeCalcFields.js.map +1 -1
  49. package/dist/calc/evaluate.d.ts +26 -3
  50. package/dist/calc/evaluate.js +33 -11
  51. package/dist/calc/evaluate.js.map +1 -1
  52. package/dist/calc/formatCalc.d.ts +11 -0
  53. package/dist/calc/formatCalc.js +35 -0
  54. package/dist/calc/formatCalc.js.map +1 -0
  55. package/dist/calc/formatCalcValue.d.ts +17 -0
  56. package/dist/calc/formatCalcValue.js +17 -0
  57. package/dist/calc/formatCalcValue.js.map +1 -0
  58. package/dist/calc/normalizeCalc.d.ts +17 -3
  59. package/dist/calc/normalizeCalc.js +39 -17
  60. package/dist/calc/normalizeCalc.js.map +1 -1
  61. package/dist/calc/registry.d.ts +43 -0
  62. package/dist/calc/registry.js +27 -0
  63. package/dist/calc/registry.js.map +1 -0
  64. package/dist/calc/resolveCalcContext.d.ts +36 -0
  65. package/dist/calc/resolveCalcContext.js +87 -0
  66. package/dist/calc/resolveCalcContext.js.map +1 -0
  67. package/dist/calc/types.d.ts +19 -4
  68. package/dist/calc/types.js +3 -2
  69. package/dist/calc/types.js.map +1 -1
  70. package/dist/client/ByteSizeField.js +11 -8
  71. package/dist/client/ByteSizeField.js.map +1 -1
  72. package/dist/client/CalcExpressionBuilder.d.ts +20 -0
  73. package/dist/client/CalcExpressionBuilder.js +888 -0
  74. package/dist/client/CalcExpressionBuilder.js.map +1 -0
  75. package/dist/client/ClosePollButton.js +3 -3
  76. package/dist/client/ClosePollButton.js.map +1 -1
  77. package/dist/client/CondensedArray.d.ts +2 -2
  78. package/dist/client/CondensedArray.js +5 -7
  79. package/dist/client/CondensedArray.js.map +1 -1
  80. package/dist/client/ConditionBuilder.js +5 -7
  81. package/dist/client/ConditionBuilder.js.map +1 -1
  82. package/dist/client/ConditionRow.js +3 -3
  83. package/dist/client/ConditionRow.js.map +1 -1
  84. package/dist/client/ConsentBlockLabel.js +2 -2
  85. package/dist/client/ConsentBlockLabel.js.map +1 -1
  86. package/dist/client/ConsentRetentionNotice.d.ts +11 -0
  87. package/dist/client/ConsentRetentionNotice.js +23 -0
  88. package/dist/client/ConsentRetentionNotice.js.map +1 -0
  89. package/dist/client/EndpointOptionsSelect.d.ts +17 -7
  90. package/dist/client/EndpointOptionsSelect.js +18 -14
  91. package/dist/client/EndpointOptionsSelect.js.map +1 -1
  92. package/dist/client/FieldBlockLabel.js +2 -2
  93. package/dist/client/FieldBlockLabel.js.map +1 -1
  94. package/dist/client/FieldNameSelect.d.ts +1 -0
  95. package/dist/client/FieldNameSelect.js +2 -4
  96. package/dist/client/FieldNameSelect.js.map +1 -1
  97. package/dist/client/FlowBuilder.js +31 -23
  98. package/dist/client/FlowBuilder.js.map +1 -1
  99. package/dist/client/FormConditionField.js +0 -1
  100. package/dist/client/FormConditionField.js.map +1 -1
  101. package/dist/client/RecipientsSelect.d.ts +9 -2
  102. package/dist/client/RecipientsSelect.js +31 -10
  103. package/dist/client/RecipientsSelect.js.map +1 -1
  104. package/dist/client/admin.css +345 -72
  105. package/dist/client/endpointOptions.d.ts +11 -0
  106. package/dist/client/endpointOptions.js +17 -8
  107. package/dist/client/endpointOptions.js.map +1 -1
  108. package/dist/collections/formSubmissions.js +145 -51
  109. package/dist/collections/formSubmissions.js.map +1 -1
  110. package/dist/collections/forms.js +170 -65
  111. package/dist/collections/forms.js.map +1 -1
  112. package/dist/collections/formsEndpoints.js +31 -26
  113. package/dist/collections/formsEndpoints.js.map +1 -1
  114. package/dist/collections/settingsFields.d.ts +32 -0
  115. package/dist/collections/settingsFields.js +55 -0
  116. package/dist/collections/settingsFields.js.map +1 -0
  117. package/dist/consent/captureConsent.d.ts +2 -1
  118. package/dist/consent/captureConsent.js +4 -1
  119. package/dist/consent/captureConsent.js.map +1 -1
  120. package/dist/consent/consentSourcesField.d.ts +7 -1
  121. package/dist/consent/consentSourcesField.js +15 -1
  122. package/dist/consent/consentSourcesField.js.map +1 -1
  123. package/dist/consent/effectiveStatement.js +16 -0
  124. package/dist/consent/effectiveStatement.js.map +1 -0
  125. package/dist/consent/resolveConsentSourcesRequest.js +2 -2
  126. package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
  127. package/dist/consent/resolveConsentStatements.js +3 -1
  128. package/dist/consent/resolveConsentStatements.js.map +1 -1
  129. package/dist/consent/resolvePublishedVersionRef.js +1 -0
  130. package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
  131. package/dist/consent/types.d.ts +8 -0
  132. package/dist/context/formContext.d.ts +30 -0
  133. package/dist/context/formContext.js +54 -0
  134. package/dist/context/formContext.js.map +1 -0
  135. package/dist/email/departmentsField.d.ts +6 -1
  136. package/dist/email/departmentsField.js +6 -1
  137. package/dist/email/departmentsField.js.map +1 -1
  138. package/dist/exports/client.d.ts +3 -1
  139. package/dist/exports/client.js +3 -1
  140. package/dist/exports/i18n.d.ts +14 -2
  141. package/dist/exports/i18n.js +14 -2
  142. package/dist/exports/react.d.ts +23 -5
  143. package/dist/exports/react.js +17 -1
  144. package/dist/exports/rsc.d.ts +4 -1
  145. package/dist/exports/rsc.js +7 -4
  146. package/dist/exports/types.d.ts +4 -3
  147. package/dist/fields/buildFieldBlocks.js +2 -1
  148. package/dist/fields/buildFieldBlocks.js.map +1 -1
  149. package/dist/fields/builtin/calculation.d.ts +17 -0
  150. package/dist/fields/builtin/calculation.js +70 -127
  151. package/dist/fields/builtin/calculation.js.map +1 -1
  152. package/dist/fields/builtin/checkbox.js +15 -0
  153. package/dist/fields/builtin/checkbox.js.map +1 -1
  154. package/dist/fields/builtin/consent.js +21 -1
  155. package/dist/fields/builtin/consent.js.map +1 -1
  156. package/dist/fields/builtin/email.js +7 -0
  157. package/dist/fields/builtin/email.js.map +1 -1
  158. package/dist/fields/builtin/index.d.ts +6 -2
  159. package/dist/fields/builtin/index.js +9 -4
  160. package/dist/fields/builtin/index.js.map +1 -1
  161. package/dist/fields/builtin/select.js +20 -1
  162. package/dist/fields/builtin/select.js.map +1 -1
  163. package/dist/fields/builtin/text.js +7 -0
  164. package/dist/fields/builtin/text.js.map +1 -1
  165. package/dist/fields/instanceOptions.js +1 -1
  166. package/dist/fields/instanceOptions.js.map +1 -1
  167. package/dist/fields/sharedConfig.js +15 -11
  168. package/dist/fields/sharedConfig.js.map +1 -1
  169. package/dist/fields/types.d.ts +8 -2
  170. package/dist/form/findFormAtLocale.d.ts +30 -0
  171. package/dist/form/findFormAtLocale.js +88 -0
  172. package/dist/form/findFormAtLocale.js.map +1 -0
  173. package/dist/form/pollState.d.ts +2 -1
  174. package/dist/form/pollState.js.map +1 -1
  175. package/dist/form/toFormDocument.d.ts +8 -0
  176. package/dist/form/toFormDocument.js +3 -1
  177. package/dist/form/toFormDocument.js.map +1 -1
  178. package/dist/form/types.d.ts +9 -1
  179. package/dist/index.d.ts +22 -6
  180. package/dist/index.js +63 -17
  181. package/dist/index.js.map +1 -1
  182. package/dist/options.d.ts +113 -4
  183. package/dist/plugin/collectionSlugs.d.ts +28 -0
  184. package/dist/plugin/collectionSlugs.js +65 -0
  185. package/dist/plugin/collectionSlugs.js.map +1 -0
  186. package/dist/plugin/customState.js +1 -1
  187. package/dist/plugin/customState.js.map +1 -1
  188. package/dist/plugin/registerCollections.js +38 -21
  189. package/dist/plugin/registerCollections.js.map +1 -1
  190. package/dist/poll/closeJob.d.ts +4 -3
  191. package/dist/poll/closeJob.js +13 -10
  192. package/dist/poll/closeJob.js.map +1 -1
  193. package/dist/poll/outcomeBeforeChange.js +2 -2
  194. package/dist/poll/outcomeBeforeChange.js.map +1 -1
  195. package/dist/poll/pollTypeRegistry.js +1 -1
  196. package/dist/poll/resolvePollCloseRequest.js +5 -4
  197. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  198. package/dist/poll/resolvePollOptionsRequest.js +2 -2
  199. package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
  200. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  201. package/dist/poll/resolvePollOutcome.js +20 -6
  202. package/dist/poll/resolvePollOutcome.js.map +1 -1
  203. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  204. package/dist/poll/votes/aggregateFromVotes.js +55 -0
  205. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  206. package/dist/poll/votes/answerValues.js +16 -0
  207. package/dist/poll/votes/answerValues.js.map +1 -0
  208. package/dist/poll/votes/bumpPollVote.js +91 -0
  209. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  210. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  211. package/dist/poll/votes/recountPollVotes.js +63 -0
  212. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  213. package/dist/poll/votes/voteTallyHook.js +76 -0
  214. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  215. package/dist/poll/votes/votesCollection.d.ts +23 -0
  216. package/dist/poll/votes/votesCollection.js +96 -0
  217. package/dist/poll/votes/votesCollection.js.map +1 -0
  218. package/dist/react/Form.d.ts +49 -7
  219. package/dist/react/Form.js +48 -13
  220. package/dist/react/Form.js.map +1 -1
  221. package/dist/react/FormContext.d.ts +8 -1
  222. package/dist/react/FormContext.js.map +1 -1
  223. package/dist/react/FormResults.d.ts +4 -2
  224. package/dist/react/FormResults.js +21 -8
  225. package/dist/react/FormResults.js.map +1 -1
  226. package/dist/react/Poll.d.ts +25 -2
  227. package/dist/react/Poll.js +76 -25
  228. package/dist/react/Poll.js.map +1 -1
  229. package/dist/react/adapters.d.ts +35 -0
  230. package/dist/react/adapters.js +11 -0
  231. package/dist/react/adapters.js.map +1 -0
  232. package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
  233. package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
  234. package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
  235. package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
  236. package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
  237. package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
  238. package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
  239. package/dist/react/captcha/TurnstileCaptcha.js +2 -2
  240. package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
  241. package/dist/react/captcha/useCaptchaScript.js +23 -5
  242. package/dist/react/captcha/useCaptchaScript.js.map +1 -1
  243. package/dist/react/fetchResults.d.ts +6 -3
  244. package/dist/react/fetchResults.js +10 -5
  245. package/dist/react/fetchResults.js.map +1 -1
  246. package/dist/react/primitives/Checkbox.d.ts +4 -2
  247. package/dist/react/primitives/Checkbox.js +3 -2
  248. package/dist/react/primitives/Checkbox.js.map +1 -1
  249. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  250. package/dist/react/primitives/ChoiceGroup.js +33 -0
  251. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  252. package/dist/react/primitives/FieldShell.d.ts +11 -1
  253. package/dist/react/primitives/FieldShell.js +43 -33
  254. package/dist/react/primitives/FieldShell.js.map +1 -1
  255. package/dist/react/primitives/Input.d.ts +3 -1
  256. package/dist/react/primitives/Input.js +2 -1
  257. package/dist/react/primitives/Input.js.map +1 -1
  258. package/dist/react/renderers/calculation.js +6 -1
  259. package/dist/react/renderers/calculation.js.map +1 -1
  260. package/dist/react/renderers/checkbox.js +2 -1
  261. package/dist/react/renderers/checkbox.js.map +1 -1
  262. package/dist/react/renderers/consent.js +8 -3
  263. package/dist/react/renderers/consent.js.map +1 -1
  264. package/dist/react/renderers/email.js +3 -1
  265. package/dist/react/renderers/email.js.map +1 -1
  266. package/dist/react/renderers/repeater.js +5 -0
  267. package/dist/react/renderers/repeater.js.map +1 -1
  268. package/dist/react/renderers/select.js +20 -2
  269. package/dist/react/renderers/select.js.map +1 -1
  270. package/dist/react/renderers/text.js +3 -1
  271. package/dist/react/renderers/text.js.map +1 -1
  272. package/dist/react/state.d.ts +10 -0
  273. package/dist/react/state.js +45 -1
  274. package/dist/react/state.js.map +1 -1
  275. package/dist/react/submitForm.d.ts +20 -3
  276. package/dist/react/submitForm.js +8 -4
  277. package/dist/react/submitForm.js.map +1 -1
  278. package/dist/react/useCalcValues.d.ts +10 -0
  279. package/dist/react/useCalcValues.js +13 -0
  280. package/dist/react/useCalcValues.js.map +1 -0
  281. package/dist/react/useField.js +2 -1
  282. package/dist/react/useField.js.map +1 -1
  283. package/dist/recall/resolver.js +1 -1
  284. package/dist/recall/resolver.js.map +1 -1
  285. package/dist/spam/constants.js +7 -1
  286. package/dist/spam/constants.js.map +1 -1
  287. package/dist/spam/spamGuard.js +2 -1
  288. package/dist/spam/spamGuard.js.map +1 -1
  289. package/dist/submissions/SubmissionAnswersClient.js +14 -14
  290. package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
  291. package/dist/submissions/createSubmission.d.ts +7 -1
  292. package/dist/submissions/createSubmission.js +10 -5
  293. package/dist/submissions/createSubmission.js.map +1 -1
  294. package/dist/submissions/formIdOf.js +13 -0
  295. package/dist/submissions/formIdOf.js.map +1 -0
  296. package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
  297. package/dist/submissions/resolveVotedSubmission.js +51 -0
  298. package/dist/submissions/resolveVotedSubmission.js.map +1 -0
  299. package/dist/submissions/runSubmission.js +6 -5
  300. package/dist/submissions/runSubmission.js.map +1 -1
  301. package/dist/submissions/submissionLocale.js +39 -0
  302. package/dist/submissions/submissionLocale.js.map +1 -0
  303. package/dist/submissions/validateSubmission.js +125 -79
  304. package/dist/submissions/validateSubmission.js.map +1 -1
  305. package/dist/submissions/verifyContext.js +35 -0
  306. package/dist/submissions/verifyContext.js.map +1 -0
  307. package/dist/submissions/voteChange.js +21 -0
  308. package/dist/submissions/voteChange.js.map +1 -0
  309. package/dist/submissions/voteChangeEndpoint.js +110 -0
  310. package/dist/submissions/voteChangeEndpoint.js.map +1 -0
  311. package/dist/submissions/votedCookie.d.ts +10 -4
  312. package/dist/submissions/votedCookie.js +49 -11
  313. package/dist/submissions/votedCookie.js.map +1 -1
  314. package/dist/translations/ar.d.ts +7 -0
  315. package/dist/translations/ar.js +379 -0
  316. package/dist/translations/ar.js.map +1 -0
  317. package/dist/translations/clientRuntimeKeys.d.ts +17 -0
  318. package/dist/translations/clientRuntimeKeys.js +48 -0
  319. package/dist/translations/clientRuntimeKeys.js.map +1 -0
  320. package/dist/translations/de.d.ts +12 -0
  321. package/dist/translations/de.js +78 -3
  322. package/dist/translations/de.js.map +1 -1
  323. package/dist/translations/en.js +78 -3
  324. package/dist/translations/en.js.map +1 -1
  325. package/dist/translations/es.d.ts +7 -0
  326. package/dist/translations/es.js +379 -0
  327. package/dist/translations/es.js.map +1 -0
  328. package/dist/translations/fr.d.ts +7 -0
  329. package/dist/translations/fr.js +379 -0
  330. package/dist/translations/fr.js.map +1 -0
  331. package/dist/translations/id.d.ts +7 -0
  332. package/dist/translations/id.js +379 -0
  333. package/dist/translations/id.js.map +1 -0
  334. package/dist/translations/index.d.ts +23 -6
  335. package/dist/translations/index.js +31 -6
  336. package/dist/translations/index.js.map +1 -1
  337. package/dist/translations/keys.d.ts +76 -1
  338. package/dist/translations/keys.js +76 -1
  339. package/dist/translations/keys.js.map +1 -1
  340. package/dist/translations/ko.d.ts +7 -0
  341. package/dist/translations/ko.js +379 -0
  342. package/dist/translations/ko.js.map +1 -0
  343. package/dist/translations/makeTranslate.d.ts +7 -3
  344. package/dist/translations/makeTranslate.js +12 -3
  345. package/dist/translations/makeTranslate.js.map +1 -1
  346. package/dist/translations/pt.d.ts +7 -0
  347. package/dist/translations/pt.js +379 -0
  348. package/dist/translations/pt.js.map +1 -0
  349. package/dist/translations/ru.d.ts +7 -0
  350. package/dist/translations/ru.js +379 -0
  351. package/dist/translations/ru.js.map +1 -0
  352. package/dist/translations/uk.d.ts +7 -0
  353. package/dist/translations/uk.js +379 -0
  354. package/dist/translations/uk.js.map +1 -0
  355. package/dist/translations/zh.d.ts +7 -0
  356. package/dist/translations/zh.js +379 -0
  357. package/dist/translations/zh.js.map +1 -0
  358. package/dist/validation/builtin/index.js +2 -0
  359. package/dist/validation/builtin/index.js.map +1 -1
  360. package/dist/validation/builtin/integer.js +15 -0
  361. package/dist/validation/builtin/integer.js.map +1 -0
  362. package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
  363. package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
  364. package/package.json +24 -16
  365. package/styles/form-builder.css +84 -0
@@ -1,108 +1,154 @@
1
1
  import { keys } from "../translations/keys.js";
2
2
  import { asFieldTranslate, asTranslate } from "../translations/server.js";
3
3
  import { resolveConsentEntries } from "../consent/resolveConsentEntries.js";
4
- import { IDENTITY_CONTEXT_KEY } from "../spam/constants.js";
4
+ import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
5
+ import { findFormAtLocale } from "../form/findFormAtLocale.js";
6
+ import { SUBMISSION_LOCALE_CONTEXT_KEY, resolveSubmissionLocale } from "./submissionLocale.js";
5
7
  import { isPollClosed, pollConfigOf } from "../form/pollState.js";
6
- import { resolveEffectivePollOptions } from "../poll/effectivePollOptions.js";
7
- import { FORMS_SLUG } from "../collections/forms.js";
8
+ import { formIdOf } from "./formIdOf.js";
9
+ import { voteChangeTargetOf } from "./voteChange.js";
10
+ import { POLL_CONTEXT_KEY } from "./votedCookie.js";
11
+ import { IDENTITY_CONTEXT_KEY } from "../spam/constants.js";
12
+ import { calcExpressionOf } from "../calc/computeCalcFields.js";
13
+ import { resolveCalcContext } from "../calc/resolveCalcContext.js";
8
14
  import { applyPollOptions } from "../poll/applyPollOptions.js";
15
+ import { resolveEffectivePollOptions } from "../poll/effectivePollOptions.js";
9
16
  import { runSubmission } from "./runSubmission.js";
10
- import { POLL_CONTEXT_KEY } from "./votedCookie.js";
11
- import { FORM_SUBMISSIONS_SLUG } from "../collections/formSubmissions.js";
12
17
  import { APIError, ValidationError } from "payload";
13
18
  //#region src/submissions/validateSubmission.ts
14
19
  /**
15
- * Server-authoritative submission validation. On create it loads the referenced form, re-runs every
20
+ * Server-authoritative submission validation. On create (and on a vote-change update flagged by the
21
+ * vote-submit endpoint) it loads the referenced form, re-runs every
16
22
  * field's required check, intrinsic validator, and declarative rules through `runSubmission`, threading
17
23
  * `req`/`payload` so server-only async rules can hit the DB, and throws a Payload `ValidationError` with
18
24
  * per-field paths on any failure. The client is never trusted.
19
25
  * Consent fields are captured into `result.consent` (array of proofs, one per visible consent field),
20
26
  * built from the host's sources re-resolved here rather than from anything the form or client carries.
21
27
  */
22
- const validateSubmission = ({ registry, ruleRegistry, consentSources, consentSnapshot, uploadSlug, pollSourceRegistry, strictUploadOwnership }) => async ({ data, operation, req }) => {
23
- if (operation !== "create" || !data) return data;
28
+ const validateSubmission = ({ registry, ruleRegistry, calcSources, calcFunctions, consentSources, consentSnapshot, uploadSlug, pollSourceRegistry, strictUploadOwnership }) => async ({ data, operation, originalDoc, req }) => {
29
+ const changeTarget = operation === "update" ? voteChangeTargetOf(req) : void 0;
30
+ if (operation !== "create" && changeTarget === void 0 || !data) return data;
24
31
  const formId = data.form;
25
32
  if (formId == null) return data;
26
- const form = await req.payload.findByID({
27
- collection: FORMS_SLUG,
28
- id: formId,
29
- depth: 0,
30
- locale: req.locale,
31
- req
32
- });
33
- const poll = pollConfigOf(form.poll);
34
- const pollEnabled = form.pollEnabled === true;
35
- req.context[POLL_CONTEXT_KEY] = pollEnabled;
36
- if (pollEnabled && isPollClosed(poll)) throw new APIError(asTranslate(req.i18n.t)(keys.pollClosed), 403);
37
- let fields = form.fields ?? [];
38
- const incoming = data.values ?? [];
39
- const locale = req.locale ?? "en";
40
- const t = asFieldTranslate(req.i18n.t);
41
- const resultsField = pollEnabled && typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
42
- const resultsInstance = resultsField ? fields.find((instance) => instance.name === resultsField) : void 0;
43
- const usesResolver = typeof poll?.optionSource === "string" && poll.optionSource.length > 0 || Boolean(resultsInstance && registry.get(resultsInstance.blockType)?.resolveOptions);
44
- if (resultsField && usesResolver) {
45
- let resolved;
46
- try {
47
- resolved = await resolveEffectivePollOptions({
33
+ if (changeTarget !== void 0) {
34
+ const originalFormId = originalDoc?.form;
35
+ const boundFormId = originalFormId != null ? formIdOf(originalFormId) : null;
36
+ if (boundFormId == null || String(boundFormId) !== String(formId)) throw new APIError("form-builder: a vote change cannot move a submission across forms", 400);
37
+ }
38
+ const { localization } = req.payload.config;
39
+ const requested = req.context["formBuilderSubmissionLocale"] ?? req.locale;
40
+ delete req.context[SUBMISSION_LOCALE_CONTEXT_KEY];
41
+ const locale = resolveSubmissionLocale(requested, localization);
42
+ const previousLocale = req.locale;
43
+ if (localization) req.locale = locale;
44
+ try {
45
+ const form = await findFormAtLocale({
46
+ payload: req.payload,
47
+ id: formId,
48
+ locale,
49
+ overrideAccess: true,
50
+ req
51
+ });
52
+ const poll = pollConfigOf(form.poll);
53
+ const pollEnabled = form.pollEnabled === true;
54
+ req.context[POLL_CONTEXT_KEY] = {
55
+ pollEnabled,
56
+ allowChange: poll?.allowChange === true
57
+ };
58
+ if (pollEnabled && isPollClosed(poll)) throw new APIError(asTranslate(req.i18n.t)(keys.pollClosed), 403);
59
+ let fields = form.fields ?? [];
60
+ const incoming = data.values ?? [];
61
+ const t = asFieldTranslate(req.i18n.t);
62
+ const resultsField = pollEnabled && typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
63
+ const resultsInstance = resultsField ? fields.find((instance) => instance.name === resultsField) : void 0;
64
+ const usesResolver = typeof poll?.optionSource === "string" && poll.optionSource.length > 0 || Boolean(resultsInstance && registry.get(resultsInstance.blockType)?.resolveOptions);
65
+ if (resultsField && usesResolver) {
66
+ let resolved;
67
+ try {
68
+ resolved = await resolveEffectivePollOptions({
69
+ payload: req.payload,
70
+ req,
71
+ form,
72
+ sources: pollSourceRegistry ?? /* @__PURE__ */ new Map(),
73
+ fieldTypes: registry
74
+ });
75
+ } catch {
76
+ throw new APIError(asTranslate(req.i18n.t)(keys.pollOptionsUnavailable), 503);
77
+ }
78
+ fields = applyPollOptions(fields, resultsField, resolved);
79
+ const answer = incoming.find((entry) => entry.field === resultsField)?.value;
80
+ if (answer != null && answer !== "" && !resolved.some((option) => option.value === answer)) throw new ValidationError({
81
+ collection: pluginSlugsOf(req.payload).formSubmissions,
82
+ errors: [{
83
+ path: resultsField,
84
+ message: asTranslate(req.i18n.t)(keys.validationSelect)
85
+ }]
86
+ }, req.t);
87
+ }
88
+ const expectedOwner = typeof req.context?.["formBuilderSpamIdentity"] === "string" ? req.context[IDENTITY_CONTEXT_KEY] : void 0;
89
+ let consentEntries = [];
90
+ if (consentSources && fields.some((field) => field.blockType === "consent")) try {
91
+ consentEntries = await resolveConsentEntries({
48
92
  payload: req.payload,
49
93
  req,
50
94
  form,
51
- sources: pollSourceRegistry ?? /* @__PURE__ */ new Map(),
52
- fieldTypes: registry
95
+ sources: consentSources
53
96
  });
54
97
  } catch {
55
- throw new APIError(asTranslate(req.i18n.t)(keys.pollOptionsUnavailable), 503);
98
+ throw new APIError(asTranslate(req.i18n.t)(keys.consentSourcesUnavailable), 503);
56
99
  }
57
- fields = applyPollOptions(fields, resultsField, resolved);
58
- const answer = incoming.find((entry) => entry.field === resultsField)?.value;
59
- if (answer != null && answer !== "" && !resolved.some((option) => option.value === answer)) throw new ValidationError({
60
- collection: FORM_SUBMISSIONS_SLUG,
61
- errors: [{
62
- path: resultsField,
63
- message: asTranslate(req.i18n.t)(keys.validationSelect)
64
- }]
65
- }, req.t);
66
- }
67
- const expectedOwner = typeof req.context?.["formBuilderSpamIdentity"] === "string" ? req.context[IDENTITY_CONTEXT_KEY] : void 0;
68
- let consentEntries = [];
69
- if (consentSources && fields.some((field) => field.blockType === "consent")) try {
70
- consentEntries = await resolveConsentEntries({
71
- payload: req.payload,
100
+ let calcResolved;
101
+ if (fields.some((instance) => calcExpressionOf(instance) !== void 0)) {
102
+ let resolved;
103
+ try {
104
+ resolved = await resolveCalcContext({
105
+ fields,
106
+ sources: calcSources ?? {},
107
+ form,
108
+ payload: req.payload,
109
+ req
110
+ });
111
+ } catch (error) {
112
+ req.payload.logger?.error(`@10x-media/form-builder: calc source resolution failed for form ${String(formId)}: ${error instanceof Error ? error.message : String(error)}`);
113
+ throw new APIError(asTranslate(req.i18n.t)(keys.calcSourcesUnavailable), 503);
114
+ }
115
+ const functions = calcFunctions && Object.keys(calcFunctions).length > 0 ? Object.fromEntries(Object.entries(calcFunctions).map(([name, definition]) => [name, definition.apply])) : void 0;
116
+ calcResolved = {
117
+ ...resolved,
118
+ ...functions ? { functions } : {}
119
+ };
120
+ }
121
+ const result = await runSubmission({
122
+ fields,
123
+ values: incoming,
124
+ calcResolved,
125
+ registry,
126
+ ruleRegistry,
127
+ consentEntries,
128
+ consentSnapshot,
129
+ locale,
130
+ t,
131
+ operation: "create",
72
132
  req,
73
- form,
74
- sources: consentSources
133
+ payload: req.payload,
134
+ formId,
135
+ uploadSlug,
136
+ expectedOwner,
137
+ strictUploadOwnership
75
138
  });
76
- } catch {
77
- throw new APIError(asTranslate(req.i18n.t)(keys.consentSourcesUnavailable), 503);
139
+ if (result.errors.length > 0) throw new ValidationError({
140
+ collection: pluginSlugsOf(req.payload).formSubmissions,
141
+ errors: result.errors
142
+ }, req.t);
143
+ data.values = result.values;
144
+ data.descriptors = result.descriptors;
145
+ data.consent = result.consent.length > 0 ? result.consent : void 0;
146
+ data.locale = locale;
147
+ if (!req.user) data.status = "complete";
148
+ return data;
149
+ } finally {
150
+ if (localization) req.locale = previousLocale;
78
151
  }
79
- const result = await runSubmission({
80
- fields,
81
- values: incoming,
82
- registry,
83
- ruleRegistry,
84
- consentEntries,
85
- consentSnapshot,
86
- locale,
87
- t,
88
- operation: "create",
89
- req,
90
- payload: req.payload,
91
- formId,
92
- uploadSlug,
93
- expectedOwner,
94
- strictUploadOwnership
95
- });
96
- if (result.errors.length > 0) throw new ValidationError({
97
- collection: FORM_SUBMISSIONS_SLUG,
98
- errors: result.errors
99
- }, req.t);
100
- data.values = result.values;
101
- data.descriptors = result.descriptors;
102
- data.consent = result.consent.length > 0 ? result.consent : void 0;
103
- data.locale = locale;
104
- if (!req.user) data.status = "complete";
105
- return data;
106
152
  };
107
153
  //#endregion
108
154
  export { validateSubmission };
@@ -1 +1 @@
1
- {"version":3,"file":"validateSubmission.js","names":[],"sources":["../../src/submissions/validateSubmission.ts"],"sourcesContent":["import { APIError, type CollectionBeforeValidateHook, ValidationError } from 'payload'\nimport { FORM_SUBMISSIONS_SLUG } from '../collections/formSubmissions'\nimport { FORMS_SLUG } from '../collections/forms'\nimport type { ConsentSnapshotMode } from '../consent/captureConsent'\nimport { resolveConsentEntries } from '../consent/resolveConsentEntries'\nimport type { ConsentSourceEntry, ConsentSourcesResolver } from '../consent/types'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { applyPollOptions } from '../poll/applyPollOptions'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport { resolveEffectivePollOptions } from '../poll/effectivePollOptions'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport { IDENTITY_CONTEXT_KEY } from '../spam/constants'\nimport { keys } from '../translations/keys'\nimport { asFieldTranslate, asTranslate } from '../translations/server'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport { runSubmission } from './runSubmission'\nimport type { FormFieldInstance, SubmissionValue } from './types'\nimport { POLL_CONTEXT_KEY } from './votedCookie'\n\nexport type ValidateSubmissionArgs = {\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\t/** The host's consent sources resolver (plugin option `consent.sources`); absent when no sources are configured. */\n\tconsentSources?: ConsentSourcesResolver\n\t/** What each consent proof snapshots of the agreed wording (plugin option `consent.snapshot`). */\n\tconsentSnapshot?: ConsentSnapshotMode\n\t/** The plugin-configured uploads collection slug; absent when uploads are disabled. */\n\tuploadSlug?: string\n\t/** Registered poll option sources; a form's configured `optionSource` resolves through this at validation time. */\n\tpollSourceRegistry?: PollOptionSourceRegistry\n\t/** Plugin `spam.uploadOwnership: 'strict'`: reject an owned upload when the submitter is unidentifiable. */\n\tstrictUploadOwnership?: boolean\n}\n\n/**\n * Server-authoritative submission validation. On create it loads the referenced form, re-runs every\n * field's required check, intrinsic validator, and declarative rules through `runSubmission`, threading\n * `req`/`payload` so server-only async rules can hit the DB, and throws a Payload `ValidationError` with\n * per-field paths on any failure. The client is never trusted.\n * Consent fields are captured into `result.consent` (array of proofs, one per visible consent field),\n * built from the host's sources re-resolved here rather than from anything the form or client carries.\n */\nexport const validateSubmission =\n\t({\n\t\tregistry,\n\t\truleRegistry,\n\t\tconsentSources,\n\t\tconsentSnapshot,\n\t\tuploadSlug,\n\t\tpollSourceRegistry,\n\t\tstrictUploadOwnership,\n\t}: ValidateSubmissionArgs): CollectionBeforeValidateHook =>\n\tasync ({ data, operation, req }) => {\n\t\tif (operation !== 'create' || !data) {\n\t\t\treturn data\n\t\t}\n\t\tconst formId = data.form\n\t\tif (formId == null) {\n\t\t\treturn data\n\t\t}\n\n\t\tconst form = await req.payload.findByID({\n\t\t\tcollection: FORMS_SLUG,\n\t\t\tid: formId as string | number,\n\t\t\tdepth: 0,\n\t\t\tlocale: req.locale,\n\t\t\treq,\n\t\t})\n\n\t\t// Stash whether the form is poll-enabled (its top-level `pollEnabled` flag) so the voted-cookie\n\t\t// afterChange hook can skip a second form fetch on the same request.\n\t\tconst poll = pollConfigOf(form.poll)\n\t\tconst pollEnabled = form.pollEnabled === true\n\t\treq.context[POLL_CONTEXT_KEY] = pollEnabled\n\n\t\t// Form-level lifecycle guard, before any field work: a closed poll accepts no submissions,\n\t\t// regardless of what the client rendered.\n\t\tif (pollEnabled && isPollClosed(poll)) {\n\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.pollClosed), 403)\n\t\t}\n\n\t\tlet fields = ((form.fields as FormFieldInstance[] | undefined) ?? []) as FormFieldInstance[]\n\t\tconst incoming = ((data.values as SubmissionValue[] | undefined) ?? []) as SubmissionValue[]\n\t\tconst locale = req.locale ?? 'en'\n\t\tconst t = asFieldTranslate(req.i18n.t)\n\n\t\t// With a resolved choice set for the results field (a poll `optionSource`, or the field type's\n\t\t// own `resolveOptions`) the resolved values are the only accepted answers: options are injected\n\t\t// into the field instance (so the select's membership check and the stored option labels use\n\t\t// them) and membership is also enforced directly, so an empty resolution or a non-select results\n\t\t// field still fails closed. A resolve failure rejects the whole submission rather than skipping\n\t\t// the check. Static authored polls are unaffected: their field validates against its own options\n\t\t// through the normal field pipeline.\n\t\tconst resultsField =\n\t\t\tpollEnabled && typeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tconst resultsInstance = resultsField\n\t\t\t? fields.find((instance) => instance.name === resultsField)\n\t\t\t: undefined\n\t\tconst usesResolver =\n\t\t\t(typeof poll?.optionSource === 'string' && poll.optionSource.length > 0) ||\n\t\t\tBoolean(resultsInstance && registry.get(resultsInstance.blockType)?.resolveOptions)\n\t\tif (resultsField && usesResolver) {\n\t\t\tlet resolved: PollOption[]\n\t\t\ttry {\n\t\t\t\tresolved = await resolveEffectivePollOptions({\n\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\treq,\n\t\t\t\t\tform,\n\t\t\t\t\tsources: pollSourceRegistry ?? new Map(),\n\t\t\t\t\tfieldTypes: registry,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.pollOptionsUnavailable), 503)\n\t\t\t}\n\t\t\tfields = applyPollOptions(fields, resultsField, resolved)\n\t\t\tconst answer = incoming.find((entry) => entry.field === resultsField)?.value\n\t\t\tconst isAnswered = answer != null && answer !== ''\n\t\t\tif (isAnswered && !resolved.some((option) => option.value === answer)) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection: FORM_SUBMISSIONS_SLUG,\n\t\t\t\t\t\terrors: [\n\t\t\t\t\t\t\t{ path: resultsField, message: asTranslate(req.i18n.t)(keys.validationSelect) },\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\treq.t\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst expectedOwner =\n\t\t\ttypeof req.context?.[IDENTITY_CONTEXT_KEY] === 'string'\n\t\t\t\t? (req.context[IDENTITY_CONTEXT_KEY] as string)\n\t\t\t\t: undefined\n\n\t\t// Every consent proof is built from the source as it reads right now, not from anything the\n\t\t// form or the client carries, so a resolver failure rejects the submission rather than\n\t\t// recording an agreement to a statement the server cannot vouch for.\n\t\tlet consentEntries: ConsentSourceEntry[] = []\n\t\tif (consentSources && fields.some((field) => field.blockType === 'consent')) {\n\t\t\ttry {\n\t\t\t\tconsentEntries = await resolveConsentEntries({\n\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\treq,\n\t\t\t\t\tform,\n\t\t\t\t\tsources: consentSources,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.consentSourcesUnavailable), 503)\n\t\t\t}\n\t\t}\n\n\t\tconst result = await runSubmission({\n\t\t\tfields,\n\t\t\tvalues: incoming,\n\t\t\tregistry,\n\t\t\truleRegistry,\n\t\t\tconsentEntries,\n\t\t\tconsentSnapshot,\n\t\t\tlocale,\n\t\t\tt,\n\t\t\toperation: 'create',\n\t\t\treq,\n\t\t\tpayload: req.payload,\n\t\t\tformId: formId as number | string,\n\t\t\tuploadSlug,\n\t\t\texpectedOwner,\n\t\t\tstrictUploadOwnership,\n\t\t})\n\n\t\tif (result.errors.length > 0) {\n\t\t\tthrow new ValidationError({ collection: FORM_SUBMISSIONS_SLUG, errors: result.errors }, req.t)\n\t\t}\n\n\t\tdata.values = result.values\n\t\tdata.descriptors = result.descriptors\n\t\tdata.consent = result.consent.length > 0 ? result.consent : undefined\n\t\tdata.locale = locale\n\t\t// Unauthenticated submits are always 'complete'. A client-supplied 'partial' would\n\t\t// silently skip all post-submit actions and events. Authenticated callers (e.g. an\n\t\t// admin draft-save flow) may set status themselves.\n\t\tif (!req.user) {\n\t\t\tdata.status = 'complete'\n\t\t}\n\t\treturn data\n\t}\n"],"mappings":"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"}
1
+ {"version":3,"file":"validateSubmission.js","names":[],"sources":["../../src/submissions/validateSubmission.ts"],"sourcesContent":["import {\n\tAPIError,\n\ttype CollectionBeforeValidateHook,\n\ttype TypedLocale,\n\tValidationError,\n} from 'payload'\nimport { calcExpressionOf } from '../calc/computeCalcFields'\nimport type { CalcResolved } from '../calc/evaluate'\nimport type { CalcFunction, CalcSource } from '../calc/registry'\nimport { resolveCalcContext } from '../calc/resolveCalcContext'\nimport type { ConsentSnapshotMode } from '../consent/captureConsent'\nimport { resolveConsentEntries } from '../consent/resolveConsentEntries'\nimport type { ConsentSourceEntry, ConsentSourcesResolver } from '../consent/types'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { findFormAtLocale } from '../form/findFormAtLocale'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport { applyPollOptions } from '../poll/applyPollOptions'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport { resolveEffectivePollOptions } from '../poll/effectivePollOptions'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport { IDENTITY_CONTEXT_KEY } from '../spam/constants'\nimport { keys } from '../translations/keys'\nimport { asFieldTranslate, asTranslate } from '../translations/server'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport { formIdOf } from './formIdOf'\nimport { runSubmission } from './runSubmission'\nimport { resolveSubmissionLocale, SUBMISSION_LOCALE_CONTEXT_KEY } from './submissionLocale'\nimport type { FormFieldInstance, SubmissionValue } from './types'\nimport { POLL_CONTEXT_KEY, type PollContextState, voteChangeTargetOf } from './votedCookie'\n\nexport type ValidateSubmissionArgs = {\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\t/** Registered calc sources (plugin option `calc.sources`); re-resolved fresh per submission. */\n\tcalcSources?: Record<string, CalcSource>\n\t/** Registered calc functions (plugin option `calc.functions`); threaded into calc evaluation. */\n\tcalcFunctions?: Record<string, CalcFunction>\n\t/** The host's consent sources resolver (plugin option `consent.sources`); absent when no sources are configured. */\n\tconsentSources?: ConsentSourcesResolver\n\t/** What each consent proof snapshots of the agreed wording (plugin option `consent.snapshot`). */\n\tconsentSnapshot?: ConsentSnapshotMode\n\t/** The plugin-configured uploads collection slug; absent when uploads are disabled. */\n\tuploadSlug?: string\n\t/** Registered poll option sources; a form's configured `optionSource` resolves through this at validation time. */\n\tpollSourceRegistry?: PollOptionSourceRegistry\n\t/** Plugin `spam.uploadOwnership: 'strict'`: reject an owned upload when the submitter is unidentifiable. */\n\tstrictUploadOwnership?: boolean\n}\n\n/**\n * Server-authoritative submission validation. On create (and on a vote-change update flagged by the\n * vote-submit endpoint) it loads the referenced form, re-runs every\n * field's required check, intrinsic validator, and declarative rules through `runSubmission`, threading\n * `req`/`payload` so server-only async rules can hit the DB, and throws a Payload `ValidationError` with\n * per-field paths on any failure. The client is never trusted.\n * Consent fields are captured into `result.consent` (array of proofs, one per visible consent field),\n * built from the host's sources re-resolved here rather than from anything the form or client carries.\n */\nexport const validateSubmission =\n\t({\n\t\tregistry,\n\t\truleRegistry,\n\t\tcalcSources,\n\t\tcalcFunctions,\n\t\tconsentSources,\n\t\tconsentSnapshot,\n\t\tuploadSlug,\n\t\tpollSourceRegistry,\n\t\tstrictUploadOwnership,\n\t}: ValidateSubmissionArgs): CollectionBeforeValidateHook =>\n\tasync ({ data, operation, originalDoc, req }) => {\n\t\t// Updates run the same create-grade pipeline only when the vote-change endpoint flagged the\n\t\t// request; every other update (host server code with overrideAccess) keeps today's behavior.\n\t\tconst changeTarget = operation === 'update' ? voteChangeTargetOf(req) : undefined\n\t\tif ((operation !== 'create' && changeTarget === undefined) || !data) {\n\t\t\treturn data\n\t\t}\n\t\tconst formId = data.form\n\t\tif (formId == null) {\n\t\t\treturn data\n\t\t}\n\t\tif (changeTarget !== undefined) {\n\t\t\t// Fail closed: an unresolvable stored form binding is as disqualifying as a mismatched one.\n\t\t\tconst originalFormId = (originalDoc as { form?: unknown } | undefined)?.form\n\t\t\tconst boundFormId = originalFormId != null ? formIdOf(originalFormId) : null\n\t\t\tif (boundFormId == null || String(boundFormId) !== String(formId)) {\n\t\t\t\tthrow new APIError('form-builder: a vote change cannot move a submission across forms', 400)\n\t\t\t}\n\t\t}\n\n\t\t// `req.locale` comes from the visitor's `?locale=` (or `createSubmission`'s `locale`). Clamp it\n\t\t// before anything reads it (the form load below, the host's consent and calc resolvers) so a\n\t\t// visitor cannot run the pipeline under `all` or an unconfigured code. On a localized host the\n\t\t// clamped value is set on `req` only while this hook runs and restored after, because `req` may\n\t\t// be the host's own request; without localization Payload leaves its `locale` unset, and so do we.\n\t\tconst { localization } = req.payload.config\n\t\tconst requested = req.context[SUBMISSION_LOCALE_CONTEXT_KEY] ?? req.locale\n\t\tdelete req.context[SUBMISSION_LOCALE_CONTEXT_KEY]\n\t\tconst locale = resolveSubmissionLocale(requested, localization)\n\t\tconst previousLocale = req.locale\n\t\tif (localization) {\n\t\t\treq.locale = locale as TypedLocale\n\t\t}\n\t\ttry {\n\t\t\tconst form = await findFormAtLocale({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tid: formId as string | number,\n\t\t\t\tlocale,\n\t\t\t\t// The submitter may not read the whole form (actions are signed-in only); validation does.\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\n\t\t\t// Stash the form's poll state so the voted-cookie afterChange hook can skip a second form\n\t\t\t// fetch on the same request.\n\t\t\tconst poll = pollConfigOf(form.poll)\n\t\t\tconst pollEnabled = form.pollEnabled === true\n\t\t\treq.context[POLL_CONTEXT_KEY] = {\n\t\t\t\tpollEnabled,\n\t\t\t\tallowChange: poll?.allowChange === true,\n\t\t\t} satisfies PollContextState\n\n\t\t\t// Form-level lifecycle guard, before any field work: a closed poll accepts no submissions,\n\t\t\t// regardless of what the client rendered.\n\t\t\tif (pollEnabled && isPollClosed(poll)) {\n\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.pollClosed), 403)\n\t\t\t}\n\n\t\t\tlet fields = ((form.fields as FormFieldInstance[] | undefined) ?? []) as FormFieldInstance[]\n\t\t\tconst incoming = ((data.values as SubmissionValue[] | undefined) ?? []) as SubmissionValue[]\n\t\t\tconst t = asFieldTranslate(req.i18n.t)\n\n\t\t\t// With a resolved choice set for the results field (a poll `optionSource`, or the field type's\n\t\t\t// own `resolveOptions`) the resolved values are the only accepted answers: options are injected\n\t\t\t// into the field instance (so the select's membership check and the stored option labels use\n\t\t\t// them) and membership is also enforced directly, so an empty resolution or a non-select results\n\t\t\t// field still fails closed. A resolve failure rejects the whole submission rather than skipping\n\t\t\t// the check. Static authored polls are unaffected: their field validates against its own options\n\t\t\t// through the normal field pipeline.\n\t\t\tconst resultsField =\n\t\t\t\tpollEnabled && typeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t\t? poll.resultsField\n\t\t\t\t\t: undefined\n\t\t\tconst resultsInstance = resultsField\n\t\t\t\t? fields.find((instance) => instance.name === resultsField)\n\t\t\t\t: undefined\n\t\t\tconst usesResolver =\n\t\t\t\t(typeof poll?.optionSource === 'string' && poll.optionSource.length > 0) ||\n\t\t\t\tBoolean(resultsInstance && registry.get(resultsInstance.blockType)?.resolveOptions)\n\t\t\tif (resultsField && usesResolver) {\n\t\t\t\tlet resolved: PollOption[]\n\t\t\t\ttry {\n\t\t\t\t\tresolved = await resolveEffectivePollOptions({\n\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tform,\n\t\t\t\t\t\tsources: pollSourceRegistry ?? new Map(),\n\t\t\t\t\t\tfieldTypes: registry,\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.pollOptionsUnavailable), 503)\n\t\t\t\t}\n\t\t\t\tfields = applyPollOptions(fields, resultsField, resolved)\n\t\t\t\tconst answer = incoming.find((entry) => entry.field === resultsField)?.value\n\t\t\t\tconst isAnswered = answer != null && answer !== ''\n\t\t\t\tif (isAnswered && !resolved.some((option) => option.value === answer)) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcollection: pluginSlugsOf(req.payload).formSubmissions,\n\t\t\t\t\t\t\terrors: [\n\t\t\t\t\t\t\t\t{ path: resultsField, message: asTranslate(req.i18n.t)(keys.validationSelect) },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq.t\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst expectedOwner =\n\t\t\t\ttypeof req.context?.[IDENTITY_CONTEXT_KEY] === 'string'\n\t\t\t\t\t? (req.context[IDENTITY_CONTEXT_KEY] as string)\n\t\t\t\t\t: undefined\n\n\t\t\t// Every consent proof is built from the source as it reads right now, not from anything the\n\t\t\t// form or the client carries, so a resolver failure rejects the submission rather than\n\t\t\t// recording an agreement to a statement the server cannot vouch for.\n\t\t\tlet consentEntries: ConsentSourceEntry[] = []\n\t\t\tif (consentSources && fields.some((field) => field.blockType === 'consent')) {\n\t\t\t\ttry {\n\t\t\t\t\tconsentEntries = await resolveConsentEntries({\n\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tform,\n\t\t\t\t\t\tsources: consentSources,\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.consentSourcesUnavailable), 503)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Calc extension values re-resolve fresh here, never trusting the render-time embedding, and a\n\t\t\t// resolver failure rejects the submission: a calc total is money math, so an outage must not\n\t\t\t// silently evaluate to 0 (the render path fails open instead; see `calcAfterRead`). Surfaced as\n\t\t\t// a translated 503 (the consent-sources precedent above), with the cause logged server-side\n\t\t\t// rather than leaked to the anonymous caller.\n\t\t\tlet calcResolved: CalcResolved | undefined\n\t\t\tif (fields.some((instance) => calcExpressionOf(instance) !== undefined)) {\n\t\t\t\tlet resolved: CalcResolved\n\t\t\t\ttry {\n\t\t\t\t\tresolved = await resolveCalcContext({\n\t\t\t\t\t\tfields,\n\t\t\t\t\t\tsources: calcSources ?? {},\n\t\t\t\t\t\t// Double cast: a host's generated Form interface has no index signature, so the direct\n\t\t\t\t\t\t// cast fails under a consumer tsconfig even though the shape is a plain document.\n\t\t\t\t\t\tform: form as unknown as { id: number | string } & Record<string, unknown>,\n\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\treq,\n\t\t\t\t\t})\n\t\t\t\t} catch (error) {\n\t\t\t\t\treq.payload.logger?.error(\n\t\t\t\t\t\t`@10x-media/form-builder: calc source resolution failed for form ${String(formId)}: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t}`\n\t\t\t\t\t)\n\t\t\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.calcSourcesUnavailable), 503)\n\t\t\t\t}\n\t\t\t\tconst functions =\n\t\t\t\t\tcalcFunctions && Object.keys(calcFunctions).length > 0\n\t\t\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\t\t\tObject.entries(calcFunctions).map(([name, definition]) => [name, definition.apply])\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined\n\t\t\t\tcalcResolved = { ...resolved, ...(functions ? { functions } : {}) }\n\t\t\t}\n\n\t\t\tconst result = await runSubmission({\n\t\t\t\tfields,\n\t\t\t\tvalues: incoming,\n\t\t\t\tcalcResolved,\n\t\t\t\tregistry,\n\t\t\t\truleRegistry,\n\t\t\t\tconsentEntries,\n\t\t\t\tconsentSnapshot,\n\t\t\t\tlocale,\n\t\t\t\tt,\n\t\t\t\toperation: 'create',\n\t\t\t\treq,\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: formId as number | string,\n\t\t\t\tuploadSlug,\n\t\t\t\texpectedOwner,\n\t\t\t\tstrictUploadOwnership,\n\t\t\t})\n\n\t\t\tif (result.errors.length > 0) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t{ collection: pluginSlugsOf(req.payload).formSubmissions, errors: result.errors },\n\t\t\t\t\treq.t\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tdata.values = result.values\n\t\t\tdata.descriptors = result.descriptors\n\t\t\tdata.consent = result.consent.length > 0 ? result.consent : undefined\n\t\t\tdata.locale = locale\n\t\t\t// Unauthenticated submits are always 'complete'. A client-supplied 'partial' would\n\t\t\t// silently skip all post-submit actions and events. Authenticated callers (e.g. an\n\t\t\t// admin draft-save flow) may set status themselves.\n\t\t\tif (!req.user) {\n\t\t\t\tdata.status = 'complete'\n\t\t\t}\n\t\t\treturn data\n\t\t} finally {\n\t\t\tif (localization) {\n\t\t\t\treq.locale = previousLocale\n\t\t\t}\n\t\t}\n\t}\n"],"mappings":"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"}
@@ -0,0 +1,35 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { asTranslate } from "../translations/server.js";
3
+ import { verifyFormContext } from "../context/formContext.js";
4
+ import { CONTEXT_KEY } from "../spam/constants.js";
5
+ import { APIError } from "payload";
6
+ //#region src/submissions/verifyContext.ts
7
+ /**
8
+ * beforeValidate: pull the reserved signed-context entry out of the submitted values, verify it, and
9
+ * stamp the verified `{ relationTo, value }` on the submission's separate `context` field. Runs
10
+ * independently of the spam config (context must work with spam off) and before `validateSubmission`
11
+ * stores the answers, so the token never reaches `values`, the answers view, or `{{*}}` output.
12
+ *
13
+ * A missing context is normal (the same form on an ordinary page carries none). An invalid one is
14
+ * rejected loudly rather than dropped to absent, so a tampered reference cannot degrade into a send to
15
+ * the statically configured recipients, which would hide the attack. The stored `value` is a string
16
+ * for cross-adapter consistency; the id it references is already public.
17
+ */
18
+ const verifyContext = () => async ({ data, operation, req }) => {
19
+ if (operation !== "create" || !data) return data;
20
+ const values = Array.isArray(data.values) ? data.values : [];
21
+ const token = values.find((entry) => entry.field === CONTEXT_KEY)?.value;
22
+ data.values = values.filter((entry) => entry.field !== CONTEXT_KEY);
23
+ if (typeof token !== "string" || token.length === 0) return data;
24
+ const verified = verifyFormContext(token, req.payload.secret);
25
+ if (!verified) throw new APIError(asTranslate(req.i18n.t)(keys.contextInvalid), 400);
26
+ data.context = {
27
+ relationTo: verified.relationTo,
28
+ value: String(verified.value)
29
+ };
30
+ return data;
31
+ };
32
+ //#endregion
33
+ export { verifyContext };
34
+
35
+ //# sourceMappingURL=verifyContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifyContext.js","names":[],"sources":["../../src/submissions/verifyContext.ts"],"sourcesContent":["import { APIError, type CollectionBeforeValidateHook } from 'payload'\nimport { verifyFormContext } from '../context/formContext'\nimport { CONTEXT_KEY } from '../spam/constants'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\nimport type { SubmissionValue } from './types'\n\n/**\n * beforeValidate: pull the reserved signed-context entry out of the submitted values, verify it, and\n * stamp the verified `{ relationTo, value }` on the submission's separate `context` field. Runs\n * independently of the spam config (context must work with spam off) and before `validateSubmission`\n * stores the answers, so the token never reaches `values`, the answers view, or `{{*}}` output.\n *\n * A missing context is normal (the same form on an ordinary page carries none). An invalid one is\n * rejected loudly rather than dropped to absent, so a tampered reference cannot degrade into a send to\n * the statically configured recipients, which would hide the attack. The stored `value` is a string\n * for cross-adapter consistency; the id it references is already public.\n */\nexport const verifyContext =\n\t(): CollectionBeforeValidateHook =>\n\tasync ({ data, operation, req }) => {\n\t\tif (operation !== 'create' || !data) {\n\t\t\treturn data\n\t\t}\n\t\tconst values = Array.isArray(data.values) ? (data.values as SubmissionValue[]) : []\n\t\tconst token = values.find((entry) => entry.field === CONTEXT_KEY)?.value\n\t\t// Always strip the reserved entry, verified or not, so it can never land in the answers.\n\t\tdata.values = values.filter((entry) => entry.field !== CONTEXT_KEY)\n\t\tif (typeof token !== 'string' || token.length === 0) {\n\t\t\treturn data\n\t\t}\n\t\tconst verified = verifyFormContext(token, req.payload.secret)\n\t\tif (!verified) {\n\t\t\tthrow new APIError(asTranslate(req.i18n.t)(keys.contextInvalid), 400)\n\t\t}\n\t\tdata.context = { relationTo: verified.relationTo, value: String(verified.value) }\n\t\treturn data\n\t}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,sBAEZ,OAAO,EAAE,MAAM,WAAW,UAAU;CACnC,IAAI,cAAc,YAAY,CAAC,MAC9B,OAAO;CAER,MAAM,SAAS,MAAM,QAAQ,KAAK,MAAM,IAAK,KAAK,SAA+B,CAAC;CAClF,MAAM,QAAQ,OAAO,MAAM,UAAU,MAAM,UAAU,WAAW,GAAG;CAEnE,KAAK,SAAS,OAAO,QAAQ,UAAU,MAAM,UAAU,WAAW;CAClE,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GACjD,OAAO;CAER,MAAM,WAAW,kBAAkB,OAAO,IAAI,QAAQ,MAAM;CAC5D,IAAI,CAAC,UACJ,MAAM,IAAI,SAAS,YAAY,IAAI,KAAK,CAAC,EAAE,KAAK,cAAc,GAAG,GAAG;CAErE,KAAK,UAAU;EAAE,YAAY,SAAS;EAAY,OAAO,OAAO,SAAS,KAAK;CAAE;CAChF,OAAO;AACR"}
@@ -0,0 +1,21 @@
1
+ //#region src/submissions/voteChange.ts
2
+ /**
3
+ * `req.context` key the vote-submit endpoint sets to the id of the submission a cookie-identified
4
+ * re-vote is updating. Its presence is what opts the update operation into the create-grade
5
+ * pipeline: the spam guard, full validation in `validateSubmission`, the dedup rule's
6
+ * self-exclusion, and the voted-cookie refresh all key off it, so an unflagged update (host
7
+ * server code, admin tooling) keeps today's behavior exactly.
8
+ *
9
+ * Kept apart from `votedCookie`, which signs cookies with `node:crypto`: the built-in validation
10
+ * rules read this key and ship in the `./react` client entry.
11
+ */
12
+ const VOTE_CHANGE_CONTEXT_KEY = "formBuilderVoteChange";
13
+ /** The change-target submission id a flagged request carries, or undefined. */
14
+ const voteChangeTargetOf = (req) => {
15
+ const target = req.context?.[VOTE_CHANGE_CONTEXT_KEY];
16
+ return typeof target === "string" || typeof target === "number" ? target : void 0;
17
+ };
18
+ //#endregion
19
+ export { VOTE_CHANGE_CONTEXT_KEY, voteChangeTargetOf };
20
+
21
+ //# sourceMappingURL=voteChange.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voteChange.js","names":[],"sources":["../../src/submissions/voteChange.ts"],"sourcesContent":["/**\n * `req.context` key the vote-submit endpoint sets to the id of the submission a cookie-identified\n * re-vote is updating. Its presence is what opts the update operation into the create-grade\n * pipeline: the spam guard, full validation in `validateSubmission`, the dedup rule's\n * self-exclusion, and the voted-cookie refresh all key off it, so an unflagged update (host\n * server code, admin tooling) keeps today's behavior exactly.\n *\n * Kept apart from `votedCookie`, which signs cookies with `node:crypto`: the built-in validation\n * rules read this key and ship in the `./react` client entry.\n */\nexport const VOTE_CHANGE_CONTEXT_KEY = 'formBuilderVoteChange'\n\n/** The change-target submission id a flagged request carries, or undefined. */\nexport const voteChangeTargetOf = (req: {\n\tcontext?: Record<string, unknown>\n}): number | string | undefined => {\n\tconst target = req.context?.[VOTE_CHANGE_CONTEXT_KEY]\n\treturn typeof target === 'string' || typeof target === 'number' ? target : undefined\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB,QAEA;CAClC,MAAM,SAAS,IAAI,UAAU;CAC7B,OAAO,OAAO,WAAW,YAAY,OAAO,WAAW,WAAW,SAAS,KAAA;AAC5E"}
@@ -0,0 +1,110 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { asTranslate } from "../translations/server.js";
3
+ import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
4
+ import "../actions/dispatchContext.js";
5
+ import { pollConfigOf } from "../form/pollState.js";
6
+ import { formIdOf } from "./formIdOf.js";
7
+ import { VOTE_CHANGE_CONTEXT_KEY } from "./voteChange.js";
8
+ import { votedSubmissionIdFromCookie } from "./votedCookie.js";
9
+ import { APIError, addDataAndFileToRequest, addLocalesToRequestFromData } from "payload";
10
+ //#region src/submissions/voteChangeEndpoint.ts
11
+ /** Marks the vote-submit endpoint in the sanitized endpoint list (`custom.formBuilder`). */
12
+ const VOTE_SUBMIT_ENDPOINT_TAG = "vote-submit";
13
+ const isComplete = (doc) => doc.status == null || doc.status === "complete";
14
+ /**
15
+ * The submission a cookie-identified re-vote should update, or null when the request must fall
16
+ * through to a plain create. Guards run cheapest-first: no valid signed cookie for the posted form
17
+ * means no form fetch at all, so the delegation overhead on ordinary submissions is one header
18
+ * parse. A token is honored only when the form is an `allowChange` poll and it names a still
19
+ * existing, complete submission of that same form; anything else (pruned row, cross-form replay,
20
+ * legacy `1` marker, tampering) makes the caller a new voter rather than an error.
21
+ */
22
+ const resolveVoteChangeTarget = async (args) => {
23
+ const { req, formId } = args;
24
+ if (formId == null) return null;
25
+ const submissionId = votedSubmissionIdFromCookie(req.headers?.get("cookie"), formId, req.payload);
26
+ if (submissionId == null) return null;
27
+ const slugs = pluginSlugsOf(req.payload);
28
+ const form = await req.payload.findByID({
29
+ collection: slugs.forms,
30
+ id: formId,
31
+ depth: 0,
32
+ overrideAccess: true,
33
+ req
34
+ }).catch(() => null);
35
+ if (form?.pollEnabled !== true || pollConfigOf(form.poll)?.allowChange !== true) return null;
36
+ const submission = await req.payload.findByID({
37
+ collection: slugs.formSubmissions,
38
+ id: submissionId,
39
+ depth: 0,
40
+ overrideAccess: true,
41
+ req
42
+ }).catch(() => null);
43
+ if (submission == null) return null;
44
+ const stored = submission;
45
+ if (String(formIdOf(stored.form) ?? "") !== String(formId) || !isComplete(stored)) return null;
46
+ return { submissionId: submission.id };
47
+ };
48
+ /**
49
+ * Custom root `POST` endpoint on the submissions collection (`/form-submissions` by default).
50
+ * Payload matches a collection's custom endpoints ahead of its built-in REST routes, so this handler sees every REST create first: when the posted
51
+ * form is an `allowChange` poll and the voted cookie identifies the caller's submission, it turns
52
+ * the request into an in-place update (create-grade hooks opt in via the context flag); otherwise
53
+ * it delegates to the stock create handler found in the same sanitized endpoint list, keeping the
54
+ * default path semantics Payload's, not a reimplementation. The update runs `overrideAccess`
55
+ * because the collection is deliberately update-closed to every API caller; the signed cookie is
56
+ * the credential here, verified above rather than by collection access.
57
+ */
58
+ const buildVoteSubmitEndpoint = () => {
59
+ const handler = async (req) => {
60
+ await addDataAndFileToRequest(req);
61
+ addLocalesToRequestFromData(req);
62
+ const data = req.data ?? {};
63
+ const submissionsSlug = pluginSlugsOf(req.payload).formSubmissions;
64
+ const target = await resolveVoteChangeTarget({
65
+ req,
66
+ formId: data.form
67
+ });
68
+ if (!target) {
69
+ const endpoints = req.payload.collections[submissionsSlug]?.config.endpoints;
70
+ const stockCreate = (Array.isArray(endpoints) ? endpoints : []).find((endpoint) => endpoint.method === "post" && endpoint.path === "/" && endpoint.custom?.formBuilder !== "vote-submit");
71
+ if (!stockCreate) throw new APIError("form-builder: stock create endpoint not found", 500);
72
+ if (req.body) Object.defineProperty(req, "body", {
73
+ configurable: true,
74
+ value: null
75
+ });
76
+ const response = await stockCreate.handler(req);
77
+ if (response.ok) {
78
+ if (req.context?.["formBuilderEssentialActionUncertain"] === true) return Response.json({ errors: [{ message: asTranslate(req.t)(keys.submissionActionUncertain) }] }, { status: 504 });
79
+ if (req.context?.["formBuilderEssentialActionFailed"] === true) return Response.json({ errors: [{ message: asTranslate(req.t)(keys.submissionActionFailed) }] }, { status: 502 });
80
+ }
81
+ return response;
82
+ }
83
+ req.context[VOTE_CHANGE_CONTEXT_KEY] = target.submissionId;
84
+ const doc = await req.payload.update.bind(req.payload)({
85
+ collection: submissionsSlug,
86
+ id: target.submissionId,
87
+ data: {
88
+ form: data.form,
89
+ values: data.values
90
+ },
91
+ depth: 0,
92
+ overrideAccess: true,
93
+ req
94
+ });
95
+ return Response.json({
96
+ doc,
97
+ message: req.t("general:updatedSuccessfully")
98
+ }, { status: 200 });
99
+ };
100
+ return {
101
+ path: "/",
102
+ method: "post",
103
+ handler,
104
+ custom: { formBuilder: VOTE_SUBMIT_ENDPOINT_TAG }
105
+ };
106
+ };
107
+ //#endregion
108
+ export { buildVoteSubmitEndpoint };
109
+
110
+ //# sourceMappingURL=voteChangeEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voteChangeEndpoint.js","names":[],"sources":["../../src/submissions/voteChangeEndpoint.ts"],"sourcesContent":["import {\n\tAPIError,\n\taddDataAndFileToRequest,\n\taddLocalesToRequestFromData,\n\ttype Endpoint,\n\ttype PayloadRequest,\n} from 'payload'\nimport {\n\tESSENTIAL_ACTION_FAILED_CONTEXT_KEY,\n\tESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY,\n} from '../actions/dispatchContext'\nimport { pollConfigOf } from '../form/pollState'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\nimport { formIdOf } from './formIdOf'\nimport { VOTE_CHANGE_CONTEXT_KEY, votedSubmissionIdFromCookie } from './votedCookie'\n\n/** Marks the vote-submit endpoint in the sanitized endpoint list (`custom.formBuilder`). */\nexport const VOTE_SUBMIT_ENDPOINT_TAG = 'vote-submit'\n\nconst isComplete = (doc: { status?: unknown }): boolean =>\n\tdoc.status == null || doc.status === 'complete'\n\n/**\n * The submission a cookie-identified re-vote should update, or null when the request must fall\n * through to a plain create. Guards run cheapest-first: no valid signed cookie for the posted form\n * means no form fetch at all, so the delegation overhead on ordinary submissions is one header\n * parse. A token is honored only when the form is an `allowChange` poll and it names a still\n * existing, complete submission of that same form; anything else (pruned row, cross-form replay,\n * legacy `1` marker, tampering) makes the caller a new voter rather than an error.\n */\nexport const resolveVoteChangeTarget = async (args: {\n\treq: PayloadRequest\n\tformId: number | string | undefined | null\n}): Promise<{ submissionId: number | string } | null> => {\n\tconst { req, formId } = args\n\tif (formId == null) {\n\t\treturn null\n\t}\n\tconst submissionId = votedSubmissionIdFromCookie(req.headers?.get('cookie'), formId, req.payload)\n\tif (submissionId == null) {\n\t\treturn null\n\t}\n\tconst slugs = pluginSlugsOf(req.payload)\n\tconst form = await req.payload\n\t\t.findByID({ collection: slugs.forms, id: formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (form?.pollEnabled !== true || pollConfigOf(form.poll)?.allowChange !== true) {\n\t\treturn null\n\t}\n\tconst submission = await req.payload\n\t\t.findByID({\n\t\t\tcollection: slugs.formSubmissions,\n\t\t\tid: submissionId,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\t.catch(() => null)\n\tif (submission == null) {\n\t\treturn null\n\t}\n\tconst stored = submission as { form?: unknown; status?: unknown }\n\tif (String(formIdOf(stored.form) ?? '') !== String(formId) || !isComplete(stored)) {\n\t\treturn null\n\t}\n\treturn { submissionId: submission.id as number | string }\n}\n\n/**\n * Custom root `POST` endpoint on the submissions collection (`/form-submissions` by default).\n * Payload matches a collection's custom endpoints ahead of its built-in REST routes, so this handler sees every REST create first: when the posted\n * form is an `allowChange` poll and the voted cookie identifies the caller's submission, it turns\n * the request into an in-place update (create-grade hooks opt in via the context flag); otherwise\n * it delegates to the stock create handler found in the same sanitized endpoint list, keeping the\n * default path semantics Payload's, not a reimplementation. The update runs `overrideAccess`\n * because the collection is deliberately update-closed to every API caller; the signed cookie is\n * the credential here, verified above rather than by collection access.\n */\nexport const buildVoteSubmitEndpoint = (): Endpoint => {\n\tconst handler = async (req: PayloadRequest): Promise<Response> => {\n\t\tawait addDataAndFileToRequest(req)\n\t\taddLocalesToRequestFromData(req)\n\t\tconst data = (req.data ?? {}) as {\n\t\t\tform?: number | string\n\t\t\tvalues?: unknown\n\t\t}\n\t\tconst submissionsSlug = pluginSlugsOf(req.payload).formSubmissions\n\t\tconst target = await resolveVoteChangeTarget({ req, formId: data.form })\n\t\tif (!target) {\n\t\t\tconst endpoints = req.payload.collections[submissionsSlug]?.config.endpoints\n\t\t\tconst registered: Endpoint[] = Array.isArray(endpoints) ? endpoints : []\n\t\t\t// Next root-POST match excluding our own tag (never handler identity: a host-wrapped\n\t\t\t// handler would find itself and recurse). First-match mirrors handleEndpoints routing,\n\t\t\t// so another plugin's interceptor still wins exactly as it would without us.\n\t\t\tconst stockCreate = registered.find(\n\t\t\t\t(endpoint) =>\n\t\t\t\t\tendpoint.method === 'post' &&\n\t\t\t\t\tendpoint.path === '/' &&\n\t\t\t\t\tendpoint.custom?.formBuilder !== VOTE_SUBMIT_ENDPOINT_TAG\n\t\t\t)\n\t\t\tif (!stockCreate) {\n\t\t\t\tthrow new APIError('form-builder: stock create endpoint not found', 500)\n\t\t\t}\n\t\t\t// A consumed fetch body stays non-null, so Payload's addDataAndFileToRequest wrapper\n\t\t\t// would re-read it and 500; req.data/req.file are already populated, so hide the spent\n\t\t\t// stream (defineProperty: `body` is a getter-only prototype accessor).\n\t\t\tif (req.body) {\n\t\t\t\tObject.defineProperty(req, 'body', { configurable: true, value: null })\n\t\t\t}\n\t\t\tconst response = await stockCreate.handler(req)\n\t\t\t// An essential action's failure is the submission's failure: the row is committed and kept\n\t\t\t// (see dispatchActions), but the visitor must not be told it worked. 502 for a definite\n\t\t\t// refusal by the upstream the submission exists for; 504 when it never answered inside the\n\t\t\t// deadline, because \"we are not sure this completed\" is a different fact from \"this\n\t\t\t// failed\" and prompts waiting over retrying.\n\t\t\tif (response.ok) {\n\t\t\t\tif (req.context?.[ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY] === true) {\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ errors: [{ message: asTranslate(req.t)(keys.submissionActionUncertain) }] },\n\t\t\t\t\t\t{ status: 504 }\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (req.context?.[ESSENTIAL_ACTION_FAILED_CONTEXT_KEY] === true) {\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ errors: [{ message: asTranslate(req.t)(keys.submissionActionFailed) }] },\n\t\t\t\t\t\t{ status: 502 }\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn response\n\t\t}\n\t\treq.context[VOTE_CHANGE_CONTEXT_KEY] = target.submissionId\n\t\t// Slug-agnostic cast (the `createSubmission` idiom): a host's generated types pin the\n\t\t// runtime-registered collection's `form` id flavor and `values` JSON shape, which this\n\t\t// framework-level write cannot know. Bound, because `update` is a prototype method.\n\t\tconst update = req.payload.update.bind(req.payload) as unknown as (options: {\n\t\t\tcollection: string\n\t\t\tid: number | string\n\t\t\tdata: { form?: number | string; values?: unknown }\n\t\t\tdepth?: number\n\t\t\toverrideAccess?: boolean\n\t\t\treq?: PayloadRequest\n\t\t}) => Promise<unknown>\n\t\tconst doc = await update({\n\t\t\tcollection: submissionsSlug,\n\t\t\tid: target.submissionId,\n\t\t\tdata: { form: data.form, values: data.values },\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\treturn Response.json({ doc, message: req.t('general:updatedSuccessfully') }, { status: 200 })\n\t}\n\treturn { path: '/', method: 'post', handler, custom: { formBuilder: VOTE_SUBMIT_ENDPOINT_TAG } }\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,2BAA2B;AAExC,MAAM,cAAc,QACnB,IAAI,UAAU,QAAQ,IAAI,WAAW;;;;;;;;;AAUtC,MAAa,0BAA0B,OAAO,SAGW;CACxD,MAAM,EAAE,KAAK,WAAW;CACxB,IAAI,UAAU,MACb,OAAO;CAER,MAAM,eAAe,4BAA4B,IAAI,SAAS,IAAI,QAAQ,GAAG,QAAQ,IAAI,OAAO;CAChG,IAAI,gBAAgB,MACnB,OAAO;CAER,MAAM,QAAQ,cAAc,IAAI,OAAO;CACvC,MAAM,OAAO,MAAM,IAAI,QACrB,SAAS;EAAE,YAAY,MAAM;EAAO,IAAI;EAAQ,OAAO;EAAG,gBAAgB;EAAM;CAAI,CAAC,EACrF,YAAY,IAAI;CAClB,IAAI,MAAM,gBAAgB,QAAQ,aAAa,KAAK,IAAI,GAAG,gBAAgB,MAC1E,OAAO;CAER,MAAM,aAAa,MAAM,IAAI,QAC3B,SAAS;EACT,YAAY,MAAM;EAClB,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC,EACA,YAAY,IAAI;CAClB,IAAI,cAAc,MACjB,OAAO;CAER,MAAM,SAAS;CACf,IAAI,OAAO,SAAS,OAAO,IAAI,KAAK,EAAE,MAAM,OAAO,MAAM,KAAK,CAAC,WAAW,MAAM,GAC/E,OAAO;CAER,OAAO,EAAE,cAAc,WAAW,GAAsB;AACzD;;;;;;;;;;;AAYA,MAAa,gCAA0C;CACtD,MAAM,UAAU,OAAO,QAA2C;EACjE,MAAM,wBAAwB,GAAG;EACjC,4BAA4B,GAAG;EAC/B,MAAM,OAAQ,IAAI,QAAQ,CAAC;EAI3B,MAAM,kBAAkB,cAAc,IAAI,OAAO,EAAE;EACnD,MAAM,SAAS,MAAM,wBAAwB;GAAE;GAAK,QAAQ,KAAK;EAAK,CAAC;EACvE,IAAI,CAAC,QAAQ;GACZ,MAAM,YAAY,IAAI,QAAQ,YAAY,kBAAkB,OAAO;GAKnE,MAAM,eAJyB,MAAM,QAAQ,SAAS,IAAI,YAAY,CAAC,GAIxC,MAC7B,aACA,SAAS,WAAW,UACpB,SAAS,SAAS,OAClB,SAAS,QAAQ,gBAAA,aACnB;GACA,IAAI,CAAC,aACJ,MAAM,IAAI,SAAS,iDAAiD,GAAG;GAKxE,IAAI,IAAI,MACP,OAAO,eAAe,KAAK,QAAQ;IAAE,cAAc;IAAM,OAAO;GAAK,CAAC;GAEvE,MAAM,WAAW,MAAM,YAAY,QAAQ,GAAG;GAM9C,IAAI,SAAS,IAAI;IAChB,IAAI,IAAI,UAAA,2CAAsD,MAC7D,OAAO,SAAS,KACf,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,IAAI,CAAC,EAAE,KAAK,yBAAyB,EAAE,CAAC,EAAE,GAC5E,EAAE,QAAQ,IAAI,CACf;IAED,IAAI,IAAI,UAAA,wCAAmD,MAC1D,OAAO,SAAS,KACf,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,IAAI,CAAC,EAAE,KAAK,sBAAsB,EAAE,CAAC,EAAE,GACzE,EAAE,QAAQ,IAAI,CACf;GAEF;GACA,OAAO;EACR;EACA,IAAI,QAAQ,2BAA2B,OAAO;EAY9C,MAAM,MAAM,MARG,IAAI,QAAQ,OAAO,KAAK,IAAI,OAQpB,EAAE;GACxB,YAAY;GACZ,IAAI,OAAO;GACX,MAAM;IAAE,MAAM,KAAK;IAAM,QAAQ,KAAK;GAAO;GAC7C,OAAO;GACP,gBAAgB;GAChB;EACD,CAAC;EACD,OAAO,SAAS,KAAK;GAAE;GAAK,SAAS,IAAI,EAAE,6BAA6B;EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;CAC7F;CACA,OAAO;EAAE,MAAM;EAAK,QAAQ;EAAQ;EAAS,QAAQ,EAAE,aAAa,yBAAyB;CAAE;AAChG"}
@@ -1,13 +1,19 @@
1
+ import { Payload } from "payload";
2
+
1
3
  //#region src/submissions/votedCookie.d.ts
2
- /** Name of the httpOnly voted cookie for a form: `fb-voted-{formId}`. */
3
- declare const votedCookieName: (formId: number | string) => string;
4
+ /**
5
+ * Name of the httpOnly voted cookie for a form: `fb-voted-{formId}` by default. Pass `payload`
6
+ * when the plugin's `poll.cookiePrefix` is set, so the configured prefix is applied.
7
+ */
8
+ declare const votedCookieName: (formId: number | string, payload?: Payload) => string;
4
9
  /**
5
10
  * Whether a request's `Cookie` header carries the voted marker for a form. For SSR hosts: read
6
11
  * the header (e.g. Next's `(await headers()).get('cookie')`) and pass the result to `<Poll hasVoted>`.
7
12
  * The cookie is httpOnly (set server-side when the plugin's `poll.votedCookie` option is on), so
8
- * this server read is the only way to consume it.
13
+ * this server read is the only way to consume it. Pass `payload` when `poll.cookiePrefix` is set;
14
+ * without it the default `fb-voted-` name is read.
9
15
  */
10
- declare const hasVotedCookie: (cookieHeader: string | null | undefined, formId: number | string) => boolean;
16
+ declare const hasVotedCookie: (cookieHeader: string | null | undefined, formId: number | string, payload?: Payload) => boolean;
11
17
  //#endregion
12
18
  export { hasVotedCookie, votedCookieName };
13
19
  //# sourceMappingURL=votedCookie.d.ts.map
@@ -1,27 +1,65 @@
1
+ import { DEFAULT_VOTED_COOKIE_PREFIX, pluginSlugsOf, votedCookiePrefixOf } from "../plugin/collectionSlugs.js";
2
+ import { signFormContext, verifyFormContext } from "../context/formContext.js";
3
+ import "./voteChange.js";
1
4
  //#region src/submissions/votedCookie.ts
2
5
  /**
3
- * `req.context` key under which `validateSubmission` stashes whether the loaded form is poll-enabled
4
- * (its top-level `pollEnabled` flag) so the voted-cookie `afterChange` hook can skip a second form
6
+ * `req.context` key under which `validateSubmission` stashes the loaded form's poll state
7
+ * (`{ pollEnabled, allowChange }`) so the voted-cookie `afterChange` hook can skip a second form
5
8
  * fetch on the same request.
6
9
  */
7
10
  const POLL_CONTEXT_KEY = "formBuilderPollConfig";
8
- /** Name of the httpOnly voted cookie for a form: `fb-voted-{formId}`. */
9
- const votedCookieName = (formId) => `fb-voted-${formId}`;
11
+ /** One year, matching the voted cookie's `Max-Age` so the token never outlives the cookie by less. */
12
+ const VOTED_COOKIE_MAX_AGE_SECONDS = 31536e3;
13
+ /**
14
+ * Name of the httpOnly voted cookie for a form: `fb-voted-{formId}` by default. Pass `payload`
15
+ * when the plugin's `poll.cookiePrefix` is set, so the configured prefix is applied.
16
+ */
17
+ const votedCookieName = (formId, payload) => `${payload ? votedCookiePrefixOf(payload) : DEFAULT_VOTED_COOKIE_PREFIX}${formId}`;
10
18
  /**
11
19
  * Whether a request's `Cookie` header carries the voted marker for a form. For SSR hosts: read
12
20
  * the header (e.g. Next's `(await headers()).get('cookie')`) and pass the result to `<Poll hasVoted>`.
13
21
  * The cookie is httpOnly (set server-side when the plugin's `poll.votedCookie` option is on), so
14
- * this server read is the only way to consume it.
22
+ * this server read is the only way to consume it. Pass `payload` when `poll.cookiePrefix` is set;
23
+ * without it the default `fb-voted-` name is read.
15
24
  */
16
- const hasVotedCookie = (cookieHeader, formId) => {
25
+ const hasVotedCookie = (cookieHeader, formId, payload) => {
17
26
  if (!cookieHeader) return false;
18
- const name = votedCookieName(formId);
19
- return cookieHeader.split(";").some((pair) => {
27
+ return votedCookieValue(cookieHeader, votedCookieName(formId, payload)) != null;
28
+ };
29
+ const votedCookieValue = (cookieHeader, name) => {
30
+ if (!cookieHeader) return null;
31
+ for (const pair of cookieHeader.split(";")) {
20
32
  const eq = pair.indexOf("=");
21
- return eq !== -1 && pair.slice(0, eq).trim() === name;
22
- });
33
+ if (eq !== -1 && pair.slice(0, eq).trim() === name) return pair.slice(eq + 1).trim();
34
+ }
35
+ return null;
36
+ };
37
+ /**
38
+ * Sign a submission id into the voted cookie's value for an `allowChange` poll. The token (same
39
+ * HMAC format as `signFormContext`) is what lets a repeat submit update that submission in place;
40
+ * signing means only ids the server issued are accepted, so a forged cookie cannot point a
41
+ * re-vote at someone else's submission.
42
+ */
43
+ const signVotedCookieValue = (payload, submissionId) => signFormContext({
44
+ payload,
45
+ relationTo: pluginSlugsOf(payload).formSubmissions,
46
+ value: submissionId,
47
+ expiresIn: VOTED_COOKIE_MAX_AGE_SECONDS
48
+ });
49
+ /**
50
+ * The submission id carried by a form's voted cookie, or null when the header has no cookie for
51
+ * the form, the value is the legacy boolean marker (`1`), or the token fails verification
52
+ * (tampered, wrong secret, expired, or issued for a different submissions collection). Null means
53
+ * "treat the caller as a new voter".
54
+ */
55
+ const votedSubmissionIdFromCookie = (cookieHeader, formId, payload) => {
56
+ const value = votedCookieValue(cookieHeader, votedCookieName(formId, payload));
57
+ if (value == null || value.length === 0) return null;
58
+ const reference = verifyFormContext(value, payload.secret);
59
+ if (reference == null || reference.relationTo !== pluginSlugsOf(payload).formSubmissions) return null;
60
+ return String(reference.value);
23
61
  };
24
62
  //#endregion
25
- export { POLL_CONTEXT_KEY, hasVotedCookie, votedCookieName };
63
+ export { POLL_CONTEXT_KEY, VOTED_COOKIE_MAX_AGE_SECONDS, hasVotedCookie, signVotedCookieValue, votedCookieName, votedSubmissionIdFromCookie };
26
64
 
27
65
  //# sourceMappingURL=votedCookie.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"votedCookie.js","names":[],"sources":["../../src/submissions/votedCookie.ts"],"sourcesContent":["/**\n * `req.context` key under which `validateSubmission` stashes whether the loaded form is poll-enabled\n * (its top-level `pollEnabled` flag) so the voted-cookie `afterChange` hook can skip a second form\n * fetch on the same request.\n */\nexport const POLL_CONTEXT_KEY = 'formBuilderPollConfig'\n\n/** Name of the httpOnly voted cookie for a form: `fb-voted-{formId}`. */\nexport const votedCookieName = (formId: number | string): string => `fb-voted-${formId}`\n\n/**\n * Whether a request's `Cookie` header carries the voted marker for a form. For SSR hosts: read\n * the header (e.g. Next's `(await headers()).get('cookie')`) and pass the result to `<Poll hasVoted>`.\n * The cookie is httpOnly (set server-side when the plugin's `poll.votedCookie` option is on), so\n * this server read is the only way to consume it.\n */\nexport const hasVotedCookie = (\n\tcookieHeader: string | null | undefined,\n\tformId: number | string\n): boolean => {\n\tif (!cookieHeader) {\n\t\treturn false\n\t}\n\tconst name = votedCookieName(formId)\n\treturn cookieHeader.split(';').some((pair) => {\n\t\tconst eq = pair.indexOf('=')\n\t\treturn eq !== -1 && pair.slice(0, eq).trim() === name\n\t})\n}\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB;;AAGhC,MAAa,mBAAmB,WAAoC,YAAY;;;;;;;AAQhF,MAAa,kBACZ,cACA,WACa;CACb,IAAI,CAAC,cACJ,OAAO;CAER,MAAM,OAAO,gBAAgB,MAAM;CACnC,OAAO,aAAa,MAAM,GAAG,EAAE,MAAM,SAAS;EAC7C,MAAM,KAAK,KAAK,QAAQ,GAAG;EAC3B,OAAO,OAAO,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM;CAClD,CAAC;AACF"}
1
+ {"version":3,"file":"votedCookie.js","names":[],"sources":["../../src/submissions/votedCookie.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { signFormContext, verifyFormContext } from '../context/formContext'\nimport {\n\tDEFAULT_VOTED_COOKIE_PREFIX,\n\tpluginSlugsOf,\n\tvotedCookiePrefixOf,\n} from '../plugin/collectionSlugs'\n\n/**\n * `req.context` key under which `validateSubmission` stashes the loaded form's poll state\n * (`{ pollEnabled, allowChange }`) so the voted-cookie `afterChange` hook can skip a second form\n * fetch on the same request.\n */\nexport const POLL_CONTEXT_KEY = 'formBuilderPollConfig'\n\n/** The poll state `validateSubmission` stashes under {@link POLL_CONTEXT_KEY}. */\nexport type PollContextState = { pollEnabled: boolean; allowChange: boolean }\n\nexport { VOTE_CHANGE_CONTEXT_KEY, voteChangeTargetOf } from './voteChange'\n\n/** One year, matching the voted cookie's `Max-Age` so the token never outlives the cookie by less. */\nexport const VOTED_COOKIE_MAX_AGE_SECONDS = 31_536_000\n\n/**\n * Name of the httpOnly voted cookie for a form: `fb-voted-{formId}` by default. Pass `payload`\n * when the plugin's `poll.cookiePrefix` is set, so the configured prefix is applied.\n */\nexport const votedCookieName = (formId: number | string, payload?: Payload): string =>\n\t`${payload ? votedCookiePrefixOf(payload) : DEFAULT_VOTED_COOKIE_PREFIX}${formId}`\n\n/**\n * Whether a request's `Cookie` header carries the voted marker for a form. For SSR hosts: read\n * the header (e.g. Next's `(await headers()).get('cookie')`) and pass the result to `<Poll hasVoted>`.\n * The cookie is httpOnly (set server-side when the plugin's `poll.votedCookie` option is on), so\n * this server read is the only way to consume it. Pass `payload` when `poll.cookiePrefix` is set;\n * without it the default `fb-voted-` name is read.\n */\nexport const hasVotedCookie = (\n\tcookieHeader: string | null | undefined,\n\tformId: number | string,\n\tpayload?: Payload\n): boolean => {\n\tif (!cookieHeader) {\n\t\treturn false\n\t}\n\treturn votedCookieValue(cookieHeader, votedCookieName(formId, payload)) != null\n}\n\nconst votedCookieValue = (cookieHeader: string | null | undefined, name: string): string | null => {\n\tif (!cookieHeader) {\n\t\treturn null\n\t}\n\tfor (const pair of cookieHeader.split(';')) {\n\t\tconst eq = pair.indexOf('=')\n\t\tif (eq !== -1 && pair.slice(0, eq).trim() === name) {\n\t\t\treturn pair.slice(eq + 1).trim()\n\t\t}\n\t}\n\treturn null\n}\n\n/**\n * Sign a submission id into the voted cookie's value for an `allowChange` poll. The token (same\n * HMAC format as `signFormContext`) is what lets a repeat submit update that submission in place;\n * signing means only ids the server issued are accepted, so a forged cookie cannot point a\n * re-vote at someone else's submission.\n */\nexport const signVotedCookieValue = (payload: Payload, submissionId: number | string): string =>\n\tsignFormContext({\n\t\tpayload,\n\t\trelationTo: pluginSlugsOf(payload).formSubmissions,\n\t\tvalue: submissionId,\n\t\texpiresIn: VOTED_COOKIE_MAX_AGE_SECONDS,\n\t})\n\n/**\n * The submission id carried by a form's voted cookie, or null when the header has no cookie for\n * the form, the value is the legacy boolean marker (`1`), or the token fails verification\n * (tampered, wrong secret, expired, or issued for a different submissions collection). Null means\n * \"treat the caller as a new voter\".\n */\nexport const votedSubmissionIdFromCookie = (\n\tcookieHeader: string | null | undefined,\n\tformId: number | string,\n\tpayload: Payload\n): string | null => {\n\tconst value = votedCookieValue(cookieHeader, votedCookieName(formId, payload))\n\tif (value == null || value.length === 0) {\n\t\treturn null\n\t}\n\tconst reference = verifyFormContext(value, payload.secret)\n\tif (reference == null || reference.relationTo !== pluginSlugsOf(payload).formSubmissions) {\n\t\treturn null\n\t}\n\treturn String(reference.value)\n}\n"],"mappings":";;;;;;;;;AAaA,MAAa,mBAAmB;;AAQhC,MAAa,+BAA+B;;;;;AAM5C,MAAa,mBAAmB,QAAyB,YACxD,GAAG,UAAU,oBAAoB,OAAO,IAAI,8BAA8B;;;;;;;;AAS3E,MAAa,kBACZ,cACA,QACA,YACa;CACb,IAAI,CAAC,cACJ,OAAO;CAER,OAAO,iBAAiB,cAAc,gBAAgB,QAAQ,OAAO,CAAC,KAAK;AAC5E;AAEA,MAAM,oBAAoB,cAAyC,SAAgC;CAClG,IAAI,CAAC,cACJ,OAAO;CAER,KAAK,MAAM,QAAQ,aAAa,MAAM,GAAG,GAAG;EAC3C,MAAM,KAAK,KAAK,QAAQ,GAAG;EAC3B,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,MAC7C,OAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK;CAEjC;CACA,OAAO;AACR;;;;;;;AAQA,MAAa,wBAAwB,SAAkB,iBACtD,gBAAgB;CACf;CACA,YAAY,cAAc,OAAO,EAAE;CACnC,OAAO;CACP,WAAW;AACZ,CAAC;;;;;;;AAQF,MAAa,+BACZ,cACA,QACA,YACmB;CACnB,MAAM,QAAQ,iBAAiB,cAAc,gBAAgB,QAAQ,OAAO,CAAC;CAC7E,IAAI,SAAS,QAAQ,MAAM,WAAW,GACrC,OAAO;CAER,MAAM,YAAY,kBAAkB,OAAO,QAAQ,MAAM;CACzD,IAAI,aAAa,QAAQ,UAAU,eAAe,cAAc,OAAO,EAAE,iBACxE,OAAO;CAER,OAAO,OAAO,UAAU,KAAK;AAC9B"}