@revenexx/cover 0.23.0 → 0.24.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.
@@ -80,7 +80,7 @@ function changeBilling() {
80
80
  v-if="!profileLoading"
81
81
  variant="ghost"
82
82
  size="sm"
83
- class="shrink-0"
83
+ class="shrink-0 min-h-11 lg:min-h-0"
84
84
  tabindex="0"
85
85
  @click="showShippingPicker = true"
86
86
  >
@@ -155,7 +155,7 @@ function changeBilling() {
155
155
  v-if="!profileLoading"
156
156
  variant="ghost"
157
157
  size="sm"
158
- class="shrink-0"
158
+ class="shrink-0 min-h-11 lg:min-h-0"
159
159
  tabindex="0"
160
160
  @click="changeBilling"
161
161
  >
@@ -65,6 +65,7 @@ const addressFields: AddressFieldRow[] = [
65
65
  type="email"
66
66
  autocomplete="email"
67
67
  class="w-full"
68
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
68
69
  @blur="validateField('guestEmail')"
69
70
  />
70
71
  </UFormField>
@@ -74,6 +75,7 @@ const addressFields: AddressFieldRow[] = [
74
75
  type="tel"
75
76
  autocomplete="tel"
76
77
  class="w-full"
78
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
77
79
  />
78
80
  </UFormField>
79
81
  </div>
@@ -98,6 +100,7 @@ const addressFields: AddressFieldRow[] = [
98
100
  <UInput
99
101
  v-model="guestShipping[field.key]"
100
102
  class="w-full"
103
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
101
104
  @update:model-value="clearFieldError(`guestShipping.${field.key}`)"
102
105
  />
103
106
  </UFormField>
@@ -111,6 +114,7 @@ const addressFields: AddressFieldRow[] = [
111
114
  v-model="guestShipping.country"
112
115
  :items="countryItems"
113
116
  class="w-full"
117
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
114
118
  @update:model-value="clearFieldError('guestShipping.country')"
115
119
  />
116
120
  </UFormField>
@@ -141,6 +145,7 @@ const addressFields: AddressFieldRow[] = [
141
145
  <UInput
142
146
  v-model="guestBilling[field.key]"
143
147
  class="w-full"
148
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
144
149
  @update:model-value="clearFieldError(`guestBilling.${field.key}`)"
145
150
  />
146
151
  </UFormField>
@@ -154,6 +159,7 @@ const addressFields: AddressFieldRow[] = [
154
159
  v-model="guestBilling.country"
155
160
  :items="countryItems"
156
161
  class="w-full"
162
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
157
163
  @update:model-value="clearFieldError('guestBilling.country')"
158
164
  />
159
165
  </UFormField>
@@ -26,6 +26,7 @@ const { form, isGuest, orderNumberRequired, fieldErrors, validateField } = useCh
26
26
  v-model="form.orderNumber"
27
27
  maxlength="20"
28
28
  class="w-full"
29
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
29
30
  :placeholder="t('onepage.orderInfo.orderNumberPlaceholder')"
30
31
  @blur="validateField('orderNumber')"
31
32
  />
@@ -38,6 +39,7 @@ const { form, isGuest, orderNumberRequired, fieldErrors, validateField } = useCh
38
39
  v-model="form.quoteNumber"
39
40
  maxlength="20"
40
41
  class="w-full"
42
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
41
43
  :placeholder="t('onepage.orderInfo.quoteNumberPlaceholder')"
42
44
  />
43
45
  </UFormField>
@@ -249,6 +249,7 @@ if (import.meta.client) {
249
249
  <UInput
250
250
  v-model="form.poNumber"
251
251
  class="w-full sm:max-w-sm"
252
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
252
253
  :placeholder="t('onepage.payment.poNumberPlaceholder')"
253
254
  />
254
255
  </div>
@@ -263,6 +264,7 @@ if (import.meta.client) {
263
264
  <USelect
264
265
  v-model="form.costCenterId"
265
266
  class="w-full sm:max-w-sm"
267
+ :ui="{ base: 'min-h-11 lg:min-h-0' }"
266
268
  :items="costCenterOptions"
267
269
  />
268
270
  </div>
@@ -82,7 +82,7 @@ function clear(): void {
82
82
  type="button"
83
83
  tabindex="0"
84
84
  :disabled="Boolean(context.disabled)"
85
- class="w-full flex items-center justify-between gap-2 px-3 py-2 text-sm border rounded-md
85
+ class="w-full min-h-11 lg:min-h-0 flex items-center justify-between gap-2 px-3 py-2 text-sm border rounded-md
86
86
  bg-transparent border-(--ui-border) text-left cursor-pointer
87
87
  focus:outline-none focus:ring-2 focus:ring-(--ui-primary)"
88
88
  :class="calendarValue ? 'text-highlighted' : 'text-muted'"
@@ -0,0 +1,86 @@
1
+ /**
2
+ * What a sign-in link carries beside the secret (RAD-472).
3
+ *
4
+ * A mailed link carries `userId` and `secret` only. The link a sales rep opens
5
+ * when acting for a buyer carries more: where the shop should open
6
+ * (`landing`), the handover entry (`acting`), and the buyer's `market`,
7
+ * `locale` and `currency`. The link's values are a suggestion for where the
8
+ * buyer starts, never a grant: each is checked for its form here, and the shop
9
+ * then treats it exactly like the same choice made in the locale selector.
10
+ *
11
+ * Pure functions, shared by the link page and the server redirect in front of
12
+ * it, so both read a link the same way.
13
+ */
14
+
15
+ import { localeLanguage, normalizeLocaleCode } from "./locale";
16
+
17
+ /** Where a handed-over buyer lands, as the sales-reps app names it. */
18
+ export type SignInLanding = "home" | "quick_order";
19
+
20
+ export interface SignInLinkPreferences {
21
+ readonly landing?: SignInLanding;
22
+ readonly market?: string;
23
+ /** The full locale code, `de-DE`, or a bare language, `de`. */
24
+ readonly locale?: string;
25
+ /** The locale's language, `de`. */
26
+ readonly language?: string;
27
+ readonly currency?: string;
28
+ }
29
+
30
+ const LANDINGS: readonly SignInLanding[] = ["home", "quick_order"];
31
+ const MARKET_CODE = /^[a-z][a-z0-9_]{0,62}$/;
32
+ const LOCALE_CODE = /^[a-z]{2,3}(?:-[A-Z]{2})?$/;
33
+ const CURRENCY_CODE = /^[A-Z]{3}$/;
34
+
35
+ const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
36
+
37
+ /** The values of a link's query the shop may follow; anything malformed is left out. */
38
+ export function signInLinkPreferences(query: Readonly<Record<string, unknown>>): SignInLinkPreferences {
39
+ const landing = text(query.landing);
40
+ const market = text(query.market).toLowerCase();
41
+ const locale = normalizeLocaleCode(text(query.locale));
42
+ const currency = text(query.currency).toUpperCase();
43
+ return {
44
+ ...(LANDINGS.includes(landing as SignInLanding) ? { landing: landing as SignInLanding } : {}),
45
+ ...(MARKET_CODE.test(market) ? { market } : {}),
46
+ ...(LOCALE_CODE.test(locale) ? { locale, language: localeLanguage(locale) } : {}),
47
+ ...(CURRENCY_CODE.test(currency) ? { currency } : {}),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * The page a signed-in link opens: the home page or the cart, whose quick entry
53
+ * is the shop's fast product entry, where the link names a landing; the
54
+ * account, as before, where it names none.
55
+ */
56
+ export function signInLinkDestination(preferences: SignInLinkPreferences): string {
57
+ switch (preferences.landing) {
58
+ case "home": return "/";
59
+ case "quick_order": return "/cart";
60
+ default: return "/account";
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The language-prefixed address of the link page for a link that arrived
66
+ * without a prefix, or null when it needs none.
67
+ *
68
+ * Links are minted as `/login/link`, which a shop that prefixes every page with
69
+ * its language does not serve. The link's own `locale` decides the language
70
+ * where the shop speaks it, so a handed-over English buyer lands in English;
71
+ * otherwise the shop's default language.
72
+ */
73
+ export function prefixedSignInLinkPath(
74
+ path: string,
75
+ query: Readonly<Record<string, unknown>>,
76
+ languages: readonly string[],
77
+ defaultLanguage: string,
78
+ ): string | null {
79
+ const [pathname = "", search = ""] = path.split("?");
80
+ if (pathname.replace(/\/+$/, "") !== "/login/link") {
81
+ return null;
82
+ }
83
+ const wanted = signInLinkPreferences(query).language;
84
+ const language = wanted && languages.includes(wanted) ? wanted : defaultLanguage;
85
+ return `/${language}/login/link${search ? `?${search}` : ""}`;
86
+ }
package/nuxt.config.ts CHANGED
@@ -149,11 +149,20 @@ export default defineNuxtConfig({
149
149
  // (PE-1103) writes the JSON-LD: a WebSite and WebPage on every page, the
150
150
  // Organization from the rules (useSeoHead), Product and BreadcrumbList from
151
151
  // the product and category pages.
152
+ //
153
+ // Analytics: @revenexx/beats-nuxt sends page views and the theme events
154
+ // (theme-events/1, mapped onto beats commerce events) to beats. There is
155
+ // no key here: the platform's Site router sets x-revenexx-beats-key on
156
+ // each request to the tenant's ingest key (and drops client copies), and
157
+ // the module hands it to the browser. A host without a key (a preview, the
158
+ // docs website, local dev) sends nothing. Cookieless; nothing identifies
159
+ // the visitor.
152
160
  modules: [
153
161
  "@formkit/nuxt",
154
162
  "@nuxt/scripts",
155
163
  "@revenexx/consent-manager-nuxt",
156
164
  "@revenexx/tag-manager-nuxt",
165
+ "@revenexx/beats-nuxt",
157
166
  "nuxt-site-config",
158
167
  "nuxt-seo-utils",
159
168
  "nuxt-schema-org",
@@ -161,6 +170,10 @@ export default defineNuxtConfig({
161
170
  "nuxt-og-image",
162
171
  ],
163
172
 
173
+ beats: {
174
+ apiHost: "https://beats.revenexx.com",
175
+ },
176
+
164
177
  // Broken links while developing; a production build has no use for it.
165
178
  $development: {
166
179
  modules: ["nuxt-link-checker"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -34,38 +34,40 @@
34
34
  "./validations/*": "./app/validations/*.ts"
35
35
  },
36
36
  "dependencies": {
37
- "@formkit/barcode": "^1.0.5",
38
- "@formkit/core": "^1.6.0",
39
- "@formkit/i18n": "^1.6.0",
40
- "@formkit/nuxt": "^1.6.0",
41
- "@formkit/themes": "^1.6.0",
42
- "@formkit/vue": "^1.6.0",
43
- "@iconify-json/lucide": "^1.2.111",
44
- "@internationalized/date": "^3.12.0",
37
+ "@formkit/barcode": "^1.1.0",
38
+ "@formkit/core": "^2.9.0",
39
+ "@formkit/i18n": "^2.9.0",
40
+ "@formkit/nuxt": "^2.9.0",
41
+ "@formkit/themes": "^2.9.0",
42
+ "@formkit/vue": "^2.9.0",
43
+ "@iconify-json/lucide": "^1.2.157",
44
+ "@internationalized/date": "^3.12.4",
45
45
  "@nuxt/scripts": "^1.3.0",
46
46
  "@nuxtjs/robots": "7.0.2",
47
- "@revenexx/consent-manager-nuxt": "^0.1.0",
48
- "@revenexx/sdk": "^0.5.0",
49
- "@revenexx/storage-model-viewer": "^0.3.0",
50
- "@revenexx/tag-manager-nuxt": "^0.1.0",
51
- "@takumi-rs/core": "2.19.0",
52
- "@vueuse/core": "^14.3.0",
47
+ "@revenexx/beats-nuxt": "0.2.0",
48
+ "@revenexx/consent-manager-nuxt": "^0.1.1",
49
+ "@revenexx/sdk": "^0.9.0",
50
+ "@revenexx/storage-model-viewer": "^0.3.1",
51
+ "@revenexx/tag-manager-nuxt": "^0.1.1",
52
+ "@takumi-rs/core": "2.22.1",
53
+ "@vueuse/core": "^15.0.0",
53
54
  "nuxt-link-checker": "6.0.1",
54
55
  "nuxt-og-image": "7.0.7",
55
56
  "nuxt-schema-org": "7.0.1",
56
- "nuxt-seo-utils": "9.0.1",
57
+ "nuxt-seo-utils": "9.0.2",
57
58
  "nuxt-site-config": "5.0.3",
58
- "typesense": "^3.0.5"
59
+ "typesense": "^3.2.0"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "@nuxt/ui": "^4.5.1",
62
- "pinia": "^3.0.4",
63
+ "pinia": "^3.0.4 || ^4.0.0",
63
64
  "vue": "^3.5.0",
64
- "vue-i18n": "^11.0.0 || ^10.0.0"
65
+ "vue-i18n": "^11.4.23"
65
66
  },
66
67
  "devDependencies": {
67
- "@nuxt/kit": "^4.6.3",
68
- "nuxt": "^4.6.3"
68
+ "@nuxt/kit": "^4.6.4",
69
+ "nuxt": "^4.6.4",
70
+ "pinia": "^4.1.0"
69
71
  },
70
72
  "publishConfig": {
71
73
  "registry": "https://registry.npmjs.org",
@@ -25,7 +25,7 @@ export default defineEventHandler(async (event) => {
25
25
  return { recorded: 0 };
26
26
  }
27
27
  const contactId = sessionOrderRefs(event).contact_id;
28
- const market = resolveSelectedMarket(event);
28
+ const market = requestMarket(event);
29
29
  const sessionKey = getOrCreateCartSessionId(event);
30
30
  try {
31
31
  await getMarketingService(event).recordTouches(event, touches.map(touch => ({
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Paths that never call an app: the bundler's, @nuxt/image's, the OG images,
3
+ * module plumbing under `/api/_`, and anything that names a file.
4
+ */
5
+ const NO_APP_CALLS = ["/_nuxt/", "/__nuxt", "/_ipx/", "/_og/", "/@", "/node_modules/", "/api/_"];
6
+ const FILE_PATH = /\.[a-z0-9]{2,5}$/i;
7
+
8
+ /**
9
+ * Decide the request's market before any handler calls an app (RAD-479).
10
+ *
11
+ * The shop used to send `X-Revenexx-Market` only when the buyer had picked a
12
+ * market, so a buyer who never touched the selector created carts that
13
+ * belonged to no market. Resolved here once, every SDK call of the request
14
+ * carries it (useRevenexxSdk reads requestMarket()): the buyer's choice, else
15
+ * the market the domain is bound to in Experience Studio (RAD-471), else the
16
+ * tenant's default market.
17
+ */
18
+ export default defineEventHandler(async (event) => {
19
+ const path = event.path.split("?")[0] ?? "";
20
+ if (FILE_PATH.test(path) || NO_APP_CALLS.some(prefix => path.startsWith(prefix))) {
21
+ return;
22
+ }
23
+ await resolveRequestMarket(event);
24
+ });
@@ -38,6 +38,8 @@ interface ApiMeAnswer {
38
38
 
39
39
  /** The verified identity of one request, resolved at most once per request. */
40
40
  const ME_KEY = "coverApiAuthMe";
41
+ /** The platform session the cookie named, once it was well-formed enough to ask about. */
42
+ const VERIFIED_SESSION_KEY = "coverApiAuthSession";
41
43
 
42
44
  /**
43
45
  * A short cross-request memory of verified answers, keyed by tenant + user +
@@ -145,15 +147,22 @@ export class ApiAuthService implements IAuthService {
145
147
  if (pending) {
146
148
  return pending;
147
149
  }
148
- const resolving = this.resolve(event).then((user) => {
149
- rememberVerifiedBuyer(event, user);
150
+ const resolving = this.resolve(event).then(({ user, sessionId }) => {
151
+ rememberVerifiedBuyer(event, user, sessionId);
150
152
  return user;
151
153
  });
152
154
  context[ME_KEY] = resolving;
153
155
  return resolving;
154
156
  }
155
157
 
156
- private async resolve(event: H3Event): Promise<AuthUser | null> {
158
+ /** The verified user, and the session it was verified for. */
159
+ private async resolve(event: H3Event): Promise<{ user: AuthUser | null; sessionId?: string }> {
160
+ const user = await this.verify(event);
161
+ const sessionId = user ? (event.context as Record<string, unknown>)[VERIFIED_SESSION_KEY] : undefined;
162
+ return { user, ...(typeof sessionId === "string" ? { sessionId } : {}) };
163
+ }
164
+
165
+ private async verify(event: H3Event): Promise<AuthUser | null> {
157
166
  const raw = getCookie(event, SESSION_COOKIE_NAME);
158
167
  if (!raw) {
159
168
  return null;
@@ -177,6 +186,8 @@ export class ApiAuthService implements IAuthService {
177
186
  return null;
178
187
  }
179
188
 
189
+ // The session every answer below is verified for, whichever path gives it.
190
+ (event.context as Record<string, unknown>)[VERIFIED_SESSION_KEY] = parsed.id;
180
191
  const cacheKey = `${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`;
181
192
  const remembered = verified.get(cacheKey);
182
193
  if (remembered && remembered.until > Date.now()) {
@@ -130,7 +130,7 @@ export async function readAppSettings(event: H3Event | undefined, app: string):
130
130
  return { ...await readDemoAppSettings(app), ...override };
131
131
  }
132
132
 
133
- const market = event ? resolveSelectedMarket(event) : undefined;
133
+ const market = event ? requestMarket(event) : undefined;
134
134
  // Partitioned by tenant: a theme serving several must never answer one
135
135
  // tenant's page with another's settings (see revenexxTenantKey()).
136
136
  const key = `${revenexxTenantKey()}|${app}|${market ?? "-"}`;
@@ -30,6 +30,7 @@ import type { AuthRole, AuthUser } from "../../app/interfaces/auth";
30
30
 
31
31
  const BUYER_KEY = "coverVerifiedBuyer";
32
32
  const PRINCIPAL_KEY = "revenexxPrincipal";
33
+ const SESSION_KEY = "revenexxBuyerSession";
33
34
 
34
35
  type BuyerContext = Record<string, unknown>;
35
36
 
@@ -42,8 +43,12 @@ function contextOf(event: H3Event | undefined): BuyerContext | null {
42
43
  * Record what the identity service answered for this request. Only a verified
43
44
  * answer comes through here; null records "signed out" so a second read in the
44
45
  * same request does not ask again.
46
+ *
47
+ * `sessionId` is the platform session the answer was verified for: the
48
+ * identity service confirmed it is that user's live one, so it may ride beside
49
+ * the principal (buyerSession).
45
50
  */
46
- export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null): void {
51
+ export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null, sessionId?: string): void {
47
52
  const context = contextOf(event);
48
53
  if (!context) {
49
54
  return;
@@ -55,6 +60,12 @@ export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null): vo
55
60
  else {
56
61
  delete context[PRINCIPAL_KEY];
57
62
  }
63
+ if (user?.contactId && sessionId) {
64
+ context[SESSION_KEY] = sessionId;
65
+ }
66
+ else {
67
+ delete context[SESSION_KEY];
68
+ }
58
69
  }
59
70
 
60
71
  /** Forget it again — after a sign-out within the same request. */
@@ -63,6 +74,7 @@ export function forgetVerifiedBuyer(event: H3Event): void {
63
74
  if (context) {
64
75
  delete context[BUYER_KEY];
65
76
  delete context[PRINCIPAL_KEY];
77
+ delete context[SESSION_KEY];
66
78
  }
67
79
  }
68
80
 
@@ -88,6 +100,21 @@ export function buyerPrincipal(event: H3Event | undefined): string {
88
100
  return typeof value === "string" ? value : "";
89
101
  }
90
102
 
103
+ /**
104
+ * The value for `X-Revenexx-Session`: the platform session the verified buyer
105
+ * holds, or "" when there is none (RAD-472).
106
+ *
107
+ * The gateway hands it to the customers app beside the principal, and only
108
+ * then learns whether a sales rep opened that session for the buyer — which it
109
+ * forwards to every app as the acting rep. Without it a handed-over session
110
+ * looks like the buyer's own. It can only ever add the rep: who the buyer is
111
+ * still comes from the principal.
112
+ */
113
+ export function buyerSession(event: H3Event | undefined): string {
114
+ const value = contextOf(event)?.[SESSION_KEY];
115
+ return typeof value === "string" ? value : "";
116
+ }
117
+
91
118
  /**
92
119
  * The contact the request acts for, or undefined. A body that names a contact
93
120
  * to an app enforcing the principal (payments 1.0) has to name exactly this
@@ -62,7 +62,7 @@ export async function resolveMarketLocale(event: H3Event): Promise<string> {
62
62
  let locales: { code: string; language?: string; isDefault?: boolean; status?: string }[] = [];
63
63
  try {
64
64
  const markets = await getMarketService(event).listMarkets();
65
- const selected = resolveSelectedMarket(event);
65
+ const selected = requestMarket(event);
66
66
  const market = markets.find(m => m.code === selected) ?? markets.find(m => m.isDefault) ?? markets[0];
67
67
  locales = market?.locales ?? [];
68
68
  }
@@ -94,7 +94,7 @@ export async function resolveStoreLocale(event: H3Event): Promise<string> {
94
94
  const language = resolveLocale(event);
95
95
  try {
96
96
  const markets = await getMarketService(event).listMarkets();
97
- const selected = resolveSelectedMarket(event);
97
+ const selected = requestMarket(event);
98
98
  const market = markets.find(m => m.code === selected) ?? markets.find(m => m.isDefault) ?? markets[0];
99
99
  const locales = market?.locales ?? [];
100
100
  if (!locales.length) {
@@ -1,15 +1,20 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
+ import type { ShopMarket } from "../../app/interfaces/market";
4
+
3
5
  /** Cookie the storefront's locale selector persists the chosen market in. */
4
6
  export const MARKET_COOKIE_NAME = "cover-market";
5
7
 
8
+ /** Where the request's market is remembered once it is resolved (resolveRequestMarket). */
9
+ const REQUEST_MARKET_KEY = "coverRequestMarket";
10
+
11
+ const MARKET_CODE = /^[a-z][a-z0-9_]{0,62}$/;
12
+
6
13
  /**
7
- * The buyer's active market for server-side scoping. Read from the cookie the
8
- * locale selector sets — the BFF forwards it as X-Revenexx-Market
9
- * (client.setMarket), so the gateway's Entity Scoping Engine filters
10
- * market-scoped data to that market plus global (unassigned) rows. Undefined →
11
- * no header → the API returns only global rows, so the shop works before any
12
- * market is chosen. Market slugs are lowercase (e.g. "de").
14
+ * The market the buyer CHOSE, from the cookie the locale selector sets — or
15
+ * undefined when they chose none. Only the choice: which market a request is
16
+ * made in is requestMarket(), which falls back to the shop's own market when
17
+ * nothing was chosen. Market slugs are lowercase (e.g. "de").
13
18
  */
14
19
  export function resolveSelectedMarket(event: H3Event): string | undefined {
15
20
  const raw = getCookie(event, MARKET_COOKIE_NAME);
@@ -17,5 +22,124 @@ export function resolveSelectedMarket(event: H3Event): string | undefined {
17
22
  return undefined;
18
23
  }
19
24
  const code = raw.trim().toLowerCase();
20
- return /^[a-z][a-z0-9_]{0,62}$/.test(code) ? code : undefined;
25
+ return MARKET_CODE.test(code) ? code : undefined;
26
+ }
27
+
28
+ /**
29
+ * Which market a request is made in (RAD-479), among the tenant's active
30
+ * markets: the chosen one when it is one of them, else the shop's own market.
31
+ *
32
+ * The shop's own market is the domain's (RAD-471): a domain in Experience
33
+ * Studio names the market it serves, or none, which means it serves every
34
+ * market and opens in the tenant's default one, else the first. A domain bound
35
+ * to a market the tenant does not run is read as one that names none. Pure,
36
+ * for the tests.
37
+ */
38
+ export function pickRequestMarket(
39
+ markets: readonly ShopMarket[],
40
+ chosen: string | undefined,
41
+ domainMarket?: string | null,
42
+ ): string | undefined {
43
+ if (chosen && markets.some(m => m.code === chosen)) {
44
+ return chosen;
45
+ }
46
+ if (domainMarket && markets.some(m => m.code === domainMarket)) {
47
+ return domainMarket;
48
+ }
49
+ return (markets.find(m => m.isDefault) ?? markets[0])?.code;
50
+ }
51
+
52
+ /** One shop domain as `GET /v1/settings/storefronts` answers it. */
53
+ interface StorefrontRow {
54
+ readonly host?: string;
55
+ readonly market?: string | null;
56
+ }
57
+
58
+ const STOREFRONTS_TTL_MS = 5 * 60 * 1000;
59
+
60
+ // Partitioned by tenant (see revenexxTenantKey()): host → bound market, or
61
+ // null where the domain serves every market. A failed read is remembered as an
62
+ // empty map for the same time, so a gateway without the route costs one call
63
+ // per tenant and TTL, not one per request.
64
+ const storefrontMarkets = new Map<string, { markets: Map<string, string | null>; loadedAt: number }>();
65
+
66
+ /** Test seam: forget every remembered storefront list. */
67
+ export function clearStorefrontMarkets(): void {
68
+ storefrontMarkets.clear();
69
+ }
70
+
71
+ /**
72
+ * The market the domain this request was made to is bound to, from the
73
+ * tenant's storefronts in Experience Studio (RAD-471): its code, or null when
74
+ * the domain serves every market, is not a storefront the platform knows, or
75
+ * the list cannot be read. Host from `Host`, as seoRequestHost reads it.
76
+ */
77
+ export async function domainMarket(event: H3Event): Promise<string | null> {
78
+ let tenant: string;
79
+ try {
80
+ tenant = revenexxTenantKey();
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ let entry = storefrontMarkets.get(tenant);
86
+ if (!entry || Date.now() - entry.loadedAt >= STOREFRONTS_TTL_MS) {
87
+ const markets = new Map<string, string | null>();
88
+ try {
89
+ const answer = await useTenantSdk().call<{ storefronts?: StorefrontRow[] }>("GET", "/v1/settings/storefronts");
90
+ for (const row of answer?.storefronts ?? []) {
91
+ const host = typeof row.host === "string" ? row.host.toLowerCase() : "";
92
+ if (host) {
93
+ markets.set(host, typeof row.market === "string" && MARKET_CODE.test(row.market) ? row.market : null);
94
+ }
95
+ }
96
+ }
97
+ catch {
98
+ // Not readable: no domain names a market, as before the list existed.
99
+ }
100
+ entry = { markets, loadedAt: Date.now() };
101
+ storefrontMarkets.set(tenant, entry);
102
+ }
103
+ return entry.markets.get(seoRequestHost(event)) ?? null;
104
+ }
105
+
106
+ /**
107
+ * Resolve the request's market once, before any handler calls an app, and
108
+ * remember it on the event (server/middleware/market-scope.ts).
109
+ *
110
+ * Every call then carries `X-Revenexx-Market`, which is what Baseline assigns a
111
+ * new row of a market-scoped table to: a cart created without the header was
112
+ * nobody's market. When the markets cannot be read, the request keeps the
113
+ * buyer's choice and nothing else — the same as before markets were read here.
114
+ */
115
+ export async function resolveRequestMarket(event: H3Event): Promise<string | undefined> {
116
+ const context = event.context as Record<string, unknown>;
117
+ if (REQUEST_MARKET_KEY in context) {
118
+ return context[REQUEST_MARKET_KEY] as string | undefined;
119
+ }
120
+ const chosen = resolveSelectedMarket(event);
121
+ let market = chosen;
122
+ try {
123
+ const [markets, bound] = await Promise.all([getMarketService(event).listMarkets(), domainMarket(event)]);
124
+ market = pickRequestMarket(markets, chosen, bound) ?? chosen;
125
+ }
126
+ catch {
127
+ // The markets app could not be asked: the choice, if any, stands.
128
+ }
129
+ context[REQUEST_MARKET_KEY] = market;
130
+ return market;
131
+ }
132
+
133
+ /**
134
+ * The market this request is made in: what resolveRequestMarket() decided, or
135
+ * the buyer's choice while nothing decided yet (startup code, the markets read
136
+ * itself). Synchronous, for the SDK client. Undefined → no header → the gateway
137
+ * answers global rows only.
138
+ */
139
+ export function requestMarket(event: H3Event): string | undefined {
140
+ const context = (event as { context?: Record<string, unknown> }).context;
141
+ if (context && REQUEST_MARKET_KEY in context) {
142
+ return context[REQUEST_MARKET_KEY] as string | undefined;
143
+ }
144
+ return resolveSelectedMarket(event);
21
145
  }
@@ -25,7 +25,7 @@ import {
25
25
 
26
26
  // Explicit rather than a Nitro auto-import, so the header logic is reachable
27
27
  // from a unit test that imports this module.
28
- import { buyerPrincipal } from "./buyerIdentity";
28
+ import { buyerPrincipal, buyerSession } from "./buyerIdentity";
29
29
 
30
30
  /**
31
31
  * The generated revenexx web SDK, configured for the BFF. Every live
@@ -227,14 +227,15 @@ export function apiErrorContext(err: unknown): Record<string, unknown> {
227
227
  const clients = new Map<string, RevenexxSdk>();
228
228
 
229
229
  /**
230
- * The active market for the current request, from the `cover-market` cookie the
231
- * locale selector sets. "" when none — then no X-Revenexx-Market is sent and the
232
- * gateway returns only global rows. Per-request, and never part of a cache key
233
- * (see useRevenexxSdk).
230
+ * The market the current request is made in (requestMarket in ./market.ts):
231
+ * the buyer's choice, else the shop's own market (RAD-479). "" only when
232
+ * neither is known — then no X-Revenexx-Market is sent and the gateway returns
233
+ * only global rows. Per-request, and never part of a cache key (see
234
+ * useRevenexxSdk).
234
235
  */
235
236
  function activeMarket(): string {
236
237
  try {
237
- return resolveSelectedMarket(useEvent()) ?? "";
238
+ return requestMarket(useEvent()) ?? "";
238
239
  }
239
240
  catch {
240
241
  // No async context (e.g. startup code) — no market scoping.
@@ -297,6 +298,24 @@ function activePrincipal(): string {
297
298
  }
298
299
  }
299
300
 
301
+ /**
302
+ * The platform session to assert beside `principal` (RAD-472): the verified
303
+ * buyer's own, and only when the call is made for that very buyer. A call made
304
+ * for nobody, or for a principal a caller named explicitly, carries none.
305
+ */
306
+ function activeSession(principal: string): string {
307
+ if (!principal) {
308
+ return "";
309
+ }
310
+ try {
311
+ const event = useEvent();
312
+ return principal === buyerPrincipal(event) ? buyerSession(event) : "";
313
+ }
314
+ catch {
315
+ return "";
316
+ }
317
+ }
318
+
300
319
  export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
301
320
  const { tenant, apiKey, jwt, source } = resolveRevenexxCredentials();
302
321
  const market = activeMarket();
@@ -349,6 +368,14 @@ export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
349
368
  // call made for a buyer, and on none made for nobody.
350
369
  if (principal) {
351
370
  client.headers["X-Revenexx-Principal"] = principal;
371
+ // The session the buyer holds, so the gateway can tell a session a sales
372
+ // rep opened for them from their own, and name the rep to every app
373
+ // (X-Revenexx-Acting-Rep). It names a rep only for the buyer it belongs
374
+ // to, and never changes who the buyer is.
375
+ const session = activeSession(principal);
376
+ if (session) {
377
+ client.headers["X-Revenexx-Session"] = session;
378
+ }
352
379
  }
353
380
  // Auth: the brokered context wins — it is a Zitadel JWT the gateway
354
381
  // verifies against the same JWKS as any interactive caller, so one theme