@lockerverse/sdk 0.1.0-alpha.2 → 0.1.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -0
- package/dist/checkout.d.ts.map +1 -1
- package/dist/checkout.js +1 -1
- package/dist/checkout.js.map +1 -1
- package/dist/signup.d.ts +8 -2
- package/dist/signup.d.ts.map +1 -1
- package/dist/signup.js +1 -1
- package/dist/signup.js.map +1 -1
- package/dist/transport.js +1 -1
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -92,6 +92,24 @@ const checkout = createLockerverseCheckout({
|
|
|
92
92
|
});
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
+
Every SDK HTTP operation has a 20-second deadline by default. Hosts can choose a
|
|
96
|
+
different positive whole-number deadline in milliseconds, up to
|
|
97
|
+
`2_147_483_647`, with `requestTimeoutMs` on either checkout or signup. The
|
|
98
|
+
deadline includes receiving and validating the complete JSON response body:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const checkout = createLockerverseCheckout({
|
|
102
|
+
communitySlug: "auburn",
|
|
103
|
+
requestTimeoutMs: 10_000,
|
|
104
|
+
widgetSlug: "auburn-tailgate-party",
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
A timeout only means the browser stopped waiting; it does not prove that a
|
|
109
|
+
payment mutation failed on Lockerverse's server. After an ambiguous payment
|
|
110
|
+
confirmation, read `recoverablePaymentReference` from the `error` state and
|
|
111
|
+
pass it to `getPaymentStatus()`.
|
|
112
|
+
|
|
95
113
|
`widget.customFields` is a discriminated union covering `text`, `textarea`,
|
|
96
114
|
`select`, `multi_select`, `radio`, and `checkboxes`. Archived fields and options
|
|
97
115
|
are omitted. Hosts own rendering and client-side required-field feedback:
|
|
@@ -132,6 +150,20 @@ const submission = await signup.submit({
|
|
|
132
150
|
});
|
|
133
151
|
```
|
|
134
152
|
|
|
153
|
+
The same ambiguity applies when a signup submission times out. Read
|
|
154
|
+
`recoverableSubmissionReference` from the `error` state and retry the same
|
|
155
|
+
values with that reference so Lockerverse can return the original submission
|
|
156
|
+
instead of creating a duplicate:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const state = signup.getState();
|
|
160
|
+
if (state.phase === "error" && state.recoverableSubmissionReference) {
|
|
161
|
+
await signup.submit(values, {
|
|
162
|
+
submissionReference: state.recoverableSubmissionReference,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
135
167
|
`subscribe()` observes `idle`, `loading`, `ready`, `submitting`, `submitted`,
|
|
136
168
|
and `error`. Definitions and submission results are immutable snapshots.
|
|
137
169
|
Lockerverse validates enabled and required built-in fields, custom-field
|
|
@@ -166,6 +198,10 @@ create a live charge.
|
|
|
166
198
|
structurally validated before it enters SDK state or is returned to the host.
|
|
167
199
|
A successful HTTP status alone is insufficient; invalid JSON or response
|
|
168
200
|
shapes become sanitized, reportable `LockerverseSdkError` failures.
|
|
201
|
+
- Public workflow input is validated before it reaches transport. Private
|
|
202
|
+
Valibot schemas own these runtime boundaries and infer their internal types;
|
|
203
|
+
schema implementation details and validation payloads do not escape through
|
|
204
|
+
the public API.
|
|
169
205
|
- Expected selection errors are marked `reportable: false`.
|
|
170
206
|
- Unexpected network/server failures are marked `reportable: true`.
|
|
171
207
|
- Reportable failures are sent directly to Sentry with only allowlisted SDK and
|
package/dist/checkout.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout.d.ts","names":[],"sources":["../src/checkout.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"checkout.d.ts","names":[],"sources":["../src/checkout.ts"],"mappings":";;iBAmCgB,0BACd,SAAS,iCACR"}
|
package/dist/checkout.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"./transport.js";import{n as p,t as m}from"./types.js";const h={development:`pk_test_51O7FkjDHAhgRuLtFHdkXdIe8T5i7rOVaG9PCtDetK3UUVKojVUEKHmQacGzigf9mOX1wz3zSOKoYwFjRcTfML9PU00OjJko2lk`,production:`pk_live_51O7FkjDHAhgRuLtFlzLdxJrwo7F09WCKTlzT9lnBePjOGizWnuijkH9oCkoAddkmBT8ngIuqAPkDiHlPEAH4KXbz00Tm0DaPT4`};function g(e){let t=c(e,`widgetSlug`);return{...t,stripePublishableKey:h[t.environment],widgetSlug:t.resourceSlug,widgetSlugValue:t.resourceSlugValue}}function _(e,t){if(!Number.isSafeInteger(e)||e<t)throw TypeError(`Expected a safe integer.`);return e}function v(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<t||e>n)throw TypeError(`Expected a bounded finite number.`);return e}function y(e,t){return e===null?null:_(e,t)}function b(e){if(e===`one-time`||e===`monthly`||e===`annually`)return e;throw TypeError(`Expected a supported payment option.`)}function x(e){if(e===`fixed`||e===`custom`)return e;throw TypeError(`Expected a supported pricing mode.`)}function S(e){if(e===`action_required`||e===`failed`||e===`pending`||e===`success`)return e;throw TypeError(`Expected a supported payment status.`)}function C(e){if(e===null)return null;let t=f(e);if(t.source!==`email_list`&&t.source!==`promo_code`)throw TypeError(`Expected a supported discount source.`);let n=t.source;return{percentageOff:v(t.percentageOff,0,100),source:n}}function w(e){let t=e===void 0?{}:f(e);return{memberId:u(t.memberId,!1),merchSize:u(t.merchSize,!1),phone:u(t.phone,!1),promoCode:u(t.promoCode,!1),serviceFee:u(t.serviceFee,!1),shipping:u(t.shipping,!1),tipping:u(t.tipping,!1)}}function T(n){let r=f(n);return{amountCents:y(r.amountCents,0),description:t(r.description,null),id:e(r.id),inventoryQuantity:y(r.inventoryQuantity,0),maxQuantity:y(r.maxQuantity,0),minimumAmountCents:y(r.minimumAmountCents,0),minQuantity:y(r.minQuantity,0),name:e(r.name),paymentOption:b(r.paymentOption),pricingMode:x(r.pricingMode)}}function E(t){let n=f(t);return{acceptsDiscounts:u(n.acceptsDiscounts,!1),id:e(n.id),product:T(n.product),productId:e(n.productId),slug:e(n.slug)}}function D(e){let n=f(e),r=n.config===void 0?{}:f(n.config),o=n.pricingPolicy===void 0?{currency:`usd`,serviceFeeRateBasisPoints:0}:f(n.pricingPolicy),s=n.products===void 0?[]:n.products;if(!Array.isArray(s))throw TypeError(`Expected a Product array.`);if(o.currency!==`usd`)throw TypeError(`Expected USD checkout pricing policy.`);return{config:{customFields:i(r.customFields),fields:w(r.fields)},description:t(n.description,null),id:a(n.id,``),name:a(n.name,`Lockerverse widget`),pricingPolicy:{currency:`usd`,serviceFeeRateBasisPoints:_(o.serviceFeeRateBasisPoints,0)},products:s.map(E),showCommunityBranding:u(n.showCommunityBranding,!0),title:t(n.title,null)}}function O(t){let n=f(t);return{acceptsDiscounts:l(n.acceptsDiscounts),listingId:e(n.listingId),listingSlug:e(n.listingSlug),paymentOption:b(n.paymentOption),pricingMode:x(n.pricingMode),productId:e(n.productId),productName:e(n.productName),quantity:_(n.quantity,1),subtotalCents:_(n.subtotalCents,0),unitAmountCents:_(n.unitAmountCents,0)}}function k(t){let n=f(t);if(!Array.isArray(n.lineItems))throw TypeError(`Expected a line item array.`);return{amountCents:_(n.amountCents,0),appliedDiscount:C(n.appliedDiscount),connectedAccountId:n.connectedAccountId===null?null:e(n.connectedAccountId),discountableSubtotalCents:_(n.discountableSubtotalCents,0),discountCents:_(n.discountCents,0),lineItems:n.lineItems.map(O),paymentOption:b(n.paymentOption),serviceFeeCents:_(n.serviceFeeCents,0),subtotalCents:_(n.subtotalCents,0),tipCents:_(n.tipCents,0),totalCents:_(n.totalCents,0)}}function A(t){let n=f(t);return{checkoutId:e(n.checkoutId),checkoutStatus:S(n.checkoutStatus),clientSecret:s(n.clientSecret),paymentReference:e(n.paymentReference),requiresAction:l(n.requiresAction),status:s(n.status)}}const j=1e4;function M(e,t){if(!Number.isSafeInteger(e)||e<0)throw TypeError(t);return e}function N(e,t){return M(e+t,`The selected checkout total is too large.`)}function P(e,t){return M(e*t,`The selected Product quantity produces an unsafe total.`)}function F(e,t){let n=(BigInt(e)*BigInt(t)+BigInt(j/2))/BigInt(j);if(n>BigInt(2**53-1))throw TypeError(`The selected checkout total is too large.`);return Number(n)}function I(e,t,n){let r=0,i=0;for(let n of t.items){let t=e.products.find(({id:e,slug:t})=>e===n.productId&&t===n.productSlug);if(!t)throw TypeError(`The selected Product is no longer available.`);if(t.paymentOption!==`one-time`)throw TypeError(`Recurring Products are not supported by this SDK checkout yet.`);let a=`quantity`in n?P(t.amountCents??0,n.quantity):n.amountCents;r=N(r,a),t.acceptsDiscounts&&(i=N(i,a))}let a=n.includeServiceFee?F(r,e.pricingPolicy.serviceFeeRateBasisPoints):0,o=n.tipCents??0,s=N(r,a);return{amountCents:s,appliedDiscount:null,authoritative:!1,discountableSubtotalCents:i,discountCents:0,serviceFeeCents:a,subtotalCents:r,tipCents:o,totalCents:N(s,o)}}function L(e){let{product:t}=e;return{acceptsDiscounts:e.acceptsDiscounts??!1,amountCents:t.amountCents,description:t.description??null,id:t.id,inventoryQuantity:t.inventoryQuantity,listingId:e.id,maximumQuantity:t.maxQuantity,minimumAmountCents:t.minimumAmountCents,minimumQuantity:t.minQuantity,name:t.name,paymentOption:t.paymentOption,pricingMode:t.pricingMode,slug:e.slug}}function R(e,t){let n=e.config?.fields??{};return{payment:{currency:`usd`,publishableKey:t},pricingPolicy:{currency:`usd`,serviceFeeRateBasisPoints:e.pricingPolicy?.serviceFeeRateBasisPoints??0},products:(e.products??[]).map(L),widget:{customFields:e.config?.customFields??[],description:e.description??null,fields:{memberId:n.memberId??!1,merchSize:n.merchSize??!1,phone:n.phone??!1,promoCode:n.promoCode??!1,serviceFee:n.serviceFee??!1,shipping:n.shipping??!1,tipping:n.tipping??!1},id:e.id??``,name:e.name??`Lockerverse widget`,showCommunityBranding:e.showCommunityBranding??!0,title:e.title??null}}}function z(e){return r({payment:{...e.payment},pricingPolicy:{...e.pricingPolicy},products:e.products.map(e=>({...e})),widget:{...e.widget,customFields:e.widget.customFields.map(e=>`options`in e?{...e,options:e.options.map(e=>({...e}))}:{...e}),fields:{...e.widget.fields}}})}function B(e){return r({...e,appliedDiscount:e.appliedDiscount?{...e.appliedDiscount}:null,lineItems:e.lineItems.map(e=>({...e})),payment:{...e.payment}})}function V(e){return r({...e})}function H(e){let{apiBaseUrl:t,communitySlug:i,communitySlugValue:a,environment:s,fetchImplementation:c,onError:l,sentryDsn:u,stripePublishableKey:f,widgetSlug:m,widgetSlugValue:h}=g(e),_=null,v=null,y=null,b=null,x=null,S=0,C=0,w=!1,T=new Map,E=o({phase:`idle`,selection:r({items:[]})});function O(e){let t=_,n=t?t.products.find(({slug:t})=>t===e):void 0;if(!n)throw Error(`Lockerverse Product "${e}" is unavailable.`);return n}let j=n({communitySlug:a,environment:s,getContext:()=>({paymentReference:b,widgetSlug:h}),onError:l,resourceContextName:`lockerverse_widget`,sentryDsn:u});function M(e,t=`update_selection`){throw j(new p({code:`invalid_selection`,message:e,operation:t,reportable:!1}))}let{fetchResponse:N,parseResponseJson:P}=d(c,j);function F(){let e=_;return r({items:(e?e.products:[]).flatMap(e=>{let t=T.get(e.slug);return t?[{productId:e.id,productSlug:e.slug,...t}]:[]})})}function L(){v=null,y=null,b=null,x=null}function H(){w&&M(`Selection cannot change while a payment is being submitted.`)}function U(e){w&&M(`This operation cannot run while a payment is being submitted.`,e)}function W(){C+=1,L()}function G(e=null){_&&E.commit({catalog:_,phase:`ready`,preview:e,selection:F()})}function K(e,t=null){E.commit({catalog:_,error:e,phase:`error`,recoverablePaymentReference:t,selection:F()})}function q(e,t){if(e!==C||t!==S)throw j(new p({code:`total_calculation_failed`,message:`This Lockerverse checkout total was superseded. Calculate the total again for the current selection.`,operation:`calculate_total`,reportable:!1}))}function J(e={}){if(U(`calculate_total`),!_)throw Error(`Load the Lockerverse widget before previewing the total.`);T.size===0&&M(`Select at least one Product before previewing.`);let t=Y(_,e);W();try{let e=r(I(_,F(),t));return x=e,G(e),e}catch(e){M(e instanceof Error?e.message:`Unable to preview checkout.`)}}function Y(e,t){X(e,t);let n=t.tipCents??0,r=t.email?.trim().toLowerCase(),i=t.promoCode?.trim();return{...r?{email:r}:{},...t.includeServiceFee===void 0?{}:{includeServiceFee:t.includeServiceFee},...i?{promoCode:i}:{},...t.tipCents===void 0?{}:{tipCents:n}}}function X(e,t){let n=t.tipCents??0;(!Number.isSafeInteger(n)||n<0)&&M(`Tip must be a non-negative whole number of cents.`),t.includeServiceFee&&!e.widget.fields.serviceFee&&M(`Service fee is not enabled for this widget.`),t.includeServiceFee&&e.pricingPolicy.serviceFeeRateBasisPoints===0&&M(`Service fee pricing is unavailable. Reload the widget and try again.`),n>0&&!e.widget.fields.tipping&&M(`Tipping is not enabled for this widget.`)}async function Z(e={}){if(U(`calculate_total`),!_)throw Error(`Load the Lockerverse widget before calculating the total.`);let n=Y(_,e);T.size===0&&M(`Select at least one Product before calculating the total.`,`calculate_total`);let a=F(),o=r(I(_,a,n));x=o,E.commit({catalog:_,phase:`quoting`,preview:o,selection:a});let s=a.items.map(({productSlug:e,...t})=>t),c=C,l=S+1;S=l,v=null,b=null;let u;try{u=await N(`${t}/v2/community/${i}/payment-widgets/${m}/checkout/quote`,{body:JSON.stringify({...n,items:s}),headers:{"Content-Type":`application/json`},method:`POST`},{code:`total_calculation_failed`,message:`Unable to calculate the Lockerverse checkout total because the request failed.`,operation:`calculate_total`,report:!1})}catch(e){throw q(c,l),e instanceof p?(K(e),j(e)):e}if(q(c,l),!u.ok){let e=new p({code:`total_calculation_failed`,message:`Unable to calculate the Lockerverse checkout total (${u.status}).`,operation:`calculate_total`,reportable:u.status>=500,status:u.status});throw K(e),j(e)}let d;try{if(d=await P(u,k,{code:`total_calculation_failed`,message:`Lockerverse returned an invalid checkout total.`,operation:`calculate_total`,report:!1}),d.paymentOption!==`one-time`)throw new p({code:`total_calculation_failed`,message:`Lockerverse returned an unsupported checkout cadence.`,operation:`calculate_total`,reportable:!0})}catch(e){throw q(c,l),e instanceof p?(K(e),j(e)):e}q(c,l);let f=globalThis.crypto.randomUUID(),{connectedAccountId:h,paymentOption:g,...w}=d,D=r({...w,authoritative:!0,payment:{..._.payment,connectedAccountId:h},paymentOption:`one-time`,paymentReference:f});return v=D,y=r({...n}),b=f,E.commit({catalog:_,phase:`quoted`,preview:o,quote:D,selection:a}),B(D)}return{calculateTotal:Z,clear(){H(),T.clear(),W(),G()},async getPaymentStatus(e=b??``){U(`get_payment_status`),e||M(`Provide a payment reference to recover its status.`,`get_payment_status`),b=e;let n=F();E.commit({catalog:_,paymentReference:e,phase:`recovering`,selection:n});try{let r=await N(`${t}/v2/community/${i}/payment-widgets/${m}/checkout/${encodeURIComponent(e)}/status`,void 0,{code:`payment_status_failed`,message:`Unable to recover the Lockerverse payment status because the request failed.`,operation:`get_payment_status`});if(!r.ok)throw j(new p({code:`payment_status_failed`,message:`Unable to recover the Lockerverse payment status (${r.status}).`,operation:`get_payment_status`,reportable:r.status>=500,status:r.status}));let a=V(await P(r,A,{code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`}));return E.commit({catalog:_,payment:a,phase:`payment`,quote:v?.paymentReference===e?v:null,selection:n}),V(a)}catch(t){throw t instanceof p&&K(t,e),t}},getSelection:F,getState:E.getState,async load(){U(`load_widget`),W(),E.commit({phase:`loading`,selection:F()});let e={code:`widget_load_failed`,message:`Unable to load Lockerverse widget because the request failed.`,operation:`load_widget`,report:!1},n;try{n=await N(`${t}/v2/community/${i}/payment-widgets/${m}`,void 0,e)}catch(e){throw e instanceof p?(K(e),j(e)):e}if(!n.ok){let e=new p({code:`widget_load_failed`,message:`Unable to load Lockerverse widget (${n.status}).`,operation:`load_widget`,reportable:n.status>=500,status:n.status});throw K(e),j(e)}let a=await P(n,D,{code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`});return T.clear(),_=r(R(a,f)),G(),z(_)},previewTotal:J,remove(e){H(),T.delete(e),W(),G()},setAmount(e,t){H();let n=O(e);n.pricingMode!==`custom`&&M(`Fixed-price Products do not accept custom amounts.`),(!Number.isSafeInteger(t)||t<=0)&&M(`Product amount must be a positive integer in cents.`),n.minimumAmountCents!==null&&t<n.minimumAmountCents&&M(`Product amount must be at least ${n.minimumAmountCents} cents.`),T.set(e,{amountCents:t}),W(),G()},setQuantity(e,t){H();let n=O(e);n.pricingMode!==`fixed`&&M(`Custom-amount Products do not accept quantities.`),(!Number.isSafeInteger(t)||t<=0)&&M(`Product quantity must be a positive integer.`),n.minimumQuantity!==null&&t<n.minimumQuantity&&M(`Product quantity must be at least ${n.minimumQuantity}.`),n.maximumQuantity!==null&&t>n.maximumQuantity&&M(`Product quantity must not exceed ${n.maximumQuantity}.`),n.inventoryQuantity!==null&&t>n.inventoryQuantity&&M(`Requested Product quantity is unavailable.`),T.set(e,{quantity:t}),W(),G()},async submitPayment(e){_&&v&&y||M(`Calculate the current total before submitting a payment.`,`submit_payment`),w&&M(`A Lockerverse payment is already being submitted.`,`submit_payment`);let n=_,r=v,a=y,o=F(),s=x??I(n,o,a),c=e.email.trim().toLowerCase();(!c||c!==a.email)&&M(`Payment email must match the current checkout quote.`,`submit_payment`);let l=o.items.map(({productSlug:e,...t})=>t);w=!0,E.commit({catalog:n,phase:`submitting`,preview:s,quote:r,selection:o});try{let s=await N(`${t}/v2/community/${i}/payment-widgets/${m}/checkout/confirm`,{body:JSON.stringify({confirmationToken:e.confirmationToken,customFieldAnswers:e.customFieldAnswers,email:c,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,...a,items:l,memberId:e.memberId,merchSize:e.merchSize,metadata:e.metadata,paymentReference:r.paymentReference,phone:e.phone,quoteContractVersion:1}),headers:{"Content-Type":`application/json`},method:`POST`},{code:`payment_submit_failed`,message:`Unable to submit the Lockerverse payment because the request failed.`,operation:`submit_payment`});if(!s.ok)throw j(new p({code:`payment_submit_failed`,message:`Unable to submit the Lockerverse payment (${s.status}).`,operation:`submit_payment`,reportable:s.status>=500,status:s.status}));let u=V(await P(s,A,{code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`}));return E.commit({catalog:n,payment:u,phase:`payment`,quote:r,selection:o}),V(u)}catch(e){throw e instanceof p&&K(e,r.paymentReference),e}finally{w=!1}},subscribe:E.subscribe}}export{m as LOCKERVERSE_SDK_VERSION,p as LockerverseSdkError,H as createLockerverseCheckout};
|
|
1
|
+
import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,_ as s,a as c,b as l,c as u,f as d,h as f,i as p,j as m,k as h,l as g,m as _,n as v,o as y,p as b,r as x,s as S,t as C,u as w,v as T,w as E,x as D,y as O}from"./transport.js";import{n as k,t as A}from"./types.js";const j={development:`pk_test_51O7FkjDHAhgRuLtFHdkXdIe8T5i7rOVaG9PCtDetK3UUVKojVUEKHmQacGzigf9mOX1wz3zSOKoYwFjRcTfML9PU00OjJko2lk`,production:`pk_live_51O7FkjDHAhgRuLtFlzLdxJrwo7F09WCKTlzT9lnBePjOGizWnuijkH9oCkoAddkmBT8ngIuqAPkDiHlPEAH4KXbz00Tm0DaPT4`};function M(e){let t=w(e,`widgetSlug`);return{...t,stripePublishableKey:j[t.environment],widgetSlug:t.resourceSlug,widgetSlugValue:t.resourceSlugValue}}const N=E(t(i({email:t(h()),includeServiceFee:t(b()),promoCode:t(h()),tipCents:t(g(0))}),{})),P=E(i({confirmationToken:S,customFieldAnswers:t(d(c)),email:h(),memberId:t(h()),merchSize:t(o([`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`])),metadata:t(n(h(),h())),phone:t(h())})),F=o([`one-time`,`monthly`,`annually`]),I=l(g(0)),L={description:u,id:S,inventoryQuantity:I,maxQuantity:I,minimumAmountCents:I,minQuantity:I,name:S,paymentOption:F},R=r(m(`pricingMode`,[a({...L,amountCents:g(0),pricingMode:s(`fixed`)}),a({...L,amountCents:I,pricingMode:s(`custom`)})]),_(({maxQuantity:e,minQuantity:t})=>e===null||t===null||t<=e)),z=a({acceptsDiscounts:t(b(),!1),id:S,product:R,productId:S,slug:S}),B=t(a({memberId:t(b(),!1),merchSize:t(b(),!1),phone:t(b(),!1),promoCode:t(b(),!1),serviceFee:t(b(),!1),shipping:t(b(),!1),tipping:t(b(),!1)}),{}),V=r(a({config:t(a({customFields:y,fields:B})),description:u,id:t(h(),``),name:t(h(),`Lockerverse widget`),pricingPolicy:t(a({currency:t(s(`usd`),`usd`),serviceFeeRateBasisPoints:t(g(0),0)})),products:t(d(z),[]),showCommunityBranding:t(b(),!0),title:u}),e(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}}))),H=l(a({percentageOff:r(D(),f(),O(0),T(100)),source:o([`email_list`,`promo_code`])})),U=a({acceptsDiscounts:b(),listingId:S,listingSlug:S,paymentOption:F,pricingMode:o([`fixed`,`custom`]),productId:S,productName:S,quantity:g(1),subtotalCents:g(0),unitAmountCents:g(0)}),W=a({amountCents:g(0),appliedDiscount:H,connectedAccountId:l(S),discountableSubtotalCents:g(0),discountCents:g(0),lineItems:d(U),paymentOption:F,serviceFeeCents:g(0),subtotalCents:g(0),tipCents:g(0),totalCents:g(0)}),G=a({checkoutId:S,checkoutStatus:o([`action_required`,`failed`,`pending`,`success`]),clientSecret:l(h()),paymentReference:S,requiresAction:b(),status:l(h())}),K=E(W),q=E(G),ee=E(V),J=1e4;function Y(e,t){if(!Number.isSafeInteger(e)||e<0)throw TypeError(t);return e}function X(e,t){return Y(e+t,`The selected checkout total is too large.`)}function te(e,t){return Y(e*t,`The selected Product quantity produces an unsafe total.`)}function ne(e,t){let n=(BigInt(e)*BigInt(t)+BigInt(J/2))/BigInt(J);if(n>BigInt(2**53-1))throw TypeError(`The selected checkout total is too large.`);return Number(n)}function Z(e,t,n){let r=0,i=0;for(let n of t.items){let t=e.products.find(({id:e,slug:t})=>e===n.productId&&t===n.productSlug);if(!t)throw TypeError(`The selected Product is no longer available.`);if(t.paymentOption!==`one-time`)throw TypeError(`Recurring Products are not supported by this SDK checkout yet.`);let a=`quantity`in n?te(t.amountCents??0,n.quantity):n.amountCents;r=X(r,a),t.acceptsDiscounts&&(i=X(i,a))}let a=n.includeServiceFee?ne(r,e.pricingPolicy.serviceFeeRateBasisPoints):0,o=n.tipCents??0,s=X(r,a);return{amountCents:s,appliedDiscount:null,authoritative:!1,discountableSubtotalCents:i,discountCents:0,serviceFeeCents:a,subtotalCents:r,tipCents:o,totalCents:X(s,o)}}function re(e){let{product:t}=e;return{acceptsDiscounts:e.acceptsDiscounts??!1,amountCents:t.amountCents,description:t.description??null,id:t.id,inventoryQuantity:t.inventoryQuantity,listingId:e.id,maximumQuantity:t.maxQuantity,minimumAmountCents:t.minimumAmountCents,minimumQuantity:t.minQuantity,name:t.name,paymentOption:t.paymentOption,pricingMode:t.pricingMode,slug:e.slug}}function ie(e,t){let n=e.config?.fields??{};return{payment:{currency:`usd`,publishableKey:t},pricingPolicy:{currency:`usd`,serviceFeeRateBasisPoints:e.pricingPolicy?.serviceFeeRateBasisPoints??0},products:(e.products??[]).map(re),widget:{customFields:e.config?.customFields??[],description:e.description??null,fields:{memberId:n.memberId??!1,merchSize:n.merchSize??!1,phone:n.phone??!1,promoCode:n.promoCode??!1,serviceFee:n.serviceFee??!1,shipping:n.shipping??!1,tipping:n.tipping??!1},id:e.id??``,name:e.name??`Lockerverse widget`,showCommunityBranding:e.showCommunityBranding??!0,title:e.title??null}}}function ae(e){return $(e)}function oe(e){return $(e)}function Q(e){return $(e)}function $(e){return p(structuredClone(e))}function se(e){let{apiBaseUrl:t,communitySlug:n,communitySlugValue:r,environment:i,fetchImplementation:a,onError:o,requestTimeoutMs:s,sentryDsn:c,stripePublishableKey:l,widgetSlug:u,widgetSlugValue:d}=M(e),f=null,m=null,h=null,g=null,_=null,y=0,b=0,S=!1,w=new Map,T=v({phase:`idle`,selection:p({items:[]})});function E(e){let t=f,n=t?t.products.find(({slug:t})=>t===e):void 0;if(!n)throw Error(`Lockerverse Product "${e}" is unavailable.`);return n}let D=x({communitySlug:r,environment:i,getContext:()=>({paymentReference:g,widgetSlug:d}),onError:o,resourceContextName:`lockerverse_widget`,sentryDsn:c});function O(e,t=`update_selection`){throw D(new k({code:`invalid_selection`,message:e,operation:t,reportable:!1}))}let{requestJson:A}=C(a,D,s);function j(){let e=f;return p({items:(e?e.products:[]).flatMap(e=>{let t=w.get(e.slug);return t?[{productId:e.id,productSlug:e.slug,...t}]:[]})})}function F(){m=null,h=null,g=null,_=null}function I(){S&&O(`Selection cannot change while a payment is being submitted.`)}function L(e){S&&O(`This operation cannot run while a payment is being submitted.`,e)}function R(){b+=1,F()}function z(e=null){f&&T.commit({catalog:f,phase:`ready`,preview:e,selection:j()})}function B(e,t=null){T.commit({catalog:f,error:e,phase:`error`,recoverablePaymentReference:t,selection:j()})}function V(e,t){return e instanceof k?e:new k({...t,reportable:!0})}function H(){return y+=1,y}function U(e,t,n=!0){if(e===y)return;let r=new k({...t,reportable:!1});throw n?D(r):r}function W(e,t){if(e!==b||t!==y)throw D(new k({code:`total_calculation_failed`,message:`This Lockerverse checkout total was superseded. Calculate the total again for the current selection.`,operation:`calculate_total`,reportable:!1}))}function G(e={}){if(L(`calculate_total`),!f)throw Error(`Load the Lockerverse widget before previewing the total.`);w.size===0&&O(`Select at least one Product before previewing.`);let t=J(f,e);R();try{let e=p(Z(f,j(),t));return _=e,z(e),e}catch(e){O(e instanceof Error?e.message:`Unable to preview checkout.`)}}function J(e,t){let n;try{n=N(t)}catch{O(`Checkout pricing input is invalid.`)}Y(e,n);let r=n.tipCents??0,i=n.email?.trim().toLowerCase(),a=n.promoCode?.trim();return{...i?{email:i}:{},...n.includeServiceFee===void 0?{}:{includeServiceFee:n.includeServiceFee},...a?{promoCode:a}:{},...n.tipCents===void 0?{}:{tipCents:r}}}function Y(e,t){let n=t.tipCents??0;(!Number.isSafeInteger(n)||n<0)&&O(`Tip must be a non-negative whole number of cents.`),t.includeServiceFee&&!e.widget.fields.serviceFee&&O(`Service fee is not enabled for this widget.`),t.includeServiceFee&&e.pricingPolicy.serviceFeeRateBasisPoints===0&&O(`Service fee pricing is unavailable. Reload the widget and try again.`),n>0&&!e.widget.fields.tipping&&O(`Tipping is not enabled for this widget.`)}async function X(e={}){if(L(`calculate_total`),!f)throw Error(`Load the Lockerverse widget before calculating the total.`);let r=J(f,e);w.size===0&&O(`Select at least one Product before calculating the total.`,`calculate_total`);let i=j(),a=H(),o=p(Z(f,i,r));_=o,T.commit({catalog:f,phase:`quoting`,preview:o,selection:i});let s=i.items.map(({productSlug:e,...t})=>t),c=b;m=null,g=null;let l=A(`${t}/v2/community/${n}/payment-widgets/${u}/checkout/quote`,{body:JSON.stringify({...r,items:s}),headers:{"Content-Type":`application/json`},method:`POST`},K,{code:`total_calculation_failed`,message:`Unable to calculate the Lockerverse checkout total because the request failed.`,operation:`calculate_total`,report:!1},{code:`total_calculation_failed`,message:`Lockerverse returned an invalid checkout total.`,operation:`calculate_total`,report:!1}),d;try{d=await l}catch(e){throw W(c,a),e instanceof k?(B(e),D(e)):e}if(W(c,a),!d.ok){let e=new k({code:`total_calculation_failed`,message:`Unable to calculate the Lockerverse checkout total (${d.response.status}).`,operation:`calculate_total`,reportable:d.response.status>=500,status:d.response.status});throw B(e),D(e)}let v;try{if(v=d.value,v.paymentOption!==`one-time`)throw new k({code:`total_calculation_failed`,message:`Lockerverse returned an unsupported checkout cadence.`,operation:`calculate_total`,reportable:!0})}catch(e){throw W(c,a),e instanceof k?(B(e),D(e)):e}W(c,a);let y=globalThis.crypto.randomUUID(),{connectedAccountId:x,paymentOption:S,...C}=v,E=p({...C,authoritative:!0,payment:{...f.payment,connectedAccountId:x},paymentOption:`one-time`,paymentReference:y});return m=E,h=p({...r}),g=y,T.commit({catalog:f,phase:`quoted`,preview:o,quote:E,selection:i}),oe(E)}return{calculateTotal:X,clear(){I(),w.clear(),R(),z()},async getPaymentStatus(e=g??``){L(`get_payment_status`),e||O(`Provide a payment reference to recover its status.`,`get_payment_status`);let r=H(),i={code:`payment_status_failed`,message:`This Lockerverse payment status request was superseded.`,operation:`get_payment_status`};g=e;let a=j();T.commit({catalog:f,paymentReference:e,phase:`recovering`,selection:a});try{let o=await A(`${t}/v2/community/${n}/payment-widgets/${u}/checkout/${encodeURIComponent(e)}/status`,void 0,q,{code:`payment_status_failed`,message:`Unable to recover the Lockerverse payment status because the request failed.`,operation:`get_payment_status`,report:!1},{code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`,report:!1});if(U(r,i,!1),!o.ok)throw new k({code:`payment_status_failed`,message:`Unable to recover the Lockerverse payment status (${o.response.status}).`,operation:`get_payment_status`,reportable:o.response.status>=500,status:o.response.status});let s=Q(o.value);if(U(r,i,!1),s.paymentReference!==e)throw new k({code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`,reportable:!0});return T.commit({catalog:f,payment:s,phase:`payment`,quote:m?.paymentReference===e?m:null,selection:a}),Q(s)}catch(t){U(r,i);let n=V(t,{code:`payment_status_failed`,message:`Lockerverse returned an invalid payment status.`,operation:`get_payment_status`});throw B(n,e),D(n)}},getSelection:j,getState:T.getState,async load(){L(`load_widget`);let e=H(),r={code:`widget_load_failed`,message:`This Lockerverse widget load was superseded.`,operation:`load_widget`};R(),T.commit({phase:`loading`,selection:j()});let i={code:`widget_load_failed`,message:`Unable to load Lockerverse widget because the request failed.`,operation:`load_widget`,report:!1};try{let a=await A(`${t}/v2/community/${n}/payment-widgets/${u}`,void 0,ee,i,{code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`,report:!1});if(U(e,r,!1),!a.ok)throw new k({code:`widget_load_failed`,message:`Unable to load Lockerverse widget (${a.response.status}).`,operation:`load_widget`,reportable:a.response.status>=500,status:a.response.status});let o=a.value;U(e,r,!1);let s=p(ie(o,l)),c=ae(s);return w.clear(),f=s,z(),c}catch(t){U(e,r);let n=V(t,{code:`widget_load_failed`,message:`Lockerverse returned an invalid widget catalog.`,operation:`load_widget`});throw B(n),D(n)}},previewTotal:G,remove(e){I(),w.delete(e),R(),z()},setAmount(e,t){I();let n=E(e);n.pricingMode!==`custom`&&O(`Fixed-price Products do not accept custom amounts.`),(!Number.isSafeInteger(t)||t<=0)&&O(`Product amount must be a positive integer in cents.`),n.minimumAmountCents!==null&&t<n.minimumAmountCents&&O(`Product amount must be at least ${n.minimumAmountCents} cents.`),w.set(e,{amountCents:t}),R(),z()},setQuantity(e,t){I();let n=E(e);n.pricingMode!==`fixed`&&O(`Custom-amount Products do not accept quantities.`),(!Number.isSafeInteger(t)||t<=0)&&O(`Product quantity must be a positive integer.`),n.minimumQuantity!==null&&t<n.minimumQuantity&&O(`Product quantity must be at least ${n.minimumQuantity}.`),n.maximumQuantity!==null&&t>n.maximumQuantity&&O(`Product quantity must not exceed ${n.maximumQuantity}.`),n.inventoryQuantity!==null&&t>n.inventoryQuantity&&O(`Requested Product quantity is unavailable.`),w.set(e,{quantity:t}),R(),z()},async submitPayment(e){f&&m&&h||O(`Calculate the current total before submitting a payment.`,`submit_payment`),S&&O(`A Lockerverse payment is already being submitted.`,`submit_payment`);let r=f,i=m,a=h,o=j(),s=_??Z(r,o,a),c;try{c=P(e)}catch{let e=new k({code:`payment_submit_failed`,message:`Lockerverse payment submission is invalid.`,operation:`submit_payment`,reportable:!0});throw B(e,i.paymentReference),D(e)}let l=c.email.trim().toLowerCase();(!l||l!==a.email)&&O(`Payment email must match the current checkout quote.`,`submit_payment`);let d=o.items.map(({productSlug:e,...t})=>t);H(),S=!0,T.commit({catalog:r,phase:`submitting`,preview:s,quote:i,selection:o});try{let e=await A(`${t}/v2/community/${n}/payment-widgets/${u}/checkout/confirm`,{body:JSON.stringify({confirmationToken:c.confirmationToken,customFieldAnswers:c.customFieldAnswers,email:l,expectedAmountCents:i.amountCents,expectedAppliedDiscount:i.appliedDiscount,expectedConnectedAccountId:i.payment.connectedAccountId,expectedDiscountableSubtotalCents:i.discountableSubtotalCents,expectedDiscountCents:i.discountCents,expectedServiceFeeCents:i.serviceFeeCents,expectedSubtotalCents:i.subtotalCents,expectedTipCents:i.tipCents,expectedTotalCents:i.totalCents,...a,items:d,memberId:c.memberId,merchSize:c.merchSize,metadata:c.metadata,paymentReference:i.paymentReference,phone:c.phone,quoteContractVersion:1}),headers:{"Content-Type":`application/json`},method:`POST`},q,{code:`payment_submit_failed`,message:`Unable to submit the Lockerverse payment because the request failed.`,operation:`submit_payment`,report:!1},{code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`,report:!1});if(!e.ok)throw new k({code:`payment_submit_failed`,message:`Unable to submit the Lockerverse payment (${e.response.status}).`,operation:`submit_payment`,reportable:e.response.status>=500,status:e.response.status});let s=Q(e.value);if(s.paymentReference!==i.paymentReference)throw new k({code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`,reportable:!0});return T.commit({catalog:r,payment:s,phase:`payment`,quote:i,selection:o}),Q(s)}catch(e){let t=V(e,{code:`payment_submit_failed`,message:`Lockerverse returned an invalid payment confirmation.`,operation:`submit_payment`});throw B(t,i.paymentReference),D(t)}finally{S=!1}},subscribe:T.subscribe}}export{A as LOCKERVERSE_SDK_VERSION,k as LockerverseSdkError,se as createLockerverseCheckout};
|
|
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/parsers.ts","../src/pricing.ts","../src/snapshots.ts","../src/checkout.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type {\n CreateLockerverseWidgetOptions,\n LockerverseEnvironment,\n} from \"./types.ts\";\n\nconst STRIPE_PUBLISHABLE_KEYS: Record<LockerverseEnvironment, string> = {\n development:\n \"pk_test_51O7FkjDHAhgRuLtFHdkXdIe8T5i7rOVaG9PCtDetK3UUVKojVUEKHmQacGzigf9mOX1wz3zSOKoYwFjRcTfML9PU00OjJko2lk\",\n production:\n \"pk_live_51O7FkjDHAhgRuLtFlzLdxJrwo7F09WCKTlzT9lnBePjOGizWnuijkH9oCkoAddkmBT8ngIuqAPkDiHlPEAH4KXbz00Tm0DaPT4\",\n};\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n stripePublishableKey: STRIPE_PUBLISHABLE_KEYS[runtime.environment],\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import type {\n PublicCheckoutQuote,\n PublicProduct,\n PublicProductListing,\n PublicWidget,\n} from \"./contracts.ts\";\nimport {\n parseBoolean,\n parseCustomFields,\n parseNonEmptyString,\n parseNullableString,\n parseOptionalBoolean,\n parseOptionalNullableString,\n parseOptionalString,\n parseRecord,\n} from \"./parsing.ts\";\nimport type {\n LockerverseAppliedDiscount,\n LockerverseCheckoutLineItem,\n LockerversePaymentOption,\n LockerversePaymentResult,\n LockerversePaymentStatus,\n LockerverseWidgetFields,\n} from \"./types.ts\";\n\nfunction parseSafeInteger(value: unknown, minimum: number): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum) {\n throw new TypeError(\"Expected a safe integer.\");\n }\n\n return value as number;\n}\n\nfunction parseFiniteNumber(\n value: unknown,\n minimum: number,\n maximum: number\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < minimum ||\n value > maximum\n ) {\n throw new TypeError(\"Expected a bounded finite number.\");\n }\n return value;\n}\n\nfunction parseNullableSafeInteger(\n value: unknown,\n minimum: number\n): number | null {\n return value === null ? null : parseSafeInteger(value, minimum);\n}\n\nfunction parsePaymentOption(value: unknown): LockerversePaymentOption {\n if (value === \"one-time\" || value === \"monthly\" || value === \"annually\") {\n return value;\n }\n\n throw new TypeError(\"Expected a supported payment option.\");\n}\n\nfunction parsePricingMode(value: unknown): \"fixed\" | \"custom\" {\n if (value === \"fixed\" || value === \"custom\") {\n return value;\n }\n\n throw new TypeError(\"Expected a supported pricing mode.\");\n}\n\nfunction parsePaymentStatus(value: unknown): LockerversePaymentStatus {\n if (\n value === \"action_required\" ||\n value === \"failed\" ||\n value === \"pending\" ||\n value === \"success\"\n ) {\n return value;\n }\n\n throw new TypeError(\"Expected a supported payment status.\");\n}\n\nfunction parseAppliedDiscount(\n value: unknown\n): LockerverseAppliedDiscount | null {\n if (value === null) {\n return null;\n }\n const discount = parseRecord(value);\n if (discount.source !== \"email_list\" && discount.source !== \"promo_code\") {\n throw new TypeError(\"Expected a supported discount source.\");\n }\n const source = discount.source as LockerverseAppliedDiscount[\"source\"];\n return {\n percentageOff: parseFiniteNumber(discount.percentageOff, 0, 100),\n source,\n };\n}\n\nfunction parseWidgetFields(value: unknown): LockerverseWidgetFields {\n const fields = value === undefined ? {} : parseRecord(value);\n\n return {\n memberId: parseOptionalBoolean(fields.memberId, false),\n merchSize: parseOptionalBoolean(fields.merchSize, false),\n phone: parseOptionalBoolean(fields.phone, false),\n promoCode: parseOptionalBoolean(fields.promoCode, false),\n serviceFee: parseOptionalBoolean(fields.serviceFee, false),\n shipping: parseOptionalBoolean(fields.shipping, false),\n tipping: parseOptionalBoolean(fields.tipping, false),\n };\n}\n\nfunction parsePublicProduct(value: unknown): PublicProduct {\n const product = parseRecord(value);\n\n return {\n amountCents: parseNullableSafeInteger(product.amountCents, 0),\n description: parseOptionalNullableString(product.description, null),\n id: parseNonEmptyString(product.id),\n inventoryQuantity: parseNullableSafeInteger(product.inventoryQuantity, 0),\n maxQuantity: parseNullableSafeInteger(product.maxQuantity, 0),\n minimumAmountCents: parseNullableSafeInteger(product.minimumAmountCents, 0),\n minQuantity: parseNullableSafeInteger(product.minQuantity, 0),\n name: parseNonEmptyString(product.name),\n paymentOption: parsePaymentOption(product.paymentOption),\n pricingMode: parsePricingMode(product.pricingMode),\n };\n}\n\nfunction parseProductListing(value: unknown): PublicProductListing {\n const listing = parseRecord(value);\n\n return {\n acceptsDiscounts: parseOptionalBoolean(listing.acceptsDiscounts, false),\n id: parseNonEmptyString(listing.id),\n product: parsePublicProduct(listing.product),\n productId: parseNonEmptyString(listing.productId),\n slug: parseNonEmptyString(listing.slug),\n };\n}\n\nexport function parsePublicWidget(value: unknown): PublicWidget {\n const widget = parseRecord(value);\n const config = widget.config === undefined ? {} : parseRecord(widget.config);\n const pricingPolicy =\n widget.pricingPolicy === undefined\n ? { currency: \"usd\", serviceFeeRateBasisPoints: 0 }\n : parseRecord(widget.pricingPolicy);\n const products = widget.products === undefined ? [] : widget.products;\n if (!Array.isArray(products)) {\n throw new TypeError(\"Expected a Product array.\");\n }\n if (pricingPolicy.currency !== \"usd\") {\n throw new TypeError(\"Expected USD checkout pricing policy.\");\n }\n\n return {\n config: {\n customFields: parseCustomFields(config.customFields),\n fields: parseWidgetFields(config.fields),\n },\n description: parseOptionalNullableString(widget.description, null),\n id: parseOptionalString(widget.id, \"\"),\n name: parseOptionalString(widget.name, \"Lockerverse widget\"),\n pricingPolicy: {\n currency: \"usd\",\n serviceFeeRateBasisPoints: parseSafeInteger(\n pricingPolicy.serviceFeeRateBasisPoints,\n 0\n ),\n },\n products: products.map(parseProductListing),\n showCommunityBranding: parseOptionalBoolean(\n widget.showCommunityBranding,\n true\n ),\n title: parseOptionalNullableString(widget.title, null),\n };\n}\n\nfunction parseCheckoutLineItem(value: unknown): LockerverseCheckoutLineItem {\n const lineItem = parseRecord(value);\n\n return {\n acceptsDiscounts: parseBoolean(lineItem.acceptsDiscounts),\n listingId: parseNonEmptyString(lineItem.listingId),\n listingSlug: parseNonEmptyString(lineItem.listingSlug),\n paymentOption: parsePaymentOption(lineItem.paymentOption),\n pricingMode: parsePricingMode(lineItem.pricingMode),\n productId: parseNonEmptyString(lineItem.productId),\n productName: parseNonEmptyString(lineItem.productName),\n quantity: parseSafeInteger(lineItem.quantity, 1),\n subtotalCents: parseSafeInteger(lineItem.subtotalCents, 0),\n unitAmountCents: parseSafeInteger(lineItem.unitAmountCents, 0),\n };\n}\n\nexport function parseCheckoutQuote(value: unknown): PublicCheckoutQuote {\n const quote = parseRecord(value);\n if (!Array.isArray(quote.lineItems)) {\n throw new TypeError(\"Expected a line item array.\");\n }\n\n return {\n amountCents: parseSafeInteger(quote.amountCents, 0),\n appliedDiscount: parseAppliedDiscount(quote.appliedDiscount),\n connectedAccountId:\n quote.connectedAccountId === null\n ? null\n : parseNonEmptyString(quote.connectedAccountId),\n discountableSubtotalCents: parseSafeInteger(\n quote.discountableSubtotalCents,\n 0\n ),\n discountCents: parseSafeInteger(quote.discountCents, 0),\n lineItems: quote.lineItems.map(parseCheckoutLineItem),\n paymentOption: parsePaymentOption(quote.paymentOption),\n serviceFeeCents: parseSafeInteger(quote.serviceFeeCents, 0),\n subtotalCents: parseSafeInteger(quote.subtotalCents, 0),\n tipCents: parseSafeInteger(quote.tipCents, 0),\n totalCents: parseSafeInteger(quote.totalCents, 0),\n };\n}\n\nexport function parsePaymentResult(value: unknown): LockerversePaymentResult {\n const paymentResult = parseRecord(value);\n\n return {\n checkoutId: parseNonEmptyString(paymentResult.checkoutId),\n checkoutStatus: parsePaymentStatus(paymentResult.checkoutStatus),\n clientSecret: parseNullableString(paymentResult.clientSecret),\n paymentReference: parseNonEmptyString(paymentResult.paymentReference),\n requiresAction: parseBoolean(paymentResult.requiresAction),\n status: parseNullableString(paymentResult.status),\n };\n}\n","import type {\n LockerverseCatalog,\n LockerverseCheckoutPreview,\n LockerverseCheckoutPricingInput,\n LockerverseSelection,\n} from \"./types.ts\";\n\nconst BASIS_POINTS_PER_WHOLE = 10_000;\n\nfunction assertSafeCents(value: number, message: string) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(message);\n }\n return value;\n}\n\nfunction addCents(left: number, right: number) {\n return assertSafeCents(\n left + right,\n \"The selected checkout total is too large.\"\n );\n}\n\nfunction multiplyCents(value: number, quantity: number) {\n return assertSafeCents(\n value * quantity,\n \"The selected Product quantity produces an unsafe total.\"\n );\n}\n\nfunction calculateBasisPoints(value: number, basisPoints: number) {\n const rounded =\n (BigInt(value) * BigInt(basisPoints) + BigInt(BASIS_POINTS_PER_WHOLE / 2)) /\n BigInt(BASIS_POINTS_PER_WHOLE);\n if (rounded > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new TypeError(\"The selected checkout total is too large.\");\n }\n return Number(rounded);\n}\n\nexport function calculateCheckoutPreview(\n catalog: LockerverseCatalog,\n selection: LockerverseSelection,\n input: LockerverseCheckoutPricingInput\n): LockerverseCheckoutPreview {\n let subtotalCents = 0;\n let discountableSubtotalCents = 0;\n\n for (const item of selection.items) {\n const product = catalog.products.find(\n ({ id, slug }) => id === item.productId && slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"The selected Product is no longer available.\");\n }\n if (product.paymentOption !== \"one-time\") {\n throw new TypeError(\n \"Recurring Products are not supported by this SDK checkout yet.\"\n );\n }\n const itemSubtotal =\n \"quantity\" in item\n ? multiplyCents(product.amountCents ?? 0, item.quantity)\n : item.amountCents;\n subtotalCents = addCents(subtotalCents, itemSubtotal);\n if (product.acceptsDiscounts) {\n discountableSubtotalCents = addCents(\n discountableSubtotalCents,\n itemSubtotal\n );\n }\n }\n\n const serviceFeeCents = input.includeServiceFee\n ? calculateBasisPoints(\n subtotalCents,\n catalog.pricingPolicy.serviceFeeRateBasisPoints\n )\n : 0;\n const tipCents = input.tipCents ?? 0;\n const amountCents = addCents(subtotalCents, serviceFeeCents);\n\n return {\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents: addCents(amountCents, tipCents),\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./contracts.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutTotal,\n LockerversePaymentResult,\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 id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: product.maxQuantity,\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\nexport function createCatalog(\n widget: PublicWidget,\n publishableKey: string\n): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n payment: {\n currency: \"usd\",\n 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 deepFreeze({\n payment: { ...catalog.payment },\n pricingPolicy: { ...catalog.pricingPolicy },\n products: catalog.products.map((product) => ({ ...product })),\n widget: {\n ...catalog.widget,\n customFields: catalog.widget.customFields.map((field) =>\n \"options\" in field\n ? {\n ...field,\n options: field.options.map((option) => ({ ...option })),\n }\n : { ...field }\n ),\n fields: { ...catalog.widget.fields },\n },\n });\n}\n\nexport function cloneCheckoutTotal(\n total: LockerverseCheckoutTotal\n): LockerverseCheckoutTotal {\n return deepFreeze({\n ...total,\n appliedDiscount: total.appliedDiscount\n ? { ...total.appliedDiscount }\n : null,\n lineItems: total.lineItems.map((lineItem) => ({ ...lineItem })),\n payment: { ...total.payment },\n });\n}\n\nexport function clonePaymentResult(\n paymentResult: LockerversePaymentResult\n): LockerversePaymentResult {\n return deepFreeze({ ...paymentResult });\n}\n","import { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport type { PublicCheckoutQuote } from \"./contracts.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidget,\n} from \"./parsers.ts\";\nimport { calculateCheckoutPreview } from \"./pricing.ts\";\nimport {\n cloneCatalog,\n cloneCheckoutTotal,\n clonePaymentResult,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createStateStore } from \"./state.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCatalog,\n type LockerverseCheckoutPreview,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutTotal,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSelection,\n type LockerverseWidget,\n type LockerverseWidgetState,\n} from \"./types.ts\";\n\nexport function createLockerverseCheckout(\n options: CreateLockerverseWidgetOptions\n): LockerverseWidget {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n sentryDsn,\n stripePublishableKey,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n let catalog: LockerverseCatalog | null = null;\n let calculatedTotal: LockerverseCheckoutTotal | null = null;\n let calculatedPricingInput: LockerverseCheckoutPricingInput | null = null;\n let latestPaymentReference: string | null = null;\n let latestPreview: LockerverseCheckoutPreview | null = null;\n let quoteGeneration = 0;\n let stateRevision = 0;\n let submitting = false;\n const selection = new Map<\n string,\n { amountCents: number } | { quantity: number }\n >();\n const stateStore = createStateStore<LockerverseWidgetState>({\n phase: \"idle\",\n selection: deepFreeze({ items: [] }),\n });\n\n function getProduct(productSlug: string) {\n const currentCatalog = catalog;\n const product = currentCatalog\n ? currentCatalog.products.find(({ slug }) => slug === productSlug)\n : undefined;\n\n if (!product) {\n throw new Error(`Lockerverse Product \"${productSlug}\" is unavailable.`);\n }\n\n return product;\n }\n\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({\n paymentReference: latestPaymentReference,\n widgetSlug: widgetSlugValue,\n }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n\n function invalidSelection(\n message: string,\n operation: LockerverseSdkOperation = \"update_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code: \"invalid_selection\",\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n const { fetchResponse, parseResponseJson } = createTransport(\n fetchImplementation,\n reportError\n );\n\n function getSelection(): LockerverseSelection {\n const currentCatalog = catalog;\n return deepFreeze({\n items: (currentCatalog ? currentCatalog.products : []).flatMap(\n (product) => {\n const selected = selection.get(product.slug);\n return selected\n ? [\n {\n productId: product.id,\n productSlug: product.slug,\n ...selected,\n },\n ]\n : [];\n }\n ),\n });\n }\n\n function invalidateCalculatedTotal() {\n calculatedTotal = null;\n calculatedPricingInput = null;\n latestPaymentReference = null;\n latestPreview = null;\n }\n\n function ensureSelectionMutable() {\n if (submitting) {\n invalidSelection(\n \"Selection cannot change while a payment is being submitted.\"\n );\n }\n }\n\n function ensureOperationAvailable(operation: LockerverseSdkOperation) {\n if (submitting) {\n invalidSelection(\n \"This operation cannot run while a payment is being submitted.\",\n operation\n );\n }\n }\n\n function reviseState() {\n stateRevision += 1;\n invalidateCalculatedTotal();\n }\n\n function commitReady(preview: LockerverseCheckoutPreview | null = null) {\n if (!catalog) {\n return;\n }\n stateStore.commit({\n catalog,\n phase: \"ready\",\n preview,\n selection: getSelection(),\n });\n }\n\n function commitError(\n error: LockerverseSdkError,\n recoverablePaymentReference: string | null = null\n ) {\n stateStore.commit({\n catalog,\n error,\n phase: \"error\",\n recoverablePaymentReference,\n selection: getSelection(),\n });\n }\n\n function rejectSupersededQuote(\n requestedStateRevision: number,\n requestedQuoteGeneration: number\n ) {\n if (\n requestedStateRevision === stateRevision &&\n requestedQuoteGeneration === quoteGeneration\n ) {\n return;\n }\n\n throw reportError(\n new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message:\n \"This Lockerverse checkout total was superseded. Calculate the total again for the current selection.\",\n operation: \"calculate_total\",\n reportable: false,\n })\n );\n }\n\n function previewTotal(input: LockerverseCheckoutPricingInput = {}) {\n ensureOperationAvailable(\"calculate_total\");\n if (!catalog) {\n throw new Error(\n \"Load the Lockerverse widget before previewing the total.\"\n );\n }\n if (selection.size === 0) {\n invalidSelection(\"Select at least one Product before previewing.\");\n }\n const normalizedInput = normalizePricingInput(catalog, input);\n reviseState();\n\n try {\n const preview = deepFreeze(\n calculateCheckoutPreview(catalog, getSelection(), normalizedInput)\n );\n latestPreview = preview;\n commitReady(preview);\n return preview;\n } catch (error) {\n invalidSelection(\n error instanceof Error ? error.message : \"Unable to preview checkout.\"\n );\n }\n }\n\n function normalizePricingInput(\n currentCatalog: LockerverseCatalog,\n input: LockerverseCheckoutPricingInput\n ): LockerverseCheckoutPricingInput {\n validatePricingInput(currentCatalog, input);\n const tipCents = input.tipCents ?? 0;\n const email = input.email?.trim().toLowerCase();\n const promoCode = input.promoCode?.trim();\n return {\n ...(email ? { email } : {}),\n ...(input.includeServiceFee === undefined\n ? {}\n : { includeServiceFee: input.includeServiceFee }),\n ...(promoCode ? { promoCode } : {}),\n ...(input.tipCents === undefined ? {} : { tipCents }),\n };\n }\n\n function validatePricingInput(\n currentCatalog: LockerverseCatalog,\n input: LockerverseCheckoutPricingInput\n ) {\n const tipCents = input.tipCents ?? 0;\n if (!Number.isSafeInteger(tipCents) || tipCents < 0) {\n invalidSelection(\"Tip must be a non-negative whole number of cents.\");\n }\n if (input.includeServiceFee && !currentCatalog.widget.fields.serviceFee) {\n invalidSelection(\"Service fee is not enabled for this widget.\");\n }\n if (\n input.includeServiceFee &&\n currentCatalog.pricingPolicy.serviceFeeRateBasisPoints === 0\n ) {\n invalidSelection(\n \"Service fee pricing is unavailable. Reload the widget and try again.\"\n );\n }\n if (tipCents > 0 && !currentCatalog.widget.fields.tipping) {\n invalidSelection(\"Tipping is not enabled for this widget.\");\n }\n }\n\n async function calculateTotal(input: LockerverseCheckoutPricingInput = {}) {\n ensureOperationAvailable(\"calculate_total\");\n if (!catalog) {\n throw new Error(\n \"Load the Lockerverse widget before calculating the total.\"\n );\n }\n\n const normalizedInput = normalizePricingInput(catalog, input);\n if (selection.size === 0) {\n invalidSelection(\n \"Select at least one Product before calculating the total.\",\n \"calculate_total\"\n );\n }\n const currentSelection = getSelection();\n const preview = deepFreeze(\n calculateCheckoutPreview(catalog, currentSelection, normalizedInput)\n );\n latestPreview = preview;\n stateStore.commit({\n catalog,\n phase: \"quoting\",\n preview,\n selection: currentSelection,\n });\n const items = currentSelection.items.map(\n ({ productSlug: _productSlug, ...item }) => item\n );\n const requestedStateRevision = stateRevision;\n const requestedQuoteGeneration = quoteGeneration + 1;\n quoteGeneration = requestedQuoteGeneration;\n calculatedTotal = null;\n latestPaymentReference = null;\n let response: Response;\n\n try {\n response = await fetchResponse(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/quote`,\n {\n body: JSON.stringify({ ...normalizedInput, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n {\n code: \"total_calculation_failed\",\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n operation: \"calculate_total\",\n report: false,\n }\n );\n } catch (error) {\n rejectSupersededQuote(requestedStateRevision, requestedQuoteGeneration);\n if (error instanceof LockerverseSdkError) {\n commitError(error);\n throw reportError(error);\n }\n throw error;\n }\n\n rejectSupersededQuote(requestedStateRevision, requestedQuoteGeneration);\n\n if (!response.ok) {\n const error = new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: `Unable to calculate the Lockerverse checkout total (${response.status}).`,\n operation: \"calculate_total\",\n reportable: response.status >= 500,\n status: response.status,\n });\n commitError(error);\n throw reportError(error);\n }\n\n let serverTotal: PublicCheckoutQuote;\n try {\n serverTotal = await parseResponseJson(response, parseCheckoutQuote, {\n code: \"total_calculation_failed\",\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\",\n report: false,\n });\n if (serverTotal.paymentOption !== \"one-time\") {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"Lockerverse returned an unsupported checkout cadence.\",\n operation: \"calculate_total\",\n reportable: true,\n });\n }\n } catch (error) {\n rejectSupersededQuote(requestedStateRevision, requestedQuoteGeneration);\n if (error instanceof LockerverseSdkError) {\n commitError(error);\n throw reportError(error);\n }\n throw error;\n }\n rejectSupersededQuote(requestedStateRevision, requestedQuoteGeneration);\n const paymentReference = globalThis.crypto.randomUUID();\n const {\n connectedAccountId,\n paymentOption: _paymentOption,\n ...total\n } = serverTotal;\n const nextCalculatedTotal = deepFreeze({\n ...total,\n authoritative: true as const,\n payment: {\n ...catalog.payment,\n connectedAccountId,\n },\n paymentOption: \"one-time\" as const,\n paymentReference,\n });\n calculatedTotal = nextCalculatedTotal;\n calculatedPricingInput = deepFreeze({ ...normalizedInput });\n latestPaymentReference = paymentReference;\n stateStore.commit({\n catalog,\n phase: \"quoted\",\n preview,\n quote: nextCalculatedTotal,\n selection: currentSelection,\n });\n return cloneCheckoutTotal(nextCalculatedTotal);\n }\n\n return {\n calculateTotal,\n clear() {\n ensureSelectionMutable();\n selection.clear();\n reviseState();\n commitReady();\n },\n async getPaymentStatus(paymentReference = latestPaymentReference ?? \"\") {\n ensureOperationAvailable(\"get_payment_status\");\n if (!paymentReference) {\n invalidSelection(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n latestPaymentReference = paymentReference;\n const currentSelection = getSelection();\n stateStore.commit({\n catalog,\n paymentReference,\n phase: \"recovering\",\n selection: currentSelection,\n });\n try {\n const response = await fetchResponse(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/${encodeURIComponent(paymentReference)}/status`,\n undefined,\n {\n code: \"payment_status_failed\",\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n operation: \"get_payment_status\",\n }\n );\n\n if (!response.ok) {\n throw reportError(\n new LockerverseSdkError({\n code: \"payment_status_failed\",\n message: `Unable to recover the Lockerverse payment status (${response.status}).`,\n operation: \"get_payment_status\",\n reportable: response.status >= 500,\n status: response.status,\n })\n );\n }\n\n const payment = clonePaymentResult(\n await parseResponseJson(response, parsePaymentResult, {\n code: \"payment_status_failed\",\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\",\n })\n );\n stateStore.commit({\n catalog,\n payment,\n phase: \"payment\",\n quote:\n calculatedTotal?.paymentReference === paymentReference\n ? calculatedTotal\n : null,\n selection: currentSelection,\n });\n return clonePaymentResult(payment);\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n commitError(error, paymentReference);\n }\n throw error;\n }\n },\n getSelection,\n getState: stateStore.getState,\n async load() {\n ensureOperationAvailable(\"load_widget\");\n reviseState();\n stateStore.commit({ phase: \"loading\", selection: getSelection() });\n const requestContext = {\n code: \"widget_load_failed\" as const,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n operation: \"load_widget\" as const,\n report: false,\n };\n let widgetResponse: Response;\n\n try {\n widgetResponse = await fetchResponse(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`,\n undefined,\n requestContext\n );\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n commitError(error);\n throw reportError(error);\n }\n throw error;\n }\n\n if (!widgetResponse.ok) {\n const error = new LockerverseSdkError({\n code: \"widget_load_failed\",\n message: `Unable to load Lockerverse widget (${widgetResponse.status}).`,\n operation: \"load_widget\",\n reportable: widgetResponse.status >= 500,\n status: widgetResponse.status,\n });\n commitError(error);\n throw reportError(error);\n }\n\n const widget = await parseResponseJson(\n widgetResponse,\n parsePublicWidget,\n {\n code: \"widget_load_failed\",\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\",\n }\n );\n\n selection.clear();\n catalog = deepFreeze(createCatalog(widget, stripePublishableKey));\n commitReady();\n\n return cloneCatalog(catalog);\n },\n previewTotal,\n remove(productSlug) {\n ensureSelectionMutable();\n selection.delete(productSlug);\n reviseState();\n commitReady();\n },\n setAmount(productSlug, amountCents) {\n ensureSelectionMutable();\n const product = getProduct(productSlug);\n\n if (product.pricingMode !== \"custom\") {\n invalidSelection(\"Fixed-price Products do not accept custom amounts.\");\n }\n if (!Number.isSafeInteger(amountCents) || amountCents <= 0) {\n invalidSelection(\"Product amount must be a positive integer in cents.\");\n }\n if (\n product.minimumAmountCents !== null &&\n amountCents < product.minimumAmountCents\n ) {\n invalidSelection(\n `Product amount must be at least ${product.minimumAmountCents} cents.`\n );\n }\n\n selection.set(productSlug, { amountCents });\n reviseState();\n commitReady();\n },\n setQuantity(productSlug, quantity) {\n ensureSelectionMutable();\n const product = getProduct(productSlug);\n\n if (product.pricingMode !== \"fixed\") {\n invalidSelection(\"Custom-amount Products do not accept quantities.\");\n }\n if (!Number.isSafeInteger(quantity) || quantity <= 0) {\n invalidSelection(\"Product quantity must be a positive integer.\");\n }\n if (\n product.minimumQuantity !== null &&\n quantity < product.minimumQuantity\n ) {\n invalidSelection(\n `Product quantity must be at least ${product.minimumQuantity}.`\n );\n }\n if (\n product.maximumQuantity !== null &&\n quantity > product.maximumQuantity\n ) {\n invalidSelection(\n `Product quantity must not exceed ${product.maximumQuantity}.`\n );\n }\n if (\n product.inventoryQuantity !== null &&\n quantity > product.inventoryQuantity\n ) {\n invalidSelection(\"Requested Product quantity is unavailable.\");\n }\n\n selection.set(productSlug, { quantity });\n reviseState();\n commitReady();\n },\n async submitPayment(submission) {\n if (!(catalog && calculatedTotal && calculatedPricingInput)) {\n invalidSelection(\n \"Calculate the current total before submitting a payment.\",\n \"submit_payment\"\n );\n }\n if (submitting) {\n invalidSelection(\n \"A Lockerverse payment is already being submitted.\",\n \"submit_payment\"\n );\n }\n\n const transactionCatalog = catalog;\n const transactionQuote = calculatedTotal;\n const transactionPricingInput = calculatedPricingInput;\n const transactionSelection = getSelection();\n const transactionPreview =\n latestPreview ??\n calculateCheckoutPreview(\n transactionCatalog,\n transactionSelection,\n transactionPricingInput\n );\n const normalizedEmail = submission.email.trim().toLowerCase();\n if (\n !normalizedEmail ||\n normalizedEmail !== transactionPricingInput.email\n ) {\n invalidSelection(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n\n const items = transactionSelection.items.map(\n ({ productSlug: _productSlug, ...item }) => item\n );\n submitting = true;\n stateStore.commit({\n catalog: transactionCatalog,\n phase: \"submitting\",\n preview: transactionPreview,\n quote: transactionQuote,\n selection: transactionSelection,\n });\n try {\n const response = await fetchResponse(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: submission.confirmationToken,\n customFieldAnswers: submission.customFieldAnswers,\n email: normalizedEmail,\n expectedAmountCents: transactionQuote.amountCents,\n expectedAppliedDiscount: transactionQuote.appliedDiscount,\n expectedConnectedAccountId:\n transactionQuote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n transactionQuote.discountableSubtotalCents,\n expectedDiscountCents: transactionQuote.discountCents,\n expectedServiceFeeCents: transactionQuote.serviceFeeCents,\n expectedSubtotalCents: transactionQuote.subtotalCents,\n expectedTipCents: transactionQuote.tipCents,\n expectedTotalCents: transactionQuote.totalCents,\n ...transactionPricingInput,\n items,\n memberId: submission.memberId,\n merchSize: submission.merchSize,\n metadata: submission.metadata,\n paymentReference: transactionQuote.paymentReference,\n phone: submission.phone,\n quoteContractVersion: 1,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n {\n code: \"payment_submit_failed\",\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n operation: \"submit_payment\",\n }\n );\n\n if (!response.ok) {\n throw reportError(\n new LockerverseSdkError({\n code: \"payment_submit_failed\",\n message: `Unable to submit the Lockerverse payment (${response.status}).`,\n operation: \"submit_payment\",\n reportable: response.status >= 500,\n status: response.status,\n })\n );\n }\n\n const payment = clonePaymentResult(\n await parseResponseJson(response, parsePaymentResult, {\n code: \"payment_submit_failed\",\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\",\n })\n );\n stateStore.commit({\n catalog: transactionCatalog,\n payment,\n phase: \"payment\",\n quote: transactionQuote,\n selection: transactionSelection,\n });\n return clonePaymentResult(payment);\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n commitError(error, transactionQuote.paymentReference);\n }\n throw error;\n } finally {\n submitting = false;\n }\n },\n subscribe: stateStore.subscribe,\n };\n}\n"],"mappings":"wJAMA,MAAM,EAAkE,CACtE,YACE,8GACF,WACE,6GACJ,EAEA,SAAgB,EACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,qBAAsB,EAAwB,EAAQ,aACtD,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,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AW,MAAM,EACrB,GAAG,EAAW,gBAAgB,EAAc,mBAAmB,EAAW,mBAC1E,CACE,KAAM,KAAK,UAAU,CACnB,kBAAmB,EAAW,kBAC9B,mBAAoB,EAAW,mBAC/B,MAAO,EACP,oBAAqB,EAAiB,YACtC,wBAAyB,EAAiB,gBAC1C,2BACE,EAAiB,QAAQ,mBAC3B,kCACE,EAAiB,0BACnB,sBAAuB,EAAiB,cACxC,wBAAyB,EAAiB,gBAC1C,sBAAuB,EAAiB,cACxC,iBAAkB,EAAiB,SACnC,mBAAoB,EAAiB,WACrC,GAAG,EACH,QACA,SAAU,EAAW,SACrB,UAAW,EAAW,UACtB,SAAU,EAAW,SACrB,iBAAkB,EAAiB,iBACnC,MAAO,EAAW,MAClB,qBAAsB,CACxB,CAAC,EACD,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,OAAQ,MACV,EACA,CACE,KAAM,wBACN,QACE,uEACF,UAAW,gBACb,CACF,EAEA,GAAI,CAAC,EAAS,GACZ,MAAM,EACJ,IAAI,EAAoB,CACtB,KAAM,wBACN,QAAS,6CAA6C,EAAS,OAAO,IACtE,UAAW,iBACX,WAAY,EAAS,QAAU,IAC/B,OAAQ,EAAS,MACnB,CAAC,CACH,EAGF,IAAM,EAAU,EACd,MAAM,EAAkB,EAAU,EAAoB,CACpD,KAAM,wBACN,QAAS,wDACT,UAAW,gBACb,CAAC,CACH,EAQA,OAPA,EAAW,OAAO,CAChB,QAAS,EACT,UACA,MAAO,UACP,MAAO,EACP,UAAW,CACb,CAAC,EACM,EAAmB,CAAO,CACnC,OAAS,EAAO,CAId,MAHI,aAAiB,GACnB,EAAY,EAAO,EAAiB,gBAAgB,EAEhD,CACR,QAAU,CACR,EAAa,EACf,CACF,EACA,UAAW,EAAW,SACxB,CACF"}
|
|
1
|
+
{"version":3,"file":"checkout.js","names":[],"sources":["../src/checkout-environment.ts","../src/checkout-input-schemas.ts","../src/checkout-schemas.ts","../src/pricing.ts","../src/snapshots.ts","../src/checkout.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type {\n CreateLockerverseWidgetOptions,\n LockerverseEnvironment,\n} from \"./types.ts\";\n\nconst STRIPE_PUBLISHABLE_KEYS: Record<LockerverseEnvironment, string> = {\n development:\n \"pk_test_51O7FkjDHAhgRuLtFHdkXdIe8T5i7rOVaG9PCtDetK3UUVKojVUEKHmQacGzigf9mOX1wz3zSOKoYwFjRcTfML9PU00OjJko2lk\",\n production:\n \"pk_live_51O7FkjDHAhgRuLtFlzLdxJrwo7F09WCKTlzT9lnBePjOGizWnuijkH9oCkoAddkmBT8ngIuqAPkDiHlPEAH4KXbz00Tm0DaPT4\",\n};\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n stripePublishableKey: STRIPE_PUBLISHABLE_KEYS[runtime.environment],\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import {\n array,\n boolean,\n optional,\n parser,\n picklist,\n record,\n strictObject,\n string,\n} from \"valibot\";\n\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nexport const parseCheckoutPricingInput = parser(\n optional(\n strictObject({\n email: optional(string()),\n includeServiceFee: optional(boolean()),\n promoCode: optional(string()),\n tipCents: optional(safeIntegerSchema(0)),\n }),\n {}\n )\n);\n\nexport const parsePaymentSubmission = parser(\n strictObject({\n confirmationToken: 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 phone: optional(string()),\n })\n);\n","import {\n array,\n boolean,\n check,\n finite,\n type InferOutput,\n literal,\n maxValue,\n minValue,\n nullable,\n number,\n object,\n optional,\n parser,\n picklist,\n pipe,\n string,\n transform,\n variant,\n} from \"valibot\";\n\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst paymentOptionSchema = picklist([\"one-time\", \"monthly\", \"annually\"]);\nconst nullableNonNegativeIntegerSchema = nullable(safeIntegerSchema(0));\n\nconst productBaseEntries = {\n description: optionalNullableStringSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n maxQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n};\n\nconst publicProductSchema = pipe(\n 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 check(\n ({ maxQuantity, minQuantity }) =>\n maxQuantity === null || minQuantity === null || minQuantity <= maxQuantity\n )\n);\n\nconst productListingSchema = object({\n acceptsDiscounts: optional(boolean(), false),\n id: nonEmptyStringSchema,\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 config: optional(\n object({\n customFields: customFieldsSchema,\n fields: widgetFieldsSchema,\n })\n ),\n description: optionalNullableStringSchema,\n id: optional(string(), \"\"),\n name: optional(string(), \"Lockerverse widget\"),\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 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 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 = 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\nexport const paymentResultSchema = object({\n checkoutId: nonEmptyStringSchema,\n checkoutStatus: picklist([\"action_required\", \"failed\", \"pending\", \"success\"]),\n clientSecret: nullable(string()),\n paymentReference: nonEmptyStringSchema,\n requiresAction: boolean(),\n status: nullable(string()),\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 parsePaymentResult = parser(paymentResultSchema);\nexport const parsePublicWidget = parser(publicWidgetSchema);\n","import type {\n LockerverseCatalog,\n LockerverseCheckoutPreview,\n LockerverseCheckoutPricingInput,\n LockerverseSelection,\n} from \"./types.ts\";\n\nconst BASIS_POINTS_PER_WHOLE = 10_000;\n\nfunction assertSafeCents(value: number, message: string) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(message);\n }\n return value;\n}\n\nfunction addCents(left: number, right: number) {\n return assertSafeCents(\n left + right,\n \"The selected checkout total is too large.\"\n );\n}\n\nfunction multiplyCents(value: number, quantity: number) {\n return assertSafeCents(\n value * quantity,\n \"The selected Product quantity produces an unsafe total.\"\n );\n}\n\nfunction calculateBasisPoints(value: number, basisPoints: number) {\n const rounded =\n (BigInt(value) * BigInt(basisPoints) + BigInt(BASIS_POINTS_PER_WHOLE / 2)) /\n BigInt(BASIS_POINTS_PER_WHOLE);\n if (rounded > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new TypeError(\"The selected checkout total is too large.\");\n }\n return Number(rounded);\n}\n\nexport function calculateCheckoutPreview(\n catalog: LockerverseCatalog,\n selection: LockerverseSelection,\n input: LockerverseCheckoutPricingInput\n): LockerverseCheckoutPreview {\n let subtotalCents = 0;\n let discountableSubtotalCents = 0;\n\n for (const item of selection.items) {\n const product = catalog.products.find(\n ({ id, slug }) => id === item.productId && slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"The selected Product is no longer available.\");\n }\n if (product.paymentOption !== \"one-time\") {\n throw new TypeError(\n \"Recurring Products are not supported by this SDK checkout yet.\"\n );\n }\n const itemSubtotal =\n \"quantity\" in item\n ? multiplyCents(product.amountCents ?? 0, item.quantity)\n : item.amountCents;\n subtotalCents = addCents(subtotalCents, itemSubtotal);\n if (product.acceptsDiscounts) {\n discountableSubtotalCents = addCents(\n discountableSubtotalCents,\n itemSubtotal\n );\n }\n }\n\n const serviceFeeCents = input.includeServiceFee\n ? calculateBasisPoints(\n subtotalCents,\n catalog.pricingPolicy.serviceFeeRateBasisPoints\n )\n : 0;\n const tipCents = input.tipCents ?? 0;\n const amountCents = addCents(subtotalCents, serviceFeeCents);\n\n return {\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents: addCents(amountCents, tipCents),\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutTotal,\n LockerversePaymentResult,\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 id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: product.maxQuantity,\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\nexport function createCatalog(\n widget: PublicWidget,\n publishableKey: string\n): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n payment: {\n currency: \"usd\",\n 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 cloneCheckoutTotal(\n total: LockerverseCheckoutTotal\n): LockerverseCheckoutTotal {\n return cloneSnapshot(total);\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 { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport {\n parseCheckoutPricingInput,\n parsePaymentSubmission,\n} from \"./checkout-input-schemas.ts\";\nimport {\n type PublicCheckoutQuote,\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidget,\n} from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport { calculateCheckoutPreview } from \"./pricing.ts\";\nimport {\n cloneCatalog,\n cloneCheckoutTotal,\n clonePaymentResult,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createStateStore } from \"./state.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCatalog,\n type LockerverseCheckoutPreview,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutTotal,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSelection,\n type LockerverseWidget,\n type LockerverseWidgetState,\n} from \"./types.ts\";\n\nexport function createLockerverseCheckout(\n options: CreateLockerverseWidgetOptions\n): LockerverseWidget {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n requestTimeoutMs,\n sentryDsn,\n stripePublishableKey,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n let catalog: LockerverseCatalog | null = null;\n let calculatedTotal: LockerverseCheckoutTotal | null = null;\n let calculatedPricingInput: LockerverseCheckoutPricingInput | null = null;\n let latestPaymentReference: string | null = null;\n let latestPreview: LockerverseCheckoutPreview | null = null;\n let remoteOperationGeneration = 0;\n let stateRevision = 0;\n let submitting = false;\n const selection = new Map<\n string,\n { amountCents: number } | { quantity: number }\n >();\n const stateStore = createStateStore<LockerverseWidgetState>({\n phase: \"idle\",\n selection: deepFreeze({ items: [] }),\n });\n\n function getProduct(productSlug: string) {\n const currentCatalog = catalog;\n const product = currentCatalog\n ? currentCatalog.products.find(({ slug }) => slug === productSlug)\n : undefined;\n\n if (!product) {\n throw new Error(`Lockerverse Product \"${productSlug}\" is unavailable.`);\n }\n\n return product;\n }\n\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({\n paymentReference: latestPaymentReference,\n widgetSlug: widgetSlugValue,\n }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n\n function invalidSelection(\n message: string,\n operation: LockerverseSdkOperation = \"update_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code: \"invalid_selection\",\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n const { requestJson } = createTransport(\n fetchImplementation,\n reportError,\n requestTimeoutMs\n );\n\n function getSelection(): LockerverseSelection {\n const currentCatalog = catalog;\n return deepFreeze({\n items: (currentCatalog ? currentCatalog.products : []).flatMap(\n (product) => {\n const selected = selection.get(product.slug);\n return selected\n ? [\n {\n productId: product.id,\n productSlug: product.slug,\n ...selected,\n },\n ]\n : [];\n }\n ),\n });\n }\n\n function invalidateCalculatedTotal() {\n calculatedTotal = null;\n calculatedPricingInput = null;\n latestPaymentReference = null;\n latestPreview = null;\n }\n\n function ensureSelectionMutable() {\n if (submitting) {\n invalidSelection(\n \"Selection cannot change while a payment is being submitted.\"\n );\n }\n }\n\n function ensureOperationAvailable(operation: LockerverseSdkOperation) {\n if (submitting) {\n invalidSelection(\n \"This operation cannot run while a payment is being submitted.\",\n operation\n );\n }\n }\n\n function reviseState() {\n stateRevision += 1;\n invalidateCalculatedTotal();\n }\n\n function commitReady(preview: LockerverseCheckoutPreview | null = null) {\n if (!catalog) {\n return;\n }\n stateStore.commit({\n catalog,\n phase: \"ready\",\n preview,\n selection: getSelection(),\n });\n }\n\n function commitError(\n error: LockerverseSdkError,\n recoverablePaymentReference: string | null = null\n ) {\n stateStore.commit({\n catalog,\n error,\n phase: \"error\",\n recoverablePaymentReference,\n selection: getSelection(),\n });\n }\n\n function normalizeOperationError(\n error: unknown,\n context: {\n code:\n | \"payment_status_failed\"\n | \"payment_submit_failed\"\n | \"widget_load_failed\";\n message: string;\n operation: \"get_payment_status\" | \"load_widget\" | \"submit_payment\";\n }\n ) {\n return error instanceof LockerverseSdkError\n ? error\n : new LockerverseSdkError({\n ...context,\n reportable: true,\n });\n }\n\n function startRemoteOperation() {\n remoteOperationGeneration += 1;\n return remoteOperationGeneration;\n }\n\n function rejectSupersededRemoteOperation(\n requestedGeneration: number,\n context: {\n code:\n | \"payment_status_failed\"\n | \"total_calculation_failed\"\n | \"widget_load_failed\";\n message: string;\n operation: \"calculate_total\" | \"get_payment_status\" | \"load_widget\";\n },\n shouldReport = true\n ) {\n if (requestedGeneration === remoteOperationGeneration) {\n return;\n }\n\n const error = new LockerverseSdkError({\n ...context,\n reportable: false,\n });\n throw shouldReport ? reportError(error) : error;\n }\n\n function rejectSupersededQuote(\n requestedStateRevision: number,\n requestedRemoteOperationGeneration: number\n ) {\n if (\n requestedStateRevision === stateRevision &&\n requestedRemoteOperationGeneration === remoteOperationGeneration\n ) {\n return;\n }\n\n throw reportError(\n new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message:\n \"This Lockerverse checkout total was superseded. Calculate the total again for the current selection.\",\n operation: \"calculate_total\",\n reportable: false,\n })\n );\n }\n\n function previewTotal(input: LockerverseCheckoutPricingInput = {}) {\n ensureOperationAvailable(\"calculate_total\");\n if (!catalog) {\n throw new Error(\n \"Load the Lockerverse widget before previewing the total.\"\n );\n }\n if (selection.size === 0) {\n invalidSelection(\"Select at least one Product before previewing.\");\n }\n const normalizedInput = normalizePricingInput(catalog, input);\n reviseState();\n\n try {\n const preview = deepFreeze(\n calculateCheckoutPreview(catalog, getSelection(), normalizedInput)\n );\n latestPreview = preview;\n commitReady(preview);\n return preview;\n } catch (error) {\n invalidSelection(\n error instanceof Error ? error.message : \"Unable to preview checkout.\"\n );\n }\n }\n\n function normalizePricingInput(\n currentCatalog: LockerverseCatalog,\n input: LockerverseCheckoutPricingInput\n ): LockerverseCheckoutPricingInput {\n let parsedInput: ReturnType<typeof parseCheckoutPricingInput>;\n try {\n parsedInput = parseCheckoutPricingInput(input);\n } catch {\n invalidSelection(\"Checkout pricing input is invalid.\");\n }\n validatePricingInput(currentCatalog, parsedInput);\n const tipCents = parsedInput.tipCents ?? 0;\n const email = parsedInput.email?.trim().toLowerCase();\n const promoCode = parsedInput.promoCode?.trim();\n return {\n ...(email ? { email } : {}),\n ...(parsedInput.includeServiceFee === undefined\n ? {}\n : { includeServiceFee: parsedInput.includeServiceFee }),\n ...(promoCode ? { promoCode } : {}),\n ...(parsedInput.tipCents === undefined ? {} : { tipCents }),\n };\n }\n\n function validatePricingInput(\n currentCatalog: LockerverseCatalog,\n input: ReturnType<typeof parseCheckoutPricingInput>\n ) {\n const tipCents = input.tipCents ?? 0;\n if (!Number.isSafeInteger(tipCents) || tipCents < 0) {\n invalidSelection(\"Tip must be a non-negative whole number of cents.\");\n }\n if (input.includeServiceFee && !currentCatalog.widget.fields.serviceFee) {\n invalidSelection(\"Service fee is not enabled for this widget.\");\n }\n if (\n input.includeServiceFee &&\n currentCatalog.pricingPolicy.serviceFeeRateBasisPoints === 0\n ) {\n invalidSelection(\n \"Service fee pricing is unavailable. Reload the widget and try again.\"\n );\n }\n if (tipCents > 0 && !currentCatalog.widget.fields.tipping) {\n invalidSelection(\"Tipping is not enabled for this widget.\");\n }\n }\n\n async function calculateTotal(input: LockerverseCheckoutPricingInput = {}) {\n ensureOperationAvailable(\"calculate_total\");\n if (!catalog) {\n throw new Error(\n \"Load the Lockerverse widget before calculating the total.\"\n );\n }\n\n const normalizedInput = normalizePricingInput(catalog, input);\n if (selection.size === 0) {\n invalidSelection(\n \"Select at least one Product before calculating the total.\",\n \"calculate_total\"\n );\n }\n const currentSelection = getSelection();\n const requestedRemoteOperationGeneration = startRemoteOperation();\n const preview = deepFreeze(\n calculateCheckoutPreview(catalog, currentSelection, normalizedInput)\n );\n latestPreview = preview;\n stateStore.commit({\n catalog,\n phase: \"quoting\",\n preview,\n selection: currentSelection,\n });\n const items = currentSelection.items.map(\n ({ productSlug: _productSlug, ...item }) => item\n );\n const requestedStateRevision = stateRevision;\n calculatedTotal = null;\n latestPaymentReference = null;\n const quoteRequest = requestJson(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/quote`,\n {\n body: JSON.stringify({ ...normalizedInput, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parseCheckoutQuote,\n {\n code: \"total_calculation_failed\",\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n operation: \"calculate_total\",\n report: false,\n },\n {\n code: \"total_calculation_failed\",\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\",\n report: false,\n }\n );\n let quoteResponse: Awaited<typeof quoteRequest>;\n\n try {\n quoteResponse = await quoteRequest;\n } catch (error) {\n rejectSupersededQuote(\n requestedStateRevision,\n requestedRemoteOperationGeneration\n );\n if (error instanceof LockerverseSdkError) {\n commitError(error);\n throw reportError(error);\n }\n throw error;\n }\n\n rejectSupersededQuote(\n requestedStateRevision,\n requestedRemoteOperationGeneration\n );\n\n if (!quoteResponse.ok) {\n const error = new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: `Unable to calculate the Lockerverse checkout total (${quoteResponse.response.status}).`,\n operation: \"calculate_total\",\n reportable: quoteResponse.response.status >= 500,\n status: quoteResponse.response.status,\n });\n commitError(error);\n throw reportError(error);\n }\n\n let serverTotal: PublicCheckoutQuote;\n try {\n serverTotal = quoteResponse.value;\n if (serverTotal.paymentOption !== \"one-time\") {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"Lockerverse returned an unsupported checkout cadence.\",\n operation: \"calculate_total\",\n reportable: true,\n });\n }\n } catch (error) {\n rejectSupersededQuote(\n requestedStateRevision,\n requestedRemoteOperationGeneration\n );\n if (error instanceof LockerverseSdkError) {\n commitError(error);\n throw reportError(error);\n }\n throw error;\n }\n rejectSupersededQuote(\n requestedStateRevision,\n requestedRemoteOperationGeneration\n );\n const paymentReference = globalThis.crypto.randomUUID();\n const {\n connectedAccountId,\n paymentOption: _paymentOption,\n ...total\n } = serverTotal;\n const nextCalculatedTotal = deepFreeze({\n ...total,\n authoritative: true as const,\n payment: {\n ...catalog.payment,\n connectedAccountId,\n },\n paymentOption: \"one-time\" as const,\n paymentReference,\n });\n calculatedTotal = nextCalculatedTotal;\n calculatedPricingInput = deepFreeze({ ...normalizedInput });\n latestPaymentReference = paymentReference;\n stateStore.commit({\n catalog,\n phase: \"quoted\",\n preview,\n quote: nextCalculatedTotal,\n selection: currentSelection,\n });\n return cloneCheckoutTotal(nextCalculatedTotal);\n }\n\n return {\n calculateTotal,\n clear() {\n ensureSelectionMutable();\n selection.clear();\n reviseState();\n commitReady();\n },\n async getPaymentStatus(paymentReference = latestPaymentReference ?? \"\") {\n ensureOperationAvailable(\"get_payment_status\");\n if (!paymentReference) {\n invalidSelection(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n const requestedRemoteOperationGeneration = startRemoteOperation();\n const supersededContext = {\n code: \"payment_status_failed\" as const,\n message: \"This Lockerverse payment status request was superseded.\",\n operation: \"get_payment_status\" as const,\n };\n latestPaymentReference = paymentReference;\n const currentSelection = getSelection();\n stateStore.commit({\n catalog,\n paymentReference,\n phase: \"recovering\",\n selection: currentSelection,\n });\n try {\n const statusResponse = await requestJson(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/${encodeURIComponent(paymentReference)}/status`,\n undefined,\n parsePaymentResult,\n {\n code: \"payment_status_failed\",\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n operation: \"get_payment_status\",\n report: false,\n },\n {\n code: \"payment_status_failed\",\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\",\n report: false,\n }\n );\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext,\n false\n );\n if (!statusResponse.ok) {\n throw new LockerverseSdkError({\n code: \"payment_status_failed\",\n message: `Unable to recover the Lockerverse payment status (${statusResponse.response.status}).`,\n operation: \"get_payment_status\",\n reportable: statusResponse.response.status >= 500,\n status: statusResponse.response.status,\n });\n }\n\n const payment = clonePaymentResult(statusResponse.value);\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext,\n false\n );\n if (payment.paymentReference !== paymentReference) {\n throw new LockerverseSdkError({\n code: \"payment_status_failed\",\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\",\n reportable: true,\n });\n }\n stateStore.commit({\n catalog,\n payment,\n phase: \"payment\",\n quote:\n calculatedTotal?.paymentReference === paymentReference\n ? calculatedTotal\n : null,\n selection: currentSelection,\n });\n return clonePaymentResult(payment);\n } catch (error) {\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext\n );\n const sdkError = normalizeOperationError(error, {\n code: \"payment_status_failed\",\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\",\n });\n commitError(sdkError, paymentReference);\n throw reportError(sdkError);\n }\n },\n getSelection,\n getState: stateStore.getState,\n async load() {\n ensureOperationAvailable(\"load_widget\");\n const requestedRemoteOperationGeneration = startRemoteOperation();\n const supersededContext = {\n code: \"widget_load_failed\" as const,\n message: \"This Lockerverse widget load was superseded.\",\n operation: \"load_widget\" as const,\n };\n reviseState();\n stateStore.commit({ phase: \"loading\", selection: getSelection() });\n const requestContext = {\n code: \"widget_load_failed\" as const,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n operation: \"load_widget\" as const,\n report: false,\n };\n try {\n const widgetResponse = await requestJson(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`,\n undefined,\n parsePublicWidget,\n requestContext,\n {\n code: \"widget_load_failed\",\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\",\n report: false,\n }\n );\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext,\n false\n );\n if (!widgetResponse.ok) {\n throw new LockerverseSdkError({\n code: \"widget_load_failed\",\n message: `Unable to load Lockerverse widget (${widgetResponse.response.status}).`,\n operation: \"load_widget\",\n reportable: widgetResponse.response.status >= 500,\n status: widgetResponse.response.status,\n });\n }\n\n const widget = widgetResponse.value;\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext,\n false\n );\n const nextCatalog = deepFreeze(\n createCatalog(widget, stripePublishableKey)\n );\n const catalogResult = cloneCatalog(nextCatalog);\n selection.clear();\n catalog = nextCatalog;\n commitReady();\n\n return catalogResult;\n } catch (error) {\n rejectSupersededRemoteOperation(\n requestedRemoteOperationGeneration,\n supersededContext\n );\n const sdkError = normalizeOperationError(error, {\n code: \"widget_load_failed\",\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\",\n });\n commitError(sdkError);\n throw reportError(sdkError);\n }\n },\n previewTotal,\n remove(productSlug) {\n ensureSelectionMutable();\n selection.delete(productSlug);\n reviseState();\n commitReady();\n },\n setAmount(productSlug, amountCents) {\n ensureSelectionMutable();\n const product = getProduct(productSlug);\n\n if (product.pricingMode !== \"custom\") {\n invalidSelection(\"Fixed-price Products do not accept custom amounts.\");\n }\n if (!Number.isSafeInteger(amountCents) || amountCents <= 0) {\n invalidSelection(\"Product amount must be a positive integer in cents.\");\n }\n if (\n product.minimumAmountCents !== null &&\n amountCents < product.minimumAmountCents\n ) {\n invalidSelection(\n `Product amount must be at least ${product.minimumAmountCents} cents.`\n );\n }\n\n selection.set(productSlug, { amountCents });\n reviseState();\n commitReady();\n },\n setQuantity(productSlug, quantity) {\n ensureSelectionMutable();\n const product = getProduct(productSlug);\n\n if (product.pricingMode !== \"fixed\") {\n invalidSelection(\"Custom-amount Products do not accept quantities.\");\n }\n if (!Number.isSafeInteger(quantity) || quantity <= 0) {\n invalidSelection(\"Product quantity must be a positive integer.\");\n }\n if (\n product.minimumQuantity !== null &&\n quantity < product.minimumQuantity\n ) {\n invalidSelection(\n `Product quantity must be at least ${product.minimumQuantity}.`\n );\n }\n if (\n product.maximumQuantity !== null &&\n quantity > product.maximumQuantity\n ) {\n invalidSelection(\n `Product quantity must not exceed ${product.maximumQuantity}.`\n );\n }\n if (\n product.inventoryQuantity !== null &&\n quantity > product.inventoryQuantity\n ) {\n invalidSelection(\"Requested Product quantity is unavailable.\");\n }\n\n selection.set(productSlug, { quantity });\n reviseState();\n commitReady();\n },\n async submitPayment(submission) {\n if (!(catalog && calculatedTotal && calculatedPricingInput)) {\n invalidSelection(\n \"Calculate the current total before submitting a payment.\",\n \"submit_payment\"\n );\n }\n if (submitting) {\n invalidSelection(\n \"A Lockerverse payment is already being submitted.\",\n \"submit_payment\"\n );\n }\n\n const transactionCatalog = catalog;\n const transactionQuote = calculatedTotal;\n const transactionPricingInput = calculatedPricingInput;\n const transactionSelection = getSelection();\n const transactionPreview =\n latestPreview ??\n calculateCheckoutPreview(\n transactionCatalog,\n transactionSelection,\n transactionPricingInput\n );\n let parsedSubmission: ReturnType<typeof parsePaymentSubmission>;\n try {\n parsedSubmission = parsePaymentSubmission(submission);\n } catch {\n const error = new LockerverseSdkError({\n code: \"payment_submit_failed\",\n message: \"Lockerverse payment submission is invalid.\",\n operation: \"submit_payment\",\n reportable: true,\n });\n commitError(error, transactionQuote.paymentReference);\n // biome-ignore lint/style/useErrorCause: Raw validation errors must not escape the SDK boundary.\n throw reportError(error);\n }\n const normalizedEmail = parsedSubmission.email.trim().toLowerCase();\n if (\n !normalizedEmail ||\n normalizedEmail !== transactionPricingInput.email\n ) {\n invalidSelection(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n\n const items = transactionSelection.items.map(\n ({ productSlug: _productSlug, ...item }) => item\n );\n startRemoteOperation();\n submitting = true;\n stateStore.commit({\n catalog: transactionCatalog,\n phase: \"submitting\",\n preview: transactionPreview,\n quote: transactionQuote,\n selection: transactionSelection,\n });\n try {\n const confirmationResponse = await requestJson(\n `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: parsedSubmission.confirmationToken,\n customFieldAnswers: parsedSubmission.customFieldAnswers,\n email: normalizedEmail,\n expectedAmountCents: transactionQuote.amountCents,\n expectedAppliedDiscount: transactionQuote.appliedDiscount,\n expectedConnectedAccountId:\n transactionQuote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n transactionQuote.discountableSubtotalCents,\n expectedDiscountCents: transactionQuote.discountCents,\n expectedServiceFeeCents: transactionQuote.serviceFeeCents,\n expectedSubtotalCents: transactionQuote.subtotalCents,\n expectedTipCents: transactionQuote.tipCents,\n expectedTotalCents: transactionQuote.totalCents,\n ...transactionPricingInput,\n items,\n memberId: parsedSubmission.memberId,\n merchSize: parsedSubmission.merchSize,\n metadata: parsedSubmission.metadata,\n paymentReference: transactionQuote.paymentReference,\n phone: parsedSubmission.phone,\n quoteContractVersion: 1,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parsePaymentResult,\n {\n code: \"payment_submit_failed\",\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n operation: \"submit_payment\",\n report: false,\n },\n {\n code: \"payment_submit_failed\",\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\",\n report: false,\n }\n );\n\n if (!confirmationResponse.ok) {\n throw new LockerverseSdkError({\n code: \"payment_submit_failed\",\n message: `Unable to submit the Lockerverse payment (${confirmationResponse.response.status}).`,\n operation: \"submit_payment\",\n reportable: confirmationResponse.response.status >= 500,\n status: confirmationResponse.response.status,\n });\n }\n\n const payment = clonePaymentResult(confirmationResponse.value);\n if (payment.paymentReference !== transactionQuote.paymentReference) {\n throw new LockerverseSdkError({\n code: \"payment_submit_failed\",\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\",\n reportable: true,\n });\n }\n stateStore.commit({\n catalog: transactionCatalog,\n payment,\n phase: \"payment\",\n quote: transactionQuote,\n selection: transactionSelection,\n });\n return clonePaymentResult(payment);\n } catch (error) {\n const sdkError = normalizeOperationError(error, {\n code: \"payment_submit_failed\",\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\",\n });\n commitError(sdkError, transactionQuote.paymentReference);\n throw reportError(sdkError);\n } finally {\n submitting = false;\n }\n },\n subscribe: stateStore.subscribe,\n };\n}\n"],"mappings":"6QAMA,MAAM,EAAkE,CACtE,YACE,8GACF,WACE,6GACJ,EAEA,SAAgB,EACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,qBAAsB,EAAwB,EAAQ,aACtD,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,CCNA,MAAa,EAA4B,EACvC,EACE,EAAa,CACX,MAAO,EAAS,EAAO,CAAC,EACxB,kBAAmB,EAAS,EAAQ,CAAC,EACrC,UAAW,EAAS,EAAO,CAAC,EAC5B,SAAU,EAAS,EAAkB,CAAC,CAAC,CACzC,CAAC,EACD,CAAC,CACH,CACF,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ACH,QACA,SAAU,EAAiB,SAC3B,UAAW,EAAiB,UAC5B,SAAU,EAAiB,SAC3B,iBAAkB,EAAiB,iBACnC,MAAO,EAAiB,MACxB,qBAAsB,CACxB,CAAC,EACD,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,OAAQ,MACV,EACA,EACA,CACE,KAAM,wBACN,QACE,uEACF,UAAW,iBACX,OAAQ,EACV,EACA,CACE,KAAM,wBACN,QAAS,wDACT,UAAW,iBACX,OAAQ,EACV,CACF,EAEA,GAAI,CAAC,EAAqB,GACxB,MAAM,IAAI,EAAoB,CAC5B,KAAM,wBACN,QAAS,6CAA6C,EAAqB,SAAS,OAAO,IAC3F,UAAW,iBACX,WAAY,EAAqB,SAAS,QAAU,IACpD,OAAQ,EAAqB,SAAS,MACxC,CAAC,EAGH,IAAM,EAAU,EAAmB,EAAqB,KAAK,EAC7D,GAAI,EAAQ,mBAAqB,EAAiB,iBAChD,MAAM,IAAI,EAAoB,CAC5B,KAAM,wBACN,QAAS,wDACT,UAAW,iBACX,WAAY,EACd,CAAC,EASH,OAPA,EAAW,OAAO,CAChB,QAAS,EACT,UACA,MAAO,UACP,MAAO,EACP,UAAW,CACb,CAAC,EACM,EAAmB,CAAO,CACnC,OAAS,EAAO,CACd,IAAM,EAAW,EAAwB,EAAO,CAC9C,KAAM,wBACN,QAAS,wDACT,UAAW,gBACb,CAAC,EAED,MADA,EAAY,EAAU,EAAiB,gBAAgB,EACjD,EAAY,CAAQ,CAC5B,QAAU,CACR,EAAa,EACf,CACF,EACA,UAAW,EAAW,SACxB,CACF"}
|
package/dist/signup.d.ts
CHANGED
|
@@ -43,10 +43,14 @@ type LockerverseSignupSubmissionResult = {
|
|
|
43
43
|
id: string;
|
|
44
44
|
submittedAt: string;
|
|
45
45
|
};
|
|
46
|
+
type LockerverseSignupSubmitOptions = {
|
|
47
|
+
submissionReference?: string;
|
|
48
|
+
};
|
|
46
49
|
type CreateLockerverseSignupBaseOptions = {
|
|
47
50
|
communitySlug: string;
|
|
48
51
|
fetch?: typeof globalThis.fetch;
|
|
49
52
|
onError?: (error: LockerverseSdkError) => void;
|
|
53
|
+
requestTimeoutMs?: number;
|
|
50
54
|
sentryDsn?: string | null;
|
|
51
55
|
signupSlug: string;
|
|
52
56
|
};
|
|
@@ -67,6 +71,7 @@ type LockerverseSignupState = {
|
|
|
67
71
|
} | {
|
|
68
72
|
phase: "submitting";
|
|
69
73
|
signup: LockerverseSignup;
|
|
74
|
+
submissionReference: string;
|
|
70
75
|
} | {
|
|
71
76
|
phase: "submitted";
|
|
72
77
|
signup: LockerverseSignup;
|
|
@@ -74,17 +79,18 @@ type LockerverseSignupState = {
|
|
|
74
79
|
} | {
|
|
75
80
|
phase: "error";
|
|
76
81
|
error: LockerverseSdkError;
|
|
82
|
+
recoverableSubmissionReference: string | null;
|
|
77
83
|
signup: LockerverseSignup | null;
|
|
78
84
|
};
|
|
79
85
|
type LockerverseSignupClient = {
|
|
80
86
|
getState: () => LockerverseSignupState;
|
|
81
87
|
load: () => Promise<LockerverseSignup>;
|
|
82
|
-
submit: (submission: LockerverseSignupSubmission) => Promise<LockerverseSignupSubmissionResult>;
|
|
88
|
+
submit: (submission: LockerverseSignupSubmission, options?: LockerverseSignupSubmitOptions) => Promise<LockerverseSignupSubmissionResult>;
|
|
83
89
|
subscribe: (listener: (state: LockerverseSignupState) => void) => () => void;
|
|
84
90
|
};
|
|
85
91
|
//#endregion
|
|
86
92
|
//#region src/signup.d.ts
|
|
87
93
|
declare function createLockerverseSignup(options: CreateLockerverseSignupOptions): LockerverseSignupClient;
|
|
88
94
|
//#endregion
|
|
89
|
-
export { type CreateLockerverseSignupOptions, type LockerverseCustomField, type LockerverseCustomFieldAnswer, type LockerverseCustomFieldAnswerValue, type LockerverseCustomFieldOption, type LockerverseEnvironment, type LockerverseSignup, type LockerverseSignupAddress, type LockerverseSignupClient, type LockerverseSignupField, type LockerverseSignupFields, type LockerverseSignupState, type LockerverseSignupSubmission, type LockerverseSignupSubmissionResult, createLockerverseSignup };
|
|
95
|
+
export { type CreateLockerverseSignupOptions, type LockerverseCustomField, type LockerverseCustomFieldAnswer, type LockerverseCustomFieldAnswerValue, type LockerverseCustomFieldOption, type LockerverseEnvironment, type LockerverseSignup, type LockerverseSignupAddress, type LockerverseSignupClient, type LockerverseSignupField, type LockerverseSignupFields, type LockerverseSignupState, type LockerverseSignupSubmission, type LockerverseSignupSubmissionResult, type LockerverseSignupSubmitOptions, createLockerverseSignup };
|
|
90
96
|
//# sourceMappingURL=signup.d.ts.map
|
package/dist/signup.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signup.d.ts","names":[],"sources":["../src/signup-types.ts","../src/signup.ts"],"mappings":";;KAOY;EACV;EACA;;KAGU;EACV,SAAS;EACT,OAAO;EACP,MAAM;EACN,kBAAkB;EAClB,OAAO;;KAGG;EACV;EACA,cAAc;EACd;EACA,QAAQ;EACR;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV,UAAU;EACV,UAAU;EACV;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;;KAGG;EACH;EACA,eAAe,WAAW;EAC1B,WAAW,OAAO;EAClB;EACA;;KAGU,iCACV;EAGQ;EACA,aAAa;;EAGb;EACA;;KAIE;EACN;;EACA;;EACA;EAAgB,QAAQ;;
|
|
1
|
+
{"version":3,"file":"signup.d.ts","names":[],"sources":["../src/signup-types.ts","../src/signup.ts"],"mappings":";;KAOY;EACV;EACA;;KAGU;EACV,SAAS;EACT,OAAO;EACP,MAAM;EACN,kBAAkB;EAClB,OAAO;;KAGG;EACV;EACA,cAAc;EACd;EACA,QAAQ;EACR;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV,UAAU;EACV,UAAU;EACV;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;;KAGG;EACH;EACA,eAAe,WAAW;EAC1B,WAAW,OAAO;EAClB;EACA;EACA;;KAGU,iCACV;EAGQ;EACA,aAAa;;EAGb;EACA;;KAIE;EACN;;EACA;;EACA;EAAgB,QAAQ;;EAExB;EACA,QAAQ;EACR;;EAGA;EACA,QAAQ;EACR,YAAY;;EAGZ;EACA,OAAO;EACP;EACA,QAAQ;;KAGF;EACV,gBAAgB;EAChB,YAAY,QAAQ;EACpB,SACE,YAAY,6BACZ,UAAU,mCACP,QAAQ;EACb,YAAY,WAAW,OAAO;;;;iBC3FhB,wBACd,SAAS,iCACR"}
|
package/dist/signup.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as e,C as t,E as n,O as r,S as i,a,b as o,c as s,d as c,f as l,g as u,i as d,k as f,l as p,n as m,o as h,p as g,r as _,s as v,t as y,w as b}from"./transport.js";import{n as x}from"./types.js";const S=r({city:f(),country:f(),line1:f(),line2:t(o(f())),postalCode:f(),state:f()}),C=b(r({address:t(o(S)),answers:t(l(a)),email:t(o(f())),honeypot:t(f()),name:v,participantCount:t(o(p(0))),phone:t(o(f()))})),w=i({enabled:g(),required:g()}),T=n(i({config:i({builtInFields:i({address:w,email:w,name:w,participantCount:w,phone:w}),customFields:h}),coverImageUrl:s,description:s,id:v,isActive:g(),name:v,slug:v,title:s}),e(({config:e,...t})=>({...t,customFields:e.customFields,fields:e.builtInFields}))),E=i({id:v,submittedAt:n(f(),u())}),D=b(T),O=b(E);function k(e){let t=c(e),n=m({phase:`idle`}),r=null,i=!1,a=!1,o=_({communitySlug:t.communitySlugValue,environment:t.environment,getContext:()=>({signupSlug:t.signupSlugValue}),onError:t.onError,resourceContextName:`lockerverse_signup`,sentryDsn:t.sentryDsn}),{requestJson:s}=y(t.fetchImplementation,o,t.requestTimeoutMs);return{getState:n.getState,async load(){let e={code:`signup_load_failed`,message:`Unable to load Lockerverse signup.`,operation:`load_signup`};if(i||a)throw o(new x({...e,reportable:!1}));i=!0,r=null,n.commit({phase:`loading`});try{let i;try{i=await s(`${t.apiBaseUrl}/community/${t.communitySlug}/sign-up-widgets/${t.signupSlug}`,void 0,D,e,e)}catch(e){throw e instanceof x&&n.commit({error:e,phase:`error`,recoverableSubmissionReference:null,signup:null}),e}if(!i.ok){let t=o(new x({...e,reportable:i.response.status>=500,status:i.response.status}));throw n.commit({error:t,phase:`error`,recoverableSubmissionReference:null,signup:null}),t}let a=d(i.value);return r=a,n.commit({phase:`ready`,signup:a}),a}finally{i=!1}},async submit(e,i){let c=r,l=i?.submissionReference??globalThis.crypto.randomUUID(),u={code:`signup_submit_failed`,message:`Unable to submit Lockerverse signup.`,operation:`submit_signup`};if(!c?.isActive||a)throw o(new x({...u,reportable:!1}));let f;try{f=C(e)}catch{let e=o(new x({...u,message:`Lockerverse signup input is invalid.`,reportable:!1}));throw n.commit({error:e,phase:`error`,recoverableSubmissionReference:l,signup:c}),e}a=!0,n.commit({phase:`submitting`,signup:c,submissionReference:l});try{let e=await s(`${t.apiBaseUrl}/community/${t.communitySlug}/sign-up-widgets/${t.signupSlug}/submissions`,{body:JSON.stringify({...f,submissionReference:l}),headers:{"content-type":`application/json`},method:`POST`},O,u,u);if(!e.ok)throw o(new x({...u,reportable:e.response.status>=500,status:e.response.status}));let r=d(e.value);if(r.id!==l)throw o(new x({...u,reportable:!0}));return n.commit({phase:`submitted`,signup:c,submission:r}),r}catch(e){let t=e instanceof x?e:o(new x({...u,reportable:!1}));throw n.commit({error:t,phase:`error`,recoverableSubmissionReference:l,signup:c}),t}finally{a=!1}},subscribe:n.subscribe}}export{k as createLockerverseSignup};
|
|
2
2
|
//# sourceMappingURL=signup.js.map
|
package/dist/signup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signup.js","names":[],"sources":["../src/signup-parsers.ts","../src/signup.ts"],"sourcesContent":["import {\n parseBoolean,\n parseCustomFields,\n parseNonEmptyString,\n parseOptionalNullableString,\n parseRecord,\n} from \"./parsing.ts\";\nimport type {\n LockerverseSignup,\n LockerverseSignupField,\n LockerverseSignupFields,\n LockerverseSignupSubmissionResult,\n} from \"./signup-types.ts\";\n\nfunction parseSignupField(value: unknown): LockerverseSignupField {\n const field = parseRecord(value);\n return {\n enabled: parseBoolean(field.enabled),\n required: parseBoolean(field.required),\n };\n}\n\nfunction parseSignupFields(value: unknown): LockerverseSignupFields {\n const fields = parseRecord(value);\n return {\n address: parseSignupField(fields.address),\n email: parseSignupField(fields.email),\n name: parseSignupField(fields.name),\n participantCount: parseSignupField(fields.participantCount),\n phone: parseSignupField(fields.phone),\n };\n}\n\nexport function parsePublicSignup(value: unknown): LockerverseSignup {\n const signup = parseRecord(value);\n const config = parseRecord(signup.config);\n\n return {\n coverImageUrl: parseOptionalNullableString(signup.coverImageUrl, null),\n customFields: parseCustomFields(config.customFields),\n description: parseOptionalNullableString(signup.description, null),\n fields: parseSignupFields(config.builtInFields),\n id: parseNonEmptyString(signup.id),\n isActive: parseBoolean(signup.isActive),\n name: parseNonEmptyString(signup.name),\n slug: parseNonEmptyString(signup.slug),\n title: parseOptionalNullableString(signup.title, null),\n };\n}\n\nexport function parseSignupSubmissionResult(\n value: unknown\n): LockerverseSignupSubmissionResult {\n const result = parseRecord(value);\n const submittedAt = parseNonEmptyString(result.submittedAt);\n if (Number.isNaN(Date.parse(submittedAt))) {\n throw new TypeError(\"Expected a submission timestamp.\");\n }\n return {\n id: parseNonEmptyString(result.id),\n submittedAt,\n };\n}\n","import { deepFreeze } from \"./deep-freeze.ts\";\nimport { resolveSignupEnvironment } from \"./environment.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n parsePublicSignup,\n parseSignupSubmissionResult,\n} from \"./signup-parsers.ts\";\nimport type {\n CreateLockerverseSignupOptions,\n LockerverseSignup,\n LockerverseSignupClient,\n LockerverseSignupState,\n LockerverseSignupSubmission,\n} from \"./signup-types.ts\";\nimport { createStateStore } from \"./state.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\nexport function createLockerverseSignup(\n options: CreateLockerverseSignupOptions\n): LockerverseSignupClient {\n const runtime = resolveSignupEnvironment(options);\n const stateStore = createStateStore<LockerverseSignupState>({\n phase: \"idle\",\n });\n let loadedSignup: LockerverseSignup | null = null;\n let loading = false;\n let submitting = false;\n\n const reportError = createSdkErrorReporter({\n communitySlug: runtime.communitySlugValue,\n environment: runtime.environment,\n getContext: () => ({ signupSlug: runtime.signupSlugValue }),\n onError: runtime.onError,\n resourceContextName: \"lockerverse_signup\",\n sentryDsn: runtime.sentryDsn,\n });\n\n const { fetchResponse, parseResponseJson } = createTransport(\n runtime.fetchImplementation,\n reportError\n );\n\n return {\n getState: stateStore.getState,\n async load() {\n const errorContext = {\n code: \"signup_load_failed\" as const,\n message: \"Unable to load Lockerverse signup.\",\n operation: \"load_signup\" as const,\n };\n if (loading || submitting) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n }\n\n loading = true;\n loadedSignup = null;\n stateStore.commit({ phase: \"loading\" });\n try {\n let response: Response;\n try {\n response = await fetchResponse(\n `${runtime.apiBaseUrl}/community/${runtime.communitySlug}/sign-up-widgets/${runtime.signupSlug}`,\n undefined,\n errorContext\n );\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n stateStore.commit({ error, phase: \"error\", signup: null });\n }\n throw error;\n }\n if (!response.ok) {\n const error = reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: response.status >= 500,\n status: response.status,\n })\n );\n stateStore.commit({ error, phase: \"error\", signup: null });\n throw error;\n }\n try {\n const signup = deepFreeze(\n await parseResponseJson(response, parsePublicSignup, errorContext)\n );\n loadedSignup = signup;\n stateStore.commit({ phase: \"ready\", signup });\n return signup;\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n stateStore.commit({ error, phase: \"error\", signup: null });\n }\n throw error;\n }\n } finally {\n loading = false;\n }\n },\n async submit(submission: LockerverseSignupSubmission) {\n const signup = loadedSignup;\n const errorContext = {\n code: \"signup_submit_failed\" as const,\n message: \"Unable to submit Lockerverse signup.\",\n operation: \"submit_signup\" as const,\n };\n if (!signup?.isActive || submitting) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n }\n\n submitting = true;\n stateStore.commit({ phase: \"submitting\", signup });\n try {\n const response = await fetchResponse(\n `${runtime.apiBaseUrl}/community/${runtime.communitySlug}/sign-up-widgets/${runtime.signupSlug}/submissions`,\n {\n body: JSON.stringify(submission),\n headers: { \"content-type\": \"application/json\" },\n method: \"POST\",\n },\n errorContext\n );\n if (!response.ok) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: response.status >= 500,\n status: response.status,\n })\n );\n }\n const result = deepFreeze(\n await parseResponseJson(\n response,\n parseSignupSubmissionResult,\n errorContext\n )\n );\n stateStore.commit({ phase: \"submitted\", signup, submission: result });\n return result;\n } catch (error) {\n const sdkError =\n error instanceof LockerverseSdkError\n ? error\n : reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n stateStore.commit({ error: sdkError, phase: \"error\", signup });\n throw sdkError;\n } finally {\n submitting = false;\n }\n },\n subscribe: stateStore.subscribe,\n };\n}\n"],"mappings":"4HAcA,SAAS,EAAiB,EAAwC,CAChE,IAAM,EAAQ,EAAY,CAAK,EAC/B,MAAO,CACL,QAAS,EAAa,EAAM,OAAO,EACnC,SAAU,EAAa,EAAM,QAAQ,CACvC,CACF,CAEA,SAAS,EAAkB,EAAyC,CAClE,IAAM,EAAS,EAAY,CAAK,EAChC,MAAO,CACL,QAAS,EAAiB,EAAO,OAAO,EACxC,MAAO,EAAiB,EAAO,KAAK,EACpC,KAAM,EAAiB,EAAO,IAAI,EAClC,iBAAkB,EAAiB,EAAO,gBAAgB,EAC1D,MAAO,EAAiB,EAAO,KAAK,CACtC,CACF,CAEA,SAAgB,EAAkB,EAAmC,CACnE,IAAM,EAAS,EAAY,CAAK,EAC1B,EAAS,EAAY,EAAO,MAAM,EAExC,MAAO,CAC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AM,EAAS,EACb,MAAM,EACJ,EACA,EACA,CACF,CACF,EAEA,OADA,EAAW,OAAO,CAAE,MAAO,YAAa,SAAQ,WAAY,CAAO,CAAC,EAC7D,CACT,OAAS,EAAO,CACd,IAAM,EACJ,aAAiB,EACb,EACA,EACE,IAAI,EAAoB,CACtB,GAAG,EACH,WAAY,EACd,CAAC,CACH,EAEN,MADA,EAAW,OAAO,CAAE,MAAO,EAAU,MAAO,QAAS,QAAO,CAAC,EACvD,CACR,QAAU,CACR,EAAa,EACf,CACF,EACA,UAAW,EAAW,SACxB,CACF"}
|
|
1
|
+
{"version":3,"file":"signup.js","names":[],"sources":["../src/signup-input-schema.ts","../src/signup-schemas.ts","../src/signup.ts"],"sourcesContent":["import {\n array,\n nullable,\n optional,\n parser,\n strictObject,\n string,\n} from \"valibot\";\n\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst signupAddressSchema = strictObject({\n city: string(),\n country: string(),\n line1: string(),\n line2: optional(nullable(string())),\n postalCode: string(),\n state: string(),\n});\n\nexport const parseSignupSubmission = parser(\n strictObject({\n address: optional(nullable(signupAddressSchema)),\n answers: optional(array(customFieldAnswerSchema)),\n email: optional(nullable(string())),\n honeypot: optional(string()),\n name: nonEmptyStringSchema,\n participantCount: optional(nullable(safeIntegerSchema(0))),\n phone: optional(nullable(string())),\n })\n);\n","import {\n boolean,\n isoTimestamp,\n object,\n parser,\n pipe,\n string,\n transform,\n} from \"valibot\";\n\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n} from \"./schema-helpers.ts\";\n\nconst signupFieldSchema = object({\n enabled: boolean(),\n required: boolean(),\n});\n\nexport const publicSignupSchema = pipe(\n object({\n config: object({\n builtInFields: object({\n address: signupFieldSchema,\n email: signupFieldSchema,\n name: signupFieldSchema,\n participantCount: signupFieldSchema,\n phone: signupFieldSchema,\n }),\n customFields: customFieldsSchema,\n }),\n coverImageUrl: optionalNullableStringSchema,\n description: optionalNullableStringSchema,\n id: nonEmptyStringSchema,\n isActive: boolean(),\n name: nonEmptyStringSchema,\n slug: nonEmptyStringSchema,\n title: optionalNullableStringSchema,\n }),\n transform(({ config, ...signup }) => ({\n ...signup,\n customFields: config.customFields,\n fields: config.builtInFields,\n }))\n);\n\nexport const signupSubmissionResultSchema = object({\n id: nonEmptyStringSchema,\n submittedAt: pipe(string(), isoTimestamp()),\n});\n\nexport const parsePublicSignup = parser(publicSignupSchema);\nexport const parseSignupSubmissionResult = parser(signupSubmissionResultSchema);\n","import { deepFreeze } from \"./deep-freeze.ts\";\nimport { resolveSignupEnvironment } from \"./environment.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport { parseSignupSubmission } from \"./signup-input-schema.ts\";\nimport {\n parsePublicSignup,\n parseSignupSubmissionResult,\n} from \"./signup-schemas.ts\";\nimport type {\n CreateLockerverseSignupOptions,\n LockerverseSignup,\n LockerverseSignupClient,\n LockerverseSignupState,\n LockerverseSignupSubmission,\n} from \"./signup-types.ts\";\nimport { createStateStore } from \"./state.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\nexport function createLockerverseSignup(\n options: CreateLockerverseSignupOptions\n): LockerverseSignupClient {\n const runtime = resolveSignupEnvironment(options);\n const stateStore = createStateStore<LockerverseSignupState>({\n phase: \"idle\",\n });\n let loadedSignup: LockerverseSignup | null = null;\n let loading = false;\n let submitting = false;\n\n const reportError = createSdkErrorReporter({\n communitySlug: runtime.communitySlugValue,\n environment: runtime.environment,\n getContext: () => ({ signupSlug: runtime.signupSlugValue }),\n onError: runtime.onError,\n resourceContextName: \"lockerverse_signup\",\n sentryDsn: runtime.sentryDsn,\n });\n\n const { requestJson } = createTransport(\n runtime.fetchImplementation,\n reportError,\n runtime.requestTimeoutMs\n );\n\n return {\n getState: stateStore.getState,\n async load() {\n const errorContext = {\n code: \"signup_load_failed\" as const,\n message: \"Unable to load Lockerverse signup.\",\n operation: \"load_signup\" as const,\n };\n if (loading || submitting) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n }\n\n loading = true;\n loadedSignup = null;\n stateStore.commit({ phase: \"loading\" });\n try {\n let signupResponse: Awaited<\n ReturnType<typeof requestJson<LockerverseSignup>>\n >;\n try {\n signupResponse = await requestJson(\n `${runtime.apiBaseUrl}/community/${runtime.communitySlug}/sign-up-widgets/${runtime.signupSlug}`,\n undefined,\n parsePublicSignup,\n errorContext,\n errorContext\n );\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n stateStore.commit({\n error,\n phase: \"error\",\n recoverableSubmissionReference: null,\n signup: null,\n });\n }\n throw error;\n }\n if (!signupResponse.ok) {\n const error = reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: signupResponse.response.status >= 500,\n status: signupResponse.response.status,\n })\n );\n stateStore.commit({\n error,\n phase: \"error\",\n recoverableSubmissionReference: null,\n signup: null,\n });\n throw error;\n }\n const signup = deepFreeze(signupResponse.value);\n loadedSignup = signup;\n stateStore.commit({ phase: \"ready\", signup });\n return signup;\n } finally {\n loading = false;\n }\n },\n async submit(submission: LockerverseSignupSubmission, submitOptions) {\n const signup = loadedSignup;\n const submissionReference =\n submitOptions?.submissionReference ?? globalThis.crypto.randomUUID();\n const errorContext = {\n code: \"signup_submit_failed\" as const,\n message: \"Unable to submit Lockerverse signup.\",\n operation: \"submit_signup\" as const,\n };\n if (!signup?.isActive || submitting) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n }\n\n let parsedSubmission: ReturnType<typeof parseSignupSubmission>;\n try {\n parsedSubmission = parseSignupSubmission(submission);\n } catch {\n const error = reportError(\n new LockerverseSdkError({\n ...errorContext,\n message: \"Lockerverse signup input is invalid.\",\n reportable: false,\n })\n );\n stateStore.commit({\n error,\n phase: \"error\",\n recoverableSubmissionReference: submissionReference,\n signup,\n });\n // biome-ignore lint/style/useErrorCause: Raw validation errors must not escape the SDK boundary.\n throw error;\n }\n\n submitting = true;\n stateStore.commit({ phase: \"submitting\", signup, submissionReference });\n try {\n const submissionResponse = await requestJson(\n `${runtime.apiBaseUrl}/community/${runtime.communitySlug}/sign-up-widgets/${runtime.signupSlug}/submissions`,\n {\n body: JSON.stringify({ ...parsedSubmission, submissionReference }),\n headers: { \"content-type\": \"application/json\" },\n method: \"POST\",\n },\n parseSignupSubmissionResult,\n errorContext,\n errorContext\n );\n if (!submissionResponse.ok) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: submissionResponse.response.status >= 500,\n status: submissionResponse.response.status,\n })\n );\n }\n const result = deepFreeze(submissionResponse.value);\n if (result.id !== submissionReference) {\n throw reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: true,\n })\n );\n }\n stateStore.commit({ phase: \"submitted\", signup, submission: result });\n return result;\n } catch (error) {\n const sdkError =\n error instanceof LockerverseSdkError\n ? error\n : reportError(\n new LockerverseSdkError({\n ...errorContext,\n reportable: false,\n })\n );\n stateStore.commit({\n error: sdkError,\n phase: \"error\",\n recoverableSubmissionReference: submissionReference,\n signup,\n });\n throw sdkError;\n } finally {\n submitting = false;\n }\n },\n subscribe: stateStore.subscribe,\n };\n}\n"],"mappings":"yMAeA,MAAM,EAAsB,EAAa,CACvC,KAAM,EAAO,EACb,QAAS,EAAO,EAChB,MAAO,EAAO,EACd,MAAO,EAAS,EAAS,EAAO,CAAC,CAAC,EAClC,WAAY,EAAO,EACnB,MAAO,EAAO,CAChB,CAAC,EAEY,EAAwB,EACnC,EAAa,CACX,QAAS,EAAS,EAAS,CAAmB,CAAC,EAC/C,QAAS,EAAS,EAAM,CAAuB,CAAC,EAChD,MAAO,EAAS,EAAS,EAAO,CAAC,CAAC,EAClC,SAAU,EAAS,EAAO,CAAC,EAC3B,KAAM,EACN,iBAAkB,EAAS,EAAS,EAAkB,CAAC,CAAC,CAAC,EACzD,MAAO,EAAS,EAAS,EAAO,CAAC,CAAC,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AAmB,EAAQ,WAAW,cAC/F,CACE,KAAM,KAAK,UAAU,CAAE,GAAG,EAAkB,qBAAoB,CAAC,EACjE,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,OAAQ,MACV,EACA,EACA,EACA,CACF,EACA,GAAI,CAAC,EAAmB,GACtB,MAAM,EACJ,IAAI,EAAoB,CACtB,GAAG,EACH,WAAY,EAAmB,SAAS,QAAU,IAClD,OAAQ,EAAmB,SAAS,MACtC,CAAC,CACH,EAEF,IAAM,EAAS,EAAW,EAAmB,KAAK,EAClD,GAAI,EAAO,KAAO,EAChB,MAAM,EACJ,IAAI,EAAoB,CACtB,GAAG,EACH,WAAY,EACd,CAAC,CACH,EAGF,OADA,EAAW,OAAO,CAAE,MAAO,YAAa,SAAQ,WAAY,CAAO,CAAC,EAC7D,CACT,OAAS,EAAO,CACd,IAAM,EACJ,aAAiB,EACb,EACA,EACE,IAAI,EAAoB,CACtB,GAAG,EACH,WAAY,EACd,CAAC,CACH,EAON,MANA,EAAW,OAAO,CAChB,MAAO,EACP,MAAO,QACP,+BAAgC,EAChC,QACF,CAAC,EACK,CACR,QAAU,CACR,EAAa,EACf,CACF,EACA,UAAW,EAAW,SACxB,CACF"}
|
package/dist/transport.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./types.js";const t=/\/+$/,n=new Set([`localhost`,`127.0.0.1`,`[::1]`]),r={development:{sentryDsn:`https://1977371f7bc44480935a7bc9726ca296@o1338376.ingest.sentry.io/6631829`},production:{sentryDsn:`https://c87cbc682ff0422eab5a4714acb95fd1@o1338376.ingest.sentry.io/6662564`}};function i(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Expected an object.`);return e}function a(e){if(e===`development`||e===`production`)return e;throw TypeError(`environment must be either development or production.`)}function o(e,r){if(typeof e!=`string`)throw TypeError(`apiBaseUrl must be a valid HTTP or HTTPS URL.`);let i;try{i=new URL(e)}catch{throw TypeError(`apiBaseUrl must be a valid HTTP or HTTPS URL.`)}if(i.protocol!==`http:`&&i.protocol!==`https:`)throw TypeError(`apiBaseUrl must be a valid HTTP or HTTPS URL.`);if(i.username||i.password)throw TypeError(`apiBaseUrl must not include credentials.`);if(i.search||i.hash)throw TypeError(`apiBaseUrl must not include a query or fragment.`);if(i.protocol!==`https:`&&!(r===`development`&&n.has(i.hostname)))throw TypeError(`apiBaseUrl must use HTTPS except for development loopback endpoints.`);return i.pathname=i.pathname.replace(t,``),i.toString().replace(t,``)}function s(e,t){if(typeof e!=`string`||e.trim().length===0)throw TypeError(`${t} must be a non-empty string.`);return e}function c(e,t){let n=i(e),c=n.environment;if(n.apiBaseUrl!==void 0&&c===void 0)throw TypeError(`environment is required when apiBaseUrl is provided.`);if(n.apiBaseUrl===void 0&&c===`development`)throw TypeError(`apiBaseUrl is required when environment is development.`);let l=c===void 0?`production`:a(c),u=s(n.communitySlug,`communitySlug`),d=s(n[t],t);if(n.fetch!==void 0&&typeof n.fetch!=`function`)throw TypeError(`fetch must be a function when provided.`);if(n.onError!==void 0&&typeof n.onError!=`function`)throw TypeError(`onError must be a function when provided.`);if(n.sentryDsn!==void 0&&n.sentryDsn!==null&&typeof n.sentryDsn!=`string`)throw TypeError(`sentryDsn must be a string or null when provided.`);let f=n.fetch??globalThis.fetch,p=n.apiBaseUrl===void 0?`https://portal.lockerverse.com/api`:o(n.apiBaseUrl,l),m=r[l],h=n.sentryDsn,g=h===null?null:h??m.sentryDsn;return{apiBaseUrl:p,communitySlug:encodeURIComponent(u),communitySlugValue:u,environment:l,fetchImplementation:f,onError:n.onError,resourceSlug:encodeURIComponent(d),resourceSlugValue:d,sentryDsn:g}}function l(e){let t=c(e,`signupSlug`);return{...t,signupSlug:t.resourceSlug,signupSlugValue:t.resourceSlugValue}}function u(e){if(typeof e!=`object`||!e||Object.isFrozen(e))return e;for(let t of Object.values(e))u(t);return Object.freeze(e)}function d({communitySlug:e,environment:t,getContext:n,onError:r,resourceContextName:i,sentryDsn:a}){let o=null;return function(s){try{r?.(s)}catch{}if(s.reportable&&a&&typeof window<`u`){let r=o??import(`./telemetry.js`);o=r;let c={communitySlug:e,...n()};s.status!==void 0&&(c.status=s.status),r.then(({captureSdkError:e})=>e({context:c,contextName:i,dsn:a,environment:t,error:s})).catch(()=>{o===r&&(o=null)})}return s}}function f(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Expected an object.`);return e}function p(e){if(typeof e!=`string`)throw TypeError(`Expected a string.`);return e}function m(e){let t=p(e);if(t.trim().length===0)throw TypeError(`Expected a non-empty string.`);return t}function h(e,t){return e===void 0?t:p(e)}function g(e){return e===null?null:p(e)}function _(e,t){return e===void 0?t:g(e)}function v(e){if(typeof e!=`boolean`)throw TypeError(`Expected a boolean.`);return e}function y(e,t){return e===void 0?t:v(e)}function b(e){return e!=null&&m(e).length>0}function x(e){if(!Array.isArray(e))throw TypeError(`Expected a custom field option array.`);let t=new Set,n=[];for(let r of e){let e=f(r);if(b(e.archivedAt))continue;let i=m(e.id);if(t.has(i))throw TypeError(`Expected unique custom field option IDs.`);t.add(i),n.push({id:i,label:m(e.label)})}if(n.length<2)throw TypeError(`Expected at least two active custom field options.`);return n}function S(e){if(e===void 0)return[];if(!Array.isArray(e))throw TypeError(`Expected a custom field array.`);let t=new Set,n=[];for(let r of e){let e=f(r);if(b(e.archivedAt))continue;let i=m(e.id);if(t.has(i))throw TypeError(`Expected unique custom field IDs.`);t.add(i);let a={id:i,label:m(e.label),required:v(e.required)};if(e.type===`text`||e.type===`textarea`)n.push({...a,type:e.type});else if(e.type===`radio`||e.type===`select`)n.push({...a,options:x(e.options),type:e.type});else if(e.type===`checkboxes`||e.type===`multi_select`)n.push({...a,options:x(e.options),type:e.type});else throw TypeError(`Expected a supported custom field type.`)}return n}function C(e){let t=u(e),n=new Set;return{commit(e){t=u(e);for(let e of[...n])try{e(t)}catch{}},getState(){return t},subscribe(e){n.add(e);try{e(t)}catch{}return()=>{n.delete(e)}}}}function w(t,n){async function r(r,i,a){try{return await t(r,i)}catch{let t=new e({code:a.code,message:a.message,operation:a.operation,reportable:!0});throw a.report===!1?t:n(t)}}async function i(t,r,i){try{return r(await t.json())}catch{let t=new e({code:i.code,message:i.message,operation:i.operation,reportable:!0});throw i.report===!1?t:n(t)}}return{fetchResponse:r,parseResponseJson:i}}export{m as a,_ as c,d,u as f,S as i,h as l,l as m,C as n,g as o,c as p,v as r,y as s,w as t,f as u};
|
|
1
|
+
import{n as e}from"./types.js";const t={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function n(e){return e?{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}:t}function r(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function i(e,t,n,i,a){let o=a&&`input`in a?a.input:n.value,s=a?.expected??e.expects??null,c=a?.received??r(o),l={kind:e.kind,type:e.type,input:o,expected:s,received:c,message:`Invalid ${t}: ${s?`Expected ${s} but r`:`R`}eceived ${c}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},u=e.kind===`schema`,d=a?.message??e.message??(e.reference,l.lang,void 0)??(u?(l.lang,void 0):null)??i.message??(l.lang,void 0);d!==void 0&&(l.message=typeof d==`function`?d(l):d),u&&(n.typed=!1),n.issues?n.issues.push(l):n.issues=[l]}const a=new WeakMap;function o(e){let t=a.get(e);return t||(t={version:1,vendor:`valibot`,validate(t){return e[`~run`]({value:t},n())}},a.set(e,t)),t}function s(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!==`__proto__`&&t!==`prototype`&&t!==`constructor`}function c(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}var l=class extends Error{constructor(e){super(e[0].message),this.name=`ValiError`,this.issues=e}};const u=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;function d(e,t){return{kind:`validation`,type:`check`,reference:d,async:!1,expects:null,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&i(this,`input`,e,t),e}}}function f(e){return{kind:`validation`,type:`finite`,reference:f,async:!1,expects:null,requirement:Number.isFinite,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&i(this,`finite`,e,t),e}}}function p(e){return{kind:`validation`,type:`iso_timestamp`,reference:p,async:!1,expects:null,requirement:u,message:e,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&i(this,`timestamp`,e,t),e}}}function m(e,t){return{kind:`validation`,type:`max_value`,reference:m,async:!1,expects:`<=${e instanceof Date?e.toJSON():r(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value<=this.requirement)&&i(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():r(e.value)}),e}}}function h(e,t){return{kind:`validation`,type:`min_length`,reference:h,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length<this.requirement&&i(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function g(e,t){return{kind:`validation`,type:`min_value`,reference:g,async:!1,expects:`>=${e instanceof Date?e.toJSON():r(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value>=this.requirement)&&i(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():r(e.value)}),e}}}function _(e){return{kind:`validation`,type:`non_empty`,reference:_,async:!1,expects:`!0`,message:e,"~run"(e,t){return e.typed&&e.value.length===0&&i(this,`length`,e,t,{received:`0`}),e}}}function v(e){return{kind:`validation`,type:`safe_integer`,reference:v,async:!1,expects:null,requirement:Number.isSafeInteger,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&i(this,`safe integer`,e,t),e}}}function y(e){return{kind:`transformation`,type:`transform`,reference:y,async:!1,operation:e,"~run"(e){return e.value=this.operation(e.value),e}}}const ee={abortEarly:!0};function b(e,t,n){return typeof e.fallback==`function`?e.fallback(t,n):e.fallback}function x(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function S(e,t){return{kind:`schema`,type:`array`,reference:S,expects:`Array`,async:!1,item:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){let i=n[r],a=this.item[`~run`]({value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else i(this,`type`,e,t);return e}}}function C(e){return{kind:`schema`,type:`boolean`,reference:C,expects:`boolean`,async:!1,message:e,get"~standard"(){return o(this)},"~run"(e,t){return typeof e.value==`boolean`?e.typed=!0:i(this,`type`,e,t),e}}}function w(e,t){return{kind:`schema`,type:`custom`,reference:w,expects:`unknown`,async:!1,check:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){return this.check(e.value)?e.typed=!0:i(this,`type`,e,t),e}}}function T(e,t){return{kind:`schema`,type:`literal`,reference:T,expects:r(e),async:!1,literal:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){return e.value===this.literal?e.typed=!0:i(this,`type`,e,t),e}}}function E(e,t){return{kind:`schema`,type:`loose_object`,reference:E,expects:`Object`,async:!1,entries:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let a=this.entries[r];if(r in n||(a.type===`exact_optional`||a.type===`optional`||a.type===`nullish`)&&a.default!==void 0){let i=r in n?n[r]:x(a),o=a[`~run`]({value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(a.fallback!==void 0)e.value[r]=b(a);else if(a.type!==`exact_optional`&&a.type!==`optional`&&a.type!==`nullish`&&(i(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}if(!e.issues||!t.abortEarly)for(let t in n)s(n,t)&&!(t in this.entries)&&(e.value[t]=n[t])}else i(this,`type`,e,t);return e}}}function D(e,t){return{kind:`schema`,type:`nullable`,reference:D,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return o(this)},"~run"(e,t){return e.value===null&&(this.default!==void 0&&(e.value=x(this,e,t)),e.value===null)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}}}function O(e){return{kind:`schema`,type:`number`,reference:O,expects:`number`,async:!1,message:e,get"~standard"(){return o(this)},"~run"(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:i(this,`type`,e,t),e}}}function k(e,t){return{kind:`schema`,type:`object`,reference:k,expects:`Object`,async:!1,entries:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let a=this.entries[r];if(r in n||(a.type===`exact_optional`||a.type===`optional`||a.type===`nullish`)&&a.default!==void 0){let i=r in n?n[r]:x(a),o=a[`~run`]({value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(a.fallback!==void 0)e.value[r]=b(a);else if(a.type!==`exact_optional`&&a.type!==`optional`&&a.type!==`nullish`&&(i(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}}else i(this,`type`,e,t);return e}}}function A(e,t){return{kind:`schema`,type:`optional`,reference:A,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return o(this)},"~run"(e,t){return e.value===void 0&&(this.default!==void 0&&(e.value=x(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}}}function j(e,t){return{kind:`schema`,type:`picklist`,reference:j,expects:c(e.map(r),`|`),async:!1,options:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:i(this,`type`,e,t),e}}}function M(e,t,n){return{kind:`schema`,type:`record`,reference:M,expects:`Object`,async:!1,key:e,value:t,message:n,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in n)if(s(n,r)){let i=n[r],a=this.key[`~run`]({value:r},t);if(a.issues){let o={type:`object`,origin:`key`,input:n,key:r,value:i};for(let t of a.issues)t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}let o=this.value[`~run`]({value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}(!a.typed||!o.typed)&&(e.typed=!1),a.typed&&(e.value[a.value]=o.value)}}else i(this,`type`,e,t);return e}}}function N(e,t){return{kind:`schema`,type:`strict_object`,reference:N,expects:`Object`,async:!1,entries:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let a=this.entries[r];if(r in n||(a.type===`exact_optional`||a.type===`optional`||a.type===`nullish`)&&a.default!==void 0){let i=r in n?n[r]:x(a),o=a[`~run`]({value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(a.fallback!==void 0)e.value[r]=b(a);else if(a.type!==`exact_optional`&&a.type!==`optional`&&a.type!==`nullish`&&(i(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}if(!e.issues||!t.abortEarly){for(let r in n)if(!(r in this.entries)){i(this,`key`,e,t,{input:r,expected:`never`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]});break}}}else i(this,`type`,e,t);return e}}}function P(e){return{kind:`schema`,type:`string`,reference:P,expects:`string`,async:!1,message:e,get"~standard"(){return o(this)},"~run"(e,t){return typeof e.value==`string`?e.typed=!0:i(this,`type`,e,t),e}}}function F(e){let t;if(e)for(let n of e)if(t)for(let e of n.issues)t.push(e);else t=n.issues;return t}function I(e,t){return{kind:`schema`,type:`union`,reference:I,expects:c(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,get"~standard"(){return o(this)},"~run"(e,t){let n,r,a;for(let i of this.options){let o=i[`~run`]({value:e.value},t);if(o.typed)if(o.issues)r?r.push(o):r=[o];else{n=o;break}else a?a.push(o):a=[o]}if(n)return n;if(r){if(r.length===1)return r[0];i(this,`type`,e,t,{issues:F(r)}),e.typed=!0}else if(a?.length===1)return a[0];else i(this,`type`,e,t,{issues:F(a)});return e}}}function L(){return{kind:`schema`,type:`unknown`,reference:L,expects:`unknown`,async:!1,get"~standard"(){return o(this)},"~run"(e){return e.typed=!0,e}}}function R(e,t,n){return{kind:`schema`,type:`variant`,reference:R,expects:`Object`,async:!1,key:e,options:t,message:n,get"~standard"(){return o(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){let r,a=0,o=this.key,s=[],l=(e,i)=>{for(let c of e.options){if(c.type===`variant`)l(c,new Set(i).add(c.key));else{let e=!0,l=0;for(let t of i){let r=c.entries[t];if(t in n?r[`~run`]({typed:!1,value:n[t]},ee).issues:r.type!==`exact_optional`&&r.type!==`optional`&&r.type!==`nullish`){e=!1,o!==t&&(a<l||a===l&&t in n&&!(o in n))&&(a=l,o=t,s=[]),o===t&&s.push(c.entries[t].expects);break}l++}if(e){let e=c[`~run`]({value:n},t);(!r||!r.typed&&e.typed)&&(r=e)}}if(r&&!r.issues)break}};if(l(this,new Set([this.key])),r)return r;i(this,`type`,e,t,{input:n[o],expected:c(s,`|`),path:[{type:`object`,origin:`value`,input:n,key:o,value:n[o]}]})}else i(this,`type`,e,t);return e}}}function z(e,t,r){let i=e[`~run`]({value:t},n(r));if(i.issues)throw new l(i.issues);return i.value}function B(e,t){let n=n=>z(e,n,t);return n.schema=e,n.config=t,n}function V(...e){return{...e[0],pipe:e,get"~standard"(){return o(this)},"~run"(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r[`~run`](t,n))}return t}}}const H=/\/+$/,U=new Set([`localhost`,`127.0.0.1`,`[::1]`]),W={development:{sentryDsn:`https://1977371f7bc44480935a7bc9726ca296@o1338376.ingest.sentry.io/6631829`},production:{sentryDsn:`https://c87cbc682ff0422eab5a4714acb95fd1@o1338376.ingest.sentry.io/6662564`}};function G(e,t){let n;try{n=new URL(e)}catch{throw TypeError(`apiBaseUrl must be a valid HTTP or HTTPS URL.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw TypeError(`apiBaseUrl must be a valid HTTP or HTTPS URL.`);if(n.username||n.password)throw TypeError(`apiBaseUrl must not include credentials.`);if(n.search||n.hash)throw TypeError(`apiBaseUrl must not include a query or fragment.`);if(n.protocol!==`https:`&&!(t===`development`&&U.has(n.hostname)))throw TypeError(`apiBaseUrl must use HTTPS except for development loopback endpoints.`);return n.pathname=n.pathname.replace(H,``),n.toString().replace(H,``)}function K(e,t){let n=`requestTimeoutMs must be a positive integer no greater than 2147483647.`,r=e=>V(P(`${e} must be a non-empty string.`),d(e=>e.trim().length>0,`${e} must be a non-empty string.`));try{let i=z(E({apiBaseUrl:A(P(`apiBaseUrl must be a valid HTTP or HTTPS URL.`)),communitySlug:r(`communitySlug`),environment:A(j([`development`,`production`],`environment must be either development or production.`)),fetch:A(w(e=>typeof e==`function`,`fetch must be a function when provided.`)),onError:A(w(e=>typeof e==`function`,`onError must be a function when provided.`)),requestTimeoutMs:A(V(O(n),v(n),g(1,n),m(2147483647,n))),sentryDsn:A(D(P(`sentryDsn must be a string or null when provided.`)))},`Expected an object.`),e);return{apiBaseUrl:i.apiBaseUrl,communitySlug:i.communitySlug,environment:i.environment,fetch:i.fetch,onError:i.onError,requestTimeoutMs:i.requestTimeoutMs,resourceSlugValue:z(r(t),i[t]),sentryDsn:i.sentryDsn}}catch(e){let t=e instanceof l?e.issues[0]?.message??`Invalid SDK options.`:`Invalid SDK options.`;throw TypeError(t)}}function q(e,t){let n=K(e,t),r=n.environment;if(n.apiBaseUrl!==void 0&&r===void 0)throw TypeError(`environment is required when apiBaseUrl is provided.`);if(n.apiBaseUrl===void 0&&r===`development`)throw TypeError(`apiBaseUrl is required when environment is development.`);let i=r===void 0?`production`:r,{communitySlug:a,resourceSlugValue:o}=n,s=n.fetch??globalThis.fetch,c=n.apiBaseUrl===void 0?`https://portal.lockerverse.com/api`:G(n.apiBaseUrl,i),l=W[i],u=n.sentryDsn,d=u===null?null:u??l.sentryDsn;return{apiBaseUrl:c,communitySlug:encodeURIComponent(a),communitySlugValue:a,environment:i,fetchImplementation:s,onError:n.onError,requestTimeoutMs:n.requestTimeoutMs??2e4,resourceSlug:encodeURIComponent(o),resourceSlugValue:o,sentryDsn:d}}function J(e){let t=q(e,`signupSlug`);return{...t,signupSlug:t.resourceSlug,signupSlugValue:t.resourceSlugValue}}const Y=V(P(),_(),d(e=>e.trim().length>0)),te=A(D(P()),null);function ne(e){return V(O(),v(),g(e))}const X=V(S(L()),y(e=>e.filter(e=>{let{archivedAt:t}=z(E({archivedAt:A(D(Y))}),e);return!t}))),Z=V(X,S(k({id:Y,label:Y})),h(2),d(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Expected unique custom field option IDs.`)),Q={id:Y,label:Y,required:C()},re=R(`type`,[k({...Q,type:j([`text`,`textarea`])}),k({...Q,options:Z,type:j([`radio`,`select`])}),k({...Q,options:Z,type:j([`checkboxes`,`multi_select`])})]),ie=V(A(X,[]),S(re),d(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Expected unique custom field IDs.`)),ae=k({fieldId:Y,value:I([P(),S(P())])});function $(e){if(typeof e!=`object`||!e||Object.isFrozen(e))return e;for(let t of Object.values(e))$(t);return Object.freeze(e)}function oe({communitySlug:e,environment:t,getContext:n,onError:r,resourceContextName:i,sentryDsn:a}){let o=null;return function(s){try{r?.(s)}catch{}if(s.reportable&&a&&typeof window<`u`){let r=o??import(`./telemetry.js`);o=r;let c={communitySlug:e,...n()};s.status!==void 0&&(c.status=s.status),r.then(({captureSdkError:e})=>e({context:c,contextName:i,dsn:a,environment:t,error:s})).catch(()=>{o===r&&(o=null)})}return s}}function se(e){let t=$(e),n=new Set;return{commit(e){t=$(e);for(let e of[...n])try{e(t)}catch{}},getState(){return t},subscribe(e){n.add(e);try{e(t)}catch{}return()=>{n.delete(e)}}}}function ce(t,n,r){function i(t){let r=new e({code:t.code,message:t.message,operation:t.operation,reportable:!0});return t.report===!1?r:n(r)}async function a(e,n,a,o,s){let c=new AbortController,l=n?.signal??void 0,u=()=>c.abort(l?.reason);l?.aborted?u():l?.addEventListener(`abort`,u,{once:!0});let d,f=new Promise((e,t)=>{d=()=>t(c.signal.reason??new DOMException(`The request was aborted.`,`AbortError`)),c.signal.aborted?d():c.signal.addEventListener(`abort`,d,{once:!0})}),p=setTimeout(()=>{c.abort(new DOMException(`The request timed out.`,`TimeoutError`))},r);try{let r;try{r=await Promise.race([t(e,{...n,signal:c.signal}),f])}catch{throw i(o)}if(!r.ok)return{ok:!1,response:r};try{let e=await Promise.race([r.json(),f]);return{ok:!0,response:r,value:a(e)}}catch{throw i(s)}}finally{clearTimeout(p),l?.removeEventListener(`abort`,u),d&&c.signal.removeEventListener(`abort`,d)}}return{requestJson:a}}export{y as A,A as C,M as D,V as E,N as O,k as S,j as T,T as _,ae as a,D as b,te as c,J as d,S as f,p as g,f as h,$ as i,R as j,P as k,ne as l,d as m,se as n,ie as o,C as p,oe as r,Y as s,ce as t,q as u,m as v,B as w,O as x,g as y};
|
|
2
2
|
//# sourceMappingURL=transport.js.map
|