@prosopo/procaptcha-frictionless 2.17.0 → 2.18.0

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 (67) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +6 -6
  2. package/.turbo/turbo-build$colon$tsc.log +24 -24
  3. package/.turbo/turbo-build.log +12 -12
  4. package/CHANGELOG.md +47 -0
  5. package/dist/{AuthenticatedBadge.d.ts → authenticatedBadge.d.ts} +3 -3
  6. package/dist/authenticatedBadge.d.ts.map +1 -0
  7. package/dist/authenticatedBadge.js +79 -0
  8. package/dist/authenticatedBadge.js.map +1 -0
  9. package/dist/cjs/authenticatedBadge.cjs +79 -0
  10. package/dist/cjs/detectorPrefetch.cjs +2 -2
  11. package/dist/cjs/index.cjs +2 -2
  12. package/dist/cjs/procaptchaFrictionless.cjs +269 -0
  13. package/dist/detectorPrefetch.js +2 -2
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/procaptchaFrictionless.d.ts +6 -0
  17. package/dist/procaptchaFrictionless.d.ts.map +1 -0
  18. package/dist/procaptchaFrictionless.js +269 -0
  19. package/dist/procaptchaFrictionless.js.map +1 -0
  20. package/dist/tests/escalationClientSession.test.d.ts +0 -3
  21. package/dist/tests/escalationClientSession.test.d.ts.map +1 -1
  22. package/dist/tests/escalationClientSession.test.js +52 -61
  23. package/dist/tests/escalationClientSession.test.js.map +1 -1
  24. package/dist/tests/escalationHandoff.integration.test.d.ts +0 -3
  25. package/dist/tests/escalationHandoff.integration.test.d.ts.map +1 -1
  26. package/dist/tests/escalationHandoff.integration.test.js +62 -61
  27. package/dist/tests/escalationHandoff.integration.test.js.map +1 -1
  28. package/dist/tests/executeBeforeMount.test.d.ts +0 -3
  29. package/dist/tests/executeBeforeMount.test.d.ts.map +1 -1
  30. package/dist/tests/executeBeforeMount.test.js +53 -49
  31. package/dist/tests/executeBeforeMount.test.js.map +1 -1
  32. package/dist/tests/manualStart.test.d.ts +0 -3
  33. package/dist/tests/manualStart.test.d.ts.map +1 -1
  34. package/dist/tests/manualStart.test.js +55 -52
  35. package/dist/tests/manualStart.test.js.map +1 -1
  36. package/dist/tests/procaptchaFrictionless.test.d.ts +2 -0
  37. package/dist/tests/procaptchaFrictionless.test.d.ts.map +1 -0
  38. package/dist/tests/procaptchaFrictionless.test.js +244 -0
  39. package/dist/tests/procaptchaFrictionless.test.js.map +1 -0
  40. package/dist/tests/sessionInvalidatedRemint.test.d.ts +0 -3
  41. package/dist/tests/sessionInvalidatedRemint.test.d.ts.map +1 -1
  42. package/dist/tests/sessionInvalidatedRemint.test.js +49 -43
  43. package/dist/tests/sessionInvalidatedRemint.test.js.map +1 -1
  44. package/package.json +11 -13
  45. package/src/authenticatedBadge.ts +151 -0
  46. package/src/customDetectBot.ts +2 -2
  47. package/src/detectorPrefetch.ts +2 -2
  48. package/src/index.ts +1 -1
  49. package/src/{ProcaptchaFrictionless.tsx → procaptchaFrictionless.ts} +285 -314
  50. package/src/tests/{escalationClientSession.test.tsx → escalationClientSession.test.ts} +83 -92
  51. package/src/tests/{escalationHandoff.integration.test.tsx → escalationHandoff.integration.test.ts} +110 -108
  52. package/src/tests/{executeBeforeMount.test.tsx → executeBeforeMount.test.ts} +79 -77
  53. package/src/tests/{manualStart.test.tsx → manualStart.test.ts} +87 -83
  54. package/src/tests/procaptchaFrictionless.test.ts +408 -0
  55. package/src/tests/{sessionInvalidatedRemint.test.tsx → sessionInvalidatedRemint.test.ts} +67 -64
  56. package/tsconfig.cjs.json +1 -2
  57. package/tsconfig.tsbuildinfo +1 -1
  58. package/dist/AuthenticatedBadge.d.ts.map +0 -1
  59. package/dist/AuthenticatedBadge.js +0 -75
  60. package/dist/AuthenticatedBadge.js.map +0 -1
  61. package/dist/ProcaptchaFrictionless.d.ts +0 -3
  62. package/dist/ProcaptchaFrictionless.d.ts.map +0 -1
  63. package/dist/ProcaptchaFrictionless.js +0 -287
  64. package/dist/ProcaptchaFrictionless.js.map +0 -1
  65. package/dist/cjs/AuthenticatedBadge.cjs +0 -75
  66. package/dist/cjs/ProcaptchaFrictionless.cjs +0 -287
  67. package/src/AuthenticatedBadge.tsx +0 -141
