@kiva/kv-shop 2.1.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/_virtual/_commonjs-dynamic-modules.js +6 -0
  2. package/dist/_virtual/_commonjsHelpers.js +8 -0
  3. package/dist/_virtual/_plugin-vue_export-helper.js +9 -0
  4. package/dist/_virtual/dropin.js +11 -0
  5. package/dist/_virtual/dropin2.js +4 -0
  6. package/dist/basket.js +35 -12
  7. package/dist/basketCredits.js +78 -14
  8. package/dist/basketItems.js +27 -8
  9. package/dist/basketTotals.js +38 -10
  10. package/dist/basketVerification.js +6 -6
  11. package/dist/checkoutStatus.js +52 -8
  12. package/dist/components/KvPaymentSelect.css +1 -0
  13. package/dist/components/KvPaymentSelect.js +23 -0
  14. package/dist/components/KvPaymentSelect2.js +110 -0
  15. package/dist/index.d.ts +321 -20
  16. package/dist/index.js +49 -96
  17. package/dist/managedAccount.js +62 -8
  18. package/dist/oneTimeCheckout.js +156 -12
  19. package/dist/receipt.js +143 -12
  20. package/dist/shopError.js +41 -6
  21. package/dist/shopQueries.js +82 -11
  22. package/dist/subscriptionCheckout.js +88 -7
  23. package/dist/useBraintreeDropIn.js +145 -9
  24. package/dist/util/cookie.js +11 -0
  25. package/dist/util/poll.js +17 -0
  26. package/dist/util/redirect.js +8 -0
  27. package/dist/util/visitorId.js +7 -0
  28. package/dist/validatePreCheckout.js +44 -11
  29. package/dist/vendor/braintree-web-drop-in/dist/browser/dropin.js +12223 -0
  30. package/package.json +28 -26
  31. package/dist/basket.cjs +0 -141
  32. package/dist/basket.d.ts +0 -8
  33. package/dist/basketCredits.cjs +0 -250
  34. package/dist/basketCredits.d.ts +0 -32
  35. package/dist/basketItems.cjs +0 -205
  36. package/dist/basketItems.d.ts +0 -26
  37. package/dist/basketTotals.cjs +0 -228
  38. package/dist/basketTotals.d.ts +0 -37
  39. package/dist/basketVerification.cjs +0 -41
  40. package/dist/basketVerification.d.ts +0 -10
  41. package/dist/checkoutStatus.cjs +0 -111
  42. package/dist/checkoutStatus.d.ts +0 -20
  43. package/dist/chunk-4ODZGLWK.js +0 -64
  44. package/dist/chunk-ASZJVUQ7.js +0 -72
  45. package/dist/chunk-FBF4WMN6.js +0 -49
  46. package/dist/chunk-FC4QW6QA.js +0 -106
  47. package/dist/chunk-FCAOCO7O.js +0 -17
  48. package/dist/chunk-GVVI7X2R.js +0 -196
  49. package/dist/chunk-IIN37LC7.js +0 -45
  50. package/dist/chunk-IOZ5ERDX.js +0 -121
  51. package/dist/chunk-KCUOMCSN.js +0 -58
  52. package/dist/chunk-LZ4UMRCV.js +0 -16
  53. package/dist/chunk-RQNRQ2E5.js +0 -155
  54. package/dist/chunk-SRGYGDAX.js +0 -80
  55. package/dist/chunk-TPJPGUO7.js +0 -12
  56. package/dist/chunk-UJXHTR43.js +0 -86
  57. package/dist/chunk-VZ3VDRRP.js +0 -167
  58. package/dist/chunk-Z7JRY3QE.js +0 -34
  59. package/dist/components/KvPaymentSelect.vue +0 -380
  60. package/dist/index.cjs +0 -1227
  61. package/dist/managedAccount.cjs +0 -231
  62. package/dist/managedAccount.d.ts +0 -59
  63. package/dist/oneTimeCheckout.cjs +0 -636
  64. package/dist/oneTimeCheckout.d.ts +0 -21
  65. package/dist/receipt.cjs +0 -191
  66. package/dist/receipt.d.ts +0 -16
  67. package/dist/shopError.cjs +0 -88
  68. package/dist/shopError.d.ts +0 -14
  69. package/dist/shopQueries.cjs +0 -248
  70. package/dist/shopQueries.d.ts +0 -8
  71. package/dist/subscriptionCheckout.cjs +0 -187
  72. package/dist/subscriptionCheckout.d.ts +0 -13
  73. package/dist/useBraintreeDropIn.cjs +0 -258
  74. package/dist/useBraintreeDropIn.d.ts +0 -25
  75. package/dist/validatePreCheckout.cjs +0 -218
  76. package/dist/validatePreCheckout.d.ts +0 -28
