@10x-media/form-builder 0.1.0-beta.9 → 4.0.0-alpha.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 (367) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +12 -4
  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/shared.d.ts +21 -0
  147. package/dist/exports/shared.js +18 -0
  148. package/dist/exports/types.d.ts +4 -3
  149. package/dist/fields/buildFieldBlocks.js +2 -1
  150. package/dist/fields/buildFieldBlocks.js.map +1 -1
  151. package/dist/fields/builtin/calculation.d.ts +17 -0
  152. package/dist/fields/builtin/calculation.js +70 -127
  153. package/dist/fields/builtin/calculation.js.map +1 -1
  154. package/dist/fields/builtin/checkbox.js +15 -0
  155. package/dist/fields/builtin/checkbox.js.map +1 -1
  156. package/dist/fields/builtin/consent.js +21 -1
  157. package/dist/fields/builtin/consent.js.map +1 -1
  158. package/dist/fields/builtin/email.js +7 -0
  159. package/dist/fields/builtin/email.js.map +1 -1
  160. package/dist/fields/builtin/index.d.ts +6 -2
  161. package/dist/fields/builtin/index.js +9 -4
  162. package/dist/fields/builtin/index.js.map +1 -1
  163. package/dist/fields/builtin/select.js +20 -1
  164. package/dist/fields/builtin/select.js.map +1 -1
  165. package/dist/fields/builtin/text.js +7 -0
  166. package/dist/fields/builtin/text.js.map +1 -1
  167. package/dist/fields/instanceOptions.js +1 -1
  168. package/dist/fields/instanceOptions.js.map +1 -1
  169. package/dist/fields/sharedConfig.js +15 -11
  170. package/dist/fields/sharedConfig.js.map +1 -1
  171. package/dist/fields/types.d.ts +8 -2
  172. package/dist/form/findFormAtLocale.d.ts +30 -0
  173. package/dist/form/findFormAtLocale.js +88 -0
  174. package/dist/form/findFormAtLocale.js.map +1 -0
  175. package/dist/form/pollState.d.ts +2 -1
  176. package/dist/form/pollState.js.map +1 -1
  177. package/dist/form/toFormDocument.d.ts +18 -6
  178. package/dist/form/toFormDocument.js +3 -1
  179. package/dist/form/toFormDocument.js.map +1 -1
  180. package/dist/form/types.d.ts +9 -1
  181. package/dist/index.d.ts +29 -7
  182. package/dist/index.js +74 -18
  183. package/dist/index.js.map +1 -1
  184. package/dist/options.d.ts +119 -4
  185. package/dist/plugin/collectionSlugs.d.ts +28 -0
  186. package/dist/plugin/collectionSlugs.js +65 -0
  187. package/dist/plugin/collectionSlugs.js.map +1 -0
  188. package/dist/plugin/customState.js +1 -1
  189. package/dist/plugin/customState.js.map +1 -1
  190. package/dist/plugin/registerCollections.js +38 -21
  191. package/dist/plugin/registerCollections.js.map +1 -1
  192. package/dist/poll/closeJob.d.ts +4 -3
  193. package/dist/poll/closeJob.js +13 -10
  194. package/dist/poll/closeJob.js.map +1 -1
  195. package/dist/poll/outcomeBeforeChange.js +2 -2
  196. package/dist/poll/outcomeBeforeChange.js.map +1 -1
  197. package/dist/poll/pollTypeRegistry.js +1 -1
  198. package/dist/poll/resolvePollCloseRequest.js +5 -4
  199. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  200. package/dist/poll/resolvePollOptionsRequest.js +2 -2
  201. package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
  202. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  203. package/dist/poll/resolvePollOutcome.js +20 -6
  204. package/dist/poll/resolvePollOutcome.js.map +1 -1
  205. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  206. package/dist/poll/votes/aggregateFromVotes.js +55 -0
  207. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  208. package/dist/poll/votes/answerValues.js +16 -0
  209. package/dist/poll/votes/answerValues.js.map +1 -0
  210. package/dist/poll/votes/bumpPollVote.js +91 -0
  211. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  212. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  213. package/dist/poll/votes/recountPollVotes.js +63 -0
  214. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  215. package/dist/poll/votes/voteTallyHook.js +76 -0
  216. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  217. package/dist/poll/votes/votesCollection.d.ts +23 -0
  218. package/dist/poll/votes/votesCollection.js +96 -0
  219. package/dist/poll/votes/votesCollection.js.map +1 -0
  220. package/dist/react/Form.d.ts +49 -7
  221. package/dist/react/Form.js +48 -13
  222. package/dist/react/Form.js.map +1 -1
  223. package/dist/react/FormContext.d.ts +8 -1
  224. package/dist/react/FormContext.js.map +1 -1
  225. package/dist/react/FormResults.d.ts +4 -2
  226. package/dist/react/FormResults.js +21 -8
  227. package/dist/react/FormResults.js.map +1 -1
  228. package/dist/react/Poll.d.ts +25 -2
  229. package/dist/react/Poll.js +76 -25
  230. package/dist/react/Poll.js.map +1 -1
  231. package/dist/react/adapters.d.ts +35 -0
  232. package/dist/react/adapters.js +11 -0
  233. package/dist/react/adapters.js.map +1 -0
  234. package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
  235. package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
  236. package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
  237. package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
  238. package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
  239. package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
  240. package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
  241. package/dist/react/captcha/TurnstileCaptcha.js +2 -2
  242. package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
  243. package/dist/react/captcha/useCaptchaScript.js +23 -5
  244. package/dist/react/captcha/useCaptchaScript.js.map +1 -1
  245. package/dist/react/fetchResults.d.ts +6 -3
  246. package/dist/react/fetchResults.js +10 -5
  247. package/dist/react/fetchResults.js.map +1 -1
  248. package/dist/react/primitives/Checkbox.d.ts +4 -2
  249. package/dist/react/primitives/Checkbox.js +3 -2
  250. package/dist/react/primitives/Checkbox.js.map +1 -1
  251. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  252. package/dist/react/primitives/ChoiceGroup.js +33 -0
  253. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  254. package/dist/react/primitives/FieldShell.d.ts +11 -1
  255. package/dist/react/primitives/FieldShell.js +43 -33
  256. package/dist/react/primitives/FieldShell.js.map +1 -1
  257. package/dist/react/primitives/Input.d.ts +3 -1
  258. package/dist/react/primitives/Input.js +2 -1
  259. package/dist/react/primitives/Input.js.map +1 -1
  260. package/dist/react/renderers/calculation.js +6 -1
  261. package/dist/react/renderers/calculation.js.map +1 -1
  262. package/dist/react/renderers/checkbox.js +2 -1
  263. package/dist/react/renderers/checkbox.js.map +1 -1
  264. package/dist/react/renderers/consent.js +8 -3
  265. package/dist/react/renderers/consent.js.map +1 -1
  266. package/dist/react/renderers/email.js +3 -1
  267. package/dist/react/renderers/email.js.map +1 -1
  268. package/dist/react/renderers/repeater.js +5 -0
  269. package/dist/react/renderers/repeater.js.map +1 -1
  270. package/dist/react/renderers/select.js +20 -2
  271. package/dist/react/renderers/select.js.map +1 -1
  272. package/dist/react/renderers/text.js +3 -1
  273. package/dist/react/renderers/text.js.map +1 -1
  274. package/dist/react/state.d.ts +10 -0
  275. package/dist/react/state.js +45 -1
  276. package/dist/react/state.js.map +1 -1
  277. package/dist/react/submitForm.d.ts +20 -3
  278. package/dist/react/submitForm.js +8 -4
  279. package/dist/react/submitForm.js.map +1 -1
  280. package/dist/react/useCalcValues.d.ts +10 -0
  281. package/dist/react/useCalcValues.js +13 -0
  282. package/dist/react/useCalcValues.js.map +1 -0
  283. package/dist/react/useField.js +2 -1
  284. package/dist/react/useField.js.map +1 -1
  285. package/dist/recall/resolver.js +1 -1
  286. package/dist/recall/resolver.js.map +1 -1
  287. package/dist/spam/constants.js +7 -1
  288. package/dist/spam/constants.js.map +1 -1
  289. package/dist/spam/spamGuard.js +2 -1
  290. package/dist/spam/spamGuard.js.map +1 -1
  291. package/dist/submissions/SubmissionAnswersClient.js +14 -14
  292. package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
  293. package/dist/submissions/createSubmission.d.ts +7 -1
  294. package/dist/submissions/createSubmission.js +10 -5
  295. package/dist/submissions/createSubmission.js.map +1 -1
  296. package/dist/submissions/formIdOf.js +13 -0
  297. package/dist/submissions/formIdOf.js.map +1 -0
  298. package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
  299. package/dist/submissions/resolveVotedSubmission.js +51 -0
  300. package/dist/submissions/resolveVotedSubmission.js.map +1 -0
  301. package/dist/submissions/runSubmission.js +6 -5
  302. package/dist/submissions/runSubmission.js.map +1 -1
  303. package/dist/submissions/submissionLocale.js +39 -0
  304. package/dist/submissions/submissionLocale.js.map +1 -0
  305. package/dist/submissions/validateSubmission.js +125 -79
  306. package/dist/submissions/validateSubmission.js.map +1 -1
  307. package/dist/submissions/verifyContext.js +35 -0
  308. package/dist/submissions/verifyContext.js.map +1 -0
  309. package/dist/submissions/voteChange.js +21 -0
  310. package/dist/submissions/voteChange.js.map +1 -0
  311. package/dist/submissions/voteChangeEndpoint.js +110 -0
  312. package/dist/submissions/voteChangeEndpoint.js.map +1 -0
  313. package/dist/submissions/votedCookie.d.ts +10 -4
  314. package/dist/submissions/votedCookie.js +49 -11
  315. package/dist/submissions/votedCookie.js.map +1 -1
  316. package/dist/translations/ar.d.ts +7 -0
  317. package/dist/translations/ar.js +379 -0
  318. package/dist/translations/ar.js.map +1 -0
  319. package/dist/translations/clientRuntimeKeys.d.ts +17 -0
  320. package/dist/translations/clientRuntimeKeys.js +48 -0
  321. package/dist/translations/clientRuntimeKeys.js.map +1 -0
  322. package/dist/translations/de.d.ts +12 -0
  323. package/dist/translations/de.js +78 -3
  324. package/dist/translations/de.js.map +1 -1
  325. package/dist/translations/en.js +78 -3
  326. package/dist/translations/en.js.map +1 -1
  327. package/dist/translations/es.d.ts +7 -0
  328. package/dist/translations/es.js +379 -0
  329. package/dist/translations/es.js.map +1 -0
  330. package/dist/translations/fr.d.ts +7 -0
  331. package/dist/translations/fr.js +379 -0
  332. package/dist/translations/fr.js.map +1 -0
  333. package/dist/translations/id.d.ts +7 -0
  334. package/dist/translations/id.js +379 -0
  335. package/dist/translations/id.js.map +1 -0
  336. package/dist/translations/index.d.ts +23 -6
  337. package/dist/translations/index.js +31 -6
  338. package/dist/translations/index.js.map +1 -1
  339. package/dist/translations/keys.d.ts +76 -1
  340. package/dist/translations/keys.js +76 -1
  341. package/dist/translations/keys.js.map +1 -1
  342. package/dist/translations/ko.d.ts +7 -0
  343. package/dist/translations/ko.js +379 -0
  344. package/dist/translations/ko.js.map +1 -0
  345. package/dist/translations/makeTranslate.d.ts +7 -3
  346. package/dist/translations/makeTranslate.js +12 -3
  347. package/dist/translations/makeTranslate.js.map +1 -1
  348. package/dist/translations/pt.d.ts +7 -0
  349. package/dist/translations/pt.js +379 -0
  350. package/dist/translations/pt.js.map +1 -0
  351. package/dist/translations/ru.d.ts +7 -0
  352. package/dist/translations/ru.js +379 -0
  353. package/dist/translations/ru.js.map +1 -0
  354. package/dist/translations/uk.d.ts +7 -0
  355. package/dist/translations/uk.js +379 -0
  356. package/dist/translations/uk.js.map +1 -0
  357. package/dist/translations/zh.d.ts +7 -0
  358. package/dist/translations/zh.js +379 -0
  359. package/dist/translations/zh.js.map +1 -0
  360. package/dist/validation/builtin/index.js +2 -0
  361. package/dist/validation/builtin/index.js.map +1 -1
  362. package/dist/validation/builtin/integer.js +15 -0
  363. package/dist/validation/builtin/integer.js.map +1 -0
  364. package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
  365. package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
  366. package/package.json +29 -16
  367. package/styles/form-builder.css +84 -0
