@onflay/js 0.0.0-stage → 0.3.0-staging-20261206175528

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,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # `@onflay/js`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Framework-agnostic Onflay checkout overlay (`onflay.js`).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @onflay/js
9
+ ```
10
+
11
+ CDN (jsDelivr):
12
+
13
+ ```html
14
+ <script
15
+ src="https://cdn.jsdelivr.net/npm/@onflay/js@<version>/dist/onflay.iife.js"
16
+ integrity="sha384-<hash of this exact file>"
17
+ crossorigin="anonymous"
18
+ ></script>
19
+ ```
20
+
21
+ Pin an exact version and its hash (`scripts/publish-cdn.sh` prints it).
22
+
23
+ Or the Onflay CDN alias (once deployed):
24
+
25
+ ```html
26
+ <script
27
+ src="https://js.onflay.com/v1/onflay.js"
28
+ integrity="sha384-<hash of this exact file>"
29
+ crossorigin="anonymous"
30
+ ></script>
31
+ ```
32
+
33
+ Prepare CDN upload artifacts:
34
+
35
+ ```bash
36
+ pnpm --filter @onflay/js build
37
+ ./sdks/browser/scripts/publish-cdn.sh
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ 1. Create a checkout session on your **server** with `uiMode: "embedded"` and your
43
+ `successUrl` / `cancelUrl` (origins are derived for `frame-ancestors`).
44
+ 2. Pass the returned `embedUrl` to the browser.
45
+ 3. Open the overlay:
46
+
47
+ ```js
48
+ OnflayCheckout.open({
49
+ url: embedUrl,
50
+ onComplete: ({ checkoutId }) => {
51
+ // UI signal only — verify payment with GET /v1/checkout-sessions/{id}/receipt?headless=true
52
+ fetch('/api/confirm-checkout', {
53
+ method: 'POST',
54
+ body: JSON.stringify({ checkoutId }),
55
+ });
56
+ },
57
+ onCancel: () => {},
58
+ onError: (error) => console.error(error),
59
+ fallback: 'redirect', // or 'popup' | 'none'
60
+ });
61
+ ```
62
+
63
+ `onComplete` fires as soon as the payment succeeds. The overlay then stays open on Onflay's
64
+ payment confirmation until the buyer presses **Done** or closes it; closing it at that point
65
+ does not call `onCancel`. Call `OnflayCheckout.close()` from `onComplete` if you want to close
66
+ it straight away.
67
+
68
+ ### Declarative (no JS required beyond the script tag)
69
+
70
+ ```html
71
+ <a
72
+ href="https://checkout.onflay.com/s/FALLBACK"
73
+ data-onflay-checkout="https://checkout.onflay.com/embed/s/SESSION?t=TOKEN"
74
+ >
75
+ Buy now
76
+ </a>
77
+ ```
78
+
79
+ ## Merchant CSP
80
+
81
+ ```
82
+ script-src https://js.onflay.com https://cdn.jsdelivr.net;
83
+ frame-src https://checkout.onflay.com https://sandbox-checkout.onflay.com;
84
+ ```
85
+
86
+ ## Security notes
87
+
88
+ - Never put `sk_*` in the browser.
89
+ - The overlay `onComplete` event is **not** proof of payment — always confirm with the receipt API using your secret key.
90
+ - Only Onflay checkout origins can be framed by this loader.
@@ -0,0 +1,65 @@
1
+ /* @onflay/js — https://docs.onflay.com */
2
+ "use strict";var v=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var B=(e,t)=>{for(var o in t)v(e,o,{get:t[o],enumerable:!0})},F=(e,t,o,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of U(t))!_.call(e,n)&&n!==o&&v(e,n,{get:()=>t[n],enumerable:!(c=N(t,n))||c.enumerable});return e};var S=e=>F(v({},"__esModule",{value:!0}),e);var Y={};B(Y,{ONFLAY_CHECKOUT_CHANNEL:()=>y,OnflayCheckout:()=>I,close:()=>w,extractCheckoutId:()=>b,isAllowedCheckoutUrl:()=>C,isOpen:()=>O,open:()=>g});module.exports=S(Y);var R=new Set(["checkout.onflay.com","checkout-staging.onflay.com"]),D=new Set(["sandbox-checkout.onflay.com","sandbox-checkout-staging.onflay.com"]);function C(e){let t;try{t=new URL(e)}catch(n){return!1}if(t.protocol!=="https:"&&t.protocol!=="http:")return!1;let o=t.hostname.toLowerCase();return R.has(o)||D.has(o)?t.protocol==="https:":o==="localhost"||o==="127.0.0.1"||o==="[::1]"?t.pathname.startsWith("/embed/s/")||t.pathname.startsWith("/s/"):!1}function b(e){try{let o=new URL(e).pathname.match(/\/(?:embed\/)?s\/([^/]+)/);return o!=null&&o[1]?decodeURIComponent(o[1]):null}catch(t){return null}}function M(e){try{return new URL(e).origin}catch(t){return null}}var K=`
3
+ :host {
4
+ all: initial;
5
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
6
+ }
7
+ .backdrop {
8
+ position: fixed;
9
+ inset: 0;
10
+ z-index: 2147483000;
11
+ display: flex;
12
+ align-items: center;
13
+ justify-content: center;
14
+ padding: 24px;
15
+ background: rgba(11, 13, 18, 0.45);
16
+ backdrop-filter: blur(2px);
17
+ }
18
+ .dialog {
19
+ position: relative;
20
+ width: min(440px, 100%);
21
+ max-height: min(900px, calc(100vh - 48px));
22
+ background: #fff;
23
+ color: #0b0d12;
24
+ border-radius: 16px;
25
+ box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);
26
+ overflow: hidden;
27
+ display: flex;
28
+ flex-direction: column;
29
+ }
30
+ .frame {
31
+ width: 100%;
32
+ flex: 1 1 auto;
33
+ min-height: 640px;
34
+ border: 0;
35
+ background: #fff;
36
+ }
37
+ .sr-only {
38
+ position: absolute;
39
+ width: 1px;
40
+ height: 1px;
41
+ padding: 0;
42
+ margin: -1px;
43
+ overflow: hidden;
44
+ clip: rect(0, 0, 0, 0);
45
+ white-space: nowrap;
46
+ border: 0;
47
+ }
48
+ @media (max-width: 640px) {
49
+ .backdrop {
50
+ padding: 40px 0 0;
51
+ align-items: flex-end;
52
+ }
53
+ .dialog {
54
+ width: 100%;
55
+ max-height: 100%;
56
+ height: 100%;
57
+ border-radius: 20px 20px 0 0;
58
+ }
59
+ .frame {
60
+ min-height: 100%;
61
+ height: 100%;
62
+ }
63
+ }
64
+ `;function L(e){let t=document.createElement("div");t.setAttribute("data-onflay-checkout-overlay","true");let o=t.attachShadow({mode:"closed"}),c=document.createElement("style");c.textContent=K;let n=document.createElement("div");n.className="backdrop",n.setAttribute("role","presentation");let r=document.createElement("div");r.className="dialog",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label","Secure checkout"),r.tabIndex=-1;let s=document.createElement("h2");s.className="sr-only",s.textContent="Onflay checkout";let i=document.createElement("iframe");i.className="frame",i.title="Onflay checkout",i.setAttribute("allow","payment *; publickey-credentials-get *"),i.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),i.src=e.checkoutUrl,r.appendChild(s),r.appendChild(i),n.appendChild(r),o.appendChild(c),o.appendChild(n),document.body.appendChild(t);let h=document.body.style.overflow;document.body.style.overflow="hidden",r.focus({preventScroll:!0});function p(l){if(l.key==="Escape"){l.preventDefault(),e.onBackdropClose();return}if(l.key!=="Tab")return;let d=[r,i],m=d[0],k=d[d.length-1];!m||!k||(l.shiftKey&&document.activeElement===m?(l.preventDefault(),i.focus()):!l.shiftKey&&document.activeElement===k&&(l.preventDefault(),r.focus()))}function a(l){l.target===n&&e.onBackdropClose()}return document.addEventListener("keydown",p),n.addEventListener("click",a),{host:t,iframe:i,dialog:r,setHeight(l){let d=Math.max(480,Math.min(l,window.innerHeight-32));i.style.minHeight=`${d}px`,i.style.height=`${d}px`},destroy(){document.removeEventListener("keydown",p),n.removeEventListener("click",a),document.body.style.overflow=h,t.remove(),e.previouslyFocused instanceof HTMLElement&&document.contains(e.previouslyFocused)&&e.previouslyFocused.focus({preventScroll:!0})}}}var y="onflay.checkout.v1";function A(e){if(!e||typeof e!="object")return!1;let t=e;if(t.channel!==y||typeof t.checkoutId!="string")return!1;let o=t.type;return o==="ready"||o==="resize"||o==="completed"||o==="failed"||o==="cancelled"||o==="expired"||o==="redirect_required"}var u=null;function f(e){e.settled||(e.settled=!0,e.readyTimer&&(clearTimeout(e.readyTimer),e.readyTimer=null),window.removeEventListener("message",e.onMessage),e.overlay.destroy(),u===e&&(u=null))}function W(e,t){var c,n,r,s,i;let o=(c=e.options.fallback)!=null?c:"redirect";if(f(e),o==="none"){(r=(n=e.options).onError)==null||r.call(n,new Error(t));return}if(o==="popup"){if(!window.open(e.url,"onflay_checkout","popup=yes,width=480,height=800")){(i=(s=e.options).onError)==null||i.call(s,new Error(`${t} Popup blocked; falling back to redirect.`)),window.location.assign(e.url);return}return}window.location.assign(e.url)}function q(e){let t=e.overlay.iframe.contentWindow;t&&t.postMessage({channel:y,type:"init",checkoutId:e.checkoutId,...e.options.distinctId?{distinctId:e.options.distinctId}:{}},e.checkoutOrigin)}function g(e){var i,h,p;if(typeof window=="undefined"||typeof document=="undefined")throw new Error("OnflayCheckout.open() requires a browser environment.");if(!e.url||!C(e.url)){let a=new Error("OnflayCheckout.open(): url must be an Onflay checkout embed URL.");throw(i=e.onError)==null||i.call(e,a),a}let t=b(e.url),o=M(e.url);if(!t||!o){let a=new Error("OnflayCheckout.open(): could not parse checkout session id.");throw(h=e.onError)==null||h.call(e,a),a}u&&w();let c=document.activeElement,n=L({checkoutUrl:e.url,previouslyFocused:c,onBackdropClose:()=>{var l,d;if(!u||u.settled)return;let a=u;f(a),a.completed||(d=(l=a.options).onCancel)==null||d.call(l)}}),r={url:e.url,checkoutId:t,checkoutOrigin:o,options:e,overlay:n,readyTimer:null,settled:!1,completed:!1,onMessage(a){var l,d,m,k,E,T;if(a.origin===o&&a.source===n.iframe.contentWindow&&A(a.data)&&a.data.checkoutId===t)switch(a.data.type){case"ready":{r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),q(r),(l=e.onReady)==null||l.call(e);break}case"resize":{n.setHeight(a.data.height);break}case"completed":{if(r.completed)break;r.completed=!0,r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),a.data.showsConfirmation!==!0&&f(r),(d=e.onComplete)==null||d.call(e,{checkoutId:t});break}case"cancelled":{f(r),r.completed||(m=e.onCancel)==null||m.call(e);break}case"expired":{f(r),(k=e.onError)==null||k.call(e,new Error("Checkout session expired."));break}case"failed":{f(r),(T=e.onError)==null||T.call(e,new Error((E=a.data.message)!=null?E:"Checkout failed."));break}case"redirect_required":{f(r),window.location.assign(a.data.url);break}default:break}}};window.addEventListener("message",r.onMessage),u=r;let s=(p=e.readyTimeoutMs)!=null?p:8e3;r.readyTimer=setTimeout(()=>{!u||u!==r||r.settled||W(r,"Checkout iframe did not become ready in time (framing may be blocked).")},s)}function w(){var o,c;if(!u)return;let e=u,t=e.overlay.iframe.contentWindow;t&&t.postMessage({channel:y,type:"close_request",checkoutId:e.checkoutId},e.checkoutOrigin),f(e),e.completed||(c=(o=e.options).onCancel)==null||c.call(o)}function O(){return u!==null}var H="data-onflay-checkout";function x(){typeof document!="undefined"&&document.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let o=t.closest(`[${H}]`);if(!(o instanceof HTMLElement))return;let c=o.getAttribute(H)||(o instanceof HTMLAnchorElement?o.href:null);if(c){e.preventDefault();try{g({url:c})}catch(n){o instanceof HTMLAnchorElement&&o.href&&window.location.assign(o.href)}}},!0)}var I={open:g,close:w,isOpen:O};typeof window!="undefined"&&(window.OnflayCheckout=I,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{x()}):x());0&&(module.exports={ONFLAY_CHECKOUT_CHANNEL,OnflayCheckout,close,extractCheckoutId,isAllowedCheckoutUrl,isOpen,open});
65
+ //# sourceMappingURL=onflay.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/origins.ts","../src/overlay.ts","../src/protocol.ts","../src/checkout.ts","../src/declarative.ts"],"sourcesContent":["import { close, isOpen, open } from './checkout';\nimport { bindDeclarativeCheckout } from './declarative';\n\nexport type { OpenCheckoutOptions, CheckoutFallback } from './checkout';\nexport { open, close, isOpen };\nexport { isAllowedCheckoutUrl, extractCheckoutId } from './origins';\nexport { ONFLAY_CHECKOUT_CHANNEL } from './protocol';\n\nexport interface OnflayCheckoutApi {\n open: typeof open;\n close: typeof close;\n isOpen: typeof isOpen;\n}\n\nconst OnflayCheckout: OnflayCheckoutApi = { open, close, isOpen };\n\ndeclare global {\n interface Window {\n OnflayCheckout?: OnflayCheckoutApi;\n }\n}\n\nif (typeof window !== 'undefined') {\n window.OnflayCheckout = OnflayCheckout;\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n bindDeclarativeCheckout();\n });\n } else {\n bindDeclarativeCheckout();\n }\n}\n\nexport { OnflayCheckout };\n","const PRODUCTION_HOSTS = new Set([\n 'checkout.onflay.com',\n // Onflay's internal staging environment.\n 'checkout-staging.onflay.com',\n]);\nconst SANDBOX_HOSTS = new Set([\n 'sandbox-checkout.onflay.com',\n 'sandbox-checkout-staging.onflay.com',\n]);\n\n/**\n * Returns true when `url` points at an Onflay-hosted checkout origin we trust\n * to load inside the overlay iframe.\n */\nexport function isAllowedCheckoutUrl(url: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return false;\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n const host = parsed.hostname.toLowerCase();\n if (PRODUCTION_HOSTS.has(host) || SANDBOX_HOSTS.has(host)) {\n return parsed.protocol === 'https:';\n }\n const isLocal =\n host === 'localhost' || host === '127.0.0.1' || host === '[::1]';\n if (!isLocal) return false;\n return (\n parsed.pathname.startsWith('/embed/s/') ||\n parsed.pathname.startsWith('/s/')\n );\n}\n\n/**\n * Extracts the checkout session id from an embed or hosted checkout URL.\n */\nexport function extractCheckoutId(url: string): string | null {\n try {\n const parsed = new URL(url);\n const match = parsed.pathname.match(/\\/(?:embed\\/)?s\\/([^/]+)/);\n return match?.[1] ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\nexport function getCheckoutOrigin(url: string): string | null {\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n","const STYLE_TEXT = `\n:host {\n all: initial;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;\n}\n.backdrop {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(11, 13, 18, 0.45);\n backdrop-filter: blur(2px);\n}\n.dialog {\n position: relative;\n width: min(440px, 100%);\n max-height: min(900px, calc(100vh - 48px));\n background: #fff;\n color: #0b0d12;\n border-radius: 16px;\n box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n}\n.frame {\n width: 100%;\n flex: 1 1 auto;\n min-height: 640px;\n border: 0;\n background: #fff;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n@media (max-width: 640px) {\n .backdrop {\n padding: 40px 0 0;\n align-items: flex-end;\n }\n .dialog {\n width: 100%;\n max-height: 100%;\n height: 100%;\n border-radius: 20px 20px 0 0;\n }\n .frame {\n min-height: 100%;\n height: 100%;\n }\n}\n`;\n\nexport interface OverlayHandles {\n readonly host: HTMLDivElement;\n readonly iframe: HTMLIFrameElement;\n readonly dialog: HTMLDivElement;\n setHeight(height: number): void;\n destroy(): void;\n}\n\n/**\n * Mounts the checkout overlay in a shadow root to avoid CSS collisions.\n */\nexport function mountOverlay(params: {\n readonly checkoutUrl: string;\n readonly onBackdropClose: () => void;\n readonly previouslyFocused: Element | null;\n}): OverlayHandles {\n const host = document.createElement('div');\n host.setAttribute('data-onflay-checkout-overlay', 'true');\n const shadow = host.attachShadow({ mode: 'closed' });\n const style = document.createElement('style');\n style.textContent = STYLE_TEXT;\n const backdrop = document.createElement('div');\n backdrop.className = 'backdrop';\n backdrop.setAttribute('role', 'presentation');\n const dialog = document.createElement('div');\n dialog.className = 'dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.setAttribute('aria-label', 'Secure checkout');\n dialog.tabIndex = -1;\n const title = document.createElement('h2');\n title.className = 'sr-only';\n title.textContent = 'Onflay checkout';\n const iframe = document.createElement('iframe');\n iframe.className = 'frame';\n iframe.title = 'Onflay checkout';\n iframe.setAttribute('allow', 'payment *; publickey-credentials-get *');\n iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');\n iframe.src = params.checkoutUrl;\n dialog.appendChild(title);\n dialog.appendChild(iframe);\n backdrop.appendChild(dialog);\n shadow.appendChild(style);\n shadow.appendChild(backdrop);\n document.body.appendChild(host);\n const previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n dialog.focus({ preventScroll: true });\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key === 'Escape') {\n event.preventDefault();\n params.onBackdropClose();\n return;\n }\n if (event.key !== 'Tab') return;\n const focusable = [dialog, iframe];\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n iframe.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n dialog.focus();\n }\n }\n\n function onBackdropClick(event: MouseEvent): void {\n if (event.target === backdrop) params.onBackdropClose();\n }\n\n document.addEventListener('keydown', onKeyDown);\n backdrop.addEventListener('click', onBackdropClick);\n\n return {\n host,\n iframe,\n dialog,\n setHeight(height: number): void {\n const clamped = Math.max(480, Math.min(height, window.innerHeight - 32));\n iframe.style.minHeight = `${clamped}px`;\n iframe.style.height = `${clamped}px`;\n },\n destroy(): void {\n document.removeEventListener('keydown', onKeyDown);\n backdrop.removeEventListener('click', onBackdropClick);\n document.body.style.overflow = previousOverflow;\n host.remove();\n if (\n params.previouslyFocused instanceof HTMLElement &&\n document.contains(params.previouslyFocused)\n ) {\n params.previouslyFocused.focus({ preventScroll: true });\n }\n },\n };\n}\n","/**\n * Versioned postMessage envelope for the Onflay checkout overlay.\n * Must stay in sync with apps/checkout/src/lib/embed-protocol.ts.\n */\nexport const ONFLAY_CHECKOUT_CHANNEL = 'onflay.checkout.v1' as const;\n\nexport interface OnflayCheckoutMessageBase {\n readonly channel: typeof ONFLAY_CHECKOUT_CHANNEL;\n readonly type: string;\n readonly checkoutId: string;\n}\n\nexport type OnflayCheckoutOutboundMessage =\n | (OnflayCheckoutMessageBase & { readonly type: 'ready' })\n | (OnflayCheckoutMessageBase & { readonly type: 'resize'; readonly height: number })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'completed';\n /**\n * The iframe shows its own payment confirmation: keep the overlay open until the\n * buyer closes it. Older checkout builds omit it, and the overlay closes at once.\n */\n readonly showsConfirmation?: boolean;\n })\n | (OnflayCheckoutMessageBase & { readonly type: 'failed'; readonly message?: string })\n | (OnflayCheckoutMessageBase & { readonly type: 'cancelled' })\n | (OnflayCheckoutMessageBase & { readonly type: 'expired' })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'redirect_required';\n readonly url: string;\n });\n\nexport function isOnflayCheckoutOutboundMessage(\n data: unknown,\n): data is OnflayCheckoutOutboundMessage {\n if (!data || typeof data !== 'object') return false;\n const message = data as Record<string, unknown>;\n if (message.channel !== ONFLAY_CHECKOUT_CHANNEL) return false;\n if (typeof message.checkoutId !== 'string') return false;\n const type = message.type;\n return (\n type === 'ready' ||\n type === 'resize' ||\n type === 'completed' ||\n type === 'failed' ||\n type === 'cancelled' ||\n type === 'expired' ||\n type === 'redirect_required'\n );\n}\n","import {\n extractCheckoutId,\n getCheckoutOrigin,\n isAllowedCheckoutUrl,\n} from './origins';\nimport { mountOverlay, type OverlayHandles } from './overlay';\nimport {\n ONFLAY_CHECKOUT_CHANNEL,\n isOnflayCheckoutOutboundMessage,\n} from './protocol';\n\nexport type CheckoutFallback = 'redirect' | 'popup' | 'none';\n\nexport interface OpenCheckoutOptions {\n /** Embed URL from `POST /v1/checkout-sessions` with `uiMode: 'embedded'`. */\n readonly url: string;\n readonly onReady?: () => void;\n readonly onComplete?: (event: { readonly checkoutId: string }) => void;\n readonly onCancel?: () => void;\n readonly onError?: (error: Error) => void;\n /**\n * Behavior when the iframe never posts `ready`.\n * Default: `redirect` (preserves payment completion).\n */\n readonly fallback?: CheckoutFallback;\n /** Timeout before fallback, in ms. Default 8000. */\n readonly readyTimeoutMs?: number;\n /** Optional PostHog distinct id forwarded via init message. */\n readonly distinctId?: string;\n}\n\ninterface ActiveCheckout {\n readonly url: string;\n readonly checkoutId: string;\n readonly checkoutOrigin: string;\n readonly options: OpenCheckoutOptions;\n readonly overlay: OverlayHandles;\n readonly onMessage: (event: MessageEvent) => void;\n readyTimer: ReturnType<typeof setTimeout> | null;\n settled: boolean;\n /** Payment completed and onComplete fired; closing now only dismisses the overlay. */\n completed: boolean;\n}\n\nlet active: ActiveCheckout | null = null;\n\nfunction settle(session: ActiveCheckout): void {\n if (session.settled) return;\n session.settled = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n window.removeEventListener('message', session.onMessage);\n session.overlay.destroy();\n if (active === session) active = null;\n}\n\nfunction runFallback(session: ActiveCheckout, reason: string): void {\n const fallback = session.options.fallback ?? 'redirect';\n settle(session);\n if (fallback === 'none') {\n session.options.onError?.(new Error(reason));\n return;\n }\n if (fallback === 'popup') {\n const popup = window.open(\n session.url,\n 'onflay_checkout',\n 'popup=yes,width=480,height=800',\n );\n if (!popup) {\n session.options.onError?.(\n new Error(`${reason} Popup blocked; falling back to redirect.`),\n );\n window.location.assign(session.url);\n return;\n }\n return;\n }\n window.location.assign(session.url);\n}\n\nfunction postInit(session: ActiveCheckout): void {\n const contentWindow = session.overlay.iframe.contentWindow;\n if (!contentWindow) return;\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'init',\n checkoutId: session.checkoutId,\n ...(session.options.distinctId\n ? { distinctId: session.options.distinctId }\n : {}),\n },\n session.checkoutOrigin,\n );\n}\n\n/**\n * Opens Onflay hosted checkout in a secure overlay iframe.\n */\nexport function open(options: OpenCheckoutOptions): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('OnflayCheckout.open() requires a browser environment.');\n }\n if (!options.url || !isAllowedCheckoutUrl(options.url)) {\n const error = new Error(\n 'OnflayCheckout.open(): url must be an Onflay checkout embed URL.',\n );\n options.onError?.(error);\n throw error;\n }\n const checkoutId = extractCheckoutId(options.url);\n const checkoutOrigin = getCheckoutOrigin(options.url);\n if (!checkoutId || !checkoutOrigin) {\n const error = new Error(\n 'OnflayCheckout.open(): could not parse checkout session id.',\n );\n options.onError?.(error);\n throw error;\n }\n if (active) close();\n\n const previouslyFocused = document.activeElement;\n const overlay = mountOverlay({\n checkoutUrl: options.url,\n previouslyFocused,\n onBackdropClose: () => {\n if (!active || active.settled) return;\n const session = active;\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n },\n });\n\n const session: ActiveCheckout = {\n url: options.url,\n checkoutId,\n checkoutOrigin,\n options,\n overlay,\n readyTimer: null,\n settled: false,\n completed: false,\n onMessage(event: MessageEvent): void {\n if (event.origin !== checkoutOrigin) return;\n if (event.source !== overlay.iframe.contentWindow) return;\n if (!isOnflayCheckoutOutboundMessage(event.data)) return;\n if (event.data.checkoutId !== checkoutId) return;\n switch (event.data.type) {\n case 'ready': {\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n postInit(session);\n options.onReady?.();\n break;\n }\n case 'resize': {\n overlay.setHeight(event.data.height);\n break;\n }\n case 'completed': {\n if (session.completed) break;\n session.completed = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n // A checkout that shows its own confirmation stays open until the buyer closes it.\n if (event.data.showsConfirmation !== true) settle(session);\n options.onComplete?.({ checkoutId });\n break;\n }\n case 'cancelled': {\n settle(session);\n if (!session.completed) options.onCancel?.();\n break;\n }\n case 'expired': {\n settle(session);\n options.onError?.(new Error('Checkout session expired.'));\n break;\n }\n case 'failed': {\n settle(session);\n options.onError?.(\n new Error(event.data.message ?? 'Checkout failed.'),\n );\n break;\n }\n case 'redirect_required': {\n settle(session);\n window.location.assign(event.data.url);\n break;\n }\n default:\n break;\n }\n },\n };\n\n window.addEventListener('message', session.onMessage);\n active = session;\n const readyTimeoutMs = options.readyTimeoutMs ?? 8000;\n session.readyTimer = setTimeout(() => {\n if (!active || active !== session || session.settled) return;\n runFallback(\n session,\n 'Checkout iframe did not become ready in time (framing may be blocked).',\n );\n }, readyTimeoutMs);\n}\n\n/**\n * Closes the active overlay and notifies the iframe via close_request.\n */\nexport function close(): void {\n if (!active) return;\n const session = active;\n const contentWindow = session.overlay.iframe.contentWindow;\n if (contentWindow) {\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'close_request',\n checkoutId: session.checkoutId,\n },\n session.checkoutOrigin,\n );\n }\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n}\n\nexport function isOpen(): boolean {\n return active !== null;\n}\n","import { open } from './checkout';\n\nconst ATTR = 'data-onflay-checkout';\n\n/**\n * Delegated click handler for `[data-onflay-checkout]` anchors/buttons.\n * When JS is unavailable the element can still navigate via a normal href.\n */\nexport function bindDeclarativeCheckout(): void {\n if (typeof document === 'undefined') return;\n document.addEventListener(\n 'click',\n (event) => {\n const target = event.target;\n if (!(target instanceof Element)) return;\n const el = target.closest(`[${ATTR}]`);\n if (!(el instanceof HTMLElement)) return;\n const url =\n el.getAttribute(ATTR) ||\n (el instanceof HTMLAnchorElement ? el.href : null);\n if (!url) return;\n event.preventDefault();\n try {\n open({ url });\n } catch {\n if (el instanceof HTMLAnchorElement && el.href) {\n window.location.assign(el.href);\n }\n }\n },\n true,\n );\n}\n"],"mappings":";yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,mBAAAC,EAAA,UAAAC,EAAA,sBAAAC,EAAA,yBAAAC,EAAA,WAAAC,EAAA,SAAAC,IAAA,eAAAC,EAAAT,GCAA,IAAMU,EAAmB,IAAI,I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AD,EAAAH,EAAQ,SAAQ,WAAhB,MAAAI,EAAA,KAAAD,EAC1B,CAEO,SAASyB,GAAkB,CAChC,OAAO9B,IAAW,IACpB,CC7OA,IAAM+B,EAAO,uBAMN,SAASC,GAAgC,CAC1C,OAAO,UAAa,aACxB,SAAS,iBACP,QACCC,GAAU,CACT,IAAMC,EAASD,EAAM,OACrB,GAAI,EAAEC,aAAkB,SAAU,OAClC,IAAMC,EAAKD,EAAO,QAAQ,IAAIH,CAAI,GAAG,EACrC,GAAI,EAAEI,aAAc,aAAc,OAClC,IAAMC,EACJD,EAAG,aAAaJ,CAAI,IACnBI,aAAc,kBAAoBA,EAAG,KAAO,MAC/C,GAAKC,EACL,CAAAH,EAAM,eAAe,EACrB,GAAI,CACFI,EAAK,CAAE,IAAAD,CAAI,CAAC,CACd,OAAQE,EAAA,CACFH,aAAc,mBAAqBA,EAAG,MACxC,OAAO,SAAS,OAAOA,EAAG,IAAI,CAElC,EACF,EACA,EACF,CACF,CLlBA,IAAMI,EAAoC,CAAE,KAAAC,EAAM,MAAAC,EAAO,OAAAC,CAAO,EAQ5D,OAAO,QAAW,cACpB,OAAO,eAAiBH,EACpB,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoB,IAAM,CAClDI,EAAwB,CAC1B,CAAC,EAEDA,EAAwB","names":["src_exports","__export","ONFLAY_CHECKOUT_CHANNEL","OnflayCheckout","close","extractCheckoutId","isAllowedCheckoutUrl","isOpen","open","__toCommonJS","PRODUCTION_HOSTS","SANDBOX_HOSTS","isAllowedCheckoutUrl","url","parsed","e","host","extractCheckoutId","match","getCheckoutOrigin","STYLE_TEXT","mountOverlay","params","host","shadow","style","backdrop","dialog","title","iframe","previousOverflow","onKeyDown","event","focusable","first","last","onBackdropClick","height","clamped","ONFLAY_CHECKOUT_CHANNEL","isOnflayCheckoutOutboundMessage","data","message","type","active","settle","session","runFallback","reason","_a","_b","_c","_d","_e","fallback","postInit","contentWindow","ONFLAY_CHECKOUT_CHANNEL","open","options","isAllowedCheckoutUrl","error","checkoutId","extractCheckoutId","checkoutOrigin","getCheckoutOrigin","close","previouslyFocused","overlay","mountOverlay","event","_f","isOnflayCheckoutOutboundMessage","readyTimeoutMs","isOpen","ATTR","bindDeclarativeCheckout","event","target","el","url","open","e","OnflayCheckout","open","close","isOpen","bindDeclarativeCheckout"]}
@@ -0,0 +1,59 @@
1
+ type CheckoutFallback = 'redirect' | 'popup' | 'none';
2
+ interface OpenCheckoutOptions {
3
+ /** Embed URL from `POST /v1/checkout-sessions` with `uiMode: 'embedded'`. */
4
+ readonly url: string;
5
+ readonly onReady?: () => void;
6
+ readonly onComplete?: (event: {
7
+ readonly checkoutId: string;
8
+ }) => void;
9
+ readonly onCancel?: () => void;
10
+ readonly onError?: (error: Error) => void;
11
+ /**
12
+ * Behavior when the iframe never posts `ready`.
13
+ * Default: `redirect` (preserves payment completion).
14
+ */
15
+ readonly fallback?: CheckoutFallback;
16
+ /** Timeout before fallback, in ms. Default 8000. */
17
+ readonly readyTimeoutMs?: number;
18
+ /** Optional PostHog distinct id forwarded via init message. */
19
+ readonly distinctId?: string;
20
+ }
21
+ /**
22
+ * Opens Onflay hosted checkout in a secure overlay iframe.
23
+ */
24
+ declare function open(options: OpenCheckoutOptions): void;
25
+ /**
26
+ * Closes the active overlay and notifies the iframe via close_request.
27
+ */
28
+ declare function close(): void;
29
+ declare function isOpen(): boolean;
30
+
31
+ /**
32
+ * Returns true when `url` points at an Onflay-hosted checkout origin we trust
33
+ * to load inside the overlay iframe.
34
+ */
35
+ declare function isAllowedCheckoutUrl(url: string): boolean;
36
+ /**
37
+ * Extracts the checkout session id from an embed or hosted checkout URL.
38
+ */
39
+ declare function extractCheckoutId(url: string): string | null;
40
+
41
+ /**
42
+ * Versioned postMessage envelope for the Onflay checkout overlay.
43
+ * Must stay in sync with apps/checkout/src/lib/embed-protocol.ts.
44
+ */
45
+ declare const ONFLAY_CHECKOUT_CHANNEL: "onflay.checkout.v1";
46
+
47
+ interface OnflayCheckoutApi {
48
+ open: typeof open;
49
+ close: typeof close;
50
+ isOpen: typeof isOpen;
51
+ }
52
+ declare const OnflayCheckout: OnflayCheckoutApi;
53
+ declare global {
54
+ interface Window {
55
+ OnflayCheckout?: OnflayCheckoutApi;
56
+ }
57
+ }
58
+
59
+ export { type CheckoutFallback, ONFLAY_CHECKOUT_CHANNEL, OnflayCheckout, type OnflayCheckoutApi, type OpenCheckoutOptions, close, extractCheckoutId, isAllowedCheckoutUrl, isOpen, open };
@@ -0,0 +1,59 @@
1
+ type CheckoutFallback = 'redirect' | 'popup' | 'none';
2
+ interface OpenCheckoutOptions {
3
+ /** Embed URL from `POST /v1/checkout-sessions` with `uiMode: 'embedded'`. */
4
+ readonly url: string;
5
+ readonly onReady?: () => void;
6
+ readonly onComplete?: (event: {
7
+ readonly checkoutId: string;
8
+ }) => void;
9
+ readonly onCancel?: () => void;
10
+ readonly onError?: (error: Error) => void;
11
+ /**
12
+ * Behavior when the iframe never posts `ready`.
13
+ * Default: `redirect` (preserves payment completion).
14
+ */
15
+ readonly fallback?: CheckoutFallback;
16
+ /** Timeout before fallback, in ms. Default 8000. */
17
+ readonly readyTimeoutMs?: number;
18
+ /** Optional PostHog distinct id forwarded via init message. */
19
+ readonly distinctId?: string;
20
+ }
21
+ /**
22
+ * Opens Onflay hosted checkout in a secure overlay iframe.
23
+ */
24
+ declare function open(options: OpenCheckoutOptions): void;
25
+ /**
26
+ * Closes the active overlay and notifies the iframe via close_request.
27
+ */
28
+ declare function close(): void;
29
+ declare function isOpen(): boolean;
30
+
31
+ /**
32
+ * Returns true when `url` points at an Onflay-hosted checkout origin we trust
33
+ * to load inside the overlay iframe.
34
+ */
35
+ declare function isAllowedCheckoutUrl(url: string): boolean;
36
+ /**
37
+ * Extracts the checkout session id from an embed or hosted checkout URL.
38
+ */
39
+ declare function extractCheckoutId(url: string): string | null;
40
+
41
+ /**
42
+ * Versioned postMessage envelope for the Onflay checkout overlay.
43
+ * Must stay in sync with apps/checkout/src/lib/embed-protocol.ts.
44
+ */
45
+ declare const ONFLAY_CHECKOUT_CHANNEL: "onflay.checkout.v1";
46
+
47
+ interface OnflayCheckoutApi {
48
+ open: typeof open;
49
+ close: typeof close;
50
+ isOpen: typeof isOpen;
51
+ }
52
+ declare const OnflayCheckout: OnflayCheckoutApi;
53
+ declare global {
54
+ interface Window {
55
+ OnflayCheckout?: OnflayCheckoutApi;
56
+ }
57
+ }
58
+
59
+ export { type CheckoutFallback, ONFLAY_CHECKOUT_CHANNEL, OnflayCheckout, type OnflayCheckoutApi, type OpenCheckoutOptions, close, extractCheckoutId, isAllowedCheckoutUrl, isOpen, open };
@@ -0,0 +1,65 @@
1
+ /* @onflay/js — https://docs.onflay.com */
2
+ "use strict";(()=>{var H=new Set(["checkout.onflay.com","checkout-staging.onflay.com"]),I=new Set(["sandbox-checkout.onflay.com","sandbox-checkout-staging.onflay.com"]);function C(e){let o;try{o=new URL(e)}catch(i){return!1}if(o.protocol!=="https:"&&o.protocol!=="http:")return!1;let t=o.hostname.toLowerCase();return H.has(t)||I.has(t)?o.protocol==="https:":t==="localhost"||t==="127.0.0.1"||t==="[::1]"?o.pathname.startsWith("/embed/s/")||o.pathname.startsWith("/s/"):!1}function b(e){try{let t=new URL(e).pathname.match(/\/(?:embed\/)?s\/([^/]+)/);return t!=null&&t[1]?decodeURIComponent(t[1]):null}catch(o){return null}}function E(e){try{return new URL(e).origin}catch(o){return null}}var N=`
3
+ :host {
4
+ all: initial;
5
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
6
+ }
7
+ .backdrop {
8
+ position: fixed;
9
+ inset: 0;
10
+ z-index: 2147483000;
11
+ display: flex;
12
+ align-items: center;
13
+ justify-content: center;
14
+ padding: 24px;
15
+ background: rgba(11, 13, 18, 0.45);
16
+ backdrop-filter: blur(2px);
17
+ }
18
+ .dialog {
19
+ position: relative;
20
+ width: min(440px, 100%);
21
+ max-height: min(900px, calc(100vh - 48px));
22
+ background: #fff;
23
+ color: #0b0d12;
24
+ border-radius: 16px;
25
+ box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);
26
+ overflow: hidden;
27
+ display: flex;
28
+ flex-direction: column;
29
+ }
30
+ .frame {
31
+ width: 100%;
32
+ flex: 1 1 auto;
33
+ min-height: 640px;
34
+ border: 0;
35
+ background: #fff;
36
+ }
37
+ .sr-only {
38
+ position: absolute;
39
+ width: 1px;
40
+ height: 1px;
41
+ padding: 0;
42
+ margin: -1px;
43
+ overflow: hidden;
44
+ clip: rect(0, 0, 0, 0);
45
+ white-space: nowrap;
46
+ border: 0;
47
+ }
48
+ @media (max-width: 640px) {
49
+ .backdrop {
50
+ padding: 40px 0 0;
51
+ align-items: flex-end;
52
+ }
53
+ .dialog {
54
+ width: 100%;
55
+ max-height: 100%;
56
+ height: 100%;
57
+ border-radius: 20px 20px 0 0;
58
+ }
59
+ .frame {
60
+ min-height: 100%;
61
+ height: 100%;
62
+ }
63
+ }
64
+ `;function T(e){let o=document.createElement("div");o.setAttribute("data-onflay-checkout-overlay","true");let t=o.attachShadow({mode:"closed"}),l=document.createElement("style");l.textContent=N;let i=document.createElement("div");i.className="backdrop",i.setAttribute("role","presentation");let r=document.createElement("div");r.className="dialog",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label","Secure checkout"),r.tabIndex=-1;let s=document.createElement("h2");s.className="sr-only",s.textContent="Onflay checkout";let a=document.createElement("iframe");a.className="frame",a.title="Onflay checkout",a.setAttribute("allow","payment *; publickey-credentials-get *"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.src=e.checkoutUrl,r.appendChild(s),r.appendChild(a),i.appendChild(r),t.appendChild(l),t.appendChild(i),document.body.appendChild(o);let y=document.body.style.overflow;document.body.style.overflow="hidden",r.focus({preventScroll:!0});function h(c){if(c.key==="Escape"){c.preventDefault(),e.onBackdropClose();return}if(c.key!=="Tab")return;let d=[r,a],p=d[0],m=d[d.length-1];!p||!m||(c.shiftKey&&document.activeElement===p?(c.preventDefault(),a.focus()):!c.shiftKey&&document.activeElement===m&&(c.preventDefault(),r.focus()))}function n(c){c.target===i&&e.onBackdropClose()}return document.addEventListener("keydown",h),i.addEventListener("click",n),{host:o,iframe:a,dialog:r,setHeight(c){let d=Math.max(480,Math.min(c,window.innerHeight-32));a.style.minHeight=`${d}px`,a.style.height=`${d}px`},destroy(){document.removeEventListener("keydown",h),i.removeEventListener("click",n),document.body.style.overflow=y,o.remove(),e.previouslyFocused instanceof HTMLElement&&document.contains(e.previouslyFocused)&&e.previouslyFocused.focus({preventScroll:!0})}}}var k="onflay.checkout.v1";function M(e){if(!e||typeof e!="object")return!1;let o=e;if(o.channel!==k||typeof o.checkoutId!="string")return!1;let t=o.type;return t==="ready"||t==="resize"||t==="completed"||t==="failed"||t==="cancelled"||t==="expired"||t==="redirect_required"}var u=null;function f(e){e.settled||(e.settled=!0,e.readyTimer&&(clearTimeout(e.readyTimer),e.readyTimer=null),window.removeEventListener("message",e.onMessage),e.overlay.destroy(),u===e&&(u=null))}function U(e,o){var l,i,r,s,a;let t=(l=e.options.fallback)!=null?l:"redirect";if(f(e),t==="none"){(r=(i=e.options).onError)==null||r.call(i,new Error(o));return}if(t==="popup"){if(!window.open(e.url,"onflay_checkout","popup=yes,width=480,height=800")){(a=(s=e.options).onError)==null||a.call(s,new Error(`${o} Popup blocked; falling back to redirect.`)),window.location.assign(e.url);return}return}window.location.assign(e.url)}function _(e){let o=e.overlay.iframe.contentWindow;o&&o.postMessage({channel:k,type:"init",checkoutId:e.checkoutId,...e.options.distinctId?{distinctId:e.options.distinctId}:{}},e.checkoutOrigin)}function g(e){var a,y,h;if(typeof window=="undefined"||typeof document=="undefined")throw new Error("OnflayCheckout.open() requires a browser environment.");if(!e.url||!C(e.url)){let n=new Error("OnflayCheckout.open(): url must be an Onflay checkout embed URL.");throw(a=e.onError)==null||a.call(e,n),n}let o=b(e.url),t=E(e.url);if(!o||!t){let n=new Error("OnflayCheckout.open(): could not parse checkout session id.");throw(y=e.onError)==null||y.call(e,n),n}u&&w();let l=document.activeElement,i=T({checkoutUrl:e.url,previouslyFocused:l,onBackdropClose:()=>{var c,d;if(!u||u.settled)return;let n=u;f(n),n.completed||(d=(c=n.options).onCancel)==null||d.call(c)}}),r={url:e.url,checkoutId:o,checkoutOrigin:t,options:e,overlay:i,readyTimer:null,settled:!1,completed:!1,onMessage(n){var c,d,p,m,O,x;if(n.origin===t&&n.source===i.iframe.contentWindow&&M(n.data)&&n.data.checkoutId===o)switch(n.data.type){case"ready":{r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),_(r),(c=e.onReady)==null||c.call(e);break}case"resize":{i.setHeight(n.data.height);break}case"completed":{if(r.completed)break;r.completed=!0,r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),n.data.showsConfirmation!==!0&&f(r),(d=e.onComplete)==null||d.call(e,{checkoutId:o});break}case"cancelled":{f(r),r.completed||(p=e.onCancel)==null||p.call(e);break}case"expired":{f(r),(m=e.onError)==null||m.call(e,new Error("Checkout session expired."));break}case"failed":{f(r),(x=e.onError)==null||x.call(e,new Error((O=n.data.message)!=null?O:"Checkout failed."));break}case"redirect_required":{f(r),window.location.assign(n.data.url);break}default:break}}};window.addEventListener("message",r.onMessage),u=r;let s=(h=e.readyTimeoutMs)!=null?h:8e3;r.readyTimer=setTimeout(()=>{!u||u!==r||r.settled||U(r,"Checkout iframe did not become ready in time (framing may be blocked).")},s)}function w(){var t,l;if(!u)return;let e=u,o=e.overlay.iframe.contentWindow;o&&o.postMessage({channel:k,type:"close_request",checkoutId:e.checkoutId},e.checkoutOrigin),f(e),e.completed||(l=(t=e.options).onCancel)==null||l.call(t)}function L(){return u!==null}var A="data-onflay-checkout";function v(){typeof document!="undefined"&&document.addEventListener("click",e=>{let o=e.target;if(!(o instanceof Element))return;let t=o.closest(`[${A}]`);if(!(t instanceof HTMLElement))return;let l=t.getAttribute(A)||(t instanceof HTMLAnchorElement?t.href:null);if(l){e.preventDefault();try{g({url:l})}catch(i){t instanceof HTMLAnchorElement&&t.href&&window.location.assign(t.href)}}},!0)}var B={open:g,close:w,isOpen:L};typeof window!="undefined"&&(window.OnflayCheckout=B,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{v()}):v());})();
65
+ //# sourceMappingURL=onflay.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/origins.ts","../src/overlay.ts","../src/protocol.ts","../src/checkout.ts","../src/declarative.ts","../src/index.ts"],"sourcesContent":["const PRODUCTION_HOSTS = new Set([\n 'checkout.onflay.com',\n // Onflay's internal staging environment.\n 'checkout-staging.onflay.com',\n]);\nconst SANDBOX_HOSTS = new Set([\n 'sandbox-checkout.onflay.com',\n 'sandbox-checkout-staging.onflay.com',\n]);\n\n/**\n * Returns true when `url` points at an Onflay-hosted checkout origin we trust\n * to load inside the overlay iframe.\n */\nexport function isAllowedCheckoutUrl(url: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return false;\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n const host = parsed.hostname.toLowerCase();\n if (PRODUCTION_HOSTS.has(host) || SANDBOX_HOSTS.has(host)) {\n return parsed.protocol === 'https:';\n }\n const isLocal =\n host === 'localhost' || host === '127.0.0.1' || host === '[::1]';\n if (!isLocal) return false;\n return (\n parsed.pathname.startsWith('/embed/s/') ||\n parsed.pathname.startsWith('/s/')\n );\n}\n\n/**\n * Extracts the checkout session id from an embed or hosted checkout URL.\n */\nexport function extractCheckoutId(url: string): string | null {\n try {\n const parsed = new URL(url);\n const match = parsed.pathname.match(/\\/(?:embed\\/)?s\\/([^/]+)/);\n return match?.[1] ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\nexport function getCheckoutOrigin(url: string): string | null {\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n","const STYLE_TEXT = `\n:host {\n all: initial;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;\n}\n.backdrop {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(11, 13, 18, 0.45);\n backdrop-filter: blur(2px);\n}\n.dialog {\n position: relative;\n width: min(440px, 100%);\n max-height: min(900px, calc(100vh - 48px));\n background: #fff;\n color: #0b0d12;\n border-radius: 16px;\n box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n}\n.frame {\n width: 100%;\n flex: 1 1 auto;\n min-height: 640px;\n border: 0;\n background: #fff;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n@media (max-width: 640px) {\n .backdrop {\n padding: 40px 0 0;\n align-items: flex-end;\n }\n .dialog {\n width: 100%;\n max-height: 100%;\n height: 100%;\n border-radius: 20px 20px 0 0;\n }\n .frame {\n min-height: 100%;\n height: 100%;\n }\n}\n`;\n\nexport interface OverlayHandles {\n readonly host: HTMLDivElement;\n readonly iframe: HTMLIFrameElement;\n readonly dialog: HTMLDivElement;\n setHeight(height: number): void;\n destroy(): void;\n}\n\n/**\n * Mounts the checkout overlay in a shadow root to avoid CSS collisions.\n */\nexport function mountOverlay(params: {\n readonly checkoutUrl: string;\n readonly onBackdropClose: () => void;\n readonly previouslyFocused: Element | null;\n}): OverlayHandles {\n const host = document.createElement('div');\n host.setAttribute('data-onflay-checkout-overlay', 'true');\n const shadow = host.attachShadow({ mode: 'closed' });\n const style = document.createElement('style');\n style.textContent = STYLE_TEXT;\n const backdrop = document.createElement('div');\n backdrop.className = 'backdrop';\n backdrop.setAttribute('role', 'presentation');\n const dialog = document.createElement('div');\n dialog.className = 'dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.setAttribute('aria-label', 'Secure checkout');\n dialog.tabIndex = -1;\n const title = document.createElement('h2');\n title.className = 'sr-only';\n title.textContent = 'Onflay checkout';\n const iframe = document.createElement('iframe');\n iframe.className = 'frame';\n iframe.title = 'Onflay checkout';\n iframe.setAttribute('allow', 'payment *; publickey-credentials-get *');\n iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');\n iframe.src = params.checkoutUrl;\n dialog.appendChild(title);\n dialog.appendChild(iframe);\n backdrop.appendChild(dialog);\n shadow.appendChild(style);\n shadow.appendChild(backdrop);\n document.body.appendChild(host);\n const previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n dialog.focus({ preventScroll: true });\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key === 'Escape') {\n event.preventDefault();\n params.onBackdropClose();\n return;\n }\n if (event.key !== 'Tab') return;\n const focusable = [dialog, iframe];\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n iframe.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n dialog.focus();\n }\n }\n\n function onBackdropClick(event: MouseEvent): void {\n if (event.target === backdrop) params.onBackdropClose();\n }\n\n document.addEventListener('keydown', onKeyDown);\n backdrop.addEventListener('click', onBackdropClick);\n\n return {\n host,\n iframe,\n dialog,\n setHeight(height: number): void {\n const clamped = Math.max(480, Math.min(height, window.innerHeight - 32));\n iframe.style.minHeight = `${clamped}px`;\n iframe.style.height = `${clamped}px`;\n },\n destroy(): void {\n document.removeEventListener('keydown', onKeyDown);\n backdrop.removeEventListener('click', onBackdropClick);\n document.body.style.overflow = previousOverflow;\n host.remove();\n if (\n params.previouslyFocused instanceof HTMLElement &&\n document.contains(params.previouslyFocused)\n ) {\n params.previouslyFocused.focus({ preventScroll: true });\n }\n },\n };\n}\n","/**\n * Versioned postMessage envelope for the Onflay checkout overlay.\n * Must stay in sync with apps/checkout/src/lib/embed-protocol.ts.\n */\nexport const ONFLAY_CHECKOUT_CHANNEL = 'onflay.checkout.v1' as const;\n\nexport interface OnflayCheckoutMessageBase {\n readonly channel: typeof ONFLAY_CHECKOUT_CHANNEL;\n readonly type: string;\n readonly checkoutId: string;\n}\n\nexport type OnflayCheckoutOutboundMessage =\n | (OnflayCheckoutMessageBase & { readonly type: 'ready' })\n | (OnflayCheckoutMessageBase & { readonly type: 'resize'; readonly height: number })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'completed';\n /**\n * The iframe shows its own payment confirmation: keep the overlay open until the\n * buyer closes it. Older checkout builds omit it, and the overlay closes at once.\n */\n readonly showsConfirmation?: boolean;\n })\n | (OnflayCheckoutMessageBase & { readonly type: 'failed'; readonly message?: string })\n | (OnflayCheckoutMessageBase & { readonly type: 'cancelled' })\n | (OnflayCheckoutMessageBase & { readonly type: 'expired' })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'redirect_required';\n readonly url: string;\n });\n\nexport function isOnflayCheckoutOutboundMessage(\n data: unknown,\n): data is OnflayCheckoutOutboundMessage {\n if (!data || typeof data !== 'object') return false;\n const message = data as Record<string, unknown>;\n if (message.channel !== ONFLAY_CHECKOUT_CHANNEL) return false;\n if (typeof message.checkoutId !== 'string') return false;\n const type = message.type;\n return (\n type === 'ready' ||\n type === 'resize' ||\n type === 'completed' ||\n type === 'failed' ||\n type === 'cancelled' ||\n type === 'expired' ||\n type === 'redirect_required'\n );\n}\n","import {\n extractCheckoutId,\n getCheckoutOrigin,\n isAllowedCheckoutUrl,\n} from './origins';\nimport { mountOverlay, type OverlayHandles } from './overlay';\nimport {\n ONFLAY_CHECKOUT_CHANNEL,\n isOnflayCheckoutOutboundMessage,\n} from './protocol';\n\nexport type CheckoutFallback = 'redirect' | 'popup' | 'none';\n\nexport interface OpenCheckoutOptions {\n /** Embed URL from `POST /v1/checkout-sessions` with `uiMode: 'embedded'`. */\n readonly url: string;\n readonly onReady?: () => void;\n readonly onComplete?: (event: { readonly checkoutId: string }) => void;\n readonly onCancel?: () => void;\n readonly onError?: (error: Error) => void;\n /**\n * Behavior when the iframe never posts `ready`.\n * Default: `redirect` (preserves payment completion).\n */\n readonly fallback?: CheckoutFallback;\n /** Timeout before fallback, in ms. Default 8000. */\n readonly readyTimeoutMs?: number;\n /** Optional PostHog distinct id forwarded via init message. */\n readonly distinctId?: string;\n}\n\ninterface ActiveCheckout {\n readonly url: string;\n readonly checkoutId: string;\n readonly checkoutOrigin: string;\n readonly options: OpenCheckoutOptions;\n readonly overlay: OverlayHandles;\n readonly onMessage: (event: MessageEvent) => void;\n readyTimer: ReturnType<typeof setTimeout> | null;\n settled: boolean;\n /** Payment completed and onComplete fired; closing now only dismisses the overlay. */\n completed: boolean;\n}\n\nlet active: ActiveCheckout | null = null;\n\nfunction settle(session: ActiveCheckout): void {\n if (session.settled) return;\n session.settled = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n window.removeEventListener('message', session.onMessage);\n session.overlay.destroy();\n if (active === session) active = null;\n}\n\nfunction runFallback(session: ActiveCheckout, reason: string): void {\n const fallback = session.options.fallback ?? 'redirect';\n settle(session);\n if (fallback === 'none') {\n session.options.onError?.(new Error(reason));\n return;\n }\n if (fallback === 'popup') {\n const popup = window.open(\n session.url,\n 'onflay_checkout',\n 'popup=yes,width=480,height=800',\n );\n if (!popup) {\n session.options.onError?.(\n new Error(`${reason} Popup blocked; falling back to redirect.`),\n );\n window.location.assign(session.url);\n return;\n }\n return;\n }\n window.location.assign(session.url);\n}\n\nfunction postInit(session: ActiveCheckout): void {\n const contentWindow = session.overlay.iframe.contentWindow;\n if (!contentWindow) return;\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'init',\n checkoutId: session.checkoutId,\n ...(session.options.distinctId\n ? { distinctId: session.options.distinctId }\n : {}),\n },\n session.checkoutOrigin,\n );\n}\n\n/**\n * Opens Onflay hosted checkout in a secure overlay iframe.\n */\nexport function open(options: OpenCheckoutOptions): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('OnflayCheckout.open() requires a browser environment.');\n }\n if (!options.url || !isAllowedCheckoutUrl(options.url)) {\n const error = new Error(\n 'OnflayCheckout.open(): url must be an Onflay checkout embed URL.',\n );\n options.onError?.(error);\n throw error;\n }\n const checkoutId = extractCheckoutId(options.url);\n const checkoutOrigin = getCheckoutOrigin(options.url);\n if (!checkoutId || !checkoutOrigin) {\n const error = new Error(\n 'OnflayCheckout.open(): could not parse checkout session id.',\n );\n options.onError?.(error);\n throw error;\n }\n if (active) close();\n\n const previouslyFocused = document.activeElement;\n const overlay = mountOverlay({\n checkoutUrl: options.url,\n previouslyFocused,\n onBackdropClose: () => {\n if (!active || active.settled) return;\n const session = active;\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n },\n });\n\n const session: ActiveCheckout = {\n url: options.url,\n checkoutId,\n checkoutOrigin,\n options,\n overlay,\n readyTimer: null,\n settled: false,\n completed: false,\n onMessage(event: MessageEvent): void {\n if (event.origin !== checkoutOrigin) return;\n if (event.source !== overlay.iframe.contentWindow) return;\n if (!isOnflayCheckoutOutboundMessage(event.data)) return;\n if (event.data.checkoutId !== checkoutId) return;\n switch (event.data.type) {\n case 'ready': {\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n postInit(session);\n options.onReady?.();\n break;\n }\n case 'resize': {\n overlay.setHeight(event.data.height);\n break;\n }\n case 'completed': {\n if (session.completed) break;\n session.completed = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n // A checkout that shows its own confirmation stays open until the buyer closes it.\n if (event.data.showsConfirmation !== true) settle(session);\n options.onComplete?.({ checkoutId });\n break;\n }\n case 'cancelled': {\n settle(session);\n if (!session.completed) options.onCancel?.();\n break;\n }\n case 'expired': {\n settle(session);\n options.onError?.(new Error('Checkout session expired.'));\n break;\n }\n case 'failed': {\n settle(session);\n options.onError?.(\n new Error(event.data.message ?? 'Checkout failed.'),\n );\n break;\n }\n case 'redirect_required': {\n settle(session);\n window.location.assign(event.data.url);\n break;\n }\n default:\n break;\n }\n },\n };\n\n window.addEventListener('message', session.onMessage);\n active = session;\n const readyTimeoutMs = options.readyTimeoutMs ?? 8000;\n session.readyTimer = setTimeout(() => {\n if (!active || active !== session || session.settled) return;\n runFallback(\n session,\n 'Checkout iframe did not become ready in time (framing may be blocked).',\n );\n }, readyTimeoutMs);\n}\n\n/**\n * Closes the active overlay and notifies the iframe via close_request.\n */\nexport function close(): void {\n if (!active) return;\n const session = active;\n const contentWindow = session.overlay.iframe.contentWindow;\n if (contentWindow) {\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'close_request',\n checkoutId: session.checkoutId,\n },\n session.checkoutOrigin,\n );\n }\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n}\n\nexport function isOpen(): boolean {\n return active !== null;\n}\n","import { open } from './checkout';\n\nconst ATTR = 'data-onflay-checkout';\n\n/**\n * Delegated click handler for `[data-onflay-checkout]` anchors/buttons.\n * When JS is unavailable the element can still navigate via a normal href.\n */\nexport function bindDeclarativeCheckout(): void {\n if (typeof document === 'undefined') return;\n document.addEventListener(\n 'click',\n (event) => {\n const target = event.target;\n if (!(target instanceof Element)) return;\n const el = target.closest(`[${ATTR}]`);\n if (!(el instanceof HTMLElement)) return;\n const url =\n el.getAttribute(ATTR) ||\n (el instanceof HTMLAnchorElement ? el.href : null);\n if (!url) return;\n event.preventDefault();\n try {\n open({ url });\n } catch {\n if (el instanceof HTMLAnchorElement && el.href) {\n window.location.assign(el.href);\n }\n }\n },\n true,\n );\n}\n","import { close, isOpen, open } from './checkout';\nimport { bindDeclarativeCheckout } from './declarative';\n\nexport type { OpenCheckoutOptions, CheckoutFallback } from './checkout';\nexport { open, close, isOpen };\nexport { isAllowedCheckoutUrl, extractCheckoutId } from './origins';\nexport { ONFLAY_CHECKOUT_CHANNEL } from './protocol';\n\nexport interface OnflayCheckoutApi {\n open: typeof open;\n close: typeof close;\n isOpen: typeof isOpen;\n}\n\nconst OnflayCheckout: OnflayCheckoutApi = { open, close, isOpen };\n\ndeclare global {\n interface Window {\n OnflayCheckout?: OnflayCheckoutApi;\n }\n}\n\nif (typeof window !== 'undefined') {\n window.OnflayCheckout = OnflayCheckout;\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n bindDeclarativeCheckout();\n });\n } else {\n bindDeclarativeCheckout();\n }\n}\n\nexport { OnflayCheckout };\n"],"mappings":";mBAAA,IAAMA,EAAmB,IAAI,IAAI,CAC/B,sBAEA,6BACF,CAAC,EACKC,EAAgB,IAAI,IAAI,CAC5B,8BACA,qCACF,CAAC,EAMM,SAASC,EAAqBC,EAAsB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAI,IAAID,CAAG,CACtB,OAAQE,EAAA,CACN,MAAO,EACT,CACA,GAAID,EAAO,WAAa,UAAYA,EAAO,WAAa,QAAS,MAAO,GACxE,IAAME,EAAOF,EAAO,SAAS,YAAY,EACzC,OAAIJ,EAAiB,IAAIM,CAAI,GAAKL,EAAc,IAAIK,CAAI,EAC/CF,EAAO,WAAa,SAG3BE,IAAS,aAAeA,IAAS,aAAeA,IAAS,QAGzDF,EAAO,SAAS,WAAW,WAAW,GACtCA,EAAO,SAAS,WAAW,KAAK,EAHb,EAKvB,CAKO,SAASG,EAAkBJ,EAA4B,CAC5D,GAAI,CAEF,IAAMK,EADS,IAAI,IAAIL,CAAG,EACL,SAAS,MAAM,0BAA0B,EAC9D,OAAOK,GAAA,MAAAA,EAAQ,GAAK,mBAAmBA,EAAM,CAAC,CAAC,EAAI,IACrD,OAAQH,EAAA,CACN,OAAO,IACT,CACF,CAEO,SAASI,EAAkBN,EAA4B,CAC5D,GAAI,CACF,OAAO,IAAI,IAAIA,CAAG,EAAE,MACtB,OAAQE,EAAA,CACN,OAAO,IACT,CACF,CCtDA,IAAMK,EAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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Origin","STYLE_TEXT","mountOverlay","params","host","shadow","style","backdrop","dialog","title","iframe","previousOverflow","onKeyDown","event","focusable","first","last","onBackdropClick","height","clamped","ONFLAY_CHECKOUT_CHANNEL","isOnflayCheckoutOutboundMessage","data","message","type","active","settle","session","runFallback","reason","_a","_b","_c","_d","_e","fallback","postInit","contentWindow","ONFLAY_CHECKOUT_CHANNEL","open","options","isAllowedCheckoutUrl","error","checkoutId","extractCheckoutId","checkoutOrigin","getCheckoutOrigin","close","previouslyFocused","overlay","mountOverlay","event","_f","isOnflayCheckoutOutboundMessage","readyTimeoutMs","isOpen","ATTR","bindDeclarativeCheckout","event","target","el","url","open","e","OnflayCheckout","open","close","isOpen","bindDeclarativeCheckout"]}
package/dist/onflay.js ADDED
@@ -0,0 +1,65 @@
1
+ /* @onflay/js — https://docs.onflay.com */
2
+ var H=new Set(["checkout.onflay.com","checkout-staging.onflay.com"]),I=new Set(["sandbox-checkout.onflay.com","sandbox-checkout-staging.onflay.com"]);function C(e){let o;try{o=new URL(e)}catch(i){return!1}if(o.protocol!=="https:"&&o.protocol!=="http:")return!1;let t=o.hostname.toLowerCase();return H.has(t)||I.has(t)?o.protocol==="https:":t==="localhost"||t==="127.0.0.1"||t==="[::1]"?o.pathname.startsWith("/embed/s/")||o.pathname.startsWith("/s/"):!1}function b(e){try{let t=new URL(e).pathname.match(/\/(?:embed\/)?s\/([^/]+)/);return t!=null&&t[1]?decodeURIComponent(t[1]):null}catch(o){return null}}function E(e){try{return new URL(e).origin}catch(o){return null}}var N=`
3
+ :host {
4
+ all: initial;
5
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
6
+ }
7
+ .backdrop {
8
+ position: fixed;
9
+ inset: 0;
10
+ z-index: 2147483000;
11
+ display: flex;
12
+ align-items: center;
13
+ justify-content: center;
14
+ padding: 24px;
15
+ background: rgba(11, 13, 18, 0.45);
16
+ backdrop-filter: blur(2px);
17
+ }
18
+ .dialog {
19
+ position: relative;
20
+ width: min(440px, 100%);
21
+ max-height: min(900px, calc(100vh - 48px));
22
+ background: #fff;
23
+ color: #0b0d12;
24
+ border-radius: 16px;
25
+ box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);
26
+ overflow: hidden;
27
+ display: flex;
28
+ flex-direction: column;
29
+ }
30
+ .frame {
31
+ width: 100%;
32
+ flex: 1 1 auto;
33
+ min-height: 640px;
34
+ border: 0;
35
+ background: #fff;
36
+ }
37
+ .sr-only {
38
+ position: absolute;
39
+ width: 1px;
40
+ height: 1px;
41
+ padding: 0;
42
+ margin: -1px;
43
+ overflow: hidden;
44
+ clip: rect(0, 0, 0, 0);
45
+ white-space: nowrap;
46
+ border: 0;
47
+ }
48
+ @media (max-width: 640px) {
49
+ .backdrop {
50
+ padding: 40px 0 0;
51
+ align-items: flex-end;
52
+ }
53
+ .dialog {
54
+ width: 100%;
55
+ max-height: 100%;
56
+ height: 100%;
57
+ border-radius: 20px 20px 0 0;
58
+ }
59
+ .frame {
60
+ min-height: 100%;
61
+ height: 100%;
62
+ }
63
+ }
64
+ `;function T(e){let o=document.createElement("div");o.setAttribute("data-onflay-checkout-overlay","true");let t=o.attachShadow({mode:"closed"}),l=document.createElement("style");l.textContent=N;let i=document.createElement("div");i.className="backdrop",i.setAttribute("role","presentation");let r=document.createElement("div");r.className="dialog",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label","Secure checkout"),r.tabIndex=-1;let s=document.createElement("h2");s.className="sr-only",s.textContent="Onflay checkout";let a=document.createElement("iframe");a.className="frame",a.title="Onflay checkout",a.setAttribute("allow","payment *; publickey-credentials-get *"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.src=e.checkoutUrl,r.appendChild(s),r.appendChild(a),i.appendChild(r),t.appendChild(l),t.appendChild(i),document.body.appendChild(o);let y=document.body.style.overflow;document.body.style.overflow="hidden",r.focus({preventScroll:!0});function h(c){if(c.key==="Escape"){c.preventDefault(),e.onBackdropClose();return}if(c.key!=="Tab")return;let d=[r,a],p=d[0],m=d[d.length-1];!p||!m||(c.shiftKey&&document.activeElement===p?(c.preventDefault(),a.focus()):!c.shiftKey&&document.activeElement===m&&(c.preventDefault(),r.focus()))}function n(c){c.target===i&&e.onBackdropClose()}return document.addEventListener("keydown",h),i.addEventListener("click",n),{host:o,iframe:a,dialog:r,setHeight(c){let d=Math.max(480,Math.min(c,window.innerHeight-32));a.style.minHeight=`${d}px`,a.style.height=`${d}px`},destroy(){document.removeEventListener("keydown",h),i.removeEventListener("click",n),document.body.style.overflow=y,o.remove(),e.previouslyFocused instanceof HTMLElement&&document.contains(e.previouslyFocused)&&e.previouslyFocused.focus({preventScroll:!0})}}}var k="onflay.checkout.v1";function M(e){if(!e||typeof e!="object")return!1;let o=e;if(o.channel!==k||typeof o.checkoutId!="string")return!1;let t=o.type;return t==="ready"||t==="resize"||t==="completed"||t==="failed"||t==="cancelled"||t==="expired"||t==="redirect_required"}var u=null;function f(e){e.settled||(e.settled=!0,e.readyTimer&&(clearTimeout(e.readyTimer),e.readyTimer=null),window.removeEventListener("message",e.onMessage),e.overlay.destroy(),u===e&&(u=null))}function U(e,o){var l,i,r,s,a;let t=(l=e.options.fallback)!=null?l:"redirect";if(f(e),t==="none"){(r=(i=e.options).onError)==null||r.call(i,new Error(o));return}if(t==="popup"){if(!window.open(e.url,"onflay_checkout","popup=yes,width=480,height=800")){(a=(s=e.options).onError)==null||a.call(s,new Error(`${o} Popup blocked; falling back to redirect.`)),window.location.assign(e.url);return}return}window.location.assign(e.url)}function _(e){let o=e.overlay.iframe.contentWindow;o&&o.postMessage({channel:k,type:"init",checkoutId:e.checkoutId,...e.options.distinctId?{distinctId:e.options.distinctId}:{}},e.checkoutOrigin)}function g(e){var a,y,h;if(typeof window=="undefined"||typeof document=="undefined")throw new Error("OnflayCheckout.open() requires a browser environment.");if(!e.url||!C(e.url)){let n=new Error("OnflayCheckout.open(): url must be an Onflay checkout embed URL.");throw(a=e.onError)==null||a.call(e,n),n}let o=b(e.url),t=E(e.url);if(!o||!t){let n=new Error("OnflayCheckout.open(): could not parse checkout session id.");throw(y=e.onError)==null||y.call(e,n),n}u&&w();let l=document.activeElement,i=T({checkoutUrl:e.url,previouslyFocused:l,onBackdropClose:()=>{var c,d;if(!u||u.settled)return;let n=u;f(n),n.completed||(d=(c=n.options).onCancel)==null||d.call(c)}}),r={url:e.url,checkoutId:o,checkoutOrigin:t,options:e,overlay:i,readyTimer:null,settled:!1,completed:!1,onMessage(n){var c,d,p,m,O,x;if(n.origin===t&&n.source===i.iframe.contentWindow&&M(n.data)&&n.data.checkoutId===o)switch(n.data.type){case"ready":{r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),_(r),(c=e.onReady)==null||c.call(e);break}case"resize":{i.setHeight(n.data.height);break}case"completed":{if(r.completed)break;r.completed=!0,r.readyTimer&&(clearTimeout(r.readyTimer),r.readyTimer=null),n.data.showsConfirmation!==!0&&f(r),(d=e.onComplete)==null||d.call(e,{checkoutId:o});break}case"cancelled":{f(r),r.completed||(p=e.onCancel)==null||p.call(e);break}case"expired":{f(r),(m=e.onError)==null||m.call(e,new Error("Checkout session expired."));break}case"failed":{f(r),(x=e.onError)==null||x.call(e,new Error((O=n.data.message)!=null?O:"Checkout failed."));break}case"redirect_required":{f(r),window.location.assign(n.data.url);break}default:break}}};window.addEventListener("message",r.onMessage),u=r;let s=(h=e.readyTimeoutMs)!=null?h:8e3;r.readyTimer=setTimeout(()=>{!u||u!==r||r.settled||U(r,"Checkout iframe did not become ready in time (framing may be blocked).")},s)}function w(){var t,l;if(!u)return;let e=u,o=e.overlay.iframe.contentWindow;o&&o.postMessage({channel:k,type:"close_request",checkoutId:e.checkoutId},e.checkoutOrigin),f(e),e.completed||(l=(t=e.options).onCancel)==null||l.call(t)}function L(){return u!==null}var A="data-onflay-checkout";function v(){typeof document!="undefined"&&document.addEventListener("click",e=>{let o=e.target;if(!(o instanceof Element))return;let t=o.closest(`[${A}]`);if(!(t instanceof HTMLElement))return;let l=t.getAttribute(A)||(t instanceof HTMLAnchorElement?t.href:null);if(l){e.preventDefault();try{g({url:l})}catch(i){t instanceof HTMLAnchorElement&&t.href&&window.location.assign(t.href)}}},!0)}var B={open:g,close:w,isOpen:L};typeof window!="undefined"&&(window.OnflayCheckout=B,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{v()}):v());export{k as ONFLAY_CHECKOUT_CHANNEL,B as OnflayCheckout,w as close,b as extractCheckoutId,C as isAllowedCheckoutUrl,L as isOpen,g as open};
65
+ //# sourceMappingURL=onflay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/origins.ts","../src/overlay.ts","../src/protocol.ts","../src/checkout.ts","../src/declarative.ts","../src/index.ts"],"sourcesContent":["const PRODUCTION_HOSTS = new Set([\n 'checkout.onflay.com',\n // Onflay's internal staging environment.\n 'checkout-staging.onflay.com',\n]);\nconst SANDBOX_HOSTS = new Set([\n 'sandbox-checkout.onflay.com',\n 'sandbox-checkout-staging.onflay.com',\n]);\n\n/**\n * Returns true when `url` points at an Onflay-hosted checkout origin we trust\n * to load inside the overlay iframe.\n */\nexport function isAllowedCheckoutUrl(url: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return false;\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n const host = parsed.hostname.toLowerCase();\n if (PRODUCTION_HOSTS.has(host) || SANDBOX_HOSTS.has(host)) {\n return parsed.protocol === 'https:';\n }\n const isLocal =\n host === 'localhost' || host === '127.0.0.1' || host === '[::1]';\n if (!isLocal) return false;\n return (\n parsed.pathname.startsWith('/embed/s/') ||\n parsed.pathname.startsWith('/s/')\n );\n}\n\n/**\n * Extracts the checkout session id from an embed or hosted checkout URL.\n */\nexport function extractCheckoutId(url: string): string | null {\n try {\n const parsed = new URL(url);\n const match = parsed.pathname.match(/\\/(?:embed\\/)?s\\/([^/]+)/);\n return match?.[1] ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\nexport function getCheckoutOrigin(url: string): string | null {\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n","const STYLE_TEXT = `\n:host {\n all: initial;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;\n}\n.backdrop {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: rgba(11, 13, 18, 0.45);\n backdrop-filter: blur(2px);\n}\n.dialog {\n position: relative;\n width: min(440px, 100%);\n max-height: min(900px, calc(100vh - 48px));\n background: #fff;\n color: #0b0d12;\n border-radius: 16px;\n box-shadow: 0 24px 64px -16px rgba(11, 13, 18, 0.5);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n}\n.frame {\n width: 100%;\n flex: 1 1 auto;\n min-height: 640px;\n border: 0;\n background: #fff;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n@media (max-width: 640px) {\n .backdrop {\n padding: 40px 0 0;\n align-items: flex-end;\n }\n .dialog {\n width: 100%;\n max-height: 100%;\n height: 100%;\n border-radius: 20px 20px 0 0;\n }\n .frame {\n min-height: 100%;\n height: 100%;\n }\n}\n`;\n\nexport interface OverlayHandles {\n readonly host: HTMLDivElement;\n readonly iframe: HTMLIFrameElement;\n readonly dialog: HTMLDivElement;\n setHeight(height: number): void;\n destroy(): void;\n}\n\n/**\n * Mounts the checkout overlay in a shadow root to avoid CSS collisions.\n */\nexport function mountOverlay(params: {\n readonly checkoutUrl: string;\n readonly onBackdropClose: () => void;\n readonly previouslyFocused: Element | null;\n}): OverlayHandles {\n const host = document.createElement('div');\n host.setAttribute('data-onflay-checkout-overlay', 'true');\n const shadow = host.attachShadow({ mode: 'closed' });\n const style = document.createElement('style');\n style.textContent = STYLE_TEXT;\n const backdrop = document.createElement('div');\n backdrop.className = 'backdrop';\n backdrop.setAttribute('role', 'presentation');\n const dialog = document.createElement('div');\n dialog.className = 'dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.setAttribute('aria-label', 'Secure checkout');\n dialog.tabIndex = -1;\n const title = document.createElement('h2');\n title.className = 'sr-only';\n title.textContent = 'Onflay checkout';\n const iframe = document.createElement('iframe');\n iframe.className = 'frame';\n iframe.title = 'Onflay checkout';\n iframe.setAttribute('allow', 'payment *; publickey-credentials-get *');\n iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');\n iframe.src = params.checkoutUrl;\n dialog.appendChild(title);\n dialog.appendChild(iframe);\n backdrop.appendChild(dialog);\n shadow.appendChild(style);\n shadow.appendChild(backdrop);\n document.body.appendChild(host);\n const previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n dialog.focus({ preventScroll: true });\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key === 'Escape') {\n event.preventDefault();\n params.onBackdropClose();\n return;\n }\n if (event.key !== 'Tab') return;\n const focusable = [dialog, iframe];\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n iframe.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n dialog.focus();\n }\n }\n\n function onBackdropClick(event: MouseEvent): void {\n if (event.target === backdrop) params.onBackdropClose();\n }\n\n document.addEventListener('keydown', onKeyDown);\n backdrop.addEventListener('click', onBackdropClick);\n\n return {\n host,\n iframe,\n dialog,\n setHeight(height: number): void {\n const clamped = Math.max(480, Math.min(height, window.innerHeight - 32));\n iframe.style.minHeight = `${clamped}px`;\n iframe.style.height = `${clamped}px`;\n },\n destroy(): void {\n document.removeEventListener('keydown', onKeyDown);\n backdrop.removeEventListener('click', onBackdropClick);\n document.body.style.overflow = previousOverflow;\n host.remove();\n if (\n params.previouslyFocused instanceof HTMLElement &&\n document.contains(params.previouslyFocused)\n ) {\n params.previouslyFocused.focus({ preventScroll: true });\n }\n },\n };\n}\n","/**\n * Versioned postMessage envelope for the Onflay checkout overlay.\n * Must stay in sync with apps/checkout/src/lib/embed-protocol.ts.\n */\nexport const ONFLAY_CHECKOUT_CHANNEL = 'onflay.checkout.v1' as const;\n\nexport interface OnflayCheckoutMessageBase {\n readonly channel: typeof ONFLAY_CHECKOUT_CHANNEL;\n readonly type: string;\n readonly checkoutId: string;\n}\n\nexport type OnflayCheckoutOutboundMessage =\n | (OnflayCheckoutMessageBase & { readonly type: 'ready' })\n | (OnflayCheckoutMessageBase & { readonly type: 'resize'; readonly height: number })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'completed';\n /**\n * The iframe shows its own payment confirmation: keep the overlay open until the\n * buyer closes it. Older checkout builds omit it, and the overlay closes at once.\n */\n readonly showsConfirmation?: boolean;\n })\n | (OnflayCheckoutMessageBase & { readonly type: 'failed'; readonly message?: string })\n | (OnflayCheckoutMessageBase & { readonly type: 'cancelled' })\n | (OnflayCheckoutMessageBase & { readonly type: 'expired' })\n | (OnflayCheckoutMessageBase & {\n readonly type: 'redirect_required';\n readonly url: string;\n });\n\nexport function isOnflayCheckoutOutboundMessage(\n data: unknown,\n): data is OnflayCheckoutOutboundMessage {\n if (!data || typeof data !== 'object') return false;\n const message = data as Record<string, unknown>;\n if (message.channel !== ONFLAY_CHECKOUT_CHANNEL) return false;\n if (typeof message.checkoutId !== 'string') return false;\n const type = message.type;\n return (\n type === 'ready' ||\n type === 'resize' ||\n type === 'completed' ||\n type === 'failed' ||\n type === 'cancelled' ||\n type === 'expired' ||\n type === 'redirect_required'\n );\n}\n","import {\n extractCheckoutId,\n getCheckoutOrigin,\n isAllowedCheckoutUrl,\n} from './origins';\nimport { mountOverlay, type OverlayHandles } from './overlay';\nimport {\n ONFLAY_CHECKOUT_CHANNEL,\n isOnflayCheckoutOutboundMessage,\n} from './protocol';\n\nexport type CheckoutFallback = 'redirect' | 'popup' | 'none';\n\nexport interface OpenCheckoutOptions {\n /** Embed URL from `POST /v1/checkout-sessions` with `uiMode: 'embedded'`. */\n readonly url: string;\n readonly onReady?: () => void;\n readonly onComplete?: (event: { readonly checkoutId: string }) => void;\n readonly onCancel?: () => void;\n readonly onError?: (error: Error) => void;\n /**\n * Behavior when the iframe never posts `ready`.\n * Default: `redirect` (preserves payment completion).\n */\n readonly fallback?: CheckoutFallback;\n /** Timeout before fallback, in ms. Default 8000. */\n readonly readyTimeoutMs?: number;\n /** Optional PostHog distinct id forwarded via init message. */\n readonly distinctId?: string;\n}\n\ninterface ActiveCheckout {\n readonly url: string;\n readonly checkoutId: string;\n readonly checkoutOrigin: string;\n readonly options: OpenCheckoutOptions;\n readonly overlay: OverlayHandles;\n readonly onMessage: (event: MessageEvent) => void;\n readyTimer: ReturnType<typeof setTimeout> | null;\n settled: boolean;\n /** Payment completed and onComplete fired; closing now only dismisses the overlay. */\n completed: boolean;\n}\n\nlet active: ActiveCheckout | null = null;\n\nfunction settle(session: ActiveCheckout): void {\n if (session.settled) return;\n session.settled = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n window.removeEventListener('message', session.onMessage);\n session.overlay.destroy();\n if (active === session) active = null;\n}\n\nfunction runFallback(session: ActiveCheckout, reason: string): void {\n const fallback = session.options.fallback ?? 'redirect';\n settle(session);\n if (fallback === 'none') {\n session.options.onError?.(new Error(reason));\n return;\n }\n if (fallback === 'popup') {\n const popup = window.open(\n session.url,\n 'onflay_checkout',\n 'popup=yes,width=480,height=800',\n );\n if (!popup) {\n session.options.onError?.(\n new Error(`${reason} Popup blocked; falling back to redirect.`),\n );\n window.location.assign(session.url);\n return;\n }\n return;\n }\n window.location.assign(session.url);\n}\n\nfunction postInit(session: ActiveCheckout): void {\n const contentWindow = session.overlay.iframe.contentWindow;\n if (!contentWindow) return;\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'init',\n checkoutId: session.checkoutId,\n ...(session.options.distinctId\n ? { distinctId: session.options.distinctId }\n : {}),\n },\n session.checkoutOrigin,\n );\n}\n\n/**\n * Opens Onflay hosted checkout in a secure overlay iframe.\n */\nexport function open(options: OpenCheckoutOptions): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('OnflayCheckout.open() requires a browser environment.');\n }\n if (!options.url || !isAllowedCheckoutUrl(options.url)) {\n const error = new Error(\n 'OnflayCheckout.open(): url must be an Onflay checkout embed URL.',\n );\n options.onError?.(error);\n throw error;\n }\n const checkoutId = extractCheckoutId(options.url);\n const checkoutOrigin = getCheckoutOrigin(options.url);\n if (!checkoutId || !checkoutOrigin) {\n const error = new Error(\n 'OnflayCheckout.open(): could not parse checkout session id.',\n );\n options.onError?.(error);\n throw error;\n }\n if (active) close();\n\n const previouslyFocused = document.activeElement;\n const overlay = mountOverlay({\n checkoutUrl: options.url,\n previouslyFocused,\n onBackdropClose: () => {\n if (!active || active.settled) return;\n const session = active;\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n },\n });\n\n const session: ActiveCheckout = {\n url: options.url,\n checkoutId,\n checkoutOrigin,\n options,\n overlay,\n readyTimer: null,\n settled: false,\n completed: false,\n onMessage(event: MessageEvent): void {\n if (event.origin !== checkoutOrigin) return;\n if (event.source !== overlay.iframe.contentWindow) return;\n if (!isOnflayCheckoutOutboundMessage(event.data)) return;\n if (event.data.checkoutId !== checkoutId) return;\n switch (event.data.type) {\n case 'ready': {\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n postInit(session);\n options.onReady?.();\n break;\n }\n case 'resize': {\n overlay.setHeight(event.data.height);\n break;\n }\n case 'completed': {\n if (session.completed) break;\n session.completed = true;\n if (session.readyTimer) {\n clearTimeout(session.readyTimer);\n session.readyTimer = null;\n }\n // A checkout that shows its own confirmation stays open until the buyer closes it.\n if (event.data.showsConfirmation !== true) settle(session);\n options.onComplete?.({ checkoutId });\n break;\n }\n case 'cancelled': {\n settle(session);\n if (!session.completed) options.onCancel?.();\n break;\n }\n case 'expired': {\n settle(session);\n options.onError?.(new Error('Checkout session expired.'));\n break;\n }\n case 'failed': {\n settle(session);\n options.onError?.(\n new Error(event.data.message ?? 'Checkout failed.'),\n );\n break;\n }\n case 'redirect_required': {\n settle(session);\n window.location.assign(event.data.url);\n break;\n }\n default:\n break;\n }\n },\n };\n\n window.addEventListener('message', session.onMessage);\n active = session;\n const readyTimeoutMs = options.readyTimeoutMs ?? 8000;\n session.readyTimer = setTimeout(() => {\n if (!active || active !== session || session.settled) return;\n runFallback(\n session,\n 'Checkout iframe did not become ready in time (framing may be blocked).',\n );\n }, readyTimeoutMs);\n}\n\n/**\n * Closes the active overlay and notifies the iframe via close_request.\n */\nexport function close(): void {\n if (!active) return;\n const session = active;\n const contentWindow = session.overlay.iframe.contentWindow;\n if (contentWindow) {\n contentWindow.postMessage(\n {\n channel: ONFLAY_CHECKOUT_CHANNEL,\n type: 'close_request',\n checkoutId: session.checkoutId,\n },\n session.checkoutOrigin,\n );\n }\n settle(session);\n if (!session.completed) session.options.onCancel?.();\n}\n\nexport function isOpen(): boolean {\n return active !== null;\n}\n","import { open } from './checkout';\n\nconst ATTR = 'data-onflay-checkout';\n\n/**\n * Delegated click handler for `[data-onflay-checkout]` anchors/buttons.\n * When JS is unavailable the element can still navigate via a normal href.\n */\nexport function bindDeclarativeCheckout(): void {\n if (typeof document === 'undefined') return;\n document.addEventListener(\n 'click',\n (event) => {\n const target = event.target;\n if (!(target instanceof Element)) return;\n const el = target.closest(`[${ATTR}]`);\n if (!(el instanceof HTMLElement)) return;\n const url =\n el.getAttribute(ATTR) ||\n (el instanceof HTMLAnchorElement ? el.href : null);\n if (!url) return;\n event.preventDefault();\n try {\n open({ url });\n } catch {\n if (el instanceof HTMLAnchorElement && el.href) {\n window.location.assign(el.href);\n }\n }\n },\n true,\n );\n}\n","import { close, isOpen, open } from './checkout';\nimport { bindDeclarativeCheckout } from './declarative';\n\nexport type { OpenCheckoutOptions, CheckoutFallback } from './checkout';\nexport { open, close, isOpen };\nexport { isAllowedCheckoutUrl, extractCheckoutId } from './origins';\nexport { ONFLAY_CHECKOUT_CHANNEL } from './protocol';\n\nexport interface OnflayCheckoutApi {\n open: typeof open;\n close: typeof close;\n isOpen: typeof isOpen;\n}\n\nconst OnflayCheckout: OnflayCheckoutApi = { open, close, isOpen };\n\ndeclare global {\n interface Window {\n OnflayCheckout?: OnflayCheckoutApi;\n }\n}\n\nif (typeof window !== 'undefined') {\n window.OnflayCheckout = OnflayCheckout;\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n bindDeclarativeCheckout();\n });\n } else {\n bindDeclarativeCheckout();\n }\n}\n\nexport { OnflayCheckout };\n"],"mappings":";AAAA,IAAMA,EAAmB,IAAI,IAAI,CAC/B,sBAEA,6BACF,CAAC,EACKC,EAAgB,IAAI,IAAI,CAC5B,8BACA,qCACF,CAAC,EAMM,SAASC,EAAqBC,EAAsB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAI,IAAID,CAAG,CACtB,OAAQE,EAAA,CACN,MAAO,EACT,CACA,GAAID,EAAO,WAAa,UAAYA,EAAO,WAAa,QAAS,MAAO,GACxE,IAAME,EAAOF,EAAO,SAAS,YAAY,EACzC,OAAIJ,EAAiB,IAAIM,CAAI,GAAKL,EAAc,IAAIK,CAAI,EAC/CF,EAAO,WAAa,SAG3BE,IAAS,aAAeA,IAAS,aAAeA,IAAS,QAGzDF,EAAO,SAAS,WAAW,WAAW,GACtCA,EAAO,SAAS,WAAW,KAAK,EAHb,EAKvB,CAKO,SAASG,EAAkBJ,EAA4B,CAC5D,GAAI,CAEF,IAAMK,EADS,IAAI,IAAIL,CAAG,EACL,SAAS,MAAM,0BAA0B,EAC9D,OAAOK,GAAA,MAAAA,EAAQ,GAAK,mBAAmBA,EAAM,CAAC,CAAC,EAAI,IACrD,OAAQH,EAAA,CACN,OAAO,IACT,CACF,CAEO,SAASI,EAAkBN,EAA4B,CAC5D,GAAI,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AAiB,mBAAoB,IAAM,CAClDI,EAAwB,CAC1B,CAAC,EAEDA,EAAwB","names":["PRODUCTION_HOSTS","SANDBOX_HOSTS","isAllowedCheckoutUrl","url","parsed","e","host","extractCheckoutId","match","getCheckoutOrigin","STYLE_TEXT","mountOverlay","params","host","shadow","style","backdrop","dialog","title","iframe","previousOverflow","onKeyDown","event","focusable","first","last","onBackdropClick","height","clamped","ONFLAY_CHECKOUT_CHANNEL","isOnflayCheckoutOutboundMessage","data","message","type","active","settle","session","runFallback","reason","_a","_b","_c","_d","_e","fallback","postInit","contentWindow","ONFLAY_CHECKOUT_CHANNEL","open","options","isAllowedCheckoutUrl","error","checkoutId","extractCheckoutId","checkoutOrigin","getCheckoutOrigin","close","previouslyFocused","overlay","mountOverlay","event","_f","isOnflayCheckoutOutboundMessage","readyTimeoutMs","isOpen","ATTR","bindDeclarativeCheckout","event","target","el","url","open","e","OnflayCheckout","open","close","isOpen","bindDeclarativeCheckout"]}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@onflay/js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0-staging-20261206175528",
4
+ "description": "Onflay for the browser: the checkout overlay (onflay.js), from npm or a script tag.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/onflay.cjs",
8
+ "module": "./dist/onflay.js",
9
+ "types": "./dist/onflay.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/onflay.d.ts",
13
+ "import": "./dist/onflay.js",
14
+ "require": "./dist/onflay.cjs",
15
+ "default": "./dist/onflay.js"
16
+ }
17
+ },
18
+ "unpkg": "./dist/onflay.iife.js",
19
+ "jsdelivr": "./dist/onflay.iife.js",
20
+ "files": [
21
+ "dist",
22
+ "README.md"
23
+ ],
24
+ "devDependencies": {
25
+ "@types/jest": "^30.0.0",
26
+ "jest": "^29.7.0",
27
+ "jest-environment-jsdom": "^30.4.1",
28
+ "ts-jest": "^29.4.11",
29
+ "tsup": "^8.5.0",
30
+ "typescript": "^5.7.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "keywords": [
36
+ "onflay",
37
+ "checkout",
38
+ "payments",
39
+ "overlay",
40
+ "cdn"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsup",
44
+ "dev": "tsup --watch",
45
+ "clean": "rm -rf dist .turbo",
46
+ "test": "jest --config jest.config.cjs --no-coverage",
47
+ "spike": "python3 -m http.server 4242 --directory spike",
48
+ "lint": "echo \"(no lint configured)\""
49
+ }
6
50
  }