@usequeek/theme-kit 0.1.38 → 0.1.40

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.
@@ -3,6 +3,8 @@
3
3
  import { roundAmount } from '../utils/format';
4
4
  import { gtagPush } from './gtag';
5
5
 
6
+ export { catalogItemId, catalogItemIdForCartLine, toPId, type CatalogItemRef, type CatalogItemSource } from '../utils/catalog-id';
7
+
6
8
  /**
7
9
  * The one place a storefront announces a shopping event.
8
10
  *
@@ -27,7 +29,17 @@ import { gtagPush } from './gtag';
27
29
  */
28
30
 
29
31
  export interface StorefrontEventItem {
32
+ /**
33
+ * The catalog id: a variant is `"{product_p_id}_{variant_p_id}"`, a product without variants is
34
+ * `"{product_p_id}"`, and with no `p_id` the product UUID (see `catalogItemId`; build it with that
35
+ * helper, never from a raw id). A string: GA4, Meta and TikTok all take string ids.
36
+ */
30
37
  item_id: string;
38
+ /**
39
+ * True when `item_id` is a product-group id (see `CatalogItemRef.is_group`). Meta and TikTok
40
+ * get `content_type: 'product_group'` for it. Never sent to GA4.
41
+ */
42
+ is_group?: boolean;
31
43
  item_name: string;
32
44
  /** The unit price actually charged, after discounts. Providers sum price * quantity as revenue. */
33
45
  price: number;
@@ -128,6 +140,7 @@ function normalizeItems(items: unknown): StorefrontEventItem[] {
128
140
  item_name: String(item?.item_name ?? ''),
129
141
  price: Number(item?.price),
130
142
  quantity: Number(item?.quantity),
143
+ ...(item?.is_group === true ? { is_group: true } : {}),
131
144
  }));
132
145
  }
133
146
 
