@bemony/payment-form-react 0.2.0-next.0 → 0.2.0-next.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.
package/README.md CHANGED
@@ -1,71 +1,439 @@
1
- # @bemony/payment-form-react
1
+ # `@bemony/payment-form-react`
2
2
 
3
- React adapter for `@bemony/payment-form`. It uses the same hosted iframe and public `pay(input)`
4
- contract; it does not make a payment request from the merchant application.
3
+ Adaptador React oficial do `@bemony/payment-form`.
5
4
 
6
- ## Install
5
+ O pacote monta a mesma instância segura do SDK Web e oferece duas formas de integração:
6
+
7
+ - `ref`, para checkouts em que formulário e botão estão próximos;
8
+ - `BemonyPaymentFormProvider` + `useBemonyPaymentForm`, para compartilhar estado e `pay()` entre
9
+ componentes.
10
+
11
+ O adaptador não realiza requests financeiros diretamente, não contém regras próprias de pagamento
12
+ e não duplica o estado canônico do SDK Web.
13
+
14
+ ## Requisitos
15
+
16
+ - React `>=19 <20`;
17
+ - React DOM `>=19 <20`;
18
+ - CheckoutSession criada no backend;
19
+ - origem do checkout cadastrada na Bemony;
20
+ - CSP compatível com os frames e collectors utilizados.
21
+
22
+ ## Instalação
7
23
 
8
24
  ```bash
9
25
  pnpm add @bemony/payment-form-react
10
26
  ```
11
27
 
12
- Use a ref when the checkout button is close to the form:
28
+ `@bemony/payment-form` é instalado como dependência do adaptador. Não é necessário montar os dois
29
+ pacotes separadamente.
30
+
31
+ ## Preparação no backend
32
+
33
+ Crie a CheckoutSession no servidor usando a Secret Key. O navegador deve receber somente o
34
+ `sessionClientSecret` e as instruções públicas de `riskCollectors`.
35
+
36
+ ```ts
37
+ const response = await fetch(
38
+ `${process.env.BEMONY_ORCHESTRATOR_API_BASE_URL}/v1/checkout-sessions`,
39
+ {
40
+ method: 'POST',
41
+ headers: {
42
+ authorization: `Bearer ${process.env.BEMONY_SECRET_KEY}`,
43
+ 'content-type': 'application/json',
44
+ 'idempotency-key': crypto.randomUUID(),
45
+ 'x-bemony-api-version': '2026-10-20'
46
+ },
47
+ body: JSON.stringify({
48
+ mode: 'CREATE',
49
+ domainId: 'cdom_...',
50
+ checkout: { checkoutConfigId: 'ccfg_...' }
51
+ })
52
+ }
53
+ );
54
+
55
+ if (!response.ok) throw new Error('Não foi possível criar a CheckoutSession.');
56
+ const session = await response.json();
57
+ ```
58
+
59
+ Nunca coloque `BEMONY_SECRET_KEY` em variável pública do React, bundle do navegador ou propriedade
60
+ do componente.
61
+
62
+ ## Integração com `ref`
63
+
64
+ Use esta forma quando o botão que chama `pay()` pertence ao mesmo componente.
13
65
 
14
66
  ```tsx
15
- import { BemonyPaymentForm, type BemonyPaymentFormRef } from '@bemony/payment-form-react';
16
- import { useRef } from 'react';
67
+ 'use client';
17
68
 
18
- const ref = useRef<BemonyPaymentFormRef>(null);
69
+ import {
70
+ BemonyPaymentForm,
71
+ PAYMENT_FORM_API_VERSION,
72
+ type BemonyPaymentFormRef,
73
+ type PayInput,
74
+ type PaymentFormError,
75
+ type RiskCollector
76
+ } from '@bemony/payment-form-react';
77
+ import { useRef, useState } from 'react';
19
78
 
20
- <BemonyPaymentForm
21
- ref={ref}
22
- clientSecret={session.sessionClientSecret}
23
- environment="sandbox"
24
- riskCollectors={session.riskCollectors}
25
- />;
26
-
27
- await ref.current?.pay({
28
- merchantOrderId: 'order_123',
29
- currency: 'USD',
30
- operation: 'SALE',
31
- items: [{ description: 'Order', unitAmount: 1000, quantity: 1, type: 'unique' }]
32
- });
79
+ type CheckoutProps = Readonly<{
80
+ sessionClientSecret: string;
81
+ riskCollectors?: readonly RiskCollector[];
82
+ }>;
83
+
84
+ export function Checkout({ sessionClientSecret, riskCollectors }: CheckoutProps) {
85
+ const formRef = useRef<BemonyPaymentFormRef>(null);
86
+ const [ready, setReady] = useState(false);
87
+ const [submitting, setSubmitting] = useState(false);
88
+ const [error, setError] = useState<PaymentFormError | null>(null);
89
+
90
+ const input: PayInput = {
91
+ merchantOrderId: 'order_123',
92
+ merchantReference: 'merchant-reference-123',
93
+ currency: 'BRL',
94
+ operation: 'PURCHASE',
95
+ customer: {
96
+ firstName: 'Ana',
97
+ lastName: 'Silva',
98
+ email: 'ana@example.com'
99
+ },
100
+ items: [
101
+ {
102
+ id: 'item_123',
103
+ sku: 'SKU-123',
104
+ description: 'Produto',
105
+ unitAmount: 10990,
106
+ quantity: 1,
107
+ type: 'ONE_TIME'
108
+ }
109
+ ],
110
+ amount: 10990,
111
+ context: { funnelId: 'checkout', funnelStep: 'payment', channel: 'WEB' }
112
+ };
113
+
114
+ async function submit() {
115
+ setSubmitting(true);
116
+ setError(null);
117
+ try {
118
+ const payment = await formRef.current!.pay(input);
119
+ console.log(payment.paymentId, payment.status);
120
+ } catch (cause) {
121
+ setError(cause as PaymentFormError);
122
+ } finally {
123
+ setSubmitting(false);
124
+ }
125
+ }
126
+
127
+ return (
128
+ <section>
129
+ <BemonyPaymentForm
130
+ ref={formRef}
131
+ clientSecret={sessionClientSecret}
132
+ environment="sandbox"
133
+ version={PAYMENT_FORM_API_VERSION.ENRICHMENT}
134
+ riskCollectors={riskCollectors}
135
+ threeDS={{ presentation: 'modal' }}
136
+ appearance={{ theme: 'system' }}
137
+ onReady={() => setReady(true)}
138
+ onStatusChange={(status) =>
139
+ setSubmitting(
140
+ ['TOKENIZING', 'SUBMITTING', 'AUTHENTICATING_3DS', 'PROCESSING'].includes(status)
141
+ )
142
+ }
143
+ onError={setError}
144
+ />
145
+
146
+ {error && <p role="alert">{error.message}</p>}
147
+ <button type="button" disabled={!ready || submitting} onClick={() => void submit()}>
148
+ {submitting ? 'Processando…' : 'Pagar'}
149
+ </button>
150
+ </section>
151
+ );
152
+ }
33
153
  ```
34
154
 
35
- For a button or summary in another component, use the optional provider and hook:
155
+ ## Integração com Provider e hook
156
+
157
+ Use esta forma quando o botão, resumo ou tratamento de estado está em outro componente. O Provider
158
+ é a autoridade da configuração; não repita `clientSecret`, `environment` ou `version` no componente
159
+ filho.
36
160
 
