orionplace-svelte 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
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
@@ -325,6 +325,8 @@ npx orionplace-svelte add frontend shop.example.com
325
325
  npx orionplace-svelte add frontend www.shop.example.com
326
326
  npx orionplace-svelte remove frontend www.shop.example.com
327
327
  npx orionplace-svelte set mimic shop.example.com
328
+ npx orionplace-svelte sitemap rebuild [shop.example.com]
329
+ npx orionplace-svelte sitemap status
328
330
  sudo npx orionplace-svelte install
329
331
  npx orionplace-svelte status
330
332
  sudo npx orionplace-svelte restart
@@ -341,8 +343,15 @@ npm run orionplace:remove-frontend -- www.shop.example.com
341
343
  npm run orionplace:mimic -- shop.example.com
342
344
  npm run orionplace:help
343
345
  npm run orionplace:update
346
+ npm run orionplace:sitemap
344
347
  ```
345
348
 
349
+ The storefront serves `/robots.txt` and `/sitemap.xml` (public pages, categories,
350
+ products and journal publications in every language). The sitemap is rebuilt
351
+ from the backend once an hour; `npm run orionplace:sitemap` rebuilds it at once,
352
+ for example after new publications, and the running storefront serves it without
353
+ a restart.
354
+
346
355
  `npm set` belongs to npm's own configuration system; use the commands above.
347
356
  The setup commands configure local integration files. They do not provision a
348
357
  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-svelte remove frontend <shop.example.com>
31
32
  npx orionplace-svelte set mimic <existing-frontend.example.com>
32
33
  npx orionplace-svelte set frontend <shop.example.com>
34
+ npx orionplace-svelte sitemap rebuild [domain] rebuild /sitemap.xml now (every frontend, or one);
35
+ the running storefront serves it at once
36
+ npx orionplace-svelte 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-svelte install
@@ -131,6 +135,9 @@ try {
131
135
  }
132
136
  const done = await controlService({ action: command, cwd, name: install.name, lines: positional[1] ?? 100, follow, dryRun });
133
137
  process.exitCode = printService(done);
138
+ } else if (command === 'sitemap' && positional.length <= 3) {
139
+ if (dryRun) throw new Error('--dry-run is not a sitemap option; sitemap status shows the state without changes.');
140
+ process.exitCode = await sitemapCommand({ cwd, action: target, domain: positional[2] });
134
141
  } else if (command === 'init' && positional.length <= 2) {
135
142
  result = await setupProject({ cwd: target ? resolve(cwd, target) : cwd, dryRun });
136
143
  } else if (command === 'update' && positional.length === 1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orionplace-svelte",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "SvelteKit 2 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",
@@ -25,3 +25,88 @@ export declare function forwardMarketplace(
25
25
  request: Request,
26
26
  configuration?: MarketplaceConfiguration,
27
27
  ): Promise<Response>;
28
+
29
+ export interface MarketplaceSitemapPage {
30
+ path: string;
31
+ lastmod?: string | null;
32
+ locales?: string[];
33
+ }
34
+
35
+ export declare function marketplacePublicOrigin(
36
+ request: Request,
37
+ tenantDomain?: string,
38
+ ): string;
39
+
40
+ export declare function marketplaceRobots(origin: string): string;
41
+
42
+ export declare function marketplaceRobotsResponse(
43
+ request: Request,
44
+ configuration?: MarketplaceConfiguration,
45
+ ): Promise<Response>;
46
+
47
+ export declare function sitemapLocales(locales: unknown): string[];
48
+
49
+ export declare function sitemapLastmod(
50
+ value: unknown,
51
+ now?: number,
52
+ ): string | null;
53
+
54
+ export declare function sitemapApiPath(
55
+ paths: unknown,
56
+ name: string,
57
+ ): string | null;
58
+
59
+ export declare function sitemapCategoryIds(categories: unknown): number[];
60
+
61
+ export declare function marketplaceSitemapXml(
62
+ origin: string,
63
+ pages: MarketplaceSitemapPage[],
64
+ locales: string[],
65
+ ): string;
66
+
67
+ export declare function marketplaceSitemapResponse(
68
+ request: Request,
69
+ configuration?: MarketplaceConfiguration,
70
+ ): Promise<Response>;
71
+
72
+ export interface MarketplaceSitemap {
73
+ version: number;
74
+ domain: string;
75
+ built: string;
76
+ locales: string[];
77
+ pages: MarketplaceSitemapPage[];
78
+ }
79
+
80
+ export interface MarketplaceSitemapRebuild {
81
+ domain: string;
82
+ path: string;
83
+ built: string;
84
+ urls: number;
85
+ pages: number;
86
+ publications: number;
87
+ }
88
+
89
+ export declare const SITEMAP_LIFETIME: number;
90
+
91
+ export declare function readMarketplaceDomain(
92
+ domain: string,
93
+ options?: { root?: string },
94
+ ): Promise<MarketplaceTenant>;
95
+
96
+ export declare function marketplaceConfigDirectory(root?: string): string;
97
+
98
+ export declare function marketplaceDomains(root?: string): Promise<string[]>;
99
+
100
+ export declare function sitemapCacheDirectory(root?: string): string;
101
+
102
+ export declare function readSitemapCache(
103
+ domain: string,
104
+ root?: string,
105
+ ): Promise<MarketplaceSitemap | null>;
106
+
107
+ export declare function sitemapUrlCount(sitemap: MarketplaceSitemap): number;
108
+
109
+ export declare function rebuildMarketplaceSitemap(
110
+ domain: string,
111
+ options?: { root?: string },
112
+ ): Promise<MarketplaceSitemapRebuild>;
@@ -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
+ }
@@ -97,6 +97,7 @@ discovery and the same-origin gateway.
97
97
  | \`settings.json\` | The CLI's frontend list, local MIMIC domain and personal backend; not a secret store. |
98
98
  | \`../src/routes/api/[...orionplace]/+server.ts\` | The route serving \`/api/...\` from your project. |
99
99
  | \`../src/routes/ps3/blog/[...orionplace]/+server.ts\` | The route serving guarded blog images and videos under \`/ps3/blog/...\`. |
100
+ | \`../src/routes/robots.txt/+server.ts\`, \`../src/routes/sitemap.xml/+server.ts\` | \`/robots.txt\` and the storefront sitemap. |
100
101
  | \`../src/hooks.server.ts\` | Marks personalized pages private and varies them by storefront domain. |
101
102
  | \`../svelte.config.js\` | Uses \`@sveltejs/adapter-node\`, which this integration requires. |
102
103
  | \`../vite.config.ts\` | Allows your storefront domains during local development. |
@@ -381,8 +382,22 @@ location / {
381
382
 
382
383
  Here localhost is your frontend process on your VPS. That process selects the
383
384
  remote personal API from the domain file. The proxy must overwrite those headers.
384
- An unknown domain never falls back to another tenant. This setup does not generate
385
- sitemap XML or add analytics.
385
+ An unknown domain never falls back to another tenant. \`/robots.txt\` points
386
+ crawlers to \`/sitemap.xml\`, which lists the public pages, categories, products
387
+ on sale and journal publications in every storefront language (each publication
388
+ only in the languages it is written in). The sitemap is built from the backend
389
+ and kept for an hour in \`node_modules/.cache/orionplace/sitemaps/\`
390
+ (\`ORIONPLACE_CACHE_DIR\` moves it). After you publish or change content, rebuild
391
+ it at once from the project folder; the running storefront serves the new
392
+ sitemap without a restart:
393
+
394
+ \`\`\`bash
395
+ npm run orionplace:sitemap # every frontend domain
396
+ npx orionplace-svelte sitemap rebuild shop.example.com # one domain
397
+ npx orionplace-svelte sitemap status # when each was built
398
+ \`\`\`
399
+
400
+ This setup does not add analytics.
386
401
 
387
402
  ## Android app
388
403
 
package/src/setup.mjs CHANGED
@@ -186,6 +186,7 @@ export async function setupProject({ cwd = process.cwd(), action = 'set', field,
186
186
  pkg.scripts['orionplace:remove-frontend'] ||= 'orionplace-svelte remove frontend';
187
187
  pkg.scripts['orionplace:mimic'] ||= 'orionplace-svelte set mimic';
188
188
  pkg.scripts['orionplace:help'] ||= 'orionplace-svelte help';
189
+ pkg.scripts['orionplace:sitemap'] ||= 'orionplace-svelte sitemap rebuild';
189
190
  pkg.scripts['orionplace:update'] ||= 'orionplace-svelte update';
190
191
  pkg.dependencies ||= {};
191
192
  pkg.dependencies['country-flag-icons'] ||= dependencies['country-flag-icons'] || '^1.6.20';
@@ -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
+ }
@@ -10,8 +10,11 @@ function escapeAttribute(value: string) {
10
10
 
11
11
  /**
12
12
  * Personalized pages are never shared between visitors or storefront domains.
13
- * The API gateway sets its own headers, so requests under /api are left alone.
13
+ * The API gateway, robots.txt and the sitemap set their own headers, so those
14
+ * requests are left alone.
14
15
  */
16
+ const ownHeaders = ['/robots.txt', '/sitemap.xml'];
17
+
15
18
  export const handle: Handle = async ({ event, resolve }) => {
16
19
  const response = await resolve(event, {
17
20
  transformPageChunk: ({ html }) =>
@@ -20,7 +23,10 @@ export const handle: Handle = async ({ event, resolve }) => {
20
23
  escapeAttribute(event.locals.orionplaceLocale ?? 'en'),
21
24
  ),
22
25
  });
23
- if (!event.url.pathname.startsWith('/api/')) {
26
+ if (
27
+ !event.url.pathname.startsWith('/api/') &&
28
+ !ownHeaders.includes(event.url.pathname)
29
+ ) {
24
30
  response.headers.set('Cache-Control', 'private, no-store');
25
31
  response.headers.set('Vary', 'Host, X-Forwarded-Host, X-Front-Domain');
26
32
  }
@@ -8,6 +8,8 @@ profile, the date is sent as `YYYY-MM-DD`, and `profile_update_info` updates the
8
8
  only after a successful answer. An error keeps the entered values, and changes to email,
9
9
  the photo or the notification preference do not discard unsaved personal details.
10
10
 
11
+ Under the phone the hint names its country: `user.origin_country` from the application load, shown with the browser's country name («Its country, Russia, decides which payment methods you can use»). Without a country the plain hint stays.
12
+
11
13
  Source: `src/lib/components/orionplace/account/ProfileDetailsForm.svelte`.
12
14
 
13
15
  ## Inputs
@@ -11,7 +11,7 @@
11
11
  IStorefrontProfileState,
12
12
  IStorefrontProfileAction,
13
13
  } from '@/lib/interfaces/orionplace/accounts/IStorefrontProfile';
14
- import { profileDate } from '@/lib/utils/orionplace/profile';
14
+ import { profileCountryName, profileDate } from '@/lib/utils/orionplace/profile';
15
15
  import '@/lib/components/orionplace/account/profile.css';
16
16
 
17
17
  type Props = {
@@ -40,6 +40,16 @@
40
40
  const store = useOrionplaceStore();
41
41
  const selectionStore = useOrionplaceSelectionsStore();
42
42
  const copy = computed(() => profileLabels(selectionStore.localeCode));
43
+ // The phone country decides which payment methods the customer gets at checkout.
44
+ const phoneHint = computed(() => {
45
+ const country = profileCountryName(
46
+ store.profile?.origin_country,
47
+ selectionStore.localeCode,
48
+ );
49
+ return country
50
+ ? copy.value.phoneCountryHint.replace('{country}', country)
51
+ : copy.value.phoneHint;
52
+ });
43
53
  const busy = computed(
44
54
  () => Boolean(inputs.state.pending) || !inputs.state.loaded,
45
55
  );
@@ -181,7 +191,7 @@
181
191
  readonly
182
192
  />
183
193
  <small>
184
- {copy.value.phoneHint}
194
+ {phoneHint.value}
185
195
  </small>
186
196
  </label>
187
197
  <label>
@@ -4,9 +4,13 @@ Delivery address, payment method, recipient and comment.
4
4
 
5
5
  This part of checkout holds everything that belongs to the order as a whole: the delivery address, the payment method, the recipient and the comment. It saves each of them itself and shows what the refreshed cart confirms. Only addresses in a delivery country (`country.is_shipping_country`) are offered; when others exist, a note says they are hidden. A new address abroad is saved, but not set for the cart, and a note asks to choose another address.
6
6
 
7
+ 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.
8
+
7
9
  The recipient's phone follows the storefront rule: 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()`).
