Skip to content

Commit

Permalink
Add support for localized URLs when the i18n fallback type is set to …
Browse files Browse the repository at this point in the history
…'rewrite'
  • Loading branch information
xentobias committed Oct 8, 2024
1 parent af8401e commit 676ce8f
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/integrations/sitemap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,26 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
return urls;
}, []);

if (
opts.i18n &&
config.i18n &&
config.i18n.routing !== 'manual' &&
config.i18n.routing.fallbackType === 'rewrite'
) {
const { locales, defaultLocale } = opts.i18n;
const alternateLocales = Object.keys(locales).filter((locale) => {
return locale !== defaultLocale;
});

pageUrls.forEach((url) => {
alternateLocales.forEach((locale) => {
const newUrl = new URL(url);
newUrl.pathname = `/${locale}${newUrl.pathname}`;
pageUrls.push(newUrl.href);
});
});
}

pageUrls = Array.from(new Set([...pageUrls, ...routeUrls, ...(customPages ?? [])]));

try {
Expand Down
41 changes: 41 additions & 0 deletions packages/integrations/sitemap/test/i18n-rewrite.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import assert from 'node:assert/strict';
import { before, describe, it } from 'node:test';
import { loadFixture, readXML } from './test-utils.js';

describe('i18n-rewrite', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
/** @type {string[]} */
let urls;

before(async () => {
fixture = await loadFixture({
root: './fixtures/static/',
i18n: {
defaultLocale: 'it',
locales: ['it', 'de'],
routing: {
fallbackType: 'rewrite',
},
},
});
await fixture.build();

const data = await readXML(fixture.readFile('/sitemap-0.xml'));
urls = data.urlset.url.map((url) => url.loc[0]);
});

it('includes internationalized for getStaticPaths', async () => {
assert.equal(urls.includes('http://example.com/de/one/'), true);
assert.equal(urls.includes('http://example.com/de/two/'), true);
});

it('includes internationalized for numerical pages', () => {
assert.equal(urls.includes('http://example.com/de/123/'), true);
});

it('includes internationalized numerical 404 pages if not for i18n', () => {
assert.equal(urls.includes('http://example.com/de/products-by-id/405/'), true);
assert.equal(urls.includes('http://example.com/de/products-by-id/404/'), true);
});
});

0 comments on commit 676ce8f

Please sign in to comment.