37
161
  ```tsx
162
+ 'use client';
163
+
38
164
  import {
39
165
  BemonyPaymentForm,
40
166
  BemonyPaymentFormProvider,
41
- useBemonyPaymentForm
167
+ PAYMENT_FORM_API_VERSION,
168
+ useBemonyPaymentForm,
169
+ type PayInput,
170
+ type RiskCollector
42
171
  } from '@bemony/payment-form-react';
43
172
 
44
- function PayButton() {
45
- const { ready, pay } = useBemonyPaymentForm();
173
+ function PayButton({ input }: Readonly<{ input: PayInput }>) {
174
+ const { ready, state, error, pay } = useBemonyPaymentForm();
175
+
46
176
  return (
47
- <button disabled={!ready} onClick={() => void pay(input)}>
48
- Pay
49
- </button>
177
+ <>
178
+ {error && <p role="alert">{error.message}</p>}
179
+ <button type="button" disabled={!ready || state.isSubmitting} onClick={() => void pay(input)}>
180
+ {state.isSubmitting ? 'Processando…' : 'Pagar'}
181
+ </button>
182
+ </>
50
183
  );
51
184
  }
52
185
 
53
- <BemonyPaymentFormProvider clientSecret={clientSecret} environment="sandbox">
54
- <BemonyPaymentForm />
55
- <PayButton />
56
- </BemonyPaymentFormProvider>;
186
+ type CheckoutWithProviderProps = Readonly<{
187
+ session: Readonly<{
188
+ sessionClientSecret: string;
189
+ riskCollectors?: readonly RiskCollector[];
190
+ }>;
191
+ input: PayInput;
192
+ }>;
193
+
194
+ export function CheckoutWithProvider({ session, input }: CheckoutWithProviderProps) {
195
+ return (
196
+ <BemonyPaymentFormProvider
197
+ clientSecret={session.sessionClientSecret}
198
+ environment="sandbox"
199
+ version={PAYMENT_FORM_API_VERSION.ENRICHMENT}
200
+ riskCollectors={session.riskCollectors}
201
+ threeDS={{ presentation: 'modal' }}
202
+ >
203
+ <BemonyPaymentForm className="payment-form" />
204
+ <PayButton input={input} />
205
+ </BemonyPaymentFormProvider>
206
+ );
207
+ }
208
+ ```
209
+
210
+ `useBemonyPaymentForm()` retorna:
211
+
212
+ | Campo | Tipo | Uso |
213
+ | ------- | ------------------------------------------ | -------------------------------------- |
214
+ | `ready` | `boolean` | formulário pronto para receber `pay()` |
215
+ | `state` | `PaymentFormState` | estado, envio, resultado e erro atuais |
216
+ | `error` | `PaymentFormError \| null` | último erro público |
217
+ | `pay` | `(input: PayInput) => Promise<PayOutcome>` | inicia ou compartilha a operação ativa |
218
+
219
+ O hook só pode ser usado dentro de `BemonyPaymentFormProvider`.
220
+
221
+ ## Props
222
+
223
+ | Prop | Tipo | Padrão | Descrição |
224
+ | ------------------- | ---------------------------------------- | ------------ | ------------------------------------------ |
225
+ | `clientSecret` | `string` | obrigatório | segredo público da CheckoutSession |
226
+ | `environment` | `'sandbox' \| 'production'` | `sandbox` | infraestrutura hospedada |
227
+ | `version` | `'2026-09-25' \| '2026-10-20'` | `2026-10-20` | contrato da API |
228
+ | `riskCollectors` | `readonly RiskCollector[]` | ausente | instruções públicas devolvidas pela sessão |
229
+ | `appearance` | `PaymentFormAppearance` | sistema | tema e variáveis visuais |
230
+ | `threeDS` | `{ presentation?: 'modal' \| 'inline' }` | `modal` | apresentação do challenge |
231
+ | `className` | `string` | ausente | classe aplicada ao container React |
232
+ | `onReady` | `() => void` | ausente | iframe e Card Frame prontos |
233
+ | `onCardStateChange` | `(state: CardState) => void` | ausente | completude e validade dos campos |
234
+ | `onStatusChange` | `(status) => void` | ausente | transição do estado público |
235
+ | `onSuccess` | `(payment) => void` | ausente | pagamento `AUTHORIZED` ou `CAPTURED` |
236
+ | `onError` | `(error) => void` | ausente | mesmo erro público rejeitado por `pay()` |
237
+ | `onEvent` | `(event) => void` | ausente | telemetria segura de montagem/pagamento |
238
+
239
+ No Provider, `children` também é obrigatório. No componente standalone, `clientSecret` é
240
+ obrigatório; dentro do Provider, a configuração vem do contexto.
241
+
242
+ ## Bandeiras de cartão habilitadas
243
+
244
+ Não passe uma lista de bandeiras por prop. A CheckoutSession é a autoridade e o Card Frame aplica
245
+ a configuração. Se uma projeção legada estiver ausente ou inválida, o frame assume apenas `VISA` e
246
+ `MASTERCARD` para preservar esses pagamentos; nenhuma outra rede é habilitada por esse fallback.
247
+ Quando a bandeira detectada não é aceita, `onCardStateChange` informa `valid: false` e nenhum token
248
+ é criado; desabilite o botão enquanto o estado for inválido.
249
+
250
+ ```tsx
251
+ <BemonyPaymentForm
252
+ clientSecret={sessionClientSecret}
253
+ onCardStateChange={(state) => setCanPay(state.valid)}
254
+ />
255
+ ```
256
+
257
+ Caso `pay()` seja chamado, capture `PaymentFormError.code === 'CARD_BRAND_NOT_SUPPORTED'`. É uma
258
+ falha local, `retryable: true`, classificada como `VALIDATION` em `CARD_TOKENIZATION`; o usuário
259
+ pode corrigir o cartão sem gerar uma tentativa financeira.
260
+
261
+ ## Versões da API
262
+
263
+ ```tsx
264
+ import {
265
+ DEFAULT_PAYMENT_FORM_API_VERSION,
266
+ PAYMENT_FORM_API_VERSION,
267
+ type PaymentFormApiVersion
268
+ } from '@bemony/payment-form-react';
269
+ ```
270
+
271
+ | Versão | Constante | Uso |
272
+ | ------------ | ------------------------------------- | ------------------------------ |
273
+ | `2026-09-25` | `PAYMENT_FORM_API_VERSION.LEGACY` | contrato legado |
274
+ | `2026-10-20` | `PAYMENT_FORM_API_VERSION.ENRICHMENT` | enriquecimento e body completo |
275
+
276
+ O padrão é `DEFAULT_PAYMENT_FORM_API_VERSION`, atualmente `2026-10-20`. O tipo é fechado e o valor
277
+ é validado novamente pelo SDK e pelo hosted BFF. Campos exclusivos da versão enriquecida retornam
278
+ `400 UNKNOWN_FIELD` quando enviados com a versão legada.
279
+
280
+ Use a mesma versão na criação da CheckoutSession e no componente React.
281
+
282
+ ## Ambientes
283
+
284
+ - `sandbox`: padrão compatível atual conectado à Railway;
285
+ - `production`: ambiente isolado de aceitação conectado à AWS durante a transição.
286
+
287
+ O componente nunca recebe endpoint ou origem arbitrária. A configuração dos hosts pertence aos
288
+ deploys Bemony.
289
+
290
+ ## Contrato de `pay()`
291
+
292
+ O adaptador reexporta os mesmos tipos do SDK Web:
293
+
294
+ ```ts
295
+ import type {
296
+ Address,
297
+ CardStorageConsent,
298
+ CheckoutClient,
299
+ CommerceContext,
300
+ Customer,
301
+ CustomerHistory,
302
+ PayInput,
303
+ PayOutcome,
304
+ PaymentAmounts,
305
+ PaymentItem,
306
+ ShippingAddress
307
+ } from '@bemony/payment-form-react';
308
+ ```
309
+
310
+ `PayInput` suporta pedido, customer, endereços, consentimento, itens, impostos/descontos, total de
311
+ integridade, contexto comercial, URLs, metadata e contexto do client. Sessão, token, PAN, CVC, IP,
312
+ User-Agent observado e evidência 3DS não pertencem ao input público.
313
+
314
+ ### Fallback de `client` por campo
315
+
316
+ Se o integrador enviar somente um campo de `client`, apenas esse campo substitui o valor observado.
317
+ Os demais continuam sendo preenchidos pelo SDK quando disponíveis. A mesma regra vale dentro de
318
+ `client.utm` e `client.browserInfo`; um objeto parcial nunca apaga o restante do contexto.
319
+
320
+ ### `amount` na versão enriquecida
321
+
322
+ `amount` é um eco opcional do total calculado pelo Runtime. Ele não define o valor cobrado. Uma
323
+ divergência retorna `422 AMOUNT_MISMATCH`.
324
+
325
+ `publicCheckoutUrl` está tipado para a evolução do Runtime, mas não deve ser enviado antes de o
326
+ ambiente de destino publicar suporte ao campo.
327
+
328
+ ## Estados e erros
329
+
330
+ ```text
331
+ MOUNTING → READY → TOKENIZING → SUBMITTING → PROCESSING
332
+ ├→ AUTHENTICATING_3DS → PROCESSING
333
+ ├→ AUTHORIZED/CAPTURED
334
+ ├→ DECLINED/FAILED/EXPIRED
335
+ └→ UNKNOWN
336
+ ```
337
+
338
+ Trate a rejeição de `pay()` mesmo quando `onError` estiver configurado:
339
+
340
+ ```tsx
341
+ try {
342
+ const result = await formRef.current!.pay(input);
343
+ // Não faça fulfillment apenas com o resultado do browser.
344
+ console.log(result.paymentId);
345
+ } catch (cause) {
346
+ const error = cause as PaymentFormError;
347
+ console.error(error.code, error.requestId, error.details);
348
+ }
349
+ ```
350
+
351
+ - `requestId` correlaciona a resposta do Runtime;
352
+ - `commandId` identifica o comando local;
353
+ - `retryable: true` permite uma nova tentativa controlada, não replay automático;
354
+ - `PAYMENT_STATUS_UNKNOWN` exige consulta/webhook antes de qualquer nova cobrança;
355
+ - `payment.transaction.attempts` é diagnóstico público, não fonte de fulfillment.
356
+
357
+ O produto consumidor escolhe a mensagem apresentada ao comprador. O Embed preserva o erro público
358
+ da API e não reinterpreta o domínio financeiro.
359
+
360
+ ## Remontagem e React Strict Mode
361
+
362
+ O adaptador adia a montagem de forma cancelável para suportar o ciclo especulativo do React Strict
363
+ Mode sem deixar dois iframes ativos.
364
+
365
+ Uma alteração real em `clientSecret`, `environment`, `version`, apresentação do 3DS, `appearance` ou
366
+ `riskCollectors` remonta o iframe. `appearance` e `riskCollectors` são comparados por valor, então
367
+ objetos equivalentes recriados durante renderizações comuns não provocam remontagem.
368
+
369
+ Callbacks são lidos pela referência mais recente e não exigem desmontar a instância quando apenas
370
+ a função muda.
371
+
372
+ ## Next.js e SSR
373
+
374
+ Use o componente a partir de uma fronteira Client Component:
375
+
376
+ ```tsx
377
+ 'use client';
378
+
379
+ import { BemonyPaymentForm } from '@bemony/payment-form-react';
57
380
  ```
