@lockerverse/sdk 0.2.177 → 0.2.180-dev.1
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/MIGRATIONS.md +83 -3
- package/dist/checkout.js +1 -1
- package/dist/checkout.js.map +1 -1
- package/dist/types.d.ts +17 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/MIGRATIONS.md
CHANGED
|
@@ -4,6 +4,15 @@ This file ships in both @lockerverse/sdk and @lockerverse/react. Use the copy in
|
|
|
4
4
|
the target installed release. This is an agent-run procedure, not an install
|
|
5
5
|
script. Installing a package does not edit host code or guarantee these steps ran.
|
|
6
6
|
|
|
7
|
+
## 0.2.180-dev.1 — live shipping for payment widgets
|
|
8
|
+
|
|
9
|
+
- **Affected:** Core checkout quotes and React payment forms for widgets with live shipping enabled.
|
|
10
|
+
- **Required:** deploy a backend with the live-shipping quote contract, then update matching Core and React packages and deploy the host. Configure and enable shipping only after the sender, package, and packing rules are complete.
|
|
11
|
+
- **Automatic:** React collects a shipping address, requests rates only when the buyer selects Calculate shipping, shows the shipping amount, and blocks payment until a current quote is available. Core preserves shipping quote tokens and expected amounts during confirmation.
|
|
12
|
+
- **Custom Core hosts:** send `shipping` to `calculateTotal`, show `shippingCents` in the total, retain `shippingQuote`, and reuse its token for price-only changes. Recalculate after a destination or cart change. Do not persist quote tokens in URLs or logs.
|
|
13
|
+
- **Unchanged:** widgets without live shipping use the existing checkout flow.
|
|
14
|
+
- **Check:** verify complete and incomplete addresses, quote errors and expiry, changed quantities, optional donations, and the displayed full total without submitting a live payment.
|
|
15
|
+
|
|
7
16
|
## Upgrade procedure
|
|
8
17
|
|
|
9
18
|
1. Before installation, record the resolved installed version of each package
|
|
@@ -36,7 +45,7 @@ If it cannot be found, report that limit and use the baseline review below. Do n
|
|
|
36
45
|
claim that every historical migration was applied. Read this file even if the
|
|
37
46
|
version already matches: a previous upgrade may have missed host adoption steps.
|
|
38
47
|
|
|
39
|
-
## 0.2.
|
|
48
|
+
## 0.2.176-dev.1 — Secure checkout loading recovery
|
|
40
49
|
|
|
41
50
|
- **Affected:** React payment widget Stripe fields.
|
|
42
51
|
- **Automatic:** failed field or script loads show a reload action. Fields that
|
|
@@ -48,9 +57,23 @@ version already matches: a previous upgrade may have missed host adoption steps.
|
|
|
48
57
|
- Reload is an explicit customer action and can clear unsaved form entries.
|
|
49
58
|
Saved payment recovery remains in session storage.
|
|
50
59
|
|
|
51
|
-
|
|
52
60
|
## 0.2.175 — Match Stripe Elements payment method configuration
|
|
53
61
|
|
|
62
|
+
- **Affected:** Core checkout submission and React payment widgets.
|
|
63
|
+
- **Automatic:** React configures explicit card, Link, and community-enabled bank
|
|
64
|
+
methods in Stripe Elements and marks the confirmation request with
|
|
65
|
+
`paymentMethodConfiguration: "explicit"`. This matches the backend's Stripe
|
|
66
|
+
PaymentIntent configuration.
|
|
67
|
+
- **Required:** deploy the backend that supports this optional marker before
|
|
68
|
+
upgrading React. Keep Core and React matched. Existing Core-only callers omit
|
|
69
|
+
the marker and retain automatic payment methods. Custom Elements integrations
|
|
70
|
+
must send the marker only when they use the explicit method list.
|
|
71
|
+
- **Check:** submit card and bank payments through Stripe Elements in test mode,
|
|
72
|
+
including recurring checkout. Confirm pending recovery and settlement.
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
## 0.2.174-dev.1 — Match Stripe Elements payment method configuration
|
|
76
|
+
|
|
54
77
|
- **Affected:** Core checkout submission and React payment widgets.
|
|
55
78
|
- **Automatic:** React configures explicit card, Link, and community-enabled bank
|
|
56
79
|
methods in Stripe Elements and marks the confirmation request with
|
|
@@ -124,7 +147,39 @@ version already matches: a previous upgrade may have missed host adoption steps.
|
|
|
124
147
|
verify a changed selection cannot discard it. Check both paid and free order
|
|
125
148
|
confirmation panels. Do not submit a live transaction for this check.
|
|
126
149
|
|
|
127
|
-
## 0.2.
|
|
150
|
+
## 0.2.172-dev.1 — Check pending payment status
|
|
151
|
+
|
|
152
|
+
- **Affected:** React payment widgets with unresolved payments.
|
|
153
|
+
- **Automatic behavior:** the existing pending-payment screen now offers Check
|
|
154
|
+
payment status. It checks the saved payment reference and cannot submit a new
|
|
155
|
+
payment. The control is disabled while the check runs.
|
|
156
|
+
- **Required host changes:** none. Update Core and React together.
|
|
157
|
+
- **Verification:** complete a test bank payment, return to its pending checkout,
|
|
158
|
+
and check its status. Confirm completion clears recovery storage.
|
|
159
|
+
|
|
160
|
+
## 0.2.171-dev.1 — SDK payment recovery and completion UI
|
|
161
|
+
|
|
162
|
+
- **Affected:** React payment widgets and custom hosts that persist payment recovery.
|
|
163
|
+
- **Optional adoption:** pass `recoveryStorageKey` to `LockerversePayment` to let
|
|
164
|
+
the SDK save and restore the pending payment in session storage. Use a stable
|
|
165
|
+
key scoped to the API environment, community, and widget. Remove the host's
|
|
166
|
+
storage code and recovery-driven component key. Do not combine automatic
|
|
167
|
+
persistence with a second host persistence writer.
|
|
168
|
+
- **Compatibility:** the SDK reads the hosted Next app's existing version 1
|
|
169
|
+
records when the same key is used. It writes version 2 records with widget
|
|
170
|
+
identity. It checks widget and selection identity before recovery and keeps
|
|
171
|
+
an unresolved record if those details differ. Recovery uses the saved connected
|
|
172
|
+
account even if current payment routing has changed. Storage is read after hydration,
|
|
173
|
+
before the payable form mounts. No contact details or payment tokens are saved.
|
|
174
|
+
- **Optional UI adoption:** use `completionView="summary"` for the SDK confirmation
|
|
175
|
+
panel and remove the host's duplicate success panel. Completion callbacks still
|
|
176
|
+
run. The default inline message and explicit `resumePayment` integrations remain
|
|
177
|
+
supported. Auctions and legacy custom checkout forms are unchanged.
|
|
178
|
+
- **Check:** reload a pending checkout and confirm the existing payment is checked;
|
|
179
|
+
verify a changed selection cannot discard it. Check both paid and free order
|
|
180
|
+
confirmation panels. Do not submit a live transaction for this check.
|
|
181
|
+
|
|
182
|
+
## 0.2.169-dev.1 — six-month payment widgets
|
|
128
183
|
|
|
129
184
|
Affected: @lockerverse/sdk checkout and @lockerverse/react payment widgets.
|
|
130
185
|
|
|
@@ -140,6 +195,31 @@ Affected: @lockerverse/sdk checkout and @lockerverse/react payment widgets.
|
|
|
140
195
|
submission. Do not submit a live payment for an integration check.
|
|
141
196
|
|
|
142
197
|
|
|
198
|
+
## 0.2.168-dev.1 — bank authorization terms
|
|
199
|
+
|
|
200
|
+
- **Affected:** React payment widgets with ACH enabled.
|
|
201
|
+
- **Automatic:** Stripe displays its bank authorization terms before payment confirmation.
|
|
202
|
+
- **Adoption:** update the matching SDK/React development pair. No prop changes are required.
|
|
203
|
+
- **Check:** confirm that the bank authorization text is visible when a bank account is selected.
|
|
204
|
+
|
|
205
|
+
## 0.2.167-dev.1 — widget ACH and subscription payment recovery
|
|
206
|
+
|
|
207
|
+
- **Affected:** Core checkout data and React payment widgets.
|
|
208
|
+
- **Automatic:** bank payment availability follows the organization default and
|
|
209
|
+
community override returned by the backend. Missing policy remains disabled.
|
|
210
|
+
Pending payments keep their existing payment reference. A failed subscription
|
|
211
|
+
invoice can return `action_required` with `requiresAction: false` and `retryUrl`;
|
|
212
|
+
React shows a link to pay the same invoice instead of creating a second subscription.
|
|
213
|
+
- **Required for custom payment UI:** preserve the reference for pending and
|
|
214
|
+
action-required results. Handle `retryUrl` by opening that invoice, and recover
|
|
215
|
+
status before permitting a new checkout. Do not treat submission as settlement.
|
|
216
|
+
- **Adoption:** deploy the matching backend policy and recovery contract before
|
|
217
|
+
enabling ACH. Existing React hosts need no component prop changes. Keep Core and
|
|
218
|
+
React versions matched when upgrading. Auction payment methods are unchanged.
|
|
219
|
+
- **Check:** verify disabled/inherited/enabled bank visibility and pending, bank
|
|
220
|
+
verification, invoice retry, success, and terminal failure in Stripe test mode.
|
|
221
|
+
Do not create a live transaction for this check.
|
|
222
|
+
|
|
143
223
|
## 0.2.166 — single dropdown arrow
|
|
144
224
|
|
|
145
225
|
- **Affected:** native single-select custom fields in React signup and payment forms.
|
package/dist/checkout.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"./schema-helpers.js";import{i as a,n as o,o as s,t as c}from"./transport.js";import{n as l,t as u}from"./types.js";import{n as d,r as f,t as p}from"./valibot.gen.js";import{array as m,boolean as h,check as g,finite as _,literal as v,looseObject as y,maxValue as b,minLength as x,minValue as S,nullable as C,number as w,object as T,optional as E,parser as D,picklist as O,pipe as k,record as A,regex as j,safeParse as M,strictObject as N,string as P,transform as F,union as ee,unknown as I,variant as te}from"valibot";function ne(e){let t=a(e,`widgetSlug`);return{...t,widgetSlug:t.resourceSlug,widgetSlugValue:t.resourceSlugValue}}const L=O([`one-time`,`monthly`,`annually`,`every-six-months`]),R=O([`none`,`event_admission`]),z=C(e(0)),re=O([`available`,`sold_out`]),ie=E(T({listings:m(T({listingId:r,maxPurchasableQuantity:z,remainingQuantity:z,status:re})),sharedLimits:m(T({id:r,listingIds:m(r),remainingQuantity:e(0),status:re}))}),{listings:[],sharedLimits:[]}),ae=k(P(),j(/^pk_(?:test|live)_\S+$/,`Invalid publishable key.`)),oe={description:t,fulfillmentType:R,id:r,inventoryQuantity:z,maxQuantity:z,minimumAmountCents:z,minQuantity:z,name:r,paymentOption:L},B=T({description:C(P()),endAt:r,id:r,location:C(P()),name:r,startAt:r,status:O([`draft`,`active`,`finished`,`cancelled`])}),se=te(`pricingMode`,[T({...oe,amountCents:e(0),pricingMode:v(`fixed`)}),T({...oe,amountCents:z,pricingMode:v(`custom`)})]),ce=T({acceptsDiscounts:E(h(),!1),id:r,maxQuantityPerOrder:E(z,null),product:se,productId:r,slug:r}),V=E(T({memberId:E(h(),!1),merchSize:E(h(),!1),phone:E(h(),!1),promoCode:E(h(),!1),serviceFee:E(h(),!1),shipping:E(h(),!1),tipping:E(h(),!1)}),{}),le=k(T({availability:ie,community:E(T({color:P(),memberIdLabel:E(C(P())),name:r,thumbnail:C(P()),widgetAchEnabled:E(h())})),config:E(T({customFields:n,fields:V})),description:t,event:C(B),id:E(P(),``),name:E(P(),`Lockerverse widget`),payment:T({connectedAccountId:E(C(r),null),currency:v(`usd`),publishableKey:ae}),pricingPolicy:E(T({currency:E(v(`usd`),`usd`),serviceFeeRateBasisPoints:E(e(0),0)})),products:E(m(ce),[]),showCommunityBranding:E(h(),!0),title:t}),F(e=>({...e,config:{customFields:e.config?.customFields??[],fields:{memberId:e.config?.fields?.memberId??!1,merchSize:e.config?.fields?.merchSize??!1,phone:e.config?.fields?.phone??!1,promoCode:e.config?.fields?.promoCode??!1,serviceFee:e.config?.fields?.serviceFee??!1,shipping:e.config?.fields?.shipping??!1,tipping:e.config?.fields?.tipping??!1}},pricingPolicy:e.pricingPolicy??{currency:`usd`,serviceFeeRateBasisPoints:0}}))),ue=T({acceptsDiscounts:h(),amountCents:C(e(0)),description:C(P()),fulfillmentType:R,id:r,inventoryQuantity:z,listingId:r,maximumQuantity:z,minimumAmountCents:z,minimumQuantity:z,name:r,paymentOption:L,pricingMode:O([`fixed`,`custom`]),slug:r}),de=T({availability:ie,community:C(T({accentColor:P(),imageUrl:C(P()),memberIdLabel:E(C(P())),name:r,widgetAchEnabled:E(h())})),event:C(B),payment:T({connectedAccountId:E(C(r),null),currency:v(`usd`),publishableKey:ae}),pricingPolicy:T({currency:v(`usd`),serviceFeeRateBasisPoints:e(0)}),products:m(ue),widget:T({customFields:n,description:C(P()),fields:V,id:P(),name:r,showCommunityBranding:h(),title:C(P())})}),fe=C(T({percentageOff:k(w(),_(),S(0),b(100)),source:O([`email_list`,`promo_code`])})),pe=T({acceptsDiscounts:h(),eventId:C(r),fulfillmentType:R,listingId:r,listingSlug:r,paymentOption:L,pricingMode:O([`fixed`,`custom`]),productId:r,productName:r,quantity:e(1),subtotalCents:e(0),unitAmountCents:e(0)}),me=k(d,T({amountCents:e(0),appliedDiscount:fe,connectedAccountId:C(r),discountableSubtotalCents:e(0),discountCents:e(0),lineItems:m(pe),paymentOption:L,serviceFeeCents:e(0),subtotalCents:e(0),tipCents:e(0),totalCents:e(0)}),g(({lineItems:e,paymentOption:t})=>e.length===0||e.some(e=>e.paymentOption!==t)?!1:t===`one-time`||e.length===1&&e[0]?.pricingMode===`fixed`&&e[0].quantity===1,`Invalid checkout cadence composition.`)),he=k(T({...p.entries,retryUrl:E(k(r,j(/^https:\/\//)))}),g(e=>e.checkoutId.trim()&&e.paymentReference.trim()?e.checkoutStatus===`action_required`?e.paymentRequired&&(e.requiresAction&&!!e.clientSecret?.trim()||!e.requiresAction&&e.clientSecret===null&&!!e.retryUrl):!e.requiresAction&&e.clientSecret===null:!1,`Invalid payment result state.`)),H=D(me),ge=D(de),U=D(he),_e=D(f),ve=D(le);function ye(e){return _e(e),ve(e)}function be(e){let t=M(y({quote:E(I())}),e),n=ye(e),r=t.success?t.output.quote:void 0;return r===void 0?{widget:n}:{quote:H(r),widget:n}}const xe={email:E(P()),includeServiceFee:E(h()),promoCode:E(P()),tipCents:E(e(0))},W=N(xe),G=D(E(W,{})),Se=N({confirmationToken:E(r),customFieldAnswers:E(m(i)),email:P(),memberId:E(P()),merchSize:E(O([`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`])),metadata:E(A(P(),P())),paymentMethodConfiguration:E(v(`explicit`)),phone:E(P()),shipping:E(N({address:N({city:P(),country:P(),line1:P(),line2:E(P()),postal_code:P(),state:P()}),name:P()}))}),Ce=ee([N({amountCents:e(1),productId:r}),N({productId:r,quantity:e(1)}),N({productId:r})]),we=ee([N({amountCents:e(1),productSlug:r}),N({productSlug:r,quantity:e(1)}),N({productSlug:r})]),K=k(m(Ce),x(1)),q=k(m(we),x(1)),Te=T({selection:q}),Ee=y({catalog:E(I()),email:E(I()),includeServiceFee:E(I()),items:E(K),promoCode:E(I()),selection:E(q),tipCents:E(I())}),J=k(y({authoritative:v(!0),items:K,payment:T({connectedAccountId:C(r),currency:v(`usd`),publishableKey:k(P(),x(1))}),paymentReference:k(P(),x(1)),pricing:W}),F(e=>{let{items:t,payment:n,paymentReference:r,pricing:i,...a}=e,o=H({...a,connectedAccountId:n.connectedAccountId}),{connectedAccountId:s,...c}=o;return{items:t,pricing:i,quote:{...c,authoritative:!0,payment:{connectedAccountId:s,currency:`usd`,publishableKey:n.publishableKey},paymentOption:o.paymentOption,paymentReference:r}}})),De=y({checkout:J,submission:Se}),Oe=r,ke=D(y({})),Ae=D(Ee);function je(e){let{catalog:t,items:n,selection:r,...i}=Ae(e),a;try{a=ke(t)}catch(e){throw TypeError(`A catalog is required to calculate a checkout.`,{cause:e})}try{return{catalog:a,items:n,pricing:G(i),selection:r}}catch(e){throw TypeError(`Checkout pricing input is invalid.`,{cause:e})}}const Me=D(Te),Ne=D(Oe);D(J);const Pe=D(De),Fe=D(q);function Y(e){return Math.max(100,e.minimumAmountCents??0)}function Ie(e,t){let n=new Map(e.products.map(({id:e,listingId:t})=>[e,t])),r=t.reduce((e,t)=>{let r=n.get(t.productId);return r&&e.set(r,(e.get(r)??0)+(`quantity`in t?t.quantity??1:1)),e},new Map),i=e.availability.listings.some(({listingId:e,maxPurchasableQuantity:t,status:n})=>r.has(e)&&(n===`sold_out`||t!==null&&(r.get(e)??0)>t)),a=e.availability.sharedLimits.some(({listingIds:e,remainingQuantity:t,status:n})=>{let i=e.reduce((e,t)=>e+(r.get(t)??0),0);return i>0&&(n===`sold_out`||i>t)});if(i||a)throw new l({code:`total_calculation_failed`,message:`This option is sold out.`,operation:`calculate_total`,reportable:!1,serverCode:`PAYMENT_WIDGET_SALES_LIMIT_REACHED`})}function Le(e,t){if(e.pricingMode!==`custom`||e.paymentOption!==`one-time`||t<Y(e))throw TypeError(`Selected Product amount is invalid.`);return{checkoutItem:{amountCents:t,productId:e.id},quantity:1,unitAmountCents:t}}function Re(e,t){if(e.pricingMode!==`fixed`||e.amountCents===null)throw TypeError(`Selected Product quantity is invalid.`);if(e.paymentOption!==`one-time`&&t!==1)throw TypeError(`Selected recurring Product is invalid.`);if(e.minimumQuantity!==null&&t<e.minimumQuantity||e.maximumQuantity!==null&&t>e.maximumQuantity||e.inventoryQuantity!==null&&t>e.inventoryQuantity)throw TypeError(`Selected Product quantity is invalid.`);return{checkoutItem:e.paymentOption===`one-time`?{productId:e.id,quantity:t}:{productId:e.id},quantity:t,unitAmountCents:e.amountCents}}function ze(e,t,n){let r=`quantity`in n?n.quantity:1,{checkoutItem:i,quantity:a,unitAmountCents:o}=`amountCents`in n?Le(t,n.amountCents):Re(t,r);return{checkoutItem:i,lineItem:{acceptsDiscounts:t.acceptsDiscounts,eventId:t.fulfillmentType===`event_admission`&&e.event?e.event.id:null,fulfillmentType:t.fulfillmentType,listingId:t.listingId,listingSlug:t.slug,paymentOption:t.paymentOption,pricingMode:t.pricingMode,productId:t.id,productName:t.name,quantity:a,subtotalCents:o*a,unitAmountCents:o}}}function X(e,t){let n=Fe(t),r=new Set,i=n.map(t=>{let n=e.products.find(e=>e.slug===t.productSlug);if(!n)throw TypeError(`Selected Product is unavailable.`);if(r.has(n.id))throw TypeError(`Each Product can appear only once per checkout.`);return r.add(n.id),ze(e,n,t)}),a=i[0]?.lineItem.paymentOption;if(!a)throw TypeError(`Select at least one Product.`);if(i.length>1&&(a!==`one-time`||i.some(({lineItem:e})=>e.paymentOption!==a)))throw TypeError(`Recurring Products must be purchased separately.`);let o=i.map(({checkoutItem:e})=>e);return Ie(e,o),{items:o,lineItems:i.map(({lineItem:e})=>e),paymentOption:a}}function Be(e){let{product:t}=e;return{acceptsDiscounts:e.acceptsDiscounts??!1,amountCents:t.amountCents,description:t.description??null,fulfillmentType:t.fulfillmentType,id:t.id,inventoryQuantity:t.inventoryQuantity,listingId:e.id,maximumQuantity:e.maxQuantityPerOrder,minimumAmountCents:t.minimumAmountCents,minimumQuantity:t.minQuantity,name:t.name,paymentOption:t.paymentOption,pricingMode:t.pricingMode,slug:e.slug}}function Ve(e){if(!e)return null;let t={accentColor:e.color,imageUrl:e.thumbnail||null,name:e.name};return e.widgetAchEnabled!==void 0&&(t.widgetAchEnabled=e.widgetAchEnabled),e.memberIdLabel!==void 0&&(t.memberIdLabel=e.memberIdLabel),t}function He(e){let t=e.config?.fields??{};return{availability:e.availability,community:Ve(e.community),event:e.event?{description:e.event.description,endAt:e.event.endAt,id:e.event.id,location:e.event.location,name:e.event.name,startAt:e.event.startAt,status:e.event.status}:null,payment:{connectedAccountId:e.payment.connectedAccountId,currency:e.payment.currency,publishableKey:e.payment.publishableKey},pricingPolicy:{currency:`usd`,serviceFeeRateBasisPoints:e.pricingPolicy?.serviceFeeRateBasisPoints??0},products:(e.products??[]).map(Be),widget:{customFields:e.config?.customFields??[],description:e.description??null,fields:{memberId:t.memberId??!1,merchSize:t.merchSize??!1,phone:t.phone??!1,promoCode:t.promoCode??!1,serviceFee:t.serviceFee??!1,shipping:t.shipping??!1,tipping:t.tipping??!1},id:e.id??``,name:e.name??`Lockerverse widget`,showCommunityBranding:e.showCommunityBranding??!0,title:e.title??null}}}function Z(e){return Q(e)}function Ue(e){return Q(e)}function We(e){return Q(e)}function Q(e){return s(structuredClone(e))}const Ge=T({code:O([`PAYMENT_WIDGET_PHONE_INVALID`,`PAYMENT_WIDGET_PHONE_REQUIRED`,`PAYMENT_WIDGET_SALES_LIMIT_REACHED`])});async function $(e){if(e.status===400||e.status===409)try{let t=M(Ge,await e.json());return t.success?t.output.code:void 0}catch{}}function Ke({catalog:e,items:t,selection:n}){if(t!==void 0&&n!==void 0)throw TypeError(`Use items or selection, not both.`);let r=Z(ge(e)),i=n===void 0?qe(t):X(r,n).items;return Ie(r,i),{catalog:r,items:i}}function qe(e){if(e===void 0)throw TypeError(`Checkout selection is invalid.`);return e}function Je(e){let{apiBaseUrl:t,communitySlug:n,communitySlugValue:r,environment:i,fetchImplementation:a,onError:u,requestTimeoutMs:d,sentryDsn:f,widgetSlug:p,widgetSlugValue:m}=ne(e),h=o({communitySlug:r,environment:i,getContext:()=>({widgetSlug:m}),onError:u,resourceContextName:`lockerverse_widget`,sentryDsn:f}),{requestJson:g}=c(a,h,d),_=`${t}/v2/community/${n}/payment-widgets/${p}/checkout`,v=`${t}/v2/community/${n}/payment-widgets/${p}`;function y(e,t,n=`invalid_selection`){throw h(new l({code:n,message:e,operation:t,reportable:!1}))}function b(e,t){return e instanceof l?e:new l({...t,reportable:!0})}function x(e,t,n=!1){let r=b(e,t);if(!(n&&(r.status===void 0||r.status>=500)))throw h(r);let i=r.status===void 0?new l({code:r.code,message:r.message,operation:r.operation,recoveryRecommended:!0,reportable:r.reportable}):new l({code:r.code,message:r.message,operation:r.operation,recoveryRecommended:!0,reportable:r.reportable,status:r.status});throw h(i)}function S(e){let t=e.email?.trim().toLowerCase(),n=e.promoCode?.trim(),r={};return t&&(r.email=t),e.includeServiceFee!==void 0&&(r.includeServiceFee=e.includeServiceFee),n&&(r.promoCode=n),e.tipCents!==void 0&&(r.tipCents=e.tipCents),r}function C(e){try{return Me(e).selection}catch{y(`Checkout selection is invalid.`,`load_widget`)}}function w(e,t,n,r){let{connectedAccountId:i,...a}=e;return Ue(s({...a,authoritative:!0,items:t,payment:{connectedAccountId:i,currency:`usd`,publishableKey:r.publishableKey},paymentOption:e.paymentOption,paymentReference:globalThis.crypto.randomUUID(),pricing:n}))}function T(e,t,n){try{return X(e,t).items}catch(e){throw e instanceof TypeError&&y(e.message,n),e}}function E(e,t,n,r){if(!n)throw new l({...r,message:`Lockerverse did not return the requested initial quote.`,reportable:!0});let i=T(e,t,r.operation);return s({catalog:Z(e),checkout:w(n,i,{includeServiceFee:e.widget.fields.serviceFee},e.payment)})}async function D(e){let t={code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`},n=e?`${v}?selection=${encodeURIComponent(JSON.stringify(e))}`:v,r=await g(n,e?{cache:`no-store`}:void 0,be,{...t,message:`Unable to load Lockerverse widget because the request failed.`,report:!1},{...t,report:!1},$);if(!r.ok){let e=r.errorValue;throw e===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?new l({...t,message:`This option is sold out.`,reportable:!1,serverCode:e,status:r.response.status}):new l({...t,message:`Unable to load Lockerverse widget (${r.response.status}).`,reportable:r.response.status>=500,status:r.response.status})}let i=s(He(r.value.widget));return e?E(i,e,r.value.quote,t):Z(i)}async function O(e,t){let n=await D(),r={includeServiceFee:n.widget.fields.serviceFee},i=T(n,e,t.operation);return s({catalog:n,checkout:await j(i,r,n.payment,t)})}async function k(e){let t={code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`};try{return e&&`${v}?selection=${encodeURIComponent(JSON.stringify(e))}`.length>4e3?await O(e,t):e?await D(e):await D()}catch(e){x(e,t)}}function A(e){return e===void 0?k():k(C(e))}async function j(e,t,n,r){let i=await g(`${_}/quote`,{body:JSON.stringify({...t,items:e}),headers:{"Content-Type":`application/json`},method:`POST`},H,{...r,message:`Unable to calculate the Lockerverse checkout total because the request failed.`,report:!1},{...r,report:!1},$);if(!i.ok){let e=i.errorValue;throw e===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?new l({...r,message:`This option is sold out.`,reportable:!1,serverCode:e,status:i.response.status}):new l({...r,message:`Unable to calculate the Lockerverse checkout total (${i.response.status}).`,reportable:i.response.status>=500,status:i.response.status})}return w(i.value,e,t,n)}async function M(e){let{catalog:t,items:n,pricing:r}=N(e),i={code:`total_calculation_failed`,message:`Lockerverse returned an invalid checkout total.`,operation:`calculate_total`};try{return await j(n,r,t.payment,i)}catch(e){x(e,i)}}function N(e){try{let t=je(e),n=Ke(t),r=S(t.pricing);return{catalog:n.catalog,items:n.items,pricing:r.includeServiceFee===void 0?{...r,includeServiceFee:n.catalog.widget.fields.serviceFee}:r}}catch(e){if(e instanceof l)throw e;y(e instanceof TypeError?e.message:`Checkout selection is invalid.`,`calculate_total`)}}function P(e){try{let t=Pe(e),{items:n,pricing:r,quote:i}=t.checkout,a=S(r),o=s(i),{submission:c}=t;o.totalCents>0&&!c.confirmationToken&&y(`Stripe confirmation is required for a paid checkout.`,`submit_payment`,`payment_submit_failed`);let l=c.email.trim().toLowerCase();return(!l||l!==a.email)&&y(`Payment email must match the current checkout quote.`,`submit_payment`),{items:n,pricing:a,quote:o,submission:{...c,email:l}}}catch(e){if(e instanceof l)throw e;y(`Lockerverse payment submission is invalid.`,`submit_payment`,`payment_submit_failed`)}}return{calculateTotal:M,async getPaymentStatus(e){let t;try{t=Ne(e).trim()}catch{y(`Provide a payment reference to recover its status.`,`get_payment_status`)}let n={code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`};try{let e=await g(`${_}/${encodeURIComponent(t)}/status`,void 0,U,{...n,message:`Unable to recover the Lockerverse payment status because the request failed.`,report:!1},{...n,report:!1});if(!e.ok)throw new l({...n,message:`Unable to recover the Lockerverse payment status (${e.response.status}).`,reportable:e.response.status>=500,status:e.response.status});if(e.value.paymentReference!==t)throw new l({...n,reportable:!0});return We(e.value)}catch(e){x(e,n)}},load:A,async submitPayment(e){let{items:t,pricing:n,quote:r,submission:i}=P(e),a={code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`};try{let e=await g(`${_}/confirm`,{body:JSON.stringify({confirmationToken:i.confirmationToken,customFieldAnswers:i.customFieldAnswers,email:i.email,expectedAmountCents:r.amountCents,expectedAppliedDiscount:r.appliedDiscount,expectedConnectedAccountId:r.payment.connectedAccountId,expectedDiscountableSubtotalCents:r.discountableSubtotalCents,expectedDiscountCents:r.discountCents,expectedServiceFeeCents:r.serviceFeeCents,expectedSubtotalCents:r.subtotalCents,expectedTipCents:r.tipCents,expectedTotalCents:r.totalCents,...n,items:t,memberId:i.memberId,merchSize:i.merchSize,metadata:i.metadata,paymentMethodConfiguration:i.paymentMethodConfiguration,paymentReference:r.paymentReference,phone:i.phone,quoteContractVersion:1,shipping:i.shipping}),headers:{"Content-Type":`application/json`},method:`POST`},U,{...a,message:`Unable to submit the Lockerverse payment because the request failed.`,report:!1},{...a,report:!1},$);if(!e.ok){let t=e.errorValue;throw t?new l({...a,message:t===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?`This option is sold out.`:`Unable to submit the Lockerverse payment (${e.response.status}).`,reportable:!1,serverCode:t,status:e.response.status}):new l({...a,message:`Unable to submit the Lockerverse payment (${e.response.status}).`,reportable:e.response.status>=500,status:e.response.status})}if(e.value.paymentReference!==r.paymentReference)throw new l({...a,reportable:!0});return We(e.value)}catch(e){x(e,a,!0)}}}}function Ye(e,t){let{selection:n,...r}=t,i;try{i=G(r)}catch(e){throw TypeError(`Checkout pricing is invalid.`,{cause:e})}let a=i.includeServiceFee??e.widget.fields.serviceFee,{tipCents:o=0}=i,{items:c,lineItems:l,paymentOption:u}=X(e,n),d=l.reduce((e,t)=>e+t.subtotalCents,0);if(!Number.isSafeInteger(d)||d<=0||d>2147483647)throw TypeError(`Checkout total is invalid.`);let f=l.reduce((e,t)=>e+(t.acceptsDiscounts?t.subtotalCents:0),0),p=a?Math.round(d*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0,m=d+p,h=m+o;if(!Number.isSafeInteger(h)||h>2147483647)throw TypeError(`Checkout total is invalid.`);return s({amountCents:m,appliedDiscount:null,authoritative:!1,discountableSubtotalCents:f,discountCents:0,items:c,lineItems:l,paymentOption:u,serviceFeeCents:p,subtotalCents:d,tipCents:o,totalCents:h})}export{u as LOCKERVERSE_SDK_VERSION,l as LockerverseSdkError,Je as createLockerverseCheckoutClient,Ye as estimateLockerverseCheckout,Y as getLockerverseMinimumCustomAmountCents};
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"./schema-helpers.js";import{i as a,n as o,o as s,t as c}from"./transport.js";import{n as l,t as u}from"./types.js";import{n as d,r as f,t as p}from"./valibot.gen.js";import{array as m,boolean as h,check as g,finite as _,literal as v,looseObject as y,maxValue as b,minLength as x,minValue as S,nullable as C,number as w,object as T,optional as E,parser as D,picklist as O,pipe as k,record as A,regex as j,safeParse as M,strictObject as N,string as P,transform as F,union as I,unknown as L,variant as ee}from"valibot";function te(e){let t=a(e,`widgetSlug`);return{...t,widgetSlug:t.resourceSlug,widgetSlugValue:t.resourceSlugValue}}const R=O([`one-time`,`monthly`,`annually`,`every-six-months`]),z=O([`none`,`event_admission`]),B=C(e(0)),V=O([`available`,`sold_out`]),H=E(T({listings:m(T({listingId:r,maxPurchasableQuantity:B,remainingQuantity:B,status:V})),sharedLimits:m(T({id:r,listingIds:m(r),remainingQuantity:e(0),status:V}))}),{listings:[],sharedLimits:[]}),U=k(P(),j(/^pk_(?:test|live)_\S+$/,`Invalid publishable key.`)),W={description:t,fulfillmentType:z,id:r,inventoryQuantity:B,maxQuantity:B,minimumAmountCents:B,minQuantity:B,name:r,paymentOption:R},G=T({description:C(P()),endAt:r,id:r,location:C(P()),name:r,startAt:r,status:O([`draft`,`active`,`finished`,`cancelled`])}),ne=ee(`pricingMode`,[T({...W,amountCents:e(0),pricingMode:v(`fixed`)}),T({...W,amountCents:B,pricingMode:v(`custom`)})]),re=T({acceptsDiscounts:E(h(),!1),id:r,maxQuantityPerOrder:E(B,null),product:ne,productId:r,slug:r}),K=E(T({enabled:h(),productIds:m(P())})),q=E(T({memberId:E(h(),!1),merchSize:E(h(),!1),phone:E(h(),!1),promoCode:E(h(),!1),serviceFee:E(h(),!1),shipping:E(h(),!1),tipping:E(h(),!1)}),{}),ie=k(T({availability:H,community:E(T({color:P(),memberIdLabel:E(C(P())),name:r,thumbnail:C(P()),widgetAchEnabled:E(h())})),config:E(T({customFields:n,fields:q,liveShipping:K})),description:t,event:C(G),id:E(P(),``),name:E(P(),`Lockerverse widget`),payment:T({connectedAccountId:E(C(r),null),currency:v(`usd`),publishableKey:U}),pricingPolicy:E(T({currency:E(v(`usd`),`usd`),serviceFeeRateBasisPoints:E(e(0),0)})),products:E(m(re),[]),showCommunityBranding:E(h(),!0),title:t}),F(e=>({...e,config:{customFields:e.config?.customFields??[],fields:{memberId:e.config?.fields?.memberId??!1,merchSize:e.config?.fields?.merchSize??!1,phone:e.config?.fields?.phone??!1,promoCode:e.config?.fields?.promoCode??!1,serviceFee:e.config?.fields?.serviceFee??!1,shipping:e.config?.fields?.shipping??!1,tipping:e.config?.fields?.tipping??!1},liveShipping:e.config?.liveShipping},pricingPolicy:e.pricingPolicy??{currency:`usd`,serviceFeeRateBasisPoints:0}}))),ae=T({acceptsDiscounts:h(),amountCents:C(e(0)),description:C(P()),fulfillmentType:z,id:r,inventoryQuantity:B,listingId:r,maximumQuantity:B,minimumAmountCents:B,minimumQuantity:B,name:r,paymentOption:R,pricingMode:O([`fixed`,`custom`]),slug:r}),oe=T({availability:H,community:C(T({accentColor:P(),imageUrl:C(P()),memberIdLabel:E(C(P())),name:r,widgetAchEnabled:E(h())})),event:C(G),payment:T({connectedAccountId:E(C(r),null),currency:v(`usd`),publishableKey:U}),pricingPolicy:T({currency:v(`usd`),serviceFeeRateBasisPoints:e(0)}),products:m(ae),widget:T({customFields:n,description:C(P()),fields:q,id:P(),liveShipping:K,name:r,showCommunityBranding:h(),title:C(P())})}),se=C(T({percentageOff:k(w(),_(),S(0),b(100)),source:O([`email_list`,`promo_code`])})),ce=T({acceptsDiscounts:h(),eventId:C(r),fulfillmentType:z,listingId:r,listingSlug:r,paymentOption:R,pricingMode:O([`fixed`,`custom`]),productId:r,productName:r,quantity:e(1),subtotalCents:e(0),unitAmountCents:e(0)}),le=k(y(d.entries),T({amountCents:e(0),appliedDiscount:se,connectedAccountId:C(r),discountableSubtotalCents:e(0),discountCents:e(0),lineItems:m(ce),paymentOption:R,serviceFeeCents:e(0),shippingCents:E(e(0)),shippingQuote:E(C(T({amountCents:e(0),carrier:P(),estimatedDays:C(w()),expiresAt:r,service:P(),token:r}))),shippingRequired:E(h()),subtotalCents:e(0),tipCents:e(0),totalCents:e(0)}),g(({lineItems:e,paymentOption:t})=>e.length===0||e.some(e=>e.paymentOption!==t)?!1:t===`one-time`||e.length===1&&e[0]?.pricingMode===`fixed`&&e[0].quantity===1,`Invalid checkout cadence composition.`)),ue=k(T({...p.entries,retryUrl:E(k(r,j(/^https:\/\//)))}),g(e=>e.checkoutId.trim()&&e.paymentReference.trim()?e.checkoutStatus===`action_required`?e.paymentRequired&&(e.requiresAction&&!!e.clientSecret?.trim()||!e.requiresAction&&e.clientSecret===null&&!!e.retryUrl):!e.requiresAction&&e.clientSecret===null:!1,`Invalid payment result state.`)),J=D(le),de=D(oe),fe=D(ue),pe=D(f),me=D(ie);function he(e){return pe(e),me(e)}function ge(e){let t=M(y({quote:E(L())}),e),n=he(e),r=t.success?t.output.quote:void 0;return r===void 0?{widget:n}:{quote:J(r),widget:n}}const _e=N({address:N({city:P(),country:P(),line1:P(),line2:E(P()),postal_code:P(),state:P()}),name:P()}),ve={email:E(P()),includeServiceFee:E(h()),promoCode:E(P()),shipping:E(_e),shippingQuoteToken:E(r),tipCents:E(e(0))},ye=N(ve),be=D(E(ye,{})),xe=N({confirmationToken:E(r),customFieldAnswers:E(m(i)),email:P(),memberId:E(P()),merchSize:E(O([`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`])),metadata:E(A(P(),P())),paymentMethodConfiguration:E(v(`explicit`)),phone:E(P()),shipping:E(_e)}),Se=I([N({amountCents:e(1),productId:r}),N({productId:r,quantity:e(1)}),N({productId:r})]),Ce=I([N({amountCents:e(1),productSlug:r}),N({productSlug:r,quantity:e(1)}),N({productSlug:r})]),we=k(m(Se),x(1)),Y=k(m(Ce),x(1)),Te=T({selection:Y}),Ee=y({catalog:E(L()),email:E(L()),includeServiceFee:E(L()),items:E(we),promoCode:E(L()),selection:E(Y),tipCents:E(L())}),De=k(y({authoritative:v(!0),items:we,payment:T({connectedAccountId:C(r),currency:v(`usd`),publishableKey:k(P(),x(1))}),paymentReference:k(P(),x(1)),pricing:ye}),F(e=>{let{items:t,payment:n,paymentReference:r,pricing:i,...a}=e,o=J({...a,connectedAccountId:n.connectedAccountId}),{connectedAccountId:s,...c}=o;return{items:t,pricing:i,quote:{...c,authoritative:!0,payment:{connectedAccountId:s,currency:`usd`,publishableKey:n.publishableKey},paymentOption:o.paymentOption,paymentReference:r}}})),Oe=y({checkout:De,submission:xe}),ke=r,Ae=D(y({})),je=D(Ee);function Me(e){let{catalog:t,items:n,selection:r,...i}=je(e),a;try{a=Ae(t)}catch(e){throw TypeError(`A catalog is required to calculate a checkout.`,{cause:e})}try{return{catalog:a,items:n,pricing:be(i),selection:r}}catch(e){throw TypeError(`Checkout pricing input is invalid.`,{cause:e})}}const Ne=D(Te),Pe=D(ke);D(De);const Fe=D(Oe),Ie=D(Y);function Le(e){return Math.max(100,e.minimumAmountCents??0)}function Re(e,t){let n=new Map(e.products.map(({id:e,listingId:t})=>[e,t])),r=t.reduce((e,t)=>{let r=n.get(t.productId);return r&&e.set(r,(e.get(r)??0)+(`quantity`in t?t.quantity??1:1)),e},new Map),i=e.availability.listings.some(({listingId:e,maxPurchasableQuantity:t,status:n})=>r.has(e)&&(n===`sold_out`||t!==null&&(r.get(e)??0)>t)),a=e.availability.sharedLimits.some(({listingIds:e,remainingQuantity:t,status:n})=>{let i=e.reduce((e,t)=>e+(r.get(t)??0),0);return i>0&&(n===`sold_out`||i>t)});if(i||a)throw new l({code:`total_calculation_failed`,message:`This option is sold out.`,operation:`calculate_total`,reportable:!1,serverCode:`PAYMENT_WIDGET_SALES_LIMIT_REACHED`})}function ze(e,t){if(e.pricingMode!==`custom`||e.paymentOption!==`one-time`||t<Le(e))throw TypeError(`Selected Product amount is invalid.`);return{checkoutItem:{amountCents:t,productId:e.id},quantity:1,unitAmountCents:t}}function Be(e,t){if(e.pricingMode!==`fixed`||e.amountCents===null)throw TypeError(`Selected Product quantity is invalid.`);if(e.paymentOption!==`one-time`&&t!==1)throw TypeError(`Selected recurring Product is invalid.`);if(e.minimumQuantity!==null&&t<e.minimumQuantity||e.maximumQuantity!==null&&t>e.maximumQuantity||e.inventoryQuantity!==null&&t>e.inventoryQuantity)throw TypeError(`Selected Product quantity is invalid.`);return{checkoutItem:e.paymentOption===`one-time`?{productId:e.id,quantity:t}:{productId:e.id},quantity:t,unitAmountCents:e.amountCents}}function Ve(e,t,n){let r=`quantity`in n?n.quantity:1,{checkoutItem:i,quantity:a,unitAmountCents:o}=`amountCents`in n?ze(t,n.amountCents):Be(t,r);return{checkoutItem:i,lineItem:{acceptsDiscounts:t.acceptsDiscounts,eventId:t.fulfillmentType===`event_admission`&&e.event?e.event.id:null,fulfillmentType:t.fulfillmentType,listingId:t.listingId,listingSlug:t.slug,paymentOption:t.paymentOption,pricingMode:t.pricingMode,productId:t.id,productName:t.name,quantity:a,subtotalCents:o*a,unitAmountCents:o}}}function X(e,t){let n=Ie(t),r=new Set,i=n.map(t=>{let n=e.products.find(e=>e.slug===t.productSlug);if(!n)throw TypeError(`Selected Product is unavailable.`);if(r.has(n.id))throw TypeError(`Each Product can appear only once per checkout.`);return r.add(n.id),Ve(e,n,t)}),a=i[0]?.lineItem.paymentOption;if(!a)throw TypeError(`Select at least one Product.`);if(i.length>1&&(a!==`one-time`||i.some(({lineItem:e})=>e.paymentOption!==a)))throw TypeError(`Recurring Products must be purchased separately.`);let o=i.map(({checkoutItem:e})=>e);return Re(e,o),{items:o,lineItems:i.map(({lineItem:e})=>e),paymentOption:a}}function He(e){let{product:t}=e;return{acceptsDiscounts:e.acceptsDiscounts??!1,amountCents:t.amountCents,description:t.description??null,fulfillmentType:t.fulfillmentType,id:t.id,inventoryQuantity:t.inventoryQuantity,listingId:e.id,maximumQuantity:e.maxQuantityPerOrder,minimumAmountCents:t.minimumAmountCents,minimumQuantity:t.minQuantity,name:t.name,paymentOption:t.paymentOption,pricingMode:t.pricingMode,slug:e.slug}}function Ue(e){if(!e)return null;let t={accentColor:e.color,imageUrl:e.thumbnail||null,name:e.name};return e.widgetAchEnabled!==void 0&&(t.widgetAchEnabled=e.widgetAchEnabled),e.memberIdLabel!==void 0&&(t.memberIdLabel=e.memberIdLabel),t}function We(e){let t=e.config?.fields??{};return{availability:e.availability,community:Ue(e.community),event:e.event?{description:e.event.description,endAt:e.event.endAt,id:e.event.id,location:e.event.location,name:e.event.name,startAt:e.event.startAt,status:e.event.status}:null,payment:{connectedAccountId:e.payment.connectedAccountId,currency:e.payment.currency,publishableKey:e.payment.publishableKey},pricingPolicy:{currency:`usd`,serviceFeeRateBasisPoints:e.pricingPolicy?.serviceFeeRateBasisPoints??0},products:(e.products??[]).map(He),widget:{customFields:e.config?.customFields??[],description:e.description??null,fields:{memberId:t.memberId??!1,merchSize:t.merchSize??!1,phone:t.phone??!1,promoCode:t.promoCode??!1,serviceFee:t.serviceFee??!1,shipping:t.shipping??!1,tipping:t.tipping??!1},id:e.id??``,liveShipping:e.config?.liveShipping,name:e.name??`Lockerverse widget`,showCommunityBranding:e.showCommunityBranding??!0,title:e.title??null}}}function Z(e){return Q(e)}function Ge(e){return Q(e)}function Ke(e){return Q(e)}function Q(e){return s(structuredClone(e))}const qe=T({code:O([`PAYMENT_WIDGET_PHONE_INVALID`,`PAYMENT_WIDGET_PHONE_REQUIRED`,`PAYMENT_WIDGET_SALES_LIMIT_REACHED`])});async function $(e){if(e.status===400||e.status===409)try{let t=M(qe,await e.json());return t.success?t.output.code:void 0}catch{}}function Je({catalog:e,items:t,selection:n}){if(t!==void 0&&n!==void 0)throw TypeError(`Use items or selection, not both.`);let r=Z(de(e)),i=n===void 0?Ye(t):X(r,n).items;return Re(r,i),{catalog:r,items:i}}function Ye(e){if(e===void 0)throw TypeError(`Checkout selection is invalid.`);return e}function Xe(e){let{apiBaseUrl:t,communitySlug:n,communitySlugValue:r,environment:i,fetchImplementation:a,onError:u,requestTimeoutMs:d,sentryDsn:f,widgetSlug:p,widgetSlugValue:m}=te(e),h=o({communitySlug:r,environment:i,getContext:()=>({widgetSlug:m}),onError:u,resourceContextName:`lockerverse_widget`,sentryDsn:f}),{requestJson:g}=c(a,h,d),_=`${t}/v2/community/${n}/payment-widgets/${p}/checkout`,v=`${t}/v2/community/${n}/payment-widgets/${p}`;function y(e,t,n=`invalid_selection`){throw h(new l({code:n,message:e,operation:t,reportable:!1}))}function b(e,t){return e instanceof l?e:new l({...t,reportable:!0})}function x(e,t,n=!1){let r=b(e,t);if(!(n&&(r.status===void 0||r.status>=500)))throw h(r);let i=r.status===void 0?new l({code:r.code,message:r.message,operation:r.operation,recoveryRecommended:!0,reportable:r.reportable}):new l({code:r.code,message:r.message,operation:r.operation,recoveryRecommended:!0,reportable:r.reportable,status:r.status});throw h(i)}function S(e){let t=e.email?.trim().toLowerCase(),n=e.promoCode?.trim(),r={};return t&&(r.email=t),e.includeServiceFee!==void 0&&(r.includeServiceFee=e.includeServiceFee),n&&(r.promoCode=n),e.tipCents!==void 0&&(r.tipCents=e.tipCents),e.shipping&&(r.shipping=e.shipping),e.shippingQuoteToken&&(r.shippingQuoteToken=e.shippingQuoteToken),r}function C(e){try{return Ne(e).selection}catch{y(`Checkout selection is invalid.`,`load_widget`)}}function w(e,t,n,r){let{connectedAccountId:i,...a}=e;return Ge(s({...a,authoritative:!0,items:t,payment:{connectedAccountId:i,currency:`usd`,publishableKey:r.publishableKey},paymentOption:e.paymentOption,paymentReference:globalThis.crypto.randomUUID(),pricing:n}))}function T(e,t,n){try{return X(e,t).items}catch(e){throw e instanceof TypeError&&y(e.message,n),e}}function E(e,t,n,r){if(!n)throw new l({...r,message:`Lockerverse did not return the requested initial quote.`,reportable:!0});let i=T(e,t,r.operation);return s({catalog:Z(e),checkout:w(n,i,{includeServiceFee:e.widget.fields.serviceFee},e.payment)})}async function D(e){let t={code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`},n=e?`${v}?selection=${encodeURIComponent(JSON.stringify(e))}`:v,r=await g(n,e?{cache:`no-store`}:void 0,ge,{...t,message:`Unable to load Lockerverse widget because the request failed.`,report:!1},{...t,report:!1},$);if(!r.ok){let e=r.errorValue;throw e===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?new l({...t,message:`This option is sold out.`,reportable:!1,serverCode:e,status:r.response.status}):new l({...t,message:`Unable to load Lockerverse widget (${r.response.status}).`,reportable:r.response.status>=500,status:r.response.status})}let i=s(We(r.value.widget));return e?E(i,e,r.value.quote,t):Z(i)}async function O(e,t){let n=await D(),r={includeServiceFee:n.widget.fields.serviceFee},i=T(n,e,t.operation);return s({catalog:n,checkout:await j(i,r,n.payment,t)})}async function k(e){let t={code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`};try{return e&&`${v}?selection=${encodeURIComponent(JSON.stringify(e))}`.length>4e3?await O(e,t):e?await D(e):await D()}catch(e){x(e,t)}}function A(e){return e===void 0?k():k(C(e))}async function j(e,t,n,r){let i=await g(`${_}/quote`,{body:JSON.stringify({...t,items:e}),headers:{"Content-Type":`application/json`},method:`POST`},J,{...r,message:`Unable to calculate the Lockerverse checkout total because the request failed.`,report:!1},{...r,report:!1},$);if(!i.ok){let e=i.errorValue;throw e===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?new l({...r,message:`This option is sold out.`,reportable:!1,serverCode:e,status:i.response.status}):new l({...r,message:`Unable to calculate the Lockerverse checkout total (${i.response.status}).`,reportable:i.response.status>=500,status:i.response.status})}return w(i.value,e,t,n)}async function M(e){let{catalog:t,items:n,pricing:r}=N(e),i={code:`total_calculation_failed`,message:`Lockerverse returned an invalid checkout total.`,operation:`calculate_total`};try{return await j(n,r,t.payment,i)}catch(e){x(e,i)}}function N(e){try{let t=Me(e),n=Je(t),r=S(t.pricing);return{catalog:n.catalog,items:n.items,pricing:r.includeServiceFee===void 0?{...r,includeServiceFee:n.catalog.widget.fields.serviceFee}:r}}catch(e){if(e instanceof l)throw e;y(e instanceof TypeError?e.message:`Checkout selection is invalid.`,`calculate_total`)}}function P(e){try{let t=Fe(e),{items:n,pricing:r,quote:i}=t.checkout,a=S(r),o=s(i),{submission:c}=t;o.totalCents>0&&!c.confirmationToken&&y(`Stripe confirmation is required for a paid checkout.`,`submit_payment`,`payment_submit_failed`);let l=c.email.trim().toLowerCase();return(!l||l!==a.email)&&y(`Payment email must match the current checkout quote.`,`submit_payment`),{items:n,pricing:a,quote:o,submission:{...c,email:l}}}catch(e){if(e instanceof l)throw e;y(`Lockerverse payment submission is invalid.`,`submit_payment`,`payment_submit_failed`)}}return{calculateTotal:M,async getPaymentStatus(e){let t;try{t=Pe(e).trim()}catch{y(`Provide a payment reference to recover its status.`,`get_payment_status`)}let n={code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`};try{let e=await g(`${_}/${encodeURIComponent(t)}/status`,void 0,fe,{...n,message:`Unable to recover the Lockerverse payment status because the request failed.`,report:!1},{...n,report:!1});if(!e.ok)throw new l({...n,message:`Unable to recover the Lockerverse payment status (${e.response.status}).`,reportable:e.response.status>=500,status:e.response.status});if(e.value.paymentReference!==t)throw new l({...n,reportable:!0});return Ke(e.value)}catch(e){x(e,n)}},load:A,async submitPayment(e){let{items:t,pricing:n,quote:r,submission:i}=P(e),a={code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`};try{let e=await g(`${_}/confirm`,{body:JSON.stringify({confirmationToken:i.confirmationToken,customFieldAnswers:i.customFieldAnswers,email:i.email,expectedAmountCents:r.amountCents,expectedAppliedDiscount:r.appliedDiscount,expectedConnectedAccountId:r.payment.connectedAccountId,expectedDiscountableSubtotalCents:r.discountableSubtotalCents,expectedDiscountCents:r.discountCents,expectedServiceFeeCents:r.serviceFeeCents,expectedShippingCents:r.shippingCents,expectedSubtotalCents:r.subtotalCents,expectedTipCents:r.tipCents,expectedTotalCents:r.totalCents,...n,items:t,memberId:i.memberId,merchSize:i.merchSize,metadata:i.metadata,paymentMethodConfiguration:i.paymentMethodConfiguration,paymentReference:r.paymentReference,phone:i.phone,quoteContractVersion:1,shipping:i.shipping??n.shipping,shippingQuoteToken:r.shippingQuote?.token}),headers:{"Content-Type":`application/json`},method:`POST`},fe,{...a,message:`Unable to submit the Lockerverse payment because the request failed.`,report:!1},{...a,report:!1},$);if(!e.ok){let t=e.errorValue;throw t?new l({...a,message:t===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`?`This option is sold out.`:`Unable to submit the Lockerverse payment (${e.response.status}).`,reportable:!1,serverCode:t,status:e.response.status}):new l({...a,message:`Unable to submit the Lockerverse payment (${e.response.status}).`,reportable:e.response.status>=500,status:e.response.status})}if(e.value.paymentReference!==r.paymentReference)throw new l({...a,reportable:!0});return Ke(e.value)}catch(e){x(e,a,!0)}}}}function Ze(e,t){let{selection:n,...r}=t,i;try{i=be(r)}catch(e){throw TypeError(`Checkout pricing is invalid.`,{cause:e})}let a=i.includeServiceFee??e.widget.fields.serviceFee,{tipCents:o=0}=i,{items:c,lineItems:l,paymentOption:u}=X(e,n),d=l.reduce((e,t)=>e+t.subtotalCents,0);if(!Number.isSafeInteger(d)||d<=0||d>2147483647)throw TypeError(`Checkout total is invalid.`);let f=l.reduce((e,t)=>e+(t.acceptsDiscounts?t.subtotalCents:0),0),p=a?Math.round(d*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0,m=d+p,h=m+o;if(!Number.isSafeInteger(h)||h>2147483647)throw TypeError(`Checkout total is invalid.`);return s({amountCents:m,appliedDiscount:null,authoritative:!1,discountableSubtotalCents:f,discountCents:0,items:c,lineItems:l,paymentOption:u,serviceFeeCents:p,subtotalCents:d,tipCents:o,totalCents:h})}export{u as LOCKERVERSE_SDK_VERSION,l as LockerverseSdkError,Xe as createLockerverseCheckoutClient,Ze as estimateLockerverseCheckout,Le as getLockerverseMinimumCustomAmountCents};
|
|
2
2
|
//# sourceMappingURL=checkout.js.map
|
package/dist/checkout.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout.js","names":[],"sources":["../src/checkout-environment.ts","../src/checkout-schemas.ts","../src/checkout-input-schemas.ts","../src/custom-amount.ts","../src/checkout-selection.ts","../src/snapshots.ts","../src/checkout-client.ts","../src/checkout-estimate.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type { CreateLockerverseWidgetOptions } from \"./types.ts\";\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import {\n array,\n boolean,\n check,\n finite,\n type InferOutput,\n literal,\n looseObject,\n maxValue,\n minValue,\n nullable,\n number,\n object,\n optional,\n parser,\n picklist,\n pipe,\n regex,\n safeParse,\n string,\n transform,\n unknown,\n variant,\n} from \"valibot\";\n\nimport {\n vPaymentWidgetPaymentResultResponseDto,\n vPaymentWidgetQuoteResponseDto,\n vPublicPaymentWidgetResponseDto,\n} from \"./generated/public-api/valibot.gen.ts\";\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst paymentOptionSchema = picklist([\n \"one-time\",\n \"monthly\",\n \"annually\",\n \"every-six-months\",\n]);\nconst fulfillmentTypeSchema = picklist([\"none\", \"event_admission\"]);\nconst nullableNonNegativeIntegerSchema = nullable(safeIntegerSchema(0));\nconst availabilityStatusSchema = picklist([\"available\", \"sold_out\"]);\nconst availabilitySchema = optional(\n object({\n listings: array(\n object({\n listingId: nonEmptyStringSchema,\n maxPurchasableQuantity: nullableNonNegativeIntegerSchema,\n remainingQuantity: nullableNonNegativeIntegerSchema,\n status: availabilityStatusSchema,\n })\n ),\n sharedLimits: array(\n object({\n id: nonEmptyStringSchema,\n listingIds: array(nonEmptyStringSchema),\n remainingQuantity: safeIntegerSchema(0),\n status: availabilityStatusSchema,\n })\n ),\n }),\n { listings: [], sharedLimits: [] }\n);\nconst publishableKeySchema = pipe(\n string(),\n regex(/^pk_(?:test|live)_\\S+$/, \"Invalid publishable key.\")\n);\n\nconst productBaseEntries = {\n description: optionalNullableStringSchema,\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n maxQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n};\n\nconst eventSchema = object({\n description: nullable(string()),\n endAt: nonEmptyStringSchema,\n id: nonEmptyStringSchema,\n location: nullable(string()),\n name: nonEmptyStringSchema,\n startAt: nonEmptyStringSchema,\n status: picklist([\"draft\", \"active\", \"finished\", \"cancelled\"]),\n});\n\nconst publicProductSchema = variant(\"pricingMode\", [\n object({\n ...productBaseEntries,\n amountCents: safeIntegerSchema(0),\n pricingMode: literal(\"fixed\"),\n }),\n object({\n ...productBaseEntries,\n amountCents: nullableNonNegativeIntegerSchema,\n pricingMode: literal(\"custom\"),\n }),\n]);\n\nconst productListingSchema = object({\n acceptsDiscounts: optional(boolean(), false),\n id: nonEmptyStringSchema,\n maxQuantityPerOrder: optional(nullableNonNegativeIntegerSchema, null),\n product: publicProductSchema,\n productId: nonEmptyStringSchema,\n slug: nonEmptyStringSchema,\n});\n\nconst widgetFieldsSchema = optional(\n object({\n memberId: optional(boolean(), false),\n merchSize: optional(boolean(), false),\n phone: optional(boolean(), false),\n promoCode: optional(boolean(), false),\n serviceFee: optional(boolean(), false),\n shipping: optional(boolean(), false),\n tipping: optional(boolean(), false),\n }),\n {}\n);\n\nexport const publicWidgetSchema = pipe(\n object({\n availability: availabilitySchema,\n community: optional(\n object({\n color: string(),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n thumbnail: nullable(string()),\n widgetAchEnabled: optional(boolean()),\n })\n ),\n config: optional(\n object({\n customFields: customFieldsSchema,\n fields: widgetFieldsSchema,\n })\n ),\n description: optionalNullableStringSchema,\n event: nullable(eventSchema),\n id: optional(string(), \"\"),\n name: optional(string(), \"Lockerverse widget\"),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: optional(\n object({\n currency: optional(literal(\"usd\"), \"usd\"),\n serviceFeeRateBasisPoints: optional(safeIntegerSchema(0), 0),\n })\n ),\n products: optional(array(productListingSchema), []),\n showCommunityBranding: optional(boolean(), true),\n title: optionalNullableStringSchema,\n }),\n transform((widget) => ({\n ...widget,\n config: {\n customFields: widget.config?.customFields ?? [],\n fields: {\n memberId: widget.config?.fields?.memberId ?? false,\n merchSize: widget.config?.fields?.merchSize ?? false,\n phone: widget.config?.fields?.phone ?? false,\n promoCode: widget.config?.fields?.promoCode ?? false,\n serviceFee: widget.config?.fields?.serviceFee ?? false,\n shipping: widget.config?.fields?.shipping ?? false,\n tipping: widget.config?.fields?.tipping ?? false,\n },\n },\n pricingPolicy: widget.pricingPolicy ?? {\n currency: \"usd\" as const,\n serviceFeeRateBasisPoints: 0,\n },\n }))\n);\n\nconst catalogProductSchema = object({\n acceptsDiscounts: boolean(),\n amountCents: nullable(safeIntegerSchema(0)),\n description: nullable(string()),\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n listingId: nonEmptyStringSchema,\n maximumQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minimumQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n slug: nonEmptyStringSchema,\n});\n\nconst catalogSchema = object({\n availability: availabilitySchema,\n community: nullable(\n object({\n accentColor: string(),\n imageUrl: nullable(string()),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n widgetAchEnabled: optional(boolean()),\n })\n ),\n event: nullable(eventSchema),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: object({\n currency: literal(\"usd\"),\n serviceFeeRateBasisPoints: safeIntegerSchema(0),\n }),\n products: array(catalogProductSchema),\n widget: object({\n customFields: customFieldsSchema,\n description: nullable(string()),\n fields: widgetFieldsSchema,\n id: string(),\n name: nonEmptyStringSchema,\n showCommunityBranding: boolean(),\n title: nullable(string()),\n }),\n});\n\nconst appliedDiscountSchema = nullable(\n object({\n percentageOff: pipe(number(), finite(), minValue(0), maxValue(100)),\n source: picklist([\"email_list\", \"promo_code\"]),\n })\n);\n\nconst checkoutLineItemSchema = object({\n acceptsDiscounts: boolean(),\n eventId: nullable(nonEmptyStringSchema),\n fulfillmentType: fulfillmentTypeSchema,\n listingId: nonEmptyStringSchema,\n listingSlug: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n productId: nonEmptyStringSchema,\n productName: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n subtotalCents: safeIntegerSchema(0),\n unitAmountCents: safeIntegerSchema(0),\n});\n\nexport const checkoutQuoteSchema = pipe(\n vPaymentWidgetQuoteResponseDto,\n object({\n amountCents: safeIntegerSchema(0),\n appliedDiscount: appliedDiscountSchema,\n connectedAccountId: nullable(nonEmptyStringSchema),\n discountableSubtotalCents: safeIntegerSchema(0),\n discountCents: safeIntegerSchema(0),\n lineItems: array(checkoutLineItemSchema),\n paymentOption: paymentOptionSchema,\n serviceFeeCents: safeIntegerSchema(0),\n subtotalCents: safeIntegerSchema(0),\n tipCents: safeIntegerSchema(0),\n totalCents: safeIntegerSchema(0),\n }),\n check(({ lineItems, paymentOption }) => {\n if (\n lineItems.length === 0 ||\n lineItems.some((item) => item.paymentOption !== paymentOption)\n ) {\n return false;\n }\n return (\n paymentOption === \"one-time\" ||\n (lineItems.length === 1 &&\n lineItems[0]?.pricingMode === \"fixed\" &&\n lineItems[0].quantity === 1)\n );\n }, \"Invalid checkout cadence composition.\")\n);\n\nexport const paymentResultSchema = pipe(\n object({\n ...vPaymentWidgetPaymentResultResponseDto.entries,\n retryUrl: optional(pipe(nonEmptyStringSchema, regex(/^https:\\/\\//))),\n }),\n check((payment) => {\n if (!(payment.checkoutId.trim() && payment.paymentReference.trim())) {\n return false;\n }\n if (payment.checkoutStatus === \"action_required\") {\n return (\n payment.paymentRequired &&\n ((payment.requiresAction && Boolean(payment.clientSecret?.trim())) ||\n (!payment.requiresAction &&\n payment.clientSecret === null &&\n Boolean(payment.retryUrl)))\n );\n }\n return !payment.requiresAction && payment.clientSecret === null;\n }, \"Invalid payment result state.\")\n);\n\nexport type PublicCheckoutQuote = InferOutput<typeof checkoutQuoteSchema>;\nexport type PublicProductListing = InferOutput<typeof productListingSchema>;\nexport type PublicWidget = InferOutput<typeof publicWidgetSchema>;\n\nexport const parseCheckoutQuote = parser(checkoutQuoteSchema);\nexport const parseCatalog = parser(catalogSchema);\nexport const parsePaymentResult = parser(paymentResultSchema);\nconst parsePublicWidgetContract = parser(vPublicPaymentWidgetResponseDto);\nconst parseSdkPublicWidget = parser(publicWidgetSchema);\n\nexport function parsePublicWidget<Input>(input: Input) {\n parsePublicWidgetContract(input);\n return parseSdkPublicWidget(input);\n}\n\nexport function parsePublicWidgetLoad<Input>(input: Input) {\n const response = safeParse(\n looseObject({ quote: optional(unknown()) }),\n input\n );\n const widget = parsePublicWidget(input);\n const quote = response.success ? response.output.quote : undefined;\n return quote === undefined\n ? { widget }\n : { quote: parseCheckoutQuote(quote), widget };\n}\n","import {\n array,\n boolean,\n type InferOutput,\n literal,\n looseObject,\n minLength,\n nullable,\n object,\n optional,\n parser,\n picklist,\n pipe,\n record,\n strictObject,\n string,\n transform,\n union,\n unknown,\n} from \"valibot\";\n\nimport { parseCheckoutQuote } from \"./checkout-schemas.ts\";\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst checkoutPricingEntries = {\n email: optional(string()),\n includeServiceFee: optional(boolean()),\n promoCode: optional(string()),\n tipCents: optional(safeIntegerSchema(0)),\n};\n\nconst checkoutPricingInputSchema = strictObject(checkoutPricingEntries);\n\nexport const parseCheckoutPricingInput = parser(\n optional(checkoutPricingInputSchema, {})\n);\n\nconst paymentSubmissionSchema = strictObject({\n confirmationToken: optional(nonEmptyStringSchema),\n customFieldAnswers: optional(array(customFieldAnswerSchema)),\n email: string(),\n memberId: optional(string()),\n merchSize: optional(picklist([\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\"])),\n metadata: optional(record(string(), string())),\n paymentMethodConfiguration: optional(literal(\"explicit\")),\n phone: optional(string()),\n shipping: optional(\n strictObject({\n address: strictObject({\n city: string(),\n country: string(),\n line1: string(),\n line2: optional(string()),\n postal_code: string(),\n state: string(),\n }),\n name: string(),\n })\n ),\n});\n\nconst checkoutItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productId: nonEmptyStringSchema,\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutSelectionItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productSlug: nonEmptyStringSchema,\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutItemsSchema = pipe(array(checkoutItemSchema), minLength(1));\nconst checkoutSelectionItemsSchema = pipe(\n array(checkoutSelectionItemSchema),\n minLength(1)\n);\n\nconst loadCheckoutInputSchema = object({\n selection: checkoutSelectionItemsSchema,\n});\n\nconst calculateTotalInputSchema = looseObject({\n catalog: optional(unknown()),\n email: optional(unknown()),\n includeServiceFee: optional(unknown()),\n items: optional(checkoutItemsSchema),\n promoCode: optional(unknown()),\n selection: optional(checkoutSelectionItemsSchema),\n tipCents: optional(unknown()),\n});\n\nconst preparedCheckoutInputSchema = pipe(\n looseObject({\n authoritative: literal(true),\n items: checkoutItemsSchema,\n payment: object({\n connectedAccountId: nullable(nonEmptyStringSchema),\n currency: literal(\"usd\"),\n publishableKey: pipe(string(), minLength(1)),\n }),\n paymentReference: pipe(string(), minLength(1)),\n pricing: checkoutPricingInputSchema,\n }),\n transform((checkout) => {\n const { items, payment, paymentReference, pricing, ...quoteInput } =\n checkout;\n const parsedQuote = parseCheckoutQuote({\n ...quoteInput,\n connectedAccountId: payment.connectedAccountId,\n });\n const { connectedAccountId, ...quote } = parsedQuote;\n return {\n items,\n pricing,\n quote: {\n ...quote,\n authoritative: true as const,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: parsedQuote.paymentOption,\n paymentReference,\n },\n };\n })\n);\n\nconst submitPaymentInputSchema = looseObject({\n checkout: preparedCheckoutInputSchema,\n submission: paymentSubmissionSchema,\n});\n\nconst paymentReferenceInputSchema = nonEmptyStringSchema;\nconst parseCatalogInputFields = parser(looseObject({}));\n\nexport type ParsedPreparedCheckoutInput = InferOutput<\n typeof preparedCheckoutInputSchema\n>;\nexport type ParsedLoadCheckoutInput = InferOutput<\n typeof loadCheckoutInputSchema\n>;\nexport type ParsedPaymentReferenceInput = InferOutput<\n typeof paymentReferenceInputSchema\n>;\nexport type ParsedSubmitPaymentInput = InferOutput<\n typeof submitPaymentInputSchema\n>;\n\nconst parseCalculateTotalInputFields = parser(calculateTotalInputSchema);\n\nexport function parseCalculateTotalInput<Input>(input: Input) {\n const { catalog, items, selection, ...pricingInput } =\n parseCalculateTotalInputFields(input);\n let parsedCatalog: ReturnType<typeof parseCatalogInputFields>;\n try {\n parsedCatalog = parseCatalogInputFields(catalog);\n } catch (error) {\n throw new TypeError(\"A catalog is required to calculate a checkout.\", {\n cause: error,\n });\n }\n try {\n return {\n catalog: parsedCatalog,\n items,\n pricing: parseCheckoutPricingInput(pricingInput),\n selection,\n };\n } catch (error) {\n throw new TypeError(\"Checkout pricing input is invalid.\", { cause: error });\n }\n}\n\nexport type ParsedCalculateTotalInput = ReturnType<\n typeof parseCalculateTotalInput\n>;\nexport type ParsedCheckoutPricingInput = InferOutput<\n typeof checkoutPricingInputSchema\n>;\n\nexport const parseLoadCheckoutInput = parser(loadCheckoutInputSchema);\nexport const parsePaymentReferenceInput = parser(paymentReferenceInputSchema);\nexport const parsePreparedCheckoutInput = parser(preparedCheckoutInputSchema);\nexport const parseSubmitPaymentInput = parser(submitPaymentInputSchema);\n\nexport const parseCheckoutSelectionItems = parser(checkoutSelectionItemsSchema);\n","import type { LockerverseProduct } from \"./types.ts\";\n\nconst minimumCustomAmountCents = 100;\n\nexport function getLockerverseMinimumCustomAmountCents(\n product: Pick<LockerverseProduct, \"minimumAmountCents\">\n) {\n return Math.max(minimumCustomAmountCents, product.minimumAmountCents ?? 0);\n}\n","import { parseCheckoutSelectionItems } from \"./checkout-input-schemas.ts\";\nimport { getLockerverseMinimumCustomAmountCents } from \"./custom-amount.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutItem,\n LockerverseCheckoutLineItem,\n LockerverseCheckoutSelectionItem,\n LockerverseProduct,\n} from \"./types.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\ntype ResolvedSelectionItem = {\n checkoutItem: LockerverseCheckoutItem;\n quantity: number;\n unitAmountCents: number;\n};\n\nexport function assertCheckoutItemsAreAvailable(\n catalog: LockerverseCatalog,\n items: LockerverseCheckoutItem[]\n) {\n const listingIdByProductId = new Map(\n catalog.products.map(({ id, listingId }) => [id, listingId])\n );\n const requestedByListingId = items.reduce((requested, item) => {\n const listingId = listingIdByProductId.get(item.productId);\n if (listingId) {\n requested.set(\n listingId,\n (requested.get(listingId) ?? 0) +\n (\"quantity\" in item ? (item.quantity ?? 1) : 1)\n );\n }\n return requested;\n }, new Map<string, number>());\n const listingIsSoldOut = catalog.availability.listings.some(\n ({ listingId, maxPurchasableQuantity, status }) =>\n requestedByListingId.has(listingId) &&\n (status === \"sold_out\" ||\n (maxPurchasableQuantity !== null &&\n (requestedByListingId.get(listingId) ?? 0) > maxPurchasableQuantity))\n );\n const sharedLimitIsSoldOut = catalog.availability.sharedLimits.some(\n ({ listingIds, remainingQuantity, status }) => {\n const requestedQuantity = listingIds.reduce(\n (total, listingId) =>\n total + (requestedByListingId.get(listingId) ?? 0),\n 0\n );\n return (\n requestedQuantity > 0 &&\n (status === \"sold_out\" || requestedQuantity > remainingQuantity)\n );\n }\n );\n if (listingIsSoldOut || sharedLimitIsSoldOut) {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"This option is sold out.\",\n operation: \"calculate_total\",\n reportable: false,\n serverCode: \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n });\n }\n}\n\nfunction resolveAmountItem(\n product: LockerverseProduct,\n amountCents: number\n): ResolvedSelectionItem {\n if (\n product.pricingMode !== \"custom\" ||\n product.paymentOption !== \"one-time\" ||\n amountCents < getLockerverseMinimumCustomAmountCents(product)\n ) {\n throw new TypeError(\"Selected Product amount is invalid.\");\n }\n return {\n checkoutItem: { amountCents, productId: product.id },\n quantity: 1,\n unitAmountCents: amountCents,\n };\n}\n\nfunction resolveFixedItem(\n product: LockerverseProduct,\n quantity: number\n): ResolvedSelectionItem {\n if (product.pricingMode !== \"fixed\" || product.amountCents === null) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n if (product.paymentOption !== \"one-time\" && quantity !== 1) {\n throw new TypeError(\"Selected recurring Product is invalid.\");\n }\n if (\n (product.minimumQuantity !== null && quantity < product.minimumQuantity) ||\n (product.maximumQuantity !== null && quantity > product.maximumQuantity) ||\n (product.inventoryQuantity !== null && quantity > product.inventoryQuantity)\n ) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n return {\n checkoutItem:\n product.paymentOption === \"one-time\"\n ? { productId: product.id, quantity }\n : { productId: product.id },\n quantity,\n unitAmountCents: product.amountCents,\n };\n}\n\nfunction resolveSelectionItem(\n catalog: LockerverseCatalog,\n product: LockerverseProduct,\n selection: LockerverseCheckoutSelectionItem\n) {\n const selectedQuantity = \"quantity\" in selection ? selection.quantity : 1;\n const resolved =\n \"amountCents\" in selection\n ? resolveAmountItem(product, selection.amountCents)\n : resolveFixedItem(product, selectedQuantity);\n const { checkoutItem, quantity, unitAmountCents } = resolved;\n\n return {\n checkoutItem,\n lineItem: {\n acceptsDiscounts: product.acceptsDiscounts,\n eventId:\n product.fulfillmentType === \"event_admission\" && catalog.event\n ? catalog.event.id\n : null,\n fulfillmentType: product.fulfillmentType,\n listingId: product.listingId,\n listingSlug: product.slug,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n productId: product.id,\n productName: product.name,\n quantity,\n subtotalCents: unitAmountCents * quantity,\n unitAmountCents,\n } satisfies LockerverseCheckoutLineItem,\n };\n}\n\nexport function resolveCheckoutSelection(\n catalog: LockerverseCatalog,\n input: LockerverseCheckoutSelectionItem[]\n) {\n const selection = parseCheckoutSelectionItems(input);\n const selectedProducts = new Set<string>();\n const resolved = selection.map((item) => {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"Selected Product is unavailable.\");\n }\n if (selectedProducts.has(product.id)) {\n throw new TypeError(\"Each Product can appear only once per checkout.\");\n }\n selectedProducts.add(product.id);\n return resolveSelectionItem(catalog, product, item);\n });\n const paymentOption = resolved[0]?.lineItem.paymentOption;\n if (!paymentOption) {\n throw new TypeError(\"Select at least one Product.\");\n }\n if (\n resolved.length > 1 &&\n (paymentOption !== \"one-time\" ||\n resolved.some(({ lineItem }) => lineItem.paymentOption !== paymentOption))\n ) {\n throw new TypeError(\"Recurring Products must be purchased separately.\");\n }\n const items = resolved.map(({ checkoutItem }) => checkoutItem);\n assertCheckoutItemsAreAvailable(catalog, items);\n return {\n items,\n lineItems: resolved.map(({ lineItem }) => lineItem),\n paymentOption,\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCommunityBranding,\n LockerversePaymentResult,\n LockerversePreparedCheckout,\n LockerverseProduct,\n} from \"./types.ts\";\n\nfunction mapProduct(listing: PublicProductListing): LockerverseProduct {\n const { product } = listing;\n\n return {\n acceptsDiscounts: listing.acceptsDiscounts ?? false,\n amountCents: product.amountCents,\n description: product.description ?? null,\n fulfillmentType: product.fulfillmentType,\n id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: listing.maxQuantityPerOrder,\n minimumAmountCents: product.minimumAmountCents,\n minimumQuantity: product.minQuantity,\n name: product.name,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n slug: listing.slug,\n };\n}\n\nfunction mapCommunity(\n community: PublicWidget[\"community\"]\n): LockerverseCommunityBranding | null {\n if (!community) {\n return null;\n }\n const branding: LockerverseCommunityBranding = {\n accentColor: community.color,\n imageUrl: community.thumbnail || null,\n name: community.name,\n };\n if (community.widgetAchEnabled !== undefined) {\n branding.widgetAchEnabled = community.widgetAchEnabled;\n }\n if (community.memberIdLabel !== undefined) {\n branding.memberIdLabel = community.memberIdLabel;\n }\n return branding;\n}\n\nexport function createCatalog(widget: PublicWidget): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n availability: widget.availability,\n community: mapCommunity(widget.community),\n event: widget.event\n ? {\n description: widget.event.description,\n endAt: widget.event.endAt,\n id: widget.event.id,\n location: widget.event.location,\n name: widget.event.name,\n startAt: widget.event.startAt,\n status: widget.event.status,\n }\n : null,\n payment: {\n connectedAccountId: widget.payment.connectedAccountId,\n currency: widget.payment.currency,\n publishableKey: widget.payment.publishableKey,\n },\n pricingPolicy: {\n currency: \"usd\",\n serviceFeeRateBasisPoints:\n widget.pricingPolicy?.serviceFeeRateBasisPoints ?? 0,\n },\n products: (widget.products ?? []).map(mapProduct),\n widget: {\n customFields: widget.config?.customFields ?? [],\n description: widget.description ?? null,\n fields: {\n memberId: fields.memberId ?? false,\n merchSize: fields.merchSize ?? false,\n phone: fields.phone ?? false,\n promoCode: fields.promoCode ?? false,\n serviceFee: fields.serviceFee ?? false,\n shipping: fields.shipping ?? false,\n tipping: fields.tipping ?? false,\n },\n id: widget.id ?? \"\",\n name: widget.name ?? \"Lockerverse widget\",\n showCommunityBranding: widget.showCommunityBranding ?? true,\n title: widget.title ?? null,\n },\n };\n}\n\nexport function cloneCatalog(catalog: LockerverseCatalog): LockerverseCatalog {\n return cloneSnapshot(catalog);\n}\n\nexport function clonePreparedCheckout(\n checkout: LockerversePreparedCheckout\n): LockerversePreparedCheckout {\n return cloneSnapshot(checkout);\n}\n\nexport function clonePaymentResult(\n paymentResult: LockerversePaymentResult\n): LockerversePaymentResult {\n return cloneSnapshot(paymentResult);\n}\n\nfunction cloneSnapshot<T>(value: T): T {\n return deepFreeze(structuredClone(value));\n}\n","import { object, picklist, safeParse } from \"valibot\";\nimport { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport {\n type ParsedCalculateTotalInput,\n type ParsedCheckoutPricingInput,\n parseCalculateTotalInput,\n parseLoadCheckoutInput,\n parsePaymentReferenceInput,\n parseSubmitPaymentInput,\n} from \"./checkout-input-schemas.ts\";\nimport {\n parseCatalog,\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidgetLoad,\n} from \"./checkout-schemas.ts\";\nimport {\n assertCheckoutItemsAreAvailable,\n resolveCheckoutSelection,\n} from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n cloneCatalog,\n clonePaymentResult,\n clonePreparedCheckout,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCalculateTotalInput,\n type LockerverseCatalog,\n type LockerverseCheckoutClient,\n type LockerverseCheckoutItem,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutSelectionItem,\n type LockerverseLoadCheckoutInput,\n type LockerverseLoadedCheckout,\n type LockerversePreparedCheckout,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSdkServerCode,\n type LockerverseSubmitPaymentInput,\n} from \"./types.ts\";\n\ntype OperationErrorContext = {\n code:\n | \"payment_status_failed\"\n | \"payment_submit_failed\"\n | \"total_calculation_failed\"\n | \"widget_load_failed\";\n message: string;\n operation:\n | \"calculate_total\"\n | \"get_payment_status\"\n | \"load_widget\"\n | \"submit_payment\";\n};\n\nconst MAX_SELECTED_WIDGET_URL_LENGTH = 4000;\nconst paymentServerErrorSchema = object({\n code: picklist([\n \"PAYMENT_WIDGET_PHONE_INVALID\",\n \"PAYMENT_WIDGET_PHONE_REQUIRED\",\n \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n ]),\n});\n\nasync function readPaymentServerCode(\n response: Response\n): Promise<LockerverseSdkServerCode | undefined> {\n if (response.status !== 400 && response.status !== 409) {\n return;\n }\n try {\n const result = safeParse(paymentServerErrorSchema, await response.json());\n return result.success ? result.output.code : undefined;\n } catch {\n // Non-JSON error bodies do not contain a safe server code.\n }\n}\n\nfunction resolveCalculateTotalItems({\n catalog,\n items,\n selection,\n}: ParsedCalculateTotalInput) {\n if (items !== undefined && selection !== undefined) {\n throw new TypeError(\"Use items or selection, not both.\");\n }\n const selectionCatalog = cloneCatalog(parseCatalog(catalog));\n const checkoutItems =\n selection === undefined\n ? requireCheckoutItems(items)\n : resolveCheckoutSelection(selectionCatalog, selection).items;\n assertCheckoutItemsAreAvailable(selectionCatalog, checkoutItems);\n return {\n catalog: selectionCatalog,\n items: checkoutItems,\n };\n}\n\nfunction requireCheckoutItems(\n items: ParsedCalculateTotalInput[\"items\"]\n): LockerverseCheckoutItem[] {\n if (items === undefined) {\n throw new TypeError(\"Checkout selection is invalid.\");\n }\n return items;\n}\n\nexport function createLockerverseCheckoutClient(\n options: CreateLockerverseWidgetOptions\n): LockerverseCheckoutClient {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n requestTimeoutMs,\n sentryDsn,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({ widgetSlug: widgetSlugValue }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n const { requestJson } = createTransport(\n fetchImplementation,\n reportError,\n requestTimeoutMs\n );\n const checkoutBaseUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout`;\n const widgetUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`;\n\n function invalidInput(\n message: string,\n operation: LockerverseSdkOperation,\n code: \"invalid_selection\" | \"payment_submit_failed\" = \"invalid_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code,\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n function normalizeOperationError<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext\n ) {\n return error instanceof LockerverseSdkError\n ? error\n : new LockerverseSdkError({ ...context, reportable: true });\n }\n\n function failOperation<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext,\n recoveryMayBeRequired = false\n ): never {\n const normalized = normalizeOperationError(error, context);\n const recoveryRecommended =\n recoveryMayBeRequired &&\n (normalized.status === undefined || normalized.status >= 500);\n if (!recoveryRecommended) {\n throw reportError(normalized);\n }\n const recoveryError =\n normalized.status === undefined\n ? new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n })\n : new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n status: normalized.status,\n });\n throw reportError(recoveryError);\n }\n\n function normalizePricingInput(input: ParsedCheckoutPricingInput) {\n const email = input.email?.trim().toLowerCase();\n const promoCode = input.promoCode?.trim();\n const pricing: LockerverseCheckoutPricingInput = {};\n if (email) {\n pricing.email = email;\n }\n if (input.includeServiceFee !== undefined) {\n pricing.includeServiceFee = input.includeServiceFee;\n }\n if (promoCode) {\n pricing.promoCode = promoCode;\n }\n if (input.tipCents !== undefined) {\n pricing.tipCents = input.tipCents;\n }\n return pricing;\n }\n\n function normalizeLoadSelection(input: LockerverseLoadCheckoutInput) {\n try {\n return parseLoadCheckoutInput(input).selection;\n } catch {\n invalidInput(\"Checkout selection is invalid.\", \"load_widget\");\n }\n }\n\n function createPreparedCheckout(\n quote: ReturnType<typeof parseCheckoutQuote>,\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"]\n ): LockerversePreparedCheckout {\n const { connectedAccountId, ...checkoutQuote } = quote;\n return clonePreparedCheckout(\n deepFreeze({\n ...checkoutQuote,\n authoritative: true as const,\n items,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: quote.paymentOption,\n paymentReference: globalThis.crypto.randomUUID(),\n pricing,\n })\n );\n }\n\n function resolveSelectedCheckoutItems(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n operation: LockerverseSdkOperation\n ) {\n try {\n return resolveCheckoutSelection(catalog, selection).items;\n } catch (error) {\n if (error instanceof TypeError) {\n invalidInput(error.message, operation);\n }\n throw error;\n }\n }\n\n function createSelectedCheckout(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n quote: ReturnType<typeof parseCheckoutQuote> | undefined,\n context: OperationErrorContext\n ) {\n if (!quote) {\n throw new LockerverseSdkError({\n ...context,\n message: \"Lockerverse did not return the requested initial quote.\",\n reportable: true,\n });\n }\n const checkoutItems = resolveSelectedCheckoutItems(\n catalog,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: cloneCatalog(catalog),\n checkout: createPreparedCheckout(\n quote,\n checkoutItems,\n { includeServiceFee: catalog.widget.fields.serviceFee },\n catalog.payment\n ),\n });\n }\n\n function requestWidgetResource(): Promise<LockerverseCatalog>;\n function requestWidgetResource(\n selection: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseLoadedCheckout>;\n async function requestWidgetResource(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n const requestUrl = selection\n ? `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n : widgetUrl;\n const response = await requestJson(\n requestUrl,\n selection ? { cache: \"no-store\" } : undefined,\n parsePublicWidgetLoad,\n {\n ...context,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to load Lockerverse widget (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n const catalog = deepFreeze(createCatalog(response.value.widget));\n if (!selection) {\n return cloneCatalog(catalog);\n }\n return createSelectedCheckout(\n catalog,\n selection,\n response.value.quote,\n context\n );\n }\n\n async function loadLargeSelection(\n selection: LockerverseCheckoutSelectionItem[],\n context: OperationErrorContext\n ): Promise<LockerverseLoadedCheckout> {\n const loaded = await requestWidgetResource();\n const pricing = {\n includeServiceFee: loaded.widget.fields.serviceFee,\n };\n const items = resolveSelectedCheckoutItems(\n loaded,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: loaded,\n checkout: await requestCheckoutQuote(\n items,\n pricing,\n loaded.payment,\n context\n ),\n });\n }\n\n async function loadWidget(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n try {\n if (\n selection &&\n `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n .length > MAX_SELECTED_WIDGET_URL_LENGTH\n ) {\n return await loadLargeSelection(selection, context);\n }\n return selection\n ? await requestWidgetResource(selection)\n : await requestWidgetResource();\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function load(): Promise<LockerverseCatalog>;\n function load(\n input: LockerverseLoadCheckoutInput\n ): Promise<LockerverseLoadedCheckout>;\n function load(input?: LockerverseLoadCheckoutInput) {\n return input === undefined\n ? loadWidget()\n : loadWidget(normalizeLoadSelection(input));\n }\n\n async function requestCheckoutQuote(\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"],\n context: OperationErrorContext\n ) {\n const response = await requestJson(\n `${checkoutBaseUrl}/quote`,\n {\n body: JSON.stringify({ ...pricing, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parseCheckoutQuote,\n {\n ...context,\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to calculate the Lockerverse checkout total (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n return createPreparedCheckout(response.value, items, pricing, payment);\n }\n\n async function calculateTotal(input: LockerverseCalculateTotalInput) {\n const { catalog, items, pricing } = normalizeCalculateTotalInput(input);\n const context = {\n code: \"total_calculation_failed\" as const,\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\" as const,\n };\n try {\n return await requestCheckoutQuote(\n items,\n pricing,\n catalog.payment,\n context\n );\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function normalizeCalculateTotalInput(input: LockerverseCalculateTotalInput) {\n try {\n const parsed = parseCalculateTotalInput(input);\n const resolved = resolveCalculateTotalItems(parsed);\n const pricing = normalizePricingInput(parsed.pricing);\n return {\n catalog: resolved.catalog,\n items: resolved.items,\n pricing:\n pricing.includeServiceFee === undefined\n ? {\n ...pricing,\n includeServiceFee: resolved.catalog.widget.fields.serviceFee,\n }\n : pricing,\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n error instanceof TypeError\n ? error.message\n : \"Checkout selection is invalid.\",\n \"calculate_total\"\n );\n }\n }\n\n function normalizeSubmitPaymentInput(input: LockerverseSubmitPaymentInput) {\n try {\n const parsed = parseSubmitPaymentInput(input);\n const {\n items,\n pricing: pricingInput,\n quote: quoteInput,\n } = parsed.checkout;\n const pricing = normalizePricingInput(pricingInput);\n const quote = deepFreeze(quoteInput);\n const { submission } = parsed;\n if (quote.totalCents > 0 && !submission.confirmationToken) {\n invalidInput(\n \"Stripe confirmation is required for a paid checkout.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n const email = submission.email.trim().toLowerCase();\n if (!email || email !== pricing.email) {\n invalidInput(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n return {\n items,\n pricing,\n quote,\n submission: { ...submission, email },\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n \"Lockerverse payment submission is invalid.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n }\n\n return {\n calculateTotal,\n async getPaymentStatus(paymentReference) {\n let normalizedReference: string;\n try {\n normalizedReference =\n parsePaymentReferenceInput(paymentReference).trim();\n } catch {\n invalidInput(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n const context = {\n code: \"payment_status_failed\" as const,\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/${encodeURIComponent(normalizedReference)}/status`,\n undefined,\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n report: false,\n },\n { ...context, report: false }\n );\n if (!response.ok) {\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to recover the Lockerverse payment status (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== normalizedReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context);\n }\n },\n load,\n async submitPayment(input) {\n const { items, pricing, quote, submission } =\n normalizeSubmitPaymentInput(input);\n const context = {\n code: \"payment_submit_failed\" as const,\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: submission.confirmationToken,\n customFieldAnswers: submission.customFieldAnswers,\n email: submission.email,\n expectedAmountCents: quote.amountCents,\n expectedAppliedDiscount: quote.appliedDiscount,\n expectedConnectedAccountId: quote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n quote.discountableSubtotalCents,\n expectedDiscountCents: quote.discountCents,\n expectedServiceFeeCents: quote.serviceFeeCents,\n expectedSubtotalCents: quote.subtotalCents,\n expectedTipCents: quote.tipCents,\n expectedTotalCents: quote.totalCents,\n ...pricing,\n items,\n memberId: submission.memberId,\n merchSize: submission.merchSize,\n metadata: submission.metadata,\n paymentMethodConfiguration: submission.paymentMethodConfiguration,\n paymentReference: quote.paymentReference,\n phone: submission.phone,\n quoteContractVersion: 1,\n shipping: submission.shipping,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode) {\n throw new LockerverseSdkError({\n ...context,\n message:\n serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n ? \"This option is sold out.\"\n : `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== quote.paymentReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context, true);\n }\n },\n };\n}\n","import { parseCheckoutPricingInput } from \"./checkout-input-schemas.ts\";\nimport { resolveCheckoutSelection } from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutEstimate,\n LockerverseEstimateCheckoutInput,\n} from \"./types.ts\";\n\nexport function estimateLockerverseCheckout(\n catalog: LockerverseCatalog,\n input: LockerverseEstimateCheckoutInput\n): LockerverseCheckoutEstimate {\n const { selection, ...pricingInput } = input;\n let pricing: ReturnType<typeof parseCheckoutPricingInput>;\n try {\n pricing = parseCheckoutPricingInput(pricingInput);\n } catch (error) {\n throw new TypeError(\"Checkout pricing is invalid.\", { cause: error });\n }\n const includeServiceFee =\n pricing.includeServiceFee ?? catalog.widget.fields.serviceFee;\n const { tipCents = 0 } = pricing;\n const { items, lineItems, paymentOption } = resolveCheckoutSelection(\n catalog,\n selection\n );\n const subtotalCents = lineItems.reduce(\n (total, lineItem) => total + lineItem.subtotalCents,\n 0\n );\n if (\n !Number.isSafeInteger(subtotalCents) ||\n subtotalCents <= 0 ||\n subtotalCents > 2_147_483_647\n ) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n const discountableSubtotalCents = lineItems.reduce(\n (total, lineItem) =>\n total + (lineItem.acceptsDiscounts ? lineItem.subtotalCents : 0),\n 0\n );\n const serviceFeeCents = includeServiceFee\n ? Math.round(\n (subtotalCents * catalog.pricingPolicy.serviceFeeRateBasisPoints) /\n 10_000\n )\n : 0;\n const amountCents = subtotalCents + serviceFeeCents;\n const totalCents = amountCents + tipCents;\n if (!Number.isSafeInteger(totalCents) || totalCents > 2_147_483_647) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n\n return deepFreeze({\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n items,\n lineItems,\n paymentOption,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents,\n });\n}\n"],"mappings":"0iBAGA,SAAgB,GACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,CCyBA,MAAM,EAAsB,EAAS,CACnC,WACA,UACA,WACA,kBACF,CAAC,EACK,EAAwB,EAAS,CAAC,OAAQ,iBAAiB,CAAC,EAC5D,EAAmC,EAAS,EAAkB,CAAC,CAAC,EAChE,GAA2B,EAAS,CAAC,YAAa,UAAU,CAAC,EAC7D,GAAqB,EACzB,EAAO,CACL,SAAU,EACR,EAAO,CACL,UAAW,EACX,uBAAwB,EACxB,kBAAmB,EACnB,OAAQ,EACV,CAAC,CACH,EACA,aAAc,EACZ,EAAO,CACL,GAAI,EACJ,WAAY,EAAM,CAAoB,EACtC,kBAAmB,EAAkB,CAAC,EACtC,OAAQ,EACV,CAAC,CACH,CACF,CAAC,EACD,CAAE,SAAU,CAAC,EAAG,aAAc,CAAC,CAAE,CACnC,EACM,GAAuB,EAC3B,EAAO,EACP,EAAM,yBAA0B,0BAA0B,CAC5D,EAEM,GAAqB,CACzB,YAAa,EACb,gBAAiB,EACjB,GAAI,EACJ,kBAAmB,EACnB,YAAa,EACb,mBAAoB,EACpB,YAAa,EACb,KAAM,EACN,cAAe,CACjB,EAEM,EAAc,EAAO,CACzB,YAAa,EAAS,EAAO,CAAC,EAC9B,MAAO,EACP,GAAI,EACJ,SAAU,EAAS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EAC9B,EAAa,EAAc,EACjC,GAAI,CAAC,OAAO,cAAc,CAAU,GAAK,EAAa,WACpD,MAAU,UAAU,4BAA4B,EAGlD,OAAO,EAAW,CAChB,cACA,gBAAiB,KACjB,cAAe,GACf,4BACA,cAAe,EACf,QACA,YACA,gBACA,kBACA,gBACA,WACA,YACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"checkout.js","names":[],"sources":["../src/checkout-environment.ts","../src/checkout-schemas.ts","../src/checkout-input-schemas.ts","../src/custom-amount.ts","../src/checkout-selection.ts","../src/snapshots.ts","../src/checkout-client.ts","../src/checkout-estimate.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type { CreateLockerverseWidgetOptions } from \"./types.ts\";\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import {\n array,\n boolean,\n check,\n finite,\n type InferOutput,\n literal,\n looseObject,\n maxValue,\n minValue,\n nullable,\n number,\n object,\n optional,\n parser,\n picklist,\n pipe,\n regex,\n safeParse,\n string,\n transform,\n unknown,\n variant,\n} from \"valibot\";\n\nimport {\n vPaymentWidgetPaymentResultResponseDto,\n vPaymentWidgetQuoteResponseDto,\n vPublicPaymentWidgetResponseDto,\n} from \"./generated/public-api/valibot.gen.ts\";\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst paymentOptionSchema = picklist([\n \"one-time\",\n \"monthly\",\n \"annually\",\n \"every-six-months\",\n]);\nconst fulfillmentTypeSchema = picklist([\"none\", \"event_admission\"]);\nconst nullableNonNegativeIntegerSchema = nullable(safeIntegerSchema(0));\nconst availabilityStatusSchema = picklist([\"available\", \"sold_out\"]);\nconst availabilitySchema = optional(\n object({\n listings: array(\n object({\n listingId: nonEmptyStringSchema,\n maxPurchasableQuantity: nullableNonNegativeIntegerSchema,\n remainingQuantity: nullableNonNegativeIntegerSchema,\n status: availabilityStatusSchema,\n })\n ),\n sharedLimits: array(\n object({\n id: nonEmptyStringSchema,\n listingIds: array(nonEmptyStringSchema),\n remainingQuantity: safeIntegerSchema(0),\n status: availabilityStatusSchema,\n })\n ),\n }),\n { listings: [], sharedLimits: [] }\n);\nconst publishableKeySchema = pipe(\n string(),\n regex(/^pk_(?:test|live)_\\S+$/, \"Invalid publishable key.\")\n);\n\nconst productBaseEntries = {\n description: optionalNullableStringSchema,\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n maxQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n};\n\nconst eventSchema = object({\n description: nullable(string()),\n endAt: nonEmptyStringSchema,\n id: nonEmptyStringSchema,\n location: nullable(string()),\n name: nonEmptyStringSchema,\n startAt: nonEmptyStringSchema,\n status: picklist([\"draft\", \"active\", \"finished\", \"cancelled\"]),\n});\n\nconst publicProductSchema = variant(\"pricingMode\", [\n object({\n ...productBaseEntries,\n amountCents: safeIntegerSchema(0),\n pricingMode: literal(\"fixed\"),\n }),\n object({\n ...productBaseEntries,\n amountCents: nullableNonNegativeIntegerSchema,\n pricingMode: literal(\"custom\"),\n }),\n]);\n\nconst productListingSchema = object({\n acceptsDiscounts: optional(boolean(), false),\n id: nonEmptyStringSchema,\n maxQuantityPerOrder: optional(nullableNonNegativeIntegerSchema, null),\n product: publicProductSchema,\n productId: nonEmptyStringSchema,\n slug: nonEmptyStringSchema,\n});\n\nconst liveShippingSchema = optional(\n object({ enabled: boolean(), productIds: array(string()) })\n);\n\nconst widgetFieldsSchema = optional(\n object({\n memberId: optional(boolean(), false),\n merchSize: optional(boolean(), false),\n phone: optional(boolean(), false),\n promoCode: optional(boolean(), false),\n serviceFee: optional(boolean(), false),\n shipping: optional(boolean(), false),\n tipping: optional(boolean(), false),\n }),\n {}\n);\n\nexport const publicWidgetSchema = pipe(\n object({\n availability: availabilitySchema,\n community: optional(\n object({\n color: string(),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n thumbnail: nullable(string()),\n widgetAchEnabled: optional(boolean()),\n })\n ),\n config: optional(\n object({\n customFields: customFieldsSchema,\n fields: widgetFieldsSchema,\n liveShipping: liveShippingSchema,\n })\n ),\n description: optionalNullableStringSchema,\n event: nullable(eventSchema),\n id: optional(string(), \"\"),\n name: optional(string(), \"Lockerverse widget\"),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: optional(\n object({\n currency: optional(literal(\"usd\"), \"usd\"),\n serviceFeeRateBasisPoints: optional(safeIntegerSchema(0), 0),\n })\n ),\n products: optional(array(productListingSchema), []),\n showCommunityBranding: optional(boolean(), true),\n title: optionalNullableStringSchema,\n }),\n transform((widget) => ({\n ...widget,\n config: {\n customFields: widget.config?.customFields ?? [],\n fields: {\n memberId: widget.config?.fields?.memberId ?? false,\n merchSize: widget.config?.fields?.merchSize ?? false,\n phone: widget.config?.fields?.phone ?? false,\n promoCode: widget.config?.fields?.promoCode ?? false,\n serviceFee: widget.config?.fields?.serviceFee ?? false,\n shipping: widget.config?.fields?.shipping ?? false,\n tipping: widget.config?.fields?.tipping ?? false,\n },\n liveShipping: widget.config?.liveShipping,\n },\n pricingPolicy: widget.pricingPolicy ?? {\n currency: \"usd\" as const,\n serviceFeeRateBasisPoints: 0,\n },\n }))\n);\n\nconst catalogProductSchema = object({\n acceptsDiscounts: boolean(),\n amountCents: nullable(safeIntegerSchema(0)),\n description: nullable(string()),\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n listingId: nonEmptyStringSchema,\n maximumQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minimumQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n slug: nonEmptyStringSchema,\n});\n\nconst catalogSchema = object({\n availability: availabilitySchema,\n community: nullable(\n object({\n accentColor: string(),\n imageUrl: nullable(string()),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n widgetAchEnabled: optional(boolean()),\n })\n ),\n event: nullable(eventSchema),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: object({\n currency: literal(\"usd\"),\n serviceFeeRateBasisPoints: safeIntegerSchema(0),\n }),\n products: array(catalogProductSchema),\n widget: object({\n customFields: customFieldsSchema,\n description: nullable(string()),\n fields: widgetFieldsSchema,\n id: string(),\n liveShipping: liveShippingSchema,\n name: nonEmptyStringSchema,\n showCommunityBranding: boolean(),\n title: nullable(string()),\n }),\n});\n\nconst appliedDiscountSchema = nullable(\n object({\n percentageOff: pipe(number(), finite(), minValue(0), maxValue(100)),\n source: picklist([\"email_list\", \"promo_code\"]),\n })\n);\n\nconst checkoutLineItemSchema = object({\n acceptsDiscounts: boolean(),\n eventId: nullable(nonEmptyStringSchema),\n fulfillmentType: fulfillmentTypeSchema,\n listingId: nonEmptyStringSchema,\n listingSlug: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n productId: nonEmptyStringSchema,\n productName: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n subtotalCents: safeIntegerSchema(0),\n unitAmountCents: safeIntegerSchema(0),\n});\n\nexport const checkoutQuoteSchema = pipe(\n looseObject(vPaymentWidgetQuoteResponseDto.entries),\n object({\n amountCents: safeIntegerSchema(0),\n appliedDiscount: appliedDiscountSchema,\n connectedAccountId: nullable(nonEmptyStringSchema),\n discountableSubtotalCents: safeIntegerSchema(0),\n discountCents: safeIntegerSchema(0),\n lineItems: array(checkoutLineItemSchema),\n paymentOption: paymentOptionSchema,\n serviceFeeCents: safeIntegerSchema(0),\n shippingCents: optional(safeIntegerSchema(0)),\n shippingQuote: optional(\n nullable(\n object({\n amountCents: safeIntegerSchema(0),\n carrier: string(),\n estimatedDays: nullable(number()),\n expiresAt: nonEmptyStringSchema,\n service: string(),\n token: nonEmptyStringSchema,\n })\n )\n ),\n shippingRequired: optional(boolean()),\n subtotalCents: safeIntegerSchema(0),\n tipCents: safeIntegerSchema(0),\n totalCents: safeIntegerSchema(0),\n }),\n check(({ lineItems, paymentOption }) => {\n if (\n lineItems.length === 0 ||\n lineItems.some((item) => item.paymentOption !== paymentOption)\n ) {\n return false;\n }\n return (\n paymentOption === \"one-time\" ||\n (lineItems.length === 1 &&\n lineItems[0]?.pricingMode === \"fixed\" &&\n lineItems[0].quantity === 1)\n );\n }, \"Invalid checkout cadence composition.\")\n);\n\nexport const paymentResultSchema = pipe(\n object({\n ...vPaymentWidgetPaymentResultResponseDto.entries,\n retryUrl: optional(pipe(nonEmptyStringSchema, regex(/^https:\\/\\//))),\n }),\n check((payment) => {\n if (!(payment.checkoutId.trim() && payment.paymentReference.trim())) {\n return false;\n }\n if (payment.checkoutStatus === \"action_required\") {\n return (\n payment.paymentRequired &&\n ((payment.requiresAction && Boolean(payment.clientSecret?.trim())) ||\n (!payment.requiresAction &&\n payment.clientSecret === null &&\n Boolean(payment.retryUrl)))\n );\n }\n return !payment.requiresAction && payment.clientSecret === null;\n }, \"Invalid payment result state.\")\n);\n\nexport type PublicCheckoutQuote = InferOutput<typeof checkoutQuoteSchema>;\nexport type PublicProductListing = InferOutput<typeof productListingSchema>;\nexport type PublicWidget = InferOutput<typeof publicWidgetSchema>;\n\nexport const parseCheckoutQuote = parser(checkoutQuoteSchema);\nexport const parseCatalog = parser(catalogSchema);\nexport const parsePaymentResult = parser(paymentResultSchema);\nconst parsePublicWidgetContract = parser(vPublicPaymentWidgetResponseDto);\nconst parseSdkPublicWidget = parser(publicWidgetSchema);\n\nexport function parsePublicWidget<Input>(input: Input) {\n parsePublicWidgetContract(input);\n return parseSdkPublicWidget(input);\n}\n\nexport function parsePublicWidgetLoad<Input>(input: Input) {\n const response = safeParse(\n looseObject({ quote: optional(unknown()) }),\n input\n );\n const widget = parsePublicWidget(input);\n const quote = response.success ? response.output.quote : undefined;\n return quote === undefined\n ? { widget }\n : { quote: parseCheckoutQuote(quote), widget };\n}\n","import {\n array,\n boolean,\n type InferOutput,\n literal,\n looseObject,\n minLength,\n nullable,\n object,\n optional,\n parser,\n picklist,\n pipe,\n record,\n strictObject,\n string,\n transform,\n union,\n unknown,\n} from \"valibot\";\n\nimport { parseCheckoutQuote } from \"./checkout-schemas.ts\";\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst shippingSchema = strictObject({\n address: strictObject({\n city: string(),\n country: string(),\n line1: string(),\n line2: optional(string()),\n postal_code: string(),\n state: string(),\n }),\n name: string(),\n});\n\nconst checkoutPricingEntries = {\n email: optional(string()),\n includeServiceFee: optional(boolean()),\n promoCode: optional(string()),\n shipping: optional(shippingSchema),\n shippingQuoteToken: optional(nonEmptyStringSchema),\n tipCents: optional(safeIntegerSchema(0)),\n};\n\nconst checkoutPricingInputSchema = strictObject(checkoutPricingEntries);\n\nexport const parseCheckoutPricingInput = parser(\n optional(checkoutPricingInputSchema, {})\n);\n\nconst paymentSubmissionSchema = strictObject({\n confirmationToken: optional(nonEmptyStringSchema),\n customFieldAnswers: optional(array(customFieldAnswerSchema)),\n email: string(),\n memberId: optional(string()),\n merchSize: optional(picklist([\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\"])),\n metadata: optional(record(string(), string())),\n paymentMethodConfiguration: optional(literal(\"explicit\")),\n phone: optional(string()),\n shipping: optional(shippingSchema),\n});\n\nconst checkoutItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productId: nonEmptyStringSchema,\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutSelectionItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productSlug: nonEmptyStringSchema,\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutItemsSchema = pipe(array(checkoutItemSchema), minLength(1));\nconst checkoutSelectionItemsSchema = pipe(\n array(checkoutSelectionItemSchema),\n minLength(1)\n);\n\nconst loadCheckoutInputSchema = object({\n selection: checkoutSelectionItemsSchema,\n});\n\nconst calculateTotalInputSchema = looseObject({\n catalog: optional(unknown()),\n email: optional(unknown()),\n includeServiceFee: optional(unknown()),\n items: optional(checkoutItemsSchema),\n promoCode: optional(unknown()),\n selection: optional(checkoutSelectionItemsSchema),\n tipCents: optional(unknown()),\n});\n\nconst preparedCheckoutInputSchema = pipe(\n looseObject({\n authoritative: literal(true),\n items: checkoutItemsSchema,\n payment: object({\n connectedAccountId: nullable(nonEmptyStringSchema),\n currency: literal(\"usd\"),\n publishableKey: pipe(string(), minLength(1)),\n }),\n paymentReference: pipe(string(), minLength(1)),\n pricing: checkoutPricingInputSchema,\n }),\n transform((checkout) => {\n const { items, payment, paymentReference, pricing, ...quoteInput } =\n checkout;\n const parsedQuote = parseCheckoutQuote({\n ...quoteInput,\n connectedAccountId: payment.connectedAccountId,\n });\n const { connectedAccountId, ...quote } = parsedQuote;\n return {\n items,\n pricing,\n quote: {\n ...quote,\n authoritative: true as const,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: parsedQuote.paymentOption,\n paymentReference,\n },\n };\n })\n);\n\nconst submitPaymentInputSchema = looseObject({\n checkout: preparedCheckoutInputSchema,\n submission: paymentSubmissionSchema,\n});\n\nconst paymentReferenceInputSchema = nonEmptyStringSchema;\nconst parseCatalogInputFields = parser(looseObject({}));\n\nexport type ParsedPreparedCheckoutInput = InferOutput<\n typeof preparedCheckoutInputSchema\n>;\nexport type ParsedLoadCheckoutInput = InferOutput<\n typeof loadCheckoutInputSchema\n>;\nexport type ParsedPaymentReferenceInput = InferOutput<\n typeof paymentReferenceInputSchema\n>;\nexport type ParsedSubmitPaymentInput = InferOutput<\n typeof submitPaymentInputSchema\n>;\n\nconst parseCalculateTotalInputFields = parser(calculateTotalInputSchema);\n\nexport function parseCalculateTotalInput<Input>(input: Input) {\n const { catalog, items, selection, ...pricingInput } =\n parseCalculateTotalInputFields(input);\n let parsedCatalog: ReturnType<typeof parseCatalogInputFields>;\n try {\n parsedCatalog = parseCatalogInputFields(catalog);\n } catch (error) {\n throw new TypeError(\"A catalog is required to calculate a checkout.\", {\n cause: error,\n });\n }\n try {\n return {\n catalog: parsedCatalog,\n items,\n pricing: parseCheckoutPricingInput(pricingInput),\n selection,\n };\n } catch (error) {\n throw new TypeError(\"Checkout pricing input is invalid.\", { cause: error });\n }\n}\n\nexport type ParsedCalculateTotalInput = ReturnType<\n typeof parseCalculateTotalInput\n>;\nexport type ParsedCheckoutPricingInput = InferOutput<\n typeof checkoutPricingInputSchema\n>;\n\nexport const parseLoadCheckoutInput = parser(loadCheckoutInputSchema);\nexport const parsePaymentReferenceInput = parser(paymentReferenceInputSchema);\nexport const parsePreparedCheckoutInput = parser(preparedCheckoutInputSchema);\nexport const parseSubmitPaymentInput = parser(submitPaymentInputSchema);\n\nexport const parseCheckoutSelectionItems = parser(checkoutSelectionItemsSchema);\n","import type { LockerverseProduct } from \"./types.ts\";\n\nconst minimumCustomAmountCents = 100;\n\nexport function getLockerverseMinimumCustomAmountCents(\n product: Pick<LockerverseProduct, \"minimumAmountCents\">\n) {\n return Math.max(minimumCustomAmountCents, product.minimumAmountCents ?? 0);\n}\n","import { parseCheckoutSelectionItems } from \"./checkout-input-schemas.ts\";\nimport { getLockerverseMinimumCustomAmountCents } from \"./custom-amount.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutItem,\n LockerverseCheckoutLineItem,\n LockerverseCheckoutSelectionItem,\n LockerverseProduct,\n} from \"./types.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\ntype ResolvedSelectionItem = {\n checkoutItem: LockerverseCheckoutItem;\n quantity: number;\n unitAmountCents: number;\n};\n\nexport function assertCheckoutItemsAreAvailable(\n catalog: LockerverseCatalog,\n items: LockerverseCheckoutItem[]\n) {\n const listingIdByProductId = new Map(\n catalog.products.map(({ id, listingId }) => [id, listingId])\n );\n const requestedByListingId = items.reduce((requested, item) => {\n const listingId = listingIdByProductId.get(item.productId);\n if (listingId) {\n requested.set(\n listingId,\n (requested.get(listingId) ?? 0) +\n (\"quantity\" in item ? (item.quantity ?? 1) : 1)\n );\n }\n return requested;\n }, new Map<string, number>());\n const listingIsSoldOut = catalog.availability.listings.some(\n ({ listingId, maxPurchasableQuantity, status }) =>\n requestedByListingId.has(listingId) &&\n (status === \"sold_out\" ||\n (maxPurchasableQuantity !== null &&\n (requestedByListingId.get(listingId) ?? 0) > maxPurchasableQuantity))\n );\n const sharedLimitIsSoldOut = catalog.availability.sharedLimits.some(\n ({ listingIds, remainingQuantity, status }) => {\n const requestedQuantity = listingIds.reduce(\n (total, listingId) =>\n total + (requestedByListingId.get(listingId) ?? 0),\n 0\n );\n return (\n requestedQuantity > 0 &&\n (status === \"sold_out\" || requestedQuantity > remainingQuantity)\n );\n }\n );\n if (listingIsSoldOut || sharedLimitIsSoldOut) {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"This option is sold out.\",\n operation: \"calculate_total\",\n reportable: false,\n serverCode: \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n });\n }\n}\n\nfunction resolveAmountItem(\n product: LockerverseProduct,\n amountCents: number\n): ResolvedSelectionItem {\n if (\n product.pricingMode !== \"custom\" ||\n product.paymentOption !== \"one-time\" ||\n amountCents < getLockerverseMinimumCustomAmountCents(product)\n ) {\n throw new TypeError(\"Selected Product amount is invalid.\");\n }\n return {\n checkoutItem: { amountCents, productId: product.id },\n quantity: 1,\n unitAmountCents: amountCents,\n };\n}\n\nfunction resolveFixedItem(\n product: LockerverseProduct,\n quantity: number\n): ResolvedSelectionItem {\n if (product.pricingMode !== \"fixed\" || product.amountCents === null) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n if (product.paymentOption !== \"one-time\" && quantity !== 1) {\n throw new TypeError(\"Selected recurring Product is invalid.\");\n }\n if (\n (product.minimumQuantity !== null && quantity < product.minimumQuantity) ||\n (product.maximumQuantity !== null && quantity > product.maximumQuantity) ||\n (product.inventoryQuantity !== null && quantity > product.inventoryQuantity)\n ) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n return {\n checkoutItem:\n product.paymentOption === \"one-time\"\n ? { productId: product.id, quantity }\n : { productId: product.id },\n quantity,\n unitAmountCents: product.amountCents,\n };\n}\n\nfunction resolveSelectionItem(\n catalog: LockerverseCatalog,\n product: LockerverseProduct,\n selection: LockerverseCheckoutSelectionItem\n) {\n const selectedQuantity = \"quantity\" in selection ? selection.quantity : 1;\n const resolved =\n \"amountCents\" in selection\n ? resolveAmountItem(product, selection.amountCents)\n : resolveFixedItem(product, selectedQuantity);\n const { checkoutItem, quantity, unitAmountCents } = resolved;\n\n return {\n checkoutItem,\n lineItem: {\n acceptsDiscounts: product.acceptsDiscounts,\n eventId:\n product.fulfillmentType === \"event_admission\" && catalog.event\n ? catalog.event.id\n : null,\n fulfillmentType: product.fulfillmentType,\n listingId: product.listingId,\n listingSlug: product.slug,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n productId: product.id,\n productName: product.name,\n quantity,\n subtotalCents: unitAmountCents * quantity,\n unitAmountCents,\n } satisfies LockerverseCheckoutLineItem,\n };\n}\n\nexport function resolveCheckoutSelection(\n catalog: LockerverseCatalog,\n input: LockerverseCheckoutSelectionItem[]\n) {\n const selection = parseCheckoutSelectionItems(input);\n const selectedProducts = new Set<string>();\n const resolved = selection.map((item) => {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"Selected Product is unavailable.\");\n }\n if (selectedProducts.has(product.id)) {\n throw new TypeError(\"Each Product can appear only once per checkout.\");\n }\n selectedProducts.add(product.id);\n return resolveSelectionItem(catalog, product, item);\n });\n const paymentOption = resolved[0]?.lineItem.paymentOption;\n if (!paymentOption) {\n throw new TypeError(\"Select at least one Product.\");\n }\n if (\n resolved.length > 1 &&\n (paymentOption !== \"one-time\" ||\n resolved.some(({ lineItem }) => lineItem.paymentOption !== paymentOption))\n ) {\n throw new TypeError(\"Recurring Products must be purchased separately.\");\n }\n const items = resolved.map(({ checkoutItem }) => checkoutItem);\n assertCheckoutItemsAreAvailable(catalog, items);\n return {\n items,\n lineItems: resolved.map(({ lineItem }) => lineItem),\n paymentOption,\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCommunityBranding,\n LockerversePaymentResult,\n LockerversePreparedCheckout,\n LockerverseProduct,\n} from \"./types.ts\";\n\nfunction mapProduct(listing: PublicProductListing): LockerverseProduct {\n const { product } = listing;\n\n return {\n acceptsDiscounts: listing.acceptsDiscounts ?? false,\n amountCents: product.amountCents,\n description: product.description ?? null,\n fulfillmentType: product.fulfillmentType,\n id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: listing.maxQuantityPerOrder,\n minimumAmountCents: product.minimumAmountCents,\n minimumQuantity: product.minQuantity,\n name: product.name,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n slug: listing.slug,\n };\n}\n\nfunction mapCommunity(\n community: PublicWidget[\"community\"]\n): LockerverseCommunityBranding | null {\n if (!community) {\n return null;\n }\n const branding: LockerverseCommunityBranding = {\n accentColor: community.color,\n imageUrl: community.thumbnail || null,\n name: community.name,\n };\n if (community.widgetAchEnabled !== undefined) {\n branding.widgetAchEnabled = community.widgetAchEnabled;\n }\n if (community.memberIdLabel !== undefined) {\n branding.memberIdLabel = community.memberIdLabel;\n }\n return branding;\n}\n\nexport function createCatalog(widget: PublicWidget): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n availability: widget.availability,\n community: mapCommunity(widget.community),\n event: widget.event\n ? {\n description: widget.event.description,\n endAt: widget.event.endAt,\n id: widget.event.id,\n location: widget.event.location,\n name: widget.event.name,\n startAt: widget.event.startAt,\n status: widget.event.status,\n }\n : null,\n payment: {\n connectedAccountId: widget.payment.connectedAccountId,\n currency: widget.payment.currency,\n publishableKey: widget.payment.publishableKey,\n },\n pricingPolicy: {\n currency: \"usd\",\n serviceFeeRateBasisPoints:\n widget.pricingPolicy?.serviceFeeRateBasisPoints ?? 0,\n },\n products: (widget.products ?? []).map(mapProduct),\n widget: {\n customFields: widget.config?.customFields ?? [],\n description: widget.description ?? null,\n fields: {\n memberId: fields.memberId ?? false,\n merchSize: fields.merchSize ?? false,\n phone: fields.phone ?? false,\n promoCode: fields.promoCode ?? false,\n serviceFee: fields.serviceFee ?? false,\n shipping: fields.shipping ?? false,\n tipping: fields.tipping ?? false,\n },\n id: widget.id ?? \"\",\n liveShipping: widget.config?.liveShipping,\n name: widget.name ?? \"Lockerverse widget\",\n showCommunityBranding: widget.showCommunityBranding ?? true,\n title: widget.title ?? null,\n },\n };\n}\n\nexport function cloneCatalog(catalog: LockerverseCatalog): LockerverseCatalog {\n return cloneSnapshot(catalog);\n}\n\nexport function clonePreparedCheckout(\n checkout: LockerversePreparedCheckout\n): LockerversePreparedCheckout {\n return cloneSnapshot(checkout);\n}\n\nexport function clonePaymentResult(\n paymentResult: LockerversePaymentResult\n): LockerversePaymentResult {\n return cloneSnapshot(paymentResult);\n}\n\nfunction cloneSnapshot<T>(value: T): T {\n return deepFreeze(structuredClone(value));\n}\n","import { object, picklist, safeParse } from \"valibot\";\nimport { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport {\n type ParsedCalculateTotalInput,\n type ParsedCheckoutPricingInput,\n parseCalculateTotalInput,\n parseLoadCheckoutInput,\n parsePaymentReferenceInput,\n parseSubmitPaymentInput,\n} from \"./checkout-input-schemas.ts\";\nimport {\n parseCatalog,\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidgetLoad,\n} from \"./checkout-schemas.ts\";\nimport {\n assertCheckoutItemsAreAvailable,\n resolveCheckoutSelection,\n} from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n cloneCatalog,\n clonePaymentResult,\n clonePreparedCheckout,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCalculateTotalInput,\n type LockerverseCatalog,\n type LockerverseCheckoutClient,\n type LockerverseCheckoutItem,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutSelectionItem,\n type LockerverseLoadCheckoutInput,\n type LockerverseLoadedCheckout,\n type LockerversePreparedCheckout,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSdkServerCode,\n type LockerverseSubmitPaymentInput,\n} from \"./types.ts\";\n\ntype OperationErrorContext = {\n code:\n | \"payment_status_failed\"\n | \"payment_submit_failed\"\n | \"total_calculation_failed\"\n | \"widget_load_failed\";\n message: string;\n operation:\n | \"calculate_total\"\n | \"get_payment_status\"\n | \"load_widget\"\n | \"submit_payment\";\n};\n\nconst MAX_SELECTED_WIDGET_URL_LENGTH = 4000;\nconst paymentServerErrorSchema = object({\n code: picklist([\n \"PAYMENT_WIDGET_PHONE_INVALID\",\n \"PAYMENT_WIDGET_PHONE_REQUIRED\",\n \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n ]),\n});\n\nasync function readPaymentServerCode(\n response: Response\n): Promise<LockerverseSdkServerCode | undefined> {\n if (response.status !== 400 && response.status !== 409) {\n return;\n }\n try {\n const result = safeParse(paymentServerErrorSchema, await response.json());\n return result.success ? result.output.code : undefined;\n } catch {\n // Non-JSON error bodies do not contain a safe server code.\n }\n}\n\nfunction resolveCalculateTotalItems({\n catalog,\n items,\n selection,\n}: ParsedCalculateTotalInput) {\n if (items !== undefined && selection !== undefined) {\n throw new TypeError(\"Use items or selection, not both.\");\n }\n const selectionCatalog = cloneCatalog(parseCatalog(catalog));\n const checkoutItems =\n selection === undefined\n ? requireCheckoutItems(items)\n : resolveCheckoutSelection(selectionCatalog, selection).items;\n assertCheckoutItemsAreAvailable(selectionCatalog, checkoutItems);\n return {\n catalog: selectionCatalog,\n items: checkoutItems,\n };\n}\n\nfunction requireCheckoutItems(\n items: ParsedCalculateTotalInput[\"items\"]\n): LockerverseCheckoutItem[] {\n if (items === undefined) {\n throw new TypeError(\"Checkout selection is invalid.\");\n }\n return items;\n}\n\nexport function createLockerverseCheckoutClient(\n options: CreateLockerverseWidgetOptions\n): LockerverseCheckoutClient {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n requestTimeoutMs,\n sentryDsn,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({ widgetSlug: widgetSlugValue }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n const { requestJson } = createTransport(\n fetchImplementation,\n reportError,\n requestTimeoutMs\n );\n const checkoutBaseUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout`;\n const widgetUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`;\n\n function invalidInput(\n message: string,\n operation: LockerverseSdkOperation,\n code: \"invalid_selection\" | \"payment_submit_failed\" = \"invalid_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code,\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n function normalizeOperationError<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext\n ) {\n return error instanceof LockerverseSdkError\n ? error\n : new LockerverseSdkError({ ...context, reportable: true });\n }\n\n function failOperation<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext,\n recoveryMayBeRequired = false\n ): never {\n const normalized = normalizeOperationError(error, context);\n const recoveryRecommended =\n recoveryMayBeRequired &&\n (normalized.status === undefined || normalized.status >= 500);\n if (!recoveryRecommended) {\n throw reportError(normalized);\n }\n const recoveryError =\n normalized.status === undefined\n ? new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n })\n : new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n status: normalized.status,\n });\n throw reportError(recoveryError);\n }\n\n function normalizePricingInput(input: ParsedCheckoutPricingInput) {\n const email = input.email?.trim().toLowerCase();\n const promoCode = input.promoCode?.trim();\n const pricing: LockerverseCheckoutPricingInput = {};\n if (email) {\n pricing.email = email;\n }\n if (input.includeServiceFee !== undefined) {\n pricing.includeServiceFee = input.includeServiceFee;\n }\n if (promoCode) {\n pricing.promoCode = promoCode;\n }\n if (input.tipCents !== undefined) {\n pricing.tipCents = input.tipCents;\n }\n if (input.shipping) {\n pricing.shipping = input.shipping;\n }\n if (input.shippingQuoteToken) {\n pricing.shippingQuoteToken = input.shippingQuoteToken;\n }\n return pricing;\n }\n\n function normalizeLoadSelection(input: LockerverseLoadCheckoutInput) {\n try {\n return parseLoadCheckoutInput(input).selection;\n } catch {\n invalidInput(\"Checkout selection is invalid.\", \"load_widget\");\n }\n }\n\n function createPreparedCheckout(\n quote: ReturnType<typeof parseCheckoutQuote>,\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"]\n ): LockerversePreparedCheckout {\n const { connectedAccountId, ...checkoutQuote } = quote;\n return clonePreparedCheckout(\n deepFreeze({\n ...checkoutQuote,\n authoritative: true as const,\n items,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: quote.paymentOption,\n paymentReference: globalThis.crypto.randomUUID(),\n pricing,\n })\n );\n }\n\n function resolveSelectedCheckoutItems(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n operation: LockerverseSdkOperation\n ) {\n try {\n return resolveCheckoutSelection(catalog, selection).items;\n } catch (error) {\n if (error instanceof TypeError) {\n invalidInput(error.message, operation);\n }\n throw error;\n }\n }\n\n function createSelectedCheckout(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n quote: ReturnType<typeof parseCheckoutQuote> | undefined,\n context: OperationErrorContext\n ) {\n if (!quote) {\n throw new LockerverseSdkError({\n ...context,\n message: \"Lockerverse did not return the requested initial quote.\",\n reportable: true,\n });\n }\n const checkoutItems = resolveSelectedCheckoutItems(\n catalog,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: cloneCatalog(catalog),\n checkout: createPreparedCheckout(\n quote,\n checkoutItems,\n { includeServiceFee: catalog.widget.fields.serviceFee },\n catalog.payment\n ),\n });\n }\n\n function requestWidgetResource(): Promise<LockerverseCatalog>;\n function requestWidgetResource(\n selection: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseLoadedCheckout>;\n async function requestWidgetResource(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n const requestUrl = selection\n ? `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n : widgetUrl;\n const response = await requestJson(\n requestUrl,\n selection ? { cache: \"no-store\" } : undefined,\n parsePublicWidgetLoad,\n {\n ...context,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to load Lockerverse widget (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n const catalog = deepFreeze(createCatalog(response.value.widget));\n if (!selection) {\n return cloneCatalog(catalog);\n }\n return createSelectedCheckout(\n catalog,\n selection,\n response.value.quote,\n context\n );\n }\n\n async function loadLargeSelection(\n selection: LockerverseCheckoutSelectionItem[],\n context: OperationErrorContext\n ): Promise<LockerverseLoadedCheckout> {\n const loaded = await requestWidgetResource();\n const pricing = {\n includeServiceFee: loaded.widget.fields.serviceFee,\n };\n const items = resolveSelectedCheckoutItems(\n loaded,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: loaded,\n checkout: await requestCheckoutQuote(\n items,\n pricing,\n loaded.payment,\n context\n ),\n });\n }\n\n async function loadWidget(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n try {\n if (\n selection &&\n `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n .length > MAX_SELECTED_WIDGET_URL_LENGTH\n ) {\n return await loadLargeSelection(selection, context);\n }\n return selection\n ? await requestWidgetResource(selection)\n : await requestWidgetResource();\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function load(): Promise<LockerverseCatalog>;\n function load(\n input: LockerverseLoadCheckoutInput\n ): Promise<LockerverseLoadedCheckout>;\n function load(input?: LockerverseLoadCheckoutInput) {\n return input === undefined\n ? loadWidget()\n : loadWidget(normalizeLoadSelection(input));\n }\n\n async function requestCheckoutQuote(\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"],\n context: OperationErrorContext\n ) {\n const response = await requestJson(\n `${checkoutBaseUrl}/quote`,\n {\n body: JSON.stringify({ ...pricing, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parseCheckoutQuote,\n {\n ...context,\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to calculate the Lockerverse checkout total (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n return createPreparedCheckout(response.value, items, pricing, payment);\n }\n\n async function calculateTotal(input: LockerverseCalculateTotalInput) {\n const { catalog, items, pricing } = normalizeCalculateTotalInput(input);\n const context = {\n code: \"total_calculation_failed\" as const,\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\" as const,\n };\n try {\n return await requestCheckoutQuote(\n items,\n pricing,\n catalog.payment,\n context\n );\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function normalizeCalculateTotalInput(input: LockerverseCalculateTotalInput) {\n try {\n const parsed = parseCalculateTotalInput(input);\n const resolved = resolveCalculateTotalItems(parsed);\n const pricing = normalizePricingInput(parsed.pricing);\n return {\n catalog: resolved.catalog,\n items: resolved.items,\n pricing:\n pricing.includeServiceFee === undefined\n ? {\n ...pricing,\n includeServiceFee: resolved.catalog.widget.fields.serviceFee,\n }\n : pricing,\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n error instanceof TypeError\n ? error.message\n : \"Checkout selection is invalid.\",\n \"calculate_total\"\n );\n }\n }\n\n function normalizeSubmitPaymentInput(input: LockerverseSubmitPaymentInput) {\n try {\n const parsed = parseSubmitPaymentInput(input);\n const {\n items,\n pricing: pricingInput,\n quote: quoteInput,\n } = parsed.checkout;\n const pricing = normalizePricingInput(pricingInput);\n const quote = deepFreeze(quoteInput);\n const { submission } = parsed;\n if (quote.totalCents > 0 && !submission.confirmationToken) {\n invalidInput(\n \"Stripe confirmation is required for a paid checkout.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n const email = submission.email.trim().toLowerCase();\n if (!email || email !== pricing.email) {\n invalidInput(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n return {\n items,\n pricing,\n quote,\n submission: { ...submission, email },\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n \"Lockerverse payment submission is invalid.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n }\n\n return {\n calculateTotal,\n async getPaymentStatus(paymentReference) {\n let normalizedReference: string;\n try {\n normalizedReference =\n parsePaymentReferenceInput(paymentReference).trim();\n } catch {\n invalidInput(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n const context = {\n code: \"payment_status_failed\" as const,\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/${encodeURIComponent(normalizedReference)}/status`,\n undefined,\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n report: false,\n },\n { ...context, report: false }\n );\n if (!response.ok) {\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to recover the Lockerverse payment status (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== normalizedReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context);\n }\n },\n load,\n async submitPayment(input) {\n const { items, pricing, quote, submission } =\n normalizeSubmitPaymentInput(input);\n const context = {\n code: \"payment_submit_failed\" as const,\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: submission.confirmationToken,\n customFieldAnswers: submission.customFieldAnswers,\n email: submission.email,\n expectedAmountCents: quote.amountCents,\n expectedAppliedDiscount: quote.appliedDiscount,\n expectedConnectedAccountId: quote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n quote.discountableSubtotalCents,\n expectedDiscountCents: quote.discountCents,\n expectedServiceFeeCents: quote.serviceFeeCents,\n expectedShippingCents: quote.shippingCents,\n expectedSubtotalCents: quote.subtotalCents,\n expectedTipCents: quote.tipCents,\n expectedTotalCents: quote.totalCents,\n ...pricing,\n items,\n memberId: submission.memberId,\n merchSize: submission.merchSize,\n metadata: submission.metadata,\n paymentMethodConfiguration: submission.paymentMethodConfiguration,\n paymentReference: quote.paymentReference,\n phone: submission.phone,\n quoteContractVersion: 1,\n shipping: submission.shipping ?? pricing.shipping,\n shippingQuoteToken: quote.shippingQuote?.token,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode) {\n throw new LockerverseSdkError({\n ...context,\n message:\n serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n ? \"This option is sold out.\"\n : `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== quote.paymentReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context, true);\n }\n },\n };\n}\n","import { parseCheckoutPricingInput } from \"./checkout-input-schemas.ts\";\nimport { resolveCheckoutSelection } from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutEstimate,\n LockerverseEstimateCheckoutInput,\n} from \"./types.ts\";\n\nexport function estimateLockerverseCheckout(\n catalog: LockerverseCatalog,\n input: LockerverseEstimateCheckoutInput\n): LockerverseCheckoutEstimate {\n const { selection, ...pricingInput } = input;\n let pricing: ReturnType<typeof parseCheckoutPricingInput>;\n try {\n pricing = parseCheckoutPricingInput(pricingInput);\n } catch (error) {\n throw new TypeError(\"Checkout pricing is invalid.\", { cause: error });\n }\n const includeServiceFee =\n pricing.includeServiceFee ?? catalog.widget.fields.serviceFee;\n const { tipCents = 0 } = pricing;\n const { items, lineItems, paymentOption } = resolveCheckoutSelection(\n catalog,\n selection\n );\n const subtotalCents = lineItems.reduce(\n (total, lineItem) => total + lineItem.subtotalCents,\n 0\n );\n if (\n !Number.isSafeInteger(subtotalCents) ||\n subtotalCents <= 0 ||\n subtotalCents > 2_147_483_647\n ) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n const discountableSubtotalCents = lineItems.reduce(\n (total, lineItem) =>\n total + (lineItem.acceptsDiscounts ? lineItem.subtotalCents : 0),\n 0\n );\n const serviceFeeCents = includeServiceFee\n ? Math.round(\n (subtotalCents * catalog.pricingPolicy.serviceFeeRateBasisPoints) /\n 10_000\n )\n : 0;\n const amountCents = subtotalCents + serviceFeeCents;\n const totalCents = amountCents + tipCents;\n if (!Number.isSafeInteger(totalCents) || totalCents > 2_147_483_647) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n\n return deepFreeze({\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n items,\n lineItems,\n paymentOption,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents,\n });\n}\n"],"mappings":"yiBAGA,SAAgB,GACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,CCyBA,MAAM,EAAsB,EAAS,CACnC,WACA,UACA,WACA,kBACF,CAAC,EACK,EAAwB,EAAS,CAAC,OAAQ,iBAAiB,CAAC,EAC5D,EAAmC,EAAS,EAAkB,CAAC,CAAC,EAChE,EAA2B,EAAS,CAAC,YAAa,UAAU,CAAC,EAC7D,EAAqB,EACzB,EAAO,CACL,SAAU,EACR,EAAO,CACL,UAAW,EACX,uBAAwB,EACxB,kBAAmB,EACnB,OAAQ,CACV,CAAC,CACH,EACA,aAAc,EACZ,EAAO,CACL,GAAI,EACJ,WAAY,EAAM,CAAoB,EACtC,kBAAmB,EAAkB,CAAC,EACtC,OAAQ,CACV,CAAC,CACH,CACF,CAAC,EACD,CAAE,SAAU,CAAC,EAAG,aAAc,CAAC,CAAE,CACnC,EACM,EAAuB,EAC3B,EAAO,EACP,EAAM,yBAA0B,0BAA0B,CAC5D,EAEM,EAAqB,CACzB,YAAa,EACb,gBAAiB,EACjB,GAAI,EACJ,kBAAmB,EACnB,YAAa,EACb,mBAAoB,EACpB,YAAa,EACb,KAAM,EACN,cAAe,CACjB,EAEM,EAAc,EAAO,CACzB,YAAa,EAAS,EAAO,CAAC,EAC9B,MAAO,EACP,GAAI,EACJ,SAAU,EAAS,EAAO,CAAC,EAC3B,KAAM,EACN,QAAS,EACT,OAAQ,EAAS,CAAC,QAAS,SAAU,WAAY,WAAW,CAAC,CAC/D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AAU,GAA0B,CAAY,CAClD,OAAS,EAAO,CACd,MAAU,UAAU,+BAAgC,CAAE,MAAO,CAAM,CAAC,CACtE,CACA,IAAM,EACJ,EAAQ,mBAAqB,EAAQ,OAAO,OAAO,WAC/C,CAAE,WAAW,GAAM,EACnB,CAAE,QAAO,YAAW,iBAAkB,EAC1C,EACA,CACF,EACM,EAAgB,EAAU,QAC7B,EAAO,IAAa,EAAQ,EAAS,cACtC,CACF,EACA,GACE,CAAC,OAAO,cAAc,CAAa,GACnC,GAAiB,GACjB,EAAgB,WAEhB,MAAU,UAAU,4BAA4B,EAElD,IAAM,EAA4B,EAAU,QACzC,EAAO,IACN,GAAS,EAAS,iBAAmB,EAAS,cAAgB,GAChE,CACF,EACM,EAAkB,EACpB,KAAK,MACF,EAAgB,EAAQ,cAAc,0BACrC,GACJ,EACA,EACE,EAAc,EAAgB,EAC9B,EAAa,EAAc,EACjC,GAAI,CAAC,OAAO,cAAc,CAAU,GAAK,EAAa,WACpD,MAAU,UAAU,4BAA4B,EAGlD,OAAO,EAAW,CAChB,cACA,gBAAiB,KACjB,cAAe,GACf,4BACA,cAAe,EACf,QACA,YACA,gBACA,kBACA,gBACA,WACA,YACF,CAAC,CACH"}
|
package/dist/types.d.ts
CHANGED
|
@@ -109,6 +109,10 @@ type LockerverseCustomFieldAnswer<Field extends LockerverseCustomField = Lockerv
|
|
|
109
109
|
value: LockerverseCustomFieldAnswerValue<Field>;
|
|
110
110
|
} : never;
|
|
111
111
|
type LockerverseWidgetConfiguration = {
|
|
112
|
+
liveShipping?: {
|
|
113
|
+
enabled: boolean;
|
|
114
|
+
productIds: string[];
|
|
115
|
+
} | undefined;
|
|
112
116
|
customFields: LockerverseCustomField[];
|
|
113
117
|
description: string | null;
|
|
114
118
|
fields: LockerverseWidgetFields;
|
|
@@ -166,6 +170,16 @@ type LockerverseCheckoutAmounts = {
|
|
|
166
170
|
totalCents: number;
|
|
167
171
|
};
|
|
168
172
|
type LockerverseCheckoutQuote = LockerverseCheckoutAmounts & {
|
|
173
|
+
shippingRequired?: boolean | undefined;
|
|
174
|
+
shippingCents?: number | undefined;
|
|
175
|
+
shippingQuote?: {
|
|
176
|
+
token: string;
|
|
177
|
+
amountCents: number;
|
|
178
|
+
carrier: string;
|
|
179
|
+
service: string;
|
|
180
|
+
estimatedDays: number | null;
|
|
181
|
+
expiresAt: string;
|
|
182
|
+
} | null | undefined;
|
|
169
183
|
appliedDiscount: LockerverseAppliedDiscount | null;
|
|
170
184
|
authoritative: true;
|
|
171
185
|
paymentReference: string;
|
|
@@ -181,6 +195,8 @@ type LockerverseCheckoutEstimate = LockerverseCheckoutAmounts & {
|
|
|
181
195
|
paymentOption: LockerversePaymentOption;
|
|
182
196
|
};
|
|
183
197
|
type LockerverseCheckoutPricingInput = {
|
|
198
|
+
shipping?: LockerverseShipping;
|
|
199
|
+
shippingQuoteToken?: string;
|
|
184
200
|
email?: string;
|
|
185
201
|
includeServiceFee?: boolean;
|
|
186
202
|
promoCode?: string;
|
|
@@ -206,7 +222,7 @@ type LockerverseShipping = {
|
|
|
206
222
|
city: string;
|
|
207
223
|
country: string;
|
|
208
224
|
line1: string;
|
|
209
|
-
line2?: string;
|
|
225
|
+
line2?: string | undefined;
|
|
210
226
|
postal_code: string;
|
|
211
227
|
state: string;
|
|
212
228
|
};
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";KAGY;KAKA;KACA;cAEC;KAED;EACV;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA,eAAe;EACf;EACA;EACA;;EAEA;EACA;EACA;;KAGU;KAEA;EACV,UAAU;IACR;IACA;IACA;IACA,QAAQ;;EAEV,cAAc;IACZ;IACA;IACA;IACA,QAAQ;;;KAIA;EACV,cAAc;EACd,WAAW;EACX,OAAO;EACP,SAAS;EACT,eAAe;EACf,UAAU;EACV,QAAQ;;KAGE;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EAAiC;EAAY;;KAEpD;EACH;EACA;EACA;EACA;;KAGU,6BAA6B;EACvC;;KAGU,gCAAgC;EAC1C;;KAGU,qCAAqC;EAC/C,SAAS;EACT;;KAGU,oCAAoC;EAC9C,SAAS;EACT;;KAGU,yBACR,gCACA,6BACA,qCACA;KAEQ,kCACV,cAAc,0BACZ,cAAc,0CAEd,cAAc;KAIN,6BACV,cAAc,yBAAyB,0BACrC,cAAc;EACZ,SAAS;EAAa,OAAO,kCAAkC;;KAGzD;EACV,cAAc;EACd;EACA,QAAQ;EACR;EACA;EACA;EACA;;KAGU;KAeA;KAeA;cAOC,4BAA4B;WAC9B,MAAM;WACN,WAAW;WACX;WACA;WACA;WACA,YAAY;WACZ;EAEG,cACV,MACA,SACA,WACA,YACA,qBACA,YACA;IAEA,MAAM;IACN;IACA,WAAW;IACX;IACA;IACA,aAAa;IACb;;;KAcQ;EACV;EACA;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA,eAAe;EACf;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU,2BAA2B;EACrC,iBAAiB;EACjB;EACA;EACA,SAAS;EACT,eAAe;EACf,WAAW;;KAGD,8BAA8B;EACxC;EACA;EACA,gBAAgB;EAChB,oBAAoB;EACpB,eAAe;;KAGL;EACV;EACA;EACA;EACA;;KAGU;KAMA;EACV;EACA;EACA,gBAAgB;EAChB;EACA;EACA;EACA;EACA;;KAGU,+BAA+B;EACzC;EACA,oBAAoB;;KAYV;EACV;IACE;IACA;IACA;IACA;IACA;IACA;;EAEF;;KAGU;EACV;EACA;EACA,qBAAqB;EACrB;EACA;EACA;EACA,WAAW;EACX;EACA,WAAW;;KAGD;EACN;EAAmB;;EACnB;EAAmB;;EACnB;;KAEM;EACN;EAAqB;;EACrB;EAAqB;;EACrB;;KAEM,mCACV;EACE,WAAW;;KAGH;EACV,WAAW;;KAGD,iCAAiC;EAC3C,SAAS;;EAGH,OAAO;EACP;;EAGA;EACA,WAAW;;KAIP,8BAA8B,SACxC;EACE,gBAAgB;EAChB,SAAS,SAAS;;KAIV,4BAA4B;EACtC,SAAS;EACT,UAAU;;KAGA;EACV,UAAU;EACV,YAAY;;KAGT;EACH;EACA,eAAe,WAAW;EAC1B,WAAW,OAAO;EAClB;EACA;EACA;;KAGU;EAEN;EACA,aAAa;;EAGb;EACA;;KAGM,iCACV,qCAAqC;KAE3B;EACV,iBACE,OAAO,mCACJ,QAAQ;EACb,mBACE,6BACG,QAAQ;EACb;QACM,QAAQ;KACX,OAAO,+BAA+B,QAAQ;;EAEjD,gBACE,OAAO,kCACJ,QAAQ"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";KAGY;KAKA;KACA;cAEC;KAED;EACV;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA,eAAe;EACf;EACA;EACA;;EAEA;EACA;EACA;;KAGU;KAEA;EACV,UAAU;IACR;IACA;IACA;IACA,QAAQ;;EAEV,cAAc;IACZ;IACA;IACA;IACA,QAAQ;;;KAIA;EACV,cAAc;EACd,WAAW;EACX,OAAO;EACP,SAAS;EACT,eAAe;EACf,UAAU;EACV,QAAQ;;KAGE;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EAAiC;EAAY;;KAEpD;EACH;EACA;EACA;EACA;;KAGU,6BAA6B;EACvC;;KAGU,gCAAgC;EAC1C;;KAGU,qCAAqC;EAC/C,SAAS;EACT;;KAGU,oCAAoC;EAC9C,SAAS;EACT;;KAGU,yBACR,gCACA,6BACA,qCACA;KAEQ,kCACV,cAAc,0BACZ,cAAc,0CAEd,cAAc;KAIN,6BACV,cAAc,yBAAyB,0BACrC,cAAc;EACZ,SAAS;EAAa,OAAO,kCAAkC;;KAGzD;EACV;IAAiB;IAAkB;;EACnC,cAAc;EACd;EACA,QAAQ;EACR;EACA;EACA;EACA;;KAGU;KAeA;KAeA;cAOC,4BAA4B;WAC9B,MAAM;WACN,WAAW;WACX;WACA;WACA;WACA,YAAY;WACZ;EAEG,cACV,MACA,SACA,WACA,YACA,qBACA,YACA;IAEA,MAAM;IACN;IACA,WAAW;IACX;IACA;IACA,aAAa;IACb;;;KAcQ;EACV;EACA;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA,eAAe;EACf;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU,2BAA2B;EACrC;EACA;EACA;IAEM;IACA;IACA;IACA;IACA;IACA;;EAIN,iBAAiB;EACjB;EACA;EACA,SAAS;EACT,eAAe;EACf,WAAW;;KAGD,8BAA8B;EACxC;EACA;EACA,gBAAgB;EAChB,oBAAoB;EACpB,eAAe;;KAGL;EACV,WAAW;EACX;EACA;EACA;EACA;EACA;;KAGU;KAMA;EACV;EACA;EACA,gBAAgB;EAChB;EACA;EACA;EACA;EACA;;KAGU,+BAA+B;EACzC;EACA,oBAAoB;;KAYV;EACV;IACE;IACA;IACA;IACA;IACA;IACA;;EAEF;;KAGU;EACV;EACA;EACA,qBAAqB;EACrB;EACA;EACA;EACA,WAAW;EACX;EACA,WAAW;;KAGD;EACN;EAAmB;;EACnB;EAAmB;;EACnB;;KAEM;EACN;EAAqB;;EACrB;EAAqB;;EACrB;;KAEM,mCACV;EACE,WAAW;;KAGH;EACV,WAAW;;KAGD,iCAAiC;EAC3C,SAAS;;EAGH,OAAO;EACP;;EAGA;EACA,WAAW;;KAIP,8BAA8B,SACxC;EACE,gBAAgB;EAChB,SAAS,SAAS;;KAIV,4BAA4B;EACtC,SAAS;EACT,UAAU;;KAGA;EACV,UAAU;EACV,YAAY;;KAGT;EACH;EACA,eAAe,WAAW;EAC1B,WAAW,OAAO;EAClB;EACA;EACA;;KAGU;EAEN;EACA,aAAa;;EAGb;EACA;;KAGM,iCACV,qCAAqC;KAE3B;EACV,iBACE,OAAO,mCACJ,QAAQ;EACb,mBACE,6BACG,QAAQ;EACb;QACM,QAAQ;KACX,OAAO,+BAA+B,QAAQ;;EAEjD,gBACE,OAAO,kCACJ,QAAQ"}
|
package/dist/types.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=`0.2.
|
|
1
|
+
const e=`0.2.180-dev.1`;var t=class extends Error{code;operation;reportable;recoveryRecommended;sdkVersion;serverCode;status;constructor({code:t,message:n,operation:r,reportable:i,recoveryRecommended:a=!1,serverCode:o,status:s}){super(n),this.name=`LockerverseSdkError`,this.code=t,this.operation=r,this.reportable=i,this.recoveryRecommended=a,this.sdkVersion=e,this.serverCode=o,this.status=s}};export{t as n,e as t};
|
|
2
2
|
//# sourceMappingURL=types.js.map
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":["packageMetadata.version"],"sources":["../package.json","../src/types.ts"],"sourcesContent":["","import packageMetadata from \"../package.json\" with { type: \"json\" };\nimport type { GeneratedPaymentResult } from \"./generated/public-contract-types.ts\";\n\nexport type LockerversePaymentOption =\n | \"one-time\"\n | \"monthly\"\n | \"annually\"\n | \"every-six-months\";\nexport type LockerverseEnvironment = \"development\" | \"production\";\nexport type LockerverseFulfillmentType = \"none\" | \"event_admission\";\n\nexport const LOCKERVERSE_SDK_VERSION = packageMetadata.version;\n\nexport type LockerverseProduct = {\n id: string;\n listingId: string;\n slug: string;\n name: string;\n description: string | null;\n fulfillmentType: LockerverseFulfillmentType;\n pricingMode: \"fixed\" | \"custom\";\n paymentOption: LockerversePaymentOption;\n amountCents: number | null;\n minimumAmountCents: number | null;\n minimumQuantity: number | null;\n /** Per-order limit for this widget listing. Null means no per-order limit. */\n maximumQuantity: number | null;\n inventoryQuantity: number | null;\n acceptsDiscounts: boolean;\n};\n\nexport type LockerverseAvailabilityStatus = \"available\" | \"sold_out\";\n\nexport type LockerverseCatalogAvailability = {\n listings: Array<{\n listingId: string;\n maxPurchasableQuantity: number | null;\n remainingQuantity: number | null;\n status: LockerverseAvailabilityStatus;\n }>;\n sharedLimits: Array<{\n id: string;\n listingIds: string[];\n remainingQuantity: number;\n status: LockerverseAvailabilityStatus;\n }>;\n};\n\nexport type LockerverseCatalog = {\n availability: LockerverseCatalogAvailability;\n community: LockerverseCommunityBranding | null;\n event: LockerverseEvent | null;\n payment: LockerversePaymentConfiguration;\n pricingPolicy: LockerverseCheckoutPricingPolicy;\n products: LockerverseProduct[];\n widget: LockerverseWidgetConfiguration;\n};\n\nexport type LockerverseEvent = {\n description: string | null;\n endAt: string;\n id: string;\n location: string | null;\n name: string;\n startAt: string;\n status: \"draft\" | \"active\" | \"finished\" | \"cancelled\";\n};\n\nexport type LockerverseCommunityBranding = {\n widgetAchEnabled?: boolean | undefined;\n accentColor: string;\n imageUrl: string | null;\n memberIdLabel?: string | null | undefined;\n name: string;\n};\n\nexport type LockerverseCheckoutPricingPolicy = {\n currency: \"usd\";\n serviceFeeRateBasisPoints: number;\n};\n\nexport type LockerversePaymentConfiguration = {\n connectedAccountId: string | null;\n currency: \"usd\";\n publishableKey: string;\n};\n\nexport type LockerverseWidgetFields = {\n memberId: boolean;\n merchSize: boolean;\n phone: boolean;\n promoCode: boolean;\n serviceFee: boolean;\n shipping: boolean;\n tipping: boolean;\n};\n\nexport type LockerverseCustomFieldOption = { id: string; label: string };\n\ntype LockerverseCustomFieldBase = {\n id: string;\n label: string;\n paymentOptionIds?: string[] | undefined;\n required: boolean;\n};\n\nexport type LockerverseTextCustomField = LockerverseCustomFieldBase & {\n type: \"text\" | \"textarea\";\n};\n\nexport type LockerverseBooleanCustomField = LockerverseCustomFieldBase & {\n type: \"checkbox\";\n};\n\nexport type LockerverseSingleOptionCustomField = LockerverseCustomFieldBase & {\n options: LockerverseCustomFieldOption[];\n type: \"radio\" | \"select\";\n};\n\nexport type LockerverseMultiOptionCustomField = LockerverseCustomFieldBase & {\n options: LockerverseCustomFieldOption[];\n type: \"checkboxes\" | \"multi_select\";\n};\n\nexport type LockerverseCustomField =\n | LockerverseBooleanCustomField\n | LockerverseTextCustomField\n | LockerverseSingleOptionCustomField\n | LockerverseMultiOptionCustomField;\n\nexport type LockerverseCustomFieldAnswerValue<\n Field extends LockerverseCustomField,\n> = Field extends LockerverseBooleanCustomField\n ? boolean\n : Field extends LockerverseMultiOptionCustomField\n ? string[]\n : string;\n\nexport type LockerverseCustomFieldAnswer<\n Field extends LockerverseCustomField = LockerverseCustomField,\n> = Field extends LockerverseCustomField\n ? { fieldId: Field[\"id\"]; value: LockerverseCustomFieldAnswerValue<Field> }\n : never;\n\nexport type LockerverseWidgetConfiguration = {\n customFields: LockerverseCustomField[];\n description: string | null;\n fields: LockerverseWidgetFields;\n id: string;\n name: string;\n showCommunityBranding: boolean;\n title: string | null;\n};\n\nexport type LockerverseSdkErrorCode =\n | \"public_events_load_failed\"\n | \"auction_load_failed\"\n | \"auction_bid_failed\"\n | \"auction_purchase_failed\"\n | \"auction_purchase_status_failed\"\n | \"auction_receipt_failed\"\n | \"widget_load_failed\"\n | \"signup_load_failed\"\n | \"signup_submit_failed\"\n | \"total_calculation_failed\"\n | \"payment_submit_failed\"\n | \"payment_status_failed\"\n | \"invalid_selection\";\n\nexport type LockerverseSdkOperation =\n | \"list_public_events\"\n | \"list_auctions\"\n | \"load_auction\"\n | \"create_auction_bid\"\n | \"create_auction_purchase\"\n | \"get_auction_purchase_receipt\"\n | \"get_auction_purchase_status\"\n | \"load_widget\"\n | \"load_signup\"\n | \"submit_signup\"\n | \"calculate_total\"\n | \"submit_payment\"\n | \"get_payment_status\";\n\nexport type LockerverseSdkServerCode =\n | \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n | \"PAYMENT_WIDGET_PHONE_INVALID\"\n | \"PAYMENT_WIDGET_PHONE_REQUIRED\"\n | \"SIGN_UP_WIDGET_PHONE_INVALID\"\n | \"SIGN_UP_WIDGET_PHONE_REQUIRED\";\n\nexport class LockerverseSdkError extends Error {\n readonly code: LockerverseSdkErrorCode;\n readonly operation: LockerverseSdkOperation;\n readonly reportable: boolean;\n readonly recoveryRecommended: boolean;\n readonly sdkVersion: string;\n readonly serverCode: LockerverseSdkServerCode | undefined;\n readonly status: number | undefined;\n\n constructor({\n code,\n message,\n operation,\n reportable,\n recoveryRecommended = false,\n serverCode,\n status,\n }: {\n code: LockerverseSdkErrorCode;\n message: string;\n operation: LockerverseSdkOperation;\n reportable: boolean;\n recoveryRecommended?: boolean;\n serverCode?: LockerverseSdkServerCode;\n status?: number;\n }) {\n super(message);\n this.name = \"LockerverseSdkError\";\n this.code = code;\n this.operation = operation;\n this.reportable = reportable;\n this.recoveryRecommended = recoveryRecommended;\n this.sdkVersion = LOCKERVERSE_SDK_VERSION;\n this.serverCode = serverCode;\n this.status = status;\n }\n}\n\nexport type LockerverseCheckoutLineItem = {\n productId: string;\n productName: string;\n listingId: string;\n listingSlug: string;\n acceptsDiscounts: boolean;\n eventId: string | null;\n fulfillmentType: LockerverseFulfillmentType;\n pricingMode: \"fixed\" | \"custom\";\n paymentOption: LockerversePaymentOption;\n quantity: number;\n unitAmountCents: number;\n subtotalCents: number;\n};\n\nexport type LockerverseAppliedDiscount = {\n percentageOff: number;\n source: \"email_list\" | \"promo_code\";\n};\n\nexport type LockerverseCheckoutAmounts = {\n amountCents: number;\n discountableSubtotalCents: number;\n discountCents: number;\n serviceFeeCents: number;\n subtotalCents: number;\n tipCents: number;\n totalCents: number;\n};\n\nexport type LockerverseCheckoutQuote = LockerverseCheckoutAmounts & {\n appliedDiscount: LockerverseAppliedDiscount | null;\n authoritative: true;\n paymentReference: string;\n payment: LockerversePaymentConfiguration;\n paymentOption: LockerversePaymentOption;\n lineItems: LockerverseCheckoutLineItem[];\n};\n\nexport type LockerverseCheckoutEstimate = LockerverseCheckoutAmounts & {\n appliedDiscount: null;\n authoritative: false;\n items: readonly LockerverseCheckoutItem[];\n lineItems: readonly LockerverseCheckoutLineItem[];\n paymentOption: LockerversePaymentOption;\n};\n\nexport type LockerverseCheckoutPricingInput = {\n email?: string;\n includeServiceFee?: boolean;\n promoCode?: string;\n tipCents?: number;\n};\n\nexport type LockerversePaymentStatus =\n | \"action_required\"\n | \"failed\"\n | \"pending\"\n | \"success\";\n\nexport type LockerversePaymentResult = {\n checkoutId: string;\n paymentReference: string;\n checkoutStatus: LockerversePaymentStatus;\n retryUrl?: string | undefined;\n clientSecret: string | null;\n paymentRequired: boolean;\n requiresAction: boolean;\n status: string | null;\n};\n\nexport type LockerversePaymentCompletion = LockerversePaymentResult & {\n email: string | null;\n lineItems: readonly LockerverseCheckoutLineItem[] | null;\n};\n\ntype AssertPaymentContract<T extends true> = T;\ntype _PaymentResultMatchesGenerated = AssertPaymentContract<\n LockerversePaymentResult extends GeneratedPaymentResult\n ? GeneratedPaymentResult extends LockerversePaymentResult\n ? true\n : false\n : false\n>;\n\nexport type LockerverseShipping = {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n };\n name: string;\n};\n\nexport type LockerversePaymentSubmission = {\n confirmationToken?: string;\n paymentMethodConfiguration?: \"explicit\";\n customFieldAnswers?: LockerverseCustomFieldAnswer[];\n email: string;\n memberId?: string;\n merchSize?: \"XS\" | \"S\" | \"M\" | \"L\" | \"XL\" | \"XXL\" | \"XXXL\";\n metadata?: Record<string, string>;\n phone?: string;\n shipping?: LockerverseShipping;\n};\n\nexport type LockerverseCheckoutItem =\n | { productId: string; quantity: number }\n | { productId: string; amountCents: number }\n | { productId: string };\n\nexport type LockerverseCheckoutSelectionItem =\n | { productSlug: string; quantity: number }\n | { productSlug: string; amountCents: number }\n | { productSlug: string };\n\nexport type LockerverseEstimateCheckoutInput =\n LockerverseCheckoutPricingInput & {\n selection: LockerverseCheckoutSelectionItem[];\n };\n\nexport type LockerverseLoadCheckoutInput = {\n selection: LockerverseCheckoutSelectionItem[];\n};\n\nexport type LockerverseCalculateTotalInput = LockerverseCheckoutPricingInput & {\n catalog: LockerverseCatalog;\n} & (\n | {\n items: LockerverseCheckoutItem[];\n selection?: never;\n }\n | {\n items?: never;\n selection: LockerverseCheckoutSelectionItem[];\n }\n );\n\nexport type LockerversePreparedCheckout = Readonly<\n LockerverseCheckoutQuote & {\n items: readonly LockerverseCheckoutItem[];\n pricing: Readonly<LockerverseCheckoutPricingInput>;\n }\n>;\n\nexport type LockerverseLoadedCheckout = Readonly<{\n catalog: LockerverseCatalog;\n checkout: LockerversePreparedCheckout;\n}>;\n\nexport type LockerverseSubmitPaymentInput = {\n checkout: LockerversePreparedCheckout;\n submission: LockerversePaymentSubmission;\n};\n\ntype CreateLockerverseWidgetBaseOptions = {\n communitySlug: string;\n fetch?: typeof globalThis.fetch;\n onError?: (error: LockerverseSdkError) => void;\n requestTimeoutMs?: number;\n sentryDsn?: string | null;\n widgetSlug: string;\n};\n\nexport type LockerverseResourceEnvironmentOptions =\n | {\n apiBaseUrl: string;\n environment: LockerverseEnvironment;\n }\n | {\n apiBaseUrl?: undefined;\n environment?: \"production\";\n };\n\nexport type CreateLockerverseWidgetOptions =\n CreateLockerverseWidgetBaseOptions & LockerverseResourceEnvironmentOptions;\n\nexport type LockerverseCheckoutClient = {\n calculateTotal: (\n input: LockerverseCalculateTotalInput\n ) => Promise<LockerversePreparedCheckout>;\n getPaymentStatus: (\n paymentReference: string\n ) => Promise<LockerversePaymentResult>;\n load: {\n (): Promise<LockerverseCatalog>;\n (input: LockerverseLoadCheckoutInput): Promise<LockerverseLoadedCheckout>;\n };\n submitPayment: (\n input: LockerverseSubmitPaymentInput\n ) => Promise<LockerversePaymentResult>;\n};\n"],"mappings":"ACWA,MAAa,EAA0BA,UAoLvC,IAAa,EAAb,cAAyC,KAAM,CAC7C,KACA,UACA,WACA,oBACA,WACA,WACA,OAEA,YAAY,CACV,OACA,UACA,YACA,aACA,sBAAsB,GACtB,aACA,UASC,CACD,MAAM,CAAO,EACb,KAAK,KAAO,sBACZ,KAAK,KAAO,EACZ,KAAK,UAAY,EACjB,KAAK,WAAa,EAClB,KAAK,oBAAsB,EAC3B,KAAK,WAAa,EAClB,KAAK,WAAa,EAClB,KAAK,OAAS,CAChB,CACF"}
|
|
1
|
+
{"version":3,"file":"types.js","names":["packageMetadata.version"],"sources":["../package.json","../src/types.ts"],"sourcesContent":["","import packageMetadata from \"../package.json\" with { type: \"json\" };\nimport type { GeneratedPaymentResult } from \"./generated/public-contract-types.ts\";\n\nexport type LockerversePaymentOption =\n | \"one-time\"\n | \"monthly\"\n | \"annually\"\n | \"every-six-months\";\nexport type LockerverseEnvironment = \"development\" | \"production\";\nexport type LockerverseFulfillmentType = \"none\" | \"event_admission\";\n\nexport const LOCKERVERSE_SDK_VERSION = packageMetadata.version;\n\nexport type LockerverseProduct = {\n id: string;\n listingId: string;\n slug: string;\n name: string;\n description: string | null;\n fulfillmentType: LockerverseFulfillmentType;\n pricingMode: \"fixed\" | \"custom\";\n paymentOption: LockerversePaymentOption;\n amountCents: number | null;\n minimumAmountCents: number | null;\n minimumQuantity: number | null;\n /** Per-order limit for this widget listing. Null means no per-order limit. */\n maximumQuantity: number | null;\n inventoryQuantity: number | null;\n acceptsDiscounts: boolean;\n};\n\nexport type LockerverseAvailabilityStatus = \"available\" | \"sold_out\";\n\nexport type LockerverseCatalogAvailability = {\n listings: Array<{\n listingId: string;\n maxPurchasableQuantity: number | null;\n remainingQuantity: number | null;\n status: LockerverseAvailabilityStatus;\n }>;\n sharedLimits: Array<{\n id: string;\n listingIds: string[];\n remainingQuantity: number;\n status: LockerverseAvailabilityStatus;\n }>;\n};\n\nexport type LockerverseCatalog = {\n availability: LockerverseCatalogAvailability;\n community: LockerverseCommunityBranding | null;\n event: LockerverseEvent | null;\n payment: LockerversePaymentConfiguration;\n pricingPolicy: LockerverseCheckoutPricingPolicy;\n products: LockerverseProduct[];\n widget: LockerverseWidgetConfiguration;\n};\n\nexport type LockerverseEvent = {\n description: string | null;\n endAt: string;\n id: string;\n location: string | null;\n name: string;\n startAt: string;\n status: \"draft\" | \"active\" | \"finished\" | \"cancelled\";\n};\n\nexport type LockerverseCommunityBranding = {\n widgetAchEnabled?: boolean | undefined;\n accentColor: string;\n imageUrl: string | null;\n memberIdLabel?: string | null | undefined;\n name: string;\n};\n\nexport type LockerverseCheckoutPricingPolicy = {\n currency: \"usd\";\n serviceFeeRateBasisPoints: number;\n};\n\nexport type LockerversePaymentConfiguration = {\n connectedAccountId: string | null;\n currency: \"usd\";\n publishableKey: string;\n};\n\nexport type LockerverseWidgetFields = {\n memberId: boolean;\n merchSize: boolean;\n phone: boolean;\n promoCode: boolean;\n serviceFee: boolean;\n shipping: boolean;\n tipping: boolean;\n};\n\nexport type LockerverseCustomFieldOption = { id: string; label: string };\n\ntype LockerverseCustomFieldBase = {\n id: string;\n label: string;\n paymentOptionIds?: string[] | undefined;\n required: boolean;\n};\n\nexport type LockerverseTextCustomField = LockerverseCustomFieldBase & {\n type: \"text\" | \"textarea\";\n};\n\nexport type LockerverseBooleanCustomField = LockerverseCustomFieldBase & {\n type: \"checkbox\";\n};\n\nexport type LockerverseSingleOptionCustomField = LockerverseCustomFieldBase & {\n options: LockerverseCustomFieldOption[];\n type: \"radio\" | \"select\";\n};\n\nexport type LockerverseMultiOptionCustomField = LockerverseCustomFieldBase & {\n options: LockerverseCustomFieldOption[];\n type: \"checkboxes\" | \"multi_select\";\n};\n\nexport type LockerverseCustomField =\n | LockerverseBooleanCustomField\n | LockerverseTextCustomField\n | LockerverseSingleOptionCustomField\n | LockerverseMultiOptionCustomField;\n\nexport type LockerverseCustomFieldAnswerValue<\n Field extends LockerverseCustomField,\n> = Field extends LockerverseBooleanCustomField\n ? boolean\n : Field extends LockerverseMultiOptionCustomField\n ? string[]\n : string;\n\nexport type LockerverseCustomFieldAnswer<\n Field extends LockerverseCustomField = LockerverseCustomField,\n> = Field extends LockerverseCustomField\n ? { fieldId: Field[\"id\"]; value: LockerverseCustomFieldAnswerValue<Field> }\n : never;\n\nexport type LockerverseWidgetConfiguration = {\n liveShipping?: { enabled: boolean; productIds: string[] } | undefined;\n customFields: LockerverseCustomField[];\n description: string | null;\n fields: LockerverseWidgetFields;\n id: string;\n name: string;\n showCommunityBranding: boolean;\n title: string | null;\n};\n\nexport type LockerverseSdkErrorCode =\n | \"public_events_load_failed\"\n | \"auction_load_failed\"\n | \"auction_bid_failed\"\n | \"auction_purchase_failed\"\n | \"auction_purchase_status_failed\"\n | \"auction_receipt_failed\"\n | \"widget_load_failed\"\n | \"signup_load_failed\"\n | \"signup_submit_failed\"\n | \"total_calculation_failed\"\n | \"payment_submit_failed\"\n | \"payment_status_failed\"\n | \"invalid_selection\";\n\nexport type LockerverseSdkOperation =\n | \"list_public_events\"\n | \"list_auctions\"\n | \"load_auction\"\n | \"create_auction_bid\"\n | \"create_auction_purchase\"\n | \"get_auction_purchase_receipt\"\n | \"get_auction_purchase_status\"\n | \"load_widget\"\n | \"load_signup\"\n | \"submit_signup\"\n | \"calculate_total\"\n | \"submit_payment\"\n | \"get_payment_status\";\n\nexport type LockerverseSdkServerCode =\n | \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n | \"PAYMENT_WIDGET_PHONE_INVALID\"\n | \"PAYMENT_WIDGET_PHONE_REQUIRED\"\n | \"SIGN_UP_WIDGET_PHONE_INVALID\"\n | \"SIGN_UP_WIDGET_PHONE_REQUIRED\";\n\nexport class LockerverseSdkError extends Error {\n readonly code: LockerverseSdkErrorCode;\n readonly operation: LockerverseSdkOperation;\n readonly reportable: boolean;\n readonly recoveryRecommended: boolean;\n readonly sdkVersion: string;\n readonly serverCode: LockerverseSdkServerCode | undefined;\n readonly status: number | undefined;\n\n constructor({\n code,\n message,\n operation,\n reportable,\n recoveryRecommended = false,\n serverCode,\n status,\n }: {\n code: LockerverseSdkErrorCode;\n message: string;\n operation: LockerverseSdkOperation;\n reportable: boolean;\n recoveryRecommended?: boolean;\n serverCode?: LockerverseSdkServerCode;\n status?: number;\n }) {\n super(message);\n this.name = \"LockerverseSdkError\";\n this.code = code;\n this.operation = operation;\n this.reportable = reportable;\n this.recoveryRecommended = recoveryRecommended;\n this.sdkVersion = LOCKERVERSE_SDK_VERSION;\n this.serverCode = serverCode;\n this.status = status;\n }\n}\n\nexport type LockerverseCheckoutLineItem = {\n productId: string;\n productName: string;\n listingId: string;\n listingSlug: string;\n acceptsDiscounts: boolean;\n eventId: string | null;\n fulfillmentType: LockerverseFulfillmentType;\n pricingMode: \"fixed\" | \"custom\";\n paymentOption: LockerversePaymentOption;\n quantity: number;\n unitAmountCents: number;\n subtotalCents: number;\n};\n\nexport type LockerverseAppliedDiscount = {\n percentageOff: number;\n source: \"email_list\" | \"promo_code\";\n};\n\nexport type LockerverseCheckoutAmounts = {\n amountCents: number;\n discountableSubtotalCents: number;\n discountCents: number;\n serviceFeeCents: number;\n subtotalCents: number;\n tipCents: number;\n totalCents: number;\n};\n\nexport type LockerverseCheckoutQuote = LockerverseCheckoutAmounts & {\n shippingRequired?: boolean | undefined;\n shippingCents?: number | undefined;\n shippingQuote?:\n | {\n token: string;\n amountCents: number;\n carrier: string;\n service: string;\n estimatedDays: number | null;\n expiresAt: string;\n }\n | null\n | undefined;\n appliedDiscount: LockerverseAppliedDiscount | null;\n authoritative: true;\n paymentReference: string;\n payment: LockerversePaymentConfiguration;\n paymentOption: LockerversePaymentOption;\n lineItems: LockerverseCheckoutLineItem[];\n};\n\nexport type LockerverseCheckoutEstimate = LockerverseCheckoutAmounts & {\n appliedDiscount: null;\n authoritative: false;\n items: readonly LockerverseCheckoutItem[];\n lineItems: readonly LockerverseCheckoutLineItem[];\n paymentOption: LockerversePaymentOption;\n};\n\nexport type LockerverseCheckoutPricingInput = {\n shipping?: LockerverseShipping;\n shippingQuoteToken?: string;\n email?: string;\n includeServiceFee?: boolean;\n promoCode?: string;\n tipCents?: number;\n};\n\nexport type LockerversePaymentStatus =\n | \"action_required\"\n | \"failed\"\n | \"pending\"\n | \"success\";\n\nexport type LockerversePaymentResult = {\n checkoutId: string;\n paymentReference: string;\n checkoutStatus: LockerversePaymentStatus;\n retryUrl?: string | undefined;\n clientSecret: string | null;\n paymentRequired: boolean;\n requiresAction: boolean;\n status: string | null;\n};\n\nexport type LockerversePaymentCompletion = LockerversePaymentResult & {\n email: string | null;\n lineItems: readonly LockerverseCheckoutLineItem[] | null;\n};\n\ntype AssertPaymentContract<T extends true> = T;\ntype _PaymentResultMatchesGenerated = AssertPaymentContract<\n LockerversePaymentResult extends GeneratedPaymentResult\n ? GeneratedPaymentResult extends LockerversePaymentResult\n ? true\n : false\n : false\n>;\n\nexport type LockerverseShipping = {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string | undefined;\n postal_code: string;\n state: string;\n };\n name: string;\n};\n\nexport type LockerversePaymentSubmission = {\n confirmationToken?: string;\n paymentMethodConfiguration?: \"explicit\";\n customFieldAnswers?: LockerverseCustomFieldAnswer[];\n email: string;\n memberId?: string;\n merchSize?: \"XS\" | \"S\" | \"M\" | \"L\" | \"XL\" | \"XXL\" | \"XXXL\";\n metadata?: Record<string, string>;\n phone?: string;\n shipping?: LockerverseShipping;\n};\n\nexport type LockerverseCheckoutItem =\n | { productId: string; quantity: number }\n | { productId: string; amountCents: number }\n | { productId: string };\n\nexport type LockerverseCheckoutSelectionItem =\n | { productSlug: string; quantity: number }\n | { productSlug: string; amountCents: number }\n | { productSlug: string };\n\nexport type LockerverseEstimateCheckoutInput =\n LockerverseCheckoutPricingInput & {\n selection: LockerverseCheckoutSelectionItem[];\n };\n\nexport type LockerverseLoadCheckoutInput = {\n selection: LockerverseCheckoutSelectionItem[];\n};\n\nexport type LockerverseCalculateTotalInput = LockerverseCheckoutPricingInput & {\n catalog: LockerverseCatalog;\n} & (\n | {\n items: LockerverseCheckoutItem[];\n selection?: never;\n }\n | {\n items?: never;\n selection: LockerverseCheckoutSelectionItem[];\n }\n );\n\nexport type LockerversePreparedCheckout = Readonly<\n LockerverseCheckoutQuote & {\n items: readonly LockerverseCheckoutItem[];\n pricing: Readonly<LockerverseCheckoutPricingInput>;\n }\n>;\n\nexport type LockerverseLoadedCheckout = Readonly<{\n catalog: LockerverseCatalog;\n checkout: LockerversePreparedCheckout;\n}>;\n\nexport type LockerverseSubmitPaymentInput = {\n checkout: LockerversePreparedCheckout;\n submission: LockerversePaymentSubmission;\n};\n\ntype CreateLockerverseWidgetBaseOptions = {\n communitySlug: string;\n fetch?: typeof globalThis.fetch;\n onError?: (error: LockerverseSdkError) => void;\n requestTimeoutMs?: number;\n sentryDsn?: string | null;\n widgetSlug: string;\n};\n\nexport type LockerverseResourceEnvironmentOptions =\n | {\n apiBaseUrl: string;\n environment: LockerverseEnvironment;\n }\n | {\n apiBaseUrl?: undefined;\n environment?: \"production\";\n };\n\nexport type CreateLockerverseWidgetOptions =\n CreateLockerverseWidgetBaseOptions & LockerverseResourceEnvironmentOptions;\n\nexport type LockerverseCheckoutClient = {\n calculateTotal: (\n input: LockerverseCalculateTotalInput\n ) => Promise<LockerversePreparedCheckout>;\n getPaymentStatus: (\n paymentReference: string\n ) => Promise<LockerversePaymentResult>;\n load: {\n (): Promise<LockerverseCatalog>;\n (input: LockerverseLoadCheckoutInput): Promise<LockerverseLoadedCheckout>;\n };\n submitPayment: (\n input: LockerverseSubmitPaymentInput\n ) => Promise<LockerversePaymentResult>;\n};\n"],"mappings":"ACWA,MAAa,EAA0BA,gBAqLvC,IAAa,EAAb,cAAyC,KAAM,CAC7C,KACA,UACA,WACA,oBACA,WACA,WACA,OAEA,YAAY,CACV,OACA,UACA,YACA,aACA,sBAAsB,GACtB,aACA,UASC,CACD,MAAM,CAAO,EACb,KAAK,KAAO,sBACZ,KAAK,KAAO,EACZ,KAAK,UAAY,EACjB,KAAK,WAAa,EAClB,KAAK,oBAAsB,EAC3B,KAAK,WAAa,EAClB,KAAK,WAAa,EAClB,KAAK,OAAS,CAChB,CACF"}
|