@@ -1,14 +1,21 @@
1
1
  import { FormProps } from "./Form.js";
2
+ import { FormResultsProps } from "./FormResults.js";
2
3
  import { fetchFormResults } from "./fetchResults.js";
4
+ import { VotedSubmission } from "../submissions/resolveVotedSubmission.js";
5
+ import { ReactNode } from "react";
3
6
 
4
7
  //#region src/react/Poll.d.ts
5
8
  type PollProps = FormProps & {
6
- /** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */resultsField: string; /** localStorage key for the per-browser voted guard. Default `fb-poll-{form.id}`. */
9
+ /** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */resultsField: string;
10
+ /**
11
+ * Key for the per-browser voted guard (localStorage by default; overridable or disabled via
12
+ * `adapters.voteStorage`). Default `fb-poll-{form.id}`.
13
+ */
7
14
  storageKey?: string;
8
15
  /**
9
16
  * Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;
10
17
  * `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`
11
- * option pass `hasVotedCookie(cookieHeader, form.id)` here.
18
+ * option pass `hasVotedCookie(cookieHeader, form.id, payload)` here.
12
19
  */
13
20
  hasVoted?: boolean;
14
21
  /**
@@ -16,6 +23,20 @@ type PollProps = FormProps & {
16
23
  * scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.
17
24
  */
18
25
  fetchResultsImpl?: typeof fetchFormResults;
26
+ /**
27
+ * The voter's server-resolved current vote (`resolveVotedSubmission`, read from the httpOnly voted
28
+ * cookie). Presence implies voted; `pick` marks the voter's option in results and `value` prefills
29
+ * the form when they change their vote. Read at mount: after a client-side change the component
30
+ * tracks the new pick itself.
31
+ */
32
+ currentVote?: Pick<VotedSubmission, 'value' | 'pick'> | null;
33
+ /**
34
+ * Replaces the built-in `<FormResults>` wherever the poll shows results (after voting, when
35
+ * closed, and for a recorded outcome). Receives exactly what `<FormResults>` receives at that
36
+ * site, so the default is `(props) => <FormResults {...props} />`; surrounding chrome (the
37
+ * closed/final notices, the change-vote button) stays the poll's.
38
+ */
39
+ renderResults?: (props: FormResultsProps) => ReactNode;
19
40
  };
20
41
  /**
21
42
  * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows
@@ -36,6 +57,8 @@ declare const Poll: ({
36
57
  fetchResultsImpl,
37
58
  apiRoute,
38
59
  onSuccess,
60
+ currentVote,
61
+ renderResults,
39
62
  ...formProps
40
63
  }: PollProps) => import("react/jsx-runtime").JSX.Element | null;
41
64
  //#endregion
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { keys } from "../translations/keys.js";
3
- import { isPollClosed } from "../form/pollState.js";
3
+ import { isPollClosed, pollConfigOf } from "../form/pollState.js";
4
+ import { answerValues } from "../poll/votes/answerValues.js";
4
5
  import { en } from "../translations/en.js";
5
6
  import { makeTranslate } from "../translations/makeTranslate.js";
6
7
  import { Form } from "./Form.js";
@@ -9,17 +10,28 @@ import { fetchFormResults } from "./fetchResults.js";
9
10
  import { jsx, jsxs } from "react/jsx-runtime";
10
11
  import { useCallback, useEffect, useMemo, useState } from "react";
11
12
  //#region src/react/Poll.tsx
12
- const readVoted = (key) => {
13
- try {
14
- return window.localStorage.getItem(key) != null;
15
- } catch {
16
- return false;
13
+ const localStorageVoteStorage = {
14
+ read: (key) => {
15
+ try {
16
+ return window.localStorage.getItem(key) != null;
17
+ } catch {
18
+ return false;
19
+ }
20
+ },
21
+ write: (key) => {
22
+ try {
23
+ window.localStorage.setItem(key, "1");
24
+ } catch {}
17
25
  }
18
26
  };
19
- const writeVoted = (key) => {
20
- try {
21
- window.localStorage.setItem(key, "1");
22
- } catch {}
27
+ /** `false` disables client persistence entirely (`hasVoted` still marks voted). */
28
+ const noopVoteStorage = {
29
+ read: () => false,
30
+ write: () => {}
31
+ };
32
+ const resolveVoteStorage = (configured) => {
33
+ if (configured === false) return noopVoteStorage;
34
+ return configured ?? localStorageVoteStorage;
23
35
  };
24
36
  /**
25
37
  * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows
@@ -33,22 +45,33 @@ const writeVoted = (key) => {
33
45
  * integrity (bypassable): server-enforced
34
46
  * one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.
35
47
  */
36
- const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchFormResults, apiRoute, onSuccess, ...formProps }) => {
48
+ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchFormResults, apiRoute, onSuccess, currentVote, renderResults, ...formProps }) => {
49
+ const renderResultsView = renderResults ?? ((props) => /* @__PURE__ */ jsx(FormResults, { ...props }));
37
50
  const key = storageKey ?? `fb-poll-${formProps.form.id}`;
38
51
  const poll = formProps.form.poll;
39
52
  const closed = isPollClosed(poll);
53
+ const allowChange = pollConfigOf(poll)?.allowChange === true;
40
54
  const winningValues = poll?.outcome?.winningValues;
41
55
  const finalized = Array.isArray(winningValues) && winningValues.length > 0;
42
56
  const resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === "afterClose";
43
- const [voted, setVoted] = useState(false);
57
+ const [voted, setVoted] = useState(hasVoted === true || currentVote != null);
58
+ const [changing, setChanging] = useState(false);
59
+ const [pick, setPick] = useState(currentVote?.pick);
60
+ const [prefill, setPrefill] = useState(currentVote?.value);
61
+ const [changeReady, setChangeReady] = useState(currentVote != null);
44
62
  const [results, setResults] = useState(null);
45
63
  const [loadFailed, setLoadFailed] = useState(false);
46
64
  const translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t]);