@@ -216,6 +229,10 @@ export function trackStorefrontEvent<K extends StorefrontEventName>(name: K, dat
216
229
 
217
230
  const finite = (value: number): boolean => Number.isFinite(value);
218
231
 
232
+ /** GA4's items: the bus item without `is_group`, which only Meta and TikTok read. */
233
+ const gaItems = (items: StorefrontEventItem[]): Array<Omit<StorefrontEventItem, 'is_group'>> =>
234
+ items.map(({ is_group: _isGroup, ...item }) => item);
235
+
219
236
  /** `{ value }` when it is a real number, nothing otherwise: GA gets no `NaN`. */
220
237
  const valueParam = (value: number): { value: number } | Record<string, never> => (finite(value) ? { value } : {});
221
238
 
@@ -232,16 +249,16 @@ const valueParam = (value: number): { value: number } | Record<string, never> =>
232
249
  function googleAnalyticsSubscriber(event: StorefrontEvent): void {
233
250
  switch (event.name) {
234
251
  case 'product_viewed':
235
- gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
252
+ gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
236
253
  return;
237
254
  case 'search_submitted':
238
255
  gtagPush('event', 'search', { search_term: event.data.search_term });
239
256
  return;
240
257
  case 'product_added_to_cart':
241
- gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
258
+ gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
242
259
  return;
243
260
  case 'checkout_started':
244
- gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
261
+ gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
245
262
  return;
246
263
  case 'checkout_completed': {
247
264
  const { order_no, currency, items, subtotal, tax, shipping } = event.data;
@@ -256,7 +273,7 @@ function googleAnalyticsSubscriber(event: StorefrontEvent): void {
256
273
  currency,
257
274
  ...(typeof tax === 'number' && finite(tax) ? { tax } : {}),
258
275
  ...(typeof shipping === 'number' && finite(shipping) ? { shipping } : {}),
259
- items,
276
+ items: gaItems(items),
260
277
  });
261
278
  }
262
279
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.38",
3
+ "version": "0.1.40",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "The runtime a Queek storefront theme is built on: hooks, stores, page renderer, navigation, shared blocks and locale strings.",
@@ -4,6 +4,7 @@ import { LOCALE_CODE_HEADER, parseLocaleCode, withLocaleQuery, withLocaleTags }
4
4
  import { isMarketPricedPath, readMarketFromCookieString, withMarketQuery } from '../utils/market';
5
5
  import { API_BASE_URL, request, type RequestCachePolicy, type RequestOptions } from './client';
6
6
  import { getActivePlatform } from './platform';
7
+ import { readProxySecret, storefrontProxyHeaders } from './storefront-proxy-auth';
7
8
 
8
9
  /**
9
10
  * Origin of the incoming storefront request, forwarded to the API so it
@@ -223,6 +224,30 @@ export async function readRequestMarket(vendorSlug: string, verify?: (marketId:
223
224
  }
224
225
  }
225
226
 
227
+ /**
228
+ * The S8-B headers for one server-side API call (see `./storefront-proxy-auth`).
229
+ *
230
+ * `cached: true` — the read goes through Next's data cache (`next.revalidate`): the secret only, never the
231
+ * shopper (the cache key includes request headers). `cached: false` — a `no-store` call: the secret plus the
232
+ * incoming request's `cf-connecting-ip` when it has one. No secret configured: `{}`.
233
+ *
234
+ * Reads `headers()` on the uncached path, so call it OUTSIDE a Next cache scope, like `getRequestOrigin`. Outside
235
+ * a request (build, tests) it quietly sends the secret alone.
236
+ */
237
+ export async function getStorefrontApiHeaders(options: { cached: boolean }): Promise<Record<string, string>> {
238
+ if (options.cached) return storefrontProxyHeaders();
239
+ if (!readProxySecret()) return {};
240
+
241
+ let shopperIp: string | null = null;
242
+ try {
243
+ shopperIp = (await headers()).get('cf-connecting-ip');
244
+ } catch {
245
+ shopperIp = null;
246
+ }
247
+
248
+ return storefrontProxyHeaders({ shopperIp });
249
+ }
250
+
226
251
  /** Options of {@link createServerStoreClient}. */
227
252
  export interface ServerStoreClientOptions {
228
253
  /**
@@ -259,25 +284,28 @@ export function createServerStoreClient(vendorSlug: string, origin?: string, opt
259
284
  // leave the shared data cache. The cache is shared by every visitor, its key is the URL, and a rate moves
260
285
  // without any revalidation tag, so a market price is never stored there. No market: today's request.
261
286
  const marketId = isMarketPricedPath(path) ? await readRequestMarket(vendorSlug, options.verifyMarket) : null;
287
+ const cachePolicy =
288
+ marketId !== null || (await isPreviewRender())
289
+ ? null
290
+ : withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code);
262
291
  return request<T>(
263
292
  API_BASE_URL,
264
293
  `/client/store${path}`,
265
294
  {
266
295
  query: withMarketQuery(withLocaleQuery(query, code), marketId),
267
296
  timeoutMs: SSR_TIMEOUT_MS,
268
- cachePolicy: marketId !== null || (await isPreviewRender())
269
- ? null
270
- : withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
297
+ cachePolicy,
271
298
  },
272
- buildHeaders(),
299
+ // A cached read carries only the secret; an uncached one also names the shopper.
300
+ { ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: !!cachePolicy })) },
273
301
  );
274
302
  },
275
- post: <T>(path: string, body?: unknown) =>
303
+ post: async <T>(path: string, body?: unknown) =>
276
304
  request<T>(API_BASE_URL, `/client/store${path}`, {
277
305
  method: 'POST',
278
306
  body: body ? JSON.stringify(body) : undefined,
279
307
  timeoutMs: SSR_TIMEOUT_MS,
280
308
  cachePolicy: null,
281
- }, buildHeaders()),
309
+ }, { ...buildHeaders(), ...(await getStorefrontApiHeaders({ cached: false })) }),
282
310
  };
283
311
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The two headers a storefront SERVER sends the Queek API so the API can tell its own storefront from a
3
+ * shopper, and which shopper a request belongs to (S8-B). Server-only: the secret is a plain env var that
4
+ * never reaches a browser bundle, and this module returns nothing when it runs in one.
5
+ *
6
+ * - `X-Storefront-Proxy-Secret`: the shared secret (`STOREFRONT_PROXY_SECRET`, the same value as on the API).
7
+ * With it the API trusts the next header; without it both are ignored.
8
+ * - `X-Shopper-IP`: the shopper's public address, so the API's per-address limits count that shopper and not
9
+ * this server. Sent only when the caller has a real one (Cloudflare's `cf-connecting-ip`); never guessed from
10
+ * `x-forwarded-for` or `x-real-ip`, and never empty or malformed (the API logs a warning for those).
11
+ *
12
+ * `STOREFRONT_PROXY_SECRET` empty or unset: nothing is sent, which is exactly how the storefront behaved before.
13
+ *
14
+ * Pure on purpose (no `next/headers`): the host app's proxy runs here too and reads `cf-connecting-ip` from its
15
+ * own request. Reads that sit in Next's data cache must pass NO shopper: the cache key includes the request
16
+ * headers, so a per-shopper header would give every visitor their own entry. The secret is one constant value
17
+ * and does not split it.
18
+ */
19
+
20
+ export const PROXY_SECRET_HEADER = 'X-Storefront-Proxy-Secret';
21
+ export const SHOPPER_IP_HEADER = 'X-Shopper-IP';
22
+
23
+ /** The configured secret, or null when unset/blank (and always null in a browser). */
24
+ export function readProxySecret(): string | null {
25
+ if (typeof window !== 'undefined') return null;
26
+ const secret = process.env.STOREFRONT_PROXY_SECRET?.trim();
27
+
28
+ return secret ? secret : null;
29
+ }
30
+
31
+ /**
32
+ * `value` as a shopper address worth sending, else null. A cheap shape check only (hex digits, `.` and `:`, one of
33
+ * the last two present, at most 45 characters, the longest IPv6 text form): the API validates for real, and ignores
34
+ * a private or reserved address.
35
+ */
36
+ export function usableShopperIp(value: string | null | undefined): string | null {
37
+ const ip = value?.trim();
38
+ if (!ip || ip.length > 45) return null;
39
+ if (!/^[0-9a-fA-F:.]+$/.test(ip) || !/[.:]/.test(ip)) return null;
40
+
41
+ return ip;
42
+ }
43
+
44
+ /**
45
+ * The headers to add to one API call: `{}` without a secret, the secret alone, or the secret plus the shopper.
46
+ * Pass `shopperIp` only for a call that is NOT in Next's data cache.
47
+ */
48
+ export function storefrontProxyHeaders(options: { shopperIp?: string | null } = {}): Record<string, string> {
49
+ const secret = readProxySecret();
50
+ if (!secret) return {};
51
+
52
+ const shopper = usableShopperIp(options.shopperIp);
53
+
54
+ return shopper ? { [PROXY_SECRET_HEADER]: secret, [SHOPPER_IP_HEADER]: shopper } : { [PROXY_SECRET_HEADER]: secret };
55
+ }
@@ -7,6 +7,7 @@ import type { Product, ProductVariant } from '../types/product';
7
7
  import { toast } from './toast-store';
8
8
  import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY, roundAmount } from '../utils/format';
9
9
  import { trackStorefrontEvent } from '../apps/storefront-events';
10
+ import { catalogItemId, toPId } from '../utils/catalog-id';
10
11
  import { getActivePlatform, platformScopedStorage } from '../sdk/platform';
11
12
  import { productRequiresVariant } from '../utils/match-variant';
12
13
  import { readLineText } from './line-text-store';
@@ -201,6 +202,9 @@ export const useCartStore = create<CartState>()(
201
202
  });
202
203
  }
