@commercus/storefront 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/dist/chunk-4FMEU3RQ.js +57 -0
- package/dist/chunk-4FMEU3RQ.js.map +1 -0
- package/dist/chunk-TTGHFREY.js +166 -0
- package/dist/chunk-TTGHFREY.js.map +1 -0
- package/dist/core-C_ZetpHp.d.ts +20 -0
- package/dist/elements.d.ts +18 -0
- package/dist/elements.js +134 -0
- package/dist/elements.js.map +1 -0
- package/dist/hooks/preact.d.ts +10 -0
- package/dist/hooks/preact.js +14 -0
- package/dist/hooks/preact.js.map +1 -0
- package/dist/hooks/react.d.ts +10 -0
- package/dist/hooks/react.js +14 -0
- package/dist/hooks/react.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/storefront-BadKsP_d.d.ts +239 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruddur B.V.
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @commercus/storefront
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The storefront API of [Commercus](https://commercus.nl), the webshop platform for small makers, as
|
|
4
|
+
one small library: the catalogue, today's prices and stock, the visitor's cart, and the hosted
|
|
5
|
+
checkout. It works in any frontend, with hooks for Preact and React and web components for plain
|
|
6
|
+
HTML. No runtime dependencies.
|
|
7
|
+
|
|
8
|
+
Payment, address and shipping happen on the platform's hosted checkout: your site never handles
|
|
9
|
+
personal or payment details, and there is nothing for it to get wrong.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @commercus/storefront
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## The client
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createStorefront, formatPrice } from "@commercus/storefront";
|
|
19
|
+
|
|
20
|
+
const shop = createStorefront({
|
|
21
|
+
apiBase: "https://api.commercus.nl",
|
|
22
|
+
shopKey: "pk_…", // the shop's public key: safe in the page
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const products = await shop.products(); // what is for sale
|
|
26
|
+
const product = await shop.product("draak"); // options, variants, images
|
|
27
|
+
const [price] = await shop.prices([variantId]); // today's price and stock, for a page built earlier
|
|
28
|
+
|
|
29
|
+
await shop.add(variantId, 1); // the cart is made on first use
|
|
30
|
+
shop.onChange((cart) => console.log(cart?.itemCount));
|
|
31
|
+
await shop.checkout(); // off to the hosted checkout
|
|
32
|
+
|
|
33
|
+
formatPrice(product.variants[0].priceGross); // "€ 12,50"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The cart's token lives in `localStorage`, per shop. A cart that expired or became an order is
|
|
37
|
+
forgotten, and the next `add` starts a new one. Every write carries an `Idempotency-Key`, so a retry
|
|
38
|
+
after a network error does not add twice. A refusal is a `StorefrontError` with `status` and
|
|
39
|
+
`detail`; `error.outOfStock` is the one to show visitors.
|
|
40
|
+
|
|
41
|
+
On the thank-you page the checkout sends the buyer back with `?order=…&token=…`:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
const order = await shop.order(id, token);
|
|
45
|
+
await shop.downloadInvoice(id, token); // the invoice PDF
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Preact and React
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
import { useCart, usePrices } from "@commercus/storefront/hooks/preact"; // or /hooks/react
|
|
52
|
+
|
|
53
|
+
function CartBadge() {
|
|
54
|
+
const { count } = useCart(shop);
|
|
55
|
+
return <a href="/winkelwagen/">🛒 {count}</a>;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`useCart(shop)` (the cart, kept in step across components, with `add`, `update`, `remove`,
|
|
60
|
+
`checkout`), `usePrices(shop, ids)`, `useProduct(shop, slug)`, `useOrder(shop, id, token)`.
|
|
61
|
+
|
|
62
|
+
## Plain HTML (Hugo, anything)
|
|
63
|
+
|
|
64
|
+
```html
|
|
65
|
+
<meta name="commercus:api" content="https://api.commercus.nl">
|
|
66
|
+
<meta name="commercus:key" content="pk_…">
|
|
67
|
+
<script type="module" src="https://esm.sh/@commercus/storefront/elements"></script>
|
|
68
|
+
|
|
69
|
+
<commercus-price variant="…">€ 12,50</commercus-price>
|
|
70
|
+
<commercus-add-to-cart variant="…">In winkelwagen</commercus-add-to-cart>
|
|
71
|
+
<commercus-cart-count></commercus-cart-count>
|
|
72
|
+
<commercus-checkout-button>Afrekenen</commercus-checkout-button>
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The elements dispatch `commercus:added` and `commercus:error` (with `detail.outOfStock`).
|
|
76
|
+
|
|
77
|
+
## A shop of your own
|
|
78
|
+
|
|
79
|
+
The [storefront template](https://github.com/commercus/storefront-template) is a complete shop on
|
|
80
|
+
this library (Astro, static, for any S3-style hosting): fork it and make it yours.
|
|
81
|
+
|
|
82
|
+
## Developing
|
|
83
|
+
|
|
84
|
+
`npm test`, `npm run typecheck`, `npm run build`. The API's types in `src/generated/` are generated
|
|
85
|
+
from `api/storefront.yaml`: `npm run sync-api` fetches the current spec and regenerates them; CI fails
|
|
86
|
+
when they are out of step. Releases: add a changeset (`npm run changeset`); a version tag publishes
|
|
87
|
+
to npm with provenance.
|
|
88
|
+
|
|
89
|
+
MIT licensed.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// src/hooks/core.ts
|
|
2
|
+
function makeHooks({ useState, useEffect }) {
|
|
3
|
+
function useAsync(load, key) {
|
|
4
|
+
const [state, setState] = useState({ data: void 0, error: void 0, loading: true });
|
|
5
|
+
useEffect(() => {
|
|
6
|
+
let current = true;
|
|
7
|
+
setState({ data: void 0, error: void 0, loading: true });
|
|
8
|
+
load().then(
|
|
9
|
+
(data) => current && setState({ data, error: void 0, loading: false }),
|
|
10
|
+
(error) => current && setState({ data: void 0, error, loading: false })
|
|
11
|
+
);
|
|
12
|
+
return () => {
|
|
13
|
+
current = false;
|
|
14
|
+
};
|
|
15
|
+
}, [key]);
|
|
16
|
+
return state;
|
|
17
|
+
}
|
|
18
|
+
function useCart(storefront) {
|
|
19
|
+
const [cart, setCart] = useState(storefront.cartSnapshot());
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
const off = storefront.onChange(setCart);
|
|
22
|
+
storefront.cart().then(setCart, () => setCart(null));
|
|
23
|
+
return off;
|
|
24
|
+
}, [storefront]);
|
|
25
|
+
return {
|
|
26
|
+
cart,
|
|
27
|
+
loading: cart === void 0,
|
|
28
|
+
count: cart?.itemCount ?? 0,
|
|
29
|
+
add: storefront.add,
|
|
30
|
+
update: storefront.update,
|
|
31
|
+
remove: storefront.remove,
|
|
32
|
+
checkout: storefront.checkout
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function usePrices(storefront, variantIds) {
|
|
36
|
+
return useAsync(
|
|
37
|
+
() => storefront.prices(variantIds).then((prices) => Object.fromEntries(prices.map((p) => [p.id, p]))),
|
|
38
|
+
[...variantIds].sort().join(",")
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
function useProduct(storefront, slug) {
|
|
42
|
+
return useAsync(() => storefront.product(slug), slug);
|
|
43
|
+
}
|
|
44
|
+
function useOrder(storefront, id, token) {
|
|
45
|
+
return useAsync(async () => {
|
|
46
|
+
if (!id || !token) throw new Error("No order in the address");
|
|
47
|
+
storefront.forgetCart();
|
|
48
|
+
return storefront.order(id, token);
|
|
49
|
+
}, `${id}:${token}`);
|
|
50
|
+
}
|
|
51
|
+
return { useCart, usePrices, useProduct, useOrder };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export {
|
|
55
|
+
makeHooks
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=chunk-4FMEU3RQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/core.ts"],"sourcesContent":["import type { CartSnapshot, Storefront } from \"../storefront.js\";\nimport type { Cart, Order, Product, VariantPrice } from \"../types.js\";\n\n/** The two hooks the bindings need; Preact and React both have them with the same shape. */\nexport interface HookRuntime {\n useState<T>(initial: T | (() => T)): [T, (value: T) => void];\n useEffect(effect: () => void | (() => void), deps?: unknown[]): void;\n}\n\nexport interface AsyncState<T> {\n data: T | undefined;\n error: unknown;\n loading: boolean;\n}\n\nexport interface CartState {\n /** `undefined` while loading, `null` when the visitor has no cart. */\n cart: CartSnapshot;\n loading: boolean;\n /** Item count, for a header badge. */\n count: number;\n add: Storefront[\"add\"];\n update: Storefront[\"update\"];\n remove: Storefront[\"remove\"];\n checkout: Storefront[\"checkout\"];\n}\n\nexport function makeHooks({ useState, useEffect }: HookRuntime) {\n /** Runs `load` when `key` changes; the state of the latest call. */\n function useAsync<T>(load: () => Promise<T>, key: string): AsyncState<T> {\n const [state, setState] = useState<AsyncState<T>>({ data: undefined, error: undefined, loading: true });\n useEffect(() => {\n let current = true;\n setState({ data: undefined, error: undefined, loading: true });\n load().then(\n (data) => current && setState({ data, error: undefined, loading: false }),\n (error: unknown) => current && setState({ data: undefined, error, loading: false }),\n );\n return () => {\n current = false;\n };\n }, [key]);\n return state;\n }\n\n /** The visitor's cart, kept up to date across every component that uses it. */\n function useCart(storefront: Storefront): CartState {\n const [cart, setCart] = useState<CartSnapshot>(storefront.cartSnapshot());\n useEffect(() => {\n const off = storefront.onChange(setCart);\n storefront.cart().then(setCart, () => setCart(null));\n return off;\n }, [storefront]);\n return {\n cart,\n loading: cart === undefined,\n count: cart?.itemCount ?? 0,\n add: storefront.add,\n update: storefront.update,\n remove: storefront.remove,\n checkout: storefront.checkout,\n };\n }\n\n /** Today's price and stock of variants, by id. */\n function usePrices(storefront: Storefront, variantIds: string[]): AsyncState<Record<string, VariantPrice>> {\n return useAsync(\n () => storefront.prices(variantIds).then((prices) => Object.fromEntries(prices.map((p) => [p.id, p]))),\n [...variantIds].sort().join(\",\"),\n );\n }\n\n function useProduct(storefront: Storefront, slug: string): AsyncState<Product> {\n return useAsync(() => storefront.product(slug), slug);\n }\n\n /** The order on the thank-you page; the cart is forgotten, as it became this order. */\n function useOrder(storefront: Storefront, id: string | null, token: string | null): AsyncState<Order> {\n return useAsync(async () => {\n if (!id || !token) throw new Error(\"No order in the address\");\n storefront.forgetCart();\n return storefront.order(id, token);\n }, `${id}:${token}`);\n }\n\n return { useCart, usePrices, useProduct, useOrder };\n}\n\nexport type { Cart };\n"],"mappings":";AA2BO,SAAS,UAAU,EAAE,UAAU,UAAU,GAAgB;AAE9D,WAAS,SAAY,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AC7E,WAAO,SAAS,MAAM,WAAW,QAAQ,IAAI,GAAG,IAAI;AAAA,EACtD;AAGA,WAAS,SAAS,YAAwB,IAAmB,OAAyC;AACpG,WAAO,SAAS,YAAY;AAC1B,UAAI,CAAC,MAAM,CAAC,MAAO,OAAM,IAAI,MAAM,yBAAyB;AAC5D,iBAAW,WAAW;AACtB,aAAO,WAAW,MAAM,IAAI,KAAK;AAAA,IACnC,GAAG,GAAG,EAAE,IAAI,KAAK,EAAE;AAAA,EACrB;AAEA,SAAO,EAAE,SAAS,WAAW,YAAY,SAAS;AACpD;","names":[]}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var StorefrontError = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
detail;
|
|
5
|
+
constructor(status, detail) {
|
|
6
|
+
super(detail ? `${status}: ${detail}` : `Storefront API answered ${status}`);
|
|
7
|
+
this.name = "StorefrontError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.detail = detail;
|
|
10
|
+
}
|
|
11
|
+
/** Not enough stock for what was asked. */
|
|
12
|
+
get outOfStock() {
|
|
13
|
+
return this.status === 409;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/storefront.ts
|
|
18
|
+
function browserStorage() {
|
|
19
|
+
try {
|
|
20
|
+
return typeof window === "undefined" ? null : window.localStorage;
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function memoryStorage() {
|
|
26
|
+
const values = /* @__PURE__ */ new Map();
|
|
27
|
+
return {
|
|
28
|
+
getItem: (key) => values.get(key) ?? null,
|
|
29
|
+
setItem: (key, value) => void values.set(key, value),
|
|
30
|
+
removeItem: (key) => void values.delete(key)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
var newKey = () => typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
|
|
34
|
+
function createStorefront(options) {
|
|
35
|
+
const apiBase = options.apiBase.replace(/\/+$/, "");
|
|
36
|
+
const shopKey = options.shopKey;
|
|
37
|
+
const doFetch = options.fetch ?? ((...args) => fetch(...args));
|
|
38
|
+
const storage = (options.storage === void 0 ? browserStorage() : options.storage) ?? memoryStorage();
|
|
39
|
+
const cartKey = `commercus-cart:${shopKey}`;
|
|
40
|
+
let snapshot;
|
|
41
|
+
let loading;
|
|
42
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
43
|
+
async function request(method, path, body, headers) {
|
|
44
|
+
const response = await doFetch(apiBase + path, {
|
|
45
|
+
method,
|
|
46
|
+
headers: {
|
|
47
|
+
"X-Shop-Key": shopKey,
|
|
48
|
+
...body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
49
|
+
...headers
|
|
50
|
+
},
|
|
51
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
52
|
+
});
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
const problem = await response.json().catch(() => ({}));
|
|
55
|
+
throw new StorefrontError(response.status, problem.detail);
|
|
56
|
+
}
|
|
57
|
+
return response.status === 204 ? null : await response.json();
|
|
58
|
+
}
|
|
59
|
+
function settle(cart) {
|
|
60
|
+
snapshot = cart;
|
|
61
|
+
if (cart) storage.setItem(cartKey, cart.token);
|
|
62
|
+
else storage.removeItem(cartKey);
|
|
63
|
+
listeners.forEach((listener) => listener(cart));
|
|
64
|
+
return cart;
|
|
65
|
+
}
|
|
66
|
+
async function load() {
|
|
67
|
+
const token = storage.getItem(cartKey);
|
|
68
|
+
if (!token) return settle(null);
|
|
69
|
+
try {
|
|
70
|
+
const cart = await request("GET", `/v1/carts/${encodeURIComponent(token)}`);
|
|
71
|
+
return settle(cart.status === "ACTIVE" ? cart : null);
|
|
72
|
+
} catch (e) {
|
|
73
|
+
if (e instanceof StorefrontError && e.status === 404) return settle(null);
|
|
74
|
+
throw e;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function current(create) {
|
|
78
|
+
const cart = snapshot === void 0 ? await storefront.cart() : snapshot;
|
|
79
|
+
if (cart || !create) return cart;
|
|
80
|
+
return settle(await request("POST", "/v1/carts", void 0, { "Idempotency-Key": newKey() }));
|
|
81
|
+
}
|
|
82
|
+
const storefront = {
|
|
83
|
+
apiBase,
|
|
84
|
+
shopKey,
|
|
85
|
+
shop: () => request("GET", "/v1/shop"),
|
|
86
|
+
products: (opts) => request("GET", "/v1/products" + (opts?.category ? `?category=${encodeURIComponent(opts.category)}` : "")),
|
|
87
|
+
product: (slug) => request("GET", `/v1/products/${encodeURIComponent(slug)}`),
|
|
88
|
+
categories: () => request("GET", "/v1/categories"),
|
|
89
|
+
prices: (ids) => ids.length === 0 ? Promise.resolve([]) : request("GET", "/v1/variants?" + [...new Set(ids)].map((id) => `id=${encodeURIComponent(id)}`).join("&")),
|
|
90
|
+
cart(opts) {
|
|
91
|
+
if (opts?.refresh || snapshot === void 0) {
|
|
92
|
+
loading ??= load().finally(() => {
|
|
93
|
+
loading = void 0;
|
|
94
|
+
});
|
|
95
|
+
return loading;
|
|
96
|
+
}
|
|
97
|
+
return Promise.resolve(snapshot);
|
|
98
|
+
},
|
|
99
|
+
cartSnapshot: () => snapshot,
|
|
100
|
+
onChange(listener) {
|
|
101
|
+
listeners.add(listener);
|
|
102
|
+
return () => listeners.delete(listener);
|
|
103
|
+
},
|
|
104
|
+
async add(variantId, quantity = 1) {
|
|
105
|
+
let cart = await current(true);
|
|
106
|
+
try {
|
|
107
|
+
cart = await request("POST", `/v1/carts/${cart.token}/items`, { variantId, quantity }, { "Idempotency-Key": newKey() });
|
|
108
|
+
} catch (e) {
|
|
109
|
+
if (!(e instanceof StorefrontError) || e.status !== 404) throw e;
|
|
110
|
+
settle(null);
|
|
111
|
+
const fresh = await current(true);
|
|
112
|
+
cart = await request("POST", `/v1/carts/${fresh.token}/items`, { variantId, quantity }, { "Idempotency-Key": newKey() });
|
|
113
|
+
}
|
|
114
|
+
return settle(cart);
|
|
115
|
+
},
|
|
116
|
+
async update(lineId, quantity) {
|
|
117
|
+
const cart = await current(false);
|
|
118
|
+
if (!cart) return null;
|
|
119
|
+
return settle(await request("PATCH", `/v1/carts/${cart.token}/items/${encodeURIComponent(lineId)}`, { quantity }));
|
|
120
|
+
},
|
|
121
|
+
remove: (lineId) => storefront.update(lineId, 0),
|
|
122
|
+
async checkout(opts) {
|
|
123
|
+
const cart = await current(false);
|
|
124
|
+
if (!cart) throw new StorefrontError(404, "There is no cart to check out");
|
|
125
|
+
const { checkoutUrl } = await request("POST", `/v1/carts/${cart.token}/checkout`);
|
|
126
|
+
if (opts?.navigate !== false && typeof window !== "undefined") window.location.assign(checkoutUrl);
|
|
127
|
+
return checkoutUrl;
|
|
128
|
+
},
|
|
129
|
+
forgetCart: () => void settle(null),
|
|
130
|
+
order: (id, token) => request("GET", `/v1/orders/${encodeURIComponent(id)}?token=${encodeURIComponent(token)}`),
|
|
131
|
+
async invoice(id, token) {
|
|
132
|
+
const response = await doFetch(`${apiBase}/v1/orders/${encodeURIComponent(id)}/invoice?token=${encodeURIComponent(token)}`, {
|
|
133
|
+
headers: { "X-Shop-Key": shopKey }
|
|
134
|
+
});
|
|
135
|
+
if (!response.ok) throw new StorefrontError(response.status);
|
|
136
|
+
return response.blob();
|
|
137
|
+
},
|
|
138
|
+
async downloadInvoice(id, token, filename = "factuur.pdf") {
|
|
139
|
+
const url = URL.createObjectURL(await storefront.invoice(id, token));
|
|
140
|
+
const link = Object.assign(document.createElement("a"), { href: url, download: filename });
|
|
141
|
+
document.body.append(link);
|
|
142
|
+
link.click();
|
|
143
|
+
link.remove();
|
|
144
|
+
URL.revokeObjectURL(url);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
return storefront;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/format.ts
|
|
151
|
+
var formats = /* @__PURE__ */ new Map();
|
|
152
|
+
function formatPrice(amount, locale = "nl-NL") {
|
|
153
|
+
let format = formats.get(locale);
|
|
154
|
+
if (!format) {
|
|
155
|
+
format = new Intl.NumberFormat(locale, { style: "currency", currency: "EUR" });
|
|
156
|
+
formats.set(locale, format);
|
|
157
|
+
}
|
|
158
|
+
return format.format(Number(amount));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export {
|
|
162
|
+
StorefrontError,
|
|
163
|
+
createStorefront,
|
|
164
|
+
formatPrice
|
|
165
|
+
};
|
|
166
|
+
//# sourceMappingURL=chunk-TTGHFREY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/storefront.ts","../src/format.ts"],"sourcesContent":["/**\n * An answer of the storefront API that is not a success. `status` is the HTTP status; `detail` the\n * API's explanation (in English, for developers: show your own text to visitors).\n *\n * Statuses worth handling: 409 (not enough stock, or the cart was checked out), 404 (an unknown or\n * expired cart, product or order), 422 (a variant that is not for sale, or an Idempotency-Key reused\n * for another request).\n */\nexport class StorefrontError extends Error {\n readonly status: number;\n readonly detail: string | undefined;\n\n constructor(status: number, detail?: string) {\n super(detail ? `${status}: ${detail}` : `Storefront API answered ${status}`);\n this.name = \"StorefrontError\";\n this.status = status;\n this.detail = detail;\n }\n\n /** Not enough stock for what was asked. */\n get outOfStock(): boolean {\n return this.status === 409;\n }\n}\n","import { StorefrontError } from \"./errors.js\";\nimport type { Cart, Category, Order, Product, ProductSummary, Shop, VariantPrice } from \"./types.js\";\n\n/** Where the cart's token is kept; `localStorage` by default. */\nexport interface TokenStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport interface StorefrontOptions {\n /** The API, e.g. `https://api.commercus.nl`. */\n apiBase: string;\n /** The shop's public key, `pk_…`: safe in a page, it identifies the shop and grants nothing more. */\n shopKey: string;\n /** Where the cart token lives; `null` keeps it in memory only (tests, server-side rendering). */\n storage?: TokenStorage | null;\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/** The cart as last seen: `undefined` before the first look, `null` when the visitor has none. */\nexport type CartSnapshot = Cart | null | undefined;\n\nexport interface Storefront {\n readonly apiBase: string;\n readonly shopKey: string;\n\n shop(): Promise<Shop>;\n /** The products for sale, by title; optionally those in one category. */\n products(options?: { category?: string }): Promise<ProductSummary[]>;\n product(slug: string): Promise<Product>;\n categories(): Promise<Category[]>;\n /** Today's price and stock of variants, for a page built earlier. Unknown ids are left out. */\n prices(variantIds: string[]): Promise<VariantPrice[]>;\n\n /** The visitor's cart, or `null` when there is none (yet). Fetched once, then kept up to date. */\n cart(options?: { refresh?: boolean }): Promise<Cart | null>;\n /** The cart as last seen, synchronously; for hooks and components. */\n cartSnapshot(): CartSnapshot;\n /** Calls `listener` after every change of the cart; returns the unsubscribe. */\n onChange(listener: (cart: Cart | null) => void): () => void;\n /** Adds `quantity` of a variant, on its line if the cart has one; makes the cart on first use. */\n add(variantId: string, quantity?: number): Promise<Cart>;\n /** Sets a line's quantity; 0 removes the line. */\n update(lineId: string, quantity: number): Promise<Cart | null>;\n remove(lineId: string): Promise<Cart | null>;\n /**\n * Starts the platform's hosted checkout for the cart and, in a browser, goes there: payment and\n * personal details never touch the site. Returns the checkout's address.\n */\n checkout(options?: { navigate?: boolean }): Promise<string>;\n /** Forgets the cart, e.g. on the thank-you page: the next `add` starts a new one. */\n forgetCart(): void;\n\n /** The order the hosted checkout sent the buyer back with (`?order=…&token=…`). */\n order(id: string, token: string): Promise<Order>;\n /** The order's invoice as PDF; 404 until it is issued, shortly after the payment. */\n invoice(id: string, token: string): Promise<Blob>;\n /** Downloads the invoice in a browser, as `factuur.pdf`. */\n downloadInvoice(id: string, token: string, filename?: string): Promise<void>;\n}\n\n/** The browser's `localStorage`; never Node's own (which warns when it is touched), so `window` first. */\nfunction browserStorage(): TokenStorage | null {\n try {\n return typeof window === \"undefined\" ? null : window.localStorage;\n } catch {\n return null;\n }\n}\n\nfunction memoryStorage(): TokenStorage {\n const values = new Map<string, string>();\n return {\n getItem: (key) => values.get(key) ?? null,\n setItem: (key, value) => void values.set(key, value),\n removeItem: (key) => void values.delete(key),\n };\n}\n\nconst newKey = () => (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`);\n\n/** A client of a shop's storefront API. Make one per shop and page, and share it. */\nexport function createStorefront(options: StorefrontOptions): Storefront {\n const apiBase = options.apiBase.replace(/\\/+$/, \"\");\n const shopKey = options.shopKey;\n const doFetch = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const storage: TokenStorage = (options.storage === undefined ? browserStorage() : options.storage) ?? memoryStorage();\n const cartKey = `commercus-cart:${shopKey}`;\n\n let snapshot: CartSnapshot;\n let loading: Promise<Cart | null> | undefined;\n const listeners = new Set<(cart: Cart | null) => void>();\n\n async function request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T> {\n const response = await doFetch(apiBase + path, {\n method,\n headers: {\n \"X-Shop-Key\": shopKey,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!response.ok) {\n const problem = (await response.json().catch(() => ({}))) as { detail?: string };\n throw new StorefrontError(response.status, problem.detail);\n }\n return (response.status === 204 ? null : await response.json()) as T;\n }\n\n function settle(cart: Cart | null): Cart | null {\n snapshot = cart;\n if (cart) storage.setItem(cartKey, cart.token);\n else storage.removeItem(cartKey);\n listeners.forEach((listener) => listener(cart));\n return cart;\n }\n\n async function load(): Promise<Cart | null> {\n const token = storage.getItem(cartKey);\n if (!token) return settle(null);\n try {\n const cart = await request<Cart>(\"GET\", `/v1/carts/${encodeURIComponent(token)}`);\n // A checked-out cart became an order: the visitor starts afresh.\n return settle(cart.status === \"ACTIVE\" ? cart : null);\n } catch (e) {\n if (e instanceof StorefrontError && e.status === 404) return settle(null);\n throw e;\n }\n }\n\n async function current(create: boolean): Promise<Cart | null> {\n const cart = snapshot === undefined ? await storefront.cart() : snapshot;\n if (cart || !create) return cart;\n return settle(await request<Cart>(\"POST\", \"/v1/carts\", undefined, { \"Idempotency-Key\": newKey() }));\n }\n\n const storefront: Storefront = {\n apiBase,\n shopKey,\n\n shop: () => request(\"GET\", \"/v1/shop\"),\n products: (opts) => request(\"GET\", \"/v1/products\" + (opts?.category ? `?category=${encodeURIComponent(opts.category)}` : \"\")),\n product: (slug) => request(\"GET\", `/v1/products/${encodeURIComponent(slug)}`),\n categories: () => request(\"GET\", \"/v1/categories\"),\n prices: (ids) =>\n ids.length === 0\n ? Promise.resolve([])\n : request(\"GET\", \"/v1/variants?\" + [...new Set(ids)].map((id) => `id=${encodeURIComponent(id)}`).join(\"&\")),\n\n cart(opts) {\n if (opts?.refresh || snapshot === undefined) {\n loading ??= load().finally(() => {\n loading = undefined;\n });\n return loading;\n }\n return Promise.resolve(snapshot);\n },\n cartSnapshot: () => snapshot,\n onChange(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async add(variantId, quantity = 1) {\n let cart = (await current(true))!;\n try {\n cart = await request<Cart>(\"POST\", `/v1/carts/${cart.token}/items`, { variantId, quantity }, { \"Idempotency-Key\": newKey() });\n } catch (e) {\n // The cart expired or was checked out meanwhile: once more, on a new one.\n if (!(e instanceof StorefrontError) || e.status !== 404) throw e;\n settle(null);\n const fresh = (await current(true))!;\n cart = await request<Cart>(\"POST\", `/v1/carts/${fresh.token}/items`, { variantId, quantity }, { \"Idempotency-Key\": newKey() });\n }\n return settle(cart)!;\n },\n async update(lineId, quantity) {\n const cart = await current(false);\n if (!cart) return null;\n return settle(await request<Cart>(\"PATCH\", `/v1/carts/${cart.token}/items/${encodeURIComponent(lineId)}`, { quantity }));\n },\n remove: (lineId) => storefront.update(lineId, 0),\n async checkout(opts) {\n const cart = await current(false);\n if (!cart) throw new StorefrontError(404, \"There is no cart to check out\");\n const { checkoutUrl } = await request<{ checkoutUrl: string }>(\"POST\", `/v1/carts/${cart.token}/checkout`);\n if (opts?.navigate !== false && typeof window !== \"undefined\") window.location.assign(checkoutUrl);\n return checkoutUrl;\n },\n forgetCart: () => void settle(null),\n\n order: (id, token) => request(\"GET\", `/v1/orders/${encodeURIComponent(id)}?token=${encodeURIComponent(token)}`),\n async invoice(id, token) {\n const response = await doFetch(`${apiBase}/v1/orders/${encodeURIComponent(id)}/invoice?token=${encodeURIComponent(token)}`, {\n headers: { \"X-Shop-Key\": shopKey },\n });\n if (!response.ok) throw new StorefrontError(response.status);\n return response.blob();\n },\n async downloadInvoice(id, token, filename = \"factuur.pdf\") {\n const url = URL.createObjectURL(await storefront.invoice(id, token));\n const link = Object.assign(document.createElement(\"a\"), { href: url, download: filename });\n document.body.append(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(url);\n },\n };\n return storefront;\n}\n","const formats = new Map<string, Intl.NumberFormat>();\n\n/**\n * An amount in euros as a price: `€ 12,50` for `nl-NL`. Amounts from the API are numbers with two\n * decimals, VAT included.\n */\nexport function formatPrice(amount: number | string, locale = \"nl-NL\"): string {\n let format = formats.get(locale);\n if (!format) {\n format = new Intl.NumberFormat(locale, { style: \"currency\", currency: \"EUR\" });\n formats.set(locale, format);\n }\n return format.format(Number(amount));\n}\n"],"mappings":";AAQO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAY,QAAgB,QAAiB;AAC3C,UAAM,SAAS,GAAG,MAAM,KAAK,MAAM,KAAK,2BAA2B,MAAM,EAAE;AAC3E,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA,EAGA,IAAI,aAAsB;AACxB,WAAO,KAAK,WAAW;AAAA,EACzB;AACF;;;ACyCA,SAAS,iBAAsC;AAC7C,MAAI;AACF,WAAO,OAAO,WAAW,cAAc,OAAO,OAAO;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,gBAA8B;AACrC,QAAM,SAAS,oBAAI,IAAoB;AACvC,SAAO;AAAA,IACL,SAAS,CAAC,QA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OAAO,OAAO,MAAM,CAAC;AACrC;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { C as CartSnapshot, S as Storefront } from './storefront-BadKsP_d.js';
|
|
2
|
+
|
|
3
|
+
interface AsyncState<T> {
|
|
4
|
+
data: T | undefined;
|
|
5
|
+
error: unknown;
|
|
6
|
+
loading: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface CartState {
|
|
9
|
+
/** `undefined` while loading, `null` when the visitor has no cart. */
|
|
10
|
+
cart: CartSnapshot;
|
|
11
|
+
loading: boolean;
|
|
12
|
+
/** Item count, for a header badge. */
|
|
13
|
+
count: number;
|
|
14
|
+
add: Storefront["add"];
|
|
15
|
+
update: Storefront["update"];
|
|
16
|
+
remove: Storefront["remove"];
|
|
17
|
+
checkout: Storefront["checkout"];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type { AsyncState as A, CartState as C };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { S as Storefront } from './storefront-BadKsP_d.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Web components for a site without a framework (Hugo, plain HTML). Configure once in the page:
|
|
5
|
+
*
|
|
6
|
+
* <meta name="commercus:api" content="https://api.commercus.nl">
|
|
7
|
+
* <meta name="commercus:key" content="pk_…">
|
|
8
|
+
* <script type="module" src="https://esm.sh/@commercus/storefront/elements"></script>
|
|
9
|
+
*
|
|
10
|
+
* then use <commercus-cart-count>, <commercus-price variant="…">, <commercus-add-to-cart
|
|
11
|
+
* variant="…">In winkelwagen</commercus-add-to-cart> and <commercus-checkout-button>.
|
|
12
|
+
* They dispatch `commercus:added` and `commercus:error` events, which bubble.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** The page's storefront, from its `commercus:api` and `commercus:key` meta tags. */
|
|
16
|
+
declare function pageStorefront(): Storefront;
|
|
17
|
+
|
|
18
|
+
export { pageStorefront };
|
package/dist/elements.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import {
|
|
2
|
+
StorefrontError,
|
|
3
|
+
createStorefront,
|
|
4
|
+
formatPrice
|
|
5
|
+
} from "./chunk-TTGHFREY.js";
|
|
6
|
+
|
|
7
|
+
// src/elements/index.ts
|
|
8
|
+
var shared;
|
|
9
|
+
function pageStorefront() {
|
|
10
|
+
if (!shared) {
|
|
11
|
+
const meta = (name) => document.querySelector(`meta[name="commercus:${name}"]`)?.content ?? "";
|
|
12
|
+
shared = createStorefront({ apiBase: meta("api"), shopKey: meta("key") });
|
|
13
|
+
}
|
|
14
|
+
return shared;
|
|
15
|
+
}
|
|
16
|
+
var locale = () => document.documentElement.lang || "nl-NL";
|
|
17
|
+
var CartCount = class extends HTMLElement {
|
|
18
|
+
#off;
|
|
19
|
+
connectedCallback() {
|
|
20
|
+
const storefront = pageStorefront();
|
|
21
|
+
const show = (count) => {
|
|
22
|
+
this.textContent = String(count);
|
|
23
|
+
this.hidden = count === 0;
|
|
24
|
+
};
|
|
25
|
+
this.#off = storefront.onChange((cart) => show(cart?.itemCount ?? 0));
|
|
26
|
+
storefront.cart().then((cart) => show(cart?.itemCount ?? 0), () => show(0));
|
|
27
|
+
}
|
|
28
|
+
disconnectedCallback() {
|
|
29
|
+
this.#off?.();
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var Price = class _Price extends HTMLElement {
|
|
33
|
+
static #pending = /* @__PURE__ */ new Map();
|
|
34
|
+
connectedCallback() {
|
|
35
|
+
const id = this.getAttribute("variant");
|
|
36
|
+
if (!id) return;
|
|
37
|
+
const waiting = _Price.#pending.get(id) ?? [];
|
|
38
|
+
waiting.push(this);
|
|
39
|
+
_Price.#pending.set(id, waiting);
|
|
40
|
+
if (_Price.#pending.size === 1 && waiting.length === 1) queueMicrotask(_Price.#flush);
|
|
41
|
+
}
|
|
42
|
+
static #flush = () => {
|
|
43
|
+
const batch = new Map(_Price.#pending);
|
|
44
|
+
_Price.#pending.clear();
|
|
45
|
+
pageStorefront().prices([...batch.keys()]).then((prices) => {
|
|
46
|
+
for (const price of prices) {
|
|
47
|
+
for (const element of batch.get(price.id) ?? []) {
|
|
48
|
+
element.textContent = formatPrice(price.priceGross, locale());
|
|
49
|
+
element.toggleAttribute("sold-out", !price.available);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}).catch(() => {
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
function whenParsed(build) {
|
|
57
|
+
if (typeof document !== "undefined" && document.readyState === "loading") {
|
|
58
|
+
document.addEventListener("DOMContentLoaded", build, { once: true });
|
|
59
|
+
} else {
|
|
60
|
+
queueMicrotask(build);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
var AddToCart = class extends HTMLElement {
|
|
64
|
+
#built = false;
|
|
65
|
+
connectedCallback() {
|
|
66
|
+
whenParsed(() => {
|
|
67
|
+
if (this.#built) return;
|
|
68
|
+
this.#built = true;
|
|
69
|
+
let button = this.querySelector("button");
|
|
70
|
+
if (!button) {
|
|
71
|
+
button = document.createElement("button");
|
|
72
|
+
button.type = "button";
|
|
73
|
+
button.append(...Array.from(this.childNodes));
|
|
74
|
+
if (!button.textContent?.trim()) button.textContent = "In winkelwagen";
|
|
75
|
+
this.append(button);
|
|
76
|
+
}
|
|
77
|
+
button.addEventListener("click", this.#add);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
#add = async () => {
|
|
81
|
+
const button = this.querySelector("button");
|
|
82
|
+
const variant = this.getAttribute("variant");
|
|
83
|
+
if (!variant) return;
|
|
84
|
+
button.disabled = true;
|
|
85
|
+
try {
|
|
86
|
+
const cart = await pageStorefront().add(variant, Number(this.getAttribute("quantity") ?? 1));
|
|
87
|
+
this.dispatchEvent(new CustomEvent("commercus:added", { bubbles: true, detail: { cart, variant } }));
|
|
88
|
+
} catch (error) {
|
|
89
|
+
this.dispatchEvent(new CustomEvent("commercus:error", {
|
|
90
|
+
bubbles: true,
|
|
91
|
+
detail: { error, outOfStock: error instanceof StorefrontError && error.outOfStock }
|
|
92
|
+
}));
|
|
93
|
+
} finally {
|
|
94
|
+
button.disabled = false;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
var CheckoutButton = class extends HTMLElement {
|
|
99
|
+
#built = false;
|
|
100
|
+
connectedCallback() {
|
|
101
|
+
whenParsed(() => this.#build());
|
|
102
|
+
}
|
|
103
|
+
#build() {
|
|
104
|
+
if (this.#built) return;
|
|
105
|
+
this.#built = true;
|
|
106
|
+
if (!this.querySelector("button")) {
|
|
107
|
+
const button = document.createElement("button");
|
|
108
|
+
button.type = "button";
|
|
109
|
+
button.textContent = this.textContent?.trim() || "Afrekenen";
|
|
110
|
+
this.replaceChildren(button);
|
|
111
|
+
}
|
|
112
|
+
this.querySelector("button").addEventListener("click", async (event) => {
|
|
113
|
+
const button = event.currentTarget;
|
|
114
|
+
button.disabled = true;
|
|
115
|
+
try {
|
|
116
|
+
await pageStorefront().checkout();
|
|
117
|
+
} catch (error) {
|
|
118
|
+
button.disabled = false;
|
|
119
|
+
this.dispatchEvent(new CustomEvent("commercus:error", { bubbles: true, detail: { error } }));
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
var define = (name, element) => {
|
|
125
|
+
if (typeof customElements !== "undefined" && !customElements.get(name)) customElements.define(name, element);
|
|
126
|
+
};
|
|
127
|
+
define("commercus-cart-count", CartCount);
|
|
128
|
+
define("commercus-price", Price);
|
|
129
|
+
define("commercus-add-to-cart", AddToCart);
|
|
130
|
+
define("commercus-checkout-button", CheckoutButton);
|
|
131
|
+
export {
|
|
132
|
+
pageStorefront
|
|
133
|
+
};
|
|
134
|
+
//# sourceMappingURL=elements.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/elements/index.ts"],"sourcesContent":["/**\n * Web components for a site without a framework (Hugo, plain HTML). Configure once in the page:\n *\n * <meta name=\"commercus:api\" content=\"https://api.commercus.nl\">\n * <meta name=\"commercus:key\" content=\"pk_…\">\n * <script type=\"module\" src=\"https://esm.sh/@commercus/storefront/elements\"></script>\n *\n * then use <commercus-cart-count>, <commercus-price variant=\"…\">, <commercus-add-to-cart\n * variant=\"…\">In winkelwagen</commercus-add-to-cart> and <commercus-checkout-button>.\n * They dispatch `commercus:added` and `commercus:error` events, which bubble.\n */\nimport { createStorefront, type Storefront } from \"../storefront.js\";\nimport { formatPrice } from \"../format.js\";\nimport { StorefrontError } from \"../errors.js\";\n\nlet shared: Storefront | undefined;\n\n/** The page's storefront, from its `commercus:api` and `commercus:key` meta tags. */\nexport function pageStorefront(): Storefront {\n if (!shared) {\n const meta = (name: string) => document.querySelector<HTMLMetaElement>(`meta[name=\"commercus:${name}\"]`)?.content ?? \"\";\n shared = createStorefront({ apiBase: meta(\"api\"), shopKey: meta(\"key\") });\n }\n return shared;\n}\n\nconst locale = () => document.documentElement.lang || \"nl-NL\";\n\n/** The number of items in the cart; hidden while it is zero. */\nclass CartCount extends HTMLElement {\n #off?: () => void;\n\n connectedCallback() {\n const storefront = pageStorefront();\n const show = (count: number) => {\n this.textContent = String(count);\n this.hidden = count === 0;\n };\n this.#off = storefront.onChange((cart) => show(cart?.itemCount ?? 0));\n storefront.cart().then((cart) => show(cart?.itemCount ?? 0), () => show(0));\n }\n\n disconnectedCallback() {\n this.#off?.();\n }\n}\n\n/** Today's price of `variant`; the page's own text stays until it is known. Requests are batched. */\nclass Price extends HTMLElement {\n static #pending = new Map<string, Price[]>();\n\n connectedCallback() {\n const id = this.getAttribute(\"variant\");\n if (!id) return;\n const waiting = Price.#pending.get(id) ?? [];\n waiting.push(this);\n Price.#pending.set(id, waiting);\n if (Price.#pending.size === 1 && waiting.length === 1) queueMicrotask(Price.#flush);\n }\n\n static #flush = () => {\n const batch = new Map(Price.#pending);\n Price.#pending.clear();\n pageStorefront().prices([...batch.keys()]).then((prices) => {\n for (const price of prices) {\n for (const element of batch.get(price.id) ?? []) {\n element.textContent = formatPrice(price.priceGross, locale());\n element.toggleAttribute(\"sold-out\", !price.available);\n }\n }\n }).catch(() => {});\n };\n}\n\n/**\n * Runs `build` once the element's children are there: an element may be connected before the parser\n * reached its content (a script that runs while the page loads).\n */\nfunction whenParsed(build: () => void) {\n if (typeof document !== \"undefined\" && document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", build, { once: true });\n } else {\n queueMicrotask(build);\n }\n}\n\n/** A button that adds `variant` (and `quantity`, default 1) to the cart; its content is the label. */\nclass AddToCart extends HTMLElement {\n #built = false;\n\n connectedCallback() {\n whenParsed(() => {\n if (this.#built) return;\n this.#built = true;\n let button = this.querySelector(\"button\");\n if (!button) {\n button = document.createElement(\"button\");\n button.type = \"button\";\n button.append(...Array.from(this.childNodes));\n if (!button.textContent?.trim()) button.textContent = \"In winkelwagen\";\n this.append(button);\n }\n button.addEventListener(\"click\", this.#add);\n });\n }\n\n #add = async () => {\n const button = this.querySelector(\"button\")!;\n const variant = this.getAttribute(\"variant\");\n if (!variant) return;\n button.disabled = true;\n try {\n const cart = await pageStorefront().add(variant, Number(this.getAttribute(\"quantity\") ?? 1));\n this.dispatchEvent(new CustomEvent(\"commercus:added\", { bubbles: true, detail: { cart, variant } }));\n } catch (error) {\n this.dispatchEvent(new CustomEvent(\"commercus:error\", {\n bubbles: true,\n detail: { error, outOfStock: error instanceof StorefrontError && error.outOfStock },\n }));\n } finally {\n button.disabled = false;\n }\n };\n}\n\n/** A button to the platform's hosted checkout. */\nclass CheckoutButton extends HTMLElement {\n #built = false;\n\n connectedCallback() {\n whenParsed(() => this.#build());\n }\n\n #build() {\n if (this.#built) return;\n this.#built = true;\n if (!this.querySelector(\"button\")) {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.textContent = this.textContent?.trim() || \"Afrekenen\";\n this.replaceChildren(button);\n }\n this.querySelector(\"button\")!.addEventListener(\"click\", async (event) => {\n const button = event.currentTarget as HTMLButtonElement;\n button.disabled = true;\n try {\n await pageStorefront().checkout();\n } catch (error) {\n button.disabled = false;\n this.dispatchEvent(new CustomEvent(\"commercus:error\", { bubbles: true, detail: { error } }));\n }\n });\n }\n}\n\nconst define = (name: string, element: CustomElementConstructor) => {\n if (typeof customElements !== \"undefined\" && !customElements.get(name)) customElements.define(name, element);\n};\ndefine(\"commercus-cart-count\", CartCount);\ndefine(\"commercus-price\", Price);\ndefine(\"commercus-add-to-cart\", AddToCart);\ndefine(\"commercus-checkout-button\", CheckoutButton);\n"],"mappings":";;;;;;;AAeA,IAAI;AAGG,SAAS,iBAA6B;AAC3C,MAAI,CAAC,QAAQ;AACX,UAAM,OAAO,CAAC,SAAiB,SAAS,cAA+B,wBAAwB,IAAI,IAAI,GAAG,WAAW;AACrH,aAAS,iBAAiB,EAAE,SAAS,KAAK,KAAK,GAAG,SAAS,KAAK,KAAK,EAAE,CAAC;AAAA,EAC1E;AACA,SAAO;AACT;AAEA,IAAM,SAAS,MAAM,SAAS,gBAAgB,QAAQ;AAGtD,IAAM,YAAN,cAAwB,YAAY;AAAA,EAClC;AAAA,EAEA,oBAAoB;AAClB,UAAM,aAAa,eAAe;AAClC,UAAM,OAAO,CAAC,UAAkB;AAC9B,WAAK,cAAc,OAAO,KAAK;AAC/B,WAAK,SAAS,UAAU;AAAA,IAC1B;AACA,SAAK,OAAO,WAAW,SAAS,CAAC,SAAS,KAAK,MAAM,aAAa,CAAC,CAAC;AACpE,eAAW,KAAK,EAAE,KAAK,CAAC,SAAS,KAAK,MAAM,aAAa,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC;AAAA,EAC5E;AAAA,EAEA,uBAAuB;AACrB,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAM,QAAN,MAAM,eAAc,YAAY;AAAA,EAC9B,OAAO,WAAW,oBAAI,IAAqB;AAAA,EAE3C,oBAAoB;AAClB,UAAM,KAAK,KAAK,aAAa,SAAS;AACtC,QAAI,CAAC,GAAI;AACT,UAAM,UAAU,OAAM,SAAS,IAAI,EAAE,KAAK,CAAC;A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,MAC7F;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,IAAM,SAAS,CAAC,MAAc,YAAsC;AAClE,MAAI,OAAO,mBAAmB,eAAe,CAAC,eAAe,IAAI,IAAI,EAAG,gBAAe,OAAO,MAAM,OAAO;AAC7G;AACA,OAAO,wBAAwB,SAAS;AACxC,OAAO,mBAAmB,KAAK;AAC/B,OAAO,yBAAyB,SAAS;AACzC,OAAO,6BAA6B,cAAc;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { S as Storefront, O as Order, V as VariantPrice, P as Product } from '../storefront-BadKsP_d.js';
|
|
2
|
+
import { C as CartState, A as AsyncState } from '../core-C_ZetpHp.js';
|
|
3
|
+
|
|
4
|
+
/** The storefront's hooks for Preact (Astro islands with `@astrojs/preact`, for one). */
|
|
5
|
+
declare const useCart: (storefront: Storefront) => CartState;
|
|
6
|
+
declare const usePrices: (storefront: Storefront, variantIds: string[]) => AsyncState<Record<string, VariantPrice>>;
|
|
7
|
+
declare const useProduct: (storefront: Storefront, slug: string) => AsyncState<Product>;
|
|
8
|
+
declare const useOrder: (storefront: Storefront, id: string | null, token: string | null) => AsyncState<Order>;
|
|
9
|
+
|
|
10
|
+
export { AsyncState, CartState, useCart, useOrder, usePrices, useProduct };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
makeHooks
|
|
3
|
+
} from "../chunk-4FMEU3RQ.js";
|
|
4
|
+
|
|
5
|
+
// src/hooks/preact.ts
|
|
6
|
+
import { useEffect, useState } from "preact/hooks";
|
|
7
|
+
var { useCart, usePrices, useProduct, useOrder } = makeHooks({ useState, useEffect });
|
|
8
|
+
export {
|
|
9
|
+
useCart,
|
|
10
|
+
useOrder,
|
|
11
|
+
usePrices,
|
|
12
|
+
useProduct
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=preact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/preact.ts"],"sourcesContent":["import { useEffect, useState } from \"preact/hooks\";\nimport { type HookRuntime, makeHooks } from \"./core.js\";\n\n/** The storefront's hooks for Preact (Astro islands with `@astrojs/preact`, for one). */\nexport const { useCart, usePrices, useProduct, useOrder } = makeHooks({ useState, useEffect } as unknown as HookRuntime);\nexport type { AsyncState, CartState } from \"./core.js\";\n"],"mappings":";;;;;AAAA,SAAS,WAAW,gBAAgB;AAI7B,IAAM,EAAE,SAAS,WAAW,YAAY,SAAS,IAAI,UAAU,EAAE,UAAU,UAAU,CAA2B;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { S as Storefront, O as Order, V as VariantPrice, P as Product } from '../storefront-BadKsP_d.js';
|
|
2
|
+
import { C as CartState, A as AsyncState } from '../core-C_ZetpHp.js';
|
|
3
|
+
|
|
4
|
+
/** The storefront's hooks for React. */
|
|
5
|
+
declare const useCart: (storefront: Storefront) => CartState;
|
|
6
|
+
declare const usePrices: (storefront: Storefront, variantIds: string[]) => AsyncState<Record<string, VariantPrice>>;
|
|
7
|
+
declare const useProduct: (storefront: Storefront, slug: string) => AsyncState<Product>;
|
|
8
|
+
declare const useOrder: (storefront: Storefront, id: string | null, token: string | null) => AsyncState<Order>;
|
|
9
|
+
|
|
10
|
+
export { AsyncState, CartState, useCart, useOrder, usePrices, useProduct };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
makeHooks
|
|
3
|
+
} from "../chunk-4FMEU3RQ.js";
|
|
4
|
+
|
|
5
|
+
// src/hooks/react.ts
|
|
6
|
+
import { useEffect, useState } from "react";
|
|
7
|
+
var { useCart, usePrices, useProduct, useOrder } = makeHooks({ useState, useEffect });
|
|
8
|
+
export {
|
|
9
|
+
useCart,
|
|
10
|
+
useOrder,
|
|
11
|
+
usePrices,
|
|
12
|
+
useProduct
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=react.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/react.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\nimport { type HookRuntime, makeHooks } from \"./core.js\";\n\n/** The storefront's hooks for React. */\nexport const { useCart, usePrices, useProduct, useOrder } = makeHooks({ useState, useEffect } as unknown as HookRuntime);\nexport type { AsyncState, CartState } from \"./core.js\";\n"],"mappings":";;;;;AAAA,SAAS,WAAW,gBAAgB;AAI7B,IAAM,EAAE,SAAS,WAAW,YAAY,SAAS,IAAI,UAAU,EAAE,UAAU,UAAU,CAA2B;","names":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export { a as Cart, b as CartLine, C as CartSnapshot, c as Category, O as Order, d as OrderLine, P as Product, e as ProductImage, f as ProductOption, g as ProductSummary, h as Shop, S as Storefront, i as StorefrontOptions, T as TokenStorage, j as Variant, V as VariantPrice, k as createStorefront } from './storefront-BadKsP_d.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* An answer of the storefront API that is not a success. `status` is the HTTP status; `detail` the
|
|
5
|
+
* API's explanation (in English, for developers: show your own text to visitors).
|
|
6
|
+
*
|
|
7
|
+
* Statuses worth handling: 409 (not enough stock, or the cart was checked out), 404 (an unknown or
|
|
8
|
+
* expired cart, product or order), 422 (a variant that is not for sale, or an Idempotency-Key reused
|
|
9
|
+
* for another request).
|
|
10
|
+
*/
|
|
11
|
+
declare class StorefrontError extends Error {
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly detail: string | undefined;
|
|
14
|
+
constructor(status: number, detail?: string);
|
|
15
|
+
/** Not enough stock for what was asked. */
|
|
16
|
+
get outOfStock(): boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* An amount in euros as a price: `€ 12,50` for `nl-NL`. Amounts from the API are numbers with two
|
|
21
|
+
* decimals, VAT included.
|
|
22
|
+
*/
|
|
23
|
+
declare function formatPrice(amount: number | string, locale?: string): string;
|
|
24
|
+
|
|
25
|
+
export { StorefrontError, formatPrice };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
interface components {
|
|
2
|
+
schemas: {
|
|
3
|
+
AddItemRequest: {
|
|
4
|
+
/** Format: int32 */
|
|
5
|
+
quantity: number;
|
|
6
|
+
/** Format: uuid */
|
|
7
|
+
variantId: string;
|
|
8
|
+
};
|
|
9
|
+
BuyerOrder: {
|
|
10
|
+
lines: components["schemas"]["OrderLineResponse"][];
|
|
11
|
+
number: string;
|
|
12
|
+
shippingGross: number;
|
|
13
|
+
shippingMethod: string;
|
|
14
|
+
/** @enum {string} */
|
|
15
|
+
status: "PENDING_PAYMENT" | "PAID" | "SHIPPED" | "CANCELLED" | "PARTIALLY_REFUNDED" | "REFUNDED";
|
|
16
|
+
subtotalGross: number;
|
|
17
|
+
totalGross: number;
|
|
18
|
+
totalVat: number;
|
|
19
|
+
trackingCode?: string;
|
|
20
|
+
trackingUrl?: string;
|
|
21
|
+
};
|
|
22
|
+
CartLineView: {
|
|
23
|
+
/** Format: int32 */
|
|
24
|
+
available?: number;
|
|
25
|
+
/** Format: uuid */
|
|
26
|
+
id: string;
|
|
27
|
+
imageUrl?: string;
|
|
28
|
+
lineTotal?: number;
|
|
29
|
+
/** @enum {string} */
|
|
30
|
+
problem?: "UNAVAILABLE" | "INSUFFICIENT_STOCK";
|
|
31
|
+
productTitle?: string;
|
|
32
|
+
/** Format: int32 */
|
|
33
|
+
quantity: number;
|
|
34
|
+
sku?: string;
|
|
35
|
+
unitPrice?: number;
|
|
36
|
+
/** Format: uuid */
|
|
37
|
+
variantId: string;
|
|
38
|
+
variantTitle?: string;
|
|
39
|
+
};
|
|
40
|
+
CartView: {
|
|
41
|
+
/** Format: date-time */
|
|
42
|
+
expiresAt: string;
|
|
43
|
+
/** Format: int32 */
|
|
44
|
+
itemCount: number;
|
|
45
|
+
lines: components["schemas"]["CartLineView"][];
|
|
46
|
+
ready: boolean;
|
|
47
|
+
/** @enum {string} */
|
|
48
|
+
status: "ACTIVE" | "CHECKED_OUT";
|
|
49
|
+
subtotal: number;
|
|
50
|
+
token: string;
|
|
51
|
+
};
|
|
52
|
+
CheckoutStart: {
|
|
53
|
+
checkoutUrl: string;
|
|
54
|
+
/** Format: date-time */
|
|
55
|
+
expiresAt: string;
|
|
56
|
+
};
|
|
57
|
+
ImageResponse: {
|
|
58
|
+
alt?: string;
|
|
59
|
+
/** Format: int32 */
|
|
60
|
+
height: number;
|
|
61
|
+
/** Format: uuid */
|
|
62
|
+
id: string;
|
|
63
|
+
url: string;
|
|
64
|
+
/** Format: int32 */
|
|
65
|
+
width: number;
|
|
66
|
+
};
|
|
67
|
+
OptionResponse: {
|
|
68
|
+
name: string;
|
|
69
|
+
values: string[];
|
|
70
|
+
};
|
|
71
|
+
OrderLineResponse: {
|
|
72
|
+
lineGross: number;
|
|
73
|
+
productTitle: string;
|
|
74
|
+
/** Format: int32 */
|
|
75
|
+
quantity: number;
|
|
76
|
+
sku: string;
|
|
77
|
+
unitGross: number;
|
|
78
|
+
/** Format: uuid */
|
|
79
|
+
variantId: string;
|
|
80
|
+
variantTitle?: string;
|
|
81
|
+
/** @enum {string} */
|
|
82
|
+
vatCode: "HIGH" | "LOW" | "ZERO" | "EXEMPT";
|
|
83
|
+
vatPercent?: number;
|
|
84
|
+
};
|
|
85
|
+
Pong: {
|
|
86
|
+
status: string;
|
|
87
|
+
};
|
|
88
|
+
QuantityRequest: {
|
|
89
|
+
/** Format: int32 */
|
|
90
|
+
quantity: number;
|
|
91
|
+
};
|
|
92
|
+
StorefrontCategory: {
|
|
93
|
+
description?: string;
|
|
94
|
+
name: string;
|
|
95
|
+
parent?: string;
|
|
96
|
+
/** Format: int32 */
|
|
97
|
+
position: number;
|
|
98
|
+
slug: string;
|
|
99
|
+
};
|
|
100
|
+
StorefrontProduct: {
|
|
101
|
+
categories: string[];
|
|
102
|
+
description?: string;
|
|
103
|
+
/** Format: uuid */
|
|
104
|
+
id: string;
|
|
105
|
+
images: components["schemas"]["ImageResponse"][];
|
|
106
|
+
options: components["schemas"]["OptionResponse"][];
|
|
107
|
+
slug: string;
|
|
108
|
+
title: string;
|
|
109
|
+
variants: components["schemas"]["StorefrontVariant"][];
|
|
110
|
+
};
|
|
111
|
+
StorefrontProductSummary: {
|
|
112
|
+
available: boolean;
|
|
113
|
+
categories: string[];
|
|
114
|
+
/** Format: uuid */
|
|
115
|
+
id: string;
|
|
116
|
+
image?: components["schemas"]["ImageResponse"];
|
|
117
|
+
priceFrom: number;
|
|
118
|
+
slug: string;
|
|
119
|
+
title: string;
|
|
120
|
+
};
|
|
121
|
+
StorefrontShop: {
|
|
122
|
+
brandColor?: string;
|
|
123
|
+
name: string;
|
|
124
|
+
/** @enum {string} */
|
|
125
|
+
status: "DRAFT" | "LIVE" | "SUSPENDED";
|
|
126
|
+
termsUrl?: string;
|
|
127
|
+
};
|
|
128
|
+
StorefrontVariant: {
|
|
129
|
+
available: boolean;
|
|
130
|
+
/** Format: uuid */
|
|
131
|
+
id: string;
|
|
132
|
+
optionValues: string[];
|
|
133
|
+
priceGross: number;
|
|
134
|
+
sku: string;
|
|
135
|
+
/** Format: int32 */
|
|
136
|
+
stock?: number;
|
|
137
|
+
title?: string;
|
|
138
|
+
};
|
|
139
|
+
VariantPrice: {
|
|
140
|
+
available: boolean;
|
|
141
|
+
/** Format: uuid */
|
|
142
|
+
id: string;
|
|
143
|
+
priceGross: number;
|
|
144
|
+
/** Format: uuid */
|
|
145
|
+
productId: string;
|
|
146
|
+
/** Format: int32 */
|
|
147
|
+
stock?: number;
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
responses: never;
|
|
151
|
+
parameters: never;
|
|
152
|
+
requestBodies: never;
|
|
153
|
+
headers: never;
|
|
154
|
+
pathItems: never;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type Schemas = components["schemas"];
|
|
158
|
+
/** The shop the public key belongs to. */
|
|
159
|
+
type Shop = Schemas["StorefrontShop"];
|
|
160
|
+
/** A product in a list: lowest price, first image, categories. */
|
|
161
|
+
type ProductSummary = Schemas["StorefrontProductSummary"];
|
|
162
|
+
/** A product with its options, variants and images. */
|
|
163
|
+
type Product = Schemas["StorefrontProduct"];
|
|
164
|
+
type Variant = Schemas["StorefrontVariant"];
|
|
165
|
+
type ProductOption = Schemas["OptionResponse"];
|
|
166
|
+
type ProductImage = Schemas["ImageResponse"];
|
|
167
|
+
type Category = Schemas["StorefrontCategory"];
|
|
168
|
+
/** Today's price and stock of a variant. */
|
|
169
|
+
type VariantPrice = Schemas["VariantPrice"];
|
|
170
|
+
/** The visitor's cart, priced from today's catalogue. */
|
|
171
|
+
type Cart = Schemas["CartView"];
|
|
172
|
+
type CartLine = Schemas["CartLineView"];
|
|
173
|
+
/** An order as its buyer sees it on the thank-you page. */
|
|
174
|
+
type Order = Schemas["BuyerOrder"];
|
|
175
|
+
type OrderLine = Schemas["OrderLineResponse"];
|
|
176
|
+
|
|
177
|
+
/** Where the cart's token is kept; `localStorage` by default. */
|
|
178
|
+
interface TokenStorage {
|
|
179
|
+
getItem(key: string): string | null;
|
|
180
|
+
setItem(key: string, value: string): void;
|
|
181
|
+
removeItem(key: string): void;
|
|
182
|
+
}
|
|
183
|
+
interface StorefrontOptions {
|
|
184
|
+
/** The API, e.g. `https://api.commercus.nl`. */
|
|
185
|
+
apiBase: string;
|
|
186
|
+
/** The shop's public key, `pk_…`: safe in a page, it identifies the shop and grants nothing more. */
|
|
187
|
+
shopKey: string;
|
|
188
|
+
/** Where the cart token lives; `null` keeps it in memory only (tests, server-side rendering). */
|
|
189
|
+
storage?: TokenStorage | null;
|
|
190
|
+
/** Defaults to the global `fetch`. */
|
|
191
|
+
fetch?: typeof fetch;
|
|
192
|
+
}
|
|
193
|
+
/** The cart as last seen: `undefined` before the first look, `null` when the visitor has none. */
|
|
194
|
+
type CartSnapshot = Cart | null | undefined;
|
|
195
|
+
interface Storefront {
|
|
196
|
+
readonly apiBase: string;
|
|
197
|
+
readonly shopKey: string;
|
|
198
|
+
shop(): Promise<Shop>;
|
|
199
|
+
/** The products for sale, by title; optionally those in one category. */
|
|
200
|
+
products(options?: {
|
|
201
|
+
category?: string;
|
|
202
|
+
}): Promise<ProductSummary[]>;
|
|
203
|
+
product(slug: string): Promise<Product>;
|
|
204
|
+
categories(): Promise<Category[]>;
|
|
205
|
+
/** Today's price and stock of variants, for a page built earlier. Unknown ids are left out. */
|
|
206
|
+
prices(variantIds: string[]): Promise<VariantPrice[]>;
|
|
207
|
+
/** The visitor's cart, or `null` when there is none (yet). Fetched once, then kept up to date. */
|
|
208
|
+
cart(options?: {
|
|
209
|
+
refresh?: boolean;
|
|
210
|
+
}): Promise<Cart | null>;
|
|
211
|
+
/** The cart as last seen, synchronously; for hooks and components. */
|
|
212
|
+
cartSnapshot(): CartSnapshot;
|
|
213
|
+
/** Calls `listener` after every change of the cart; returns the unsubscribe. */
|
|
214
|
+
onChange(listener: (cart: Cart | null) => void): () => void;
|
|
215
|
+
/** Adds `quantity` of a variant, on its line if the cart has one; makes the cart on first use. */
|
|
216
|
+
add(variantId: string, quantity?: number): Promise<Cart>;
|
|
217
|
+
/** Sets a line's quantity; 0 removes the line. */
|
|
218
|
+
update(lineId: string, quantity: number): Promise<Cart | null>;
|
|
219
|
+
remove(lineId: string): Promise<Cart | null>;
|
|
220
|
+
/**
|
|
221
|
+
* Starts the platform's hosted checkout for the cart and, in a browser, goes there: payment and
|
|
222
|
+
* personal details never touch the site. Returns the checkout's address.
|
|
223
|
+
*/
|
|
224
|
+
checkout(options?: {
|
|
225
|
+
navigate?: boolean;
|
|
226
|
+
}): Promise<string>;
|
|
227
|
+
/** Forgets the cart, e.g. on the thank-you page: the next `add` starts a new one. */
|
|
228
|
+
forgetCart(): void;
|
|
229
|
+
/** The order the hosted checkout sent the buyer back with (`?order=…&token=…`). */
|
|
230
|
+
order(id: string, token: string): Promise<Order>;
|
|
231
|
+
/** The order's invoice as PDF; 404 until it is issued, shortly after the payment. */
|
|
232
|
+
invoice(id: string, token: string): Promise<Blob>;
|
|
233
|
+
/** Downloads the invoice in a browser, as `factuur.pdf`. */
|
|
234
|
+
downloadInvoice(id: string, token: string, filename?: string): Promise<void>;
|
|
235
|
+
}
|
|
236
|
+
/** A client of a shop's storefront API. Make one per shop and page, and share it. */
|
|
237
|
+
declare function createStorefront(options: StorefrontOptions): Storefront;
|
|
238
|
+
|
|
239
|
+
export { type CartSnapshot as C, type Order as O, type Product as P, type Storefront as S, type TokenStorage as T, type VariantPrice as V, type Cart as a, type CartLine as b, type Category as c, type OrderLine as d, type ProductImage as e, type ProductOption as f, type ProductSummary as g, type Shop as h, type StorefrontOptions as i, type Variant as j, createStorefront as k };
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercus/storefront",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The storefront API of the Commercus webshop platform: catalogue, live prices and stock, the cart and the hosted checkout. For any frontend; Preact and React hooks and web components included.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": { "type": "git", "url": "git+https://github.com/commercus/storefront.git" },
|
|
8
|
+
"homepage": "https://github.com/commercus/storefront#readme",
|
|
9
|
+
"bugs": "https://github.com/commercus/storefront/issues",
|
|
10
|
+
"keywords": ["commercus", "webshop", "ecommerce", "storefront", "cart", "checkout", "headless"],
|
|
11
|
+
"sideEffects": ["./dist/elements.js"],
|
|
12
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
13
|
+
"exports": {
|
|
14
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
15
|
+
"./hooks/preact": { "types": "./dist/hooks/preact.d.ts", "import": "./dist/hooks/preact.js" },
|
|
16
|
+
"./hooks/react": { "types": "./dist/hooks/react.d.ts", "import": "./dist/hooks/react.js" },
|
|
17
|
+
"./elements": { "types": "./dist/elements.d.ts", "import": "./dist/elements.js" }
|
|
18
|
+
},
|
|
19
|
+
"engines": { "node": ">=20" },
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsup",
|
|
22
|
+
"typecheck": "tsc --noEmit",
|
|
23
|
+
"test": "vitest run",
|
|
24
|
+
"generate": "openapi-typescript api/storefront.yaml -o src/generated/storefront.ts",
|
|
25
|
+
"sync-api": "node scripts/sync-api.mjs && npm run generate",
|
|
26
|
+
"check-generated": "npm run generate && git diff --exit-code src/generated",
|
|
27
|
+
"changeset": "changeset",
|
|
28
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"preact": ">=10.19",
|
|
32
|
+
"react": ">=18"
|
|
33
|
+
},
|
|
34
|
+
"peerDependenciesMeta": {
|
|
35
|
+
"preact": { "optional": true },
|
|
36
|
+
"react": { "optional": true }
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@changesets/cli": "^2.29.7",
|
|
40
|
+
"@types/react": "^19.2.2",
|
|
41
|
+
"happy-dom": "^20.0.10",
|
|
42
|
+
"openapi-typescript": "^7.13.0",
|
|
43
|
+
"preact": "^10.27.2",
|
|
44
|
+
"react": "^19.2.0",
|
|
45
|
+
"tsup": "^8.5.0",
|
|
46
|
+
"typescript": "^5.9.3",
|
|
47
|
+
"vitest": "^4.0.8"
|
|
48
|
+
}
|
|
49
|
+
}
|