orionplace-nuxt 0.6.2 → 0.7.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/README.md CHANGED
@@ -466,7 +466,9 @@ The corresponding `.cfg` is read on every request. Backend URLs must use HTTPS,
466
466
  end in `/api`, and belong to `*.orionplace.app`. API methods, query strings, bodies,
467
467
  authorization and cookies are forwarded. Backend statuses are retained and cookie
468
468
  Domain attributes are removed to bind cookies to the storefront. Gateway responses
469
- use `Cache-Control: no-store`. Network failures return `502`.
469
+ use `Cache-Control: no-store`, except public blog images and videos: they keep the
470
+ backend's `private, max-age` rule, so the browser does not download them again on
471
+ every page. Network failures return `502`.
470
472
 
471
473
  A changing request (POST, PUT, PATCH, DELETE) from another site is rejected with
472
474
  `403`. A request from the page's own host or the storefront domain passes, and the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orionplace-nuxt",
3
- "version": "0.6.2",
3
+ "version": "0.7.1",
4
4
  "description": "Nuxt 4 storefront for your Orionplace marketplace: setup CLI, server API gateway, typed store and ready-made catalog, cart, checkout and account components in English and Russian, plus an Android app build.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,6 +41,18 @@ const hostnamePattern =
41
41
  const blogMediaPattern =
42
42
  /^\/ps3\/blog\/posts\/(?:images\/\d+|videos\/\d+(?:\/preview)?)$/;
43
43
 
44
+ /**
45
+ * API answers are never stored. A media file keeps the backend's own browser
46
+ * cache rule when the backend allows it (a published public blog image:
47
+ * "private, max-age=…"); "private" keeps it out of shared caches.
48
+ */
49
+ export function marketplaceCacheControl(media, upstream) {
50
+ const value = upstream.headers.get('cache-control') ?? '';
51
+ return media && upstream.ok && /\bprivate\b/i.test(value) && /\bmax-age=\d+/i.test(value) && !/no-store|no-cache/i.test(value)
52
+ ? value
53
+ : 'no-store';
54
+ }
55
+
44
56
  /** @param {string} pathname */
45
57
  export function isMarketplaceMediaPath(pathname) {
46
58
  return blogMediaPattern.test(pathname);
@@ -307,7 +319,7 @@ export async function forwardMarketplace(request, configuration = {}) {
307
319
  : destination.href,
308
320
  );
309
321
  }
310
- responseHeaders.set('Cache-Control', 'no-store');
322
+ responseHeaders.set('Cache-Control', marketplaceCacheControl(media, upstream));
311
323
  responseHeaders.set('Vary', 'Host, X-Forwarded-Host, X-Front-Domain');
312
324
  // fetch decodes compressed bodies: do not reuse upstream Content-Length/Encoding.
