@easy-web/core 1.3.3 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +9 -9
  3. package/src/components/Header.astro +205 -205
  4. package/src/components/HeaderCentered.astro +230 -230
  5. package/src/components/HeaderFlyout.astro +370 -370
  6. package/src/components/HeaderHideOnScroll.astro +234 -234
  7. package/src/components/LanguageSwitch.astro +82 -82
  8. package/src/components/NotFound.astro +115 -115
  9. package/src/components/PageShell.astro +82 -82
  10. package/src/components/SeoHead.astro +106 -106
  11. package/src/components/StructuredData.astro +1 -1
  12. package/src/components/ThemeToggle.astro +84 -84
  13. package/src/components/UniversalMedia.astro +106 -106
  14. package/src/components/__tests__/StructuredData.test.ts +1 -1
  15. package/src/components/__tests__/UniversalMedia.test.ts +65 -65
  16. package/src/contracts/__tests__/jsonld.test.ts +1 -1
  17. package/src/contracts/index.ts +1 -1
  18. package/src/contracts/jsonld.ts +1 -1
  19. package/src/i18n/__tests__/factory.test.ts +54 -54
  20. package/src/i18n/__tests__/localized-paths.test.ts +258 -258
  21. package/src/i18n/__tests__/routing-multi-locale.test.ts +89 -89
  22. package/src/i18n/__tests__/seo.test.ts +140 -140
  23. package/src/i18n/factory.ts +66 -66
  24. package/src/i18n/index.ts +5 -5
  25. package/src/i18n/localized-paths.ts +181 -181
  26. package/src/i18n/seo.ts +131 -131
  27. package/src/markdown/__tests__/__fixtures__/abs-src-assets.md +1 -1
  28. package/src/markdown/__tests__/__fixtures__/external-url.md +1 -1
  29. package/src/markdown/__tests__/__fixtures__/public-slash.md +1 -1
  30. package/src/markdown/__tests__/__fixtures__/rel-double-dot.md +1 -1
  31. package/src/markdown/__tests__/index.test.ts +60 -60
  32. package/src/markdown/index.ts +1 -1
  33. package/src/markdown/plugin.ts +42 -42
  34. package/src/schemas/__tests__/notFound.test.ts +32 -32
  35. package/src/schemas/notFound.ts +33 -33
  36. package/src/seo/__tests__/crawl-policy.test.ts +50 -50
  37. package/src/seo/__tests__/integration.test.ts +195 -195
  38. package/src/seo/__tests__/no-index-resolution.test.ts +53 -53
  39. package/src/seo/__tests__/robots-txt.test.ts +66 -66
  40. package/src/seo/__tests__/sitemap-options.test.ts +400 -400
  41. package/src/seo/crawl-policy.ts +36 -36
  42. package/src/seo/index.ts +254 -254
  43. package/src/seo/routes/robots-txt.ts +36 -36