203
204
  const addedQuantity = Math.max(1, quantity);
205
+ // The catalog ids of this line (what the pixel sends); null when the payload carries none.
206
+ const productPId = toPId(product.p_id);
207
+ const variantPId = toPId(variant?.p_id);
204
208
 
205
209
  set((state) => {
206
210
  const existing = state.items.findIndex(
@@ -214,6 +218,8 @@ export const useCartStore = create<CartState>()(
214
218
  ...current,
215
219
  quantity: current.quantity + Math.max(1, quantity),
216
220
  unit_price: unitPrice,
221
+ ...(productPId !== null ? { product_p_id: productPId } : {}),
222
+ ...(variantPId !== null ? { variant_p_id: variantPId } : {}),
217
223
  };
218
224
 
219
225
  return { items };
@@ -234,6 +240,9 @@ export const useCartStore = create<CartState>()(
234
240
  addons,
235
241
  variant_id: variant?.id ?? null,
236
242
  variant_title: variant?.title ?? null,
243
+ // Like `properties`: a payload without a p_id leaves the key off, so a line keeps the shape it always had.
244
+ ...(productPId !== null ? { product_p_id: productPId } : {}),
245
+ ...(variantPId !== null ? { variant_p_id: variantPId } : {}),
237
246
  ...(hasLineText ? { properties: lineText.properties, property_labels: lineText.labels } : {}),
238
247
  },
239
248
  ],
@@ -243,7 +252,14 @@ export const useCartStore = create<CartState>()(
243
252
  trackStorefrontEvent('product_added_to_cart', {
244
253
  currency: get().currency,
245
254
  value: roundAmount(unitPrice * addedQuantity),
246
- items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
255
+ items: [
256
+ {
257
+ ...catalogItemId({ variantPId, productPId, hasVariant: variant !== null, fallbackId: product.id }),
258
+ item_name: product.title,
259
+ price: unitPrice,
260
+ quantity: addedQuantity,
261
+ },
262
+ ],
247
263
  });
248
264
 
249
265
  return 'added';
package/types/cart.ts CHANGED
@@ -16,6 +16,13 @@ export interface CartItem {
16
16
  quantity: number;
17
17
  addons: CartAddon[];
18
18
  variant_id?: string | null;
19
+ /**
20
+ * The product's and the variant's `p_id`, the ids a catalog feed uses, kept so the pixel
21
+ * can send them. Absent on a line saved before they existed or read from a cart the API
22
+ * answered without them: `catalogItemIdForCartLine` then falls back.
23
+ */
24
+ product_p_id?: number | null;
25
+ variant_p_id?: number | null;
19
26
  /** e.g. "Denim" — the selected variant's display name, when this line has one. */
20
27
  variant_title?: string | null;
21
28
  /**
package/types/order.ts CHANGED
@@ -25,6 +25,15 @@ export interface OrderItem {
25
25
  unit_price: number | string;
26
26
  addons: Array<Record<string, unknown>>;
27
27
  product?: { id: string; thumbnail_image?: string | null } | null;
28
+ /**
29
+ * What the API sends on an order line to identify it in a catalog: the product's and the variant's
30
+ * `p_id` and the variant's name. All optional: older answers lack them, and the variant's `p_id` is
31
+ * null for a line whose variant was deleted.
32
+ */
33
+ product_p_id?: number | null;
34
+ variant_id?: string | null;
35
+ variant_p_id?: number | null;
36
+ variant_title?: string | null;
28
37
  }
29
38
 
30
39
  export interface OrderTimeline {
package/types/product.ts CHANGED
@@ -101,6 +101,11 @@ export interface ProductVariantOptionValue {
101
101
 
102
102
  export interface ProductVariant {
103
103
  id: string;
104
+ /**
105
+ * The variant's `p_id`, the id ad-platform catalog feeds use for it (feed `id`) and so the id
106
+ * the pixel must send. Absent on a payload that predates it: read it through `catalogItemId`.
107
+ */
108
+ p_id?: number;
104
109
  sku: string | null;
105
110
  /** Printed barcode / GTIN (EAN-13/8, UPC-A/E) for in-store scan-to-cart. */
106
111
  barcode: string | null;
@@ -0,0 +1,83 @@
1
+ import type { CartItem } from '../types/cart';
2
+
3
+ /**
4
+ * The id a shopping event carries for an item, and the ONE place that decides it.
5
+ *
6
+ * THE CATALOG ID RULE (the ad-platform catalog feeds use the same one):
7
+ *
8
+ * - a variant row is `"{product_p_id}_{variant_p_id}"`;
9
+ * - a product without variants is `"{product_p_id}"`;
10
+ * - the `product_group` id (the feed's `item_group_id`) is `"{product_p_id}"`.
11
+ *
12
+ * Products and variants number their `p_id`s from separate sequences that overlap (both
13
+ * start at 1000), so a bare variant `p_id` could equal an unrelated product's: the id of
14
+ * a variant is always the pair. A pixel event matches a catalog item only when it sends
15
+ * that same id.
16
+ *
17
+ * Fallbacks, in order:
18
+ * - a variant `p_id` AND a product `p_id` -> `"P_V"`;
19
+ * - only a product `p_id` -> `"P"` (flagged `is_group` when the
20
+ * item belongs to a product with variants, because then `"P"` names the group, not a row);
21
+ * - a variant `p_id` but NO product `p_id` -> the UUID. A bare variant `p_id` is never sent;
22
+ * - no `p_id` at all -> the product's UUID.
23
+ *
24
+ * The UUID is the last resort for a line that has no `p_id` (a cart saved before the ids
25
+ * existed, an API answer that predates them). It matches no catalog item, which is no
26
+ * worse than before p_ids. When that fallback is no longer needed, deleting the
27
+ * `fallbackId` branch below is the whole cleanup.
28
+ */
29
+ export interface CatalogItemRef {
30
+ item_id: string;
31
+ /**
32
+ * True when `item_id` is a PRODUCT-group id (a product `p_id` standing for a product that
33
+ * has variants, because no variant is known). Meta and TikTok match that against the
34
+ * feed's `item_group_id` only when the event says `content_type: 'product_group'`.
35
+ */
36
+ is_group?: true;
37
+ }
38
+
39
+ export interface CatalogItemSource {
40
+ variantPId?: unknown;
41
+ /** Needed for any p_id id: without it the item falls back to `fallbackId`. */
42
+ productPId?: unknown;
43
+ /** The item is a specific variant (chosen or bought), or belongs to a product that has variants. */
44
+ hasVariant?: boolean;
45
+ /** The product's UUID: the last resort. Never an order or cart line id. */
46
+ fallbackId?: string | null;
47
+ }
48
+
49
+ /** A `p_id` as a number: a positive whole number (a number, or digits in a string). Anything else is null. */
50
+ export function toPId(value: unknown): number | null {
51
+ const number = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : value;
52
+
53
+ return typeof number === 'number' && Number.isSafeInteger(number) && number > 0 ? number : null;
54
+ }
55
+
56
+ export function catalogItemId(source: CatalogItemSource): CatalogItemRef {
57
+ const productPId = toPId(source.productPId);
58
+
59
+ if (productPId === null) {
60
+ // No product p_id: never a bare variant p_id (variant and product p_ids overlap), so the UUID.
61
+ return { item_id: source.fallbackId ?? '' };
62
+ }
63
+
64
+ const variantPId = toPId(source.variantPId);
65
+
66
+ if (variantPId !== null) {
67
+ return { item_id: `${productPId}_${variantPId}` };
68
+ }
69
+
70
+ return source.hasVariant === true ? { item_id: String(productPId), is_group: true } : { item_id: String(productPId) };
71
+ }
72
+
73
+ /** The catalog id of a cart line (`CartItem`). */
74
+ export function catalogItemIdForCartLine(
75
+ line: Pick<CartItem, 'product_id' | 'variant_id' | 'product_p_id' | 'variant_p_id'>,
76
+ ): CatalogItemRef {
77
+ return catalogItemId({
78
+ variantPId: line.variant_p_id,
79
+ productPId: line.product_p_id,
80
+ hasVariant: typeof line.variant_id === 'string' && line.variant_id !== '',
81
+ fallbackId: line.product_id,
82
+ });
83
+ }
@@ -9,6 +9,7 @@ import type {
9
9
  ProductVariantOptionValue,
10
10
  } from '../types/product';
11
11
  import { normalizeCurrencyCode } from './format';
12
+ import { toPId } from './catalog-id';
12
13
 
13
14
  const KIND_SET = new Set(['physical', 'service', 'digital']);
14
15
  const STATUS_SET = new Set(['active', 'inactive']);
@@ -331,6 +332,8 @@ export function normalizeProduct(raw: LegacyProductLike): Product {
331
332
 
332
333
  return {
333
334
  id: String(variant.id ?? `variant-${index}`),
335
+ // Only a real `p_id` (a positive whole number) is carried; a payload without one keeps its shape.
336
+ ...(toPId(variant.p_id) !== null ? { p_id: toPId(variant.p_id) as number } : {}),
334
337
  sku: variant.sku ?? null,
335
338
  barcode: typeof variant.barcode === 'string' && variant.barcode !== '' ? variant.barcode : null,
336
339
  title: variant.title ?? null,
@@ -5,6 +5,8 @@
5
5
  * server fetchers and a host app's proxy can both import it.
6
6
  */
7
7
 
8
+ import { storefrontProxyHeaders } from '../sdk/storefront-proxy-auth';
9
+
8
10
  // Mirrors the API's reserved store slugs. Keep in sync.
9
11
  // These are subdomains the storefront proxy must NOT treat as vendor slugs.
10
12
  export const RESERVED_VENDOR_SLUGS = new Set([
@@ -167,16 +169,64 @@ export function resolveCustomDomainVendorSlug(hostname: string): string | null {
167
169
  }
168
170
  }
169
171
 
170
- export async function resolveCustomDomainVendorSlugRemote(hostname: string): Promise<string | null> {
172
+ /**
173
+ * What `resolve-by-host` said about a host. Three answers, never two:
174
+ *
175
+ * - `store` a store lives on this host (`slug`);
176
+ * - `not-store` DEFINITELY no store: the API answered 200, `status: 'success'` and `data.slug: null`;
177
+ * - `unknown` the API did not answer usefully: 404 (the API never sends one for a host), 429, 5xx, any
178
+ * other status, a timeout, a
179
+ * network error, an unreadable body, no API URL configured.
180
+ *
181
+ * Only `not-store` may become a 404 for the visitor. `unknown` is an outage, not an answer, and
182
+ * must fail open (render as before) and never be remembered.
183
+ */
184
+ export type HostLookup =
185
+ | { kind: 'store'; slug: string }
186
+ | { kind: 'not-store' }
187
+ | {
188
+ kind: 'unknown';
189
+ /**
190
+ * Set only when the API answered 429: this caller's own budget (or the server's) is spent. `retryAfterSeconds`
191
+ * is the API's `Retry-After`, or null when it sent none or an unreadable one. Still `unknown` for every
192
+ * purpose that treats an outage as one; it is here so a host app can tell a 429 from other outages, e.g. to
193
+ * retry once as itself (without a shopper address) when the shopper's own budget is what ran out.
194
+ */
195
+ rateLimited?: { retryAfterSeconds: number | null };
196
+ };
197
+
198
+ export interface LookupStoreByHostOptions {
199
+ /**
200
+ * `'no-store'` keeps Next's Data Cache out of this call (no `next.revalidate`, no tags), for a caller that
201
+ * does its own caching and must see a fresh answer when its own entry expires (the host app's proxy).
202
+ * Omitted: the fetch is revalidated every 5 minutes and tagged `host:<hostname>`, as it always was.
203
+ */
204
+ cache?: 'no-store';
205
+ /**
206
+ * The shopper this lookup is made for (the request's `cf-connecting-ip`), sent as `X-Shopper-IP` so a scanner
207
+ * rotating random hosts spends its own per-address budget, not the storefront server's. Only used with
208
+ * `cache: 'no-store'`: a cached read must not carry a per-shopper header (it would split the data cache).
209
+ */
210
+ shopperIp?: string | null;
211
+ }
212
+
213
+ /**
214
+ * Asks `resolve-by-host` about one host and reports which of the three answers came back. Never throws.
215
+ *
216
+ * The API ALWAYS answers a known or unknown host with 200 `{ status: 'success', data: { slug: <slug|null> } }`.
217
+ * So `not-store` is exactly that: HTTP 200, `status === 'success'`, `data.slug === null`. A 404 (a wrong API URL,
218
+ * a gateway answering during a deploy) or anything else off-contract is `unknown`.
219
+ */
220
+ export async function lookupStoreByHost(hostname: string, options: LookupStoreByHostOptions = {}): Promise<HostLookup> {
171
221
  if (!hostname) {
172
- return null;
222
+ return { kind: 'unknown' };
173
223
  }
174
224
 
175
225
  // Middleware runs server-side — prefer the server-only absolute URL. The
176
226
  // public var can be a same-origin relative path, which `fetch()` can't resolve without a document origin here.
177
227
  const baseUrl = process.env.QUEEK_API_URL ?? process.env.NEXT_PUBLIC_QUEEK_API_URL;
178
228
  if (!baseUrl) {
179
- return null;
229
+ return { kind: 'unknown' };
180
230
  }
181
231
 
182
232
  const url = `${baseUrl.replace(/\/+$/, '')}/client/resolve-by-host?host=${encodeURIComponent(hostname)}`;
@@ -186,31 +236,54 @@ export async function resolveCustomDomainVendorSlugRemote(hostname: string): Pro
186
236
  try {
187
237
  const response = await fetch(url, {
188
238
  method: 'GET',
189
- headers: { Accept: 'application/json' },
239
+ // The S8-B secret rides every lookup (when configured); the shopper only the uncached one.
240
+ headers: { Accept: 'application/json', ...storefrontProxyHeaders(options.cache === 'no-store' ? { shopperIp: options.shopperIp } : {}) },
190
241
  signal: controller.signal,
191
- next: {
192
- revalidate: REMOTE_RESOLVE_REVALIDATE_SECONDS,
193
- tags: [`host:${hostname}`],
194
- },
242
+ ...(options.cache === 'no-store'
243
+ ? { cache: 'no-store' as const }
244
+ : { next: { revalidate: REMOTE_RESOLVE_REVALIDATE_SECONDS, tags: [`host:${hostname}`] } }),
195
245
  });
196
246
 
197
247
  if (!response.ok) {
198
248
  logRemoteFailure(`status ${response.status}`);
199
- return null;
249
+ if (response.status === 429) {
250
+ const raw = response.headers.get('retry-after');
251
+ const seconds = raw === null || raw.trim() === '' ? NaN : Number(raw);
252
+ return { kind: 'unknown', rateLimited: { retryAfterSeconds: Number.isFinite(seconds) && seconds >= 0 ? Math.ceil(seconds) : null } };
253
+ }
254
+ return { kind: 'unknown' };
200
255
  }
201
256
 
202
- const payload = (await response.json()) as { data?: { slug?: unknown } };
203
- const slug = payload?.data?.slug;
257
+ const payload = (await response.json()) as { status?: unknown; data?: { slug?: unknown } } | null;
258
+ const data = payload?.data;
259
+ if (!data || typeof data !== 'object' || !('slug' in data)) {
260
+ // 200 without the field the API always sends (a CDN or captive page in front of it):
261
+ // not an answer about this host.
262
+ logRemoteFailure('unexpected body');
263
+ return { kind: 'unknown' };
264
+ }
204
265
 
205
- return typeof slug === 'string' && slug !== '' ? slug : null;
266
+ const { slug } = data;
267
+ if (typeof slug === 'string' && slug !== '') {
268
+ return { kind: 'store', slug };
269
+ }
270
+
271
+ // The one definite "no": the API's own success envelope carrying a null slug.
272
+ return slug === null && payload?.status === 'success' ? { kind: 'not-store' } : { kind: 'unknown' };
206
273
  } catch (error) {
207
274
  logRemoteFailure(error instanceof Error ? error.message : 'unknown');
208
- return null;
275
+ return { kind: 'unknown' };
209
276
  } finally {
210
277
  clearTimeout(timeoutId);
211
278
  }
212
279
  }
213
280
 
281
+ export async function resolveCustomDomainVendorSlugRemote(hostname: string): Promise<string | null> {
282
+ const lookup = await lookupStoreByHost(hostname);
283
+
284
+ return lookup.kind === 'store' ? lookup.slug : null;
285
+ }
286
+
214
287
  function logRemoteFailure(reason: string): void {
215
288
  const now = Date.now();
216
289
  if (now - lastRemoteFailureLoggedAt < REMOTE_FAILURE_LOG_WINDOW_MS) {
@@ -254,3 +327,67 @@ export async function resolveVendorSlug(options: {
254
327
 
255
328
  return options.searchVendor;
256
329
  }
330
+
331
+ /**
332
+ * The host without its port or one trailing root dot (`acme.queek.app.:443` is `acme.queek.app`: a fully
333
+ * qualified name is the same host); keeps a bracketed IPv6 literal whole (`[::1]:3001` → `[::1]`).
334
+ */
335
+ function hostnameOf(host: string | null): string {
336
+ return (host ?? '').trim().toLowerCase().replace(/:\d+$/, '').replace(/\.$/, '');
337
+ }
338
+
339
+ export interface VendorHostResolution {
340
+ /**
341
+ * The store this request is for, or null. Set from the host when the lookup says `store`; from the
342
+ * subdomain label while the lookup is `unknown` (fail open, as before); from `?vendor=` otherwise.
343
+ */
344
+ slug: string | null;
345
+ /**
346
+ * What the host lookup concluded. `not-store` is a definite answer; `unknown` covers an outage AND
347
+ * every case where no lookup was made (no host, no API URL).
348
+ */
349
+ outcome: HostLookup['kind'];
350
+ }
351
+
352
+ /**
353
+ * `resolveVendorSlug`, but it says WHY there is no slug — so the host app can answer 404 for a host
354
+ * that is definitely not a store without ever mistaking an outage for one — and it checks that a
355
+ * subdomain store actually exists (the older function trusts any `{label}.<store domain>`).
356
+ *
357
+ * `lookup` replaces the API call; a host app passes a cached one. It must behave like
358
+ * `lookupStoreByHost`: never throw, `unknown` for anything that is not a definite answer.
359
+ *
360
+ * Order, as in `resolveVendorSlug`: subdomain, static custom-domain map, remote lookup, `?vendor=`.
361
+ */
362
+ export async function resolveVendorHost(options: {
363
+ host: string | null;
364
+ searchVendor: string | null;
365
+ lookup?: (hostname: string) => Promise<HostLookup>;
366
+ }): Promise<VendorHostResolution> {
367
+ const hostname = hostnameOf(options.host);
368
+ const lookup = options.lookup ?? lookupStoreByHost;
369
+ const subdomainSlug = resolveSubdomainVendorSlug(hostname);
370
+
371
+ if (subdomainSlug) {
372
+ const found = await lookup(hostname);
373
+ if (found.kind === 'store') return { slug: found.slug, outcome: 'store' };
374
+ // Unknown: the label is trusted, exactly as before the check existed.
375
+ if (found.kind === 'unknown') return { slug: subdomainSlug, outcome: 'unknown' };
376
+
377
+ return { slug: options.searchVendor, outcome: 'not-store' };
378
+ }
379
+
380
+ const staticCustomDomainSlug = resolveCustomDomainVendorSlug(hostname);
381
+ if (staticCustomDomainSlug) {
382
+ return { slug: staticCustomDomainSlug, outcome: 'store' };
383
+ }
384
+
385
+ if (!hostname) {
386
+ return { slug: options.searchVendor, outcome: 'unknown' };
387
+ }
388
+
389
+ const found = await lookup(hostname);
390
+ if (found.kind === 'store') return { slug: found.slug, outcome: 'store' };
391
+
392
+ return { slug: options.searchVendor, outcome: found.kind };
393
+ }