58
381
 
59
- Create `clientSecret` on the merchant server. Never expose a Bemony secret API key in React code
60
- or a public environment variable.
382
+ Crie a CheckoutSession em Route Handler, Server Action protegida ou backend próprio. Envie ao Client
383
+ Component apenas `sessionClientSecret` e dados públicos da sessão. Nunca use uma variável
384
+ `NEXT_PUBLIC_*` para Secret Key ou token interno.
385
+
386
+ ## Aparência
387
+
388
+ ```tsx
389
+ <BemonyPaymentForm
390
+ clientSecret={clientSecret}
391
+ appearance={{
392
+ theme: 'dark',
393
+ variables: {
394
+ colorPrimary: '#00e68a',
395
+ colorBackground: '#101513',
396
+ colorText: '#ffffff',
397
+ colorDanger: '#ff5b6e',
398
+ colorBorder: '#33413a',
399
+ borderRadius: '12px',
400
+ fontFamily: 'Inter, sans-serif'
401
+ },
402
+ threeDS: { modalBackdrop: 'rgba(0, 0, 0, 0.72)' }
403
+ }}
404
+ />
405
+ ```
406
+
407
+ ## Risk collectors e CSP
408
+
409
+ Passe `riskCollectors` diretamente da CheckoutSession ao componente ou Provider. Collector lento,
410
+ bloqueado ou indisponível não bloqueia o pagamento e não deve ser persistido pelo checkout.
411
+
412
+ Durante a transição atual, use uma política consolidada que preserve as fontes exigidas pelo seu
413
+ site e permita os hosts Bemony e os collectors habilitados:
414
+
415
+ ```text
416
+ default-src 'self';
417
+ frame-src https://form.bemony.com https://bemony-payment-form.vercel.app https://bemony-payment-form-sandbox.vercel.app;
418
+ script-src 'self' https://js.stripe.com https://tst.kaptcha.com https://ssl.kaptcha.com;
419
+ connect-src 'self' https://form.bemony.com https://bemony-payment-form.vercel.app https://bemony-payment-form-sandbox.vercel.app https://api.stripe.com https://r.stripe.com https://m.stripe.com https://tst.kaptcha.com https://ssl.kaptcha.com;
420
+ ```
421
+
422
+ ## Migração e rollout
423
+
424
+ 1. publique primeiro o hosted Payment Form compatível com `apiVersion`;
425
+ 2. valide o hosted usando a versão antiga do pacote;
426
+ 3. publique Web e React com tag `next`;
427
+ 4. atualize um consumidor de teste explicitamente para `next`;
428
+ 5. valide legado e enriquecimento antes de promover `latest`.
61
429
 
62
- `environment` accepts `sandbox` or `production` and defaults to `sandbox` for compatibility. The
63
- adapter forwards the value to the Web SDK; it does not select or configure Card Frame URLs itself.
430
+ Omitir `version` mantém `2026-10-20`, que já era o comportamento do BFF. Consumidores antigos não
431
+ mudam de pacote nem recebem a nova implementação até atualizarem sua dependência.
64
432
 
65
- Pass the optional `riskCollectors` returned with the CheckoutSession directly to the component or
66
- provider. The adapter forwards it only during mounting; it does not remount the secure iframe for
67
- ordinary React state changes.
433
+ ## Regras de segurança
68
434
 
69
- The adapter compares `appearance` and `riskCollectors` by value rather than object identity. It
70
- therefore preserves the mounted iframe when a parent React render recreates equivalent objects. A
71
- real change to either configuration, or to `clientSecret`, intentionally starts a new mount.
435
+ - não envie Secret Key, token interno, PAN, CVC ou evidência 3DS por props;
436
+ - não registre `clientSecret`, token do cartão ou valor bruto de collectors;
437
+ - não permita que o browser escolha endpoints privados;
438
+ - não libere pedido apenas com `onSuccess`; confirme por webhook ou consulta autenticada;
439
+ - não implemente tokenização, 3DS ou retry financeiro fora do SDK.
@@ -1,4 +1,4 @@
1
- import { type CardState, type PayInput, type PayOutcome, type PaymentFormAppearance, type PaymentFormCallbacks, type PaymentFormError, type PaymentFormEnvironment, type PaymentFormState, type RiskCollector, type ThreeDSPresentation } from '@bemony/payment-form';
1
+ import { type CardState, type PayInput, type PayOutcome, type PaymentFormAppearance, type PaymentFormApiVersion, type PaymentFormCallbacks, type PaymentFormError, type PaymentFormEnvironment, type PaymentFormState, type RiskCollector, type ThreeDSPresentation } from '@bemony/payment-form';
2
2
  import { type ReactNode } from 'react';
