commerce-kit 0.0.5 → 0.0.7

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/LICENSE.md CHANGED
@@ -1,21 +1,201 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Your Next Store, Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Your Next Store, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1 +1,66 @@
1
1
  # commerce-kit
2
+
3
+ `commerce-kit` is a simple TypeScript library designed specifically for e-commerce applications built with Next.js. It provides a range of utilities to interact with products, categories, and orders, seamlessly integrating with Stripe for payment processing.
4
+
5
+ Built by [Your Next Store](https://yournextstore.com).
6
+
7
+ ## Features
8
+
9
+ - **Product Browsing**: Easily fetch and display products.
10
+ - **Category Management**: Manage and retrieve product categories.
11
+ - **Order Handling**: Create and manage customer orders.
12
+ - **Cart Operations**: Add products to cart and retrieve cart details.
13
+ - **Stripe Integration**: Built-in support for payment processing using Stripe.
14
+
15
+ ## Installation
16
+
17
+ Install the package via npm:
18
+
19
+ ```bash
20
+ npm install commerce-kit
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ `commerce-kit` is intended for use with Next.js applications. Here's a simple example of how to use it to fetch and display products:
26
+
27
+ ```tsx
28
+ import * as Commerce from "commerce-kit";
29
+ import { formatMoney } from "commerce-kit/currencies";
30
+ import Image from "next/image";
31
+ import Link from "next/link";
32
+
33
+ export async function ProductList() {
34
+ const products = await Commerce.productBrowse({ first: 6 });
35
+
36
+ return (
37
+ <ul>
38
+ {products.map((product) => (
39
+ <li key={product.id}>
40
+ <Link href={`/product/${product.metadata.slug}`}>
41
+ <article>
42
+ {product.images[0] && (
43
+ <Image src={product.images[0]} width={300} height={300} alt={product.name} />
44
+ )}
45
+ <h2>{product.name}</h2>
46
+ {product.default_price.unit_amount && (
47
+ <p>
48
+ {formatMoney({
49
+ amount: product.default_price.unit_amount,
50
+ currency: product.default_price.currency,
51
+ locale: "en-US",
52
+ })}
53
+ </p>
54
+ )}
55
+ </article>
56
+ </Link>
57
+ </li>
58
+ ))}
59
+ </ul>
60
+ );
61
+ }
62
+ ```
63
+
64
+ ## License
65
+
66
+ This project is licensed under the MIT License – see the [LICENSE](LICENSE.md) file for details.
@@ -0,0 +1,11 @@
1
+ type Money = {
2
+ amount: number;
3
+ currency: string;
4
+ };
5
+ declare const getStripeAmountFromDecimal: ({ amount: major, currency }: Money) => number;
6
+ declare const getDecimalFromStripeAmount: ({ amount: minor, currency }: Money) => number;
7
+ declare const formatMoney: ({ amount: minor, currency, locale, }: Money & {
8
+ locale?: string;
9
+ }) => string;
10
+
11
+ export { formatMoney, getDecimalFromStripeAmount, getStripeAmountFromDecimal };
@@ -0,0 +1 @@
1
+ function o(e,n){if(!e)throw new Error(n)}var s=e=>{o(Number.isInteger(e),"Value must be an integer")};var u=e=>(o(e.length===3,"currency needs to be a 3-letter code"),a[e.toUpperCase()]??2),m=({amount:e,currency:n})=>{let t=10**u(n);return Number.parseInt((e*t).toFixed(0),10)},i=({amount:e,currency:n})=>{s(e);let r=u(n),t=10**r;return Number.parseFloat((e/t).toFixed(r))},p=({amount:e,currency:n,locale:r="en-US"})=>{let t=i({amount:e,currency:n});return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(t)},a={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export{p as formatMoney,i as getDecimalFromStripeAmount,m as getStripeAmountFromDecimal};
package/dist/index.d.ts CHANGED
@@ -1,13 +1,12 @@
1
- import Stripe from 'stripe';
2
- import { z, TypeOf } from 'zod';
3
1
  import { CartMetadata, mapCart } from './internal.js';
4
2
  export { MappedProduct } from './internal.js';
3
+ import Stripe from 'stripe';
4
+ import { z, TypeOf } from 'zod';
5
5
 
6
- declare const findStripeAccount: () => string | Promise<string | undefined> | undefined;
7
6
  type Entity = "Product" | "Category" | "Order";
8
7
  type Provider = ({ tags, revalidate, cache, }: {
9
- tags?: string[];
10
- revalidate?: number;
8
+ tags?: NextFetchRequestConfig["tags"];
9
+ revalidate?: NextFetchRequestConfig["revalidate"];
11
10
  cache?: RequestInit["cache"];
12
11
  }) => Stripe;
13
12
  type Filter<T extends Entity> = {
@@ -23,7 +22,7 @@ type BrowseParams<T extends Entity> = {
23
22
  offset?: number;
24
23
  filter?: Filter<T>;
25
24
  };
26
- type SearchParams<T extends Entity> = {
25
+ type SearchParams<_T extends Entity> = {
27
26
  query: string;
28
27
  };
29
28
  type Cart = NonNullable<Awaited<ReturnType<typeof cartGet>>>;
@@ -481,18 +480,6 @@ declare function orderGet(orderId: string): Promise<{
481
480
  }[];
482
481
  shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
483
482
  } | null>;
484
- declare const sanitizeQueryValue: (slug: string | number | boolean) => string;
485
- declare const objectToStripeQuery: (obj: Record<string, string | number | boolean>) => string;
486
- declare const StripeClient: ({ tags, revalidate, cache, }: {
487
- tags?: string[];
488
- revalidate?: number;
489
- cache?: RequestInit["cache"];
490
- }) => Stripe;
491
- declare const provider: ({ tags, revalidate, cache, }: {
492
- tags?: string[];
493
- revalidate?: number;
494
- cache?: RequestInit["cache"];
495
- }) => Stripe;
496
483
  declare const getProductsFromCart: (metadata: CartMetadata) => (readonly [productId: string, quantity: number])[];
497
484
  type MappedCart = ReturnType<typeof mapCart>;
498
485
  declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Promise<{
@@ -684,6 +671,48 @@ declare const getAddressSchema: (tr: {
684
671
  phone?: string | null | undefined;
685
672
  }>;
686
673
  type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
674
+ declare const calculateCartTotalPossiblyWithTax: (cart: {
675
+ cart: {
676
+ amount: number;
677
+ metadata?: {
678
+ taxCalculationId?: string;
679
+ };
680
+ };
681
+ lines: Array<{
682
+ product: {
683
+ default_price?: {
684
+ unit_amount?: number | null;
685
+ };
686
+ };
687
+ quantity: number;
688
+ }>;
689
+ shippingRate?: {
690
+ fixed_amount?: {
691
+ amount?: number;
692
+ };
693
+ } | null;
694
+ }) => number;
695
+ declare const calculateCartTotalNetWithoutShipping: (cart: {
696
+ cart: {
697
+ amount: number;
698
+ metadata?: {
699
+ taxCalculationId?: string;
700
+ };
701
+ };
702
+ lines: Array<{
703
+ product: {
704
+ default_price?: {
705
+ unit_amount?: number | null;
706
+ };
707
+ };
708
+ quantity: number;
709
+ }>;
710
+ shippingRate?: {
711
+ fixed_amount?: {
712
+ amount?: number;
713
+ };
714
+ } | null;
715
+ }) => number;
687
716
  declare function cartChangeQuantity({ productId, cartId, operation, clearTaxCalculation, }: {
688
717
  productId: string;
689
718
  cartId: string;
@@ -704,12 +733,16 @@ declare function cartSaveBillingAddress({ cartId, billingAddress, }: {
704
733
  }): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
705
734
  declare function taxDefaultGet(): Promise<Stripe.Response<Stripe.Tax.Settings>>;
706
735
  declare function cartCount(metadata: CartMetadata): number;
707
- declare global {
708
- /**
709
- * ⚠️ Warning: This might be `undefined` but TypeScript doesn't have a syntax to express that.
710
- * @see https://github.com/microsoft/TypeScript/issues/36057
711
- */
712
- function __ynsFindStripeAccount(): string | undefined | Promise<string | undefined>;
713
- }
714
736
 
715
- export { type AddressSchema, type Cart, type MappedCart, type ProductsFromMetadata, type ShippingRate, StripeClient, accountGet, calculateCartTotalNet, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, categoryBrowse, fileGet, findStripeAccount, getAddressSchema, getCartWithProductsById, getProductsFromCart, objectToStripeQuery, orderGet, productBrowse, productGet, productGetById, productSearch, provider, sanitizeQueryValue, shippingBrowse, shippingGet, taxDefaultGet };
737
+ declare const StripeClient: ({ tags, revalidate, cache, }: {
738
+ tags?: NextFetchRequestConfig["tags"];
739
+ revalidate?: NextFetchRequestConfig["revalidate"];
740
+ cache?: RequestInit["cache"];
741
+ }) => Stripe;
742
+ declare const provider: ({ tags, revalidate, cache, }: {
743
+ tags?: NextFetchRequestConfig["tags"];
744
+ revalidate?: NextFetchRequestConfig["revalidate"];
745
+ cache?: RequestInit["cache"];
746
+ }) => Stripe;
747
+
748
+ export { type AddressSchema, type Cart, type MappedCart, type ProductsFromMetadata, type ShippingRate, StripeClient, accountGet, calculateCartTotalNet, calculateCartTotalNetWithoutShipping, calculateCartTotalPossiblyWithTax, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, categoryBrowse, fileGet, getAddressSchema, getCartWithProductsById, getProductsFromCart, orderGet, productBrowse, productGet, productGetById, productSearch, provider, shippingBrowse, shippingGet, taxDefaultGet };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import{revalidatePath as W,revalidateTag as b}from"next/cache";import h from"stripe";import{z as x}from"zod";import"server-only";import{z as c}from"zod";function C(t,e){if(!t)throw new Error(e)}var Q=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},P=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},O=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};function R(t){return t.toSorted((e,a)=>{let r=Number(e.metadata.order),n=Number(a.metadata.order);return Number.isNaN(r)&&Number.isNaN(n)||r===n?a.updated-e.updated:Number.isNaN(r)?1:Number.isNaN(n)?-1:r-n})}var et=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function B({default_price:t,marketing_features:e,...a}){return C(t,"Product must have a default price"),C(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(r=>r.name).filter(Boolean),metadata:et.parse(a.metadata)}}function A(t){return t.data.map(B)}function L(t){return t.filter((e,a,r)=>a===r.findIndex(n=>n.metadata.slug===e.metadata.slug))}var N=t=>!t.deleted&&t.active,$=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),G=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function j(t){let e=t.payment_method;C(typeof e!="string","Payment method is missing from cart");let a=$.parse(t.metadata),r=Object.entries(a).filter(([n])=>n.startsWith("taxBreakdown")).map(([n,o])=>{let i=G.safeParse(O(String(o)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:r}}function U({payment_method:t,latest_charge:e,...a}){C(typeof t=="object","Payment method is missing from order"),C(typeof e=="object","Latest charge is missing from order");let r=$.parse(a.metadata),n=Object.entries(r).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,i])=>{let s=G.safeParse(O(String(i)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:n,metadata:r}}var m=()=>{if(global.__ynsFindStripeAccount)return global.__ynsFindStripeAccount()},V=process.env.STRIPE_SECRET_KEY;if(!V)throw new Error("Missing STRIPE_SECRET_KEY");var y=process.env.STRIPE_CURRENCY;if(!y)throw new Error("Missing STRIPE_CURRENCY");var q=1e3;function bt({productId:t,cartId:e}){return e?k.add(l,{productId:t,cartId:e}):k.create(l,{productId:t})}function v(t){return k.get(l,{cartId:t})}function St(){return k.create(l,{})}async function Pt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let n=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),o=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:o},lines:n}}async function Rt({cartId:t,productId:e,quantity:a}){let[r,n]=await Promise.all([z(e),v(t)]);if(!r)throw new Error(`Product not found: ${e}`);if(!n)throw new Error(`Cart not found: ${t}`);if(y?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${y}`);let o=n.cart.metadata??{};a<=0?o[e]="":o[e]=a.toString();let i=M(n)+(r.default_price.unit_amount??0);try{return await S({paymentIntentId:t,data:{metadata:o,amount:i||q}})}catch(s){console.error(s)}finally{b(`cart-${t}`),W("/cart"),W("/cart-overlay")}}async function z(t){let e=await m(),a=l({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return B(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function At({slug:t}){let e=await m(),r=await l({tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:J({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(n=>!n.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return R(A(r).filter(N))}async function rt(t){let e=await m();if(t.filter?.category){let a=t.filter?.category,n=await l({tags:["product",`category-${a}`],cache:"force-cache"}).products.search({limit:100,query:J({active:!0,'metadata["category"]':a}),expand:["data.default_price"]},{stripeAccount:e});return R(L(A(n)).filter(N).slice(t.offset,t.first))}else{let r=await l({tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return R(L(A(r)).filter(N).slice(t.offset,t.first))}}async function Et(){let t=await m();return await l({tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let e=await m(),a=l({tags:["shipping",`shipping-${t}`]});try{return await a.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function vt(t){let a=(await rt({first:100})).map(n=>n.metadata.category),r=new Set(a);return Array.from(r).filter(Boolean)}async function Tt(t){let e=await m(),a=l({tags:["products","search"]}),r=Y(t.query),n=await a.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return R(A(n).filter(o=>o.active&&!o.deleted))}async function It(t){let e=await m(),a=l({tags:["files",`file-${t}`]});try{return await a.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Bt(){let t=await m(),e=l({tags:["account"]});try{let[a,r]=await Q(e.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),n=r?.settings?.branding.logo??null;return!n||typeof n=="string"?{account:r,logo:null}:{account:r,logo:n}}catch(a){if(console.error(a),a instanceof h.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function at(t){let e=await m(),a=l({tags:["order",`order-${t}`]});try{let r=await a.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return U(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Nt(t){let e=await at(t);if(!e)return null;let a=H(e.metadata),r=await Promise.all(a.map(async([i,s])=>({product:await E(i),quantity:s}))),{metadata:{shippingRateId:n}}=e,o=n&&await T(n);return{order:e,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}}var Y=t=>t.toString().replace(/"/g,'\\"'),J=t=>Object.entries(t).map(([e,a])=>`${e}:"${Y(a)}"`).join(" AND ").trim(),$t=({tags:t,revalidate:e,cache:a})=>K({next:{tags:t,revalidate:e},cache:a}),K=({cache:t,next:e}={})=>new h(V,{typescript:!0,apiVersion:"2024-06-20",httpClient:h.createFetchHttpClient((r,n)=>fetch(r,{...n,cache:t??n?.cache,next:e??n?.next})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),l=({tags:t,revalidate:e,cache:a})=>K({next:{tags:t,revalidate:e},cache:a}),E=async t=>{let e=await m(),a=l({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return B(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}},X=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],H=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,P(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),nt=async(t,e)=>{let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(X.includes(n.status))return j(n)}catch(n){if(console.error(n),n instanceof h.errors.StripeError&&n.code==="resource_missing")return null;throw n}};async function F(t){let e=H(t);return await Promise.all(e.map(async([r,n])=>({product:await E(r),quantity:n})))}var Z=async(t,e)=>{let a=await nt(t,e);if(!a)return null;let r=await F(a.metadata),{metadata:{shippingRateId:n}}=a,o=n&&await T(n);return{cart:a,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}},ot=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0,it=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function st({oldCart:t,data:e,mergedMetadata:a,lines:r}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let n=Date.now(),o=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!o||n>=o)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,p=it.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),d=r.length!==t.lines.length||r.some(u=>{let g=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==g?.product.default_price.unit_amount||u.quantity!==g?.quantity});return s&&i!==s||p||d}var qt=t=>x.object({name:x.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:x.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:x.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:x.string({required_error:t.line1Required}).min(1,t.line1Required),line2:x.string().optional().nullable().default(""),postalCode:x.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:x.string().optional().nullable().default(""),phone:x.string().optional().nullable().default(""),taxId:x.string().optional().nullable().default("")}),ct=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:r,taxId:n})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let o=await m(),i=l({tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let s=r?await T(r):null,p=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,d=await dt(),f=y==="usd"||y==="cad"?"exclusive":"inclusive",w=d.defaults.tax_behavior==="inferred_by_currency"?f:d.defaults.tax_behavior??f;return d.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y}: ${f}.`),await i.tax.calculations.create({expand:["line_items"],line_items:t.map(g=>({...g,tax_behavior:g.tax_behavior??w})),currency:y,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":w,tax_code:p??d.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:n?[{type:"eu_vat",value:n}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:o})},D={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},S=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let r=await m(),n=await Z(l,t);C(n,`Cart not found: ${t}`);let o=$.parse({...n.cart.metadata,...e.metadata}),i=await F(o),p=!a&&st({oldCart:n,data:e,mergedMetadata:o,lines:i})?await ct({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:i.map(({product:u,quantity:g})=>{if(u?.default_price.unit_amount)return{product:u.id,reference:[u.metadata.slug,u.metadata.variant].filter(Boolean).join("-"),quantity:g,amount:u.default_price.unit_amount*g,tax_behavior:u.default_price.tax_behavior==="exclusive"?"exclusive":u.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:u.tax_code?typeof u.tax_code=="string"?u.tax_code:u.tax_code.id:void 0}}).filter(Boolean)}):null,d=e.amount?e.amount.toString():null;if(p){let u=Object.fromEntries(p.tax_breakdown.map(_=>({taxType:_.tax_rate_details.tax_type,taxPercentage:_.tax_rate_details.percentage_decimal,taxAmount:_.amount})).map((_,tt)=>[`taxBreakdown${tt}`,JSON.stringify(_)]));return await l({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:p.amount_total,metadata:{...o,...d&&{netAmount:d},...D,...u,taxCalculationId:p.id,taxCalculationExp:p?.expires_at}},{stripeAccount:r})}return await l({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...d&&{netAmount:d},...a&&{...D,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:r})},k={async create(t,{productId:e,cartId:a}){let r=await m(),n=t({cache:"no-cache"});try{let o=e?await E(e):null;return await n.paymentIntents.create({currency:y,amount:o?.default_price.unit_amount||q,automatic_payment_methods:{enabled:!0},metadata:{...o&&{[o.id]:"1"}}},{stripeAccount:r})}catch(o){throw console.error(o),o}},async get(t,{cartId:e}){let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(X.includes(n.status)){let o=j(n);if(!o)return null;let i=await F(o.metadata),{metadata:{shippingRateId:s}}=o,p=s&&await T(s);return{cart:o,lines:i.map(({product:d,quantity:f})=>d?{product:d,quantity:f}:null).filter(Boolean),shippingRate:p||null}}}catch(n){if(console.error(n),n instanceof h.errors.StripeError&&n.code==="resource_missing")return null;throw n}},async add(t,{cartId:e,productId:a}){return(async({productId:n,cartId:o,operation:i,clearTaxCalculation:s})=>{let[p,d]=await Promise.all([E(n),Z(t,o)]);if(!p)throw new Error(`Product not found: ${n}`);if(!d)throw new Error(`Cart not found: ${o}`);if(y.toLowerCase()!==p.default_price.currency.toLowerCase())throw new Error(`Product currency ${p.default_price.currency} does not match cart currency ${y}`);let f=d.cart.metadata??{},g=P(f[n])+(i==="INCREASE"?1:-1);g<=0?f[n]="":f[n]=g.toString();let I=ot(d)+(p.default_price.unit_amount??0);try{return await S({paymentIntentId:o,data:{metadata:f,amount:I||q},clearTaxCalculation:s})}catch(_){console.error(_)}finally{b(`cart-${o}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+ut(t):0,ut=t=>t?t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0;async function kt({productId:t,cartId:e,operation:a,clearTaxCalculation:r}){let[n,o]=await Promise.all([z(t),v(e)]);if(!n)throw new Error(`Product not found: ${t}`);if(!o)throw new Error(`Cart not found: ${e}`);if(y?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${y}`);let i=o.cart.metadata??{},d=P(i[t])+(a==="INCREASE"?1:-1);d<=0?i[t]="":i[t]=d.toString();let f=M(o)+(n.default_price.unit_amount??0);try{return await S({paymentIntentId:e,data:{metadata:i,amount:f||q},clearTaxCalculation:r})}catch(w){console.error(w)}finally{b(`cart-${e}`)}}var Mt=async({cartId:t,taxId:e})=>{let a=await v(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(r){console.error(r)}finally{b(`cart-${t}`)}};async function Ot({cartId:t,shippingRateId:e}){let a=await v(t);if(!a)throw new Error(`Cart not found: ${t}`);let r=await T(e);if(!r)throw new Error(`Shipping rate not found: ${e}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:r})}})}catch(n){console.error(n)}finally{b(`cart-${t}`)}}async function Lt({cartId:t,billingAddress:e}){if(!await v(t))throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(r){console.error(r)}finally{b(`cart-${t}`)}}async function dt(){let t=await m();return await l({tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function jt(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,P(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{$t as StripeClient,Bt as accountGet,ot as calculateCartTotalNet,bt as cartAdd,Pt as cartAddOptimistic,kt as cartChangeQuantity,jt as cartCount,St as cartCreate,v as cartGet,Lt as cartSaveBillingAddress,Ot as cartSaveShipping,Mt as cartSaveTax,Rt as cartSetQuantity,vt as categoryBrowse,It as fileGet,m as findStripeAccount,qt as getAddressSchema,Z as getCartWithProductsById,H as getProductsFromCart,J as objectToStripeQuery,Nt as orderGet,rt as productBrowse,At as productGet,z as productGetById,Tt as productSearch,l as provider,Y as sanitizeQueryValue,Et as shippingBrowse,T as shippingGet,dt as taxDefaultGet};
1
+ import"server-only";import"server-only";import{z as c}from"zod";function _(t,e){if(!t)throw new Error(e)}var U=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},F=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var L=t=>t.toString().replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${L(a)}"`).join(" AND ").trim();function P(t){return t.toSorted((e,a)=>{let r=Number(e.metadata.order),n=Number(a.metadata.order);return Number.isNaN(r)&&Number.isNaN(n)||r===n?a.updated-e.updated:Number.isNaN(r)?1:Number.isNaN(n)?-1:r-n})}var rt=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function N({default_price:t,marketing_features:e,...a}){return _(t,"Product must have a default price"),_(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(r=>r.name).filter(Boolean),metadata:rt.parse(a.metadata)}}function A(t){return t.data.map(N)}function j(t){return t.filter((e,a,r)=>a===r.findIndex(n=>n.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,q=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),W=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Q(t){let e=t.payment_method;_(typeof e!="string","Payment method is missing from cart");let a=q.parse(t.metadata),r=Object.entries(a).filter(([n])=>n.startsWith("taxBreakdown")).map(([n,o])=>{let i=W.safeParse(F(String(o)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:r}}function V({payment_method:t,latest_charge:e,...a}){_(typeof t=="object","Payment method is missing from order"),_(typeof e=="object","Latest charge is missing from order");let r=q.parse(a.metadata),n=Object.entries(r).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,i])=>{let s=W.safeParse(F(String(i)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:n,metadata:r}}import"server-only";import{revalidatePath as Y,revalidateTag as S}from"next/cache";import C from"stripe";import{z as x}from"zod";import"server-only";var m=()=>{if(global.__ynsFindStripeAccount)return global.__ynsFindStripeAccount()};import"server-only";import K from"stripe";import"server-only";var z=process.env.STRIPE_SECRET_KEY;if(!z)throw new Error("Missing STRIPE_SECRET_KEY");var D=process.env.STRIPE_CURRENCY;if(!D)throw new Error("Missing STRIPE_CURRENCY");var g={StripeSecretKey:z,StripeCurrency:D};var at=({tags:t,revalidate:e,cache:a})=>new K(g.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((n,o)=>fetch(n,{...o,cache:a??o?.cache,next:{tags:t??o?.next?.tags,revalidate:e??o?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),p=({tags:t,revalidate:e,cache:a})=>at({tags:t,revalidate:e,cache:a});var $=1e3;function Lt({productId:t,cartId:e}){return e?k.add(p,{productId:t,cartId:e}):k.create(p,{productId:t})}function E(t){return k.get(p,{cartId:t})}function Ot(){return k.create(p,{})}async function jt({cart:t,add:e}){if(!e)return t;let a=await v(e);if(!a)return console.warn(`Product not found: ${e}`),t;let n=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),o=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:o},lines:n}}async function Qt({cartId:t,productId:e,quantity:a}){let[r,n]=await Promise.all([X(e),E(t)]);if(!r)throw new Error(`Product not found: ${e}`);if(!n)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=n.cart.metadata??{};a<=0?o[e]="":o[e]=a.toString();let i=M(n)+(r.default_price.unit_amount??0);try{return await b({paymentIntentId:t,data:{metadata:o,amount:i||$}})}catch(s){console.error(s)}finally{S(`cart-${t}`),Y("/cart"),Y("/cart-overlay")}}async function X(t){let e=await m(),a=p({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Gt({slug:t}){let e=await m(),r=await p({tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(n=>!n.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return P(A(r).filter(B))}async function nt(t){let e=await m();if(t.filter?.category){let a=t.filter?.category,n=await p({tags:["product",`category-${a}`],cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':a}),expand:["data.default_price"]},{stripeAccount:e});return P(j(A(n)).filter(B).slice(t.offset,t.first))}else{let r=await p({tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return P(j(A(r)).filter(B).slice(t.offset,t.first))}}async function Ut(){let t=await m();return await p({tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let e=await m(),a=p({tags:["shipping",`shipping-${t}`]});try{return await a.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Wt(t){let a=(await nt({first:100})).map(n=>n.metadata.category),r=new Set(a);return Array.from(r).filter(Boolean)}async function Vt(t){let e=await m(),a=p({tags:["products","search"]}),r=L(t.query),n=await a.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return P(A(n).filter(o=>o.active&&!o.deleted))}async function zt(t){let e=await m(),a=p({tags:["files",`file-${t}`]});try{return await a.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Dt(){let t=await m(),e=p({tags:["account"]});try{let[a,r]=await U(e.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),n=r?.settings?.branding.logo??null;return!n||typeof n=="string"?{account:r,logo:null}:{account:r,logo:n}}catch(a){if(console.error(a),a instanceof C.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function ot(t){let e=await m(),a=p({tags:["order",`order-${t}`]});try{let r=await a.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return V(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Kt(t){let e=await ot(t);if(!e)return null;let a=Z(e.metadata),r=await Promise.all(a.map(async([i,s])=>({product:await v(i),quantity:s}))),{metadata:{shippingRateId:n}}=e,o=n&&await T(n);return{order:e,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}}var v=async t=>{let e=await m(),a=p({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}},H=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Z=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),it=async(t,e)=>{let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(H.includes(n.status))return Q(n)}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}};async function G(t){let e=Z(t);return await Promise.all(e.map(async([r,n])=>({product:await v(r),quantity:n})))}var tt=async(t,e)=>{let a=await it(t,e);if(!a)return null;let r=await G(a.metadata),{metadata:{shippingRateId:n}}=a,o=n&&await T(n);return{cart:a,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}},st=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0,ct=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function ut({oldCart:t,data:e,mergedMetadata:a,lines:r}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let n=Date.now(),o=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!o||n>=o)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,l=ct.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),d=r.length!==t.lines.length||r.some(u=>{let y=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==y?.product.default_price.unit_amount||u.quantity!==y?.quantity});return s&&i!==s||l||d}var Yt=t=>x.object({name:x.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:x.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:x.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:x.string({required_error:t.line1Required}).min(1,t.line1Required),line2:x.string().optional().nullable().default(""),postalCode:x.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:x.string().optional().nullable().default(""),phone:x.string().optional().nullable().default(""),taxId:x.string().optional().nullable().default("")}),dt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:r,taxId:n})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let o=await m(),i=p({tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let s=r?await T(r):null,l=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,d=await lt(),f=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",h=d.defaults.tax_behavior==="inferred_by_currency"?f:d.defaults.tax_behavior??f;return d.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${f}.`),await i.tax.calculations.create({expand:["line_items"],line_items:t.map(y=>({...y,tax_behavior:y.tax_behavior??h})),currency:g.StripeCurrency,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":h,tax_code:l??d.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:n?[{type:"eu_vat",value:n}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:o})},J={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},b=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let r=await m(),n=await tt(p,t);_(n,`Cart not found: ${t}`);let o=q.parse({...n.cart.metadata,...e.metadata}),i=await G(o),l=!a&&ut({oldCart:n,data:e,mergedMetadata:o,lines:i})?await dt({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:i.map(({product:u,quantity:y})=>{if(u?.default_price.unit_amount)return{product:u.id,reference:[u.metadata.slug,u.metadata.variant].filter(Boolean).join("-"),quantity:y,amount:u.default_price.unit_amount*y,tax_behavior:u.default_price.tax_behavior==="exclusive"?"exclusive":u.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:u.tax_code?typeof u.tax_code=="string"?u.tax_code:u.tax_code.id:void 0}}).filter(Boolean)}):null,d=e.amount?e.amount.toString():null;if(l){let u=Object.fromEntries(l.tax_breakdown.map(w=>({taxType:w.tax_rate_details.tax_type,taxPercentage:w.tax_rate_details.percentage_decimal,taxAmount:w.amount})).map((w,et)=>[`taxBreakdown${et}`,JSON.stringify(w)]));return await p({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:l.amount_total,metadata:{...o,...d&&{netAmount:d},...J,...u,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}},{stripeAccount:r})}return await p({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...d&&{netAmount:d},...a&&{...J,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:r})},k={async create(t,{productId:e,cartId:a}){let r=await m(),n=t({cache:"no-cache"});try{let o=e?await v(e):null;return await n.paymentIntents.create({currency:g.StripeCurrency,amount:o?.default_price.unit_amount||$,automatic_payment_methods:{enabled:!0},metadata:{...o&&{[o.id]:"1"}}},{stripeAccount:r})}catch(o){throw console.error(o),o}},async get(t,{cartId:e}){let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(H.includes(n.status)){let o=Q(n);if(!o)return null;let i=await G(o.metadata),{metadata:{shippingRateId:s}}=o,l=s&&await T(s);return{cart:o,lines:i.map(({product:d,quantity:f})=>d?{product:d,quantity:f}:null).filter(Boolean),shippingRate:l||null}}}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}},async add(t,{cartId:e,productId:a}){return(async({productId:n,cartId:o,operation:i,clearTaxCalculation:s})=>{let[l,d]=await Promise.all([v(n),tt(t,o)]);if(!l)throw new Error(`Product not found: ${n}`);if(!d)throw new Error(`Cart not found: ${o}`);if(g.StripeCurrency.toLowerCase()!==l.default_price.currency.toLowerCase())throw new Error(`Product currency ${l.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let f=d.cart.metadata??{},y=R(f[n])+(i==="INCREASE"?1:-1);y<=0?f[n]="":f[n]=y.toString();let I=st(d)+(l.default_price.unit_amount??0);try{return await b({paymentIntentId:o,data:{metadata:f,amount:I||$},clearTaxCalculation:s})}catch(w){console.error(w)}finally{S(`cart-${o}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+pt(t):0,pt=t=>t?t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0;async function Jt({productId:t,cartId:e,operation:a,clearTaxCalculation:r}){let[n,o]=await Promise.all([X(t),E(e)]);if(!n)throw new Error(`Product not found: ${t}`);if(!o)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let i=o.cart.metadata??{},d=R(i[t])+(a==="INCREASE"?1:-1);d<=0?i[t]="":i[t]=d.toString();let f=M(o)+(n.default_price.unit_amount??0);try{return await b({paymentIntentId:e,data:{metadata:i,amount:f||$},clearTaxCalculation:r})}catch(h){console.error(h)}finally{S(`cart-${e}`)}}var Xt=async({cartId:t,taxId:e})=>{let a=await E(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await b({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(r){console.error(r)}finally{S(`cart-${t}`)}};async function Ht({cartId:t,shippingRateId:e}){let a=await E(t);if(!a)throw new Error(`Cart not found: ${t}`);let r=await T(e);if(!r)throw new Error(`Shipping rate not found: ${e}`);try{return await b({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:r})}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}}async function Zt({cartId:t,billingAddress:e}){if(!await E(t))throw new Error(`Cart not found: ${t}`);try{return await b({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(r){console.error(r)}finally{S(`cart-${t}`)}}async function lt(){let t=await m();return await p({tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function te(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{at as StripeClient,Dt as accountGet,st as calculateCartTotalNet,pt as calculateCartTotalNetWithoutShipping,M as calculateCartTotalPossiblyWithTax,Lt as cartAdd,jt as cartAddOptimistic,Jt as cartChangeQuantity,te as cartCount,Ot as cartCreate,E as cartGet,Zt as cartSaveBillingAddress,Ht as cartSaveShipping,Xt as cartSaveTax,Qt as cartSetQuantity,Wt as categoryBrowse,zt as fileGet,Yt as getAddressSchema,tt as getCartWithProductsById,Z as getProductsFromCart,Kt as orderGet,nt as productBrowse,Gt as productGet,X as productGetById,Vt as productSearch,p as provider,Ut as shippingBrowse,T as shippingGet,lt as taxDefaultGet};
@@ -1,7 +1,13 @@
1
1
  import Stripe from 'stripe';
2
2
  import { z } from 'zod';
3
3
 
4
+ declare const sanitizeQueryValue: (slug: string | number | boolean) => string;
5
+ declare const objectToStripeQuery: (obj: Record<string, string | number | boolean>) => string;
6
+
4
7
  type MappedProduct = ReturnType<typeof mapProduct>;
8
+ /**
9
+ * @internal
10
+ */
5
11
  declare function sortProducts(products: MappedProduct[]): {
6
12
  default_price: Stripe.Price;
7
13
  marketing_features: string[];
@@ -29,6 +35,26 @@ declare function sortProducts(products: MappedProduct[]): {
29
35
  updated: number;
30
36
  url: string | null;
31
37
  }[];
38
+ declare const productMetadataSchema: z.ZodObject<{
39
+ category: z.ZodOptional<z.ZodString>;
40
+ order: z.ZodOptional<z.ZodNumber>;
41
+ slug: z.ZodString;
42
+ variant: z.ZodOptional<z.ZodString>;
43
+ }, "strip", z.ZodTypeAny, {
44
+ slug: string;
45
+ category?: string | undefined;
46
+ order?: number | undefined;
47
+ variant?: string | undefined;
48
+ }, {
49
+ slug: string;
50
+ category?: string | undefined;
51
+ order?: number | undefined;
52
+ variant?: string | undefined;
53
+ }>;
54
+ type ProductMetadata = z.infer<typeof productMetadataSchema>;
55
+ /**
56
+ * @internal
57
+ */
32
58
  declare function mapProduct({ default_price, marketing_features, ...product }: Stripe.Product): {
33
59
  default_price: Stripe.Price;
34
60
  marketing_features: string[];
@@ -56,6 +82,9 @@ declare function mapProduct({ default_price, marketing_features, ...product }: S
56
82
  updated: number;
57
83
  url: string | null;
58
84
  };
85
+ /**
86
+ * @internal
87
+ */
59
88
  declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
60
89
  default_price: Stripe.Price;
61
90
  marketing_features: string[];
@@ -83,6 +112,9 @@ declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<St
83
112
  updated: number;
84
113
  url: string | null;
85
114
  }[];
115
+ /**
116
+ * @internal
117
+ */
86
118
  declare function getUniqueVariants(products: MappedProduct[]): {
87
119
  default_price: Stripe.Price;
88
120
  marketing_features: string[];
@@ -110,7 +142,13 @@ declare function getUniqueVariants(products: MappedProduct[]): {
110
142
  updated: number;
111
143
  url: string | null;
112
144
  }[];
145
+ /**
146
+ * @internal
147
+ */
113
148
  declare const isProductAvailable: (product: MappedProduct) => boolean;
149
+ /**
150
+ * @internal
151
+ */
114
152
  declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
115
153
  shippingRateId: z.ZodOptional<z.ZodString>;
116
154
  taxCalculationId: z.ZodOptional<z.ZodString>;
@@ -170,6 +208,9 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
170
208
  taxBreakdown5?: string | undefined;
171
209
  }>, z.ZodRecord<z.ZodString, z.ZodString>>;
172
210
  type CartMetadata = z.infer<typeof cartMetadataSchema>;
211
+ /**
212
+ * @internal
213
+ */
173
214
  declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
174
215
  taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
175
216
  taxPercentage: z.ZodString;
@@ -183,6 +224,9 @@ declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
183
224
  taxAmount: number;
184
225
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
185
226
  }>;
227
+ /**
228
+ * @internal
229
+ */
186
230
  declare function mapCart(cart: Stripe.PaymentIntent): {
187
231
  metadata: {
188
232
  shippingRateId?: string | undefined;
@@ -249,6 +293,9 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
249
293
  transfer_data: Stripe.PaymentIntent.TransferData | null;
250
294
  transfer_group: string | null;
251
295
  };
296
+ /**
297
+ * @internal
298
+ */
252
299
  declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.PaymentIntent): {
253
300
  payment_method: Stripe.PaymentMethod | null;
254
301
  latest_charge: Stripe.Charge | null;
@@ -316,4 +363,4 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
316
363
  transfer_group: string | null;
317
364
  };
318
365
 
319
- export { type CartMetadata, type MappedProduct, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, sortProducts };
366
+ export { type CartMetadata, type MappedProduct, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, objectToStripeQuery, sanitizeQueryValue, sortProducts };
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import{z as t}from"zod";function i(e,r){if(!e)throw new Error(r)}var p=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}};function P(e){return e.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var m=t.object({category:t.string().optional(),order:t.coerce.number().optional(),slug:t.string(),variant:t.string().optional()});function g({default_price:e,marketing_features:r,...n}){return i(e,"Product must have a default price"),i(typeof e=="object","Product default price must be an object"),{...n,default_price:e,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:m.parse(n.metadata)}}function w(e){return e.data.map(g)}function k(e){return e.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var S=e=>!e.deleted&&e.active,l=t.object({shippingRateId:t.string().optional(),taxCalculationId:t.string().optional(),taxCalculationExp:t.string().optional(),taxId:t.string().optional(),"billingAddress.city":t.string().optional(),"billingAddress.country":t.string().optional(),"billingAddress.line1":t.string().optional(),"billingAddress.line2":t.string().optional(),"billingAddress.name":t.string().optional(),"billingAddress.postalCode":t.string().optional(),"billingAddress.state":t.string().optional(),netAmount:t.string().optional(),taxBreakdown0:t.string().optional(),taxBreakdown1:t.string().optional(),taxBreakdown2:t.string().optional(),taxBreakdown3:t.string().optional(),taxBreakdown4:t.string().optional(),taxBreakdown5:t.string().optional()}).and(t.record(t.string())),c=t.object({taxType:t.string(),taxPercentage:t.string(),taxAmount:t.number()});function N(e){let r=e.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(e.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let d=c.safeParse(p(String(s)));return d.success?d.data:null}).filter(Boolean);return{...e,metadata:n,payment_method:r,taxBreakdown:a}}function B({payment_method:e,latest_charge:r,...n}){i(typeof e=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,d])=>{let u=c.safeParse(p(String(d)));return u.success?u.data:null}).filter(Boolean);return{...n,payment_method:e,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,k as getUniqueVariants,S as isProductAvailable,N as mapCart,B as mapOrder,g as mapProduct,w as mapProducts,P as sortProducts};
1
+ import"server-only";import{z as t}from"zod";function i(e,r){if(!e)throw new Error(r)}var p=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}};var m=e=>e.toString().replace(/"/g,'\\"'),b=e=>Object.entries(e).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function k(e){return e.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=t.object({category:t.string().optional(),order:t.coerce.number().optional(),slug:t.string(),variant:t.string().optional()});function f({default_price:e,marketing_features:r,...n}){return i(e,"Product must have a default price"),i(typeof e=="object","Product default price must be an object"),{...n,default_price:e,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function N(e){return e.data.map(f)}function T(e){return e.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var B=e=>!e.deleted&&e.active,l=t.object({shippingRateId:t.string().optional(),taxCalculationId:t.string().optional(),taxCalculationExp:t.string().optional(),taxId:t.string().optional(),"billingAddress.city":t.string().optional(),"billingAddress.country":t.string().optional(),"billingAddress.line1":t.string().optional(),"billingAddress.line2":t.string().optional(),"billingAddress.name":t.string().optional(),"billingAddress.postalCode":t.string().optional(),"billingAddress.state":t.string().optional(),netAmount:t.string().optional(),taxBreakdown0:t.string().optional(),taxBreakdown1:t.string().optional(),taxBreakdown2:t.string().optional(),taxBreakdown3:t.string().optional(),taxBreakdown4:t.string().optional(),taxBreakdown5:t.string().optional()}).and(t.record(t.string())),c=t.object({taxType:t.string(),taxPercentage:t.string(),taxAmount:t.number()});function h(e){let r=e.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(e.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let u=c.safeParse(p(String(s)));return u.success?u.data:null}).filter(Boolean);return{...e,metadata:n,payment_method:r,taxBreakdown:a}}function A({payment_method:e,latest_charge:r,...n}){i(typeof e=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let d=c.safeParse(p(String(u)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:e,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,T as getUniqueVariants,B as isProductAvailable,h as mapCart,A as mapOrder,f as mapProduct,N as mapProducts,b as objectToStripeQuery,m as sanitizeQueryValue,k as sortProducts};
package/package.json CHANGED
@@ -1,9 +1,18 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "commerce-kit",
4
- "version": "0.0.5",
4
+ "version": "0.0.7",
5
5
  "type": "module",
6
- "license": "MIT",
6
+ "license": "Apache-2.0",
7
+ "keywords": [
8
+ "commerce",
9
+ "ecommerce",
10
+ "shop",
11
+ "shopping",
12
+ "next.js",
13
+ "react",
14
+ "stripe"
15
+ ],
7
16
  "author": {
8
17
  "name": "Your Next Store",
9
18
  "email": "hi@yournextstore.com",
@@ -14,6 +23,10 @@
14
23
  "import": "./dist/index.js",
15
24
  "types": "./dist/index.d.ts"
16
25
  },
26
+ "./currencies": {
27
+ "import": "./dist/currencies.js",
28
+ "types": "./dist/currencies.d.ts"
29
+ },
17
30
  "./internal": {
18
31
  "import": "./dist/internal.js",
19
32
  "types": "./dist/internal.d.ts"
@@ -26,9 +39,6 @@
26
39
  "LICENSE.md"
27
40
  ],
28
41
  "sideEffects": false,
29
- "dependencies": {
30
- "server-only": "^0.0.1"
31
- },
32
42
  "devDependencies": {
33
43
  "@types/node": "^20.14.8",
34
44
  "@types/react": "npm:types-react@19.0.0-rc.1",
@@ -38,6 +48,7 @@
38
48
  "react": "^19.0.0-rc.1",
39
49
  "react-dom": "^19.0.0-rc.1",
40
50
  "rimraf": "5.0.7",
51
+ "server-only": "0.0.1",
41
52
  "stripe": "^16.5.0",
42
53
  "tsup": "8.1.0",
43
54
  "tsx": "^4.15.7",
@@ -50,6 +61,7 @@
50
61
  "next": "15.0.0-canary.96",
51
62
  "react": "19.0.0-rc-3208e73e-20240730",
52
63
  "react-dom": "19.0.0-rc-3208e73e-20240730",
64
+ "server-only": "0.0.1",
53
65
  "stripe": "^16.5.0",
54
66
  "typescript": "^5.5.4",
55
67
  "zod": "^3.23.8"