@@ -1,187 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
-
19
- // src/subscriptionCheckout.ts
20
- var subscriptionCheckout_exports = {};
21
- __export(subscriptionCheckout_exports, {
22
- checkSubscriptionStatus: () => checkSubscriptionStatus,
23
- executeNewSubscriptionCheckout: () => executeNewSubscriptionCheckout
24
- });
25
- module.exports = __toCommonJS(subscriptionCheckout_exports);
26
- var import_core = require("@apollo/client/core/core.cjs");
27
-
28
- // src/shopError.ts
29
- var ShopError = class extends Error {
30
- constructor({ code, original }, ...params) {
31
- super(...params);
32
- if (Error.captureStackTrace) {
33
- Error.captureStackTrace(this, ShopError);
34
- }
35
- this.name = "ShopError";
36
- this.code = code;
37
- this.original = original;
38
- }
39
- aggregateErrors(errors) {
40
- this.errors = errors;
41
- }
42
- };
43
- function parseShopError(error) {
44
- if (error instanceof ShopError) {
45
- return error;
46
- }
47
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
48
- const errorMessage = typeof error === "string" ? error : error?.message ?? "";
49
- if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
50
- return new ShopError({
51
- code: "paymentMethod.create.invalidMethodParameter",
52
- original: error
53
- }, "There was a problem validating your payment information. Please double-check the details and try again.");
54
- }
55
- if (errorMessage.includes("Invalid request: ")) {
56
- const finalError = errorMessage.split("Invalid request: ")[1].split("., ").map((e) => e.matchAll(/[A-Z_]+: (.*)/g))[0];
57
- const finalCode = finalError[1];
58
- const finalMessage = finalError[2];
59
- return new ShopError({
60
- code: `paymentMethod.${finalCode}`,
61
- original: error
62
- }, finalMessage);
63
- }
64
- if (errorCode === "insufficientFunds" || errorMessage.includes("There is not enough credit")) {
65
- return new ShopError({
66
- code: "shop.insufficientFunds",
67
- original: error
68
- }, "There is not enough money to complete the checkout. Please double-check the details and try again.");
69
- }
70
- if (errorCode === "shop.invalidBasketId" || errorCode === "shop.basketRequired" || errorCode === "shop.alreadyCheckedOut") {
71
- return new ShopError({
72
- code: errorCode,
73
- original: error
74
- }, "There was a problem with your basket. Please, refresh the page and try again.");
75
- }
76
- if (errorCode === "donationAmountTooLarge") {
77
- return new ShopError({
78
- code: errorCode,
79
- original: error
80
- }, errorMessage);
81
- }
82
- return new ShopError({
83
- code: "shop.unknown",
84
- original: error
85
- }, "An unknown error occurred.");
86
- }
87
-
88
- // src/subscriptionCheckout.ts
89
- async function checkSubscriptionStatus(apollo) {
90
- const { data: subsData } = await apollo.query({
91
- query: import_core.gql`query subscriptionStatus{
92
- my {
93
- id
94
- subscriptions {
95
- totalCount
96
- }
97
- autoDeposit {
98
- id
99
- isSubscriber
100
- }
101
- }
102
- }`
103
- });
104
- if (!subsData?.my?.id) {
105
- throw new ShopError({ code: "api.authenticationRequired" }, "You must be logged in to continue.");
106
- }
107
- if ((subsData?.my?.subscriptions?.totalCount ?? 0) > 0 || subsData?.my?.autoDeposit?.isSubscriber) {
108
- throw new ShopError({ code: "shop.subscriptionExists" }, "You already have an existing Monthly Good subscription. Changes can be made in your subscription settings.");
109
- }
110
- if (subsData?.my?.autoDeposit?.id) {
111
- throw new ShopError({ code: "shop.autoDepositExists" }, "You already have existing Auto Deposit settings. Changes can be made in your subscription settings.");
112
- }
113
- return true;
114
- }
115
- async function executeNewSubscriptionCheckout({
116
- amount,
117
- apollo,
118
- dayOfMonth = (/* @__PURE__ */ new Date()).getDate(),
119
- donateAmount,
120
- paymentMethod
121
- }) {
122
- const amountRegex = new RegExp(/^\d+\.\d{2}$/);
123
- if (!amountRegex.test(amount) || !amountRegex.test(donateAmount)) {
124
- throw new ShopError({
125
- code: "api.invalidMethodParameter"
126
- }, "Please check that the amount is correct and try again.");
127
- }
128
- await checkSubscriptionStatus(apollo);
129
- const { deviceData, nonce } = paymentMethod;
130
- let data;
131
- let error;
132
- try {
133
- const result = await apollo.mutate({
134
- variables: {
135
- nonce,
136
- deviceData,
137
- amount,
138
- donateAmount,
139
- dayOfMonth
140
- },
141
- mutation: import_core.gql`mutation createAutoDepositSubscription(
142
- $nonce: String!,
143
- $deviceData: String,
144
- $amount: Money!,
145
- $donateAmount: Money!,
146
- $dayOfMonth: Int!
147
- ) {
148
- my {
149
- createAutoDeposit (
150
- autoDeposit: {
151
- amount: $amount,
152
- donateAmount: $donateAmount,
153
- dayOfMonth: $dayOfMonth,
154
- },
155
- deviceData: $deviceData,
156
- paymentMethodNonce: $nonce
157
- ) {
158
- id amount donateAmount dayOfMonth status
159
- }
160
- }
161
- }`
162
- });
163
- if (result?.error || result?.errors?.length) {
164
- error = result?.error ?? result?.errors?.[0];
165
- } else {
166
- data = result?.data;
167
- }
168
- } catch (e) {
169
- error = e;
170
- }
171
- if (error) {
172
- const parsed = parseShopError(error);
173
- if (parsed?.code === "shop.unknown") {
174
- throw new ShopError({
175
- code: "shop.createAutoDepositError",
176
- original: parsed
177
- }, "There was a problem trying to setup your monthly deposit.");
178
- }
179
- throw parsed;
180
- }
181
- return data?.my?.createAutoDeposit;
182
- }
183
- // Annotate the CommonJS export names for ESM import in node:
184
- 0 && (module.exports = {
185
- checkSubscriptionStatus,
186
- executeNewSubscriptionCheckout
187
- });
@@ -1,13 +0,0 @@
1
- import { PaymentMethodPayload } from 'braintree-web-drop-in';
2
-
3
- declare function checkSubscriptionStatus(apollo: any): Promise<boolean>;
4
- interface SubscriptionCheckoutOptions {
5
- amount: string;
6
- apollo: any;
7
- dayOfMonth?: number;
8
- donateAmount: string;
9
- paymentMethod: PaymentMethodPayload;
10
- }
11
- declare function executeNewSubscriptionCheckout({ amount, apollo, dayOfMonth, donateAmount, paymentMethod, }: SubscriptionCheckoutOptions): Promise<any>;
12
-
13
- export { SubscriptionCheckoutOptions, checkSubscriptionStatus, executeNewSubscriptionCheckout };
@@ -1,258 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/useBraintreeDropIn.ts
30
- var useBraintreeDropIn_exports = {};
31
- __export(useBraintreeDropIn_exports, {
32
- default: () => useBraintreeDropIn,
33
- defaultPaymentTypes: () => defaultPaymentTypes,
34
- getClientToken: () => getClientToken
35
- });
36
- module.exports = __toCommonJS(useBraintreeDropIn_exports);
37
- var import_core = require("@apollo/client/core/core.cjs");
38
- var import_numeral = __toESM(require("numeral"), 1);
39
- var import_vue_demi = require("vue-demi");
40
-
41
- // src/shopError.ts
42
- var ShopError = class extends Error {
43
- constructor({ code, original }, ...params) {
44
- super(...params);
45
- if (Error.captureStackTrace) {
46
- Error.captureStackTrace(this, ShopError);
47
- }
48
- this.name = "ShopError";
49
- this.code = code;
50
- this.original = original;
51
- }
52
- aggregateErrors(errors) {
53
- this.errors = errors;
54
- }
55
- };
56
- function parseShopError(error) {
57
- if (error instanceof ShopError) {
58
- return error;
59
- }
60
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
61
- const errorMessage = typeof error === "string" ? error : error?.message ?? "";
62
- if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
63
- return new ShopError({
64
- code: "paymentMethod.create.invalidMethodParameter",
65
- original: error
66
- }, "There was a problem validating your payment information. Please double-check the details and try again.");
67
- }
68
- if (errorMessage.includes("Invalid request: ")) {
69
- const finalError = errorMessage.split("Invalid request: ")[1].split("., ").map((e) => e.matchAll(/[A-Z_]+: (.*)/g))[0];
70
- const finalCode = finalError[1];
71
- const finalMessage = finalError[2];
72
- return new ShopError({
73
- code: `paymentMethod.${finalCode}`,
74
- original: error
75
- }, finalMessage);
76
- }
77
- if (errorCode === "insufficientFunds" || errorMessage.includes("There is not enough credit")) {
78
- return new ShopError({
79
- code: "shop.insufficientFunds",
80
- original: error
81
- }, "There is not enough money to complete the checkout. Please double-check the details and try again.");
82
- }
83
- if (errorCode === "shop.invalidBasketId" || errorCode === "shop.basketRequired" || errorCode === "shop.alreadyCheckedOut") {
84
- return new ShopError({
85
- code: errorCode,
86
- original: error
87
- }, "There was a problem with your basket. Please, refresh the page and try again.");
88
- }
89
- if (errorCode === "donationAmountTooLarge") {
90
- return new ShopError({
91
- code: errorCode,
92
- original: error
93
- }, errorMessage);
94
- }
95
- return new ShopError({
96
- code: "shop.unknown",
97
- original: error
98
- }, "An unknown error occurred.");
99
- }
100
-
101
- // src/useBraintreeDropIn.ts
102
- var defaultPaymentTypes = ["paypal", "card", "applePay", "googlePay"];
103
- async function getClientToken(apollo) {
104
- const { data, error, errors } = await apollo.query({
105
- query: import_core.gql`query getClientToken {
106
- shop {
107
- id
108
- getClientToken(useCustomerId: true)
109
- }
110
- }`
111
- });
112
- if (error || errors?.length) {
113
- throw parseShopError(error ?? errors?.[0]);
114
- }
115
- return data?.shop?.getClientToken;
116
- }
117
- function initBraintreeDropin() {
118
- let instance;
119
- let formattedAmount = "";
120
- const paymentMethodRequestable = (0, import_vue_demi.ref)(false);
121
- function getApplePaymentRequest(amount) {
122
- return {
123
- countryCode: "US",
124
- currencyCode: "USD",
125
- // merchantCapabilities: ['supports3DS'], // TODO: confirm/update
126
- requiredBillingContactFields: ["postalAddress"],
127
- // supportedNetworks: ['amex', 'discover', 'interac', 'jcb', 'masterCard', 'visa'], // TODO: confirm/update
128
- total: {
129
- label: "Kiva",
130
- amount
131
- }
132
- };
133
- }
134
- function getGoogleTransactionInfo(amount) {
135
- return {
136
- totalPriceStatus: "FINAL",
137
- totalPrice: amount,
138
- currencyCode: "USD",
139
- countryCode: "US"
140
- };
141
- }
142
- function initDropInActions() {
143
- if (instance.isPaymentMethodRequestable()) {
144
- paymentMethodRequestable.value = true;
145
- }
146
- instance.on("paymentMethodRequestable", (event) => {
147
- paymentMethodRequestable.value = true;
148
- });
149
- instance.on("noPaymentMethodRequestable", () => {
150
- paymentMethodRequestable.value = false;
151
- });
152
- }
153
- async function initDropIn({
154
- amount,
155
- authToken,
156
- container,
157
- googlePayMerchantId,
158
- paymentTypes = [...defaultPaymentTypes],
159
- preselectVaultedPaymentMethod = true,
160
- paypalFlow = "checkout"
161
- }) {
162
- formattedAmount = (0, import_numeral.default)(amount).format("0.00");
163
- const { default: DropIn } = await import("braintree-web-drop-in");
164
- try {
165
- instance = await DropIn.create({
166
- authorization: authToken,
167
- container,
168
- dataCollector: {
169
- kount: true
170
- // Required if Kount fraud data collection is enabled
171
- },
172
- // vaultManager: true, - Useful for testing and removing payment methods easily.
173
- paymentOptionPriority: paymentTypes,
174
- preselectVaultedPaymentMethod,
175
- card: {
176
- vault: {
177
- allowVaultCardOverride: true
178
- }
179
- },
180
- paypal: {
181
- flow: paypalFlow,
182
- amount: formattedAmount,
183
- currency: "USD",
184
- buttonStyle: {
185
- // @ts-ignore
186
- color: "gold",
187
- // @ts-ignore
188
- shape: "rect",
189
- // @ts-ignore
190
- size: "responsive"
191
- }
192
- },
193
- googlePay: {
194
- googlePayVersion: 2,
195
- merchantId: googlePayMerchantId,
196
- transactionInfo: getGoogleTransactionInfo(formattedAmount),
197
- button: {
198
- allowedPaymentMethods: [{
199
- type: "CARD",
200
- // @ts-ignore
201
- parameters: {
202
- // allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], // TODO: confirm/update
203
- // allowedCardNetworks: ['AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'MASTERCARD', 'VISA'], // TODO: confirm/update
204
- billingAddressRequired: true,
205
- billingAddressParameters: {
206
- format: "FULL"
207
- }
208
- }
209
- }]
210
- }
211
- },
212
- applePay: {
213
- displayName: "Kiva",
214
- paymentRequest: getApplePaymentRequest(formattedAmount)
215
- }
216
- });
217
- initDropInActions();
218
- } catch (e) {
219
- throw new ShopError({
220
- code: "shop.braintreeDropinInitError",
221
- original: e
222
- }, "An Error has occured. Please refresh the page and try again.");
223
- }
224
- return instance;
225
- }
226
- async function requestPaymentMethod() {
227
- if (instance.isPaymentMethodRequestable()) {
228
- return instance.requestPaymentMethod();
229
- }
230
- }
231
- function updateAmount(amount) {
232
- const newAmount = (0, import_numeral.default)(amount).format("0.00");
233
- if (newAmount !== formattedAmount) {
234
- formattedAmount = newAmount;
235
- instance?.updateConfiguration("paypal", "amount", formattedAmount);
236
- instance?.updateConfiguration("googlePay", "transactionInfo", getGoogleTransactionInfo(formattedAmount));
237
- instance?.updateConfiguration?.("applePay", "paymentRequest", getApplePaymentRequest(formattedAmount));
238
- }
239
- }
240
- return {
241
- initDropIn,
242
- paymentMethodRequestable,
243
- requestPaymentMethod,
244
- updateAmount
245
- };
246
- }
247
- var instances = {};
248
- function useBraintreeDropIn(key = "default") {
249
- if (!instances[key]) {
250
- instances[key] = initBraintreeDropin();
251
- }
252
- return instances[key];
253
- }
254
- // Annotate the CommonJS export names for ESM import in node:
255
- 0 && (module.exports = {
256
- defaultPaymentTypes,
257
- getClientToken
258
- });
@@ -1,25 +0,0 @@
1
- import { Ref } from 'vue-demi';
2
- import { Dropin, PaymentMethodPayload } from 'braintree-web-drop-in';
3
-
4
- type PaymentType = 'card' | 'paypal' | 'paypalCredit' | 'venmo' | 'applePay' | 'googlePay';
5
- type PayPalFlowType = 'checkout' | 'vault';
6
- declare const defaultPaymentTypes: readonly ["paypal", "card", "applePay", "googlePay"];
7
- declare function getClientToken(apollo: any): Promise<any>;
8
- interface DropInInitOptions {
9
- amount: string | number;
10
- authToken: string;
11
- container: string | HTMLElement;
12
- googlePayMerchantId: string;
13
- paymentTypes?: PaymentType[];
14
- preselectVaultedPaymentMethod?: boolean;
15
- paypalFlow?: PayPalFlowType;
16
- }
17
- interface DropInWrapper {
18
- initDropIn: (options: DropInInitOptions) => Promise<Dropin>;
19
- paymentMethodRequestable: Ref<boolean>;
20
- requestPaymentMethod: () => Promise<PaymentMethodPayload | void>;
21
- updateAmount: (amount: string | number) => void;
22
- }
23
- declare function useBraintreeDropIn(key?: string): DropInWrapper;
24
-
25
- export { DropInInitOptions, DropInWrapper, PayPalFlowType, PaymentType, useBraintreeDropIn as default, defaultPaymentTypes, getClientToken };
@@ -1,218 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
-
19
- // src/validatePreCheckout.ts
20
- var validatePreCheckout_exports = {};
21
- __export(validatePreCheckout_exports, {
22
- validatePreCheckout: () => validatePreCheckout,
23
- validatePreCheckoutMutation: () => validatePreCheckoutMutation
24
- });
25
- module.exports = __toCommonJS(validatePreCheckout_exports);
26
- var import_core2 = require("@apollo/client/core/core.cjs");
27
-
28
- // src/basket.ts
29
- var import_core = require("@apollo/client/core/core.cjs");
30
-
31
- // src/util/cookie.ts
32
- var getCookieValue = (name) => {
33
- if (typeof document !== void 0) {
34
- return decodeURIComponent(document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`)?.pop() || "");
35
- }
36
- };
37
- var setCookieValue = (name, value, options = "") => {
38
- if (typeof document !== void 0) {
39
- document.cookie = `${name}=${encodeURIComponent(value)};${options}`;
40
- }
41
- };
42
-
43
- // src/shopError.ts
44
- var ShopError = class extends Error {
45
- constructor({ code, original }, ...params) {
46
- super(...params);
47
- if (Error.captureStackTrace) {
48
- Error.captureStackTrace(this, ShopError);
49
- }
50
- this.name = "ShopError";
51
- this.code = code;
52
- this.original = original;
53
- }
54
- aggregateErrors(errors) {
55
- this.errors = errors;
56
- }
57
- };
58
- function parseShopError(error) {
59
- if (error instanceof ShopError) {
60
- return error;
61
- }
62
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
63
- const errorMessage = typeof error === "string" ? error : error?.message ?? "";
64
- if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
65
- return new ShopError({
66
- code: "paymentMethod.create.invalidMethodParameter",
67
- original: error
68
- }, "There was a problem validating your payment information. Please double-check the details and try again.");
69
- }
70
- if (errorMessage.includes("Invalid request: ")) {
71
- const finalError = errorMessage.split("Invalid request: ")[1].split("., ").map((e) => e.matchAll(/[A-Z_]+: (.*)/g))[0];
72
- const finalCode = finalError[1];
73
- const finalMessage = finalError[2];
74
- return new ShopError({
75
- code: `paymentMethod.${finalCode}`,
76
- original: error
77
- }, finalMessage);
78
- }
79
- if (errorCode === "insufficientFunds" || errorMessage.includes("There is not enough credit")) {
80
- return new ShopError({
81
- code: "shop.insufficientFunds",
82
- original: error
83
- }, "There is not enough money to complete the checkout. Please double-check the details and try again.");
84
- }
85
- if (errorCode === "shop.invalidBasketId" || errorCode === "shop.basketRequired" || errorCode === "shop.alreadyCheckedOut") {
86
- return new ShopError({
87
- code: errorCode,
88
- original: error
89
- }, "There was a problem with your basket. Please, refresh the page and try again.");
90
- }
91
- if (errorCode === "donationAmountTooLarge") {
92
- return new ShopError({
93
- code: errorCode,
94
- original: error
95
- }, errorMessage);
96
- }
97
- return new ShopError({
98
- code: "shop.unknown",
99
- original: error
100
- }, "An unknown error occurred.");
101
- }
102
-
103
- // src/basket.ts
104
- function getBasketID() {
105
- return getCookieValue("kvbskt");
106
- }
107
- function setBasketID(basketId) {
108
- setCookieValue("kvbskt", basketId, "path=/;secure;");
109
- }
110
- async function createBasketHelper(apollo) {
111
- try {
112
- return apollo.mutate({
113
- mutation: import_core.gql`mutation createNewBasketForUser { shop { id createBasket } }`
114
- }).then(({ data }) => {
115
- const newBasketId = data.shop?.createBasket ?? null;
116
- if (newBasketId) {
117
- setBasketID(newBasketId);
118
- }
119
- });
120
- } catch (error) {
121
- throw parseShopError(error);
122
- }
123
- }
124
- var activeBasketCreationQuery = null;
125
- async function createBasket(apollo) {
126
- if (activeBasketCreationQuery) {
127
- return activeBasketCreationQuery;
128
- }
129
- activeBasketCreationQuery = createBasketHelper(apollo);
130
- return activeBasketCreationQuery;
131
- }
132
- function hasBasketExpired(error) {
133
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
134
- return ["shop.invalidBasketId", "shop.basketRequired", "shop.alreadyCheckedOut"].includes(errorCode);
135
- }
136
-
137
- // src/shopQueries.ts
138
- var watchQueries = /* @__PURE__ */ new Set();
139
- async function callShopMutation(apollo, options, maxretries = 2) {
140
- try {
141
- const result = await apollo.mutate({
142
- ...options,
143
- variables: {
144
- ...options.variables,
145
- basketId: getBasketID()
146
- },
147
- refetchQueries: options.awaitRefetchQueries ? Array.from(watchQueries) : []
148
- });
149
- if (result?.errors?.length) {
150
- const basketErrors = result?.errors.filter((err) => hasBasketExpired(err));
151
- if (basketErrors.length) {
152
- if (maxretries > 0) {
153
- await createBasket(apollo);
154
- return callShopMutation(apollo, options, maxretries - 1);
155
- }
156
- throw basketErrors[0];
157
- }
158
- if (result?.errors?.length) {
159
- throw result.errors[0];
160
- }
161
- }
162
- return result?.data;
163
- } catch (e) {
164
- throw parseShopError(e);
165
- }
166
- }
167
-
168
- // src/util/visitorId.ts
169
- function getVisitorID() {
170
- return getCookieValue("uiv");
171
- }
172
-
173
- // src/validatePreCheckout.ts
174
- var validatePreCheckoutMutation = import_core2.gql`
175
- mutation validatePreCheckout(
176
- $basketId: String,
177
- $email: String,
178
- $visitorId: String,
179
- $emailOptIn: Boolean,
180
- $inviter: InviterInput
181
- ) {
182
- shop (basketId: $basketId) {
183
- id
184
- validatePreCheckout (email: $email, visitorId: $visitorId, emailOptIn: $emailOptIn, inviter: $inviter) {
185
- error
186
- success
187
- value
188
- }
189
- }
190
- }`;
191
- async function validatePreCheckout({
192
- apollo,
193
- emailAddress,
194
- emailOptIn,
195
- valetInviter
196
- }) {
197
- const data = await callShopMutation(apollo, {
198
- mutation: validatePreCheckoutMutation,
199
- variables: {
200
- visitorId: getVisitorID(),
201
- email: emailAddress,
202
- emailOptIn,
203
- inviter: valetInviter
204
- }
205
- }, 0);
206
- const results = data?.shop?.validatePreCheckout;
207
- const errors = results.filter(({ success }) => !success).map((result) => parseShopError(result));
208
- if (errors.length) {
209
- const aggregate = new ShopError({ code: "shop.failedCheckoutValidation" });
210
- aggregate.aggregateErrors(errors);
211
- throw aggregate;
212
- }
213
- }
214
- // Annotate the CommonJS export names for ESM import in node:
215
- 0 && (module.exports = {
216
- validatePreCheckout,
217
- validatePreCheckoutMutation
218
- });