orionplace-nuxt 0.5.0 → 0.6.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 CHANGED
@@ -8,7 +8,7 @@ account, journal and support, in English and Russian. The package includes a Nux
8
8
  setup CLI and the full storefront source, so every page and component in your
9
9
  project is yours to change.
10
10
 
11
- - **Setup CLI:** `init`, `set backend`, `add frontend`, `set mimic` and `update`.
11
+ - **Setup CLI:** `init`, `set backend`, `add frontend`, `set mimic`, `sitemap rebuild` and `update`.
12
12
  - **Server install:** `install` builds the storefront on your Linux server and
13
13
  runs it as a system service behind nginx with HTTPS.
14
14
  - **API gateway:** the browser calls `/api/...` on your own domain; the server
@@ -320,6 +320,8 @@ npx orionplace-nuxt add frontend shop.example.com
320
320
  npx orionplace-nuxt add frontend www.shop.example.com
321
321
  npx orionplace-nuxt remove frontend www.shop.example.com
322
322
  npx orionplace-nuxt set mimic shop.example.com
323
+ npx orionplace-nuxt sitemap rebuild [shop.example.com]
324
+ npx orionplace-nuxt sitemap status
323
325
  sudo npx orionplace-nuxt install
324
326
  npx orionplace-nuxt status
325
327
  sudo npx orionplace-nuxt restart
@@ -336,8 +338,15 @@ npm run orionplace:remove-frontend -- www.shop.example.com
336
338
  npm run orionplace:mimic -- shop.example.com
337
339
  npm run orionplace:help
338
340
  npm run orionplace:update