65
+ const configuredVoteStorage = formProps.adapters?.voteStorage;
66
+ const voteStorage = useMemo(() => resolveVoteStorage(configuredVoteStorage), [configuredVoteStorage]);
67
+ const formsCollection = formProps.collections?.forms;
47
68
  const loadResults = useCallback(async () => {
48
69
  const result = await fetchResultsImpl({
49
70
  formId: formProps.form.id,
50
71
  field: resultsField,
51
- apiRoute
72
+ apiRoute,
73
+ ...formsCollection ? { collection: formsCollection } : {},
74
+ locale: formProps.submissionLocale
52
75
  });
53
76
  if (result.ok) {
54
77
  setResults(result.results);
@@ -58,7 +81,9 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
58
81
  fetchResultsImpl,
59
82
  formProps.form.id,
60
83
  resultsField,
61
- apiRoute
84
+ apiRoute,
85
+ formsCollection,
86
+ formProps.submissionLocale
62
87
  ]);
63
88
  const resultsError = /* @__PURE__ */ jsx("p", {
64
89
  className: "fb-poll__error",
@@ -66,36 +91,47 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
66
91
  children: translate(keys.pollResultsError)
67
92
  });
68
93
  useEffect(() => {
69
- const already = hasVoted === true || readVoted(key);
94
+ const already = hasVoted === true || currentVote != null || voteStorage.read(key);
70
95
  if (already) setVoted(true);
71
96
  if (already && !resultsAwaitClose || closed || finalized) loadResults();
72
97
  }, [
73
98
  hasVoted,
99
+ currentVote,
74
100
  key,
75
101
  loadResults,
76
102
  closed,
77
103
  resultsAwaitClose,
78
- finalized
104
+ finalized,
105
+ voteStorage
79
106
  ]);
80
107
  const handleSuccess = useCallback((submissionId, result) => {
81
- writeVoted(key);
108
+ voteStorage.write(key);
82
109
  setVoted(true);
110
+ setChanging(false);
111
+ setChangeReady(true);
112
+ if (result?.values) {
113
+ setPrefill(result.values.find((row) => row.field === resultsField)?.value);
114
+ setPick(answerValues(result.values, resultsField));
115
+ }
83
116
  if (!resultsAwaitClose) loadResults();
84
117
  onSuccess?.(submissionId, result);
85
118
  }, [
86
119
  key,
87
120
  loadResults,
88
121
  onSuccess,
89
- resultsAwaitClose
122
+ resultsAwaitClose,
123
+ voteStorage,
124
+ resultsField
90
125
  ]);
91
126
  if (finalized) return /* @__PURE__ */ jsxs("div", {
92
127
  className: "fb-poll fb-poll--final",
93
128
  children: [/* @__PURE__ */ jsx("p", {
94
129
  className: "fb-poll__final",
95
130
  children: translate(keys.pollFinalResult)
96
- }), loadFailed ? resultsError : results ? /* @__PURE__ */ jsx(FormResults, {
131
+ }), loadFailed ? resultsError : results ? renderResultsView({
97
132
  results,
98
133
  winningValues,
134
+ currentValues: pick,
99
135
  t: formProps.t,
100
136
  locale: formProps.locale
101
137
  }) : null]
@@ -105,26 +141,41 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
105
141
  children: [/* @__PURE__ */ jsx("p", {
106
142
  className: "fb-poll__closed",
107
143
  children: translate(keys.pollClosed)
108
- }), loadFailed ? resultsError : results ? /* @__PURE__ */ jsx(FormResults, {
144
+ }), loadFailed ? resultsError : results ? renderResultsView({
109
145
  results,
146
+ currentValues: pick,
110
147
  t: formProps.t,
111
148
  locale: formProps.locale
112
149
  }) : null]
113
150
  });
114
- if (voted) {
151
+ if (voted && !changing) {
115
152
  if (resultsAwaitClose) return /* @__PURE__ */ jsx("p", {
116
153
  className: "fb-poll__await-close",
117
154
  children: translate(keys.pollResultsAfterClose)
118
155
  });
119
156
  if (loadFailed) return resultsError;
120
- return results ? /* @__PURE__ */ jsx(FormResults, {
121
- results,
122
- t: formProps.t,
123
- locale: formProps.locale
157
+ return results ? /* @__PURE__ */ jsxs("div", {
158
+ className: "fb-poll fb-poll--voted",
159
+ children: [renderResultsView({
160
+ results,
161
+ currentValues: pick,
162
+ t: formProps.t,
163
+ locale: formProps.locale
164
+ }), allowChange && changeReady ? /* @__PURE__ */ jsx("button", {
165
+ className: "fb-poll__change",
166
+ type: "button",
167
+ onClick: () => setChanging(true),
168
+ children: translate(keys.pollChangeVote)
169
+ }) : null]
124
170
  }) : null;
125
171
  }
172
+ const initialValues = changing && prefill !== void 0 ? {
173
+ ...formProps.initialValues ?? {},
174
+ [resultsField]: prefill
175
+ } : formProps.initialValues;
126
176
  return /* @__PURE__ */ jsx(Form, {
127
177
  ...formProps,
178
+ initialValues,
128
179
  apiRoute,
129
180
  onSuccess: handleSuccess
130
181
  });
@@ -1 +1 @@
1
- {"version":3,"file":"Poll.js","names":[],"sources":["../../src/react/Poll.tsx"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { isPollClosed } from '../form/pollState'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport { Form, type FormProps } from './Form'\nimport { FormResults } from './FormResults'\nimport { type FetchResultsResult, fetchFormResults } from './fetchResults'\n\nexport type PollProps = FormProps & {\n\t/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */\n\tresultsField: string\n\t/** localStorage key for the per-browser voted guard. Default `fb-poll-{form.id}`. */\n\tstorageKey?: string\n\t/**\n\t * Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;\n\t * `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`\n\t * option pass `hasVotedCookie(cookieHeader, form.id)` here.\n\t */\n\thasVoted?: boolean\n\t/**\n\t * Injectable results fetch (testing); defaults to `fetchFormResults`. Pass a stable reference (module\n\t * scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.\n\t */\n\tfetchResultsImpl?: typeof fetchFormResults\n}\n\nconst readVoted = (key: string): boolean => {\n\ttry {\n\t\treturn window.localStorage.getItem(key) != null\n\t} catch {\n\t\treturn false\n\t}\n}\n\nconst writeVoted = (key: string): void => {\n\ttry {\n\t\twindow.localStorage.setItem(key, '1')\n\t} catch {\n\t\t// Private mode / storage disabled: the guard is best-effort UX, never integrity.\n\t}\n}\n\n/**\n * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows\n * `<FormResults>`. Lifecycle comes from `form.poll`: past `closesAt` the poll is closed (a translated\n * notice plus results, which the endpoint serves for any visibility once closed); a voted-but-open\n * `afterClose` poll shows a translated wait notice instead of fetching (the endpoint would refuse). A\n * recorded `outcome.winningValues` (via `resolvePollOutcome`) supersedes everything: a translated final\n * notice plus results with every winning bucket highlighted (a tie highlights more than one). A\n * per-browser localStorage flag (`storageKey`) skips straight to results on revisit; `hasVoted: true`\n * (e.g. from the server-set voted cookie) marks voted regardless of localStorage. The guard is UX, not\n * integrity (bypassable): server-enforced\n * one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.\n */\nexport const Poll = ({\n\tresultsField,\n\tstorageKey,\n\thasVoted,\n\tfetchResultsImpl = fetchFormResults,\n\tapiRoute,\n\tonSuccess,\n\t...formProps\n}: PollProps) => {\n\tconst key = storageKey ?? `fb-poll-${formProps.form.id}`\n\tconst poll = formProps.form.poll\n\tconst closed = isPollClosed(poll)\n\tconst winningValues = poll?.outcome?.winningValues\n\tconst finalized = Array.isArray(winningValues) && winningValues.length > 0\n\tconst resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === 'afterClose'\n\tconst [voted, setVoted] = useState(false)\n\tconst [results, setResults] = useState<FieldAggregation[] | null>(null)\n\tconst [loadFailed, setLoadFailed] = useState(false)\n\tconst translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t])\n\n\tconst loadResults = useCallback(async () => {\n\t\tconst result: FetchResultsResult = await fetchResultsImpl({\n\t\t\tformId: formProps.form.id,\n\t\t\tfield: resultsField,\n\t\t\tapiRoute,\n\t\t})\n\t\t// A failed load surfaces as an error, not an empty result set: `[]` would read as \"no votes yet\".\n\t\tif (result.ok) {\n\t\t\tsetResults(result.results)\n\t\t\tsetLoadFailed(false)\n\t\t} else {\n\t\t\tsetLoadFailed(true)\n\t\t}\n\t}, [fetchResultsImpl, formProps.form.id, resultsField, apiRoute])\n\n\tconst resultsError = (\n\t\t<p className=\"fb-poll__error\" role=\"alert\">\n\t\t\t{translate(keys.pollResultsError)}\n\t\t</p>\n\t)\n\n\tuseEffect(() => {\n\t\tconst already = hasVoted === true || readVoted(key)\n\t\tif (already) {\n\t\t\tsetVoted(true)\n\t\t}\n\t\tif ((already && !resultsAwaitClose) || closed || finalized) {\n\t\t\tvoid loadResults()\n\t\t}\n\t}, [hasVoted, key, loadResults, closed, resultsAwaitClose, finalized])\n\n\tconst handleSuccess = useCallback<NonNullable<FormProps['onSuccess']>>(\n\t\t(submissionId, result) => {\n\t\t\twriteVoted(key)\n\t\t\tsetVoted(true)\n\t\t\tif (!resultsAwaitClose) {\n\t\t\t\tvoid loadResults()\n\t\t\t}\n\t\t\t// Forward the resolved success response so a Poll host gets the same onSuccess payload as a Form host.\n\t\t\tonSuccess?.(submissionId, result)\n\t\t},\n\t\t[key, loadResults, onSuccess, resultsAwaitClose]\n\t)\n\n\tif (finalized) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--final\">\n\t\t\t\t<p className=\"fb-poll__final\">{translate(keys.pollFinalResult)}</p>\n\t\t\t\t{loadFailed ? (\n\t\t\t\t\tresultsError\n\t\t\t\t) : results ? (\n\t\t\t\t\t<FormResults\n\t\t\t\t\t\tresults={results}\n\t\t\t\t\t\twinningValues={winningValues}\n\t\t\t\t\t\tt={formProps.t}\n\t\t\t\t\t\tlocale={formProps.locale}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (closed) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--closed\">\n\t\t\t\t<p className=\"fb-poll__closed\">{translate(keys.pollClosed)}</p>\n\t\t\t\t{loadFailed ? (\n\t\t\t\t\tresultsError\n\t\t\t\t) : results ? (\n\t\t\t\t\t<FormResults results={results} t={formProps.t} locale={formProps.locale} />\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (voted) {\n\t\tif (resultsAwaitClose) {\n\t\t\treturn <p className=\"fb-poll__await-close\">{translate(keys.pollResultsAfterClose)}</p>\n\t\t}\n\t\tif (loadFailed) {\n\t\t\treturn resultsError\n\t\t}\n\t\treturn results ? (\n\t\t\t<FormResults results={results} t={formProps.t} locale={formProps.locale} />\n\t\t) : null\n\t}\n\n\treturn <Form {...formProps} apiRoute={apiRoute} onSuccess={handleSuccess} />\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,aAAa,QAAyB;CAC3C,IAAI;EACH,OAAO,OAAO,aAAa,QAAQ,GAAG,KAAK;CAC5C,QAAQ;EACP,OAAO;CACR;AACD;AAEA,MAAM,cAAc,QAAsB;CACzC,IAAI;EACH,OAAO,aAAa,QAAQ,KAAK,GAAG;CACrC,QAAQ,CAER;AACD;;;;;;;;;;;;;AAcA,MAAa,QAAQ,EACpB,cACA,YACA,UACA,mBAAmB,kBACnB,UACA,WACA,GAAG,gBACa;CAChB,MAAM,MAAM,cAAc,WAAW,UAAU,KAAK;CACpD,MAAM,OAAO,UAAU,KAAK;CAC5B,MAAM,SAAS,aAAa,IAAI;CAChC,MAAM,gBAAgB,MAAM,SAAS;CACrC,MAAM,YAAY,MAAM,QAAQ,aAAa,KAAK,cAAc,SAAS;CACzE,MAAM,oBAAoB,CAAC,UAAU,CAAC,aAAa,MAAM,sBAAsB;CAC/E,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,MAAM,CAAC,SAAS,cAAc,SAAoC,IAAI;CACtE,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,YAAY,cAAc,UAAU,KAAK,cAAc,EAAE,GAAG,CAAC,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IAAI,mBACH,OAAO,oBAAC,KAAD;GAAG,WAAU;aAAwB,UAAU,KAAK,qBAAqB;EAAK,CAAA;EAEtF,IAAI,YACH,OAAO;EAER,OAAO,UACN,oBAAC,aAAD;GAAsB;GAAS,GAAG,UAAU;GAAG,QAAQ,UAAU;EAAS,CAAA,IACvE;CACL;CAEA,OAAO,oBAAC,MAAD;EAAM,GAAI;EAAqB;EAAU,WAAW;CAAgB,CAAA;AAC5E"}
1
+ {"version":3,"file":"Poll.js","names":[],"sources":["../../src/react/Poll.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { answerValues } from '../poll/votes/answerValues'\nimport type { VotedSubmission } from '../submissions/resolveVotedSubmission'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport type { VoteStorage } from './adapters'\nimport { Form, type FormProps } from './Form'\nimport { FormResults, type FormResultsProps } from './FormResults'\nimport { type FetchResultsResult, fetchFormResults } from './fetchResults'\n\nexport type PollProps = FormProps & {\n\t/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */\n\tresultsField: string\n\t/**\n\t * Key for the per-browser voted guard (localStorage by default; overridable or disabled via\n\t * `adapters.voteStorage`). Default `fb-poll-{form.id}`.\n\t */\n\tstorageKey?: string\n\t/**\n\t * Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;\n\t * `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`\n\t * option pass `hasVotedCookie(cookieHeader, form.id, payload)` here.\n\t */\n\thasVoted?: boolean\n\t/**\n\t * Injectable results fetch (testing); defaults to `fetchFormResults`. Pass a stable reference (module\n\t * scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.\n\t */\n\tfetchResultsImpl?: typeof fetchFormResults\n\t/**\n\t * The voter's server-resolved current vote (`resolveVotedSubmission`, read from the httpOnly voted\n\t * cookie). Presence implies voted; `pick` marks the voter's option in results and `value` prefills\n\t * the form when they change their vote. Read at mount: after a client-side change the component\n\t * tracks the new pick itself.\n\t */\n\tcurrentVote?: Pick<VotedSubmission, 'value' | 'pick'> | null\n\t/**\n\t * Replaces the built-in `<FormResults>` wherever the poll shows results (after voting, when\n\t * closed, and for a recorded outcome). Receives exactly what `<FormResults>` receives at that\n\t * site, so the default is `(props) => <FormResults {...props} />`; surrounding chrome (the\n\t * closed/final notices, the change-vote button) stays the poll's.\n\t */\n\trenderResults?: (props: FormResultsProps) => ReactNode\n}\n\nconst localStorageVoteStorage: VoteStorage = {\n\tread: (key) => {\n\t\ttry {\n\t\t\treturn window.localStorage.getItem(key) != null\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t},\n\twrite: (key) => {\n\t\ttry {\n\t\t\twindow.localStorage.setItem(key, '1')\n\t\t} catch {\n\t\t\t// Private mode / storage disabled: the guard is best-effort UX, never integrity.\n\t\t}\n\t},\n}\n\n/** `false` disables client persistence entirely (`hasVoted` still marks voted). */\nconst noopVoteStorage: VoteStorage = { read: () => false, write: () => {} }\n\nconst resolveVoteStorage = (configured: VoteStorage | false | undefined): VoteStorage => {\n\tif (configured === false) {\n\t\treturn noopVoteStorage\n\t}\n\treturn configured ?? localStorageVoteStorage\n}\n\n/**\n * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows\n * `<FormResults>`. Lifecycle comes from `form.poll`: past `closesAt` the poll is closed (a translated\n * notice plus results, which the endpoint serves for any visibility once closed); a voted-but-open\n * `afterClose` poll shows a translated wait notice instead of fetching (the endpoint would refuse). A\n * recorded `outcome.winningValues` (via `resolvePollOutcome`) supersedes everything: a translated final\n * notice plus results with every winning bucket highlighted (a tie highlights more than one). A\n * per-browser localStorage flag (`storageKey`) skips straight to results on revisit; `hasVoted: true`\n * (e.g. from the server-set voted cookie) marks voted regardless of localStorage. The guard is UX, not\n * integrity (bypassable): server-enforced\n * one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.\n */\nexport const Poll = ({\n\tresultsField,\n\tstorageKey,\n\thasVoted,\n\tfetchResultsImpl = fetchFormResults,\n\tapiRoute,\n\tonSuccess,\n\tcurrentVote,\n\trenderResults,\n\t...formProps\n}: PollProps) => {\n\tconst renderResultsView =\n\t\trenderResults ?? ((props: FormResultsProps): ReactNode => <FormResults {...props} />)\n\tconst key = storageKey ?? `fb-poll-${formProps.form.id}`\n\tconst poll = formProps.form.poll\n\tconst closed = isPollClosed(poll)\n\tconst allowChange = pollConfigOf(poll)?.allowChange === true\n\tconst winningValues = poll?.outcome?.winningValues\n\tconst finalized = Array.isArray(winningValues) && winningValues.length > 0\n\tconst resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === 'afterClose'\n\t// Server-known voted state renders the results view on the very first paint; the effect below\n\t// only adds the localStorage read.\n\tconst [voted, setVoted] = useState(hasVoted === true || currentVote != null)\n\tconst [changing, setChanging] = useState(false)\n\tconst [pick, setPick] = useState<string[] | undefined>(currentVote?.pick)\n\tconst [prefill, setPrefill] = useState<unknown>(currentVote?.value)\n\t// Changing is offered only when the signed cookie verifiably identifies a submission: at mount\n\t// via a resolved `currentVote`, or after an in-session vote (the server just issued the cookie).\n\t// A localStorage-only voted flag proves nothing about the cookie, and a \"change\" without one\n\t// would create a second submission instead of updating.\n\tconst [changeReady, setChangeReady] = useState(currentVote != null)\n\tconst [results, setResults] = useState<FieldAggregation[] | null>(null)\n\tconst [loadFailed, setLoadFailed] = useState(false)\n\tconst translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t])\n\tconst configuredVoteStorage = formProps.adapters?.voteStorage\n\tconst voteStorage = useMemo(\n\t\t() => resolveVoteStorage(configuredVoteStorage),\n\t\t[configuredVoteStorage]\n\t)\n\n\tconst formsCollection = formProps.collections?.forms\n\tconst loadResults = useCallback(async () => {\n\t\tconst result: FetchResultsResult = await fetchResultsImpl({\n\t\t\tformId: formProps.form.id,\n\t\t\tfield: resultsField,\n\t\t\tapiRoute,\n\t\t\t...(formsCollection ? { collection: formsCollection } : {}),\n\t\t\tlocale: formProps.submissionLocale,\n\t\t})\n\t\t// A failed load surfaces as an error, not an empty result set: `[]` would read as \"no votes yet\".\n\t\tif (result.ok) {\n\t\t\tsetResults(result.results)\n\t\t\tsetLoadFailed(false)\n\t\t} else {\n\t\t\tsetLoadFailed(true)\n\t\t}\n\t}, [\n\t\tfetchResultsImpl,\n\t\tformProps.form.id,\n\t\tresultsField,\n\t\tapiRoute,\n\t\tformsCollection,\n\t\tformProps.submissionLocale,\n\t])\n\n\tconst resultsError = (\n\t\t<p className=\"fb-poll__error\" role=\"alert\">\n\t\t\t{translate(keys.pollResultsError)}\n\t\t</p>\n\t)\n\n\tuseEffect(() => {\n\t\tconst already = hasVoted === true || currentVote != null || voteStorage.read(key)\n\t\tif (already) {\n\t\t\tsetVoted(true)\n\t\t}\n\t\tif ((already && !resultsAwaitClose) || closed || finalized) {\n\t\t\tvoid loadResults()\n\t\t}\n\t}, [hasVoted, currentVote, key, loadResults, closed, resultsAwaitClose, finalized, voteStorage])\n\n\tconst handleSuccess = useCallback<NonNullable<FormProps['onSuccess']>>(\n\t\t(submissionId, result) => {\n\t\t\tvoteStorage.write(key)\n\t\t\tsetVoted(true)\n\t\t\tsetChanging(false)\n\t\t\tsetChangeReady(true)\n\t\t\t// Track the pick client-side so the \"your vote\" marker is fresh right after a (re-)vote,\n\t\t\t// without waiting for a server-resolved currentVote on the next page load.\n\t\t\tif (result?.values) {\n\t\t\t\tconst entry = result.values.find((row) => row.field === resultsField)\n\t\t\t\tsetPrefill(entry?.value)\n\t\t\t\tsetPick(answerValues(result.values, resultsField))\n\t\t\t}\n\t\t\tif (!resultsAwaitClose) {\n\t\t\t\tvoid loadResults()\n\t\t\t}\n\t\t\t// Forward the resolved success response so a Poll host gets the same onSuccess payload as a Form host.\n\t\t\tonSuccess?.(submissionId, result)\n\t\t},\n\t\t[key, loadResults, onSuccess, resultsAwaitClose, voteStorage, resultsField]\n\t)\n\n\tif (finalized) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--final\">\n\t\t\t\t<p className=\"fb-poll__final\">{translate(keys.pollFinalResult)}</p>\n\t\t\t\t{loadFailed\n\t\t\t\t\t? resultsError\n\t\t\t\t\t: results\n\t\t\t\t\t\t? renderResultsView({\n\t\t\t\t\t\t\t\tresults,\n\t\t\t\t\t\t\t\twinningValues,\n\t\t\t\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\t\t\t\tt: formProps.t,\n\t\t\t\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (closed) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--closed\">\n\t\t\t\t<p className=\"fb-poll__closed\">{translate(keys.pollClosed)}</p>\n\t\t\t\t{loadFailed\n\t\t\t\t\t? resultsError\n\t\t\t\t\t: results\n\t\t\t\t\t\t? renderResultsView({\n\t\t\t\t\t\t\t\tresults,\n\t\t\t\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\t\t\t\tt: formProps.t,\n\t\t\t\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (voted && !changing) {\n\t\tif (resultsAwaitClose) {\n\t\t\treturn <p className=\"fb-poll__await-close\">{translate(keys.pollResultsAfterClose)}</p>\n\t\t}\n\t\tif (loadFailed) {\n\t\t\treturn resultsError\n\t\t}\n\t\treturn results ? (\n\t\t\t<div className=\"fb-poll fb-poll--voted\">\n\t\t\t\t{renderResultsView({\n\t\t\t\t\tresults,\n\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\tt: formProps.t,\n\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t})}\n\t\t\t\t{allowChange && changeReady ? (\n\t\t\t\t\t<button className=\"fb-poll__change\" type=\"button\" onClick={() => setChanging(true)}>\n\t\t\t\t\t\t{translate(keys.pollChangeVote)}\n\t\t\t\t\t</button>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t) : null\n\t}\n\n\t// While changing, the current pick prefills the results field; the server identifies the\n\t// submission to update from the httpOnly voted cookie, so the client sends a normal submit.\n\tconst initialValues =\n\t\tchanging && prefill !== undefined\n\t\t\t? { ...(formProps.initialValues ?? {}), [resultsField]: prefill }\n\t\t\t: formProps.initialValues\n\treturn (\n\t\t<Form\n\t\t\t{...formProps}\n\t\t\tinitialValues={initialValues}\n\t\t\tapiRoute={apiRoute}\n\t\t\tonSuccess={handleSuccess}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;AAmDA,MAAM,0BAAuC;CAC5C,OAAO,QAAQ;EACd,IAAI;GACH,OAAO,OAAO,aAAa,QAAQ,GAAG,KAAK;EAC5C,QAAQ;GACP,OAAO;EACR;CACD;CACA,QAAQ,QAAQ;EACf,IAAI;GACH,OAAO,aAAa,QAAQ,KAAK,GAAG;EACrC,QAAQ,CAER;CACD;AACD;;AAGA,MAAM,kBAA+B;CAAE,YAAY;CAAO,aAAa,CAAC;AAAE;AAE1E,MAAM,sBAAsB,eAA6D;CACxF,IAAI,eAAe,OAClB,OAAO;CAER,OAAO,cAAc;AACtB;;;;;;;;;;;;;AAcA,MAAa,QAAQ,EACpB,cACA,YACA,UACA,mBAAmB,kBACnB,UACA,WACA,aACA,eACA,GAAG,gBACa;CAChB,MAAM,oBACL,mBAAmB,UAAuC,oBAAC,aAAD,EAAa,GAAI,MAAQ,CAAA;CACpF,MAAM,MAAM,cAAc,WAAW,UAAU,KAAK;CACpD,MAAM,OAAO,UAAU,KAAK;CAC5B,MAAM,SAAS,aAAa,IAAI;CAChC,MAAM,cAAc,aAAa,IAAI,GAAG,gBAAgB;CACxD,MAAM,gBAAgB,MAAM,SAAS;CACrC,MAAM,YAAY,MAAM,QAAQ,aAAa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AK;IAAS,eAAe,YAAY,IAAI;cAC/E,UAAU,KAAK,cAAc;GACvB,CAAA,IACL,IACA;OACF;CACL;CAIA,MAAM,gBACL,YAAY,YAAY,KAAA,IACrB;EAAE,GAAI,UAAU,iBAAiB,CAAC;GAAK,eAAe;CAAQ,IAC9D,UAAU;CACd,OACC,oBAAC,MAAD;EACC,GAAI;EACW;EACL;EACV,WAAW;CACX,CAAA;AAEH"}
@@ -0,0 +1,35 @@
1
+ //#region src/react/adapters.d.ts
2
+ /** The plugin's navigation intent for a post-submit redirect, passed through to the adapter. */
3
+ type NavigateOptions = {
4
+ replace: boolean;
5
+ };
6
+ /**
7
+ * Client persistence for a poll's per-browser voted flag. `read` reports whether the flag is set;
8
+ * `write` sets it after a successful vote.
9
+ */
10
+ type VoteStorage = {
11
+ read: (key: string) => boolean;
12
+ write: (key: string) => void;
13
+ };
14
+ /** Loads a third-party script and resolves once it is executable (e.g. a consent-gated loader). */
15
+ type LoadScript = (src: string) => Promise<void>;
16
+ /**
17
+ * Host-owned effects. Every member is optional and defaults to the current DOM behavior, so
18
+ * omitting the prop entirely preserves the default semantics exactly.
19
+ *
20
+ * - `navigate`: replaces `window.location.assign`/`.replace` for the post-submit redirect. When
21
+ * set, the plugin never touches `window.location` for that form; a throwing adapter propagates
22
+ * and never falls back to a hard navigation. Not awaited.
23
+ * - `voteStorage`: replaces the `<Poll>` localStorage voted-flag read/write; `false` disables
24
+ * client persistence entirely (e.g. when the server-side `poll.votedCookie` is the source of truth).
25
+ * - `loadScript`: replaces the captcha widgets' `document.head` script injection (consent
26
+ * managers, CSP nonces). The per-src cache and evict-on-failure retry still apply.
27
+ */
28
+ type FormAdapters = {
29
+ navigate?: (url: string, options: NavigateOptions) => void;
30
+ voteStorage?: VoteStorage | false;
31
+ loadScript?: LoadScript;
32
+ };
33
+ //#endregion
34
+ export { FormAdapters, LoadScript, NavigateOptions, VoteStorage };
35
+ //# sourceMappingURL=adapters.d.ts.map
@@ -0,0 +1,11 @@
1
+ //#region src/react/adapters.ts
2
+ /** The default navigation: a full document load, push semantics unless `replace` is requested. */
3
+ const defaultNavigate = (url, options) => {
4
+ if (typeof window === "undefined") return;
5
+ if (options.replace) window.location.replace(url);
6
+ else window.location.assign(url);
7
+ };
8
+ //#endregion
9
+ export { defaultNavigate };
10
+
11
+ //# sourceMappingURL=adapters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters.js","names":[],"sources":["../../src/react/adapters.ts"],"sourcesContent":["/** The plugin's navigation intent for a post-submit redirect, passed through to the adapter. */\nexport type NavigateOptions = { replace: boolean }\n\n/**\n * Client persistence for a poll's per-browser voted flag. `read` reports whether the flag is set;\n * `write` sets it after a successful vote.\n */\nexport type VoteStorage = {\n\tread: (key: string) => boolean\n\twrite: (key: string) => void\n}\n\n/** Loads a third-party script and resolves once it is executable (e.g. a consent-gated loader). */\nexport type LoadScript = (src: string) => Promise<void>\n\n/**\n * Host-owned effects. Every member is optional and defaults to the current DOM behavior, so\n * omitting the prop entirely preserves the default semantics exactly.\n *\n * - `navigate`: replaces `window.location.assign`/`.replace` for the post-submit redirect. When\n * set, the plugin never touches `window.location` for that form; a throwing adapter propagates\n * and never falls back to a hard navigation. Not awaited.\n * - `voteStorage`: replaces the `<Poll>` localStorage voted-flag read/write; `false` disables\n * client persistence entirely (e.g. when the server-side `poll.votedCookie` is the source of truth).\n * - `loadScript`: replaces the captcha widgets' `document.head` script injection (consent\n * managers, CSP nonces). The per-src cache and evict-on-failure retry still apply.\n */\nexport type FormAdapters = {\n\tnavigate?: (url: string, options: NavigateOptions) => void\n\tvoteStorage?: VoteStorage | false\n\tloadScript?: LoadScript\n}\n\n/** The default navigation: a full document load, push semantics unless `replace` is requested. */\nexport const defaultNavigate = (url: string, options: NavigateOptions): void => {\n\tif (typeof window === 'undefined') {\n\t\treturn\n\t}\n\tif (options.replace) {\n\t\twindow.location.replace(url)\n\t} else {\n\t\twindow.location.assign(url)\n\t}\n}\n"],"mappings":";;AAkCA,MAAa,mBAAmB,KAAa,YAAmC;CAC/E,IAAI,OAAO,WAAW,aACrB;CAED,IAAI,QAAQ,SACX,OAAO,SAAS,QAAQ,GAAG;MAE3B,OAAO,SAAS,OAAO,GAAG;AAE5B"}
@@ -1,3 +1,4 @@
1
+ import { FormAdapters } from "../adapters.js";
1
2
  import { CaptchaWidgetHandle } from "./types.js";
2
3
  import { Ref } from "react";
3
4
 
@@ -8,7 +9,8 @@ type HcaptchaCaptchaProps = {
8
9
  onToken: (token: string | null) => void; /** Extra vendor render params (theme, size, ...). */
9
10
  options?: Record<string, unknown>;
10
11
  className?: string; /** Override the vendor script URL. */
11
- scriptSrc?: string;
12
+ scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
13
+ adapters?: Pick<FormAdapters, 'loadScript'>;
12
14
  ref?: Ref<CaptchaWidgetHandle>;
13
15
  };
14
16
  /**
@@ -21,6 +23,7 @@ declare const HcaptchaCaptcha: ({
21
23
  options,
22
24
  className,
23
25
  scriptSrc,
26
+ adapters,
24
27
  ref
25
28
  }: HcaptchaCaptchaProps) => import("react/jsx-runtime").JSX.Element;
26
29
  //#endregion
@@ -9,14 +9,14 @@ const HCAPTCHA_SCRIPT_URL = "https://js.hcaptcha.com/1/api.js?render=explicit";
9
9
  * Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,
10
10
  * and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.
11
11
  */
12
- const HcaptchaCaptcha = ({ siteKey, onToken, options, className, scriptSrc = HCAPTCHA_SCRIPT_URL, ref }) => {
12
+ const HcaptchaCaptcha = ({ siteKey, onToken, options, className, scriptSrc = HCAPTCHA_SCRIPT_URL, adapters, ref }) => {
13
13
  const containerRef = useRef(null);
14
14
  const widgetIdRef = useRef(null);
15
15
  const onTokenRef = useRef(onToken);
16
16
  onTokenRef.current = onToken;
17
17
  const optionsRef = useRef(options);
18
18
  optionsRef.current = options;
19
- const ready = useCaptchaScript(scriptSrc);
19
+ const ready = useCaptchaScript(scriptSrc, adapters?.loadScript);
20
20
  useImperativeHandle(ref, () => ({ reset: () => {
21
21
  const api = getHcaptcha();
22
22
  if (api && widgetIdRef.current !== null) api.reset(widgetIdRef.current);
@@ -1 +1 @@
1
- {"version":3,"file":"HcaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/HcaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getHcaptcha } from './vendors'\n\nexport const HCAPTCHA_SCRIPT_URL = 'https://js.hcaptcha.com/1/api.js?render=explicit'\n\nexport type HcaptchaCaptchaProps = {\n\t/** hCaptcha site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,\n * and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const HcaptchaCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = HCAPTCHA_SCRIPT_URL,\n\tref,\n}: HcaptchaCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getHcaptcha()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getHcaptcha()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;;;;AAmBnC,MAAa,mBAAmB,EAC/B,SACA,SACA,SACA,WACA,YAAY,qBACZ,UAC2B;CAC3B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,SAAS;CAExC,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,YAAY;EACxB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,YAAY;EACxB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
1
+ {"version":3,"file":"HcaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/HcaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getHcaptcha } from './vendors'\n\nexport const HCAPTCHA_SCRIPT_URL = 'https://js.hcaptcha.com/1/api.js?render=explicit'\n\nexport type HcaptchaCaptchaProps = {\n\t/** hCaptcha site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,\n * and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const HcaptchaCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = HCAPTCHA_SCRIPT_URL,\n\tadapters,\n\tref,\n}: HcaptchaCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc, adapters?.loadScript)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getHcaptcha()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getHcaptcha()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,sBAAsB;;;;;AAqBnC,MAAa,mBAAmB,EAC/B,SACA,SACA,SACA,WACA,YAAY,qBACZ,UACA,UAC2B;CAC3B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,WAAW,UAAU,UAAU;CAE9D,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,YAAY;EACxB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,YAAY;EACxB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
@@ -1,3 +1,4 @@
1
+ import { FormAdapters } from "../adapters.js";
1
2
  import { CaptchaWidgetHandle } from "./types.js";
2
3
  import { Ref } from "react";
3
4
 
@@ -18,7 +19,8 @@ type RecaptchaCaptchaProps = {
18
19
  onToken: (token: string | null) => void; /** Extra vendor render params for v2 (theme, size, ...). */
19
20
  options?: Record<string, unknown>;
20
21
  className?: string; /** Override the vendor script URL (the version-specific `render` query is not appended). */
21
- scriptSrc?: string;
22
+ scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
23
+ adapters?: Pick<FormAdapters, 'loadScript'>;
22
24
  ref?: Ref<RecaptchaCaptchaHandle>;
23
25
  };
24
26
  /**
@@ -34,6 +36,7 @@ declare const RecaptchaCaptcha: ({
34
36
  options,
35
37
  className,
36
38
  scriptSrc,
39
+ adapters,
37
40
  ref
38
41
  }: RecaptchaCaptchaProps) => import("react/jsx-runtime").JSX.Element;
39
42
  //#endregion
@@ -10,7 +10,7 @@ const RECAPTCHA_SCRIPT_URL = "https://www.google.com/recaptcha/api.js";
10
10
  * tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes
11
11
  * `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.
12
12
  */
13
- const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, className, scriptSrc, ref }) => {
13
+ const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, className, scriptSrc, adapters, ref }) => {
14
14
  const src = scriptSrc ?? `https://www.google.com/recaptcha/api.js?render=${version === "v3" ? siteKey : "explicit"}`;
15
15
  const containerRef = useRef(null);
16
16
  const widgetIdRef = useRef(null);
@@ -20,7 +20,7 @@ const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, classNam
20
20
  optionsRef.current = options;
21
21
  const actionRef = useRef(action);
22
22
  actionRef.current = action;
23
- const ready = useCaptchaScript(src);
23
+ const ready = useCaptchaScript(src, adapters?.loadScript);
24
24
  const execute = useCallback(async (overrideAction) => {
25
25
  const api = getGrecaptcha();
26
26
  if (!api || version !== "v3") return null;
@@ -1 +1 @@
1
- {"version":3,"file":"RecaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/RecaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useCallback, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getGrecaptcha } from './vendors'\n\nexport const RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js'\n\nexport type RecaptchaCaptchaHandle = CaptchaWidgetHandle & {\n\t/**\n\t * v3 only: fetch a fresh token on demand and report it through `onToken`. v3 tokens expire\n\t * after about two minutes, so call this right before submit for a long-lived form. Resolves\n\t * null for v2 or when execution fails.\n\t */\n\texecute: (action?: string) => Promise<string | null>\n}\n\nexport type RecaptchaCaptchaProps = {\n\t/** reCAPTCHA site key (public). */\n\tsiteKey: string\n\t/** 'v2' renders the checkbox widget; 'v3' runs invisibly and produces score-based tokens. */\n\tversion: 'v2' | 'v3'\n\t/** v3 action name reported to reCAPTCHA. Default 'submit'. */\n\taction?: string\n\t/** Receives each fresh token, and null when the token expires, errors, or is reset. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params for v2 (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL (the version-specific `render` query is not appended). */\n\tscriptSrc?: string\n\tref?: Ref<RecaptchaCaptchaHandle>\n}\n\n/**\n * Headless Google reCAPTCHA widget for v2 (checkbox) and v3 (invisible, score-based). v2 reports\n * tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes\n * `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.\n */\nexport const RecaptchaCaptcha = ({\n\tsiteKey,\n\tversion,\n\taction,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc,\n\tref,\n}: RecaptchaCaptchaProps) => {\n\tconst src =\n\t\tscriptSrc ?? `${RECAPTCHA_SCRIPT_URL}?render=${version === 'v3' ? siteKey : 'explicit'}`\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<number | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst actionRef = useRef(action)\n\tactionRef.current = action\n\tconst ready = useCaptchaScript(src)\n\n\tconst execute = useCallback(\n\t\tasync (overrideAction?: string): Promise<string | null> => {\n\t\t\tconst api = getGrecaptcha()\n\t\t\tif (!api || version !== 'v3') {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst token = await api.execute(siteKey, {\n\t\t\t\t\taction: overrideAction ?? actionRef.current ?? 'submit',\n\t\t\t\t})\n\t\t\t\tonTokenRef.current(token)\n\t\t\t\treturn token\n\t\t\t} catch {\n\t\t\t\tonTokenRef.current(null)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[siteKey, version]\n\t)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getGrecaptcha()\n\t\t\t\tif (api && version === 'v2' && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t\texecute,\n\t\t}),\n\t\t[execute, version]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst api = getGrecaptcha()\n\t\tif (!api) {\n\t\t\treturn\n\t\t}\n\t\tlet active = true\n\t\tif (version === 'v3') {\n\t\t\tapi.ready(() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tvoid execute()\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn () => {\n\t\t\t\tactive = false\n\t\t\t}\n\t\t}\n\t\tconst container = containerRef.current\n\t\tif (!container) {\n\t\t\treturn\n\t\t}\n\t\tapi.ready(() => {\n\t\t\tif (!active || widgetIdRef.current !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twidgetIdRef.current = api.render(container, {\n\t\t\t\t...optionsRef.current,\n\t\t\t\tsitekey: siteKey,\n\t\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t\t})\n\t\t})\n\t\treturn () => {\n\t\t\tactive = false\n\t\t\tif (widgetIdRef.current !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t} catch {}\n\t\t\t\twidgetIdRef.current = null\n\t\t\t}\n\t\t\t// grecaptcha has no remove(); clearing the container drops the detached widget DOM.\n\t\t\tcontainer.replaceChildren()\n\t\t}\n\t}, [ready, siteKey, version, execute])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAOA,MAAa,uBAAuB;;;;;;AAiCpC,MAAa,oBAAoB,EAChC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IACd,SAAS;IACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;IACrD,0BAA0B,WAAW,QAAQ,IAAI;IACjD,wBAAwB,WAAW,QAAQ,IAAI;GAChD,CAAC;EACF,CAAC;EACD,aAAa;GACZ,SAAS;GACT,IAAI,YAAY,YAAY,MAAM;IACjC,IAAI;KACH,IAAI,MAAM,YAAY,OAAO;IAC9B,QAAQ,CAAC;IACT,YAAY,UAAU;GACvB;GAEA,UAAU,gBAAgB;EAC3B;CACD,GAAG;EAAC;EAAO;EAAS;EAAS;CAAO,CAAC;CAErC,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
1
+ {"version":3,"file":"RecaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/RecaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useCallback, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getGrecaptcha } from './vendors'\n\nexport const RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js'\n\nexport type RecaptchaCaptchaHandle = CaptchaWidgetHandle & {\n\t/**\n\t * v3 only: fetch a fresh token on demand and report it through `onToken`. v3 tokens expire\n\t * after about two minutes, so call this right before submit for a long-lived form. Resolves\n\t * null for v2 or when execution fails.\n\t */\n\texecute: (action?: string) => Promise<string | null>\n}\n\nexport type RecaptchaCaptchaProps = {\n\t/** reCAPTCHA site key (public). */\n\tsiteKey: string\n\t/** 'v2' renders the checkbox widget; 'v3' runs invisibly and produces score-based tokens. */\n\tversion: 'v2' | 'v3'\n\t/** v3 action name reported to reCAPTCHA. Default 'submit'. */\n\taction?: string\n\t/** Receives each fresh token, and null when the token expires, errors, or is reset. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params for v2 (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL (the version-specific `render` query is not appended). */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<RecaptchaCaptchaHandle>\n}\n\n/**\n * Headless Google reCAPTCHA widget for v2 (checkbox) and v3 (invisible, score-based). v2 reports\n * tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes\n * `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.\n */\nexport const RecaptchaCaptcha = ({\n\tsiteKey,\n\tversion,\n\taction,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc,\n\tadapters,\n\tref,\n}: RecaptchaCaptchaProps) => {\n\tconst src =\n\t\tscriptSrc ?? `${RECAPTCHA_SCRIPT_URL}?render=${version === 'v3' ? siteKey : 'explicit'}`\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<number | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst actionRef = useRef(action)\n\tactionRef.current = action\n\tconst ready = useCaptchaScript(src, adapters?.loadScript)\n\n\tconst execute = useCallback(\n\t\tasync (overrideAction?: string): Promise<string | null> => {\n\t\t\tconst api = getGrecaptcha()\n\t\t\tif (!api || version !== 'v3') {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst token = await api.execute(siteKey, {\n\t\t\t\t\taction: overrideAction ?? actionRef.current ?? 'submit',\n\t\t\t\t})\n\t\t\t\tonTokenRef.current(token)\n\t\t\t\treturn token\n\t\t\t} catch {\n\t\t\t\tonTokenRef.current(null)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[siteKey, version]\n\t)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getGrecaptcha()\n\t\t\t\tif (api && version === 'v2' && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t\texecute,\n\t\t}),\n\t\t[execute, version]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst api = getGrecaptcha()\n\t\tif (!api) {\n\t\t\treturn\n\t\t}\n\t\tlet active = true\n\t\tif (version === 'v3') {\n\t\t\tapi.ready(() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tvoid execute()\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn () => {\n\t\t\t\tactive = false\n\t\t\t}\n\t\t}\n\t\tconst container = containerRef.current\n\t\tif (!container) {\n\t\t\treturn\n\t\t}\n\t\tapi.ready(() => {\n\t\t\tif (!active || widgetIdRef.current !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twidgetIdRef.current = api.render(container, {\n\t\t\t\t...optionsRef.current,\n\t\t\t\tsitekey: siteKey,\n\t\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t\t})\n\t\t})\n\t\treturn () => {\n\t\t\tactive = false\n\t\t\tif (widgetIdRef.current !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t} catch {}\n\t\t\t\twidgetIdRef.current = null\n\t\t\t}\n\t\t\t// grecaptcha has no remove(); clearing the container drops the detached widget DOM.\n\t\t\tcontainer.replaceChildren()\n\t\t}\n\t}, [ready, siteKey, version, execute])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,uBAAuB;;;;;;AAmCpC,MAAa,oBAAoB,EAChC,SACA,SACA,QACA,SACA,SACA,WACA,WACA,UACA,UAC4B;CAC5B,MAAM,MACL,aAAa,kDAAkC,YAAY,OAAO,UAAU;CAC7E,MAAM,eAA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AAW,QAAQ,IAAI;GAChD,CAAC;EACF,CAAC;EACD,aAAa;GACZ,SAAS;GACT,IAAI,YAAY,YAAY,MAAM;IACjC,IAAI;KACH,IAAI,MAAM,YAAY,OAAO;IAC9B,QAAQ,CAAC;IACT,YAAY,UAAU;GACvB;GAEA,UAAU,gBAAgB;EAC3B;CACD,GAAG;EAAC;EAAO;EAAS;EAAS;CAAO,CAAC;CAErC,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
@@ -1,3 +1,4 @@
1
+ import { FormAdapters } from "../adapters.js";
1
2
  import { CaptchaWidgetHandle } from "./types.js";
2
3
  import { Ref } from "react";
3
4
 
@@ -8,7 +9,8 @@ type TurnstileCaptchaProps = {
8
9
  onToken: (token: string | null) => void; /** Extra vendor render params (theme, size, appearance, ...). */
9
10
  options?: Record<string, unknown>;
10
11
  className?: string; /** Override the vendor script URL. */
11
- scriptSrc?: string;
12
+ scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
13
+ adapters?: Pick<FormAdapters, 'loadScript'>;
12
14
  ref?: Ref<CaptchaWidgetHandle>;
13
15
  };
14
16
  /**
@@ -21,6 +23,7 @@ declare const TurnstileCaptcha: ({
21
23
  options,
22
24
  className,
23
25
  scriptSrc,
26
+ adapters,
24
27
  ref
25
28
  }: TurnstileCaptchaProps) => import("react/jsx-runtime").JSX.Element;
26
29
  //#endregion
@@ -9,14 +9,14 @@ const TURNSTILE_SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api
9
9
  * Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a
10
10
  * bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.
11
11
  */
12
- const TurnstileCaptcha = ({ siteKey, onToken, options, className, scriptSrc = TURNSTILE_SCRIPT_URL, ref }) => {
12
+ const TurnstileCaptcha = ({ siteKey, onToken, options, className, scriptSrc = TURNSTILE_SCRIPT_URL, adapters, ref }) => {
13
13
  const containerRef = useRef(null);
14
14
  const widgetIdRef = useRef(null);
15
15
  const onTokenRef = useRef(onToken);
16
16
  onTokenRef.current = onToken;
17
17
  const optionsRef = useRef(options);
18
18
  optionsRef.current = options;
19
- const ready = useCaptchaScript(scriptSrc);
19
+ const ready = useCaptchaScript(scriptSrc, adapters?.loadScript);
20
20
  useImperativeHandle(ref, () => ({ reset: () => {
21
21
  const api = getTurnstile();
22
22
  if (api && widgetIdRef.current !== null) api.reset(widgetIdRef.current);
@@ -1 +1 @@
1
- {"version":3,"file":"TurnstileCaptcha.js","names":[],"sources":["../../../src/react/captcha/TurnstileCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getTurnstile } from './vendors'\n\nexport const TURNSTILE_SCRIPT_URL =\n\t'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'\n\nexport type TurnstileCaptchaProps = {\n\t/** Turnstile site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, appearance, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a\n * bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const TurnstileCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = TURNSTILE_SCRIPT_URL,\n\tref,\n}: TurnstileCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getTurnstile()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getTurnstile()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAOA,MAAa,uBACZ;;;;;AAmBD,MAAa,oBAAoB,EAChC,SACA,SACA,SACA,WACA,YAAY,sBACZ,UAC4B;CAC5B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,SAAS;CAExC,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,aAAa;EACzB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,aAAa;EACzB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
1
+ {"version":3,"file":"TurnstileCaptcha.js","names":[],"sources":["../../../src/react/captcha/TurnstileCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getTurnstile } from './vendors'\n\nexport const TURNSTILE_SCRIPT_URL =\n\t'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'\n\nexport type TurnstileCaptchaProps = {\n\t/** Turnstile site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, appearance, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a\n * bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const TurnstileCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = TURNSTILE_SCRIPT_URL,\n\tadapters,\n\tref,\n}: TurnstileCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc, adapters?.loadScript)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getTurnstile()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getTurnstile()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,uBACZ;;;;;AAqBD,MAAa,oBAAoB,EAChC,SACA,SACA,SACA,WACA,YAAY,sBACZ,UACA,UAC4B;CAC5B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,WAAW,UAAU,UAAU;CAE9D,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,aAAa;EACzB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,aAAa;EACzB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
@@ -2,7 +2,7 @@
2
2
  import { useEffect, useState } from "react";
3
3
  //#region src/react/captcha/useCaptchaScript.ts
4
4
  const pending = /* @__PURE__ */ new Map();
5
- const loadScript = (src) => {
5
+ const injectScript = (src) => {
6
6
  const cached = pending.get(src);
7
7
  if (cached) return cached;
8
8
  const promise = new Promise((resolve, reject) => {
@@ -20,23 +20,41 @@ const loadScript = (src) => {
20
20
  pending.set(src, promise);
21
21
  return promise;
22
22
  };
23
+ const customCaches = /* @__PURE__ */ new WeakMap();
24
+ const loadThrough = (loader, src) => {
25
+ let cache = customCaches.get(loader);
26
+ if (!cache) {
27
+ cache = /* @__PURE__ */ new Map();
28
+ customCaches.set(loader, cache);
29
+ }
30
+ const cached = cache.get(src);
31
+ if (cached) return cached;
32
+ const promise = loader(src).catch((error) => {
33
+ cache.delete(src);
34
+ throw error;
35
+ });
36
+ cache.set(src, promise);
37
+ return promise;
38
+ };
23
39
  /**
24
40
  * Load a vendor captcha script once per src, shared across all widget instances. SSR-safe (the
25
41
  * DOM is only touched inside the effect). A failed load evicts the cache entry so a later mount
26
- * can retry; consumers just see `ready` stay false.
42
+ * can retry; consumers just see `ready` stay false. A host `loadScript` (e.g. a consent-gated
43
+ * loader) replaces the `document.head` injection; pass a stable reference, since a new function
44
+ * identity re-runs the load with a fresh cache.
27
45
  */
28
- const useCaptchaScript = (src) => {
46
+ const useCaptchaScript = (src, loadScript) => {
29
47
  const [ready, setReady] = useState(false);
30
48
  useEffect(() => {
31
49
  let active = true;
32
50
  setReady(false);
33
- loadScript(src).then(() => {
51
+ (loadScript ? loadThrough(loadScript, src) : injectScript(src)).then(() => {
34
52
  if (active) setReady(true);
35
53
  }, () => {});
36
54
  return () => {
37
55
  active = false;
38
56
  };
39
- }, [src]);
57
+ }, [src, loadScript]);
40
58
  return ready;
41
59
  };
42
60
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useCaptchaScript.js","names":[],"sources":["../../../src/react/captcha/useCaptchaScript.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useState } from 'react'\n\nconst pending = new Map<string, Promise<void>>()\n\nconst loadScript = (src: string): Promise<void> => {\n\tconst cached = pending.get(src)\n\tif (cached) {\n\t\treturn cached\n\t}\n\tconst promise = new Promise<void>((resolve, reject) => {\n\t\tconst script = document.createElement('script')\n\t\tscript.src = src\n\t\tscript.async = true\n\t\tscript.addEventListener('load', () => resolve())\n\t\tscript.addEventListener('error', () => {\n\t\t\tpending.delete(src)\n\t\t\tscript.remove()\n\t\t\treject(new Error(`Failed to load ${src}`))\n\t\t})\n\t\tdocument.head.appendChild(script)\n\t})\n\tpending.set(src, promise)\n\treturn promise\n}\n\n/**\n * Load a vendor captcha script once per src, shared across all widget instances. SSR-safe (the\n * DOM is only touched inside the effect). A failed load evicts the cache entry so a later mount\n * can retry; consumers just see `ready` stay false.\n */\nexport const useCaptchaScript = (src: string): boolean => {\n\tconst [ready, setReady] = useState(false)\n\tuseEffect(() => {\n\t\tlet active = true\n\t\tsetReady(false)\n\t\tloadScript(src).then(\n\t\t\t() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tsetReady(true)\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\treturn () => {\n\t\t\tactive = false\n\t\t}\n\t}, [src])\n\treturn ready\n}\n"],"mappings":";;;AAIA,MAAM,0BAAU,IAAI,IAA2B;AAE/C,MAAM,cAAc,QAA+B;CAClD,MAAM,SAAS,QAAQ,IAAI,GAAG;CAC9B,IAAI,QACH,OAAO;CAER,MAAM,UAAU,IAAI,SAAe,SAAS,WAAW;EACtD,MAAM,SAAS,SAAS,cAAc,QAAQ;EAC9C,OAAO,MAAM;EACb,OAAO,QAAQ;EACf,OAAO,iBAAiB,cAAc,QAAQ,CAAC;EAC/C,OAAO,iBAAiB,eAAe;GACtC,QAAQ,OAAO,GAAG;GAClB,OAAO,OAAO;GACd,uBAAO,IAAI,MAAM,kBAAkB,KAAK,CAAC;EAC1C,CAAC;EACD,SAAS,KAAK,YAAY,MAAM;CACjC,CAAC;CACD,QAAQ,IAAI,KAAK,OAAO;CACxB,OAAO;AACR;;;;;;AAOA,MAAa,oBAAoB,QAAyB;CACzD,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,gBAAgB;EACf,IAAI,SAAS;EACb,SAAS,KAAK;EACd,WAAW,GAAG,EAAE,WACT;GACL,IAAI,QACH,SAAS,IAAI;EAEf,SACM,CAAC,CACR;EACA,aAAa;GACZ,SAAS;EACV;CACD,GAAG,CAAC,GAAG,CAAC;CACR,OAAO;AACR"}
1
+ {"version":3,"file":"useCaptchaScript.js","names":[],"sources":["../../../src/react/captcha/useCaptchaScript.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useState } from 'react'\nimport type { LoadScript } from '../adapters'\n\nconst pending = new Map<string, Promise<void>>()\n\nconst injectScript = (src: string): Promise<void> => {\n\tconst cached = pending.get(src)\n\tif (cached) {\n\t\treturn cached\n\t}\n\tconst promise = new Promise<void>((resolve, reject) => {\n\t\tconst script = document.createElement('script')\n\t\tscript.src = src\n\t\tscript.async = true\n\t\tscript.addEventListener('load', () => resolve())\n\t\tscript.addEventListener('error', () => {\n\t\t\tpending.delete(src)\n\t\t\tscript.remove()\n\t\t\treject(new Error(`Failed to load ${src}`))\n\t\t})\n\t\tdocument.head.appendChild(script)\n\t})\n\tpending.set(src, promise)\n\treturn promise\n}\n\n// A custom loader gets the same per-src cache and evict-on-failure retry, keyed per loader so two\n// adapters (or the default injector) never share entries.\nconst customCaches = new WeakMap<LoadScript, Map<string, Promise<void>>>()\n\nconst loadThrough = (loader: LoadScript, src: string): Promise<void> => {\n\tlet cache = customCaches.get(loader)\n\tif (!cache) {\n\t\tcache = new Map()\n\t\tcustomCaches.set(loader, cache)\n\t}\n\tconst cached = cache.get(src)\n\tif (cached) {\n\t\treturn cached\n\t}\n\tconst promise = loader(src).catch((error) => {\n\t\tcache.delete(src)\n\t\tthrow error\n\t})\n\tcache.set(src, promise)\n\treturn promise\n}\n\n/**\n * Load a vendor captcha script once per src, shared across all widget instances. SSR-safe (the\n * DOM is only touched inside the effect). A failed load evicts the cache entry so a later mount\n * can retry; consumers just see `ready` stay false. A host `loadScript` (e.g. a consent-gated\n * loader) replaces the `document.head` injection; pass a stable reference, since a new function\n * identity re-runs the load with a fresh cache.\n */\nexport const useCaptchaScript = (src: string, loadScript?: LoadScript): boolean => {\n\tconst [ready, setReady] = useState(false)\n\tuseEffect(() => {\n\t\tlet active = true\n\t\tsetReady(false)\n\t\tconst load = loadScript ? loadThrough(loadScript, src) : injectScript(src)\n\t\tload.then(\n\t\t\t() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tsetReady(true)\n\t\t\t\t}\n\t\t\t},\n\t\t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