8
10
 
9
11
  В русской витрине номер без «+», набранный по-российски — «8 900 555-01-72» или «900 555-01-72», — при выходе из поля и перед отправкой становится «+79005550172»: бэкенд принимает только международный формат. Номер с «+», другие номера и другие языки отправляются как набраны (`phoneWithCountryCode()`).
10
12
 
13
+ Когда `payment_methods` пуст, вместо списка показывается «Для этого заказа нет доступных способов оплаты…». Способ, ограниченный по странам, бэкенд предлагает только покупателям с номером телефона одной из этих стран (`origin_country`), а не по адресу доставки.
14
+
11
15
  Source: `src/lib/components/orionplace/cart/CartCheckoutDetails.svelte`.
12
16
 
@@ -211,15 +211,26 @@
211
211
  <h2 class={['commerce-subtitle']}>
212
212
  {labels.value.payment}
213
213
  </h2>
214
- <OrionplaceSelect
215
- modelValue={String(summary.value?.selected_payment ?? 0)}
216
- options={payments.value}
217
- icons={paymentIcons.value}
218
- label={labels.value.payment}
219
- disabled={cart.disabled.value}
220
- required
221
- onChange={selectPayment}
222
- />
214
+ <!-- Methods depend on the order and on the customer's phone country:
215
+ an empty list is said, not shown as a select with only the prompt. -->
216
+ {#if !methods.value.length}
217
+ <p
218
+ class={['op-feature-copy text-sm text-orionplace-muted']}
219
+ role="status"
220
+ >
221
+ {labels.value.noPayment}
222
+ </p>
223
+ {:else}
224
+ <OrionplaceSelect
225
+ modelValue={String(summary.value?.selected_payment ?? 0)}
226
+ options={payments.value}
227
+ icons={paymentIcons.value}
228
+ label={labels.value.payment}
229
+ disabled={cart.disabled.value}
230
+ required
231
+ onChange={selectPayment}
232
+ />
233
+ {/if}
223
234
  </section>
224
235
  <section class={['commerce-panel op-feature-stack']}>
225
236
  <h2 class={['commerce-subtitle']}>
@@ -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: 'Загружаем профиль…',
@@ -0,0 +1,9 @@
1
+ // robots.txt of the storefront domain; it points crawlers to the sitemap.
2
+ import { env } from '$env/dynamic/private';
3
+ import { marketplaceRobotsResponse } from '@orionplace-runtime/marketplace.mjs';
4
+ import type { RequestHandler } from './$types';
5
+
6
+ export const GET: RequestHandler = ({ request }) =>
7
+ marketplaceRobotsResponse(request, {
8
+ mimicFrontDomain: env.MIMIC_FRONT_DOMAIN ?? '',
9
+ });
@@ -0,0 +1,10 @@
1
+ // The storefront sitemap: public pages, categories, products and journal
2
+ // publications in every language, built from the backend for an hour.
3
+ import { env } from '$env/dynamic/private';
4
+ import { marketplaceSitemapResponse } from '@orionplace-runtime/marketplace.mjs';
5
+ import type { RequestHandler } from './$types';
6
+
7
+ export const GET: RequestHandler = ({ request }) =>
8
+ marketplaceSitemapResponse(request, {
9
+ mimicFrontDomain: env.MIMIC_FRONT_DOMAIN ?? '',
10
+ });