341
+ npm run orionplace:sitemap
339
342
  ```
340
343
 
344
+ The storefront serves `/robots.txt` and `/sitemap.xml` (public pages, categories,
345
+ products and journal publications in every language). The sitemap is rebuilt
346
+ from the backend once an hour; `npm run orionplace:sitemap` rebuilds it at once,
347
+ for example after new publications, and the running storefront serves it without
348
+ a restart.
349
+
341
350
  `npm set` belongs to npm's own configuration system; use the commands above.
342
351
  The setup commands configure local integration files. They do not provision a
343
352
  backend, change your account or create DNS records. `install` deploys the
@@ -3,6 +3,7 @@ import { setupProject } from '../src/setup.mjs';
3
3
  import { updateProject } from '../src/update.mjs';
4
4
  import { installService } from '../src/install.mjs';
5
5
  import { SERVICE_ACTIONS, SERVICE_ALIASES, controlService, findApp, printService } from '../src/service.mjs';
6
+ import { sitemapCommand } from '../src/sitemap.mjs';
6
7
  import { readFile } from 'node:fs/promises';
7
8
  import { resolve } from 'node:path';
8
9
  import { createInterface } from 'node:readline/promises';
@@ -30,6 +31,9 @@ Commands for an existing project (run from its root):
30
31
  npx orionplace-nuxt remove frontend <shop.example.com>
31
32
  npx orionplace-nuxt set mimic <existing-frontend.example.com>
32
33
  npx orionplace-nuxt set frontend <shop.example.com>
34
+ npx orionplace-nuxt sitemap rebuild [domain] rebuild /sitemap.xml now (every frontend, or one);
35
+ the running storefront serves it at once
36
+ npx orionplace-nuxt sitemap status [domain] when each sitemap was built
33
37
 
34
38
  On your Linux server (run from the project root):
35
39
  sudo npx orionplace-nuxt install
@@ -130,6 +134,9 @@ try {
130
134
  }
131
135
  const done = await controlService({ action: command, cwd, name: install.name, lines: positional[1] ?? 100, follow, dryRun });
132
136
  process.exitCode = printService(done);
137
+ } else if (command === 'sitemap' && positional.length <= 3) {
138
+ if (dryRun) throw new Error('--dry-run is not a sitemap option; sitemap status shows the state without changes.');
139
+ process.exitCode = await sitemapCommand({ cwd, action: target, domain: positional[2] });
133
140
  } else if (command === 'init' && positional.length <= 2) {
134
141
  result = await setupProject({ cwd: target ? resolve(cwd, target) : cwd, dryRun });
135
142
  } else if (command === 'update' && positional.length === 1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orionplace-nuxt",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
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",
@@ -1,5 +1,5 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { resolve } from 'node:path';
1
+ import { chown, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { dirname, relative, resolve } from 'node:path';
3
3
  import {
4
4
  getDefaultAutoSelectFamilyAttemptTimeout,
5
5
  isIP,
@@ -81,8 +81,20 @@ export async function readMarketplace(request, configuration = {}) {
81
81
  if (!domain) {
82
82
  throw new Error('Invalid storefront domain');
83
83
  }
84
+ return readMarketplaceDomain(domain);
85
+ }
84
86
 
85
- const directory = environment.SITEMAPS_DIR || resolve('sitemaps');
87
+ /**
88
+ * The marketplace of one storefront domain: its `sitemaps/<domain>.cfg` in
89
+ * the project (`root`, the working directory by default).
90
+ * @param {string} name @param {{root?: string}} options
91
+ */
92
+ export async function readMarketplaceDomain(name, options = {}) {
93
+ const domain = normalizeFrontDomain(name);
94
+ if (!domain) {
95
+ throw new Error('Invalid storefront domain');
96
+ }
97
+ const directory = marketplaceConfigDirectory(options.root);
86
98
  const source = await readFile(resolve(directory, `${domain}.cfg`), 'utf8');
87
99
  const lines = source
88
100
  .split(/\r?\n/)
@@ -111,6 +123,13 @@ export async function readMarketplace(request, configuration = {}) {
111
123
  return { domain, api };
112
124
  }
113
125
 
126
+ /** The folder of the domain files (`SITEMAPS_DIR`, or `sitemaps`). */
127
+ export function marketplaceConfigDirectory(root = process.cwd()) {
128
+ return environment.SITEMAPS_DIR
129
+ ? resolve(root, environment.SITEMAPS_DIR)
130
+ : resolve(root, 'sitemaps');
131
+ }
132
+
114
133
  /** @param {number} status @param {string} message */
115
134
  function failure(status, message) {
116
135
  return Response.json(
@@ -297,3 +316,471 @@ export async function forwardMarketplace(request, configuration = {}) {
297
316
  headers: responseHeaders,
298
317
  });
299
318
  }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // robots.txt and sitemap.xml
322
+ //
323
+ // The sitemap lists the storefront's public pages in every language the
324
+ // marketplace offers (`?locale=<code>` links, with hreflang alternates): the
325
+ // home, catalog and directory pages, the journal and its publications when
326
+ // the blog is on, the subscription plans when there are any, every public
327
+ // category and every product on sale. It is built from the backend's public
328
+ // API and kept for an hour per storefront domain in
329
+ // node_modules/.cache/orionplace/sitemaps/<domain>.json (ORIONPLACE_CACHE_DIR
330
+ // moves it). "orionplace-<framework> sitemap rebuild" rebuilds that file at
331
+ // once; the running storefront serves the new file without a restart.
332
+
333
+ export const SITEMAP_LIFETIME = 60 * 60 * 1000;
334
+ const sitemapPageSize = 100;
335
+ const sitemapMaxPages = 500;
336
+ const sitemapMaxUrls = 50_000;
337
+ const sitemapVersion = 1;
338
+ /** Built sitemaps of this process, for when the cache folder is read-only. */
339
+ const sitemapMemory = new Map();
340
+ /** @type {Map<string, Promise<object>>} */
341
+ const sitemapBuilds = new Map();
342
+
343
+ /** The public origin a crawler used: the storefront host, or a local one. */
344
+ export function marketplacePublicOrigin(request, tenantDomain = '') {
345
+ const url = new URL(request.url);
346
+ const host = normalizeFrontDomain(
347
+ request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? '',
348
+ );
349
+ if (host) {
350
+ return `https://${host}`;
351
+ }
352
+ const local = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/.test(url.hostname);
353
+ return local || !tenantDomain ? url.origin : `https://${tenantDomain}`;
354
+ }
355
+
356
+ /** @param {string} origin */
357
+ export function marketplaceRobots(origin) {
358
+ return `User-agent: *\nDisallow: /api/\nAllow: /\n\nSitemap: ${origin}/sitemap.xml\n`;
359
+ }
360
+
361
+ /** @param {Request} request @param {{mimicFrontDomain?: string}} configuration */
362
+ export async function marketplaceRobotsResponse(request, configuration = {}) {
363
+ let domain = '';
364
+ try {
365
+ domain = (await readMarketplace(request, configuration)).domain;
366
+ } catch {
367
+ domain = '';
368
+ }
369
+ return new Response(
370
+ marketplaceRobots(marketplacePublicOrigin(request, domain)),
371
+ {
372
+ headers: {
373
+ 'Content-Type': 'text/plain; charset=utf-8',
374
+ 'Cache-Control': 'public, max-age=3600',
375
+ 'Vary': 'Host, X-Forwarded-Host, X-Front-Domain',
376
+ },
377
+ },
378
+ );
379
+ }
380
+
381
+ /** @param {string} value */
382
+ function escapeXml(value) {
383
+ return value.replace(/[<>&"']/g, (character) => ({
384
+ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;',
385
+ })[character]);
386
+ }
387
+
388
+ /** @param {unknown} value */
389
+ function publicId(value) {
390
+ const id = Number(value);
391
+ return Number.isSafeInteger(id) && id > 0 ? id : null;
392
+ }
393
+
394
+ /** The marketplace's languages from /appload `init.locale`. */
395
+ export function sitemapLocales(locales) {
396
+ const codes = Object.entries(locales && typeof locales === 'object' ? locales : {})
397
+ .map(([key, item]) => String(item?.code || key).trim().toLowerCase())
398
+ .filter((code) => /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/.test(code));
399
+ return [...new Set(codes)].sort();
400
+ }
401
+
402
+ /** A product edit time (ISO 8601) or a blog post day ({date: 'DD.MM.YYYY'}). */
403
+ export function sitemapLastmod(value, now = Date.now()) {
404
+ if (typeof value === 'string' && value) {
405
+ const time = Date.parse(value);
406
+ return Number.isFinite(time) && time <= now + 60_000
407
+ ? new Date(time).toISOString().replace(/\.\d{3}Z$/, 'Z')
408
+ : null;
409
+ }
410
+ const match = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value?.date ?? '');
411
+ if (!match) {
412
+ return null;
413
+ }
414
+ const [, day, month, year] = match;
415
+ const time = Date.UTC(Number(year), Number(month) - 1, Number(day));
416
+ const date = new Date(time);
417
+ return date.getUTCDate() === Number(day) &&
418
+ date.getUTCMonth() === Number(month) - 1 &&
419
+ time <= now + 24 * 60 * 60 * 1000
420
+ ? `${year}-${month}-${day}`
421
+ : null;
422
+ }
423
+
424
+ /** The API path (under /api) of a route named in /appload `unauth.paths`. */
425
+ export function sitemapApiPath(paths, name) {
426
+ for (const group of Object.values(paths ?? {})) {
427
+ for (const route of Object.values(group ?? {})) {
428
+ if (route?.url_name === name) {
429
+ const target = String(route.target ?? '').split('/{')[0].replace(/^\/+/, '');
430
+ return target.startsWith('api/') ? `/${target}` : null;
431
+ }
432
+ }
433
+ }
434
+ return null;
435
+ }
436
+
437
+ /** Public categories, parents before children. */
438
+ export function sitemapCategoryIds(categories) {
439
+ const ids = [];
440
+ const visit = (category) => {
441
+ const id = publicId(category?.id);
442
+ if (id && category?.is_public) {
443
+ ids.push(id);
444
+ }
445
+ (category?.childs ?? []).forEach(visit);
446
+ };
447
+ (Array.isArray(categories) ? categories : []).forEach(visit);
448
+ return [...new Set(ids)];
449
+ }
450
+
451
+ /**
452
+ * One <url> per page and language, each with alternates for its languages.
453
+ * A page with its own `locales` (a publication written in some languages
454
+ * only) is listed in those of the marketplace's languages.
455
+ * @param {string} origin
456
+ * @param {{path: string, lastmod?: string | null, locales?: string[]}[]} pages
457
+ * @param {string[]} locales
458
+ */
459
+ export function marketplaceSitemapXml(origin, pages, locales) {
460
+ const href = (path, code) => {
461
+ const url = new URL(path, `${origin}/`);
462
+ if (code) {
463
+ url.searchParams.set('locale', code);
464
+ }
465
+ return escapeXml(url.toString());
466
+ };
467
+ const urls = [];
468
+ for (const page of pages) {
469
+ const own = page.locales
470
+ ? locales.filter((code) => page.locales.includes(code))
471
+ : locales;
472
+ if (page.locales && !own.length) {
473
+ continue;
474
+ }
475
+ const codes = own.length ? own : [''];
476
+ const alternates = own.length > 1
477
+ ? own.map((code) =>
478
+ ` <xhtml:link rel="alternate" hreflang="${escapeXml(code)}" href="${href(page.path, code)}" />\n`).join('')
479
+ : '';
480
+ const lastmod = page.lastmod ? ` <lastmod>${escapeXml(page.lastmod)}</lastmod>\n` : '';
481
+ for (const code of codes) {
482
+ if (urls.length >= sitemapMaxUrls) {
483
+ break;
484
+ }
485
+ urls.push(` <url>\n <loc>${href(page.path, code)}</loc>\n${lastmod}${alternates} </url>\n`);
486
+ }
487
+ }
488
+ return '<?xml version="1.0" encoding="UTF-8"?>\n' +
489
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n' +
490
+ urls.join('') +
491
+ '</urlset>\n';
492
+ }
493
+
494
+ /** @param {{domain: string, api: URL}} tenant @param {string} path @param {unknown} body */
495
+ async function sitemapRequest(tenant, path, body) {
496
+ const response = await fetch(new URL(path, tenant.api.origin), {
497
+ method: 'POST',
498
+ headers: {
499
+ 'Content-Type': 'application/json',
500
+ 'Accept': 'application/json',
501
+ 'X-Front-Domain': tenant.domain,
502
+ },
503
+ body: JSON.stringify(body),
504
+ cache: 'no-store',
505
+ signal: AbortSignal.timeout(requestTimeout),
506
+ });
507
+ if (!response.ok) {
508
+ throw new Error(`${path} answered ${response.status}`);
509
+ }
510
+ return response.json();
511
+ }
512
+
513
+ /** Every record of a paginated list (`page_data[key].data` + `rpag`). */
514
+ async function sitemapList(tenant, path, key, filters = {}) {
515
+ const records = new Map();
516
+ let page = 1;
517
+ for (let count = 0; count < sitemapMaxPages; count++) {
518
+ const payload = await sitemapRequest(tenant, path, {
519
+ filters,
520
+ paginate: { page, pp_items: sitemapPageSize },
521
+ });
522
+ const list = payload?.page_data?.[key];
523
+ if (!Array.isArray(list?.data)) {
524
+ throw new Error(`${path} returned no ${key} list`);
525
+ }
526
+ for (const record of list.data) {
527
+ const id = publicId(record?.id);
528
+ if (id) {
529
+ records.set(id, record);
530
+ }
531
+ }
532
+ const next = Number(list.rpag?.next_page_number);
533
+ if (!list.rpag?.has_next || !Number.isSafeInteger(next) || next <= page) {
534
+ return [...records.values()];
535
+ }
536
+ page = next;
537
+ }
538
+ throw new Error(`${path} has more than ${sitemapMaxPages} pages`);
539
+ }
540
+
541
+ /** Products on sale and in stock states a shopper can open. */
542
+ function productOnSale(product) {
543
+ const status = Number(product?.status?.status ?? product?.status);
544
+ return [2, -2, -3].includes(status);
545
+ }
546
+
547
+ /** Blog publications that are published. */
548
+ function postPublished(post) {
549
+ const state = post?.publishing_state?.int ?? post?.publishing_state;
550
+ return state === undefined || state === null || Number(state) === 1;
551
+ }
552
+
553
+ /** The languages a publication is written in (it has a title there). */
554
+ function postLocales(post) {
555
+ return Object.entries(post?.locale && typeof post.locale === 'object' ? post.locale : {})
556
+ .filter(([, text]) => typeof text?.post_title === 'string' && text.post_title.trim())
557
+ .map(([code]) => code.toLowerCase());
558
+ }
559
+
560
+ /** @param {{domain: string, api: URL}} tenant */
561
+ async function buildMarketplaceSitemap(tenant) {
562
+ const appload = await sitemapRequest(tenant, '/api/appload', {
563
+ detalize_mode: 'light',
564
+ ignore_cache: false,
565
+ });
566
+ const init = appload?.page_data?.init;
567
+ const paths = appload?.page_data?.unauth?.paths;
568
+ if (!init || !Array.isArray(init.catalog)) {
569
+ throw new Error('appload returned no catalog');
570
+ }
571
+ const locales = sitemapLocales(init.locale);
572
+ const categories = sitemapCategoryIds(init.catalog);
573
+ const blogPath = sitemapApiPath(paths, 'blog_posts_get');
574
+ const searchPath = sitemapApiPath(paths, 'products_search');
575
+ const [products, posts] = await Promise.all([
576
+ searchPath && categories.length
577
+ ? sitemapList(tenant, searchPath, 'products', { categories })
578
+ : [],
579
+ blogPath ? sitemapList(tenant, blogPath, 'posts') : [],
580
+ ]);
581
+ const postPages = posts
582
+ .filter(postPublished)
583
+ .sort((left, right) => left.id - right.id)
584
+ .map((post) => ({
585
+ path: `/journal/${post.id}`,
586
+ lastmod: sitemapLastmod(post.date_updated),
587
+ locales: postLocales(post),
588
+ }));
589
+ const newestPost = postPages.map((page) => page.lastmod).filter(Boolean).sort().at(-1) ?? null;
590
+ const pages = [
591
+ { path: '/' },
592
+ { path: '/catalog' },
593
+ ...(blogPath ? [{ path: '/journal', lastmod: newestPost }] : []),
594
+ ...(init.tariffs?.data?.length ? [{ path: '/tariffs' }] : []),
595
+ { path: '/manufacturers' },
596
+ ...(init.visual_settings?.single_seller_mode ? [] : [{ path: '/sellers' }]),
597
+ { path: '/stores' },
598
+ { path: '/contact' },
599
+ { path: '/privacy' },
600
+ ...categories.map((id) => ({ path: `/category/${id}` })),
601
+ ...products
602
+ .filter(productOnSale)
603
+ .map((product) => ({
604
+ path: `/product/${product.id}`,
605
+ lastmod: sitemapLastmod(product.date_updated),
606
+ })),
607
+ ...postPages,
608
+ ];
609
+ return {
610
+ version: sitemapVersion,
611
+ domain: tenant.domain,
612
+ built: new Date().toISOString(),
613
+ locales,
614
+ pages,
615
+ };
616
+ }
617
+
618
+ /** How many <url> entries a built sitemap has. */
619
+ export function sitemapUrlCount(sitemap) {
620
+ let count = 0;
621
+ for (const page of sitemap.pages) {
622
+ const own = page.locales
623
+ ? sitemap.locales.filter((code) => page.locales.includes(code))
624
+ : sitemap.locales;
625
+ count += page.locales ? own.length : Math.max(own.length, 1);
626
+ }
627
+ return Math.min(count, sitemapMaxUrls);
628
+ }
629
+
630
+ /** The cache folder of built sitemaps. */
631
+ export function sitemapCacheDirectory(root = process.cwd()) {
632
+ return environment.ORIONPLACE_CACHE_DIR
633
+ ? resolve(root, environment.ORIONPLACE_CACHE_DIR, 'sitemaps')
634
+ : resolve(root, 'node_modules', '.cache', 'orionplace', 'sitemaps');
635
+ }
636
+
637
+ /** @param {string} domain @param {string} root */
638
+ function sitemapCachePath(domain, root) {
639
+ return resolve(sitemapCacheDirectory(root), `${domain}.json`);
640
+ }
641
+
642
+ /** A cached sitemap of the domain, or null. @param {string} domain */
643
+ export async function readSitemapCache(domain, root = process.cwd()) {
644
+ let sitemap;
645
+ try {
646
+ sitemap = JSON.parse(await readFile(sitemapCachePath(domain, root), 'utf8'));
647
+ } catch {
648
+ return null;
649
+ }
650
+ return sitemap?.version === sitemapVersion &&
651
+ sitemap.domain === domain &&
652
+ Number.isFinite(Date.parse(sitemap.built)) &&
653
+ Array.isArray(sitemap.locales) &&
654
+ Array.isArray(sitemap.pages)
655
+ ? sitemap
656
+ : null;
657
+ }
658
+
659
+ /**
660
+ * Write the cache file. When root writes it (sudo), the folders it creates
661
+ * and the file go to the project owner, so the storefront service can
662
+ * replace them later.
663
+ */
664
+ async function writeSitemapCache(sitemap, root) {
665
+ const path = sitemapCachePath(sitemap.domain, root);
666
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
667
+ await mkdir(dirname(path), { recursive: true });
668
+ try {
669
+ await writeFile(temporary, JSON.stringify(sitemap), { mode: 0o644 });
670
+ await rename(temporary, path);
671
+ } catch (error) {
672
+ await unlink(temporary).catch(() => {});
673
+ throw error;
674
+ }
675
+ if (process.getuid?.() === 0) {
676
+ const owner = await stat(root);
677
+ if (owner.uid !== 0) {
678
+ let cursor = path;
679
+ while (cursor !== root && !relative(root, cursor).startsWith('..')) {
680
+ const info = await stat(cursor);
681
+ if (info.uid === 0) {
682
+ await chown(cursor, owner.uid, owner.gid);
683
+ }
684
+ cursor = dirname(cursor);
685
+ }
686
+ }
687
+ }
688
+ return path;
689
+ }
690
+
691
+ /** @param {{domain: string, api: URL}} tenant @param {string} root */
692
+ function buildOnce(tenant, root) {
693
+ let build = sitemapBuilds.get(tenant.domain);
694
+ if (!build) {
695
+ build = buildMarketplaceSitemap(tenant)
696
+ .then(async (sitemap) => {
697
+ sitemapMemory.set(tenant.domain, sitemap);
698
+ try {
699
+ await writeSitemapCache(sitemap, root);
700
+ } catch (error) {
701
+ console.error(`[orionplace] Sitemap cache not written: ${error?.code ?? error?.message ?? error}`);
702
+ }
703
+ return sitemap;
704
+ })
705
+ .finally(() => sitemapBuilds.delete(tenant.domain));
706
+ sitemapBuilds.set(tenant.domain, build);
707
+ }
708
+ return build;
709
+ }
710
+
711
+ /**
712
+ * Rebuild the sitemap of one storefront domain now and store it where the
713
+ * running storefront reads it (the "sitemap rebuild" command).
714
+ * @param {string} domain @param {{root?: string}} options
715
+ */
716
+ export async function rebuildMarketplaceSitemap(domain, options = {}) {
717
+ const root = resolve(options.root ?? process.cwd());
718
+ const tenant = await readMarketplaceDomain(domain, { root });
719
+ const sitemap = await buildMarketplaceSitemap(tenant);
720
+ const path = await writeSitemapCache(sitemap, root);
721
+ return {
722
+ domain: tenant.domain,
723
+ path,
724
+ built: sitemap.built,
725
+ urls: sitemapUrlCount(sitemap),
726
+ pages: sitemap.pages.length,
727
+ publications: sitemap.pages.filter((page) => page.path.startsWith('/journal/')).length,
728
+ };
729
+ }
730
+
731
+ /** The storefront domains of the project (its `sitemaps/*.cfg` files). */
732
+ export async function marketplaceDomains(root = process.cwd()) {
733
+ let names;
734
+ try {
735
+ names = await readdir(marketplaceConfigDirectory(root));
736
+ } catch (error) {
737
+ if (error?.code === 'ENOENT') {
738
+ return [];
739
+ }
740
+ throw error;
741
+ }
742
+ return names
743
+ .filter((name) => name.endsWith('.cfg'))
744
+ .map((name) => normalizeFrontDomain(name.slice(0, -4)))
745
+ .filter(Boolean)
746
+ .sort();
747
+ }
748
+
749
+ /** @param {Request} request @param {{mimicFrontDomain?: string}} configuration */
750
+ export async function marketplaceSitemapResponse(request, configuration = {}) {
751
+ let tenant;
752
+ try {
753
+ tenant = await readMarketplace(request, configuration);
754
+ } catch {
755
+ return failure(503, 'Storefront domain configuration is missing or invalid');
756
+ }
757
+ const root = process.cwd();
758
+ const fresh = (sitemap) =>
759
+ sitemap && Date.now() - Date.parse(sitemap.built) < SITEMAP_LIFETIME;
760
+ // The file wins when it is newer: a "sitemap rebuild" replaced it.
761
+ const file = await readSitemapCache(tenant.domain, root);
762
+ const memory = sitemapMemory.get(tenant.domain);
763
+ const newest = [file, memory]
764
+ .filter(Boolean)
765
+ .sort((left, right) => Date.parse(right.built) - Date.parse(left.built))[0];
766
+ let sitemap = fresh(newest) ? newest : null;
767
+ if (!sitemap) {
768
+ try {
769
+ sitemap = await buildOnce(tenant, root);
770
+ } catch (error) {
771
+ console.error(`[orionplace] Sitemap build failed: ${error?.message ?? error}`);
772
+ if (!newest) {
773
+ return failure(502, 'Marketplace backend is unavailable');
774
+ }
775
+ sitemap = newest;
776
+ }
777
+ }
778
+ const origin = marketplacePublicOrigin(request, tenant.domain);
779
+ return new Response(marketplaceSitemapXml(origin, sitemap.pages, sitemap.locales), {
780
+ headers: {
781
+ 'Content-Type': 'application/xml; charset=utf-8',
782
+ 'Cache-Control': 'public, max-age=3600',
783
+ 'Vary': 'Host, X-Forwarded-Host, X-Front-Domain',
784
+ },
785
+ });
786
+ }
@@ -0,0 +1,17 @@
1
+ // robots.txt and sitemap.xml of the storefront domain (see marketplace.mjs).
2
+ import { defineEventHandler, getRequestURL, toWebRequest, sendWebResponse } from 'h3';
3
+ import { useRuntimeConfig } from '#imports';
4
+ import { marketplaceRobotsResponse, marketplaceSitemapResponse } from './marketplace.mjs';
5
+
6
+ export default defineEventHandler(async (event) => {
7
+ const configuration = {
8
+ mimicFrontDomain:
9
+ process.env.MIMIC_FRONT_DOMAIN ??
10
+ useRuntimeConfig(event).mimicFrontDomain,
11
+ };
12
+ const request = toWebRequest(event);
13
+ const response = getRequestURL(event).pathname === '/robots.txt'
14
+ ? await marketplaceRobotsResponse(request, configuration)
15
+ : await marketplaceSitemapResponse(request, configuration);
16
+ return sendWebResponse(event, response);
17
+ });
package/src/module.mjs CHANGED
@@ -75,6 +75,12 @@ export default defineNuxtModule({
75
75
  addServerHandler({ route: '/api/**', handler: resolve(directory, 'api.mjs') });
76
76
  // Guarded blog images and videos; the runtime accepts only those paths.
77
77
  addServerHandler({ route: '/ps3/blog/**', handler: resolve(directory, 'api.mjs') });
78
+ // robots.txt and the sitemap of the storefront domain (projects set up
79
+ // earlier get seo.mjs with `npx orionplace-nuxt update`).
80
+ if (existsSync(resolve(directory, 'seo.mjs'))) {
81
+ addServerHandler({ route: '/robots.txt', method: 'get', handler: resolve(directory, 'seo.mjs') });
82
+ addServerHandler({ route: '/sitemap.xml', method: 'get', handler: resolve(directory, 'seo.mjs') });
83
+ }
78
84
  addServerHandler({ middleware: true, handler: resolve(directory, 'domain.mjs') });
79
85
  addServerPlugin(resolve(import.meta.dirname, 'asset-loading-plugin.mjs'));
80
86
  },
@@ -148,6 +148,7 @@ The React and Svelte packages supply the corresponding storefront and account UI
148
148
  | \`runtime/marketplace.mjs\` | Domain lookup, configuration validation, API transport and cookies. |
149
149
  | \`runtime/api.mjs\` | The Nuxt/Nitro HTTP handler for \`/api/**\` and blog media under \`/ps3/blog/**\`. |
150
150
  | \`runtime/domain.mjs\` | Resolves the frontend domain into the request context. |
151
+ | \`runtime/seo.mjs\` | The handler for \`/robots.txt\` and \`/sitemap.xml\`. |
151
152
  | \`settings.json\` | The CLI's frontend list, local MIMIC domain and personal backend; not a secret store. |
152
153
  | \`../sitemaps/${frontend}.cfg\` | The backend URL used for this frontend domain. |
153
154
  | \`../.env\` | Local MIMIC setting; keep secrets out of version control. |
@@ -555,8 +556,22 @@ location / {
555
556
 
556
557
  Here localhost is your frontend process on your VPS. That process selects the
557
558
  remote personal API from the domain file. The proxy must overwrite those headers.
558
- An unknown domain never falls back to another tenant. This setup does not generate
559
- sitemap XML or add analytics.
559
+ An unknown domain never falls back to another tenant. \`/robots.txt\` points
560
+ crawlers to \`/sitemap.xml\`, which lists the public pages, categories, products
561
+ on sale and journal publications in every storefront language (each publication
562
+ only in the languages it is written in). The sitemap is built from the backend
563
+ and kept for an hour in \`node_modules/.cache/orionplace/sitemaps/\`
564
+ (\`ORIONPLACE_CACHE_DIR\` moves it). After you publish or change content, rebuild
565
+ it at once from the project folder; the running storefront serves the new
566
+ sitemap without a restart:
567
+
568
+ \`\`\`bash
569
+ npm run orionplace:sitemap # every frontend domain
570
+ npx orionplace-nuxt sitemap rebuild shop.example.com # one domain
571
+ npx orionplace-nuxt sitemap status # when each was built
572
+ \`\`\`
573
+
574
+ This setup does not add analytics.
560
575
 
561
576
  ## Android app
562
577
 
package/src/setup.mjs CHANGED
@@ -167,6 +167,7 @@ export async function setupProject({ cwd = process.cwd(), action = 'set', field,
167
167
  pkg.scripts['orionplace:remove-frontend'] ||= 'orionplace-nuxt remove frontend';
168
168
  pkg.scripts['orionplace:mimic'] ||= 'orionplace-nuxt set mimic';
169
169
  pkg.scripts['orionplace:help'] ||= 'orionplace-nuxt help';
170
+ pkg.scripts['orionplace:sitemap'] ||= 'orionplace-nuxt sitemap rebuild';
170
171
  pkg.scripts['orionplace:update'] ||= 'orionplace-nuxt update';
171
172
  pkg.dependencies ||= {};
172
173
  pkg.dependencies['libphonenumber-js'] ||= dependencies['libphonenumber-js'] || '^1.13.10';
@@ -211,7 +212,7 @@ export async function setupProject({ cwd = process.cwd(), action = 'set', field,
211
212
  ] }, null, 2) + '\n', { managed: true });
212
213
  }
213
214
  await plan('package.json', JSON.stringify(pkg, null, 2) + '\n');
214
- for (const file of ['marketplace.mjs', 'api.mjs', 'domain.mjs']) {
215
+ for (const file of ['marketplace.mjs', 'api.mjs', 'domain.mjs', 'seo.mjs']) {
215
216
  await plan(`orionplace/runtime/${file}`, await readFile(new URL(`../runtime/${file}`, import.meta.url), 'utf8'), { managed: true, preserve: true });
216
217
  }
217
218
  await plan('orionplace/README.md', projectReadme(settings), { managed: true, preserve: true });
@@ -0,0 +1,93 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { relative, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
7
+ const cli = metadata.name;
8
+
9
+ /**
10
+ * The project's own gateway runtime (orionplace/runtime/marketplace.mjs): the
11
+ * sitemap is built with the code the running storefront uses.
12
+ */
13
+ async function projectRuntime(root) {
14
+ const path = resolve(root, 'orionplace/runtime/marketplace.mjs');
15
+ if (!existsSync(path)) {
16
+ throw new Error(`No orionplace/runtime/marketplace.mjs in ${root}. Run this in the storefront project (or pass --cwd).`);
17
+ }
18
+ const runtime = await import(pathToFileURL(path).href);
19
+ if (typeof runtime.rebuildMarketplaceSitemap !== 'function') {
20
+ throw new Error(`This project's runtime has no sitemap support. Run npx ${cli} update first.`);
21
+ }
22
+ return runtime;
23
+ }
24
+
25
+ /**
26
+ * The storefront reads SITEMAPS_DIR and ORIONPLACE_CACHE_DIR from the
27
+ * project's .env; the command uses the same folders. Variables already set
28
+ * in the shell win.
29
+ */
30
+ async function projectEnvironment(root) {
31
+ let source = '';
32
+ try { source = await readFile(resolve(root, '.env'), 'utf8'); }
33
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
34
+ for (const line of source.split(/\r?\n/)) {
35
+ const match = /^\s*(?:export\s+)?(SITEMAPS_DIR|ORIONPLACE_CACHE_DIR)\s*=\s*(.*?)\s*$/.exec(line);
36
+ if (!match || process.env[match[1]] !== undefined) continue;
37
+ const value = match[2].replace(/^(['"])(.*)\1$/, '$2');
38
+ if (value) process.env[match[1]] = resolve(root, value);
39
+ }
40
+ }
41
+
42
+ async function domainsFor(runtime, root, domain) {
43
+ if (domain) {
44
+ const normalized = runtime.normalizeFrontDomain(domain);
45
+ if (!normalized) throw new Error(`Invalid frontend domain: ${domain}`);
46
+ return [normalized];
47
+ }
48
+ const domains = await runtime.marketplaceDomains(root);
49
+ if (!domains.length) throw new Error(`No frontend domains yet. Add one: npx ${cli} add frontend <shop.example.com>`);
50
+ return domains;
51
+ }
52
+
53
+ function age(built, now = Date.now()) {
54
+ const minutes = Math.max(0, Math.round((now - Date.parse(built)) / 60_000));
55
+ return minutes < 60 ? `${minutes} min ago` : `${Math.floor(minutes / 60)} h ${minutes % 60} min ago`;
56
+ }
57
+
58
+ /**
59
+ * `sitemap rebuild [domain]`: build the sitemap of every frontend domain (or
60
+ * one) now. `sitemap status [domain]`: show when each was built.
61
+ * @param {{cwd: string, action: string, domain?: string, log?: (line: string) => void}} options
62
+ * @returns {Promise<number>} exit code
63
+ */
64
+ export async function sitemapCommand({ cwd, action, domain, log = console.log }) {
65
+ if (!['rebuild', 'status'].includes(action)) {
66
+ throw new Error(`Use: npx ${cli} sitemap rebuild [domain] | sitemap status [domain]`);
67
+ }
68
+ const root = resolve(cwd);
69
+ await projectEnvironment(root);
70
+ const runtime = await projectRuntime(root);
71
+ const domains = await domainsFor(runtime, root, domain);
72
+ let failed = 0;
73
+ for (const name of domains) {
74
+ if (action === 'status') {
75
+ const sitemap = await runtime.readSitemapCache(name, root);
76
+ const stale = sitemap && Date.now() - Date.parse(sitemap.built) >= runtime.SITEMAP_LIFETIME;
77
+ log(sitemap
78
+ ? `${name}: built ${sitemap.built} (${age(sitemap.built)}), ${runtime.sitemapUrlCount(sitemap)} URLs${stale ? '; rebuilt at the next crawl' : ''}`
79
+ : `${name}: not built yet; built at the first /sitemap.xml request or with: npx ${cli} sitemap rebuild`);
80
+ continue;
81
+ }
82
+ const started = Date.now();
83
+ try {
84
+ const done = await runtime.rebuildMarketplaceSitemap(name, { root });
85
+ log(`${name}: ${done.urls} URLs (${done.pages} pages, ${done.publications} journal publications) in ${((Date.now() - started) / 1000).toFixed(1)} s`);
86
+ log(` saved ${relative(root, done.path)}; the running storefront serves it now at https://${name}/sitemap.xml`);
87
+ } catch (error) {
88
+ failed++;
89
+ log(`${name}: not rebuilt: ${error?.message ?? error}`);
90
+ }
91
+ }
92
+ return failed ? 1 : 0;
93
+ }
@@ -7,13 +7,23 @@
7
7
  IStorefrontProfileState,
8
8
  IStorefrontProfileAction,
9
9
  } from '@/interfaces/orionplace/accounts/IStorefrontProfile';
10
- import { profileDate } from '@/utils/orionplace/profile';
10
+ import { profileCountryName, profileDate } from '@/utils/orionplace/profile';
11
11
 
12
12
  const props = defineProps<{ state: IStorefrontProfileState }>();
13
13
  const emit = defineEmits<{ request: [value: IStorefrontProfileAction] }>();
14
14
  const store = useOrionplaceStore();
15
15
  const selectionStore = useOrionplaceSelectionsStore();
16
16
  const copy = computed(() => profileLabels(selectionStore.localeCode));
17
+ // The phone country decides which payment methods the customer gets at checkout.
18
+ const phoneHint = computed(() => {
19
+ const country = profileCountryName(
20
+ store.profile?.origin_country,
21
+ selectionStore.localeCode,
22
+ );
23
+ return country
24
+ ? copy.value.phoneCountryHint.replace('{country}', country)
25
+ : copy.value.phoneHint;
26
+ });
17
27
  const busy = computed(
18
28
  () => Boolean(props.state.pending) || !props.state.loaded,
19
29
  );
@@ -140,7 +150,7 @@
140
150
  autocomplete="tel"
141
151
  readonly
142
152
  />
143
- <small>{{ copy.phoneHint }}</small>
153
+ <small>{{ phoneHint }}</small>
144
154
  </label>
145
155
  <label>
146
156
  {{ copy.dob }}
@@ -54,12 +54,16 @@ The cart response returns `cart.cart_address` as a copy of the address fields, w
54
54
 
55
55
  Payment choices come from `cart.payment_methods`. Each method shows its `logo`, or a card icon when the method has no logo or the image fails to load. Choosing a method sends its ID to `cart_customer_payment_set`. The «Choose payment method» prompt is listed only until a method is set: the backend cannot unset it.
56
56
 
57
+ When `payment_methods` is empty, the payment block shows «No payment method is available for this order…» instead of a select. The backend offers a method limited by country only to customers whose phone number is from one of its countries (`origin_country`), not by the delivery address.
58
+
57
59
  During checkout the user can enter another recipient or choose to receive the order personally. Personal receipt calls `cart_customer_reciever_clean`; the refreshed cart supplies the current recipient name and phone. The comment field takes up to 1024 characters and has a separate save button.
58
60
 
59
61
  On the Russian storefront a phone number typed without «+» the way it is written in Russia — «8 900 555-01-72» or «900 555-01-72» — becomes «+79005550172» when the field loses focus and before it is sent: the backend accepts only international numbers. A number typed with «+», other numbers and other languages are sent as typed (`phoneWithCountryCode()`).
60
62
 
61
63
  В русской витрине номер без «+», набранный по-российски — «8 900 555-01-72» или «900 555-01-72», — при выходе из поля и перед отправкой становится «+79005550172»: бэкенд принимает только международный формат. Номер с «+», другие номера и другие языки отправляются как набраны (`phoneWithCountryCode()`).
62
64
 
65
+ Когда `payment_methods` пуст, вместо списка показывается «Для этого заказа нет доступных способов оплаты…». Способ, ограниченный по странам, бэкенд предлагает только покупателям с номером телефона одной из этих стран (`origin_country`), а не по адресу доставки.
66
+
63
67
  The guide describes its inputs and events. Source is maintained in
64
68
  `app/components/orionplace/cart/CartCheckoutDetails.vue`; the primary interface is `app/interfaces/orionplace/cart/ICartData.ts`.
65
69
  The component belongs to the `cart` composition; render it with that
@@ -192,7 +192,17 @@
192
192
  <template v-if="cart.checkout.value">
193
193
  <section class="commerce-panel op-feature-stack">
194
194
  <h2 class="commerce-subtitle">{{ labels.payment }}</h2>
195
+ <!-- Methods depend on the order and on the customer's phone country:
196
+ an empty list is said, not shown as a select with only the prompt. -->
197
+ <p
198
+ v-if="!methods.length"
199
+ class="op-feature-copy text-sm text-orionplace-muted"
200
+ role="status"
201
+ >
202
+ {{ labels.noPayment }}
203
+ </p>
195
204
  <OrionplaceSelect
205
+ v-else
196
206
  :model-value="String(summary?.selected_payment ?? 0)"
197
207
  :options="payments"
198
208
  :icons="paymentIcons"
@@ -31,6 +31,8 @@ export interface IApiDateTime {
31
31
  export interface IProfileData {
32
32
  id: number;
33
33
  phone: string;
34
+ /** ISO 3166-1 alpha-2 country of the phone number; null when the number has none. */
35
+ origin_country: string | null;
34
36
  first_name: string;
35
37
  last_name: string;
36
38
  email: string;
@@ -6,6 +6,8 @@ export interface IApploadUserProfile {
6
6
  last_login: string | null;
7
7
  date_joined: string;
8
8
  phone: string;
9
+ /** ISO 3166-1 alpha-2 country of the phone number; null when the number has none. */
10
+ origin_country: string | null;
9
11
  password: boolean;
10
12
  dob: string | null;
11
13
  notifications_enabled: boolean;
@@ -22,6 +22,7 @@ const en = {
22
22
  'The address is saved, but there is no delivery to this country. Choose another address.',
23
23
  payment: 'Payment method',
24
24
  choosePayment: 'Choose payment method',
25
+ noPayment: 'No payment method is available for this order. Available methods depend on the order and on the country of your phone number.',
25
26
  delivery: 'Delivery',
26
27
  chooseDelivery: 'Choose delivery',
27
28
  selectDelivery: 'Please select a delivery method',
@@ -148,6 +149,7 @@ const ru: typeof en = {
148
149
  'Адрес сохранён, но доставки в эту страну нет. Выберите другой адрес.',
149
150
  payment: 'Способ оплаты',
150
151
  choosePayment: 'Выберите способ оплаты',
152
+ noPayment: 'Для этого заказа нет доступных способов оплаты. Они зависят от заказа и от страны вашего номера телефона.',
151
153
  delivery: 'Доставка',
152
154
  chooseDelivery: 'Выбрать доставку',
153
155
  selectDelivery: 'Выберите способ доставки',
@@ -34,6 +34,18 @@ export function profileDate(value: string | null | undefined) {
34
34
  : '';
35
35
  }
36
36
 
37
+ /** The name of a phone country code (`RU` → «Россия» / «Russia»); the code itself when the browser has no name. */
38
+ export function profileCountryName(code: string | null | undefined, locale: string) {
39
+ if (!code) {
40
+ return '';
41
+ }
42
+ try {
43
+ return new Intl.DisplayNames([locale], { type: 'region' }).of(code) || code;
44
+ } catch {
45
+ return code;
46
+ }
47
+ }
48
+
37
49
  export class ProfileRequestError extends Error {
38
50
  readonly kind = 'profile-request';
39
51
  fields: Record<string, string>;
@@ -10,6 +10,7 @@ const en = {
10
10
  phone: 'Phone number',
11
11
  dob: 'Date of birth',
12
12
  phoneHint: 'Your sign-in phone number.',
13
+ phoneCountryHint: 'Your sign-in phone number. Its country, {country}, decides which payment methods you can use.',
13
14
  save: 'Save',
14
15
  saved: 'Changes saved.',
15
16
  loading: 'Loading your profile…',
@@ -84,6 +85,7 @@ const ru: typeof en = {
84
85
  phone: 'Номер телефона',
85
86
  dob: 'Дата рождения',
86
87
  phoneHint: 'Номер телефона для входа.',
88
+ phoneCountryHint: 'Номер телефона для входа. Его страна, {country}, определяет доступные способы оплаты.',
87
89
  save: 'Сохранить',
88
90
  saved: 'Изменения сохранены.',
89
91
  loading: 'Загружаем профиль…',