3
3
  export type BemonyPaymentFormRef = Readonly<{
4
4
  pay(input: PayInput): Promise<PayOutcome>;
@@ -8,6 +8,7 @@ export type BemonyPaymentFormRef = Readonly<{
8
8
  type FormConfig = PaymentFormCallbacks & Readonly<{
9
9
  clientSecret: string;
10
10
  environment?: PaymentFormEnvironment;
11
+ version?: PaymentFormApiVersion;
11
12
  riskCollectors?: readonly RiskCollector[];
12
13
  appearance?: PaymentFormAppearance;
13
14
  threeDS?: Readonly<{
@@ -1 +1 @@
1
- {"version":3,"file":"payment-form.d.ts","sourceRoot":"","sources":["../../src/components/payment-form.tsx"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EAErB,KAAK,sBAAsB,EAE3B,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EASL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CAAC;IAC1C,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC1C,QAAQ,IAAI,gBAAgB,CAA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B,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,EAAE,EAAE,8BAA8B,+BAQhG;AAED,wBAAgB,oBAAoB,IAAI,QAAQ,CAAC;IAC/C,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,gBAAgB,CAAC;IACxB,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC/B,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC3C,CAAC,CAaD;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB;gBAlDoD,MAAM;;eAhB3E,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC;gBAC7B,gBAAgB;eACjB,IAAI;IA0MhB,CAAC"}
@@ -74,6 +74,7 @@ export const BemonyPaymentForm = forwardRef(function BemonyPaymentForm(props, re
74
74
  target,
75
75
  clientSecret: config.clientSecret,
76
76
  ...(config.environment === undefined ? {} : { environment: config.environment }),
77
+ ...(config.version === undefined ? {} : { version: config.version }),
77
78
  ...(config.riskCollectors === undefined
78
79
  ? {}
79
80
  : { riskCollectors: config.riskCollectors }),
@@ -160,6 +161,7 @@ export const BemonyPaymentForm = forwardRef(function BemonyPaymentForm(props, re
160
161
  }, [
161
162
  config.clientSecret,
162
163
  config.environment,
164
+ config.version,
163
165
  config.threeDS?.presentation,
164
166
  appearanceSignature,
165
167
  riskCollectorsSignature,
@@ -186,10 +188,24 @@ function mountError(error) {
186
188
  typeof error.message === 'string') {
187
189
  const details = error;
188
190
  return {
191
+ ...(isApiErrorType(details.type) ? { type: details.type } : {}),
189
192
  code: error.code,
190
193
  message: error.message,
194
+ ...(isErrorField(details.field) ? { field: details.field } : {}),
195
+ ...(isPublicErrorDetails(details.details) ? { details: details.details } : {}),
191
196
  ...(isErrorCategory(details.category) ? { category: details.category } : {}),
192
- ...(isErrorStage(details.stage) ? { stage: details.stage } : {})
197
+ ...(isErrorStage(details.stage) ? { stage: details.stage } : {}),
198
+ ...(isText(details.requestId) ? { requestId: details.requestId } : {}),
199
+ ...(isText(details.commandId) ? { commandId: details.commandId } : {}),
200
+ ...(isText(details.paymentId) ? { paymentId: details.paymentId } : {}),
201
+ ...(typeof details.retryable === 'boolean' ? { retryable: details.retryable } : {}),
202
+ ...(isHttpStatus(details.httpStatus) ? { httpStatus: details.httpStatus } : {}),
203
+ ...(isText(details.upstreamRequestId)
204
+ ? { upstreamRequestId: details.upstreamRequestId }
205
+ : {}),
206
+ ...(details.frameStage === 'FRAME_DOCUMENT' || details.frameStage === 'CARD_FRAME'
207
+ ? { frameStage: details.frameStage }
208
+ : {})
193
209
  };
194
210
  }
195
211
  return {
@@ -199,6 +215,38 @@ function mountError(error) {
199
215
  stage: 'FORM_SDK'
200
216
  };
201
217
  }
218
+ function isApiErrorType(value) {
219
+ return (typeof value === 'string' &&
220
+ [
221
+ 'authentication_error',
222
+ 'authorization_error',
223
+ 'validation_error',
224
+ 'idempotency_error',
225
+ 'rate_limit_error',
226
+ 'conflict_error',
227
+ 'internal_error',
228
+ 'not_found'
229
+ ].includes(value));
230
+ }
231
+ function isErrorField(value) {
232
+ return typeof value === 'string' && value.length > 0 && value.length <= 256;
233
+ }
234
+ function isText(value) {
235
+ return typeof value === 'string' && value.length > 0 && value.length <= 1_000;
236
+ }
237
+ function isHttpStatus(value) {
238
+ return typeof value === 'number' && Number.isInteger(value) && value >= 400 && value <= 599;
239
+ }
240
+ function isPublicErrorDetails(value) {
241
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
242
+ return false;
243
+ try {
244
+ return JSON.stringify(value).length <= 16_384;
245
+ }
246
+ catch {
247
+ return false;
248
+ }
249
+ }
202
250
  function stableSignature(value) {
203
251
  if (value === undefined)
204
252
  return '';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { BemonyPaymentForm, BemonyPaymentFormProvider, useBemonyPaymentForm } from './components/payment-form';
2
+ export { DEFAULT_PAYMENT_FORM_API_VERSION, PAYMENT_FORM_API_VERSION } from '@bemony/payment-form';
2
3
  export type { BemonyPaymentFormProps, BemonyPaymentFormProviderProps, BemonyPaymentFormRef } from './components/payment-form';
3
- export type { PayInput, PayOutcome, PaymentFormAppearance, PaymentFormError, PaymentFormErrorAttempt, PaymentFormEvent, PaymentFormErrorPayment, PaymentFormEnvironment, PaymentFormState, PaymentFormStatus, RiskCollector, ThreeDSPresentation } from '@bemony/payment-form';
4
+ export type { Address, CardStorageConsent, CheckoutClient, CommerceContext, Customer, CustomerHistory, PayInput, PayOutcome, PaymentAmounts, PaymentItem, PaymentFormAppearance, PaymentFormApiVersion, PaymentFormApiErrorType, PaymentFormError, PaymentFormErrorAttempt, PaymentFormErrorDetails, PaymentFormErrorDetailValue, PaymentFormEvent, PaymentFormErrorPayment, PaymentFormEnvironment, PaymentFormState, PaymentFormStatus, RiskCollector, ShippingAddress, ThreeDSPresentation } from '@bemony/payment-form';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EACV,sBAAsB,EACtB,8BAA8B,EAC9B,oBAAoB,EACrB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EACV,QAAQ,EACR,UAAU,EACV,qBAAqB,EACrB,gBAAgB,EAChB,uBAAuB,EACvB,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,mBAAmB,EACpB,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,gCAAgC,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAClG,YAAY,EACV,sBAAsB,EACtB,8BAA8B,EAC9B,oBAAoB,EACrB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EACV,OAAO,EACP,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,QAAQ,EACR,eAAe,EACf,QAAQ,EACR,UAAU,EACV,cAAc,EACd,WAAW,EACX,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACvB,gBAAgB,EAChB,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,eAAe,EACf,mBAAmB,EACpB,MAAM,sBAAsB,CAAC"}
package/dist/index.js CHANGED
@@ -84,6 +84,7 @@ var BemonyPaymentForm = forwardRef(
84
84
  target,
85
85
  clientSecret: config.clientSecret,
86
86
  ...config.environment === void 0 ? {} : { environment: config.environment },
87
+ ...config.version === void 0 ? {} : { version: config.version },
87
88
  ...config.riskCollectors === void 0 ? {} : { riskCollectors: config.riskCollectors },
88
89
  ...config.appearance === void 0 ? {} : { appearance: config.appearance },
89
90
  ...config.threeDS === void 0 ? {} : { threeDS: config.threeDS },
@@ -155,6 +156,7 @@ var BemonyPaymentForm = forwardRef(
155
156
  }, [
156
157
  config.clientSecret,
157
158
  config.environment,
159
+ config.version,
158
160
  config.threeDS?.presentation,
159
161
  appearanceSignature,
160
162
  riskCollectorsSignature,
@@ -177,10 +179,20 @@ function mountError(error) {
177
179
  if (typeof error === "object" && error !== null && "code" in error && "message" in error && typeof error.code === "string" && typeof error.message === "string") {
178
180
  const details = error;
179
181
  return {
182
+ ...isApiErrorType(details.type) ? { type: details.type } : {},
180
183
  code: error.code,
181
184
  message: error.message,
185
+ ...isErrorField(details.field) ? { field: details.field } : {},
186
+ ...isPublicErrorDetails(details.details) ? { details: details.details } : {},
182
187
  ...isErrorCategory(details.category) ? { category: details.category } : {},
183
- ...isErrorStage(details.stage) ? { stage: details.stage } : {}
188
+ ...isErrorStage(details.stage) ? { stage: details.stage } : {},
189
+ ...isText(details.requestId) ? { requestId: details.requestId } : {},
190
+ ...isText(details.commandId) ? { commandId: details.commandId } : {},
191
+ ...isText(details.paymentId) ? { paymentId: details.paymentId } : {},
192
+ ...typeof details.retryable === "boolean" ? { retryable: details.retryable } : {},
193
+ ...isHttpStatus(details.httpStatus) ? { httpStatus: details.httpStatus } : {},
194
+ ...isText(details.upstreamRequestId) ? { upstreamRequestId: details.upstreamRequestId } : {},
195
+ ...details.frameStage === "FRAME_DOCUMENT" || details.frameStage === "CARD_FRAME" ? { frameStage: details.frameStage } : {}
184
196
  };
185
197
  }
186
198
  return {
@@ -190,6 +202,35 @@ function mountError(error) {
190
202
  stage: "FORM_SDK"
191
203
  };
192
204
  }
205
+ function isApiErrorType(value) {
206
+ return typeof value === "string" && [
207
+ "authentication_error",
208
+ "authorization_error",
209
+ "validation_error",
210
+ "idempotency_error",
211
+ "rate_limit_error",
212
+ "conflict_error",
213
+ "internal_error",
214
+ "not_found"
215
+ ].includes(value);
216
+ }
217
+ function isErrorField(value) {
218
+ return typeof value === "string" && value.length > 0 && value.length <= 256;
219
+ }
220
+ function isText(value) {
221
+ return typeof value === "string" && value.length > 0 && value.length <= 1e3;
222
+ }
223
+ function isHttpStatus(value) {
224
+ return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
225
+ }
226
+ function isPublicErrorDetails(value) {
227
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
228
+ try {
229
+ return JSON.stringify(value).length <= 16384;
230
+ } catch {
231
+ return false;
232
+ }
233
+ }
193
234
  function stableSignature(value) {
194
235
  if (value === void 0) return "";
195
236
  return JSON.stringify(value, (_key, item) => {
@@ -231,9 +272,14 @@ function isErrorStage(value) {
231
272
  "RUNTIME"
232
273
  ].includes(value);
233
274
  }
275
+
276
+ // src/index.ts
277
+ import { DEFAULT_PAYMENT_FORM_API_VERSION, PAYMENT_FORM_API_VERSION } from "@bemony/payment-form";
234
278
  export {
235
279
  BemonyPaymentForm,
236
280
  BemonyPaymentFormProvider,
281
+ DEFAULT_PAYMENT_FORM_API_VERSION,
282
+ PAYMENT_FORM_API_VERSION,
237
283
  useBemonyPaymentForm
238
284
  };
239
285
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/components/payment-form.tsx"],
4
- "sourcesContent": ["'use client';\n\nimport {\n BemonyPaymentForm as WebPaymentForm,\n type CardState,\n type PayInput,\n type PayOutcome,\n type PaymentFormAppearance,\n type PaymentFormCallbacks,\n type PaymentFormError,\n type PaymentFormEvent,\n type PaymentFormEnvironment,\n type PaymentFormInstance,\n type PaymentFormState,\n type RiskCollector,\n type ThreeDSPresentation\n} from '@bemony/payment-form';\nimport {\n createContext,\n forwardRef,\n useContext,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ReactNode\n} from 'react';\n\nexport type BemonyPaymentFormRef = Readonly<{\n pay(input: PayInput): Promise<PayOutcome>;\n getState(): PaymentFormState;\n destroy(): void;\n}>;\n\ntype FormConfig = PaymentFormCallbacks &\n Readonly<{\n clientSecret: string;\n environment?: PaymentFormEnvironment;\n riskCollectors?: readonly RiskCollector[];\n appearance?: PaymentFormAppearance;\n threeDS?: Readonly<{ presentation?: ThreeDSPresentation }>;\n onCardStateChange?: (state: CardState) => void;\n }>;\n\nexport type BemonyPaymentFormProps = Partial<FormConfig> & Readonly<{ className?: string }>;\n\ntype ContextValue = Readonly<{\n config: FormConfig;\n instance?: PaymentFormInstance;\n state: PaymentFormState;\n register(instance: PaymentFormInstance | undefined): void;\n setState(state: PaymentFormState): void;\n}>;\n\nconst PaymentFormContext = createContext<ContextValue | undefined>(undefined);\nconst mountingState: PaymentFormState = { status: 'MOUNTING', ready: false, isSubmitting: false };\n\nexport type BemonyPaymentFormProviderProps = FormConfig & Readonly<{ children: ReactNode }>;\n\n/** Optional React-only convenience layer over the single Web SDK instance. */\nexport function BemonyPaymentFormProvider({ children, ...config }: BemonyPaymentFormProviderProps) {\n const [instance, register] = useState<PaymentFormInstance | undefined>(undefined);\n const [state, setState] = useState<PaymentFormState>(mountingState);\n const value = useMemo<ContextValue>(\n () => ({ config, instance, state, register, setState }),\n [config, instance, state]\n );\n return <PaymentFormContext.Provider value={value}>{children}</PaymentFormContext.Provider>;\n}\n\nexport function useBemonyPaymentForm(): Readonly<{\n ready: boolean;\n state: PaymentFormState;\n error: PaymentFormError | null;\n pay(input: PayInput): Promise<PayOutcome>;\n}> {\n const context = useContext(PaymentFormContext);\n if (context === undefined) {\n throw new Error('useBemonyPaymentForm deve ser usado dentro de BemonyPaymentFormProvider.');\n }\n return {\n ready: context.state.ready,\n state: context.state,\n error: context.state.error ?? null,\n pay(input) {\n return context.instance?.pay(input) ?? Promise.reject(notReady());\n }\n };\n}\n\n/**\n * Works standalone with a ref or as the mount point inside\n * BemonyPaymentFormProvider. Both paths mount the same Web SDK instance.\n */\nexport const BemonyPaymentForm = forwardRef<BemonyPaymentFormRef, BemonyPaymentFormProps>(\n function BemonyPaymentForm(props, ref) {\n const context = useContext(PaymentFormContext);\n const config = context?.config ?? completeConfig(props);\n const register = context?.register;\n const setProviderState = context?.setState;\n const targetRef = useRef<HTMLDivElement>(null);\n const instanceRef = useRef<PaymentFormInstance | undefined>(undefined);\n const stateRef = useRef<PaymentFormState>(mountingState);\n const latestConfig = useRef(config);\n latestConfig.current = config;\n // Parent components often recreate appearance/collector objects inline.\n // Reference-only dependencies would unnecessarily reload the secure iframe\n // on ordinary React state changes. Remount only on semantic changes.\n const appearanceSignature = stableSignature(config.appearance);\n const riskCollectorsSignature = stableSignature(config.riskCollectors);\n\n useImperativeHandle(\n ref,\n () => ({\n pay(input) {\n return instanceRef.current?.pay(input) ?? Promise.reject(notReady());\n },\n getState() {\n return instanceRef.current?.getState() ?? stateRef.current;\n },\n destroy() {\n instanceRef.current?.destroy();\n instanceRef.current = undefined;\n register?.(undefined);\n }\n }),\n [register]\n );\n\n useEffect(() => {\n const target = targetRef.current;\n if (target === null) return;\n const abort = new AbortController();\n let disposed = false;\n let instance: PaymentFormInstance | undefined;\n const publish = (next: PaymentFormState): void => {\n stateRef.current = next;\n setProviderState?.(next);\n };\n const mount = async (): Promise<void> => {\n try {\n const mounted = await WebPaymentForm.mount({\n target,\n clientSecret: config.clientSecret,\n ...(config.environment === undefined ? {} : { environment: config.environment }),\n ...(config.riskCollectors === undefined\n ? {}\n : { riskCollectors: config.riskCollectors }),\n ...(config.appearance === undefined ? {} : { appearance: config.appearance }),\n ...(config.threeDS === undefined ? {} : { threeDS: config.threeDS }),\n signal: abort.signal,\n onReady() {\n if (disposed) return;\n latestConfig.current.onReady?.();\n publish({ ...stateRef.current, status: 'READY', ready: true, isSubmitting: false });\n },\n onCardStateChange(state) {\n if (!disposed) latestConfig.current.onCardStateChange?.(state);\n },\n onStatusChange(status) {\n if (disposed) return;\n latestConfig.current.onStatusChange?.(status);\n publish({\n ...stateRef.current,\n status,\n ready: status !== 'MOUNTING' && status !== 'DESTROYED',\n isSubmitting: [\n 'TOKENIZING',\n 'SUBMITTING',\n 'AUTHENTICATING_3DS',\n 'PROCESSING'\n ].includes(status)\n });\n },\n onSuccess(payment) {\n if (disposed) return;\n latestConfig.current.onSuccess?.(payment);\n publish({ status: payment.status, ready: true, isSubmitting: false, payment });\n },\n onError(error) {\n if (disposed) return;\n latestConfig.current.onError?.(error);\n publish({ ...stateRef.current, isSubmitting: false, error });\n },\n onEvent(event: PaymentFormEvent) {\n if (!disposed) latestConfig.current.onEvent?.(event);\n }\n });\n if (disposed) {\n mounted.destroy();\n return;\n }\n instance = mounted;\n instanceRef.current = mounted;\n register?.(mounted);\n publish(mounted.getState());\n } catch (error: unknown) {\n if (disposed) return;\n const publicError = mountError(error);\n latestConfig.current.onError?.(publicError);\n publish({ ...stateRef.current, isSubmitting: false, error: publicError });\n }\n };\n // React Strict Mode runs a speculative effect setup/cleanup pair. Deferring\n // the imperative mount to a cancelable task lets that discarded pass clean\n // up before an iframe is inserted, so only the committed effect owns a Frame.\n const scheduledMount = window.setTimeout(() => {\n if (!disposed) void mount();\n }, 0);\n return () => {\n disposed = true;\n window.clearTimeout(scheduledMount);\n abort.abort();\n instance?.destroy();\n if (instanceRef.current === instance) instanceRef.current = undefined;\n register?.(undefined);\n target.replaceChildren();\n };\n }, [\n config.clientSecret,\n config.environment,\n config.threeDS?.presentation,\n appearanceSignature,\n riskCollectorsSignature,\n register,\n setProviderState\n ]);\n\n return <div ref={targetRef} className={props.className} data-bemony-payment-form=\"\" />;\n }\n);\n\nfunction completeConfig(value: BemonyPaymentFormProps): FormConfig {\n if (typeof value.clientSecret !== 'string' || value.clientSecret.length === 0) {\n throw new Error('BemonyPaymentForm exige clientSecret fora de BemonyPaymentFormProvider.');\n }\n return { ...value, clientSecret: value.clientSecret };\n}\n\nfunction notReady(): PaymentFormError {\n return { code: 'FORM_NOT_READY', message: 'O formul\u00E1rio de pagamento ainda n\u00E3o est\u00E1 pronto.' };\n}\n\nfunction mountError(error: unknown): PaymentFormError {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n 'message' in error &&\n typeof error.code === 'string' &&\n typeof error.message === 'string'\n ) {\n const details = error as Record<string, unknown>;\n return {\n code: error.code,\n message: error.message,\n ...(isErrorCategory(details.category) ? { category: details.category } : {}),\n ...(isErrorStage(details.stage) ? { stage: details.stage } : {})\n };\n }\n return {\n code: 'MOUNT_FAILED',\n message: 'N\u00E3o foi poss\u00EDvel montar o formul\u00E1rio de pagamento.',\n category: 'FRAME',\n stage: 'FORM_SDK'\n };\n}\n\nfunction stableSignature(value: unknown): string {\n if (value === undefined) return '';\n return JSON.stringify(value, (_key, item: unknown) => {\n if (item !== null && typeof item === 'object' && !Array.isArray(item)) {\n return Object.fromEntries(\n Object.entries(item as Record<string, unknown>).sort(([left], [right]) =>\n left.localeCompare(right)\n )\n );\n }\n return item;\n });\n}\n\nfunction isErrorCategory(value: unknown): value is NonNullable<PaymentFormError['category']> {\n return (\n typeof value === 'string' &&\n [\n 'VALIDATION',\n 'CONFIGURATION',\n 'LIFECYCLE',\n 'FRAME',\n 'TOKENIZATION',\n 'THREE_DS',\n 'PAYMENT',\n 'RUNTIME',\n 'UNKNOWN'\n ].includes(value)\n );\n}\n\nfunction isErrorStage(value: unknown): value is NonNullable<PaymentFormError['stage']> {\n return (\n typeof value === 'string' &&\n [\n 'FORM_SDK',\n 'FORM_IFRAME_NAVIGATION',\n 'FORM_HANDSHAKE',\n 'CARD_FRAME_DOCUMENT',\n 'CARD_FRAME_HANDSHAKE',\n 'CARD_FRAME_INITIALIZATION',\n 'CARD_TOKENIZATION',\n 'THREE_DS',\n 'PAYMENT_SUBMISSION',\n 'PAYMENT_RECONCILIATION',\n 'RUNTIME'\n ].includes(value)\n );\n}\n"],
5
- "mappings": ";AAEA;AAAA,EACE,qBAAqB;AAAA,OAahB;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAyCE;AAbT,IAAM,qBAAqB,cAAwC,MAAS;AAC5E,IAAM,gBAAkC,EAAE,QAAQ,YAAY,OAAO,OAAO,cAAc,MAAM;AAKzF,SAAS,0BAA0B,EAAE,UAAU,GAAG,OAAO,GAAmC;AACjG,QAAM,CAAC,UAAU,QAAQ,IAAI,SAA0C,MAAS;AAChF,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA2B,aAAa;AAClE,QAAM,QAAQ;AAAA,IACZ,OAAO,EAAE,QAAQ,UAAU,OAAO,UAAU,SAAS;AAAA,IACrD,CAAC,QAAQ,UAAU,KAAK;AAAA,EAC1B;AACA,SAAO,oBAAC,mBAAmB,UAAnB,EAA4B,OAAe,UAAS;AAC9D;AAEO,SAAS,uBAKb;AACD,QAAM,UAAU,WAAW,kBAAkB;AAC7C,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,0EA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IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,SAAS,KAAK;AAEpB;",
3
+ "sources": ["../src/components/payment-form.tsx", "../src/index.ts"],
4
+ "sourcesContent": ["'use client';\n\nimport {\n BemonyPaymentForm as WebPaymentForm,\n type CardState,\n type PayInput,\n type PayOutcome,\n type PaymentFormAppearance,\n type PaymentFormApiVersion,\n type PaymentFormCallbacks,\n type PaymentFormError,\n type PaymentFormEvent,\n type PaymentFormEnvironment,\n type PaymentFormInstance,\n type PaymentFormState,\n type RiskCollector,\n type ThreeDSPresentation\n} from '@bemony/payment-form';\nimport {\n createContext,\n forwardRef,\n useContext,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ReactNode\n} from 'react';\n\nexport type BemonyPaymentFormRef = Readonly<{\n pay(input: PayInput): Promise<PayOutcome>;\n getState(): PaymentFormState;\n destroy(): void;\n}>;\n\ntype FormConfig = PaymentFormCallbacks &\n Readonly<{\n clientSecret: string;\n environment?: PaymentFormEnvironment;\n version?: PaymentFormApiVersion;\n riskCollectors?: readonly RiskCollector[];\n appearance?: PaymentFormAppearance;\n threeDS?: Readonly<{ presentation?: ThreeDSPresentation }>;\n onCardStateChange?: (state: CardState) => void;\n }>;\n\nexport type BemonyPaymentFormProps = Partial<FormConfig> & Readonly<{ className?: string }>;\n\ntype ContextValue = Readonly<{\n config: FormConfig;\n instance?: PaymentFormInstance;\n state: PaymentFormState;\n register(instance: PaymentFormInstance | undefined): void;\n setState(state: PaymentFormState): void;\n}>;\n\nconst PaymentFormContext = createContext<ContextValue | undefined>(undefined);\nconst mountingState: PaymentFormState = { status: 'MOUNTING', ready: false, isSubmitting: false };\n\nexport type BemonyPaymentFormProviderProps = FormConfig & Readonly<{ children: ReactNode }>;\n\n/** Optional React-only convenience layer over the single Web SDK instance. */\nexport function BemonyPaymentFormProvider({ children, ...config }: BemonyPaymentFormProviderProps) {\n const [instance, register] = useState<PaymentFormInstance | undefined>(undefined);\n const [state, setState] = useState<PaymentFormState>(mountingState);\n const value = useMemo<ContextValue>(\n () => ({ config, instance, state, register, setState }),\n [config, instance, state]\n );\n return <PaymentFormContext.Provider value={value}>{children}</PaymentFormContext.Provider>;\n}\n\nexport function useBemonyPaymentForm(): Readonly<{\n ready: boolean;\n state: PaymentFormState;\n error: PaymentFormError | null;\n pay(input: PayInput): Promise<PayOutcome>;\n}> {\n const context = useContext(PaymentFormContext);\n if (context === undefined) {\n throw new Error('useBemonyPaymentForm deve ser usado dentro de BemonyPaymentFormProvider.');\n }\n return {\n ready: context.state.ready,\n state: context.state,\n error: context.state.error ?? null,\n pay(input) {\n return context.instance?.pay(input) ?? Promise.reject(notReady());\n }\n };\n}\n\n/**\n * Works standalone with a ref or as the mount point inside\n * BemonyPaymentFormProvider. Both paths mount the same Web SDK instance.\n */\nexport const BemonyPaymentForm = forwardRef<BemonyPaymentFormRef, BemonyPaymentFormProps>(\n function BemonyPaymentForm(props, ref) {\n const context = useContext(PaymentFormContext);\n const config = context?.config ?? completeConfig(props);\n const register = context?.register;\n const setProviderState = context?.setState;\n const targetRef = useRef<HTMLDivElement>(null);\n const instanceRef = useRef<PaymentFormInstance | undefined>(undefined);\n const stateRef = useRef<PaymentFormState>(mountingState);\n const latestConfig = useRef(config);\n latestConfig.current = config;\n // Parent components often recreate appearance/collector objects inline.\n // Reference-only dependencies would unnecessarily reload the secure iframe\n // on ordinary React state changes. Remount only on semantic changes.\n const appearanceSignature = stableSignature(config.appearance);\n const riskCollectorsSignature = stableSignature(config.riskCollectors);\n\n useImperativeHandle(\n ref,\n () => ({\n pay(input) {\n return instanceRef.current?.pay(input) ?? Promise.reject(notReady());\n },\n getState() {\n return instanceRef.current?.getState() ?? stateRef.current;\n },\n destroy() {\n instanceRef.current?.destroy();\n instanceRef.current = undefined;\n register?.(undefined);\n }\n }),\n [register]\n );\n\n useEffect(() => {\n const target = targetRef.current;\n if (target === null) return;\n const abort = new AbortController();\n let disposed = false;\n let instance: PaymentFormInstance | undefined;\n const publish = (next: PaymentFormState): void => {\n stateRef.current = next;\n setProviderState?.(next);\n };\n const mount = async (): Promise<void> => {\n try {\n const mounted = await WebPaymentForm.mount({\n target,\n clientSecret: config.clientSecret,\n ...(config.environment === undefined ? {} : { environment: config.environment }),\n ...(config.version === undefined ? {} : { version: config.version }),\n ...(config.riskCollectors === undefined\n ? {}\n : { riskCollectors: config.riskCollectors }),\n ...(config.appearance === undefined ? {} : { appearance: config.appearance }),\n ...(config.threeDS === undefined ? {} : { threeDS: config.threeDS }),\n signal: abort.signal,\n onReady() {\n if (disposed) return;\n latestConfig.current.onReady?.();\n publish({ ...stateRef.current, status: 'READY', ready: true, isSubmitting: false });\n },\n onCardStateChange(state) {\n if (!disposed) latestConfig.current.onCardStateChange?.(state);\n },\n onStatusChange(status) {\n if (disposed) return;\n latestConfig.current.onStatusChange?.(status);\n publish({\n ...stateRef.current,\n status,\n ready: status !== 'MOUNTING' && status !== 'DESTROYED',\n isSubmitting: [\n 'TOKENIZING',\n 'SUBMITTING',\n 'AUTHENTICATING_3DS',\n 'PROCESSING'\n ].includes(status)\n });\n },\n onSuccess(payment) {\n if (disposed) return;\n latestConfig.current.onSuccess?.(payment);\n publish({ status: payment.status, ready: true, isSubmitting: false, payment });\n },\n onError(error) {\n if (disposed) return;\n latestConfig.current.onError?.(error);\n publish({ ...stateRef.current, isSubmitting: false, error });\n },\n onEvent(event: PaymentFormEvent) {\n if (!disposed) latestConfig.current.onEvent?.(event);\n }\n });\n if (disposed) {\n mounted.destroy();\n return;\n }\n instance = mounted;\n instanceRef.current = mounted;\n register?.(mounted);\n publish(mounted.getState());\n } catch (error: unknown) {\n if (disposed) return;\n const publicError = mountError(error);\n latestConfig.current.onError?.(publicError);\n publish({ ...stateRef.current, isSubmitting: false, error: publicError });\n }\n };\n // React Strict Mode runs a speculative effect setup/cleanup pair. Deferring\n // the imperative mount to a cancelable task lets that discarded pass clean\n // up before an iframe is inserted, so only the committed effect owns a Frame.\n const scheduledMount = window.setTimeout(() => {\n if (!disposed) void mount();\n }, 0);\n return () => {\n disposed = true;\n window.clearTimeout(scheduledMount);\n abort.abort();\n instance?.destroy();\n if (instanceRef.current === instance) instanceRef.current = undefined;\n register?.(undefined);\n target.replaceChildren();\n };\n }, [\n config.clientSecret,\n config.environment,\n config.version,\n config.threeDS?.presentation,\n appearanceSignature,\n riskCollectorsSignature,\n register,\n setProviderState\n ]);\n\n return <div ref={targetRef} className={props.className} data-bemony-payment-form=\"\" />;\n }\n);\n\nfunction completeConfig(value: BemonyPaymentFormProps): FormConfig {\n if (typeof value.clientSecret !== 'string' || value.clientSecret.length === 0) {\n throw new Error('BemonyPaymentForm exige clientSecret fora de BemonyPaymentFormProvider.');\n }\n return { ...value, clientSecret: value.clientSecret };\n}\n\nfunction notReady(): PaymentFormError {\n return { code: 'FORM_NOT_READY', message: 'O formul\u00E1rio de pagamento ainda n\u00E3o est\u00E1 pronto.' };\n}\n\nfunction mountError(error: unknown): PaymentFormError {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n 'message' in error &&\n typeof error.code === 'string' &&\n typeof error.message === 'string'\n ) {\n const details = error as Record<string, unknown>;\n return {\n ...(isApiErrorType(details.type) ? { type: details.type } : {}),\n code: error.code,\n message: error.message,\n ...(isErrorField(details.field) ? { field: details.field } : {}),\n ...(isPublicErrorDetails(details.details) ? { details: details.details } : {}),\n ...(isErrorCategory(details.category) ? { category: details.category } : {}),\n ...(isErrorStage(details.stage) ? { stage: details.stage } : {}),\n ...(isText(details.requestId) ? { requestId: details.requestId } : {}),\n ...(isText(details.commandId) ? { commandId: details.commandId } : {}),\n ...(isText(details.paymentId) ? { paymentId: details.paymentId } : {}),\n ...(typeof details.retryable === 'boolean' ? { retryable: details.retryable } : {}),\n ...(isHttpStatus(details.httpStatus) ? { httpStatus: details.httpStatus } : {}),\n ...(isText(details.upstreamRequestId)\n ? { upstreamRequestId: details.upstreamRequestId }\n : {}),\n ...(details.frameStage === 'FRAME_DOCUMENT' || details.frameStage === 'CARD_FRAME'\n ? { frameStage: details.frameStage }\n : {})\n };\n }\n return {\n code: 'MOUNT_FAILED',\n message: 'N\u00E3o foi poss\u00EDvel montar o formul\u00E1rio de pagamento.',\n category: 'FRAME',\n stage: 'FORM_SDK'\n };\n}\n\nfunction isApiErrorType(value: unknown): value is NonNullable<PaymentFormError['type']> {\n return (\n typeof value === 'string' &&\n [\n 'authentication_error',\n 'authorization_error',\n 'validation_error',\n 'idempotency_error',\n 'rate_limit_error',\n 'conflict_error',\n 'internal_error',\n 'not_found'\n ].includes(value)\n );\n}\n\nfunction isErrorField(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= 256;\n}\n\nfunction isText(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= 1_000;\n}\n\nfunction isHttpStatus(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 400 && value <= 599;\n}\n\nfunction isPublicErrorDetails(value: unknown): value is NonNullable<PaymentFormError['details']> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n try {\n return JSON.stringify(value).length <= 16_384;\n } catch {\n return false;\n }\n}\n\nfunction stableSignature(value: unknown): string {\n if (value === undefined) return '';\n return JSON.stringify(value, (_key, item: unknown) => {\n if (item !== null && typeof item === 'object' && !Array.isArray(item)) {\n return Object.fromEntries(\n Object.entries(item as Record<string, unknown>).sort(([left], [right]) =>\n left.localeCompare(right)\n )\n );\n }\n return item;\n });\n}\n\nfunction isErrorCategory(value: unknown): value is NonNullable<PaymentFormError['category']> {\n return (\n typeof value === 'string' &&\n [\n 'VALIDATION',\n 'CONFIGURATION',\n 'LIFECYCLE',\n 'FRAME',\n 'TOKENIZATION',\n 'THREE_DS',\n 'PAYMENT',\n 'RUNTIME',\n 'UNKNOWN'\n ].includes(value)\n );\n}\n\nfunction isErrorStage(value: unknown): value is NonNullable<PaymentFormError['stage']> {\n return (\n typeof value === 'string' &&\n [\n 'FORM_SDK',\n 'FORM_IFRAME_NAVIGATION',\n 'FORM_HANDSHAKE',\n 'CARD_FRAME_DOCUMENT',\n 'CARD_FRAME_HANDSHAKE',\n 'CARD_FRAME_INITIALIZATION',\n 'CARD_TOKENIZATION',\n 'THREE_DS',\n 'PAYMENT_SUBMISSION',\n 'PAYMENT_RECONCILIATION',\n 'RUNTIME'\n ].includes(value)\n );\n}\n", "export {\n BemonyPaymentForm,\n BemonyPaymentFormProvider,\n useBemonyPaymentForm\n} from './components/payment-form';\nexport { DEFAULT_PAYMENT_FORM_API_VERSION, PAYMENT_FORM_API_VERSION } from '@bemony/payment-form';\nexport type {\n BemonyPaymentFormProps,\n BemonyPaymentFormProviderProps,\n BemonyPaymentFormRef\n} from './components/payment-form';\nexport type {\n Address,\n CardStorageConsent,\n CheckoutClient,\n CommerceContext,\n Customer,\n CustomerHistory,\n PayInput,\n PayOutcome,\n PaymentAmounts,\n PaymentItem,\n PaymentFormAppearance,\n PaymentFormApiVersion,\n PaymentFormApiErrorType,\n PaymentFormError,\n PaymentFormErrorAttempt,\n PaymentFormErrorDetails,\n PaymentFormErrorDetailValue,\n PaymentFormEvent,\n PaymentFormErrorPayment,\n PaymentFormEnvironment,\n PaymentFormState,\n PaymentFormStatus,\n RiskCollector,\n ShippingAddress,\n ThreeDSPresentation\n} from '@bemony/payment-form';\n"],
5
+ "mappings": ";AAEA;AAAA,EACE,qBAAqB;AAAA,OAchB;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA0CE;AAbT,IAAM,qBAAqB,cAAwC,MAAS;AAC5E,IAAM,gBAAkC,EAAE,QAAQ,YAAY,OAAO,OAAO,cAAc,MAAM;AAKzF,SAAS,0BAA0B,EAAE,UAAU,GAAG,OAAO,GAAmC;AACjG,QAAM,CAAC,UAAU,QAAQ,IAAI,SAA0C,MAAS;AAChF,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA2B,aAAa;AAClE,QAAM,QAAQ;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,OAAO,CAAC,MAAM,SAAkB;AACpD,QAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI,GAAG;AACrE,aAAO,OAAO;AAAA,QACZ,OAAO,QAAQ,IAA+B,EAAE;AAAA,UAAK,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,MAClE,KAAK,cAAc,KAAK;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,SAAS,gBAAgB,OAAoE;AAC3F,SACE,OAAO,UAAU,YACjB;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,SAAS,KAAK;AAEpB;AAEA,SAAS,aAAa,OAAiE;AACrF,SACE,OAAO,UAAU,YACjB;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,SAAS,KAAK;AAEpB;;;AC/WA,SAAS,kCAAkC,gCAAgC;",
6
6
  "names": ["BemonyPaymentForm"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bemony/payment-form-react",
3
- "version": "0.2.0-next.0",
3
+ "version": "0.2.0-next.2",
4
4
  "description": "Official React adapter for the hosted Bemony Payment Form.",
5
5
  "keywords": [
6
6
  "bemony",
@@ -33,8 +33,17 @@
33
33
  "default": "./dist/index.js"
34
34
  }
35
35
  },
36
+ "scripts": {
37
+ "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.build.json && esbuild ./src/index.ts --bundle --format=esm --platform=browser --target=es2022 --packages=external --sourcemap --outfile=dist/index.js && pnpm run verify:dist",
38
+ "verify:dist": "node ../../scripts/verify-payment-form-react-package.mjs",
39
+ "prepack": "pnpm run build",
40
+ "prepublishOnly": "node ../../scripts/verify-payment-form-release-source.mjs @bemony/payment-form-react",
41
+ "lint": "eslint src",
42
+ "typecheck": "tsc --noEmit -p tsconfig.json",
43
+ "test": "vitest run --passWithNoTests"
44
+ },
36
45
  "dependencies": {
37
- "@bemony/payment-form": "^0.2.0-next.0"
46
+ "@bemony/payment-form": "^0.2.0-next.2"
38
47
  },
39
48
  "peerDependencies": {
40
49
  "react": ">=19.0.0 <20.0.0",
@@ -46,12 +55,5 @@
46
55
  "publishConfig": {
47
56
  "registry": "https://registry.npmjs.org/",
48
57
  "access": "public"
49
- },
50
- "scripts": {
51
- "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.build.json && esbuild ./src/index.ts --bundle --format=esm --platform=browser --target=es2022 --packages=external --sourcemap --outfile=dist/index.js && pnpm run verify:dist",
52
- "verify:dist": "node ../../scripts/verify-payment-form-react-package.mjs",
53
- "lint": "eslint src",
54
- "typecheck": "tsc --noEmit -p tsconfig.json",
55
- "test": "vitest run --passWithNoTests"
56
58
  }
57
- }
59
+ }