### Multi-Language Configuration Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Configure multiple locales with different domains or prefixes in the '@apostrophecms/i18n' module options. This setup affects how sitemaps are generated and accessed. ```javascript modules: { '@apostrophecms/i18n': { options: { defaultLocale: 'en', locales: { en: { label: 'English' }, es: { label: 'Español', prefix: '/es' }, fr: { label: 'Français', hostname: 'fr.example.com' } } } } } ``` -------------------------------- ### UrlEntry Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md An example of a UrlEntry object, demonstrating how to structure URL data including multiple alternate language links. ```javascript { url: { id: 'ck4x2k9x2x9x2x9x', locale: 'en', priority: 0.9, changefreq: 'daily', loc: 'https://example.com/about', 'xhtml:link': [ { _attributes: { rel: 'alternate', hreflang: 'en', href: 'https://example.com/about' } }, { _attributes: { rel: 'alternate', hreflang: 'es', href: 'https://example.com/es/about' } } ] } } ``` -------------------------------- ### GitHub Actions CI/CD Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md This example demonstrates how to integrate sitemap cache warming into a GitHub Actions workflow. It ensures the sitemap is up-to-date after deployment. ```yaml name: Deploy on: [push] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install dependencies run: npm install - name: Start application run: npm start & # Let app start - name: Warm sitemap cache run: apos sitemap:update-cache - name: Verify run: curl -f http://localhost:3000/sitemap.xml > /dev/null - name: Deploy to production run: npm run deploy ``` -------------------------------- ### SitemapOptions Usage Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Example of how to configure the SitemapOptions object in your ApostropheCMS module configuration. ```javascript const options = { cacheLifetime: 3600, piecesPerBatch: 100, excludeTypes: ['draft', 'internal'], perLocale: false }; ``` -------------------------------- ### Fetch Main Sitemap via cURL Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Example of how to fetch the main sitemap.xml using cURL. ```bash curl https://example.com/sitemap.xml ``` -------------------------------- ### Unit Test Example for Sitemap Generation Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Write unit tests for the sitemap module to verify XML generation and content inclusion. This example demonstrates testing basic XML structure, inclusion of published content, and exclusion of specified types. ```javascript // In your test file describe('Sitemap', function() { let apos; before(async function() { apos = await t.create({ baseUrl: 'http://localhost:3000', modules: { '@apostrophecms/sitemap': {} } }); }); it('should generate valid XML', async function() { const xml = await apos.http.get('/sitemap.xml'); assert(xml.includes('')); }); it('should include published content', async function() { // Create and publish test page const page = apos.page.newInstance(); page.title = 'Test'; page.slug = '/test'; await apos.page.insert(apos.task.getReq(), page); // Get sitemap const xml = await apos.http.get('/sitemap.xml'); assert(xml.includes('/test')); }); it('should exclude specified types', async function() { const xml = await apos.http.get('/sitemap.xml'); // Verify exclusions assert(!xml.includes('internal-')); }); after(async function() { return t.destroy(apos); }); }); ``` -------------------------------- ### Sitemap Module Configuration Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Configures sitemap options including cache lifetime, excluded types, and per-locale sitemaps. ```javascript modules: { '@apostrophecms/sitemap': { options: { cacheLifetime: 3600, excludeTypes: ['draft'], perLocale: false } } } ``` -------------------------------- ### Print Sitemap CLI Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Use this command to print the sitemap to the console without caching. It accepts options to exclude specific content types. ```bash apos sitemap:print --exclude-types draft,temp ``` -------------------------------- ### CacheEntry Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md An example of a CacheEntry object, showing the structure of cached sitemap XML data. ```javascript { filename: 'sitemap.xml', data: ' ...', createdAt: new Date('2025-01-15T10:30:45.123Z') } ``` -------------------------------- ### Fetch Main Sitemap via JavaScript Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Example of how to fetch the main sitemap.xml using JavaScript's fetch API in a browser or Node.js environment. ```javascript // In a browser or Node.js const response = await fetch('https://example.com/sitemap.xml'); const xml = await response.text(); console.log(xml); ``` -------------------------------- ### Map Task Method Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Demonstrates how to call the mapTask method from a custom route or handler to update the sitemap cache. ```javascript // In a custom route or handler const sitemapModule = self.apos.modules['@apostrophecms/sitemap']; await sitemapModule.mapTask(true); // Update cache ``` -------------------------------- ### Post-Deployment Cache Warming - Bash Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md Example of warming the sitemap cache after a build in a deployment script. This ensures that initial requests after deployment do not incur the cost of sitemap generation. ```bash # In deployment script npm run build apos sitemap:update-cache # Now first requests won't wait for sitemap generation ``` -------------------------------- ### AposLocale Examples Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Examples of full locale identifiers, including default and variant formats. ```javascript 'en' // English default 'es:default' // Spanish with variant 'en:es' // English as primary, Spanish variant ``` -------------------------------- ### Update Sitemap Cache CLI Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Use this command to update the sitemap cache with fresh data. No options are required for a basic update. ```bash apos sitemap:update-cache ``` -------------------------------- ### Post-Deploy Hook Script Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md A bash script to warm the sitemap cache after deployment. It starts the application, waits for it to be ready, warms the cache, and verifies the sitemap. ```bash #!/bin/bash # deploy-hook.sh set -e # Start application npm start & APP_PID=$! # Wait for ready sleep 5 # Warm cache apos sitemap:update-cache # Verify curl -f http://localhost:3000/sitemap.xml > /dev/null || { kill $APP_PID exit 1 } echo "Sitemap cache warmed successfully" kill $APP_PID ``` -------------------------------- ### Exclude Types Configuration Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Example of configuring `excludeTypes` in the sitemap module options. Note that type name comparison is case-sensitive. ```javascript options: { excludeTypes: ['Page'] // Wrong case } // Actually need: ['page'] ``` -------------------------------- ### Module Lifecycle Flow Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/README.md Illustrates the sequence of operations from application start through module initialization, route registration, task execution, and HTTP request handling for sitemap generation, including cache hit and miss scenarios. ```mermaid graph TD A[Application Start] B[Module init() → validates baseUrl, sets defaults] C[Routes registered → /sitemap.xml and /sitemaps/*] D[Tasks registered → print, update-cache, clear] E[HTTP Request to /sitemap.xml] F[sendCache() → check cache] G[Cache hit → serve cached file (10-50ms)] H[Cache miss → cacheAndRetry()] I[map() → orchestrates generation] J[lock('apos-sitemap')] K[getPages() for each locale] L[getPieces() for each locale (batched)] M[hreflang() → add alternate links] N[writeSitemap() → serialize and cache] O[unlock('apos-sitemap')] P[sendCache() → serve newly cached file] Q[User receives XML response] A --> B B --> C C --> D D --> E E --> F F --> G F --> H H --> I I --> J J --> K K --> L L --> M M --> N N --> O O --> P P --> Q ``` -------------------------------- ### Priority Calculation Examples Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Illustrates how SEO priority is determined based on document level or explicit siteMapPriority property. ```javascript // Automatic from level level: 0 // priority = 1.0 (home page) level: 1 // priority = 0.9 (top-level pages) level: 2 // priority = 0.8 (second-level pages) level: 10 // priority = 0.1 (deep pages) // Custom priority siteMapPriority: 0.5 // Explicit custom priority ``` -------------------------------- ### Example Curl Commands for Sitemap Access Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Use these curl commands to fetch the sitemap index or specific locale sitemaps. Ensure your application's base URL is correctly configured. ```bash # Get the sitemap index curl https://example.com/sitemaps/index.xml # Get the English locale sitemap curl https://example.com/sitemaps/en.xml # Get the Spanish locale sitemap curl https://example.com/sitemaps/es.xml ``` -------------------------------- ### Example ApostropheCMS Request Object Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md An example of a request object, showing the locale and mode properties set for a sitemap generation task. ```javascript { locale: 'en', mode: 'published', // ... other properties from getAnonReq() } ``` -------------------------------- ### Alternate Language Links Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Demonstrates the structure of alternate language links within a sitemap entry. ```xml ``` -------------------------------- ### Example ApostropheCMS Document Object Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md An example of a document object, illustrating the expected fields and their typical values for sitemap generation. ```javascript { _id: 'ck4x2k9x2x9x2x9x:en', aposDocId: 'ck4x2k9x2x9x2x9x', type: 'page', aposLocale: 'en', aposMode: 'published', level: 2, rank: 1, _url: '/about', title: 'About Us', slug: '/about' } ``` -------------------------------- ### Sitemap Cache Lifetime Validation Examples Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Examples demonstrating valid and invalid configurations for 'cacheLifetime'. A value of 0 disables caching, while negative numbers trigger a warning and use the default. ```javascript // Invalid: will warn and use default options: { cacheLifetime: -1 // Warning logged } // Valid: disables caching options: { cacheLifetime: 0 } ``` -------------------------------- ### GET /sitemap.xml Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Serves the main sitemap file, which includes all URLs from all locales when per-locale mode is disabled. It checks the cache and generates the sitemap on demand if necessary. ```APIDOC ## GET /sitemap.xml ### Description Serves the main sitemap file. This endpoint is used when the `perLocale` option is false. ### Method GET ### Endpoint /sitemap.xml ### Parameters No request body or parameters required. ### Response #### Success Response (200) - **Content-Type**: `text/xml` - XML sitemap document #### Error Responses - **404** (`text/plain`) - "not found" - returned if cache exists but this file does not - **500** (`text/plain`) - "error" - returned if cache retrieval fails ### Response Format (Single-Locale Mode) ```xml https://example.com/ 1.0 daily ``` ### Behavior 1. Checks cache for `'sitemap.xml'`. 2. If not found in cache, checks if the main sitemap file exists in the cache. If yes, returns 404. If no, calls `cacheAndRetry()` to generate and cache the sitemap. 3. Returns the file with `text/xml` content type. ### Caching - Files are cached for the duration of `cacheLifetime` (default 3600 seconds). - Cache can be cleared with the `sitemap:clear` CLI task. - Cache is automatically regenerated on-demand if expired. ### Example Usage ```bash curl https://example.com/sitemap.xml ``` ```javascript const response = await fetch('https://example.com/sitemap.xml'); const xml = await response.text(); console.log(xml); ``` ``` -------------------------------- ### XML Attributes Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Demonstrates how to define XML attributes using the special `_attributes` key within an object. This is used by the `stringify` function. ```javascript { url: { _attributes: { rel: 'alternate', hreflang: 'en' }, loc: 'https://example.com' } } // Produces: https://example.com ``` -------------------------------- ### Deployment Workflow: Update Sitemap Cache Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md After building and starting a new version of the application, clear the old cache and generate a new sitemap. This ensures the deployed version uses fresh sitemap data. ```bash # Before deployment npm run build # After successful start of new version apos sitemap:clear # Clear old cache apos sitemap:update-cache # Generate new # Or as a single warmed deployment: apos sitemap:update-cache # First requests use cache instead of generating on-demand ``` -------------------------------- ### Hreflang Tag Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Example of hreflang tags used to indicate alternate language versions of a URL. This helps search engines index language variants correctly. ```xml ``` -------------------------------- ### Create Custom Route Using Sitemap Module Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Example of creating a custom API route that uses the sitemap module to generate sitemap statistics. It triggers a fresh sitemap generation and analyzes the results. ```javascript // In your custom module modules: { 'my-module': { apiRoutes(self) { return { get: { '/sitemap-stats': async (req, res) => { const sitemap = self.apos.modules['@apostrophecms/sitemap']; // Generate fresh sitemap await sitemap.map(); // Analyze it const totalUrls = Object.values(sitemap.maps) .reduce((sum, localeUrls) => sum + localeUrls.length, 0); const localeStats = Object.entries(sitemap.maps).map(([locale, urls]) => ({ locale, count: urls.length })); return res.json({ totalUrls, byLocale: localeStats, timestamp: new Date() }); } } }; } } } ``` -------------------------------- ### GET /sitemaps/* Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Serves per-locale sitemaps and the sitemap index. This endpoint is used when the `perLocale` option is true, providing access to individual locale sitemaps and a main index file. ```APIDOC ## GET /sitemaps/* ### Description Serves per-locale sitemaps and the sitemap index. This endpoint is used when `perLocale` is true. ### Method GET ### Endpoint /sitemaps/* ### Parameters #### Path Parameters - **`*`** (string) - Required - File path within `sitemaps/` directory, e.g., `index.xml`, `en.xml`, `es.xml`, `fr.xml` ### Response #### Success Response (200) - **Content-Type**: `text/xml` - XML sitemap or index document #### Error Responses - **404** (`text/plain`) - "not found" - returned if the requested file does not exist - **500** (`text/plain`) - "error" - returned if cache retrieval fails ### Sitemap Index (/sitemaps/index.xml) Available when `perLocale` is true. Points to individual per-locale sitemaps. **Response Format:** ```xml https://example.com/apos/sitemaps/en.xml 2025-01-15T10:30:45.123Z ``` **Index Fields:** - **`/`** (URL) - Full URL to the locale-specific sitemap file - **`/`** (ISO 8601 timestamp) - When the sitemap was generated ``` -------------------------------- ### Scheduled Sitemap Updates - Bash Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md Example of scheduling daily sitemap cache updates using a cron job. This ensures the sitemap is up-to-date for search engines. ```bash # In cron job 0 2 * * * /path/to/apos sitemap:update-cache # Update at 2 AM daily ``` -------------------------------- ### Programmatic Sitemap Generation and Cache Clearing Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md This JavaScript example demonstrates how to programmatically generate the sitemap and clear its cache using the ApostropheCMS API. This is useful for custom logic or integrations. ```javascript const sitemap = self.apos.modules['@apostrophecms/sitemap']; // Generate fresh await sitemap.map(); // Clear cache await self.apos.cache.clear('apos-sitemap'); // Both await self.apos.cache.clear('apos-sitemap'); await sitemap.map(); ``` -------------------------------- ### GET /sitemaps/* Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Retrieves specific sitemap files, typically used for paginated sitemaps or localized sitemaps. The wildcard captures the specific sitemap file requested. ```APIDOC ## GET /sitemaps/* ### Description Retrieves specific sitemap files, typically used for paginated sitemaps or localized sitemaps. The wildcard captures the specific sitemap file requested. ### Method GET ### Endpoint /sitemaps/* ### Parameters #### Path Parameters - ** *** (string) - Required - The name of the sitemap file to retrieve (e.g., 'sitemap-1.xml', 'en/sitemap.xml'). ### Response #### Success Response (200) - **sitemap file** (file) - The content of the requested sitemap file. ``` -------------------------------- ### Route Registration for Sitemaps Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Register GET routes for the main sitemap and per-locale sitemaps. These routes delegate to the `sendCache` method to serve cached sitemap files. ```javascript routes (self) { return { get: { '/sitemap.xml': async function(req, res) { return self.sendCache(res, 'sitemap.xml'); }, '/sitemaps/*': async function(req, res) { return self.sendCache(res, 'sitemaps/' + req.params[0]); } } }; } ``` -------------------------------- ### ExcludeTypes Example Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Example array of document type names to be excluded from the sitemap generation. ```javascript excludeTypes = ['draft-page', 'internal', 'author']; ``` -------------------------------- ### Configuration Options Summary Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/README.md Summary of configuration options for the sitemap module. These options allow customization of sitemap generation, caching, and content exclusion. ```APIDOC ## Configuration Options Summary | Option | Type | Default | Purpose | |---|---|---|---| | `baseUrl` | string | (required) | Site base URL for absolute links | | `cacheLifetime` | number | 3600 | Cache duration in seconds | | `piecesPerBatch` | number | 100 | Pieces per batch iteration | | `excludeTypes` | string[] | [] | Types to exclude from sitemap | | `perLocale` | boolean | false | Separate sitemaps per locale | ``` -------------------------------- ### Access Standard Sitemap via HTTP Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Demonstrates how to access the main sitemap file using curl, wget, or a JavaScript fetch request. ```bash # Get the sitemap in a browser curl https://mysite.com/sitemap.xml # Using wget wget https://mysite.com/sitemap.xml # In JavaScript fetch('https://mysite.com/sitemap.xml') .then(res => res.text()) .then(xml => console.log(xml)); ``` -------------------------------- ### Minimal Sitemap Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Configure the sitemap module with a base URL. Ensure the baseUrl is set at the app level without a trailing slash. ```javascript module.exports = { baseUrl: 'https://mysite.com', modules: { '@apostrophecms/sitemap': {} } }; ``` -------------------------------- ### LocaleMap Structure Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Example of the LocaleMap type, showing an object mapping locale codes to arrays of URL entries. ```javascript { 'en': [ { url: { loc: '/', priority: 1.0, ... } }, { url: { loc: '/about', priority: 0.9, ... } } ], 'es': [ { url: { loc: '/es/', priority: 1.0, ... } }, { url: { loc: '/es/about', priority: 0.9, ... } } ] } ``` -------------------------------- ### Sitemap Configuration Options Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Understand the available configuration options for the sitemap module, including baseUrl, cacheLifetime, piecesPerBatch, excludeTypes, and perLocale. ```json { "baseUrl": "string", "cacheLifetime": "number", "piecesPerBatch": "number", "excludeTypes": "string[]", "perLocale": "boolean" } ``` -------------------------------- ### Accessing Sitemap Module State Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to access the sitemap module instance and its properties like baseUrl, defaultLocale, and cache settings. ```javascript const sitemap = self.apos.modules['@apostrophecms/sitemap']; sitemap.baseUrl; sitemap.defaultLocale; sitemap.cacheLifetime; sitemap.piecesPerBatch; sitemap.excludeTypes; sitemap.perLocale; sitemap.maps; // { locale: [entries] } ``` -------------------------------- ### Locale Code Examples Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Illustrates various valid locale codes used within ApostropheCMS, following ISO 639-1 standards. ```string 'en' // English 'es' // Spanish 'fr' // French 'de' // German 'zh' // Chinese ``` -------------------------------- ### Task Commands Summary Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/README.md Summary of available command-line tasks for managing the sitemap generation and cache. These commands allow for manual sitemap updates and cache clearing. ```APIDOC ## Task Commands Summary | Command | Purpose | Options | |---|---|---| | `apos sitemap:print` | Generate and print to stdout | `--exclude-types`, `--per-locale` | | `apos sitemap:update-cache` | Generate and cache | `--exclude-types`, `--per-locale` | | `apos sitemap:clear` | Clear cached sitemaps | (none) | ``` -------------------------------- ### Module Constructor Options Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Configures the sitemap module with specific options for cache lifetime, pieces per batch, excluded types, and locale handling. ```javascript modules: { '@apostrophecms/sitemap': { options: { cacheLifetime: 3600, piecesPerBatch: 100, excludeTypes: [], perLocale: false } } } ``` -------------------------------- ### Print Sitemap for Debugging Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Use this command to print the generated sitemap to the console. This is helpful for debugging and verifying included types. ```bash apos sitemap:print ``` -------------------------------- ### Sitemap CLI Commands Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Utilize CLI commands to print sitemap content to stdout, update the cache, or clear the cache. ```bash apos sitemap:print # Print to stdout ``` ```bash apos sitemap:update-cache # Cache it ``` ```bash apos sitemap:clear # Clear cache ``` -------------------------------- ### Verify Sitemap Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Log the current configuration of the sitemap module, including baseUrl, cacheLifetime, piecesPerBatch, excludeTypes, perLocale, and defaultLocale. ```javascript const config = { baseUrl: sitemap.baseUrl, cacheLifetime: sitemap.cacheLifetime, piecesPerBatch: sitemap.piecesPerBatch, excludeTypes: sitemap.excludeTypes, perLocale: sitemap.perLocale, defaultLocale: sitemap.defaultLocale }; console.log('Sitemap config:', JSON.stringify(config, null, 2)); ``` -------------------------------- ### Enable Verbose Logging for Sitemap Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Enable detailed debugging logs for the sitemap module by setting the DEBUG environment variable. ```bash DEBUG=apostrophecms:* apos sitemap:update-cache ``` -------------------------------- ### Verify Public Directory Permissions Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Check and set permissions for the public directory where sitemaps might be written. Ensure the directory exists and is writable by the application user. ```bash ls -la /path/to/apos/public chmod 755 /path/to/apos/public ``` -------------------------------- ### Configure Cache Backend Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Configure the application-level cache system to use Redis instead of the default in-memory cache for the sitemap module. ```javascript modules: { '@apostrophecms/cache': { options: { // Use Redis instead of default in-memory cache db: 0, host: 'redis-host', port: 6379 } } } ``` -------------------------------- ### SitemapOptions Interface Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Configuration options for the sitemap module, passed during initialization. Customize cache lifetime, batch size, excluded types, and locale-specific sitemaps. ```typescript interface SitemapOptions { cacheLifetime?: number, piecesPerBatch?: number, excludeTypes?: string[], perLocale?: boolean } ``` -------------------------------- ### ModuleOptions Object Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Default configuration values for the sitemap module, including its alias and default batch size. ```javascript { alias: 'sitemap', piecesPerBatch: 100 } ``` -------------------------------- ### Debug Mode Environment Variables Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md These examples show how to enable debug logging for sitemap tasks using the DEBUG environment variable. You can enable general ApostropheCMS debugging or specific module debugging. ```bash # Debug mode DEBUG=apostrophecms:* apos sitemap:update-cache # Specific module debug DEBUG=apostrophecms:sitemap apos sitemap:print # Node debugging NODE_DEBUG_NATIVE=* apos sitemap:update-cache # Production vs development NODE_ENV=production apos sitemap:update-cache ``` -------------------------------- ### Serve Per-Locale Sitemaps and Index Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Serves individual per-locale sitemaps (e.g., en.xml, es.xml) or the sitemap index file (index.xml) when perLocale is true. Cache retrieval is attempted before generation. ```xml https://example.com/apos/sitemaps/en.xml 2025-01-15T10:30:45.123Z https://example.com/apos/sitemaps/es.xml 2025-01-15T10:30:45.123Z https://example.com/apos/sitemaps/fr.xml 2025-01-15T10:30:45.123Z ``` -------------------------------- ### Locale-Specific baseUrl Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Demonstrates configuring locale-specific hostnames for sitemaps when different locales use different domains. ```javascript modules: { '@apostrophecms/i18n': { options: { defaultLocale: 'en', locales: { en: { label: 'English', prefix: '/' // baseUrl inherited from application level }, es: { label: 'Español', prefix: '/es' // baseUrl inherited from application level }, fr: { label: 'Français', hostname: 'fr.example.com' // baseUrl inherited from application level } } } }, '@apostrophecms/sitemap': { options: { perLocale: true } } } ``` -------------------------------- ### Multi-Language Sitemap Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Sets up sitemaps for multiple locales, generating separate sitemaps per language and an index file. Configures cache lifetime for multi-language sitemaps. ```javascript module.exports = { baseUrl: 'https://mysite.com', modules: { '@apostrophecms/i18n': { options: { defaultLocale: 'en', locales: { en: { label: 'English' }, es: { label: 'Español', prefix: '/es' }, fr: { label: 'Français', prefix: '/fr' } } } }, '@apostrophecms/sitemap': { options: { perLocale: true, // Separate sitemaps per locale cacheLifetime: 86400 // 24 hours } } } }; ``` -------------------------------- ### Get Request Object for Published Content Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Retrieves a request object configured for fetching published content in a specific locale. Override this to customize request behavior for proxied URLs or custom locale handling. ```javascript const sitemapModule = self.apos.modules['@apostrophecms/sitemap']; const req = sitemapModule.getReq('en'); const pages = await self.apos.page.find(req, {}).toArray(); ``` -------------------------------- ### Troubleshooting baseUrl Error Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md This snippet shows how to configure the 'baseUrl' option, which is crucial for resolving 'baseUrl' errors during sitemap generation. Ensure it's set in your configuration. ```bash # Verify baseUrl is configured # In your config or data/local.js: module.exports = { baseUrl: 'https://mysite.com' }; # Restart app and try again apos sitemap:update-cache ``` -------------------------------- ### Development Sitemap Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Configures the sitemap module for development with a short cache lifetime and smaller batch sizes for rapid testing. ```javascript modules: { '@apostrophecms/sitemap': { options: { cacheLifetime: 60, // 1 minute for rapid testing piecesPerBatch: 50 // Smaller batches for development } } } ``` -------------------------------- ### Minimal Sitemap Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Minimal configuration for the sitemap module, relying on all default settings for a single locale. ```javascript modules: { '@apostrophecms/sitemap': { // Uses all defaults } } ``` -------------------------------- ### Common Sitemap CLI Tasks Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Perform common tasks using CLI commands, such as verifying content by counting URL entries, testing exclusions, clearing and updating the cache for deployment, or finding specific URLs. ```bash apos sitemap:print | grep -c "" ``` ```bash apos sitemap:print --exclude-types draft | wc -l ``` ```bash apos sitemap:clear && apos sitemap:update-cache ``` ```bash apos sitemap:print | grep -oP '(?<=)[^<]+' ``` -------------------------------- ### Creating an ApostropheCMS Request Object Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/types.md Demonstrates how to create a request object using `getAnonReq()`, ensuring the correct locale and mode are set for sitemap queries. ```javascript self.apos.task.getAnonReq({ locale, mode: 'published' }) ``` -------------------------------- ### Access Multi-Locale Sitemaps via HTTP Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Shows how to access the sitemap index and locale-specific sitemaps when multi-language support is enabled. ```bash # Get the index curl https://mysite.com/sitemaps/index.xml # Get locale-specific sitemaps curl https://mysite.com/sitemaps/en.xml curl https://mysite.com/sitemaps/es.xml curl https://mysite.com/sitemaps/fr.xml ``` -------------------------------- ### Serve Main Sitemap XML Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/endpoints.md Serves the main sitemap file, typically used in single-locale mode. Cache is checked before generation. ```xml https://example.com/ 1.0 daily https://example.com/about 0.9 daily ``` -------------------------------- ### ApostropheCMS Sitemap Package JSON Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Displays the package.json information for the @apostrophecms/sitemap module, including its name, version, description, main file, license, and dependencies. ```json { "name": "@apostrophecms/sitemap", "version": "1.2.0", "description": "Sitemap generator for ApostropheCMS", "main": "index.js", "license": "MIT", "dependencies": { "common-tags": "^1.8.0" } } ``` -------------------------------- ### Application-Level Configuration with baseUrl Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Sets the required application-level baseUrl for the sitemap module, typically in production configuration. ```javascript // In your ApostropheCMS main config or data/local.js module.exports = { baseUrl: 'https://mycompany.com', // No trailing slash modules: { '@apostrophecms/sitemap': { options: { // ... sitemap options } } } }; ``` -------------------------------- ### Development Workflow: Print Sitemap Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md Use `apos sitemap:print` for testing sitemap generation without caching during development. It's useful for verifying exclusions and saving the output for inspection. ```bash # Test sitemap generation without caching apos sitemap:print # Verify exclusions apos sitemap:print --exclude-types draft | wc -l # Save for inspection apos sitemap:print > /tmp/sitemap.xml xmllint /tmp/sitemap.xml ``` -------------------------------- ### Print Sitemap to Stdout - Bash Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md Use this task to generate and print the sitemap to stdout without updating the cache. Useful for debugging or inspecting the sitemap content. Options can be used to exclude specific types or generate per-locale sitemaps. ```bash apos sitemap:print ``` ```bash apos sitemap:print --exclude-types draft,internal,temp ``` ```bash apos sitemap:print --per-locale ``` ```bash apos sitemap:print --per-locale --exclude-types draft,temp ``` -------------------------------- ### writeFile Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Writes content to disk or to the cache output buffer. If not caching, it resolves the path relative to `apos.rootDir/public`. Special handling for `/dev/stdout` is included. ```APIDOC ## writeFile(filename, str) ### Description Writes content to disk (when not caching) or to cache output buffer (when caching). ### Method `writeFile(filename: string, str: string): void` ### Parameters #### Filename Parameter - `filename` (string) - Yes - File path. If not caching, resolved relative to `apos.rootDir/public`. Special case: `/dev/stdout` uses `fs.writeSync()`. #### Str Parameter - `str` (string) - Yes - Content to write. ### Returns - void ### Behavior - If `updatingCache` is false: writes directly to disk. - Resolves path relative to `{apos.rootDir}/public/`. - For `/dev/stdout`: uses `fs.writeSync(1, str)` to work around macOS bug with `writeFileSync`. - If `updatingCache` is true: pushes to `self.cacheOutput` buffer. - Cache entry includes `filename`, `data`, and `createdAt` timestamp. ### Example ```javascript // Write to disk sitemapModule.writeFile('sitemap.xml', xmlContent); // Or to cache sitemapModule.writeFile('sitemap.xml', xmlContent); // buffered ``` ``` -------------------------------- ### Write Sitemap Map to File Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Routes content to the appropriate writing method based on format. It calls `writeXmlMap` for XML content. ```javascript writeMap(file: string, map: string): void const mapContent = entries.map(self.stringify).join('\n'); sitemapModule.writeMap('sitemap.xml', mapContent); ``` -------------------------------- ### Default Sitemap Module Configuration Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Shows the default values for the sitemap module configuration. Note that 'format' and 'indent' are hardcoded and not configurable. ```javascript { alias: 'sitemap', piecesPerBatch: 100, cacheLifetime: 3600, excludeTypes: [], perLocale: false, format: 'xml', // Hardcoded, not configurable indent: false, // Hardcoded } ``` -------------------------------- ### Access Sitemap Module Programmatically Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Demonstrates how to access the sitemap module within ApostropheCMS code to check configuration or trigger regeneration. ```javascript // In a method, route handler, or extension const sitemapModule = self.apos.modules['@apostrophecms/sitemap']; // Check configuration console.log('Cache lifetime:', sitemapModule.cacheLifetime); console.log('Base URL:', sitemapModule.baseUrl); console.log('Per-locale:', sitemapModule.perLocale); // Trigger regeneration await sitemapModule.map(); // Clear cache await self.apos.cache.clear('apos-sitemap'); ``` -------------------------------- ### Debugging Sitemap Generation Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/QUICK-REFERENCE.md Provides bash commands for debugging the sitemap module, including printing the sitemap, filtering output, enabling verbose logging, and checking cache headers. ```bash # Print sitemap apos sitemap:print # Print with grep apos sitemap:print | grep '' # Verbose logging DEBUG=apostrophecms:* apos sitemap:print # Check cache exists curl -I https://mysite.com/sitemap.xml ``` -------------------------------- ### Test Sitemap Generation Commands Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Use the `apos sitemap:print` command to test sitemap generation, with options to exclude types or generate per-locale output. ```bash # Print to stdout apos sitemap:print ``` ```bash # Print with excluded types apos sitemap:print --exclude-types draft,temp ``` ```bash # Per-locale output apos sitemap:print --per-locale ``` -------------------------------- ### Write XML Sitemap Map Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Wraps provided content in standard XML declaration and urlset tags, then writes it to the specified file. ```xml {map} ``` ```javascript writeXmlMap(file: string, map: string): void sitemapModule.writeXmlMap('sitemap.xml', '...\n...'); ``` -------------------------------- ### High-Performance Configuration for Large Sites Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Configure sitemap options for large sites to optimize performance. This includes increasing cache lifetime and batch sizes, and enabling per-locale files. ```javascript modules: { '@apostrophecms/sitemap': { options: { cacheLifetime: 86400, // 24 hours - less frequent regen piecesPerBatch: 500, // Larger batches for speed excludeTypes: [ 'internal', 'draft', 'temporary', 'archive' ], perLocale: true // Smaller per-locale files } } } ``` -------------------------------- ### writeSitemap() Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Main method to write all accumulated sitemaps to disk or cache. It handles both single sitemap files and per-locale sitemaps. ```APIDOC ## writeSitemap() ### Description Main method to write all accumulated sitemaps to disk or cache. This method orchestrates the writing process, determining whether to create a single sitemap file or multiple files per locale based on configuration. ### Method Signature ```javascript writeSitemap(): Promise ``` ### Returns - `null` if `updatingCache` is false (indicating the sitemap was written to disk). - A Promise from `writeToCache()` if `updatingCache` is true. ### Behavior - If `perLocale` is false: writes a single `/sitemap.xml` with all locales combined. - If `perLocale` is true: writes separate `sitemaps/[locale].xml` files and a `sitemaps/index.xml` index file. - Calls `stringfiy()` on each entry to convert it to XML. - Calls `writeMap()` or `writeFile()` to persist the output. ### Example ```javascript await sitemapModule.writeSitemap(); ``` ``` -------------------------------- ### Verify Sitemap URL Count - Bash Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md This command pipes the output of `apos sitemap:print` to `grep` to count the number of URLs in the generated sitemap. Useful for verifying content inclusion. ```bash apos sitemap:print | grep -c "" ``` -------------------------------- ### Access Sitemap Configuration at Runtime Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/configuration.md Access configured sitemap module options like 'cacheLifetime', 'piecesPerBatch', 'baseUrl', and 'defaultLocale' from within module or extension code. ```javascript // In a method or handler const sitemapModule = self.apos.modules['@apostrophecms/sitemap']; console.log(sitemapModule.cacheLifetime); // Configured cache lifetime console.log(sitemapModule.piecesPerBatch); // Configured batch size console.log(sitemapModule.baseUrl); // Application baseUrl console.log(sitemapModule.defaultLocale); // Default locale ``` -------------------------------- ### Custom output() Implementation for Sitemap Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Customize the sitemap output logic by extending the sitemap module. Ensure `self.write()` is called and valid priority is provided. ```javascript extend: '@apostrophecms/sitemap', methods(self) { return { async output(page) { // Custom logic // Could throw or return incomplete entries } }; } ``` -------------------------------- ### Output Sitemap Entry for a Document Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Generates and buffers a sitemap entry for a given document (page or piece) and its children. It calculates priority based on document level or a provided value and handles locale extraction. ```javascript const page = { _url: '/about', type: 'page', aposDocId: 'abc123', level: 1 }; await sitemapModule.output(page); ``` -------------------------------- ### Custom getReq() Implementation for Sitemap Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/errors.md Extend the sitemap module to provide a custom `getReq` implementation. Ensure all required properties for `apos.task.getAnonReq` are present to avoid errors. ```javascript extend: '@apostrophecms/sitemap', methods(self) { return { getReq(locale) { // Custom implementation return self.apos.task.getAnonReq({ locale, // Missing required properties could cause errors later }); } }; } ``` -------------------------------- ### Validate XML Sitemap - Bash Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/tasks.md Pipes the output of `apos sitemap:print` to `xmllint` for XML validation. This helps ensure the generated sitemap is well-formed. ```bash apos sitemap:print | xmllint - ``` -------------------------------- ### Print Sitemap with Exclusions via CLI Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/usage-patterns.md Prints the sitemap to standard output, excluding specified page types. Useful for testing sitemap content with specific filters. ```bash apos sitemap:print --exclude-types internal,draft ``` -------------------------------- ### cacheAndRetry(res, path) Source: https://github.com/apostrophecms/sitemap/blob/main/_autodocs/api-reference/module.md Handles cache misses by generating the sitemap and retrying the request. It calls internal methods to generate the sitemap, serve it from cache, and handles errors by logging and returning a 500 status. ```APIDOC ## cacheAndRetry(res, path) ### Description Handles cache misses by generating the sitemap and retrying the request. It calls internal methods to generate the sitemap, serve it from cache, and handles errors by logging and returning a 500 status. ### Method Asynchronous function call ### Parameters #### Path Parameters - `res` (Response) - Required - Express/ApostropheCMS response object - `path` (string) - Required - File path to serve from cache ### Returns Response object. ### Status Codes - `200` - Successfully generated and sent - `500` - Error during generation ### Behavior 1. Calls `self.map()` to generate the sitemap 2. Calls `self.sendCache()` to serve the file 3. On error, logs and returns 500 ### Example ```javascript // Called internally when cache miss occurs ``` ```