@easypayment/medusa-paypal-ui 1.2.0 → 1.2.3

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/src/order.ts CHANGED
@@ -1,134 +1,140 @@
1
- /**
2
- * Server-safe helpers for displaying PayPal payments on order / confirmation
3
- * pages.
4
- *
5
- * This module is intentionally free of React and any client-only code, so it
6
- * can be imported from Next.js **server components** (e.g. the order
7
- * confirmation page) without pulling in the checkout UI.
8
- *
9
- * @example
10
- * import { getPaymentLabel, fetchPayPalConfig } from "@easypayment/medusa-paypal-ui/order"
11
- *
12
- * // In the (async) server component that renders the payment method:
13
- * const titles = await fetchPayPalConfig({
14
- * baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!,
15
- * publishableApiKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
16
- * })
17
- *
18
- * <Text>
19
- * {getPaymentLabel(
20
- * payment.provider_id,
21
- * paymentInfoMap[payment.provider_id]?.title,
22
- * titles
23
- * )}
24
- * </Text>
25
- */
26
-
27
- import {
28
- PAYPAL_WALLET_PROVIDER_ID,
29
- PAYPAL_CARD_PROVIDER_ID,
30
- isPayPalProviderId,
31
- } from "./constants"
32
-
33
- export { PAYPAL_WALLET_PROVIDER_ID, PAYPAL_CARD_PROVIDER_ID, isPayPalProviderId }
34
-
35
- export type PayPalPaymentInfo = { title: string }
36
-
37
- /** Built-in fallback titles, used only when admin titles aren't supplied. */
38
- export const paypalPaymentInfoMap: Record<string, PayPalPaymentInfo> = {
39
- [PAYPAL_WALLET_PROVIDER_ID]: { title: "PayPal" },
40
- [PAYPAL_CARD_PROVIDER_ID]: { title: "Credit or Debit Card" },
41
- }
42
-
43
- /** Admin-configured titles, as returned by `GET /store/paypal/config`. */
44
- export type PayPalConfigTitles = {
45
- paypal_title?: string | null
46
- card_title?: string | null
47
- }
48
-
49
- /**
50
- * Null-safe payment label resolver for order / confirmation pages.
51
- *
52
- * Precedence for the PayPal providers: **admin-configured title** (`titles`,
53
- * from {@link fetchPayPalConfig}) → built-in default. For any other provider:
54
- * `fallback` → raw id. Never throws on an unknown / missing provider, which is
55
- * what causes the common `Cannot read properties of undefined (reading 'title')`
56
- * crash on the order confirmation page.
57
- *
58
- * @param titles Admin titles so the order page shows the same labels configured
59
- * in Medusa Admin → Settings → PayPal (e.g. a custom "Credit or Debit Card").
60
- */
61
- export function getPaymentLabel(
62
- providerId: string | undefined | null,
63
- fallback?: string,
64
- titles?: PayPalConfigTitles
65
- ): string {
66
- if (!providerId) {
67
- return fallback ?? ""
68
- }
69
- if (providerId === PAYPAL_WALLET_PROVIDER_ID) {
70
- return (
71
- titles?.paypal_title?.trim() ||
72
- paypalPaymentInfoMap[PAYPAL_WALLET_PROVIDER_ID].title
73
- )
74
- }
75
- if (providerId === PAYPAL_CARD_PROVIDER_ID) {
76
- return (
77
- titles?.card_title?.trim() ||
78
- paypalPaymentInfoMap[PAYPAL_CARD_PROVIDER_ID].title
79
- )
80
- }
81
- return fallback ?? providerId
82
- }
83
-
84
- /**
85
- * Fetch the admin-configured PayPal titles from the storefront API
86
- * (`GET /store/paypal/config`). Server-safe (uses the global `fetch`).
87
- *
88
- * Returns `{}` on any error/network failure so callers can fall back to the
89
- * built-in defaults without their own try/catch.
90
- */
91
- export async function fetchPayPalConfig(opts: {
92
- baseUrl: string
93
- publishableApiKey?: string
94
- signal?: AbortSignal
95
- }): Promise<PayPalConfigTitles> {
96
- const { baseUrl, publishableApiKey, signal } = opts
97
- if (!baseUrl) {
98
- return {}
99
- }
100
- try {
101
- const timeoutMs = 30_000
102
- let effectiveSignal = signal
103
- let timeoutId: ReturnType<typeof setTimeout> | undefined
104
- if (!signal) {
105
- const controller = new AbortController()
106
- timeoutId = setTimeout(() => controller.abort(), timeoutMs)
107
- effectiveSignal = controller.signal
108
- }
109
- let res: Response
110
- try {
111
- res = await fetch(`${baseUrl.replace(/\/$/, "")}/store/paypal/config`, {
112
- headers: {
113
- accept: "application/json",
114
- ...(publishableApiKey ? { "x-publishable-api-key": publishableApiKey } : {}),
115
- },
116
- signal: effectiveSignal,
117
- })
118
- } finally {
119
- if (timeoutId !== undefined) clearTimeout(timeoutId)
120
- }
121
- if (!res.ok) {
122
- return {}
123
- }
124
- const cfg = (await res.json()) as Record<string, unknown>
125
- return {
126
- paypal_title:
127
- typeof cfg.paypal_title === "string" ? cfg.paypal_title : undefined,
128
- card_title:
129
- typeof cfg.card_title === "string" ? cfg.card_title : undefined,
130
- }
131
- } catch {
132
- return {}
133
- }
134
- }
1
+ /**
2
+ * Server-safe helpers for displaying PayPal payments on order / confirmation
3
+ * pages.
4
+ *
5
+ * This module is intentionally free of React and any client-only code, so it
6
+ * can be imported from Next.js **server components** (e.g. the order
7
+ * confirmation page) without pulling in the checkout UI.
8
+ *
9
+ * @example
10
+ * import { getPaymentLabel, fetchPayPalConfig } from "@easypayment/medusa-paypal-ui/order"
11
+ *
12
+ * // In the (async) server component that renders the payment method:
13
+ * const titles = await fetchPayPalConfig({
14
+ * baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!,
15
+ * publishableApiKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
16
+ * })
17
+ *
18
+ * <Text>
19
+ * {getPaymentLabel(
20
+ * payment.provider_id,
21
+ * paymentInfoMap[payment.provider_id]?.title,
22
+ * titles
23
+ * )}
24
+ * </Text>
25
+ */
26
+
27
+ import {
28
+ PAYPAL_WALLET_PROVIDER_ID,
29
+ PAYPAL_CARD_PROVIDER_ID,
30
+ isPayPalProviderId,
31
+ } from "./constants"
32
+
33
+ export {
34
+ PAYPAL_WALLET_PROVIDER_ID,
35
+ PAYPAL_CARD_PROVIDER_ID,
36
+ isPayPalProviderId,
37
+ }
38
+
39
+ export type PayPalPaymentInfo = { title: string }
40
+
41
+ /** Built-in fallback titles, used only when admin titles aren't supplied. */
42
+ export const paypalPaymentInfoMap: Record<string, PayPalPaymentInfo> = {
43
+ [PAYPAL_WALLET_PROVIDER_ID]: { title: "PayPal" },
44
+ [PAYPAL_CARD_PROVIDER_ID]: { title: "Credit or Debit Card" },
45
+ }
46
+
47
+ /** Admin-configured titles, as returned by `GET /store/paypal/config`. */
48
+ export type PayPalConfigTitles = {
49
+ paypal_title?: string | null
50
+ card_title?: string | null
51
+ }
52
+
53
+ /**
54
+ * Null-safe payment label resolver for order / confirmation pages.
55
+ *
56
+ * Precedence for the PayPal providers: **admin-configured title** (`titles`,
57
+ * from {@link fetchPayPalConfig}) → built-in default. For any other provider:
58
+ * `fallback` → raw id. Never throws on an unknown / missing provider, which is
59
+ * what causes the common `Cannot read properties of undefined (reading 'title')`
60
+ * crash on the order confirmation page.
61
+ *
62
+ * @param titles Admin titles so the order page shows the same labels configured
63
+ * in Medusa Admin → Settings → PayPal (e.g. a custom "Credit or Debit Card").
64
+ */
65
+ export function getPaymentLabel(
66
+ providerId: string | undefined | null,
67
+ fallback?: string,
68
+ titles?: PayPalConfigTitles
69
+ ): string {
70
+ if (!providerId) {
71
+ return fallback ?? ""
72
+ }
73
+ if (providerId === PAYPAL_WALLET_PROVIDER_ID) {
74
+ return (
75
+ titles?.paypal_title?.trim() ||
76
+ paypalPaymentInfoMap[PAYPAL_WALLET_PROVIDER_ID].title
77
+ )
78
+ }
79
+ if (providerId === PAYPAL_CARD_PROVIDER_ID) {
80
+ return (
81
+ titles?.card_title?.trim() ||
82
+ paypalPaymentInfoMap[PAYPAL_CARD_PROVIDER_ID].title
83
+ )
84
+ }
85
+ return fallback ?? providerId
86
+ }
87
+
88
+ /**
89
+ * Fetch the admin-configured PayPal titles from the storefront API
90
+ * (`GET /store/paypal/config`). Server-safe (uses the global `fetch`).
91
+ *
92
+ * Returns `{}` on any error/network failure so callers can fall back to the
93
+ * built-in defaults without their own try/catch.
94
+ */
95
+ export async function fetchPayPalConfig(opts: {
96
+ baseUrl: string
97
+ publishableApiKey?: string
98
+ signal?: AbortSignal
99
+ }): Promise<PayPalConfigTitles> {
100
+ const { baseUrl, publishableApiKey, signal } = opts
101
+ if (!baseUrl) {
102
+ return {}
103
+ }
104
+ try {
105
+ const timeoutMs = 30_000
106
+ let effectiveSignal = signal
107
+ let timeoutId: ReturnType<typeof setTimeout> | undefined
108
+ if (!signal) {
109
+ const controller = new AbortController()
110
+ timeoutId = setTimeout(() => controller.abort(), timeoutMs)
111
+ effectiveSignal = controller.signal
112
+ }
113
+ let res: Response
114
+ try {
115
+ res = await fetch(`${baseUrl.replace(/\/$/, "")}/store/paypal/config`, {
116
+ headers: {
117
+ accept: "application/json",
118
+ ...(publishableApiKey
119
+ ? { "x-publishable-api-key": publishableApiKey }
120
+ : {}),
121
+ },
122
+ signal: effectiveSignal,
123
+ })
124
+ } finally {
125
+ if (timeoutId !== undefined) clearTimeout(timeoutId)
126
+ }
127
+ if (!res.ok) {
128
+ return {}
129
+ }
130
+ const cfg = (await res.json()) as Record<string, unknown>
131
+ return {
132
+ paypal_title:
133
+ typeof cfg.paypal_title === "string" ? cfg.paypal_title : undefined,
134
+ card_title:
135
+ typeof cfg.card_title === "string" ? cfg.card_title : undefined,
136
+ }
137
+ } catch {
138
+ return {}
139
+ }
140
+ }
@@ -1,21 +1,21 @@
1
- /**
2
- * Detect Next.js router errors (redirect / notFound) that must be re-thrown.
3
- *
4
- * Next.js implements redirect() and notFound() by throwing special errors with
5
- * a `digest` property starting with "NEXT_REDIRECT" or "NEXT_NOT_FOUND".
6
- * Catching these in user-land try/catch blocks prevents the navigation from
7
- * happening. Because this package can't import from `next` (it's a peer dep),
8
- * we detect them by duck-typing the digest.
9
- */
10
- export function isNextRouterError(e: unknown): boolean {
11
- if (typeof e !== "object" || e === null || !("digest" in e)) return false
12
- const digest = (e as { digest: unknown }).digest
13
- return (
14
- typeof digest === "string" &&
15
- (digest.startsWith("NEXT_REDIRECT") ||
16
- digest.startsWith("NEXT_NOT_FOUND") ||
17
- // Next.js 15: notFound()/forbidden()/unauthorized() throw
18
- // HTTPAccessFallbackError with digest "NEXT_HTTP_ERROR_FALLBACK;<status>".
19
- digest.startsWith("NEXT_HTTP_ERROR_FALLBACK"))
20
- )
21
- }
1
+ /**
2
+ * Detect Next.js router errors (redirect / notFound) that must be re-thrown.
3
+ *
4
+ * Next.js implements redirect() and notFound() by throwing special errors with
5
+ * a `digest` property starting with "NEXT_REDIRECT" or "NEXT_NOT_FOUND".
6
+ * Catching these in user-land try/catch blocks prevents the navigation from
7
+ * happening. Because this package can't import from `next` (it's a peer dep),
8
+ * we detect them by duck-typing the digest.
9
+ */
10
+ export function isNextRouterError(e: unknown): boolean {
11
+ if (typeof e !== "object" || e === null || !("digest" in e)) return false
12
+ const digest = (e as { digest: unknown }).digest
13
+ return (
14
+ typeof digest === "string" &&
15
+ (digest.startsWith("NEXT_REDIRECT") ||
16
+ digest.startsWith("NEXT_NOT_FOUND") ||
17
+ // Next.js 15: notFound()/forbidden()/unauthorized() throw
18
+ // HTTPAccessFallbackError with digest "NEXT_HTTP_ERROR_FALLBACK;<status>".
19
+ digest.startsWith("NEXT_HTTP_ERROR_FALLBACK"))
20
+ )
21
+ }
@@ -1,96 +1,96 @@
1
- const OVERLAY_ID = "__pp_processing_overlay"
2
-
3
- let cleanupNavListener: (() => void) | null = null
4
-
5
- export function showProcessingOverlay() {
6
- if (typeof document === "undefined") return
7
- if (document.getElementById(OVERLAY_ID)) return
8
-
9
- const overlay = document.createElement("div")
10
- overlay.id = OVERLAY_ID
11
- overlay.setAttribute("role", "status")
12
- overlay.setAttribute("aria-label", "Processing payment")
13
-
14
- overlay.innerHTML = `
15
- <style>
16
- @keyframes _pp_spin { to { transform: rotate(360deg) } }
17
- @keyframes _pp_progress { 0% { transform: translateX(-100%) } 100% { transform: translateX(350%) } }
18
- </style>
19
- <div style="position:relative;width:56px;height:56px">
20
- <div style="position:absolute;inset:0;border-radius:50%;border:3px solid #e5e7eb"></div>
21
- <div style="position:absolute;inset:0;border-radius:50%;border:3px solid transparent;border-top-color:#0070ba;animation:_pp_spin .8s linear infinite"></div>
22
- <svg viewBox="0 0 24 24" fill="none" stroke="#0070ba" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"
23
- style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:24px;height:24px">
24
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
25
- </svg>
26
- </div>
27
- <div style="text-align:center">
28
- <div style="font-size:18px;font-weight:600;color:#111827;letter-spacing:-0.01em">Processing your payment</div>
29
- <div style="font-size:14px;color:#6b7280;margin-top:6px;line-height:1.5">
30
- This may take a few moments. Please do not close<br>or refresh this page.
31
- </div>
32
- </div>
33
- <div style="width:200px;height:3px;background:#e5e7eb;border-radius:3px;overflow:hidden;margin-top:4px">
34
- <div style="width:40%;height:100%;background:linear-gradient(90deg,#0070ba,#003087);border-radius:3px;animation:_pp_progress 1.5s ease-in-out infinite"></div>
35
- </div>
36
- `
37
-
38
- Object.assign(overlay.style, {
39
- position: "fixed",
40
- inset: "0",
41
- zIndex: "99999",
42
- background: "rgba(255,255,255,0.96)",
43
- display: "flex",
44
- flexDirection: "column",
45
- alignItems: "center",
46
- justifyContent: "center",
47
- gap: "20px",
48
- fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
49
- })
50
-
51
- document.body.appendChild(overlay)
52
-
53
- // Auto-remove on client-side navigation (Next.js App Router uses
54
- // pushState/replaceState for soft navigations, not full reloads).
55
- const startUrl = location.href
56
- const onNav = () => {
57
- if (location.href !== startUrl) hideProcessingOverlay()
58
- }
59
- window.addEventListener("popstate", onNav)
60
-
61
- const origPush = history.pushState.bind(history)
62
- const origReplace = history.replaceState.bind(history)
63
- history.pushState = function (...args) {
64
- origPush(...args)
65
- onNav()
66
- }
67
- history.replaceState = function (...args) {
68
- origReplace(...args)
69
- onNav()
70
- }
71
-
72
- // bfcache restore: the overlay intentionally survives the unload of a
73
- // full-page navigation (that's its purpose), but when the buyer presses
74
- // Back the browser restores this page from the back/forward cache with the
75
- // overlay element still in the DOM and the URL equal to startUrl — no nav
76
- // listener ever fires, leaving checkout permanently covered. `pageshow`
77
- // with `persisted: true` is exactly that restore.
78
- const onPageShow = (e: PageTransitionEvent) => {
79
- if (e.persisted) hideProcessingOverlay()
80
- }
81
- window.addEventListener("pageshow", onPageShow)
82
-
83
- cleanupNavListener = () => {
84
- window.removeEventListener("popstate", onNav)
85
- window.removeEventListener("pageshow", onPageShow)
86
- history.pushState = origPush
87
- history.replaceState = origReplace
88
- }
89
- }
90
-
91
- export function hideProcessingOverlay() {
92
- if (typeof document === "undefined") return
93
- cleanupNavListener?.()
94
- cleanupNavListener = null
95
- document.getElementById(OVERLAY_ID)?.remove()
96
- }
1
+ const OVERLAY_ID = "__pp_processing_overlay"
2
+
3
+ let cleanupNavListener: (() => void) | null = null
4
+
5
+ export function showProcessingOverlay() {
6
+ if (typeof document === "undefined") return
7
+ if (document.getElementById(OVERLAY_ID)) return
8
+
9
+ const overlay = document.createElement("div")
10
+ overlay.id = OVERLAY_ID
11
+ overlay.setAttribute("role", "status")
12
+ overlay.setAttribute("aria-label", "Processing payment")
13
+
14
+ overlay.innerHTML = `
15
+ <style>
16
+ @keyframes _pp_spin { to { transform: rotate(360deg) } }
17
+ @keyframes _pp_progress { 0% { transform: translateX(-100%) } 100% { transform: translateX(350%) } }
18
+ </style>
19
+ <div style="position:relative;width:56px;height:56px">
20
+ <div style="position:absolute;inset:0;border-radius:50%;border:3px solid #e5e7eb"></div>
21
+ <div style="position:absolute;inset:0;border-radius:50%;border:3px solid transparent;border-top-color:#0070ba;animation:_pp_spin .8s linear infinite"></div>
22
+ <svg viewBox="0 0 24 24" fill="none" stroke="#0070ba" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"
23
+ style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:24px;height:24px">
24
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
25
+ </svg>
26
+ </div>
27
+ <div style="text-align:center">
28
+ <div style="font-size:18px;font-weight:600;color:#111827;letter-spacing:-0.01em">Processing your payment</div>
29
+ <div style="font-size:14px;color:#6b7280;margin-top:6px;line-height:1.5">
30
+ This may take a few moments. Please do not close<br>or refresh this page.
31
+ </div>
32
+ </div>
33
+ <div style="width:200px;height:3px;background:#e5e7eb;border-radius:3px;overflow:hidden;margin-top:4px">
34
+ <div style="width:40%;height:100%;background:linear-gradient(90deg,#0070ba,#003087);border-radius:3px;animation:_pp_progress 1.5s ease-in-out infinite"></div>
35
+ </div>
36
+ `
37
+
38
+ Object.assign(overlay.style, {
39
+ position: "fixed",
40
+ inset: "0",
41
+ zIndex: "99999",
42
+ background: "rgba(255,255,255,0.96)",
43
+ display: "flex",
44
+ flexDirection: "column",
45
+ alignItems: "center",
46
+ justifyContent: "center",
47
+ gap: "20px",
48
+ fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
49
+ })
50
+
51
+ document.body.appendChild(overlay)
52
+
53
+ // Auto-remove on client-side navigation (Next.js App Router uses
54
+ // pushState/replaceState for soft navigations, not full reloads).
55
+ const startUrl = location.href
56
+ const onNav = () => {
57
+ if (location.href !== startUrl) hideProcessingOverlay()
58
+ }
59
+ window.addEventListener("popstate", onNav)
60
+
61
+ const origPush = history.pushState.bind(history)
62
+ const origReplace = history.replaceState.bind(history)
63
+ history.pushState = function (...args) {
64
+ origPush(...args)
65
+ onNav()
66
+ }
67
+ history.replaceState = function (...args) {
68
+ origReplace(...args)
69
+ onNav()
70
+ }
71
+
72
+ // bfcache restore: the overlay intentionally survives the unload of a
73
+ // full-page navigation (that's its purpose), but when the buyer presses
74
+ // Back the browser restores this page from the back/forward cache with the
75
+ // overlay element still in the DOM and the URL equal to startUrl — no nav
76
+ // listener ever fires, leaving checkout permanently covered. `pageshow`
77
+ // with `persisted: true` is exactly that restore.
78
+ const onPageShow = (e: PageTransitionEvent) => {
79
+ if (e.persisted) hideProcessingOverlay()
80
+ }
81
+ window.addEventListener("pageshow", onPageShow)
82
+
83
+ cleanupNavListener = () => {
84
+ window.removeEventListener("popstate", onNav)
85
+ window.removeEventListener("pageshow", onPageShow)
86
+ history.pushState = origPush
87
+ history.replaceState = origReplace
88
+ }
89
+ }
90
+
91
+ export function hideProcessingOverlay() {
92
+ if (typeof document === "undefined") return
93
+ cleanupNavListener?.()
94
+ cleanupNavListener = null
95
+ document.getElementById(OVERLAY_ID)?.remove()
96
+ }