@@ -0,0 +1,408 @@
1
+ // Copyright 2021-2026 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ import type { Ti18n } from "@prosopo/locale";
16
+ import {
17
+ type BotDetectionFunction,
18
+ type BotDetectionFunctionResult,
19
+ CaptchaType,
20
+ type ProcaptchaClientConfigOutput,
21
+ type ProcaptchaFrictionlessProps,
22
+ type ProcaptchaProps,
23
+ } from "@prosopo/types";
24
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
25
+
26
+ /**
27
+ * The orchestrator decides which solver to mount, tears the previous one down,
28
+ * and owns the recovery paths. Each solver package is stubbed to a probe so a
29
+ * test can read the props it was handed and assert the mount/unmount ordering
30
+ * that used to come free from the reconciler.
31
+ */
32
+ const mocks = vi.hoisted(() => {
33
+ const mounted: { solver: string; props: ProcaptchaProps }[] = [];
34
+ const destroyed: string[] = [];
35
+ const probe =
36
+ (solver: string) => (container: HTMLElement, props: ProcaptchaProps) => {
37
+ mounted.push({ solver, props });
38
+ const element = container.ownerDocument.createElement("div");
39
+ element.setAttribute("data-solver", solver);
40
+ container.appendChild(element);
41
+ return {
42
+ destroy: () => {
43
+ element.remove();
44
+ destroyed.push(solver);
45
+ },
46
+ };
47
+ };
48
+ return { mounted, destroyed, probe };
49
+ });
50
+
51
+ // jsdom serves the suite over http, so the widget's own HTTPS guard would
52
+ // short-circuit every test before detection ran.
53
+ vi.mock("@prosopo/procaptcha-common", async (importOriginal) => ({
54
+ ...(await importOriginal<typeof import("@prosopo/procaptcha-common")>()),
55
+ isSecureBrowserContext: () => true,
56
+ }));
57
+
58
+ vi.mock("@prosopo/procaptcha-react", () => ({
59
+ mountProcaptchaImageWidget: mocks.probe("image"),
60
+ }));
61
+ vi.mock("@prosopo/procaptcha-puzzle", () => ({
62
+ mountProcaptchaPuzzleWidget: mocks.probe("puzzle"),
63
+ }));
64
+ vi.mock("@prosopo/procaptcha-pow", () => ({
65
+ mountProcaptchaPowWidget: mocks.probe("pow"),
66
+ }));
67
+
68
+ const { mountProcaptchaFrictionless } = await import(
69
+ "../procaptchaFrictionless.js"
70
+ );
71
+ const { MAX_SESSION_INVALIDATED_RETRIES } = await import(
72
+ "../sessionInvalidatedRecovery.js"
73
+ );
74
+
75
+ const SITE_KEY = "5CcNvLUdiXFpzKDMjThGLSK9rhWHA1H4EF3zrgkpkjAdqmuP";
76
+
77
+ const config = (): ProcaptchaClientConfigOutput =>
78
+ ({
79
+ account: { address: SITE_KEY },
80
+ defaultEnvironment: "staging",
81
+ mode: "visible",
82
+ theme: "light",
83
+ }) as unknown as ProcaptchaClientConfigOutput;
84
+
85
+ const i18n = (): Ti18n =>
86
+ ({
87
+ isInitialized: true,
88
+ t: (key: string) => key,
89
+ language: "en",
90
+ changeLanguage: () => Promise.resolve(),
91
+ }) as unknown as Ti18n;
92
+
93
+ const detection = (
94
+ captchaType: CaptchaType,
95
+ overrides: Partial<BotDetectionFunctionResult> = {},
96
+ ): BotDetectionFunctionResult =>
97
+ ({
98
+ captchaType,
99
+ sessionId: "session-1",
100
+ provider: { providerAccount: "acc", provider: { url: "https://p.one" } },
101
+ userAccount: { account: { address: "user" } },
102
+ ...overrides,
103
+ }) as unknown as BotDetectionFunctionResult;
104
+
105
+ let container: HTMLDivElement;
106
+ let widget: { destroy: () => void } | undefined;
107
+
108
+ const props = (
109
+ detectBot: BotDetectionFunction,
110
+ overrides: Partial<ProcaptchaFrictionlessProps> = {},
111
+ ): ProcaptchaFrictionlessProps => ({
112
+ config: config(),
113
+ callbacks: {},
114
+ i18n: i18n(),
115
+ restart: () => undefined,
116
+ detectBot,
117
+ ...overrides,
118
+ });
119
+
120
+ const settle = async (): Promise<void> => {
121
+ await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
122
+ await Promise.resolve();
123
+ };
124
+
125
+ const waitFor = async (condition: () => boolean): Promise<void> => {
126
+ for (let poll = 0; poll < 100 && !condition(); poll++) {
127
+ await new Promise<void>((resolve: () => void) => setTimeout(resolve, 20));
128
+ }
129
+ };
130
+
131
+ const solvers = (): string[] =>
132
+ Array.from(container.querySelectorAll("[data-solver]")).map(
133
+ (element: Element) => element.getAttribute("data-solver") ?? "",
134
+ );
135
+
136
+ beforeEach(() => {
137
+ mocks.mounted.length = 0;
138
+ mocks.destroyed.length = 0;
139
+ widget = undefined;
140
+ container = document.createElement("div");
141
+ document.body.appendChild(container);
142
+ });
143
+
144
+ afterEach(() => {
145
+ widget?.destroy();
146
+ widget = undefined;
147
+ container.remove();
148
+ });
149
+
150
+ describe("choosing a solver", () => {
151
+ test("mounts the image widget when the provider asks for one", async () => {
152
+ widget = mountProcaptchaFrictionless(
153
+ container,
154
+ props(() => Promise.resolve(detection(CaptchaType.image))),
155
+ );
156
+ await settle();
157
+ expect(solvers()).toEqual(["image"]);
158
+ });
159
+
160
+ test("mounts the puzzle widget when the provider asks for one", async () => {
161
+ widget = mountProcaptchaFrictionless(
162
+ container,
163
+ props(() => Promise.resolve(detection(CaptchaType.puzzle))),
164
+ );
165
+ await settle();
166
+ expect(solvers()).toEqual(["puzzle"]);
167
+ });
168
+
169
+ test("falls through to PoW for anything else", async () => {
170
+ widget = mountProcaptchaFrictionless(
171
+ container,
172
+ props(() => Promise.resolve(detection(CaptchaType.pow))),
173
+ );
174
+ await settle();
175
+ expect(solvers()).toEqual(["pow"]);
176
+ });
177
+
178
+ test("hands the solver the session the frictionless call minted", async () => {
179
+ widget = mountProcaptchaFrictionless(
180
+ container,
181
+ props(() => Promise.resolve(detection(CaptchaType.image))),
182
+ );
183
+ await settle();
184
+ expect(mocks.mounted[0]?.props.frictionlessState).toMatchObject({
185
+ sessionId: "session-1",
186
+ });
187
+ });
188
+
189
+ test("only PoW is given an escalation handler", async () => {
190
+ widget = mountProcaptchaFrictionless(
191
+ container,
192
+ props(() => Promise.resolve(detection(CaptchaType.pow))),
193
+ );
194
+ await settle();
195
+ expect(mocks.mounted[0]?.props.onEscalate).toBeTypeOf("function");
196
+ });
197
+ });
198
+
199
+ describe("the loading placeholder", () => {
200
+ test("shows a checkbox before detection resolves", () => {
201
+ widget = mountProcaptchaFrictionless(
202
+ container,
203
+ props(() => new Promise<BotDetectionFunctionResult>(() => undefined)),
204
+ );
205
+ // The spinner is the checkbox's loading state; either way there must be
206
+ // something widget-shaped on the page while the round trip is in flight.
207
+ expect(container.querySelector('[role="status"]')).not.toBe(null);
208
+ });
209
+
210
+ test("is replaced by the solver, not left behind it", async () => {
211
+ widget = mountProcaptchaFrictionless(
212
+ container,
213
+ props(() => Promise.resolve(detection(CaptchaType.image))),
214
+ );
215
+ await settle();
216
+ expect(container.querySelector('[role="status"]')).toBeNull();
217
+ expect(solvers()).toEqual(["image"]);
218
+ });
219
+
220
+ test("shows a terminal detection error instead of a solver", async () => {
221
+ const onError = vi.fn<(error: Error) => void>();
222
+ widget = mountProcaptchaFrictionless(
223
+ container,
224
+ props(
225
+ () =>
226
+ Promise.resolve(
227
+ detection(CaptchaType.image, {
228
+ error: {
229
+ message: "site key not registered",
230
+ key: "API.SITE_KEY_NOT_REGISTERED",
231
+ },
232
+ } as Partial<BotDetectionFunctionResult>),
233
+ ),
234
+ { callbacks: { onError } },
235
+ ),
236
+ );
237
+ await settle();
238
+ expect(solvers()).toEqual([]);
239
+ expect(container.textContent).toContain("site key not registered");
240
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
241
+ });
242
+
243
+ test("re-rolls onto another provider for a failure that is not the caller's fault", async () => {
244
+ // An unrecognised key means the provider broke in a way it has no
245
+ // vocabulary for; another node may well be healthy, so the user should
246
+ // not be stranded on the first answer.
247
+ const detectBot = vi
248
+ .fn<BotDetectionFunction>()
249
+ .mockResolvedValueOnce(
250
+ detection(CaptchaType.image, {
251
+ error: { message: "no capacity", key: "API.UNKNOWN_ERROR" },
252
+ } as Partial<BotDetectionFunctionResult>),
253
+ )
254
+ .mockResolvedValue(detection(CaptchaType.image));
255
+ widget = mountProcaptchaFrictionless(container, props(detectBot));
256
+ // providerRetry backs off before re-rolling, so the second call lands a
257
+ // randomised delay later rather than on the next tick.
258
+ await waitFor(() => detectBot.mock.calls.length > 1);
259
+ await settle();
260
+ expect(solvers()).toEqual(["image"]);
261
+ });
262
+
263
+ test("refuses to mount anything when the response names no captcha type", async () => {
264
+ // A hard block short-circuits the request and answers with a bare
265
+ // `{ error: "..." }`; mounting the PoW default against it only earns an
266
+ // API.INCORRECT_CAPTCHA_TYPE from the next call.
267
+ const onError = vi.fn<(error: Error) => void>();
268
+ widget = mountProcaptchaFrictionless(
269
+ container,
270
+ props(
271
+ () =>
272
+ Promise.resolve({
273
+ sessionId: "session-1",
274
+ } as unknown as BotDetectionFunctionResult),
275
+ { callbacks: { onError } },
276
+ ),
277
+ );
278
+ await settle();
279
+ expect(solvers()).toEqual([]);
280
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
281
+ });
282
+ });
283
+
284
+ describe("escalating from PoW", () => {
285
+ test("swaps PoW for the escalated solver rather than stacking them", async () => {
286
+ // Nothing reconciles this for us: without the explicit teardown the page
287
+ // ends up with two live widgets, two modals and two sets of document
288
+ // listeners.
289
+ widget = mountProcaptchaFrictionless(
290
+ container,
291
+ props(() => Promise.resolve(detection(CaptchaType.pow))),
292
+ );
293
+ await settle();
294
+
295
+ mocks.mounted[0]?.props.onEscalate?.(CaptchaType.image, "session-2", {
296
+ x: 4,
297
+ y: 5,
298
+ });
299
+ await settle();
300
+
301
+ expect(solvers()).toEqual(["image"]);
302
+ expect(mocks.destroyed).toContain("pow");
303
+ });
304
+
305
+ test("carries the new session and the original click into the escalation", async () => {
306
+ widget = mountProcaptchaFrictionless(
307
+ container,
308
+ props(() => Promise.resolve(detection(CaptchaType.pow))),
309
+ );
310
+ await settle();
311
+
312
+ mocks.mounted[0]?.props.onEscalate?.(CaptchaType.image, "session-2", {
313
+ x: 4,
314
+ y: 5,
315
+ });
316
+ await settle();
317
+
318
+ expect(mocks.mounted[1]?.props).toMatchObject({
319
+ autoStart: true,
320
+ startCoords: { x: 4, y: 5 },
321
+ });
322
+ expect(mocks.mounted[1]?.props.frictionlessState).toMatchObject({
323
+ sessionId: "session-2",
324
+ });
325
+ });
326
+ });
327
+
328
+ describe("recovering an invalidated session", () => {
329
+ test("re-runs detection and remounts with the preserved coordinates", async () => {
330
+ const detectBot = vi
331
+ .fn<BotDetectionFunction>()
332
+ .mockResolvedValueOnce(detection(CaptchaType.image))
333
+ .mockResolvedValue(
334
+ detection(CaptchaType.image, {
335
+ sessionId: "session-2",
336
+ } as Partial<BotDetectionFunctionResult>),
337
+ );
338
+ widget = mountProcaptchaFrictionless(container, props(detectBot));
339
+ await settle();
340
+
341
+ mocks.mounted[0]?.props.onSessionInvalidated?.(11, 22);
342
+ await settle();
343
+
344
+ expect(detectBot).toHaveBeenCalledTimes(2);
345
+ expect(solvers()).toEqual(["image"]);
346
+ expect(mocks.mounted[1]?.props).toMatchObject({
347
+ autoStart: true,
348
+ startCoords: { x: 11, y: 22 },
349
+ });
350
+ });
351
+
352
+ test("stops re-minting once the budget is spent, so a persistently broken session cannot loop", async () => {
353
+ const detectBot = vi
354
+ .fn<BotDetectionFunction>()
355
+ .mockResolvedValue(detection(CaptchaType.image));
356
+ widget = mountProcaptchaFrictionless(container, props(detectBot));
357
+ await settle();
358
+
359
+ // One more failure than the budget allows; the last one falls over
360
+ // visibly rather than asking for yet another session.
361
+ for (
362
+ let attempt = 0;
363
+ attempt <= MAX_SESSION_INVALIDATED_RETRIES;
364
+ attempt++
365
+ ) {
366
+ mocks.mounted.at(-1)?.props.onSessionInvalidated?.(11, 22);
367
+ await settle();
368
+ }
369
+
370
+ expect(detectBot).toHaveBeenCalledTimes(
371
+ MAX_SESSION_INVALIDATED_RETRIES + 1,
372
+ );
373
+ });
374
+ });
375
+
376
+ describe("tearing down", () => {
377
+ test("takes the mounted solver with it", async () => {
378
+ widget = mountProcaptchaFrictionless(
379
+ container,
380
+ props(() => Promise.resolve(detection(CaptchaType.image))),
381
+ );
382
+ await settle();
383
+ widget.destroy();
384
+ widget = undefined;
385
+ expect(mocks.destroyed).toContain("image");
386
+ expect(container.querySelector("[data-solver]")).toBeNull();
387
+ });
388
+
389
+ test("does not mount a solver that resolves after destroy", async () => {
390
+ let release: (result: BotDetectionFunctionResult) => void = () => undefined;
391
+ widget = mountProcaptchaFrictionless(
392
+ container,
393
+ props(
394
+ () =>
395
+ new Promise<BotDetectionFunctionResult>(
396
+ (resolve: (result: BotDetectionFunctionResult) => void) => {
397
+ release = resolve;
398
+ },
399
+ ),
400
+ ),
401
+ );
402
+ widget.destroy();
403
+ widget = undefined;
404
+ release(detection(CaptchaType.image));
405
+ await settle();
406
+ expect(mocks.mounted).toHaveLength(0);
407
+ });
408
+ });
@@ -18,12 +18,10 @@ import {
18
18
  type BotDetectionFunction,
19
19
  CaptchaType,
20
20
  ModeEnum,
21
- type ProcaptchaClientConfigInput,
21
+ type ProcaptchaClientConfigOutput,
22
22
  type ProcaptchaProps,
23
23
  type RandomProvider,
24
24
  } from "@prosopo/types";