313
325
  return new Response(upstream.body, {
@@ -577,6 +577,13 @@ for example \`ORIONPLACE_NOINDEX_PATHS="/catalog /category /product"\`. Those
577
577
  pages answer with \`X-Robots-Tag: noindex, follow\` and the sitemap leaves them
578
578
  out; the journal and other pages stay indexable. Leave it empty on a live shop.
579
579
 
580
+ Every product page carries schema.org product data for Google and Yandex: the
581
+ price, the crossed-out old price, stock, photos, brand, seller, rating and the
582
+ return terms the page shows. The return terms name the shop's shipping
583
+ countries, which Application Load sends in \`init.shipping_countries\`; without
584
+ a shipping country they are left out. The delivery cost is not included: it
585
+ depends on the buyer's address.
586
+
580
587
  This setup does not add analytics.
581
588
 
582
589
  ## Android app
@@ -8,6 +8,7 @@ import {
8
8
  storefrontPublicOrigin,
9
9
  } from '@/utils/orionplace/pageSeo';
10
10
  import type { StorefrontSeoPage } from '@/utils/orionplace/pageSeo';
11
+ import { structuredDataJson } from '@/utils/orionplace/productStructuredData';
11
12
 
12
13
  export function useOrionplacePageSeo(
13
14
  page: MaybeRefOrGetter<StorefrontSeoPage>,
@@ -18,6 +19,12 @@ export function useOrionplacePageSeo(
18
19
  keywords?: MaybeRefOrGetter<string | undefined>;
19
20
  robots?: MaybeRefOrGetter<string | undefined>;
20
21
  image?: MaybeRefOrGetter<string | undefined>;
22
+ /**
23
+ * The page's schema.org data (a record page, e.g. the product), built
24
+ * from its canonical address and the visitor's origin. A page without a
25
+ * canonical address (preview, filtered, noindex) gets none.
26
+ */
27
+ structuredData?: (canonical: string, origin: string) => unknown;
21
28
  } = {},
22
29
  ) {
23
30
  const route = useRoute();
@@ -57,11 +64,26 @@ export function useOrionplacePageSeo(
57
64
  ogImage: () => storefrontAbsoluteUrl(toValue(values.image), origin),
58
65
  ogUrl: () => canonical.value,
59
66
  };
67
+ const structured = computed(() =>
68
+ canonical.value && values.structuredData
69
+ ? structuredDataJson(values.structuredData(canonical.value, origin))
70
+ : '',
71
+ );
60
72
  useSeoMeta(seo);
61
73
  useHead({
62
74
  link: () =>
63
75
  canonical.value
64
76
  ? [{ key: 'canonical', rel: 'canonical', href: canonical.value }]
65
77
  : [],
78
+ script: () =>
79
+ structured.value
80
+ ? [
81
+ {
82
+ key: 'orionplace-structured-data',
83
+ type: 'application/ld+json',
84
+ innerHTML: structured.value,
85
+ },
86
+ ]
87
+ : [],
66
88
  });
67
89
  }
@@ -24,6 +24,8 @@ export interface IAppLoadCommon {
24
24
  weights: Record<string, IAppLoadCommonUnit>;
25
25
  lengths: Record<string, IAppLoadCommonUnit>;
26
26
  geo_location_enabled: boolean;
27
+ /** ISO codes of the shop's shipping countries, sorted. */
28
+ shipping_countries?: string[];
27
29
  is_authenticated: boolean;
28
30
  wallet?: Record<string, IAppLoadCommonWalletValue>;
29
31
  logos: IAppLoadCommonLogos;
@@ -6,6 +6,11 @@
6
6
  import { useOrionplaceMissingPage } from '@/composables/useOrionplaceMissingPage';
7
7
  import { useOrionplaceServerData } from '@/composables/useOrionplaceServerData';
8
8
  import { requestProductPage } from '@/utils/orionplace/productPage';
9
+ import { storefrontAbsoluteUrl } from '@/utils/orionplace/pageSeo';
10
+ import {
11
+ shippingCountryCodes,
12
+ storefrontProductStructuredData,
13
+ } from '@/utils/orionplace/productStructuredData';
9
14
  import {
10
15
  getAvailableNestedValueFromObject,
11
16
  plainText,
@@ -66,29 +71,48 @@
66
71
  return images?.full?.[0] ?? images?.small?.[0];
67
72
  });
68
73
 
69
- useOrionplacePageSeo('product', () => store.localeCode, {
70
- title: () =>
74
+ const productName = computed(() =>
75
+ getAvailableNestedValueFromObject(
76
+ product.value?.locale,
77
+ store.localeCode,
78
+ 'product_name',
79
+ ),
80
+ );
81
+ const productSummary = computed(() =>
82
+ plainText(
71
83
  getAvailableNestedValueFromObject(
72
84
  product.value?.locale,
73
85
  store.localeCode,
74
- 'product_name',
75
- ),
76
- description: () =>
77
- plainText(
86
+ 'meta_description',
87
+ ) ||
78
88
  getAvailableNestedValueFromObject(
79
89
  product.value?.locale,
80
90
  store.localeCode,
81
- 'meta_description',
82
- ) ||
83
- getAvailableNestedValueFromObject(
84
- product.value?.locale,
85
- store.localeCode,
86
- 'short_description',
87
- ),
88
- ).slice(0, 160),
91
+ 'short_description',
92
+ ),
93
+ ).slice(0, 160),
94
+ );
95
+
96
+ useOrionplacePageSeo('product', () => store.localeCode, {
97
+ title: () => productName.value,
98
+ description: () => productSummary.value,
89
99
  image: () => image.value,
90
100
  robots: () =>
91
101
  previewKey.value ? 'noindex, nofollow' : undefined,
102
+ structuredData: (canonical, origin) =>
103
+ storefrontProductStructuredData(product.value, {
104
+ url: canonical,
105
+ name: productName.value,
106
+ description: productSummary.value,
107
+ currencyId: store.currencyId,
108
+ currencyCode: store.currentCurrency?.currency_code,
109
+ // The backend's shipping countries, for the return terms.
110
+ shippingCountries: shippingCountryCodes(
111
+ store.init?.shipping_countries,
112
+ ),
113
+ showSeller: !store.init?.visual_settings?.single_seller_mode,
114
+ absoluteUrl: (value) => storefrontAbsoluteUrl(value, origin),
115
+ }),
92
116
  });
93
117
 
94
118
  // An invalid ID, or a product that the selected endpoint does not return,
@@ -0,0 +1,221 @@
1
+ // The product page's schema.org data for search engines: Google merchant
2
+ // listings and Yandex product snippets read the same block. Every value
3
+ // repeats what the page shows: the price and the crossed-out old price,
4
+ // stock, return terms, photos, brand, seller and rating. The delivery cost is
5
+ // left out: it depends on the buyer's address.
6
+ // The same file is in the three packages; it has no imports so that it stays
7
+ // identical.
8
+
9
+ const SCHEMA_ORG = 'https://schema.org/';
10
+ const MAX_IMAGES = 10;
11
+ // EProductStatus.PUBLISHED and PUBLISHED_AS_OPTION: the product is on sale.
12
+ const ON_SALE_STATUSES = [2, 1];
13
+
14
+ interface StructuredPrice {
15
+ transform_value: number;
16
+ }
17
+
18
+ /** The product fields the data uses (IProduct has them all). */
19
+ export interface StorefrontStructuredProduct {
20
+ id: number;
21
+ is_digital?: boolean;
22
+ discount: number;
23
+ base_price_dict: Record<string, StructuredPrice>;
24
+ product_price_dict: Record<string, StructuredPrice>;
25
+ images?: { full?: string[] | null; small?: string[] | null } | null;
26
+ status: { status: number };
27
+ c_real_left: number;
28
+ seller?: { name?: string | null } | null;
29
+ manufacture?: { name?: string | null } | null;
30
+ refunds?: {
31
+ customer_max_refund_days: number;
32
+ max_refund_days_with_defect: number;
33
+ } | null;
34
+ feedback_stat?: {
35
+ c_feedbacks?: number | null;
36
+ avg_raiting?: number | string | null;
37
+ } | null;
38
+ }
39
+
40
+ export interface StorefrontProductDataOptions {
41
+ /** The page's canonical address; without one the page gets no data. */
42
+ url: string | undefined;
43
+ name: string | undefined;
44
+ description?: string;
45
+ /** The currency the page shows prices in (its ID and code). */
46
+ currencyId: string;
47
+ currencyCode: string | undefined;
48
+ /** App Load `init.shipping_countries`, parsed by shippingCountryCodes(). */
49
+ shippingCountries: string[];
50
+ /** False when the page hides the seller (single-seller storefront). */
51
+ showSeller: boolean;
52
+ /** Makes an image address complete (storefrontAbsoluteUrl). */
53
+ absoluteUrl: (value: string | undefined) => string | undefined;
54
+ }
55
+
56
+ /**
57
+ * The countries the shop ships to: App Load `init.shipping_countries` (the
58
+ * backend's countries marked as shipping countries), as valid ISO 3166-1
59
+ * alpha-2 codes.
60
+ */
61
+ export function shippingCountryCodes(value: unknown): string[] {
62
+ const codes = (Array.isArray(value) ? value.join(' ') : String(value ?? ''))
63
+ .split(/[\s,;]+/)
64
+ .map((code) => code.trim().toUpperCase())
65
+ .filter((code) => /^[A-Z]{2}$/.test(code));
66
+
67
+ return [...new Set(codes)];
68
+ }
69
+
70
+ function wholeDays(value: unknown) {
71
+ const days = Math.floor(Number(value));
72
+
73
+ return Number.isFinite(days) && days > 0 ? days : 0;
74
+ }
75
+
76
+ /**
77
+ * The return terms the page shows: the days for a product without a defect
78
+ * are the return window (sent back by mail at the buyer's cost); a defective
79
+ * product goes back at the shop's cost. A digital product or one without
80
+ * days cannot be returned. Without a shipping country there is no policy:
81
+ * search engines require the country.
82
+ */
83
+ export function productReturnPolicy(
84
+ product: Pick<StorefrontStructuredProduct, 'is_digital' | 'refunds'>,
85
+ countries: string[],
86
+ ) {
87
+ if (!countries.length) {
88
+ return undefined;
89
+ }
90
+
91
+ const applicableCountry = countries.length === 1 ? countries[0] : countries;
92
+ const returnDays = product.is_digital
93
+ ? 0
94
+ : wholeDays(product.refunds?.customer_max_refund_days);
95
+ const defectDays = product.is_digital
96
+ ? 0
97
+ : wholeDays(product.refunds?.max_refund_days_with_defect);
98
+
99
+ if (!returnDays) {
100
+ return {
101
+ '@type': 'MerchantReturnPolicy',
102
+ applicableCountry,
103
+ 'returnPolicyCategory': `${SCHEMA_ORG}MerchantReturnNotPermitted`,
104
+ };
105
+ }
106
+
107
+ return {
108
+ '@type': 'MerchantReturnPolicy',
109
+ applicableCountry,
110
+ 'returnPolicyCategory': `${SCHEMA_ORG}MerchantReturnFiniteReturnWindow`,
111
+ 'merchantReturnDays': returnDays,
112
+ 'returnMethod': `${SCHEMA_ORG}ReturnByMail`,
113
+ 'returnFees': `${SCHEMA_ORG}ReturnFeesCustomerResponsibility`,
114
+ ...(defectDays ? { itemDefectReturnFees: `${SCHEMA_ORG}FreeReturn` } : {}),
115
+ };
116
+ }
117
+
118
+ function priceValue(
119
+ prices: Record<string, StructuredPrice> | undefined,
120
+ currencyId: string,
121
+ ) {
122
+ const value = Number(prices?.[currencyId]?.transform_value);
123
+
124
+ return prices?.[currencyId] && Number.isFinite(value) ? value : undefined;
125
+ }
126
+
127
+ /** The schema.org Product of the page, or undefined when it cannot be built. */
128
+ export function storefrontProductStructuredData(
129
+ product: StorefrontStructuredProduct | undefined,
130
+ options: StorefrontProductDataOptions,
131
+ ) {
132
+ const name = options.name?.trim();
133
+ const currencyCode = options.currencyCode?.trim().toUpperCase() ?? '';
134
+
135
+ if (!product || !options.url || !name) {
136
+ return undefined;
137
+ }
138
+
139
+ // The price the page shows, as ProductCardPrice picks it.
140
+ const currencyId =
141
+ options.currencyId ||
142
+ Object.keys(product.product_price_dict ?? {})[0] ||
143
+ Object.keys(product.base_price_dict ?? {})[0] ||
144
+ '';
145
+ const basePrice = priceValue(product.base_price_dict, currencyId);
146
+ const price =
147
+ priceValue(product.product_price_dict, currencyId) ?? basePrice;
148
+ const images = [
149
+ ...(product.images?.full ?? []),
150
+ ...(product.images?.small ?? []),
151
+ ]
152
+ .map((image) => options.absoluteUrl(image))
153
+ .filter((image, index, list): image is string =>
154
+ Boolean(image) && list.indexOf(image) === index,
155
+ )
156
+ .slice(0, MAX_IMAGES);
157
+ const inStock =
158
+ ON_SALE_STATUSES.includes(product.status?.status) &&
159
+ product.c_real_left > 0;
160
+ const returns = productReturnPolicy(product, options.shippingCountries);
161
+ const brand = product.manufacture?.name?.trim();
162
+ const seller = options.showSeller ? product.seller?.name?.trim() : '';
163
+ const reviews = Number(product.feedback_stat?.c_feedbacks ?? 0);
164
+ const rating = Number(product.feedback_stat?.avg_raiting ?? 0);
165
+ const offer =
166
+ price !== undefined && /^[A-Z]{3}$/.test(currencyCode)
167
+ ? {
168
+ '@type': 'Offer',
169
+ 'url': options.url,
170
+ price,
171
+ 'priceCurrency': currencyCode,
172
+ // The crossed-out old price, when the page shows one.
173
+ ...(basePrice !== undefined && price < basePrice
174
+ ? {
175
+ priceSpecification: {
176
+ '@type': 'UnitPriceSpecification',
177
+ 'priceType': `${SCHEMA_ORG}StrikethroughPrice`,
178
+ 'price': basePrice,
179
+ 'priceCurrency': currencyCode,
180
+ },
181
+ }
182
+ : {}),
183
+ 'availability': `${SCHEMA_ORG}${inStock ? 'InStock' : 'OutOfStock'}`,
184
+ 'itemCondition': `${SCHEMA_ORG}NewCondition`,
185
+ ...(returns ? { hasMerchantReturnPolicy: returns } : {}),
186
+ ...(seller
187
+ ? { seller: { '@type': 'Organization', 'name': seller } }
188
+ : {}),
189
+ }
190
+ : undefined;
191
+
192
+ return {
193
+ '@context': 'https://schema.org',
194
+ '@type': 'Product',
195
+ name,
196
+ 'url': options.url,
197
+ 'sku': String(product.id),
198
+ ...(options.description?.trim()
199
+ ? { description: options.description.trim() }
200
+ : {}),
201
+ ...(images.length ? { image: images } : {}),
202
+ ...(brand ? { brand: { '@type': 'Brand', 'name': brand } } : {}),
203
+ ...(offer ? { offers: offer } : {}),
204
+ ...(reviews > 0 && Number.isFinite(rating) && rating > 0
205
+ ? {
206
+ aggregateRating: {
207
+ '@type': 'AggregateRating',
208
+ 'ratingValue': Math.round(rating * 10) / 10,
209
+ 'reviewCount': reviews,
210
+ },
211
+ }
212
+ : {}),
213
+ };
214
+ }
215
+
216
+ /** The data as the text of a <script type="application/ld+json"> tag. */
217
+ export function structuredDataJson(value: unknown): string {
218
+ return value === undefined
219
+ ? ''
220
+ : JSON.stringify(value).replace(/</g, '\\u003c');
221
+ }