@@ -1,36 +1,36 @@
1
- /**
2
- * Single source of truth for what crawlers may see.
3
- *
4
- * robots.txt and the sitemap previously decided this independently: the route
5
- * handler hardcoded `Disallow: /admin/` while the sitemap integration applied
6
- * no exclusions at all, so every instance shipped a sitemap advertising the
7
- * very path its robots.txt blocked. Both outputs now derive from this module,
8
- * which makes that class of contradiction unrepresentable.
9
- */
10
-
11
- export interface CrawlPolicy {
12
- readonly disallow: readonly string[]
13
- readonly allow: readonly string[]
14
- /** Whether this site publishes a sitemap at all — read by both robots.txt and the integration. */
15
- readonly sitemap: boolean
16
- }
17
-
18
- const PUBLIC_DISALLOW = ['/admin/'] as const
19
-
20
- export function createCrawlPolicy(noIndex: boolean): CrawlPolicy {
21
- return noIndex
22
- ? { disallow: ['/'], allow: [], sitemap: false }
23
- : { disallow: [...PUBLIC_DISALLOW], allow: ['/'], sitemap: true }
24
- }
25
-
26
- export function isDisallowedPath(pathname: string, policy: CrawlPolicy): boolean {
27
- return policy.disallow.some((rule) => {
28
- if (rule === '/') {
29
- return true
30
- }
31
-
32
- const prefix = rule.endsWith('/') ? rule : `${rule}/`
33
-
34
- return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix)
35
- })
36
- }
1
+ /**
2
+ * Single source of truth for what crawlers may see.
3
+ *
4
+ * robots.txt and the sitemap previously decided this independently: the route
5
+ * handler hardcoded `Disallow: /admin/` while the sitemap integration applied
6
+ * no exclusions at all, so every instance shipped a sitemap advertising the
7
+ * very path its robots.txt blocked. Both outputs now derive from this module,
8
+ * which makes that class of contradiction unrepresentable.
9
+ */
10
+
11
+ export interface CrawlPolicy {
12
+ readonly disallow: readonly string[]
13
+ readonly allow: readonly string[]
14
+ /** Whether this site publishes a sitemap at all — read by both robots.txt and the integration. */
15
+ readonly sitemap: boolean
16
+ }
17
+
18
+ const PUBLIC_DISALLOW = ['/admin/'] as const
19
+
20
+ export function createCrawlPolicy(noIndex: boolean): CrawlPolicy {
21
+ return noIndex
22
+ ? { disallow: ['/'], allow: [], sitemap: false }
23
+ : { disallow: [...PUBLIC_DISALLOW], allow: ['/'], sitemap: true }
24
+ }
25
+
26
+ export function isDisallowedPath(pathname: string, policy: CrawlPolicy): boolean {
27
+ return policy.disallow.some((rule) => {
28
+ if (rule === '/') {
29
+ return true
30
+ }
31
+
32
+ const prefix = rule.endsWith('/') ? rule : `${rule}/`
33
+
34
+ return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix)
35
+ })
36
+ }
package/src/seo/index.ts CHANGED
@@ -1,254 +1,254 @@
1
- import type { AstroConfig, AstroIntegration } from 'astro'
2
- import sitemap from '@astrojs/sitemap'
3
- import {
4
- normalizeLocalizedPath,
5
- toServedPath,
6
- validateLocalizedPaths,
7
- type LocalizedPathGroup,
8
- type TrailingSlash,
9
- } from '../i18n/index.js'
10
-
11
- import { createCrawlPolicy, isDisallowedPath } from './crawl-policy.js'
12
-
13
- export type { LocalizedPathGroup }
14
-
15
- export type Options = {
16
- noIndex?: boolean
17
- sitemapLocales?: Record<string, string>
18
- /**
19
- * Routes whose slug differs per locale, e.g. `{ de: '/datenschutz/', en: '/en/privacy/' }`.
20
- *
21
- * `@astrojs/sitemap` pairs translations by comparing the path left after the
22
- * locale prefix is stripped, so translated slugs never pair and their
23
- * hreflang alternates are silently omitted. Declaring the group here restores
24
- * them. Declare the same groups on `createI18n` so the page `<head>` and the
25
- * sitemap agree.
26
- *
27
- * A stale or misspelled entry fails the build rather than degrading quietly.
28
- */
29
- localizedPaths?: readonly LocalizedPathGroup[]
30
- /** Composed with the built-in crawl policy using AND semantics; cannot re-admit blocked paths. */
31
- filter?: (page: string) => boolean
32
- }
33
-
34
- type LinkItem = { lang: string; url: string }
35
- type SitemapItem = { url: string; links?: LinkItem[] } & Record<string, unknown>
36
-
37
- function localeIdsOf(config: AstroConfig): string[] {
38
- return (config.i18n?.locales ?? []).map((locale) =>
39
- typeof locale === 'string' ? locale : locale.path,
40
- )
41
- }
42
-
43
- function resolveTrailingSlash(
44
- config: AstroConfig,
45
- logger?: { warn: (msg: string) => void },
46
- ): TrailingSlash {
47
- // An explicit astro `trailingSlash` is a statement of intent about the served
48
- // URL, so it outranks the output shape. Only when it is left at 'ignore' does
49
- // `build.format` decide.
50
- if (config.trailingSlash === 'always') return 'always'
51
- if (config.trailingSlash === 'never') return 'never'
52
-
53
- if (config.build.format === 'file') return 'never'
54
- if (config.build.format === 'directory') return 'always'
55
-
56
- // 'preserve' mirrors the source tree, so some routes emit as files and others
57
- // as directories. No single form is correct for the whole site.
58
- logger?.warn(
59
- '@easy-web/seo: `build.format: "preserve"` emits a mix of file and directory routes, ' +
60
- 'so no single canonical URL form is correct. Assuming trailing slashes; ' +
61
- 'set `trailingSlash` in astro.config.mjs to state the intent explicitly.'
62
- )
63
- return 'always'
64
- }
65
-
66
- function toOutputUrl(path: string, config: AstroConfig): string {
67
- const route = toServedPath(path, resolveTrailingSlash(config))
68
-
69
- const base = new URL(
70
- config.base.endsWith('/') ? config.base : `${config.base}/`,
71
- config.site,
72
- )
73
-
74
- return new URL(route.replace(/^\/+/, ''), base).href
75
- }
76
-
77
- function pathnameOf(page: string, config: AstroConfig): string {
78
- const absolute = page.startsWith('http') ? page : new URL(page, config.site).href
79
- const basePath = normalizeLocalizedPath(config.base)
80
- const pathname = normalizeLocalizedPath(new URL(absolute).pathname)
81
-
82
- if (basePath !== '/' && (pathname === basePath || pathname.startsWith(`${basePath}/`))) {
83
- const stripped = pathname.slice(basePath.length)
84
- return stripped === '' ? '/' : stripped
85
- }
86
-
87
- return pathname
88
- }
89
-
90
- export default function easyWebSeo(options: Options = {}): AstroIntegration {
91
- return {
92
- name: '@easy-web/seo',
93
- hooks: {
94
- 'astro:config:setup': ({ config, updateConfig, injectRoute, logger }) => {
95
- if (!config.site) {
96
- logger.error(
97
- '@easy-web/seo: astro.config.mjs must set `site` (a full https:// URL). ' +
98
- 'Example: site: "https://yoursite.example"'
99
- )
100
- throw new Error('@easy-web/seo: `site` is required in astro.config.mjs')
101
- }
102
-
103
- const noIndex = options.noIndex ?? false
104
- const policy = createCrawlPolicy(noIndex)
105
-
106
- let sitemapI18n: { defaultLocale: string; locales: Record<string, string> } | undefined
107
- if (config.i18n && config.i18n.locales.length > 0) {
108
- const localeMap: Record<string, string> = options.sitemapLocales ?? {}
109
- if (!options.sitemapLocales) {
110
- // Language-only tags, never a guessed region. "uppercase the language"
111
- // only coincidentally works (de-DE, fr-FR) and invents nonexistent
112
- // regions otherwise (en-EN, ja-JA, sv-SV), which Google discards.
113
- for (const locale of config.i18n.locales) {
114
- const id = typeof locale === 'string' ? locale : locale.path
115
- localeMap[id] = id
116
- }
117
- logger.warn(
118
- '@easy-web/seo: no `sitemapLocales` provided, falling back to language-only hreflang tags (' +
119
- Object.keys(localeMap).join(', ') +
120
- '). Provide `sitemapLocales` for region-specific tags (e.g. { de: "de-DE", en: "en-US" }).'
121
- )
122
- }
123
- sitemapI18n = {
124
- defaultLocale: config.i18n.defaultLocale,
125
- locales: localeMap,
126
- }
127
- }
128
-
129
- const declaredGroups = options.localizedPaths ?? []
130
-
131
- if (declaredGroups.length > 0 && !sitemapI18n) {
132
- throw new Error(
133
- '@easy-web/seo: `localizedPaths` requires `i18n` to be configured in astro.config.mjs.'
134
- )
135
- }
136
-
137
- const localeIds = localeIdsOf(config)
138
- const problems = validateLocalizedPaths(declaredGroups, localeIds)
139
- if (problems.length > 0) {
140
- throw new Error(
141
- `@easy-web/seo: invalid \`localizedPaths\`:\n- ${problems.join('\n- ')}`
142
- )
143
- }
144
-
145
- const linksByUrl = new Map<string, LinkItem[]>()
146
- const declaredUrls = new Set<string>()
147
-
148
- for (const group of declaredGroups) {
149
- const links: LinkItem[] = localeIds
150
- .filter((locale) => group[locale] !== undefined)
151
- .map((locale) => ({
152
- lang: (sitemapI18n as { locales: Record<string, string> }).locales[locale] as string,
153
- url: toOutputUrl(group[locale] as string, config),
154
- }))
155
-
156
- for (const link of links) {
157
- linksByUrl.set(link.url, links)
158
- declaredUrls.add(link.url)
159
- }
160
- }
161
-
162
- const seenUrls = new Set<string>()
163
- const conflicts: string[] = []
164
-
165
- if (policy.sitemap) {
166
- const sitemapIntegration = sitemap({
167
- ...(sitemapI18n ? { i18n: sitemapI18n } : {}),
168
- namespaces: { xhtml: true },
169
- filter: (page: string): boolean =>
170
- !isDisallowedPath(pathnameOf(page, config), policy) &&
171
- (options.filter?.(page) ?? true),
172
- serialize: (item: SitemapItem): SitemapItem => {
173
- // Re-render every <loc> through the same helper that produces the
174
- // canonical, so the two agree byte-for-byte. @astrojs/sitemap
175
- // renders the site root as a bare origin with no path, which the
176
- // canonical never does.
177
- const url = toOutputUrl(pathnameOf(item.url, config), config)
178
- const declared = linksByUrl.get(url)
179
-
180
- if (declared) {
181
- seenUrls.add(url)
182
- // Replace, never merge: every member of a group must carry the
183
- // same complete, reciprocal set or Google rejects the cluster.
184
- return { ...item, url, links: [...declared] }
185
- }
186
-
187
- for (const link of item.links ?? []) {
188
- if (linksByUrl.has(link.url)) {
189
- conflicts.push(
190
- `${url} was auto-paired with ${link.url}, which is already claimed by a localizedPaths group.`
191
- )
192
- }
193
- }
194
-
195
- return {
196
- ...item,
197
- url,
198
- ...(item.links
199
- ? {
200
- links: item.links.map((link) => ({
201
- ...link,
202
- url: toOutputUrl(pathnameOf(link.url, config), config),
203
- })),
204
- }
205
- : {}),
206
- }
207
- },
208
- })
209
-
210
- const validatorIntegration: AstroIntegration = {
211
- name: '@easy-web/seo:localized-paths-validation',
212
- hooks: {
213
- 'astro:build:done': () => {
214
- const missing = [...declaredUrls].filter((url) => !seenUrls.has(url))
215
- const failures = [
216
- ...missing.map(
217
- (url) =>
218
- `${url} is declared in localizedPaths but no such page was built. Check for a typo or a removed route.`
219
- ),
220
- ...conflicts,
221
- ]
222
-
223
- if (failures.length > 0) {
224
- throw new Error(
225
- `@easy-web/seo: invalid \`localizedPaths\`:\n- ${failures.join('\n- ')}`
226
- )
227
- }
228
- },
229
- },
230
- }
231
-
232
- // Order matters: @astrojs/sitemap runs serialize inside its own
233
- // astro:build:done, and it swallows errors thrown from serialize, so
234
- // validation has to run in a later hook to fail the build.
235
- updateConfig({ integrations: [sitemapIntegration, validatorIntegration] })
236
- }
237
-
238
- process.env.EASY_WEB_SEO_NO_INDEX = String(noIndex)
239
- // <SeoHead> is a component and cannot read astro.config, so the style
240
- // the sitemap uses is published here for it to reuse. Both surfaces
241
- // therefore derive the canonical URL form from one resolver.
242
- process.env.EASY_WEB_SEO_TRAILING_SLASH = resolveTrailingSlash(config, logger)
243
-
244
- injectRoute({
245
- pattern: '/robots.txt',
246
- entrypoint: new URL('./routes/robots-txt.js', import.meta.url),
247
- prerender: true,
248
- })
249
- },
250
- },
251
- }
252
- }
253
-
254
- export { createCrawlPolicy, isDisallowedPath, type CrawlPolicy } from './crawl-policy.js'
1
+ import type { AstroConfig, AstroIntegration } from 'astro'
2
+ import sitemap from '@astrojs/sitemap'
3
+ import {
4
+ normalizeLocalizedPath,
5
+ toServedPath,
6
+ validateLocalizedPaths,
7
+ type LocalizedPathGroup,
8
+ type TrailingSlash,
9
+ } from '../i18n/index.js'
10
+
11
+ import { createCrawlPolicy, isDisallowedPath } from './crawl-policy.js'
12
+
13
+ export type { LocalizedPathGroup }
14
+
15
+ export type Options = {
16
+ noIndex?: boolean
17
+ sitemapLocales?: Record<string, string>
18
+ /**
19
+ * Routes whose slug differs per locale, e.g. `{ de: '/datenschutz/', en: '/en/privacy/' }`.
20
+ *
21
+ * `@astrojs/sitemap` pairs translations by comparing the path left after the
22
+ * locale prefix is stripped, so translated slugs never pair and their
23
+ * hreflang alternates are silently omitted. Declaring the group here restores
24
+ * them. Declare the same groups on `createI18n` so the page `<head>` and the
25
+ * sitemap agree.
26
+ *
27
+ * A stale or misspelled entry fails the build rather than degrading quietly.
28
+ */
29
+ localizedPaths?: readonly LocalizedPathGroup[]
30
+ /** Composed with the built-in crawl policy using AND semantics; cannot re-admit blocked paths. */
31
+ filter?: (page: string) => boolean
32
+ }
33
+
34
+ type LinkItem = { lang: string; url: string }
35
+ type SitemapItem = { url: string; links?: LinkItem[] } & Record<string, unknown>
36
+
37
+ function localeIdsOf(config: AstroConfig): string[] {
38
+ return (config.i18n?.locales ?? []).map((locale) =>
39
+ typeof locale === 'string' ? locale : locale.path,
40
+ )
41
+ }
42
+
43
+ function resolveTrailingSlash(
44
+ config: AstroConfig,
45
+ logger?: { warn: (msg: string) => void },
46
+ ): TrailingSlash {
47
+ // An explicit astro `trailingSlash` is a statement of intent about the served
48
+ // URL, so it outranks the output shape. Only when it is left at 'ignore' does
49
+ // `build.format` decide.
50
+ if (config.trailingSlash === 'always') return 'always'
51
+ if (config.trailingSlash === 'never') return 'never'
52
+
53
+ if (config.build.format === 'file') return 'never'
54
+ if (config.build.format === 'directory') return 'always'
55
+
56
+ // 'preserve' mirrors the source tree, so some routes emit as files and others
57
+ // as directories. No single form is correct for the whole site.
58
+ logger?.warn(
59
+ '@easy-web/seo: `build.format: "preserve"` emits a mix of file and directory routes, ' +
60
+ 'so no single canonical URL form is correct. Assuming trailing slashes; ' +
61
+ 'set `trailingSlash` in astro.config.mjs to state the intent explicitly.'
62
+ )
63
+ return 'always'
64
+ }
65
+
66
+ function toOutputUrl(path: string, config: AstroConfig): string {
67
+ const route = toServedPath(path, resolveTrailingSlash(config))
68
+
69
+ const base = new URL(
70
+ config.base.endsWith('/') ? config.base : `${config.base}/`,
71
+ config.site,
72
+ )
73
+
74
+ return new URL(route.replace(/^\/+/, ''), base).href
75
+ }
76
+
77
+ function pathnameOf(page: string, config: AstroConfig): string {
78
+ const absolute = page.startsWith('http') ? page : new URL(page, config.site).href
79
+ const basePath = normalizeLocalizedPath(config.base)
80
+ const pathname = normalizeLocalizedPath(new URL(absolute).pathname)
81
+
82
+ if (basePath !== '/' && (pathname === basePath || pathname.startsWith(`${basePath}/`))) {
83
+ const stripped = pathname.slice(basePath.length)
84
+ return stripped === '' ? '/' : stripped
85
+ }
86
+
87
+ return pathname
88
+ }
89
+
90
+ export default function easyWebSeo(options: Options = {}): AstroIntegration {
91
+ return {
92
+ name: '@easy-web/seo',
93
+ hooks: {
94
+ 'astro:config:setup': ({ config, updateConfig, injectRoute, logger }) => {
95
+ if (!config.site) {
96
+ logger.error(
97
+ '@easy-web/seo: astro.config.mjs must set `site` (a full https:// URL). ' +
98
+ 'Example: site: "https://yoursite.example"'
99
+ )
100
+ throw new Error('@easy-web/seo: `site` is required in astro.config.mjs')
101
+ }
102
+
103
+ const noIndex = options.noIndex ?? false
104
+ const policy = createCrawlPolicy(noIndex)
105
+
106
+ let sitemapI18n: { defaultLocale: string; locales: Record<string, string> } | undefined
107
+ if (config.i18n && config.i18n.locales.length > 0) {
108
+ const localeMap: Record<string, string> = options.sitemapLocales ?? {}
109
+ if (!options.sitemapLocales) {
110
+ // Language-only tags, never a guessed region. "uppercase the language"
111
+ // only coincidentally works (de-DE, fr-FR) and invents nonexistent
112
+ // regions otherwise (en-EN, ja-JA, sv-SV), which Google discards.
113
+ for (const locale of config.i18n.locales) {
114
+ const id = typeof locale === 'string' ? locale : locale.path
115
+ localeMap[id] = id
116
+ }
117
+ logger.warn(
118
+ '@easy-web/seo: no `sitemapLocales` provided, falling back to language-only hreflang tags (' +
119
+ Object.keys(localeMap).join(', ') +
120
+ '). Provide `sitemapLocales` for region-specific tags (e.g. { de: "de-DE", en: "en-US" }).'
121
+ )
122
+ }
123
+ sitemapI18n = {
124
+ defaultLocale: config.i18n.defaultLocale,
125
+ locales: localeMap,
126
+ }
127
+ }
128
+
129
+ const declaredGroups = options.localizedPaths ?? []
130
+
131
+ if (declaredGroups.length > 0 && !sitemapI18n) {
132
+ throw new Error(
133
+ '@easy-web/seo: `localizedPaths` requires `i18n` to be configured in astro.config.mjs.'
134
+ )
135
+ }
136
+
137
+ const localeIds = localeIdsOf(config)
138
+ const problems = validateLocalizedPaths(declaredGroups, localeIds)
139
+ if (problems.length > 0) {
140
+ throw new Error(
141
+ `@easy-web/seo: invalid \`localizedPaths\`:\n- ${problems.join('\n- ')}`
142
+ )
143
+ }
144
+
145
+ const linksByUrl = new Map<string, LinkItem[]>()
146
+ const declaredUrls = new Set<string>()
147
+
148
+ for (const group of declaredGroups) {
149
+ const links: LinkItem[] = localeIds
150
+ .filter((locale) => group[locale] !== undefined)
151
+ .map((locale) => ({
152
+ lang: (sitemapI18n as { locales: Record<string, string> }).locales[locale] as string,
153
+ url: toOutputUrl(group[locale] as string, config),
154
+ }))
155
+
156
+ for (const link of links) {
157
+ linksByUrl.set(link.url, links)
158
+ declaredUrls.add(link.url)
159
+ }
160
+ }
161
+
162
+ const seenUrls = new Set<string>()
163
+ const conflicts: string[] = []
164
+
165
+ if (policy.sitemap) {
166
+ const sitemapIntegration = sitemap({
167
+ ...(sitemapI18n ? { i18n: sitemapI18n } : {}),
168
+ namespaces: { xhtml: true },
169
+ filter: (page: string): boolean =>
170
+ !isDisallowedPath(pathnameOf(page, config), policy) &&
171
+ (options.filter?.(page) ?? true),
172
+ serialize: (item: SitemapItem): SitemapItem => {
173
+ // Re-render every <loc> through the same helper that produces the
174
+ // canonical, so the two agree byte-for-byte. @astrojs/sitemap
175
+ // renders the site root as a bare origin with no path, which the
176
+ // canonical never does.
177
+ const url = toOutputUrl(pathnameOf(item.url, config), config)
178
+ const declared = linksByUrl.get(url)
179
+
180
+ if (declared) {
181
+ seenUrls.add(url)
182
+ // Replace, never merge: every member of a group must carry the
183
+ // same complete, reciprocal set or Google rejects the cluster.
184
+ return { ...item, url, links: [...declared] }
185
+ }
186
+
187
+ for (const link of item.links ?? []) {
188
+ if (linksByUrl.has(link.url)) {
189
+ conflicts.push(
190
+ `${url} was auto-paired with ${link.url}, which is already claimed by a localizedPaths group.`
191
+ )
192
+ }
193
+ }
194
+
195
+ return {
196
+ ...item,
197
+ url,
198
+ ...(item.links
199
+ ? {
200
+ links: item.links.map((link) => ({
201
+ ...link,
202
+ url: toOutputUrl(pathnameOf(link.url, config), config),
203
+ })),
204
+ }
205
+ : {}),
206
+ }
207
+ },
208
+ })
209
+
210
+ const validatorIntegration: AstroIntegration = {
211
+ name: '@easy-web/seo:localized-paths-validation',
212
+ hooks: {
213
+ 'astro:build:done': () => {
214
+ const missing = [...declaredUrls].filter((url) => !seenUrls.has(url))
215
+ const failures = [
216
+ ...missing.map(
217
+ (url) =>
218
+ `${url} is declared in localizedPaths but no such page was built. Check for a typo or a removed route.`
219
+ ),
220
+ ...conflicts,
221
+ ]
222
+
223
+ if (failures.length > 0) {
224
+ throw new Error(
225
+ `@easy-web/seo: invalid \`localizedPaths\`:\n- ${failures.join('\n- ')}`
226
+ )
227
+ }
228
+ },
229
+ },
230
+ }
231
+
232
+ // Order matters: @astrojs/sitemap runs serialize inside its own
233
+ // astro:build:done, and it swallows errors thrown from serialize, so
234
+ // validation has to run in a later hook to fail the build.
235
+ updateConfig({ integrations: [sitemapIntegration, validatorIntegration] })
236
+ }
237
+
238
+ process.env.EASY_WEB_SEO_NO_INDEX = String(noIndex)
239
+ // <SeoHead> is a component and cannot read astro.config, so the style
240
+ // the sitemap uses is published here for it to reuse. Both surfaces
241
+ // therefore derive the canonical URL form from one resolver.
242
+ process.env.EASY_WEB_SEO_TRAILING_SLASH = resolveTrailingSlash(config, logger)
243
+
244
+ injectRoute({
245
+ pattern: '/robots.txt',
246
+ entrypoint: new URL('./routes/robots-txt.js', import.meta.url),
247
+ prerender: true,
248
+ })
249
+ },
250
+ },
251
+ }
252
+ }
253
+
254
+ export { createCrawlPolicy, isDisallowedPath, type CrawlPolicy } from './crawl-policy.js'
@@ -1,36 +1,36 @@
1
- import type { APIRoute } from 'astro'
2
-
3
- import { createCrawlPolicy, type CrawlPolicy } from '../crawl-policy.js'
4
-
5
- function render(policy: CrawlPolicy, site: URL | undefined): string {
6
- const lines = ['User-agent: *']
7
-
8
- for (const path of policy.disallow) {
9
- lines.push(`Disallow: ${path}`)
10
- }
11
- for (const path of policy.allow) {
12
- lines.push(`Allow: ${path}`)
13
- }
14
-
15
- if (policy.sitemap && site) {
16
- lines.push('')
17
- lines.push(`Sitemap: ${new URL('sitemap-index.xml', site).href}`)
18
- }
19
-
20
- return `${lines.join('\n')}\n`
21
- }
22
-
23
- export const GET: APIRoute = ({ site }) => {
24
- if (!site) {
25
- return new Response(render(createCrawlPolicy(true), undefined), {
26
- status: 500,
27
- headers: { 'Content-Type': 'text/plain; charset=utf-8' },
28
- })
29
- }
30
-
31
- const policy = createCrawlPolicy(process.env.EASY_WEB_SEO_NO_INDEX === 'true')
32
-
33
- return new Response(render(policy, site), {
34
- headers: { 'Content-Type': 'text/plain; charset=utf-8' },
35
- })
36
- }
1
+ import type { APIRoute } from 'astro'
2
+
3
+ import { createCrawlPolicy, type CrawlPolicy } from '../crawl-policy.js'
4
+
5
+ function render(policy: CrawlPolicy, site: URL | undefined): string {
6
+ const lines = ['User-agent: *']
7
+
8
+ for (const path of policy.disallow) {
9
+ lines.push(`Disallow: ${path}`)
10
+ }
11
+ for (const path of policy.allow) {
12
+ lines.push(`Allow: ${path}`)
13
+ }
14
+
15
+ if (policy.sitemap && site) {
16
+ lines.push('')
17
+ lines.push(`Sitemap: ${new URL('sitemap-index.xml', site).href}`)
18
+ }
19
+
20
+ return `${lines.join('\n')}\n`
21
+ }
22
+
23
+ export const GET: APIRoute = ({ site }) => {
24
+ if (!site) {
25
+ return new Response(render(createCrawlPolicy(true), undefined), {
26
+ status: 500,
27
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
28
+ })
29
+ }
30
+
31
+ const policy = createCrawlPolicy(process.env.EASY_WEB_SEO_NO_INDEX === 'true')
32
+
33
+ return new Response(render(policy, site), {
34
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
35
+ })
36
+ }