25
- import { type ReactElement, act, createElement } from "react";
26
- import { type Root, createRoot } from "react-dom/client";
27
25
  import {
28
26
  type Mock,
29
27
  afterEach,
@@ -35,41 +33,49 @@ import {
35
33
  } from "vitest";
36
34
  import { MAX_SESSION_INVALIDATED_RETRIES } from "../sessionInvalidatedRecovery.js";
37
35
 
38
- declare global {
39
- var IS_REACT_ACT_ENVIRONMENT: boolean;
40
- }
41
-
42
- globalThis.IS_REACT_ACT_ENVIRONMENT = true;
36
+ const mocks = vi.hoisted(() => {
37
+ const mounts: { props: ProcaptchaProps }[] = [];
38
+ const stub = (host: HTMLElement, props: ProcaptchaProps) => {
39
+ mounts.push({ props });
40
+ const element = host.ownerDocument.createElement("div");
41
+ element.setAttribute("data-widget", "image");
42
+ host.appendChild(element);
43
+ return { destroy: () => element.remove() };
44
+ };
45
+ return { mounts, stub };
46
+ });
43
47
 
44
- const mocks = vi.hoisted(() => ({
45
- mounts: [] as { props: ProcaptchaProps }[],
48
+ vi.mock("@prosopo/procaptcha-react", () => ({
49
+ mountProcaptchaImageWidget: mocks.stub,
50
+ }));
51
+ vi.mock("@prosopo/procaptcha-pow", () => ({
52
+ mountProcaptchaPowWidget: mocks.stub,
53
+ }));
54
+ vi.mock("@prosopo/procaptcha-puzzle", () => ({
55
+ mountProcaptchaPuzzleWidget: mocks.stub,
46
56
  }));
47
57
 
48
- const imageStub = (props: ProcaptchaProps) => {
49
- mocks.mounts.push({ props });
50
- return createElement("div", { "data-widget": "image" });
51
- };
52
-
53
- vi.mock("@prosopo/procaptcha-react", () => ({ Procaptcha: imageStub }));
54
- vi.mock("@prosopo/procaptcha-pow", () => ({ ProcaptchaPow: imageStub }));
55
- vi.mock("@prosopo/procaptcha-puzzle", () => ({ ProcaptchaPuzzle: imageStub }));
56
-
57
- vi.mock("@prosopo/procaptcha-common", async (importOriginal) => {
58
- const actual =
59
- await importOriginal<typeof import("@prosopo/procaptcha-common")>();
60
- return { ...actual, isSecureBrowserContext: () => true };
61
- });
58
+ // jsdom serves the suite over http, so the widget's own HTTPS guard would
59
+ // short-circuit every test before detection ran.
60
+ vi.mock("@prosopo/procaptcha-common", async (importOriginal) => ({
61
+ ...(await importOriginal<typeof import("@prosopo/procaptcha-common")>()),
62
+ isSecureBrowserContext: () => true,
63
+ }));
62
64
 
63
- const { ProcaptchaFrictionless } = await import("../ProcaptchaFrictionless.js");
65
+ const { mountProcaptchaFrictionless } = await import(
66
+ "../procaptchaFrictionless.js"
67
+ );
64
68
 
65
69
  const SITE_KEY = "5siteKey";
66
70
 
67
- const config = (): ProcaptchaClientConfigInput => ({
68
- account: { address: SITE_KEY },
69
- userAccountAddress: "",
70
- web2: true,
71
- mode: ModeEnum.visible,
72
- });
71
+ const config = (): ProcaptchaClientConfigOutput =>
72
+ ({
73
+ account: { address: SITE_KEY },
74
+ userAccountAddress: "",
75
+ web2: true,
76
+ theme: "light",
77
+ mode: ModeEnum.visible,
78
+ }) as unknown as ProcaptchaClientConfigOutput;
73
79
 
74
80
  const i18nStub = {
75
81
  isInitialized: true,
@@ -81,9 +87,11 @@ const i18nStub = {
81
87
  const provider: RandomProvider = {
82
88
  providerAccount: "provider-account",
83
89
  provider: { url: "https://provider.test" },
84
- };
90
+ } as unknown as RandomProvider;
85
91
 
86
- const userAccount: Account = { account: { address: "user-address" } };
92
+ const userAccount: Account = {
93
+ account: { address: "user-address" },
94
+ } as unknown as Account;
87
95
 
88
96
  // Each /frictionless run mints a new session, exactly as the provider does.
89
97
  let sessionCounter = 0;
@@ -99,10 +107,15 @@ const detectBot: Mock<BotDetectionFunction> = vi.fn(async () => {
99
107
  });
100
108
 
101
109
  let container: HTMLDivElement;
102
- let root: Root;
110
+ let widget: { destroy: () => void } | undefined;
103
111
  let restart: Mock<() => void>;
104
112
  let onError: Mock<(error: Error) => void>;
105
113
 
114
+ const settle = async (): Promise<void> => {
115
+ await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
116
+ await Promise.resolve();
117
+ };
118
+
106
119
  const lastMount = () => {
107
120
  const mount = mocks.mounts.at(-1);
108
121
  if (!mount) throw new Error("expected the image widget to have mounted");
@@ -112,9 +125,8 @@ const lastMount = () => {
112
125
  /** The inner widget reporting `CAPTCHA.NO_SESSION_FOUND` on its challenge fetch. */
113
126
  const reportSessionInvalidated = async (): Promise<void> => {
114
127
  const { onSessionInvalidated } = lastMount().props;
115
- await act(async () => {
116
- onSessionInvalidated?.(120, 340);
117
- });
128
+ onSessionInvalidated?.(120, 340);
129
+ await settle();
118
130
  };
119
131
 
120
132
  const isCheckboxPlaceholder = (): boolean =>
@@ -128,26 +140,19 @@ beforeEach(async () => {
128
140
  onError = vi.fn<(error: Error) => void>();
129
141
  container = document.createElement("div");
130
142
  document.body.appendChild(container);
131
- act(() => {
132
- root = createRoot(container);
133
- });
134
- await act(async () => {
135
- root.render(
136
- createElement(ProcaptchaFrictionless, {
137
- config: config(),
138
- callbacks: { onError },
139
- restart,
140
- i18n: i18nStub,
141
- detectBot,
142
- }) as ReactElement,
143
- );
143
+ widget = mountProcaptchaFrictionless(container, {
144
+ config: config(),
145
+ callbacks: { onError },
146
+ restart,
147
+ i18n: i18nStub,
148
+ detectBot,
144
149
  });
150
+ await settle();
145
151
  });
146
152
 
147
153
  afterEach(() => {
148
- act(() => {
149
- root.unmount();
150
- });
154
+ widget?.destroy();
155
+ widget = undefined;
151
156
  container.remove();
152
157
  vi.clearAllMocks();
153
158
  });
@@ -158,7 +163,7 @@ afterEach(() => {
158
163
  // behind it. The outer recovery guard was one-shot per widget lifetime and the
159
164
  // inner widget always returns through this handler, so the second failure was
160
165
  // handled by nobody at all.
161
- describe("NO_SESSION_FOUND recovery in ProcaptchaFrictionless", () => {
166
+ describe("NO_SESSION_FOUND recovery in the frictionless widget", () => {
162
167
  it("re-mints a session and re-mounts the widget on the first failure", async () => {
163
168
  expect(detectBot).toHaveBeenCalledTimes(1);
164
169
  expect(lastMount().props.frictionlessState?.sessionId).toBe(
@@ -207,16 +212,15 @@ describe("NO_SESSION_FOUND recovery in ProcaptchaFrictionless", () => {
207
212
  );
208
213
  });
209
214
 
210
- // `resetState(0)` used to be `0 || stateRef.current.attemptCount`, so the
211
- // counter never went back to zero and `start()`'s own `attemptCount >= 5`
212
- // fall-over fired after five cumulative runs — five successful reload
213
- // presses were enough to strand the user on the error placeholder.
215
+ // `resetState(0)` used to be `0 || state.attemptCount`, so the counter never
216
+ // went back to zero and `start()`'s own `attemptCount >= 5` fall-over fired
217
+ // after five cumulative runs — five successful reload presses were enough to
218
+ // strand the user on the error placeholder.
214
219
  it("does not fall over after repeated successful reloads", async () => {
215
220
  for (let i = 0; i < 8; i++) {
216
221
  const { onReload } = lastMount().props;
217
- await act(async () => {
218
- onReload?.(10, 20);
219
- });
222
+ onReload?.(10, 20);
223
+ await settle();
220
224
  }
221
225
 
222
226
  expect(isCheckboxPlaceholder()).toBe(false);
@@ -231,9 +235,8 @@ describe("NO_SESSION_FOUND recovery in ProcaptchaFrictionless", () => {
231
235
  const beforeReload = detectBot.mock.calls.length;
232
236
 
233
237
  const { onReload } = lastMount().props;
234
- await act(async () => {
235
- onReload?.(10, 20);
236
- });
238
+ onReload?.(10, 20);
239
+ await settle();
237
240
  expect(detectBot).toHaveBeenCalledTimes(beforeReload + 1);
238
241
 
239
242
  // Without the reset this failure would land on the exhausted branch.
package/tsconfig.cjs.json CHANGED
@@ -3,8 +3,7 @@
3
3
  "compilerOptions": {
4
4
  "rootDir": "./src",
5
5
  "outDir": "./dist/cjs",
6
- "lib": ["es6", "dom"],
7
- "jsxImportSource": "@emotion/react"
6
+ "lib": ["es6", "dom"]
8
7
  },
9
8
  "include": ["src/index.ts", "src/index.html"],
10
9
  "references": [