@sunbay/checkout-sdk-react 0.0.0-stage → 0.5.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,581 @@
1
+ "use client";
2
+
3
+ // src/CheckoutProvider.tsx
4
+ import * as React from "react";
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6
+ import { createCheckout, ErrorCode } from "@sunbay/checkout-sdk-js";
7
+
8
+ // src/context.ts
9
+ import { createContext } from "react";
10
+ var CheckoutContext = createContext(null);
11
+
12
+ // src/internal/env.ts
13
+ var isDevelopment = typeof process !== "undefined" && process.env.NODE_ENV !== "production";
14
+
15
+ // src/internal/parity.ts
16
+ var CREATE_OPTION_KINDS = {
17
+ sessionId: "identity",
18
+ checkoutClientSecret: "identity",
19
+ customerAccessSecret: "identity",
20
+ env: "identity",
21
+ hostOrigin: "identity",
22
+ locale: "updatable",
23
+ appearance: "updatable",
24
+ billingAddress: "updatable",
25
+ shippingAddress: "updatable",
26
+ paymentMethods: "creationOnly",
27
+ signal: "internal",
28
+ __transportFactory: "internal"
29
+ };
30
+ function keysOfKind(kind) {
31
+ return Object.keys(CREATE_OPTION_KINDS).filter(
32
+ (k) => CREATE_OPTION_KINDS[k] === kind
33
+ );
34
+ }
35
+ var IDENTITY_KEYS = keysOfKind("identity");
36
+ var UPDATABLE_KEYS = keysOfKind("updatable");
37
+
38
+ // src/internal/structuralEqual.ts
39
+ function isPlainObject(x) {
40
+ const proto = Object.getPrototypeOf(x);
41
+ return proto === Object.prototype || proto === null;
42
+ }
43
+ function structuralEqual(a, b) {
44
+ if (Object.is(a, b)) {
45
+ return true;
46
+ }
47
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
48
+ return false;
49
+ }
50
+ const aIsArray = Array.isArray(a);
51
+ if (aIsArray !== Array.isArray(b)) {
52
+ return false;
53
+ }
54
+ if (!aIsArray && !(isPlainObject(a) && isPlainObject(b))) {
55
+ return false;
56
+ }
57
+ if (aIsArray) {
58
+ const x2 = a;
59
+ const y2 = b;
60
+ return x2.length === y2.length && x2.every((item, i) => structuralEqual(item, y2[i]));
61
+ }
62
+ const x = a;
63
+ const y = b;
64
+ const keys = Object.keys(x);
65
+ if (keys.length !== Object.keys(y).length) {
66
+ return false;
67
+ }
68
+ return keys.every(
69
+ (k) => Object.prototype.hasOwnProperty.call(y, k) && structuralEqual(x[k], y[k])
70
+ );
71
+ }
72
+
73
+ // src/CheckoutProvider.tsx
74
+ function identityValues(o) {
75
+ return IDENTITY_KEYS.map((k) => o[k] ?? null);
76
+ }
77
+ function pickUpdatable(o) {
78
+ const picked = {};
79
+ UPDATABLE_KEYS.forEach((k) => {
80
+ picked[k] = o[k];
81
+ });
82
+ return picked;
83
+ }
84
+ function CheckoutProvider(props) {
85
+ const { options, children } = props;
86
+ const identityRef = useRef(null);
87
+ const values = identityValues(options);
88
+ if (identityRef.current === null) {
89
+ identityRef.current = { values, generation: 0 };
90
+ } else if (!structuralEqual(identityRef.current.values, values)) {
91
+ identityRef.current = { values, generation: identityRef.current.generation + 1 };
92
+ }
93
+ const key = identityRef.current.generation;
94
+ const [state, setState] = useState({
95
+ key,
96
+ checkout: null,
97
+ status: "loading",
98
+ error: null
99
+ });
100
+ const optionsRef = useRef(options);
101
+ optionsRef.current = options;
102
+ const onErrorRef = useRef(props.onError);
103
+ onErrorRef.current = props.onError;
104
+ const onWarningRef = useRef(props.onWarning);
105
+ onWarningRef.current = props.onWarning;
106
+ const appliedRef = useRef(
107
+ pickUpdatable(options)
108
+ );
109
+ const destroyedRef = useRef(/* @__PURE__ */ new WeakSet());
110
+ const subscribersRef = useRef(/* @__PURE__ */ new Set());
111
+ const recordRef = useRef({ buffer: [], delivered: /* @__PURE__ */ new WeakMap() });
112
+ const deliver = useCallback((handler) => {
113
+ const record = recordRef.current;
114
+ let index = record.delivered.get(handler) ?? 0;
115
+ while (index < record.buffer.length) {
116
+ const w = record.buffer[index];
117
+ index += 1;
118
+ record.delivered.set(handler, index);
119
+ handler(w);
120
+ }
121
+ }, []);
122
+ const subscribeWarning = useCallback(
123
+ (handler) => {
124
+ subscribersRef.current.add(handler);
125
+ deliver(handler);
126
+ return () => {
127
+ subscribersRef.current.delete(handler);
128
+ };
129
+ },
130
+ [deliver]
131
+ );
132
+ useEffect(() => {
133
+ const forward = (w) => onWarningRef.current?.(w);
134
+ return subscribeWarning(forward);
135
+ }, [subscribeWarning]);
136
+ useEffect(() => {
137
+ const controller = new AbortController();
138
+ let cancelled = false;
139
+ let instance = null;
140
+ const record = { buffer: [], delivered: /* @__PURE__ */ new WeakMap() };
141
+ recordRef.current = record;
142
+ appliedRef.current = pickUpdatable(optionsRef.current);
143
+ const onInstanceWarning = (w) => {
144
+ record.buffer.push(w);
145
+ subscribersRef.current.forEach((h) => deliver(h));
146
+ };
147
+ setState(
148
+ (prev) => prev.key === key && prev.status === "loading" && prev.checkout === null ? prev : { key, checkout: null, status: "loading", error: null }
149
+ );
150
+ createCheckout({ ...optionsRef.current, signal: controller.signal }).then(
151
+ (created) => {
152
+ if (cancelled) {
153
+ created.destroy();
154
+ return;
155
+ }
156
+ instance = created;
157
+ created.on("warning", onInstanceWarning);
158
+ setState({ key, checkout: created, status: "ready", error: null });
159
+ },
160
+ (err) => {
161
+ if (cancelled) {
162
+ return;
163
+ }
164
+ const error2 = err;
165
+ if (error2 && error2.code === ErrorCode.CANCELLED) {
166
+ return;
167
+ }
168
+ setState({ key, checkout: null, status: "error", error: error2 });
169
+ onErrorRef.current?.(error2);
170
+ }
171
+ );
172
+ return () => {
173
+ cancelled = true;
174
+ controller.abort();
175
+ if (instance) {
176
+ destroyedRef.current.add(instance);
177
+ instance.off("warning", onInstanceWarning);
178
+ instance.destroy();
179
+ }
180
+ };
181
+ }, [key, deliver]);
182
+ const current = state.key === key ? state.checkout : null;
183
+ useEffect(() => {
184
+ if (!current) {
185
+ return;
186
+ }
187
+ const next = pickUpdatable(optionsRef.current);
188
+ const patch = {};
189
+ const sent = [];
190
+ let advanced = false;
191
+ for (const k of UPDATABLE_KEYS) {
192
+ if (!structuralEqual(appliedRef.current[k], next[k])) {
193
+ advanced = true;
194
+ if (next[k] !== void 0) {
195
+ patch[k] = next[k];
196
+ sent.push(k);
197
+ }
198
+ }
199
+ }
200
+ if (!advanced) {
201
+ return;
202
+ }
203
+ const previous = appliedRef.current;
204
+ appliedRef.current = next;
205
+ if (sent.length === 0) {
206
+ return;
207
+ }
208
+ const onFailure = (failure) => {
209
+ if (destroyedRef.current.has(current)) {
210
+ return;
211
+ }
212
+ const restored = { ...appliedRef.current };
213
+ for (const k of sent) {
214
+ if (structuralEqual(appliedRef.current[k], next[k])) {
215
+ restored[k] = previous[k];
216
+ }
217
+ }
218
+ appliedRef.current = restored;
219
+ if (isDevelopment) {
220
+ const code = failure?.code;
221
+ console.warn(
222
+ `[checkout-sdk-react] updateCheckout failed (code: ${typeof code === "string" ? code : "UNKNOWN"}). It will be retried on the next render.`
223
+ );
224
+ }
225
+ };
226
+ let pending;
227
+ try {
228
+ pending = Promise.resolve(current.updateCheckout(patch));
229
+ } catch (failure) {
230
+ pending = Promise.reject(failure);
231
+ }
232
+ pending.catch(onFailure);
233
+ });
234
+ const initialPaymentMethods = useRef(options.paymentMethods);
235
+ const warnedRef = useRef(false);
236
+ useEffect(() => {
237
+ if (!warnedRef.current && isDevelopment && !structuralEqual(initialPaymentMethods.current, options.paymentMethods)) {
238
+ warnedRef.current = true;
239
+ console.warn(
240
+ "[checkout-sdk-react] `paymentMethods` is read only when the checkout is created. Changing it later has no effect."
241
+ );
242
+ }
243
+ });
244
+ const stale = state.key !== key;
245
+ const checkout = stale ? null : state.checkout;
246
+ const status = stale ? "loading" : state.status;
247
+ const error = stale ? null : state.error;
248
+ const value = useMemo(
249
+ () => ({ checkout, status, error, subscribeWarning }),
250
+ [checkout, status, error, subscribeWarning]
251
+ );
252
+ return /* @__PURE__ */ React.createElement(CheckoutContext.Provider, { value }, children);
253
+ }
254
+
255
+ // src/hooks/useCheckout.ts
256
+ import { useContext } from "react";
257
+ function useCheckout() {
258
+ const ctx = useContext(CheckoutContext);
259
+ if (!ctx) {
260
+ throw new Error("useCheckout must be used within <CheckoutProvider>");
261
+ }
262
+ return { checkout: ctx.checkout, status: ctx.status, error: ctx.error };
263
+ }
264
+
265
+ // src/hooks/useCheckoutEvent.ts
266
+ import { useContext as useContext2, useEffect as useEffect2, useRef as useRef2 } from "react";
267
+ function useCheckoutEvent(name, handler) {
268
+ const ctx = useContext2(CheckoutContext);
269
+ if (!ctx) {
270
+ throw new Error("useCheckoutEvent must be used within <CheckoutProvider>");
271
+ }
272
+ const { checkout, subscribeWarning } = ctx;
273
+ const handlerRef = useRef2(handler);
274
+ useEffect2(() => {
275
+ handlerRef.current = handler;
276
+ });
277
+ useEffect2(() => {
278
+ if (name === "warning") {
279
+ return subscribeWarning((w) => handlerRef.current(w));
280
+ }
281
+ if (!checkout) {
282
+ return void 0;
283
+ }
284
+ const listener = (payload) => handlerRef.current(payload);
285
+ checkout.on(name, listener);
286
+ return () => {
287
+ checkout.off(name, listener);
288
+ };
289
+ }, [checkout, name, subscribeWarning]);
290
+ }
291
+
292
+ // src/elements/createElementComponent.tsx
293
+ import * as React2 from "react";
294
+ import { forwardRef, useContext as useContext3, useEffect as useEffect3, useRef as useRef3, useState as useState2 } from "react";
295
+ import { ErrorCode as ErrorCode2 } from "@sunbay/checkout-sdk-js";
296
+
297
+ // src/elements/updatableOptions.ts
298
+ var UPDATABLE_OPTION_KEYS = {
299
+ card: [],
300
+ cardNumber: [],
301
+ cardExpiry: [],
302
+ cardCvc: [],
303
+ address: [],
304
+ expressCheckout: ["paymentMethods", "layout", "buttonHeight"]
305
+ };
306
+
307
+ // src/elements/createElementComponent.tsx
308
+ function codeOf(e) {
309
+ const code = e?.code;
310
+ return typeof code === "string" ? code : "UNKNOWN";
311
+ }
312
+ function assignRef(ref, value) {
313
+ if (typeof ref === "function") {
314
+ ref(value);
315
+ } else if (ref) {
316
+ ref.current = value;
317
+ }
318
+ }
319
+ function recreateKeyOf(options, updatable) {
320
+ const entries = Object.keys(options ?? {}).filter((k) => !updatable.includes(k) && options?.[k] !== void 0).sort().map((k) => [k, options?.[k]]);
321
+ return JSON.stringify(entries);
322
+ }
323
+ function createElementComponent(type, displayName) {
324
+ const updatable = UPDATABLE_OPTION_KEYS[type];
325
+ const Component = forwardRef(function ElementComponent(props, ref) {
326
+ const ctx = useContext3(CheckoutContext);
327
+ const checkout = ctx ? ctx.checkout : null;
328
+ const divRef = useRef3(null);
329
+ const propsRef = useRef3(props);
330
+ propsRef.current = props;
331
+ const refRef = useRef3(ref);
332
+ refRef.current = ref;
333
+ const appliedRef = useRef3({});
334
+ const elementRef = useRef3(null);
335
+ const assignedRefRef = useRef3(null);
336
+ const [generation, setGeneration] = useState2(0);
337
+ const recreateKey = recreateKeyOf(props.options, updatable);
338
+ useEffect3(() => {
339
+ const div = divRef.current;
340
+ if (!checkout || !div) {
341
+ return;
342
+ }
343
+ let cancelled = false;
344
+ const reportedIds = /* @__PURE__ */ new Set();
345
+ const reportedErrors = /* @__PURE__ */ new WeakSet();
346
+ let loadErrorReported = false;
347
+ const report = (error, source) => {
348
+ if (cancelled || source === "mount" && loadErrorReported) {
349
+ return;
350
+ }
351
+ const errorId = error?.errorId;
352
+ if (typeof errorId === "string") {
353
+ if (reportedIds.has(errorId)) {
354
+ return;
355
+ }
356
+ reportedIds.add(errorId);
357
+ } else if (error !== null && typeof error === "object") {
358
+ if (reportedErrors.has(error)) {
359
+ return;
360
+ }
361
+ reportedErrors.add(error);
362
+ }
363
+ if (source === "event") {
364
+ loadErrorReported = true;
365
+ }
366
+ if (codeOf(error) === ErrorCode2.ELEMENT_CONFLICT && isDevelopment) {
367
+ console.error(
368
+ `[checkout-sdk-react] <${displayName}> could not be created (code: ELEMENT_CONFLICT). Card Elements are mutually exclusive.`
369
+ );
370
+ }
371
+ propsRef.current.onLoadError?.(error);
372
+ };
373
+ let element;
374
+ try {
375
+ element = checkout.create(type, propsRef.current.options);
376
+ } catch (error) {
377
+ report(error, "create");
378
+ return;
379
+ }
380
+ appliedRef.current = { ...propsRef.current.options ?? {} };
381
+ elementRef.current = element;
382
+ assignedRefRef.current = refRef.current;
383
+ assignRef(refRef.current, element);
384
+ element.on("elementReady", (e) => propsRef.current.onReady?.(e));
385
+ element.on("change", (e) => propsRef.current.onChange?.(e));
386
+ element.on("focus", (e) => propsRef.current.onFocus?.(e));
387
+ element.on("blur", (e) => propsRef.current.onBlur?.(e));
388
+ element.on("loadError", (e) => report(e.error, "event"));
389
+ if (type === "expressCheckout") {
390
+ element.on(
391
+ "expressAvailabilityChange",
392
+ (e) => propsRef.current.onAvailabilityChange?.(e.availableWallets)
393
+ );
394
+ }
395
+ element.mount(div).catch((error) => {
396
+ const code = codeOf(error);
397
+ if (code === ErrorCode2.CANCELLED || code === ErrorCode2.INSTANCE_DESTROYED) {
398
+ return;
399
+ }
400
+ report(error, "mount");
401
+ });
402
+ return () => {
403
+ cancelled = true;
404
+ elementRef.current = null;
405
+ assignRef(assignedRefRef.current, null);
406
+ assignedRefRef.current = null;
407
+ element.destroy();
408
+ };
409
+ }, [checkout, recreateKey, generation]);
410
+ useEffect3(() => {
411
+ const assigned = assignedRefRef.current;
412
+ if (!assigned || assigned === ref) {
413
+ return;
414
+ }
415
+ assignRef(assigned, null);
416
+ assignRef(ref, elementRef.current);
417
+ assignedRefRef.current = ref;
418
+ }, [ref]);
419
+ useEffect3(() => {
420
+ const element = elementRef.current;
421
+ if (!element) {
422
+ return;
423
+ }
424
+ const next = propsRef.current.options ?? {};
425
+ const applied = appliedRef.current;
426
+ const patch = {};
427
+ let changed = false;
428
+ let removed = false;
429
+ updatable.forEach((k) => {
430
+ if (structuralEqual(applied[k], next[k])) {
431
+ return;
432
+ }
433
+ changed = true;
434
+ if (next[k] === void 0) {
435
+ removed = true;
436
+ } else {
437
+ patch[k] = next[k];
438
+ }
439
+ });
440
+ if (!changed) {
441
+ return;
442
+ }
443
+ if (removed) {
444
+ setGeneration((g) => g + 1);
445
+ return;
446
+ }
447
+ appliedRef.current = { ...next };
448
+ const onFailure = (failure) => {
449
+ if (elementRef.current !== element) {
450
+ return;
451
+ }
452
+ if (isDevelopment) {
453
+ console.warn(
454
+ `[checkout-sdk-react] <${displayName}> update failed (code: ${codeOf(failure)}). The Element is recreated with the current options.`
455
+ );
456
+ }
457
+ setGeneration((g) => g + 1);
458
+ };
459
+ try {
460
+ Promise.resolve(element.update(patch)).catch(onFailure);
461
+ } catch (failure) {
462
+ onFailure(failure);
463
+ }
464
+ });
465
+ return /* @__PURE__ */ React2.createElement("div", { ref: divRef, id: props.id, className: props.className, style: props.style });
466
+ });
467
+ Component.displayName = displayName;
468
+ return Component;
469
+ }
470
+
471
+ // src/elements/index.tsx
472
+ var CardElement = createElementComponent("card", "CardElement");
473
+ var CardNumberElement = createElementComponent("cardNumber", "CardNumberElement");
474
+ var CardExpiryElement = createElementComponent("cardExpiry", "CardExpiryElement");
475
+ var CardCvcElement = createElementComponent("cardCvc", "CardCvcElement");
476
+ var AddressElement = createElementComponent("address", "AddressElement");
477
+ var ExpressCheckoutElement = createElementComponent("expressCheckout", "ExpressCheckoutElement");
478
+
479
+ // src/hooks/useConfirm.ts
480
+ import { useCallback as useCallback2, useEffect as useEffect4, useRef as useRef4, useState as useState3 } from "react";
481
+ function notReadyError() {
482
+ const rand = Math.random().toString(36).slice(2, 10) || "0";
483
+ return {
484
+ code: "INVALID_OPTIONS",
485
+ category: "configuration",
486
+ message: "Checkout is not ready",
487
+ errorId: `err_${Date.now().toString(36)}_${rand}`
488
+ };
489
+ }
490
+ function useConfirm() {
491
+ const { checkout } = useCheckout();
492
+ const checkoutRef = useRef4(checkout);
493
+ useEffect4(() => {
494
+ checkoutRef.current = checkout;
495
+ }, [checkout]);
496
+ const mounted = useRef4(true);
497
+ useEffect4(() => {
498
+ mounted.current = true;
499
+ return () => {
500
+ mounted.current = false;
501
+ };
502
+ }, []);
503
+ const activeCall = useRef4(0);
504
+ const nextCall = useRef4(0);
505
+ const [isConfirming, setIsConfirming] = useState3(false);
506
+ const [outcome, setOutcome] = useState3(null);
507
+ const [error, setError] = useState3(null);
508
+ const confirm = useCallback2((opts) => {
509
+ const instance = checkoutRef.current;
510
+ const owner = activeCall.current === 0;
511
+ if (owner && mounted.current) {
512
+ setOutcome(null);
513
+ setError(null);
514
+ }
515
+ if (!instance) {
516
+ const err = notReadyError();
517
+ if (owner && mounted.current) {
518
+ setError(err);
519
+ }
520
+ return Promise.reject(err);
521
+ }
522
+ const id = ++nextCall.current;
523
+ let promise;
524
+ try {
525
+ promise = instance.confirm(opts);
526
+ } catch (e) {
527
+ promise = Promise.reject(e);
528
+ }
529
+ if (owner) {
530
+ activeCall.current = id;
531
+ if (mounted.current) {
532
+ setIsConfirming(true);
533
+ }
534
+ }
535
+ const finish = () => {
536
+ if (owner && activeCall.current === id) {
537
+ activeCall.current = 0;
538
+ if (mounted.current) {
539
+ setIsConfirming(false);
540
+ }
541
+ }
542
+ };
543
+ return promise.then(
544
+ (result) => {
545
+ finish();
546
+ if (owner && mounted.current) {
547
+ setOutcome(result);
548
+ }
549
+ return result;
550
+ },
551
+ (err) => {
552
+ finish();
553
+ if (owner && mounted.current) {
554
+ setError(err);
555
+ }
556
+ throw err;
557
+ }
558
+ );
559
+ }, []);
560
+ return { confirm, isConfirming, outcome, error };
561
+ }
562
+
563
+ // src/index.ts
564
+ import { ErrorCode as ErrorCode3, WARNING_CODES } from "@sunbay/checkout-sdk-js";
565
+ var version = true ? "0.5.0" : "0.0.0";
566
+ export {
567
+ AddressElement,
568
+ CardCvcElement,
569
+ CardElement,
570
+ CardExpiryElement,
571
+ CardNumberElement,
572
+ CheckoutProvider,
573
+ ErrorCode3 as ErrorCode,
574
+ ExpressCheckoutElement,
575
+ WARNING_CODES,
576
+ useCheckout,
577
+ useCheckoutEvent,
578
+ useConfirm,
579
+ version
580
+ };
581
+ //# sourceMappingURL=index.mjs.map