@asstio-dev/storefront 0.57.1 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -0
- package/dist/analytics/facts.d.ts +2 -1
- package/dist/analytics/facts.js +7 -3
- package/dist/analytics/types.d.ts +3 -1
- package/dist/code-link/index.d.ts +83 -0
- package/dist/code-link/index.js +109 -0
- package/dist/filters.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/listing.d.ts +12 -0
- package/dist/listing.js +19 -0
- package/dist/schema.d.ts +606 -38
- package/dist/seo/head.d.ts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +7 -2
- package/src/schema.d.ts +606 -38
package/README.md
CHANGED
|
@@ -1002,6 +1002,71 @@ const attribution = await attributionForCheckout(site, { origin: "https://shop.e
|
|
|
1002
1002
|
await syncCheckout(storefront, cartToken, { returnOrigin: "https://shop.example", shopper, ...attribution }, { retries: 0 });
|
|
1003
1003
|
```
|
|
1004
1004
|
|
|
1005
|
+
### Listings v2
|
|
1006
|
+
|
|
1007
|
+
`GET /v2/products`, `GET /v2/collections/{slugOrId}` and `GET /v2/products/facets/{key}` are plain operations of the typed
|
|
1008
|
+
client (`storefront.GET("/v2/products", …)`); v1 is unchanged. Optional blocks (`facets`, `groups`, `childCollections`,
|
|
1009
|
+
and on a card `variants` and `matchedVariant`) come with `include=…`. Continue a listing by `page`, `pageSize` and `total`,
|
|
1010
|
+
never by `items.length`. Follow a group by spreading the current `group` map, setting one key and going back to `page: 1`.
|
|
1011
|
+
|
|
1012
|
+
A facet menu opened on a listing takes the listing's scope but not its window: `page` and `pageSize` mean something else
|
|
1013
|
+
on the facet operation. `facetScope(query, { collection })` keeps `q`, `filter`, `group` and the collection, and drops
|
|
1014
|
+
`page`, `pageSize`, `sort`, `origin` and `include`. On a collection route pass the answer's `collection.id`.
|
|
1015
|
+
What the shopper types into the menu is `match` on v2, where v1's facet endpoint took it as `q`: v2's `q` is the
|
|
1016
|
+
listing's own search text, so a frontend that keeps sending `q=<typed text>` gets a different answer (the values of
|
|
1017
|
+
a listing searched for that text, not the values whose label matches it).
|
|
1018
|
+
`productFacts`, `toGa4Item`, `collectionHead` and `priceFacetBasis` accept the v2 answers; a v2 card reads with
|
|
1019
|
+
`attributes: []`, meaning "not supplied by this representation".
|
|
1020
|
+
|
|
1021
|
+
```ts
|
|
1022
|
+
// searchText: what the shopper typed in the menu; `match` narrows the values by label (1-100 characters, and a blank `match` is a 400).
|
|
1023
|
+
const { data: answer } = await storefront.GET("/v2/collections/{slugOrId}", {
|
|
1024
|
+
params: { path: { slugOrId: "parfym" }, query: { include: "facets,groups,childCollections,variants", pageSize: 24 } },
|
|
1025
|
+
});
|
|
1026
|
+
const { collection, listing } = answer!;
|
|
1027
|
+
const menu = await storefront.GET("/v2/products/facets/{key}", {
|
|
1028
|
+
params: {
|
|
1029
|
+
path: { key: "brand" },
|
|
1030
|
+
query: { ...facetScope({ pageSize: 24 }, { collection: collection.id }), match: searchText.trim() || undefined },
|
|
1031
|
+
},
|
|
1032
|
+
});
|
|
1033
|
+
const nextPage = { page: listing.page + 1, pageSize: listing.pageSize };
|
|
1034
|
+
const head = collectionHead(answer!, headOptions);
|
|
1035
|
+
```
|
|
1036
|
+
|
|
1037
|
+
### Discount-code links
|
|
1038
|
+
|
|
1039
|
+
`@asstio-dev/storefront/code-link` lets a link carry a discount code: `shop.example/?kod=VALKOMMEN10`,
|
|
1040
|
+
`shop.example/produkt/x?kod=VALKOMMEN10` (straight to a product, `?variant=` and utm parameters kept) or the short form
|
|
1041
|
+
`shop.example/kod/VALKOMMEN10` (lands on `/`; `/kod/VALKOMMEN10/produkt/x` lands on `/produkt/x`).
|
|
1042
|
+
|
|
1043
|
+
The landing never creates a cart. The proxy answers the link with a `307` to the same URL without the code and remembers
|
|
1044
|
+
the code in the HttpOnly cookie `__Host-sf_code` (7 days by default). The code is put on the cart by the next server code
|
|
1045
|
+
that holds a cart token. The cookie is cleared once the API has decided (applied, `PROMOTION_CODE_UNKNOWN`, `_INVALID` or
|
|
1046
|
+
`_NOT_APPLICABLE`) and kept on a rate limit, a cart conflict or a server error. The redirect keeps the referrer, so
|
|
1047
|
+
attribution capture on the clean page still sees the landing. A code from a link replaces the cart's code, as typing it would.
|
|
1048
|
+
|
|
1049
|
+
```ts
|
|
1050
|
+
// proxy.ts (middleware.ts before Next 16): first, before anything else that reads the URL.
|
|
1051
|
+
import { codeLinkResponse } from "@asstio-dev/storefront/code-link";
|
|
1052
|
+
const CODE_LINKS = { params: ["kod"], paths: ["/kod"] }; // default params: ["code"]; no short form by default
|
|
1053
|
+
export function proxy(request: Request) {
|
|
1054
|
+
return codeLinkResponse(request, CODE_LINKS) ?? undefined; // or hand on to the rest of the proxy
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// The add-to-cart Server Action (or the cart route handler), after the cart exists:
|
|
1058
|
+
import { cookies } from "next/headers";
|
|
1059
|
+
import { codeReasonText } from "@asstio-dev/storefront";
|
|
1060
|
+
import { consumePendingCode } from "@asstio-dev/storefront/code-link";
|
|
1061
|
+
const applied = await consumePendingCode(await cookies(), storefront, cartToken, { origin: "https://shop.example", shopper });
|
|
1062
|
+
if (applied && !applied.ok && applied.problem.code === "PROMOTION_CODE_NOT_APPLICABLE")
|
|
1063
|
+
message = codeReasonText(String(applied.problem.reason ?? ""), locale);
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
The short-form prefix must not be a real page path of the shop. A Server Component render cannot set cookies, so call
|
|
1067
|
+
`consumePendingCode` from a Server Action or a route handler. Prices in listings and on product pages do not include the
|
|
1068
|
+
code yet; the cart shows what it does.
|
|
1069
|
+
|
|
1005
1070
|
## Headers
|
|
1006
1071
|
|
|
1007
1072
|
The client sets `X-Site-Key` and the context it was built with: `X-Market`, `X-Country` and `X-Locale`, from `market`,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CartLineDto, type CheckoutCartLineDto, type OrderLineDto, type ProductCardDto, type ProductDto, type ProductFacts, type SelectedVariant } from "./types.js";
|
|
1
|
+
import { type CartLineDto, type CheckoutCartLineDto, type OrderLineDto, type ProductCardDto, type ProductCardV2Dto, type ProductDto, type ProductFacts, type SelectedVariant } from "./types.js";
|
|
2
2
|
/**
|
|
3
3
|
* The product facts of a card, a product page (with or without a selected variant), a cart line, a checkout cart line or an order line, so a
|
|
4
4
|
* frontend never needs to know where a surface keeps them. Returns the DTO's own arrays and objects — never copies,
|
|
@@ -6,6 +6,7 @@ import { type CartLineDto, type CheckoutCartLineDto, type OrderLineDto, type Pro
|
|
|
6
6
|
* family brand (null can mean an explicit "none"). An order line that is not a product line throws.
|
|
7
7
|
*/
|
|
8
8
|
export declare function productFacts(source: ProductCardDto): ProductFacts;
|
|
9
|
+
export declare function productFacts(source: ProductCardV2Dto): ProductFacts;
|
|
9
10
|
export declare function productFacts(source: ProductDto): ProductFacts;
|
|
10
11
|
export declare function productFacts(source: SelectedVariant): ProductFacts;
|
|
11
12
|
export declare function productFacts(source: CartLineDto): ProductFacts;
|
package/dist/analytics/facts.js
CHANGED
|
@@ -23,11 +23,15 @@ export function productFacts(source) {
|
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
25
|
const flat = source;
|
|
26
|
-
|
|
26
|
+
// A v2 card has no `attributes` (spec §6.9): a valid card (a string `sku`, an array `categories`) reads them as `[]`, "not supplied by
|
|
27
|
+
// this representation". Anything else, and an `attributes` that is present but not an array, is not a source.
|
|
28
|
+
const attributes = "attributes" in flat && flat.attributes !== undefined ? flat.attributes : typeof flat.sku === "string" ? [] : undefined;
|
|
29
|
+
if (!Array.isArray(flat.categories) || !Array.isArray(attributes))
|
|
27
30
|
throw new AnalyticsError("not a product facts source");
|
|
31
|
+
const short = flat.shortDescription;
|
|
28
32
|
return {
|
|
29
|
-
brand: flat.brand, productBrand: flat.brand, categories: flat.categories, primaryCategory: flat.primaryCategory ?? null, attributes
|
|
30
|
-
shortDescription:
|
|
33
|
+
brand: flat.brand, productBrand: flat.brand, categories: flat.categories, primaryCategory: flat.primaryCategory ?? null, attributes,
|
|
34
|
+
shortDescription: short ?? null,
|
|
31
35
|
};
|
|
32
36
|
}
|
|
33
37
|
const isObject = (v) => typeof v === "object" && v !== null;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { components } from "../schema";
|
|
2
2
|
type Schemas = components["schemas"];
|
|
3
3
|
export type ProductCardDto = Schemas["ProductCardDto"];
|
|
4
|
+
/** A v2 listing card (spec §6.9): the same product facts as a v1 card, without `attributes`, `collections`, `updatedAt` and `shortDescription`. */
|
|
5
|
+
export type ProductCardV2Dto = Schemas["ProductCardV2Dto"];
|
|
4
6
|
export type ProductDto = Schemas["ProductDto"];
|
|
5
7
|
export type VariantDto = Schemas["VariantDto"];
|
|
6
8
|
export type CartDto = Schemas["CartDto"];
|
|
@@ -77,7 +79,7 @@ export type Ga4ItemOptions = Ga4SharedOptions & {
|
|
|
77
79
|
itemId?: string;
|
|
78
80
|
index?: number;
|
|
79
81
|
};
|
|
80
|
-
export type Ga4ItemSource = ProductCardDto | SelectedVariant | CartLineDto | CheckoutCartLineDto | OrderLineDto;
|
|
82
|
+
export type Ga4ItemSource = ProductCardDto | ProductCardV2Dto | SelectedVariant | CartLineDto | CheckoutCartLineDto | OrderLineDto;
|
|
81
83
|
/** `view_cart`, `begin_checkout` and the like. */
|
|
82
84
|
export type Ga4Ecommerce = {
|
|
83
85
|
currency: string;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@asstio-dev/storefront/code-link`: discount-code links. A link such as `noly.se/?kod=VALKOMMEN10`,
|
|
3
|
+
* `noly.se/produkt/x?kod=VALKOMMEN10` or the short form `noly.se/kod/VALKOMMEN10` puts the code on the shopper's cart
|
|
4
|
+
* without any typing.
|
|
5
|
+
*
|
|
6
|
+
* Two steps, so that a landing never creates a cart (link previews and crawlers would otherwise leave empty carts behind and
|
|
7
|
+
* spend the cart's failed-code budget):
|
|
8
|
+
*
|
|
9
|
+
* 1. **Landing** (the frontend's proxy/middleware): `codeLinkResponse(request, opts)` answers a link with a `307` to the same
|
|
10
|
+
* URL without the code (every other parameter, utm included, is kept) and remembers the code in an HttpOnly cookie. The
|
|
11
|
+
* redirect keeps the referrer, so attribution capture on the clean page still sees the landing.
|
|
12
|
+
* 2. **Apply** (server code that holds a cart token: the add-to-cart Server Action, the cart route handler):
|
|
13
|
+
* `consumePendingCode(store, client, cartToken, opts)` puts a remembered code on the cart through `POST /v1/cart/codes` and
|
|
14
|
+
* clears the cookie once the API has decided (applied, unknown, invalid or not applicable). A rate limit, a conflict or a
|
|
15
|
+
* transport failure keeps it for the next call.
|
|
16
|
+
*
|
|
17
|
+
* The code is never priced here: the cart answers with what the code does. The link carries no price.
|
|
18
|
+
*/
|
|
19
|
+
import type { Client } from "openapi-fetch";
|
|
20
|
+
import type { StorefrontPaths } from "../index.js";
|
|
21
|
+
import { type CartCodeOptions, type CartCodeResult } from "../cart-codes.js";
|
|
22
|
+
import { type CookieSecurity, type CookieSpec } from "../account/cookies.js";
|
|
23
|
+
export interface CodeLinkOptions {
|
|
24
|
+
/** Query parameter names that carry a code, matched without regard to case. Default `["code"]`; Noly uses `["kod"]`. */
|
|
25
|
+
params?: readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* Path prefixes of the short form, e.g. `"/kod"`: `/kod/VALKOMMEN10` lands on `/`, `/kod/VALKOMMEN10/produkt/x` on
|
|
28
|
+
* `/produkt/x`. Default none. The prefix must not be a real page path of the shop.
|
|
29
|
+
*/
|
|
30
|
+
paths?: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
/** A link's code (normalized; null when the text is not a well-formed code) and the clean same-origin path to land on. */
|
|
33
|
+
export interface CodeLink {
|
|
34
|
+
code: string | null;
|
|
35
|
+
location: string;
|
|
36
|
+
}
|
|
37
|
+
/** The API's code rule (`PromotionCodes`): trimmed, upper case, 3–32 of `A–Z 0–9 - _`. Null when the text is not one. */
|
|
38
|
+
export declare function normalizeCode(raw: string | null | undefined): string | null;
|
|
39
|
+
/**
|
|
40
|
+
* Reads a code link from a URL. Null when the URL is no code link (no code parameter, no short-form prefix), so the request
|
|
41
|
+
* goes on as it is. Otherwise the code and the location: the same path and query with every code parameter removed (the short
|
|
42
|
+
* form's prefix and code segment too). A malformed code still yields a location, so the parameter is dropped either way.
|
|
43
|
+
*/
|
|
44
|
+
export declare function readCodeLink(url: string | URL, opts?: CodeLinkOptions): CodeLink | null;
|
|
45
|
+
interface CodeCookie {
|
|
46
|
+
/** The remembered code: HttpOnly, `days` (default 7) from the landing. */
|
|
47
|
+
(code: string, opts: CookieSecurity & {
|
|
48
|
+
days?: number;
|
|
49
|
+
}): CookieSpec;
|
|
50
|
+
clear(opts: CookieSecurity): CookieSpec;
|
|
51
|
+
cookieName(opts: CookieSecurity): string;
|
|
52
|
+
}
|
|
53
|
+
export declare const codeCookie: CodeCookie;
|
|
54
|
+
/**
|
|
55
|
+
* The landing step for a proxy/middleware (any runtime with the Fetch API; in Next.js return it from `proxy.ts`/`middleware.ts`
|
|
56
|
+
* when it is not null). A `GET`/`HEAD` code link answers `307` to the clean location, `Cache-Control: no-store`, and sets the
|
|
57
|
+
* code cookie when the code is well formed (a malformed one leaves an earlier cookie alone). Anything else is null.
|
|
58
|
+
*/
|
|
59
|
+
export declare function codeLinkResponse(request: Request, opts?: CodeLinkOptions & {
|
|
60
|
+
days?: number;
|
|
61
|
+
}): Response | null;
|
|
62
|
+
/** The cookie store `consumePendingCode` reads and writes: Next's `await cookies()` in a Server Action or route handler. */
|
|
63
|
+
export type CodeCookieStore = {
|
|
64
|
+
get(name: string): {
|
|
65
|
+
value: string;
|
|
66
|
+
} | undefined;
|
|
67
|
+
set(spec: CookieSpec): unknown;
|
|
68
|
+
};
|
|
69
|
+
/** The remembered code, or null (absent or not a well-formed code). */
|
|
70
|
+
export declare function readPendingCode(store: Pick<CodeCookieStore, "get">, opts: {
|
|
71
|
+
origin: string | URL;
|
|
72
|
+
}): string | null;
|
|
73
|
+
/**
|
|
74
|
+
* The apply step: puts the remembered code on the cart. Null when no code is remembered (nothing is sent). Otherwise the
|
|
75
|
+
* `applyCode` answer; the cookie is cleared when the API has decided — applied, or `PROMOTION_CODE_INVALID`/`_UNKNOWN`/
|
|
76
|
+
* `_NOT_APPLICABLE` (show `codeReasonText(problem.reason)` if the shop wants to) — and kept on a rate limit, a cart conflict, a
|
|
77
|
+
* server error or a transport failure (which rejects, like `applyCode`). Call it where cookies can be set: a Server Action or
|
|
78
|
+
* a route handler, not a Server Component render.
|
|
79
|
+
*/
|
|
80
|
+
export declare function consumePendingCode(store: CodeCookieStore, client: Client<StorefrontPaths>, cartToken: string, opts: CartCodeOptions & {
|
|
81
|
+
origin: string | URL;
|
|
82
|
+
}): Promise<CartCodeResult | null>;
|
|
83
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { applyCode } from "../cart-codes.js";
|
|
2
|
+
import { cookieSecurity, serializeCookie } from "../account/cookies.js";
|
|
3
|
+
import { safeReturnPath } from "../account/security.js";
|
|
4
|
+
const CODE = /^[A-Z0-9_-]{3,32}$/;
|
|
5
|
+
const COOKIE = "sf_code";
|
|
6
|
+
const DAY_SECONDS = 24 * 3600;
|
|
7
|
+
const DEFAULT_DAYS = 7;
|
|
8
|
+
const DECIDED = new Set(["PROMOTION_CODE_INVALID", "PROMOTION_CODE_UNKNOWN", "PROMOTION_CODE_NOT_APPLICABLE"]);
|
|
9
|
+
/** The API's code rule (`PromotionCodes`): trimmed, upper case, 3–32 of `A–Z 0–9 - _`. Null when the text is not one. */
|
|
10
|
+
export function normalizeCode(raw) {
|
|
11
|
+
if (typeof raw !== "string")
|
|
12
|
+
return null;
|
|
13
|
+
const code = raw.trim().toUpperCase();
|
|
14
|
+
return CODE.test(code) ? code : null;
|
|
15
|
+
}
|
|
16
|
+
const decode = (s) => {
|
|
17
|
+
try {
|
|
18
|
+
return decodeURIComponent(s);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const prefixOf = (p) => "/" + p.replace(/^\/+|\/+$/g, "").toLowerCase();
|
|
25
|
+
/**
|
|
26
|
+
* Reads a code link from a URL. Null when the URL is no code link (no code parameter, no short-form prefix), so the request
|
|
27
|
+
* goes on as it is. Otherwise the code and the location: the same path and query with every code parameter removed (the short
|
|
28
|
+
* form's prefix and code segment too). A malformed code still yields a location, so the parameter is dropped either way.
|
|
29
|
+
*/
|
|
30
|
+
export function readCodeLink(url, opts = {}) {
|
|
31
|
+
const u = new URL(url);
|
|
32
|
+
const names = new Set((opts.params ?? ["code"]).map((n) => n.toLowerCase()));
|
|
33
|
+
let found = false;
|
|
34
|
+
let code = null;
|
|
35
|
+
let path = u.pathname;
|
|
36
|
+
for (const raw of opts.paths ?? []) {
|
|
37
|
+
const prefix = prefixOf(raw);
|
|
38
|
+
if (prefix === "/")
|
|
39
|
+
continue;
|
|
40
|
+
const lower = path.toLowerCase();
|
|
41
|
+
if (!lower.startsWith(prefix + "/"))
|
|
42
|
+
continue;
|
|
43
|
+
const rest = path.slice(prefix.length + 1);
|
|
44
|
+
const slash = rest.indexOf("/");
|
|
45
|
+
const segment = slash < 0 ? rest : rest.slice(0, slash);
|
|
46
|
+
if (segment === "")
|
|
47
|
+
continue;
|
|
48
|
+
found = true;
|
|
49
|
+
code = normalizeCode(decode(segment));
|
|
50
|
+
path = slash < 0 ? "/" : rest.slice(slash);
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
const kept = new URLSearchParams();
|
|
54
|
+
for (const [name, value] of u.searchParams) {
|
|
55
|
+
if (names.has(name.toLowerCase())) {
|
|
56
|
+
found = true;
|
|
57
|
+
code ??= normalizeCode(value);
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
kept.append(name, value);
|
|
61
|
+
}
|
|
62
|
+
if (!found)
|
|
63
|
+
return null;
|
|
64
|
+
const query = kept.toString();
|
|
65
|
+
return { code, location: safeReturnPath(path + (query ? "?" + query : ""), "/") };
|
|
66
|
+
}
|
|
67
|
+
const named = ({ secure }) => (secure ? "__Host-" + COOKIE : COOKIE);
|
|
68
|
+
const spec = (value, maxAge, { secure }) => ({ name: named({ secure }), value, httpOnly: true, secure, sameSite: "lax", path: "/", maxAge: Math.max(0, Math.floor(maxAge)) });
|
|
69
|
+
export const codeCookie = Object.assign((code, opts) => spec(code, (opts.days ?? DEFAULT_DAYS) * DAY_SECONDS, opts), {
|
|
70
|
+
clear: (opts) => spec("", 0, opts),
|
|
71
|
+
cookieName: (opts) => named(opts),
|
|
72
|
+
});
|
|
73
|
+
/**
|
|
74
|
+
* The landing step for a proxy/middleware (any runtime with the Fetch API; in Next.js return it from `proxy.ts`/`middleware.ts`
|
|
75
|
+
* when it is not null). A `GET`/`HEAD` code link answers `307` to the clean location, `Cache-Control: no-store`, and sets the
|
|
76
|
+
* code cookie when the code is well formed (a malformed one leaves an earlier cookie alone). Anything else is null.
|
|
77
|
+
*/
|
|
78
|
+
export function codeLinkResponse(request, opts = {}) {
|
|
79
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
80
|
+
return null;
|
|
81
|
+
const link = readCodeLink(request.url, opts);
|
|
82
|
+
if (!link)
|
|
83
|
+
return null;
|
|
84
|
+
const headers = new Headers({ Location: link.location, "Cache-Control": "no-store" });
|
|
85
|
+
if (link.code)
|
|
86
|
+
headers.append("Set-Cookie", serializeCookie(codeCookie(link.code, { ...cookieSecurity(request.url), days: opts.days })));
|
|
87
|
+
return new Response(null, { status: 307, headers });
|
|
88
|
+
}
|
|
89
|
+
/** The remembered code, or null (absent or not a well-formed code). */
|
|
90
|
+
export function readPendingCode(store, opts) {
|
|
91
|
+
return normalizeCode(store.get(codeCookie.cookieName(cookieSecurity(opts.origin)))?.value);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The apply step: puts the remembered code on the cart. Null when no code is remembered (nothing is sent). Otherwise the
|
|
95
|
+
* `applyCode` answer; the cookie is cleared when the API has decided — applied, or `PROMOTION_CODE_INVALID`/`_UNKNOWN`/
|
|
96
|
+
* `_NOT_APPLICABLE` (show `codeReasonText(problem.reason)` if the shop wants to) — and kept on a rate limit, a cart conflict, a
|
|
97
|
+
* server error or a transport failure (which rejects, like `applyCode`). Call it where cookies can be set: a Server Action or
|
|
98
|
+
* a route handler, not a Server Component render.
|
|
99
|
+
*/
|
|
100
|
+
export async function consumePendingCode(store, client, cartToken, opts) {
|
|
101
|
+
const code = readPendingCode(store, opts);
|
|
102
|
+
if (code === null)
|
|
103
|
+
return null;
|
|
104
|
+
const { origin, ...codeOpts } = opts;
|
|
105
|
+
const result = await applyCode(client, cartToken, code, codeOpts);
|
|
106
|
+
if (result.ok || DECIDED.has(result.problem.code ?? ""))
|
|
107
|
+
store.set(codeCookie.clear(cookieSecurity(origin)));
|
|
108
|
+
return result;
|
|
109
|
+
}
|
package/dist/filters.d.ts
CHANGED
|
@@ -18,5 +18,5 @@ export declare function decodeFilterValues(param: string): string[];
|
|
|
18
18
|
* basis (`inc` or `ex`) and currency, which the API sets on the price facet only. A slider labels itself from this ("excl.
|
|
19
19
|
* VAT, SEK" for a dealer, "incl. VAT, EUR" for a consumer) rather than assuming a basis; null for any other facet.
|
|
20
20
|
*/
|
|
21
|
-
export declare function priceFacetBasis(facet: FacetDto): PriceBasisDto | null;
|
|
21
|
+
export declare function priceFacetBasis(facet: Pick<FacetDto, "range" | "priceBasis">): PriceBasisDto | null;
|
|
22
22
|
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -44,6 +44,7 @@ export type FilterSelection = NonNullable<NonNullable<paths["/v1/products"]["get
|
|
|
44
44
|
* The client sends it as `filter[brand]=dior,chanel` (deepObject), which is what the API reads.
|
|
45
45
|
*/
|
|
46
46
|
export declare function filterQuery(selection: Record<string, string | string[] | undefined>): FilterSelection;
|
|
47
|
+
export { facetScope, type FacetValuesV2Query, type ListingV2Query } from "./listing.js";
|
|
47
48
|
export { decodeFilterValues, encodeFilterValues, priceFacetBasis } from "./filters.js";
|
|
48
49
|
export { coverOffset, fileUrl, fillFactor, formatFactor, formatImage, imageRect, mediaHash, mediaUrl, MediaUrlError, pickWidth, pictureSources, posterUrl, scaledSizes, srcSet, styleToCss, videoSources, type FormatFit, type FormattedImage, type MediaConfig, type MediaDescriptor, type MediaFormat, type PictureSources, type SlotSize, type VideoSource, } from "./media.js";
|
|
49
50
|
export { awaitCompletion, completeCheckout, getCheckoutStatus, getOrder, liveShippingFor, startCheckout, syncCheckout, type CheckoutClient, type ShopperOption, type StartCheckoutOptions, type SyncRetryOptions, type AwaitCompletionOptions } from "./checkout/server.js";
|
package/dist/index.js
CHANGED
|
@@ -37,6 +37,7 @@ export function filterQuery(selection) {
|
|
|
37
37
|
}
|
|
38
38
|
return out;
|
|
39
39
|
}
|
|
40
|
+
export { facetScope } from "./listing.js";
|
|
40
41
|
export { decodeFilterValues, encodeFilterValues, priceFacetBasis } from "./filters.js";
|
|
41
42
|
export { coverOffset, fileUrl, fillFactor, formatFactor, formatImage, imageRect, mediaHash, mediaUrl, MediaUrlError, pickWidth, pictureSources, posterUrl, scaledSizes, srcSet, styleToCss, videoSources, } from "./media.js";
|
|
42
43
|
export { awaitCompletion, completeCheckout, getCheckoutStatus, getOrder, liveShippingFor, startCheckout, syncCheckout } from "./checkout/server.js"; // SyncRetryOptions *(plan review 3 #5)*
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { paths } from "./schema";
|
|
2
|
+
export type ListingV2Query = NonNullable<paths["/v2/products"]["get"]["parameters"]["query"]>;
|
|
3
|
+
export type FacetValuesV2Query = NonNullable<paths["/v2/products/facets/{key}"]["get"]["parameters"]["query"]>;
|
|
4
|
+
/**
|
|
5
|
+
* The facet operation's query for a menu opened on a listing: the listing's `q`, `filter` and `group`, and its collection, without `page`,
|
|
6
|
+
* `pageSize`, `sort`, `origin` or `include`. On a collections route pass the answer's `collection.id` as `opts.collection`; it overrides
|
|
7
|
+
* any `collection` in the listing query (spec §6.2: follow-ups use the returned id). Both operations have `page` and `pageSize` with other
|
|
8
|
+
* meanings, so a listing query passed whole would page the menu by the grid's page.
|
|
9
|
+
*/
|
|
10
|
+
export declare function facetScope(listing: ListingV2Query, opts?: {
|
|
11
|
+
collection?: string;
|
|
12
|
+
}): FacetValuesV2Query;
|
package/dist/listing.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The facet operation's query for a menu opened on a listing: the listing's `q`, `filter` and `group`, and its collection, without `page`,
|
|
3
|
+
* `pageSize`, `sort`, `origin` or `include`. On a collections route pass the answer's `collection.id` as `opts.collection`; it overrides
|
|
4
|
+
* any `collection` in the listing query (spec §6.2: follow-ups use the returned id). Both operations have `page` and `pageSize` with other
|
|
5
|
+
* meanings, so a listing query passed whole would page the menu by the grid's page.
|
|
6
|
+
*/
|
|
7
|
+
export function facetScope(listing, opts) {
|
|
8
|
+
const out = {};
|
|
9
|
+
if (listing.q)
|
|
10
|
+
out.q = listing.q;
|
|
11
|
+
if (listing.filter && Object.keys(listing.filter).length > 0)
|
|
12
|
+
out.filter = listing.filter;
|
|
13
|
+
if (listing.group && Object.keys(listing.group).length > 0)
|
|
14
|
+
out.group = listing.group;
|
|
15
|
+
const collection = opts?.collection ?? listing.collection;
|
|
16
|
+
if (collection)
|
|
17
|
+
out.collection = collection;
|
|
18
|
+
return out;
|
|
19
|
+
}
|