@easy-web/core 1.9.1 → 1.11.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.
Files changed (53) hide show
  1. package/README.md +25 -6
  2. package/dist/contracts/capabilities.d.ts +3 -0
  3. package/dist/contracts/capabilities.d.ts.map +1 -1
  4. package/dist/contracts/content-composition.d.ts +16 -0
  5. package/dist/contracts/content-composition.d.ts.map +1 -1
  6. package/dist/contracts/content-composition.js +8 -0
  7. package/dist/contracts/content-composition.js.map +1 -1
  8. package/dist/contracts/index.d.ts +1 -0
  9. package/dist/contracts/index.d.ts.map +1 -1
  10. package/dist/contracts/index.js +1 -0
  11. package/dist/contracts/index.js.map +1 -1
  12. package/dist/contracts/ordering.d.ts +6 -0
  13. package/dist/contracts/ordering.d.ts.map +1 -0
  14. package/dist/contracts/ordering.js +22 -0
  15. package/dist/contracts/ordering.js.map +1 -0
  16. package/dist/contracts/traits.d.ts +4 -0
  17. package/dist/contracts/traits.d.ts.map +1 -1
  18. package/dist/contracts/traits.js +3 -1
  19. package/dist/contracts/traits.js.map +1 -1
  20. package/dist/recipes/content-site.d.ts +8 -0
  21. package/dist/recipes/content-site.d.ts.map +1 -1
  22. package/dist/recipes/content-site.js +226 -42
  23. package/dist/recipes/content-site.js.map +1 -1
  24. package/dist/recipes/shell-recipe.d.ts +4 -0
  25. package/dist/recipes/shell-recipe.d.ts.map +1 -1
  26. package/dist/recipes/shell-recipe.js +127 -6
  27. package/dist/recipes/shell-recipe.js.map +1 -1
  28. package/dist/seo/index.d.ts +5 -0
  29. package/dist/seo/index.d.ts.map +1 -1
  30. package/dist/seo/index.js +7 -3
  31. package/dist/seo/index.js.map +1 -1
  32. package/dist/seo/rendered-sitemap-alternates.d.ts +7 -0
  33. package/dist/seo/rendered-sitemap-alternates.d.ts.map +1 -0
  34. package/dist/seo/rendered-sitemap-alternates.js +232 -0
  35. package/dist/seo/rendered-sitemap-alternates.js.map +1 -0
  36. package/package.json +1 -1
  37. package/src/contracts/__tests__/content-composition.test.ts +17 -0
  38. package/src/contracts/__tests__/ordering.test.ts +34 -0
  39. package/src/contracts/capabilities.ts +4 -0
  40. package/src/contracts/content-composition.ts +8 -0
  41. package/src/contracts/index.ts +1 -0
  42. package/src/contracts/ordering.ts +33 -0
  43. package/src/contracts/traits.ts +4 -1
  44. package/src/recipes/__tests__/content-site.test.ts +98 -2
  45. package/src/recipes/__tests__/shell-recipe.test.ts +23 -0
  46. package/src/recipes/content-site.ts +227 -48
  47. package/src/recipes/shell-recipe.ts +132 -6
  48. package/src/seo/__tests__/integration.test.ts +28 -0
  49. package/src/seo/__tests__/rendered-sitemap-alternates.test.ts +127 -0
  50. package/src/seo/__tests__/sitemap-options.test.ts +7 -7
  51. package/src/seo/index.ts +17 -3
  52. package/src/seo/rendered-sitemap-alternates.ts +231 -0
  53. package/src/type-tests/contracts.ts +6 -0
@@ -7,9 +7,16 @@ import type { ShellConfiguration, ShellRecipeOptions } from './shell-recipe.js';
7
7
  import type { RecipeGeneratedFile, RecipeMetadata } from './types.js';
8
8
  import type { RecipeOutputContribution } from './schema.js';
9
9
 
10
- const supportedTraits = new Set(['title', 'slug', 'summary', 'image', 'body']);
10
+ const supportedTraits = new Set(['title', 'slug', 'summary', 'image', 'body', 'order']);
11
11
  const supportedBindings = new Set(['list', 'detail', 'navigation', 'cms-admin']);
12
12
  const contentRuntimeRange = '^1.6.0';
13
+ const orderedContentRuntimeRange = '^1.10.0';
14
+
15
+ function contentRuntimeFor(composition: ContentComposition): string {
16
+ if (composition.contentTypes.some((type) => type.publish)) return '^1.11.0';
17
+ return composition.contentLocales.length > 1 || composition.contentTypes.some((type) => type.traits.includes('order'))
18
+ ? orderedContentRuntimeRange : contentRuntimeRange;
19
+ }
13
20
 
14
21
  export interface ContentSiteOptions {
15
22
  readonly mediaFolder?: string;
@@ -17,13 +24,16 @@ export interface ContentSiteOptions {
17
24
  }
18
25
 
19
26
  export const generatedContentCompositionSchema = contentCompositionSchema.superRefine((composition, context) => {
20
- if (composition.contentLocales.length !== 1) {
21
- context.addIssue({ code: 'custom', path: ['contentLocales'], message: 'Content generation currently requires exactly one locale' });
27
+ const locales = composition.contentLocales;
28
+ const localeIds: readonly string[] = locales;
29
+ if (locales.length > 1 && (locales.length !== 2 || !localeIds.includes('de') || !localeIds.includes('en'))) {
30
+ context.addIssue({ code: 'custom', path: ['contentLocales'], message: 'Content generation supports one locale or the bilingual DE/EN pair' });
22
31
  }
23
32
  if (!composition.contentTypes.length) {
24
33
  context.addIssue({ code: 'custom', path: ['contentTypes'], message: 'Content generation requires at least one content type' });
25
34
  }
26
35
  const routes: string[] = [];
36
+ const localeRoots = new Set(locales.slice(1).map((locale) => `/${locale}`));
27
37
  composition.contentTypes.forEach((type, index) => {
28
38
  const path = ['contentTypes', index];
29
39
  for (const trait of type.traits) {
@@ -41,7 +51,10 @@ export const generatedContentCompositionSchema = contentCompositionSchema.superR
41
51
  || defaultReservedContentRoutes.some((reserved) => reserved !== '/' && `${base}/`.startsWith(reserved))) {
42
52
  context.addIssue({ code: 'custom', path: [...path, 'routes'], message: `Unsupported generated content route "${route}"; use non-reserved lowercase path segments` });
43
53
  }
44
- if (routes.some((other) => base.startsWith(`${other}/`) || other.startsWith(`${base}/`))) {
54
+ if (localeRoots.has(base)) {
55
+ context.addIssue({ code: 'custom', path: [...path, 'routes'], message: `Generated content route "${route}" conflicts with the localized home page` });
56
+ }
57
+ if (routes.some((other) => base === other || base.startsWith(`${other}/`) || other.startsWith(`${base}/`))) {
45
58
  context.addIssue({ code: 'custom', path: [...path, 'routes'], message: `Generated list/detail routes overlap at "${route}"` });
46
59
  }
47
60
  routes.push(base);
@@ -53,12 +66,18 @@ function routeBase(type: ContentTypeDefinition, locale: string): string {
53
66
  return type.routes[locale]!.replace(/\/$/, '');
54
67
  }
55
68
 
56
- function collectionSchema(type: ContentTypeDefinition): string {
69
+ function collectionSchema(type: ContentTypeDefinition, locales: readonly string[]): string {
57
70
  const shapes = ['...titleTraitSchema.unwrap().shape', '...slugTraitSchema.unwrap().shape'];
58
71
  if (type.traits.includes('summary')) shapes.push('...summaryTraitSchema.unwrap().shape');
59
72
  if (type.traits.includes('image')) {
60
73
  shapes.push('image: imageTraitSchema.unwrap().shape.image.unwrap().extend({ src: image() })');
61
74
  }
75
+ if (locales.length > 1) {
76
+ shapes.push(`locale: z.enum(${JSON.stringify(locales)})`);
77
+ shapes.push("translationKey: z.string().min(1).regex(/\\S/, 'Darf nicht nur aus Leerzeichen bestehen.')");
78
+ }
79
+ if (type.traits.includes('order')) shapes.push('...optionalOrderTraitSchema.unwrap().shape');
80
+ if (type.publish) shapes.push("publishDate: z.preprocess((value) => value === '' || value === null ? undefined : value, z.union([z.date(), z.string()]).pipe(z.coerce.date()).optional())");
62
81
  // File-based IDs keep duplicate public slugs visible to route validation.
63
82
  return `${JSON.stringify(type.id)}: defineCollection({
64
83
  loader: glob({ pattern: '**/*.md', base: ${JSON.stringify(`./src/content/${type.id}`)}, generateId: ({ entry }) => entry.replace(/\\.md$/, '') }),
@@ -66,40 +85,94 @@ function collectionSchema(type: ContentTypeDefinition): string {
66
85
  })`;
67
86
  }
68
87
 
69
- function adapterSource(type: ContentTypeDefinition, locale: string, index: number): string {
70
- const contracts = ['HasTitle', 'HasSlug', ...(type.traits.includes('summary') ? ['HasSummary'] : []), ...(type.traits.includes('image') ? ['HasImage'] : [])];
88
+ function adapterSource(type: ContentTypeDefinition, index: number, locales: readonly string[]): string {
89
+ const contracts = [
90
+ 'HasTitle',
91
+ 'HasSlug',
92
+ ...(type.traits.includes('summary') ? ['HasSummary'] : []),
93
+ ...(type.traits.includes('image') ? ['HasImage'] : []),
94
+ ...(type.traits.includes('order') ? ['HasOptionalOrder'] : []),
95
+ ];
96
+ const localeType = locales.map((locale) => JSON.stringify(locale)).join(' | ');
97
+ const defaultLocale = locales[0]!;
98
+ const localized = locales.length > 1;
71
99
  return `import type { CollectionEntry } from 'astro:content';
72
100
  import { assertImplements, type Item, type Linkable, ${contracts.map((name) => `type ${name}`).join(', ')} } from '@easy-web/core/contracts';
73
101
  import { composition } from '../../content/definitions';
74
102
 
75
103
  type Entry = CollectionEntry<${JSON.stringify(type.id)}>;
76
104
  assertImplements<Entry['data'], ${contracts.join(' & ')}>();
77
-
78
- export function toItem(entry: Entry): Item & Linkable {
105
+ ${localized ? `type ContentLocale = ${localeType};\n` : ''}
106
+ export function toItem(entry: Entry${localized ? `, locale: ContentLocale = ${JSON.stringify(defaultLocale)}, basePath = import.meta.env.BASE_URL.replace(/\\/$/, '')` : ''}): Item & Linkable {
79
107
  const data = entry.data;
80
108
  return {
81
109
  title: data.title,
82
110
  ${type.traits.includes('summary') ? 'description: data.summary,' : ''}
83
111
  ${type.traits.includes('image') ? 'image: data.image,' : ''}
84
- href: composition.contentTypes[${index}].routes[${JSON.stringify(locale)}].replace(/\\/$/, '') + '/' + data.slug + '/',
112
+ href: ${localized ? `basePath + ` : `import.meta.env.BASE_URL.replace(/\\/$/, '') + `}composition.contentTypes[${index}].routes[${localized ? 'locale' : JSON.stringify(defaultLocale)}].replace(/\\/$/, '') + '/' + data.slug + '/',
85
113
  };
86
114
  }
87
115
  `;
88
116
  }
89
117
 
90
- function listSource(type: ContentTypeDefinition, locale: string): string {
118
+ function listSource(type: ContentTypeDefinition, locale: string, composition: ContentComposition): string {
91
119
  const prefix = '../'.repeat(routeBase(type, locale).split('/').length);
120
+ const localized = composition.contentLocales.length > 1;
121
+ const filters = [
122
+ ...(localized ? [`data.locale === ${JSON.stringify(locale)}`] : []),
123
+ ...(type.publish ? [`isPublished(data, ${JSON.stringify(type.publish)}, now)`] : []),
124
+ ];
125
+ const localeFilter = filters.length ? `, ({ data }) => ${filters.join(' && ')}` : '';
126
+ const localizedPaths = JSON.stringify([Object.fromEntries(composition.contentLocales.map((itemLocale) => [itemLocale, `${routeBase(type, itemLocale)}/`]))]);
127
+ const localizedBaseSetup = localized ? `
128
+ const routePath = ${JSON.stringify(`${routeBase(type, locale)}/`)};
129
+ const pagePath = Astro.url.pathname.replace(/\\/+$/, '') || '/';
130
+ const routeWithoutSlash = routePath.replace(/\\/+$/, '') || '/';
131
+ const sitePrefix = routeWithoutSlash === '/' ? (pagePath === '/' ? '' : pagePath)
132
+ : pagePath.endsWith(routeWithoutSlash) ? pagePath.slice(0, -routeWithoutSlash.length) : '';
133
+ ` : '';
134
+ const alternateSetup = localized ? `
135
+ const localizedPathGroups = ${localizedPaths};
136
+ const alternates = getAlternateLinks({
137
+ path: routePath, locales: ${JSON.stringify(composition.contentLocales)},
138
+ defaultLocale: ${JSON.stringify(composition.contentLocales[0])},
139
+ baseUrl: new URL(sitePrefix ? sitePrefix + '/' : '/', Astro.site?.toString() ?? 'https://replace-with-your-domain.example').toString(),
140
+ localizedPaths: localizedPathGroups,
141
+ trailingSlash: ambientTrailingSlash(),
142
+ });
143
+ const alternateHref = alternates.find(({ hreflang }) => hreflang !== ${JSON.stringify(locale)} && hreflang !== 'x-default')?.href;
144
+ ` : '';
145
+ const localeArgument = localized ? `, ${JSON.stringify(locale)}, sitePrefix` : '';
146
+ const itemMapping = type.traits.includes('order')
147
+ ? `.sort((left, right) => compareContentOrder(
148
+ { order: left.data.order, slug: left.data.slug, id: left.id },
149
+ { order: right.data.order, slug: right.data.slug, id: right.id },
150
+ ${JSON.stringify(locale)},
151
+ ))
152
+ ${localized ? `.map((entry) => toItem(entry${localeArgument}))` : '.map(toItem)'}`
153
+ : localized
154
+ ? `.sort((left, right) => left.data.slug < right.data.slug ? -1 : left.data.slug > right.data.slug ? 1 : left.id < right.id ? -1 : left.id > right.id ? 1 : 0)
155
+ .map((entry) => toItem(entry${localeArgument}))`
156
+ : `.map(toItem).sort((left, right) => left.href < right.href ? -1 : left.href > right.href ? 1 : 0)`;
92
157
  return `---
93
158
  import { getCollection } from 'astro:content';
94
159
  import Base from '${prefix}layouts/Base.astro';
95
160
  import { toItem } from '${prefix}lib/content/${type.id}';
161
+ ${type.traits.includes('order') ? "import { compareContentOrder } from '@easy-web/core/contracts';" : ''}
162
+ ${type.publish ? "import { isPublished } from '@easy-web/core/contracts';" : ''}
96
163
  import Card from '@easy-web/core/components/Card.astro';
97
164
  import CardGrid from '@easy-web/core/components/CardGrid.astro';
165
+ ${localized ? "import { getAlternateLinks, ambientTrailingSlash } from '@easy-web/core/i18n';" : ''}
98
166
 
99
- const items = (await getCollection(${JSON.stringify(type.id)}))
100
- .map(toItem).sort((left, right) => left.href < right.href ? -1 : left.href > right.href ? 1 : 0);
167
+ ${localizedBaseSetup}
168
+ ${type.publish ? `const buildInstant = import.meta.env.EASY_WEB_PUBLICATION_INSTANT;
169
+ if (buildInstant === undefined) throw new Error('Publication instant is not configured');
170
+ const now = buildInstant === null ? new Date() : new Date(Number(buildInstant));` : ''}
171
+ const items = (await getCollection(${JSON.stringify(type.id)}${localeFilter}))
172
+ ${itemMapping};
173
+ ${alternateSetup}
101
174
  ---
102
- <Base title={${JSON.stringify(type.labels[locale])}}>
175
+ <Base title={${JSON.stringify(type.labels[locale])}}${localized ? ` locale={${JSON.stringify(locale)}} basePath={sitePrefix} alternates={alternates} alternateHref={alternateHref}` : ''}>
103
176
  <h1>{${JSON.stringify(type.labels[locale])}}</h1>
104
177
  <CardGrid>
105
178
  {items.map((item) => <Card item={item} />)}
@@ -108,32 +181,88 @@ const items = (await getCollection(${JSON.stringify(type.id)}))
108
181
  `;
109
182
  }
110
183
 
111
- function detailSource(type: ContentTypeDefinition, locale: string): string {
184
+ function detailSource(type: ContentTypeDefinition, locale: string, composition: ContentComposition): string {
112
185
  const prefix = '../'.repeat(routeBase(type, locale).split('/').length);
186
+ const localized = composition.contentLocales.length > 1;
187
+ const currentRoute = JSON.stringify(`${routeBase(type, locale)}/`);
188
+ const alternateListRoute = localized
189
+ ? JSON.stringify(`${routeBase(type, composition.contentLocales.find((itemLocale) => itemLocale !== locale)! )}/`)
190
+ : "''";
191
+ const localizedSetup = localized ? `
192
+ const routeBases = ${JSON.stringify(Object.fromEntries(composition.contentLocales.map((itemLocale) => [
193
+ itemLocale, routeBase(type, itemLocale),
194
+ ])))};
195
+ ` : '';
196
+ const localizedMap = localized ? `
197
+ const translations = allEntries.filter((candidate) => candidate.data.translationKey === entry.data.translationKey);
198
+ const translatedLocales = new Set<string>();
199
+ for (const candidate of translations) {
200
+ if (translatedLocales.has(candidate.data.locale)) {
201
+ throw new Error('Duplicate translationKey in locale: ' + candidate.data.translationKey + ' (' + candidate.data.locale + ')');
202
+ }
203
+ translatedLocales.add(candidate.data.locale);
204
+ }
205
+ const localizedPaths = translations.length > 1
206
+ ? Object.fromEntries(translations.map((candidate) => [
207
+ candidate.data.locale, routeBases[candidate.data.locale] + '/' + candidate.data.slug + '/',
208
+ ]))
209
+ : undefined;
210
+ return { params: { slug: entry.data.slug }, props: { entry, localizedPaths } };
211
+ ` : `
212
+ return { params: { slug: entry.data.slug }, props: { entry } };
213
+ `;
214
+ const localeArgument = localized ? `, ${JSON.stringify(locale)}` : '';
113
215
  return `---
114
216
  import { getCollection, render, type CollectionEntry } from 'astro:content';
115
217
  import type { Rendered, Item, Linkable } from '@easy-web/core/contracts';
218
+ ${type.publish ? "import { isPublished } from '@easy-web/core/contracts';" : ''}
116
219
  import Base from '${prefix}layouts/Base.astro';
117
220
  import { toItem } from '${prefix}lib/content/${type.id}';
118
221
  import Prose from '@easy-web/core/components/Prose.astro';
222
+ ${localized ? "import { getAlternateLinks, ambientTrailingSlash } from '@easy-web/core/i18n';" : ''}
119
223
  ${type.traits.includes('image') ? "import Media from '@easy-web/core/components/Media.astro';" : ''}
224
+ interface Props { entry: CollectionEntry<${JSON.stringify(type.id)}>${localized ? '; localizedPaths?: Record<string, string>' : ''} }
225
+ type StaticPath = { params: { slug: string }; props: Props };
120
226
 
121
- export async function getStaticPaths() {
122
- const entries = await getCollection(${JSON.stringify(type.id)});
227
+ export async function getStaticPaths(): Promise<StaticPath[]> {
228
+ ${type.publish ? `const buildInstant = import.meta.env.EASY_WEB_PUBLICATION_INSTANT;
229
+ if (buildInstant === undefined) throw new Error('Publication instant is not configured');
230
+ const now = buildInstant === null ? new Date() : new Date(Number(buildInstant));
231
+ ` : ''}const allEntries = await getCollection(${JSON.stringify(type.id)}${type.publish ? `, ({ data }) => isPublished(data, ${JSON.stringify(type.publish)}, now)` : ''});
232
+ const entries = ${localized ? `allEntries.filter((entry) => entry.data.locale === ${JSON.stringify(locale)})` : 'allEntries'};
123
233
  const seen = new Set<string>();
234
+ ${localizedSetup}
124
235
  return entries.map((entry) => {
125
236
  if (seen.has(entry.data.slug)) throw new Error('Duplicate content slug: ' + entry.data.slug);
126
237
  seen.add(entry.data.slug);
127
- return { params: { slug: entry.data.slug }, props: { entry } };
128
- });
238
+ ${localizedMap} });
129
239
  }
130
240
 
131
- interface Props { entry: CollectionEntry<${JSON.stringify(type.id)}> }
132
- const { entry } = Astro.props;
133
- const rendered: Rendered<Item & Linkable> = { ...toItem(entry), ...(await render(entry)) };
241
+ const { entry${localized ? ', localizedPaths' : ''} } = Astro.props;
242
+ ${localized ? `
243
+ const localizedPathGroups = localizedPaths
244
+ ? [localizedPaths]
245
+ : undefined;
246
+ const routePath = ${currentRoute} + entry.data.slug + '/';
247
+ const pagePath = Astro.url.pathname.replace(/\\/+$/, '') || '/';
248
+ const routeWithoutSlash = routePath.replace(/\\/+$/, '') || '/';
249
+ const sitePrefix = routeWithoutSlash === '/' ? (pagePath === '/' ? '' : pagePath)
250
+ : pagePath.endsWith(routeWithoutSlash) ? pagePath.slice(0, -routeWithoutSlash.length) : '';
251
+ const alternates = localizedPathGroups ? getAlternateLinks({
252
+ path: routePath,
253
+ locales: ${JSON.stringify(composition.contentLocales)},
254
+ defaultLocale: ${JSON.stringify(composition.contentLocales[0])},
255
+ baseUrl: new URL(sitePrefix ? sitePrefix + '/' : '/', Astro.site?.toString() ?? 'https://replace-with-your-domain.example').toString(),
256
+ localizedPaths: localizedPathGroups,
257
+ trailingSlash: ambientTrailingSlash(),
258
+ }) : [];
259
+ const alternateHref = alternates.find(({ hreflang }) => hreflang !== ${JSON.stringify(locale)} && hreflang !== 'x-default')?.href
260
+ ?? sitePrefix + ${alternateListRoute};
261
+ ` : ''}
262
+ const rendered: Rendered<Item & Linkable> = { ...toItem(entry${localeArgument}), ...(await render(entry)) };
134
263
  const { Content } = rendered;
135
264
  ---
136
- <Base title={rendered.title} description={rendered.description}${type.traits.includes('image') ? ' image={rendered.image?.src && (typeof rendered.image.src === \'string\' ? rendered.image.src : rendered.image.src.src)}' : ''}>
265
+ <Base title={rendered.title} description={rendered.description}${localized ? ` locale={${JSON.stringify(locale)}} basePath={sitePrefix} alternates={alternates} alternateHref={alternateHref}` : ''}${type.traits.includes('image') ? ' image={rendered.image?.src && (typeof rendered.image.src === \'string\' ? rendered.image.src : rendered.image.src.src)}' : ''}>
137
266
  <Prose>
138
267
  <h1>{rendered.title}</h1>
139
268
  {rendered.description && <p>{rendered.description}</p>}
@@ -145,24 +274,26 @@ const { Content } = rendered;
145
274
  }
146
275
 
147
276
  function contentFiles(composition: ContentComposition, options: ContentSiteOptions): readonly RecipeGeneratedFile[] {
148
- const locale = composition.contentLocales[0]!;
277
+ const locales = composition.contentLocales;
278
+ const localized = locales.length > 1;
279
+ const runtimeRange = contentRuntimeFor(composition);
149
280
  const mediaFolder = z.string().regex(/^src\/assets(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/)
150
281
  .parse(options.mediaFolder ?? 'src/assets');
151
282
  const exampleImage = `${mediaFolder}/content-example.svg`;
152
283
  const files: RecipeGeneratedFile[] = [
153
284
  { path: 'src/content/definitions.ts', content: `import { defineCollection, z } from 'astro:content';
154
285
  import { glob } from 'astro/loaders';
155
- import { titleTraitSchema, slugTraitSchema${composition.contentTypes.some((type) => type.traits.includes('summary')) ? ', summaryTraitSchema' : ''}${composition.contentTypes.some((type) => type.traits.includes('image')) ? ', imageTraitSchema' : ''} } from '@easy-web/core/contracts';
286
+ import { titleTraitSchema, slugTraitSchema${composition.contentTypes.some((type) => type.traits.includes('summary')) ? ', summaryTraitSchema' : ''}${composition.contentTypes.some((type) => type.traits.includes('image')) ? ', imageTraitSchema' : ''}${composition.contentTypes.some((type) => type.traits.includes('order')) ? ', optionalOrderTraitSchema' : ''} } from '@easy-web/core/contracts';
156
287
 
157
288
  export const composition = ${JSON.stringify(composition, null, 2)} as const;
158
289
 
159
290
  export const collections = {
160
- ${composition.contentTypes.map(collectionSchema).join(',\n ')},
291
+ ${composition.contentTypes.map((type) => collectionSchema(type, locales)).join(',\n ')},
161
292
  };
162
293
  ` },
163
294
  { path: 'src/content.config.ts', content: "export { collections } from './content/definitions';\n" },
164
295
  { path: 'package.json', content: `${JSON.stringify({ dependencies: {
165
- '@easy-web/core': contentRuntimeRange,
296
+ '@easy-web/core': runtimeRange,
166
297
  ...(composition.contentTypes.some((type) => type.traits.includes('image')) ? { sharp: '^0.35.0' } : {}),
167
298
  } }, null, 2)}\n` },
168
299
  ];
@@ -170,19 +301,35 @@ export const collections = {
170
301
  files.push({ path: exampleImage, content: '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360"><rect width="640" height="360" fill="#334155"/><circle cx="320" cy="180" r="90" fill="#94a3b8"/></svg>\n' });
171
302
  }
172
303
  for (const [index, type] of composition.contentTypes.entries()) {
173
- const data = {
174
- title: `${type.labels[locale]} - ${locale === 'de' ? 'Beispiel' : 'Example'}`,
175
- slug: 'example',
176
- ...(type.traits.includes('summary') ? { summary: locale === 'de' ? 'Generierter Beispielinhalt.' : 'Generated example content.' } : {}),
177
- ...(type.traits.includes('image') ? { image: { src: posix.relative(`src/content/${type.id}`, exampleImage), alt: locale === 'de' ? 'Kreis auf dunklem Hintergrund' : 'Circle on a dark background' } } : {}),
178
- };
179
- const base = routeBase(type, locale).slice(1);
180
- files.push(
181
- { path: `src/content/${type.id}/example.md`, content: `---\n${JSON.stringify(data, null, 2)}\n---\n\n${locale === 'de' ? 'Ersetze diesen Beispielinhalt vor der Veroeffentlichung.' : 'Replace this example content before production.'}\n` },
182
- { path: `src/lib/content/${type.id}.ts`, content: adapterSource(type, locale, index) },
183
- { path: `src/pages/${base}/index.astro`, content: listSource(type, locale) },
184
- { path: `src/pages/${base}/[slug].astro`, content: detailSource(type, locale) },
185
- );
304
+ files.push({ path: `src/lib/content/${type.id}.ts`, content: adapterSource(type, index, locales) });
305
+ for (const locale of locales) {
306
+ const isGerman = locale === 'de';
307
+ const data = {
308
+ title: `${type.labels[locale]} - ${isGerman ? 'Beispiel' : 'Example'}`,
309
+ slug: 'example',
310
+ ...(localized ? { locale, translationKey: 'example' } : {}),
311
+ ...(type.traits.includes('summary') ? { summary: isGerman ? 'Generierter Beispielinhalt.' : 'Generated example content.' } : {}),
312
+ ...(type.traits.includes('image') ? {
313
+ image: {
314
+ src: posix.relative(`src/content/${type.id}${localized ? `/${locale}` : ''}`, exampleImage),
315
+ alt: isGerman ? 'Kreis auf dunklem Hintergrund' : 'Circle on a dark background',
316
+ },
317
+ } : {}),
318
+ };
319
+ const contentFolder = `src/content/${type.id}${localized ? `/${locale}` : ''}`;
320
+ const body = isGerman ? 'Ersetze diesen Beispielinhalt vor der Veroeffentlichung.' : 'Replace this example content before production.';
321
+ files.push({
322
+ path: `${contentFolder}/example.md`,
323
+ content: `---\n${JSON.stringify(data, null, 2)}\n---\n\n${body}\n`,
324
+ });
325
+ }
326
+ for (const locale of locales) {
327
+ const route = routeBase(type, locale).slice(1);
328
+ files.push(
329
+ { path: `src/pages/${route}/index.astro`, content: listSource(type, locale, composition) },
330
+ { path: `src/pages/${route}/[slug].astro`, content: detailSource(type, locale, composition) },
331
+ );
332
+ }
186
333
  }
187
334
  return files;
188
335
  }
@@ -193,7 +340,24 @@ export function createContentSiteRecipes(rawComposition: unknown, options: Conte
193
340
  readonly content: RecipeMetadata;
194
341
  } {
195
342
  const composition = generatedContentCompositionSchema.parse(rawComposition);
196
- const locale = composition.contentLocales[0]!;
343
+ const locales = composition.contentLocales;
344
+ const locale = locales[0]!;
345
+ const runtimeRange = contentRuntimeFor(composition);
346
+ const navigationByLocale = Object.fromEntries(locales.map((contentLocale) => [
347
+ contentLocale,
348
+ composition.contentTypes.filter((type) => type.bindings.includes('navigation'))
349
+ .map((type) => ({ label: type.labels[contentLocale]!, href: `${routeBase(type, contentLocale)}/` })),
350
+ ]));
351
+ const localizedPaths = locales.length > 1
352
+ ? [
353
+ Object.fromEntries(locales.map((contentLocale) => [
354
+ contentLocale, contentLocale === locale ? '/' : `/${contentLocale}/`,
355
+ ])),
356
+ ...composition.contentTypes.map((type) => Object.fromEntries(locales.map((contentLocale) => [
357
+ contentLocale, `${routeBase(type, contentLocale)}/`,
358
+ ]))),
359
+ ]
360
+ : [];
197
361
  const files = contentFiles(composition, options);
198
362
  const contributions: RecipeOutputContribution[] = files
199
363
  .filter(({ path }) => !path.startsWith('src/pages/'))
@@ -201,25 +365,40 @@ export function createContentSiteRecipes(rawComposition: unknown, options: Conte
201
365
  for (const type of composition.contentTypes) {
202
366
  contributions.push(
203
367
  { kind: 'content', id: `content.type.${type.id}`, target: type.primary ? 'primary' : 'additional' },
204
- { kind: 'route', id: `content.list.${type.id}`, target: `${routeBase(type, locale)}/` },
205
- { kind: 'route', id: `content.detail.${type.id}`, target: `${routeBase(type, locale)}/[slug]` },
368
+ ...locales.flatMap((contentLocale) => [
369
+ { kind: 'route' as const, id: `content.list.${type.id}.${contentLocale}`, target: `${routeBase(type, contentLocale)}/` },
370
+ { kind: 'route' as const, id: `content.detail.${type.id}.${contentLocale}`, target: `${routeBase(type, contentLocale)}/[slug]` },
371
+ ]),
206
372
  ...type.bindings.map((binding) => ({ kind: 'binding' as const, id: `content.binding.${type.id}.${binding}`, target: `content.type.${type.id}` })),
207
373
  );
208
374
  }
209
- const navigation = composition.contentTypes.filter((type) => type.bindings.includes('navigation'))
210
- .map((type) => ({ label: type.labels[locale]!, href: `${routeBase(type, locale)}/` }));
375
+ const shellOutputContributions = locales.length > 1
376
+ ? [
377
+ ...shellRecipe.outputContributions,
378
+ ...locales.slice(1).map((contentLocale) => ({
379
+ kind: 'route' as const, id: `shell.home.${contentLocale}`, target: `/${contentLocale}/`,
380
+ })),
381
+ ]
382
+ : shellRecipe.outputContributions;
211
383
  return {
212
384
  shell: {
213
385
  ...shellRecipe,
386
+ outputContributions: shellOutputContributions,
214
387
  validators: [{
215
388
  id: 'shell.content-locale', phase: 'options',
216
- validate: ({ options }) => options.defaultLocale === locale ? [] : [{ code: 'CONTENT_LOCALE_MISMATCH', message: 'shell.defaultLocale must match the content composition locale' }],
389
+ validate: ({ options: shellOptions }) => shellOptions.defaultLocale === locale ? [] : [{ code: 'CONTENT_LOCALE_MISMATCH', message: 'shell.defaultLocale must match the content composition locale' }],
217
390
  }],
218
- generate: ({ options: shellOptions }) => ({ files: buildShellFiles(shellOptions, navigation, options.shellConfiguration) }),
391
+ generate: ({ options: shellOptions }) => ({
392
+ files: buildShellFiles(shellOptions, navigationByLocale[locale]!, {
393
+ ...options.shellConfiguration,
394
+ ...(composition.contentTypes.some((type) => type.publish) ? { publicationGating: true } : {}),
395
+ ...(locales.length > 1 ? { contentLocales: locales, navigationByLocale, localizedPaths } : {}),
396
+ }),
397
+ }),
219
398
  },
220
399
  content: {
221
400
  id: 'content.pages', version: '1.7.1', protocolVersion: 1,
222
- compatibleCliRange: '^0.1.0 || ^0.2.0', compatibleRuntimeRange: contentRuntimeRange,
401
+ compatibleCliRange: '^0.1.0 || ^0.2.0 || ^0.3.0', compatibleRuntimeRange: runtimeRange,
223
402
  provides: ['content.pages', 'content.typed-definitions'], requires: ['site.shell'], conflicts: [],
224
403
  order: { priority: 10, key: 'content' }, optionsSchema: z.strictObject({}),
225
404
  outputContributions: contributions, validators: [],
@@ -19,9 +19,26 @@ export interface ShellConfiguration {
19
19
  readonly imports?: readonly string[];
20
20
  readonly integrations?: readonly string[];
21
21
  readonly markdownProcessor?: string;
22
+ readonly contentLocales?: readonly string[];
23
+ readonly navigationByLocale?: Readonly<Record<string, readonly NavItem[]>>;
24
+ readonly localizedPaths?: readonly Readonly<Record<string, string>>[];
25
+ readonly publicationGating?: boolean;
22
26
  }
23
27
 
24
28
  function astroConfig(options: ShellRecipeOptions, configuration: ShellConfiguration): string {
29
+ const locales = configuration.contentLocales;
30
+ const multilingual = !!locales && locales.length > 1;
31
+ const seoOptions = {
32
+ noIndex: options.noIndex,
33
+ ...(multilingual ? {
34
+ sitemapLocales: Object.fromEntries(locales!.map((locale) => [locale, locale])),
35
+ localizedPaths: configuration.localizedPaths,
36
+ synchronizeRenderedAlternates: true,
37
+ } : {}),
38
+ };
39
+ const seoConfig = multilingual
40
+ ? `easyWebSeo(${JSON.stringify(seoOptions)})`
41
+ : `easyWebSeo({ noIndex: ${options.noIndex ? 'true' : 'false'} })`;
25
42
  return `import { defineConfig } from 'astro/config';
26
43
  import easyWebSeo from '@easy-web/core/seo';
27
44
  ${(configuration.imports ?? []).join('\n')}
@@ -29,8 +46,20 @@ ${(configuration.imports ?? []).join('\n')}
29
46
  export default defineConfig({
30
47
  site: ${JSON.stringify(PLACEHOLDER_SITE_URL)},
31
48
  ${configuration.markdownProcessor ? `markdown: { processor: ${configuration.markdownProcessor} },` : ''}
49
+ ${multilingual ? `i18n: { defaultLocale: ${JSON.stringify(options.defaultLocale)}, locales: ${JSON.stringify(locales)} },` : ''}
32
50
  integrations: [
33
- easyWebSeo({ noIndex: ${options.noIndex ? 'true' : 'false'} }),
51
+ ${seoConfig},
52
+ ${configuration.publicationGating ? `{
53
+ name: 'easy-web-publication-instant',
54
+ hooks: {
55
+ 'astro:config:setup': ({ command, updateConfig }) => {
56
+ // A build-time literal is shared by all prerender bundles and workers.
57
+ updateConfig({
58
+ vite: { define: { 'import.meta.env.EASY_WEB_PUBLICATION_INSTANT': JSON.stringify(command === 'build' ? Date.now() : null) } },
59
+ });
60
+ },
61
+ },
62
+ },` : ''}
34
63
  ${(configuration.integrations ?? []).map((integration) => `${integration},`).join('\n ')}
35
64
  ],
36
65
  });
@@ -49,7 +78,67 @@ const pnpmWorkspace = `allowBuilds:
49
78
  sharp: true
50
79
  `;
51
80
 
52
- function baseLayout(options: ShellRecipeOptions, navigation: readonly NavItem[]): string {
81
+ function baseLayout(options: ShellRecipeOptions, navigation: readonly NavItem[], configuration: ShellConfiguration): string {
82
+ const locales = configuration.contentLocales;
83
+ if (locales && locales.length > 1) {
84
+ return `---
85
+ import PageShell from '@easy-web/core/components/PageShell.astro';
86
+ import Header from '@easy-web/core/components/Header.astro';
87
+ import Footer from '@easy-web/core/components/Footer.astro';
88
+ import SeoHead from '@easy-web/core/components/SeoHead.astro';
89
+ import '@easy-web/core/styles/tokens.css';
90
+
91
+ interface Props {
92
+ title: string;
93
+ description?: string;
94
+ image?: string;
95
+ locale?: string;
96
+ basePath?: string;
97
+ alternates?: { hreflang: string; href: string }[];
98
+ alternateHref?: string;
99
+ }
100
+ const { title, description, image, locale = ${JSON.stringify(options.defaultLocale)}, basePath: configuredBasePath, alternates = [], alternateHref } = Astro.props;
101
+ const siteName = ${JSON.stringify(options.siteName)};
102
+ const currentLang = locale;
103
+ const locales = ${JSON.stringify(locales)};
104
+ const navigationByLocale: Record<string, { label: string; href: string }[]> = ${JSON.stringify(configuration.navigationByLocale ?? { [options.defaultLocale]: navigation })};
105
+ const basePath = configuredBasePath ?? import.meta.env.BASE_URL.replace(/\\/$/, '');
106
+ const navItems = (navigationByLocale[currentLang] ?? []).map((item) => ({ ...item, href: basePath + item.href }));
107
+ const languageHref = alternateHref
108
+ ? new URL(alternateHref, Astro.site ?? new URL(${JSON.stringify(PLACEHOLDER_SITE_URL)})).pathname
109
+ : undefined;
110
+ ---
111
+ <!doctype html>
112
+ <html lang={currentLang}>
113
+ <head>
114
+ <meta charset="utf-8" />
115
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
116
+ <SeoHead title={title} description={description} ogImage={image}
117
+ pathname={Astro.url.pathname} locale={currentLang} siteName={siteName} alternates={alternates} />
118
+ </head>
119
+ <body>
120
+ <PageShell lang={currentLang}>
121
+ <Header
122
+ slot="header"
123
+ lang={currentLang}
124
+ siteName={siteName}
125
+ navItems={navItems}
126
+ currentLang={currentLang}
127
+ pathname={Astro.url.pathname}
128
+ brandHref={basePath + (currentLang === ${JSON.stringify(options.defaultLocale)} ? '/' : '/' + currentLang + '/')}
129
+ alternateHref={languageHref}
130
+ locales={locales}
131
+ />
132
+ <slot />
133
+ <Footer slot="footer" lang={currentLang} siteName={siteName} legalLinks={[
134
+ { label: currentLang === 'de' ? 'Impressum (Beispiel)' : 'Imprint (sample)', href: basePath + '/imprint' },
135
+ { label: currentLang === 'de' ? 'Datenschutz (Beispiel)' : 'Privacy (sample)', href: basePath + '/privacy' },
136
+ ]} />
137
+ </PageShell>
138
+ </body>
139
+ </html>
140
+ `;
141
+ }
53
142
  return `---
54
143
  import PageShell from '@easy-web/core/components/PageShell.astro';
55
144
  import Header from '@easy-web/core/components/Header.astro';
@@ -130,16 +219,53 @@ dist
130
219
  .astro
131
220
  `;
132
221
 
222
+ function localizedHomePage(options: ShellRecipeOptions, locale: string, locales: readonly string[]): string {
223
+ return `---
224
+ import Base from '${locale === options.defaultLocale ? '../layouts/Base.astro' : '../../layouts/Base.astro'}';
225
+ import { getAlternateLinks, ambientTrailingSlash } from '@easy-web/core/i18n';
226
+
227
+ const localizedPaths = [Object.fromEntries(${JSON.stringify(locales)}.map((itemLocale) => [
228
+ itemLocale, itemLocale === ${JSON.stringify(options.defaultLocale)} ? '/' : '/' + itemLocale + '/',
229
+ ]))];
230
+ const routePath = ${JSON.stringify(locale === options.defaultLocale ? '/' : `/${locale}/`)};
231
+ const pagePath = Astro.url.pathname.replace(/\\/+$/, '') || '/';
232
+ const routeWithoutSlash = routePath.replace(/\\/+$/, '') || '/';
233
+ const sitePrefix = routeWithoutSlash === '/' ? (pagePath === '/' ? '' : pagePath)
234
+ : pagePath.endsWith(routeWithoutSlash) ? pagePath.slice(0, -routeWithoutSlash.length) : '';
235
+ const alternates = getAlternateLinks({
236
+ path: routePath, locales: ${JSON.stringify(locales)},
237
+ defaultLocale: ${JSON.stringify(options.defaultLocale)},
238
+ baseUrl: new URL(sitePrefix ? sitePrefix + '/' : '/', Astro.site?.toString() ?? ${JSON.stringify(PLACEHOLDER_SITE_URL)}).toString(),
239
+ localizedPaths,
240
+ trailingSlash: ambientTrailingSlash(),
241
+ });
242
+ const alternateHref = alternates.find(({ hreflang }) => hreflang !== ${JSON.stringify(locale)} && hreflang !== 'x-default')?.href;
243
+ ---
244
+ <Base title={${JSON.stringify(options.siteName)}} locale={${JSON.stringify(locale)}} basePath={sitePrefix} alternates={alternates} alternateHref={alternateHref}>
245
+ <h1>${locale === 'de' ? 'Willkommen' : 'Welcome'}</h1>
246
+ <p>${locale === 'de' ? 'Dies ist eine generierte Platzhalter-Startseite. Ersetze diesen Inhalt vor der Veröffentlichung.' : 'This is a generated placeholder home page. Replace this content before production.'}</p>
247
+ </Base>
248
+ `;
249
+ }
250
+
133
251
  export function buildShellFiles(rawOptions: unknown, navigation: readonly NavItem[] = [], configuration: ShellConfiguration = {}): readonly { path: string; content: string }[] {
134
252
  const options = shellOptionsSchema.parse(rawOptions ?? {});
253
+ const locales = configuration.contentLocales;
254
+ const multilingual = !!locales && locales.length > 1;
135
255
  return [
136
256
  { path: 'astro.config.mjs', content: astroConfig(options, configuration) },
137
257
  { path: 'package.json', content: packageJsonFragment },
138
258
  { path: 'pnpm-workspace.yaml', content: pnpmWorkspace },
139
- { path: 'src/layouts/Base.astro', content: baseLayout(options, navigation) },
140
- { path: 'src/pages/index.astro', content: homePage(options) },
259
+ { path: 'src/layouts/Base.astro', content: baseLayout(options, navigation, configuration) },
260
+ { path: 'src/pages/index.astro', content: multilingual ? localizedHomePage(options, options.defaultLocale, locales!) : homePage(options) },
261
+ ...(multilingual ? locales!.slice(1).map((locale) => ({
262
+ path: `src/pages/${locale}/index.astro`,
263
+ content: localizedHomePage(options, locale, locales!),
264
+ })) : []),
141
265
  { path: 'src/pages/404.astro', content: notFoundPage(options) },
142
- { path: 'src/lib/localized-paths.ts', content: localizedPaths },
266
+ { path: 'src/lib/localized-paths.ts', content: multilingual
267
+ ? `import type { LocalizedPathGroup } from '@easy-web/core/i18n';\n\nexport const localizedPaths: readonly LocalizedPathGroup[] = ${JSON.stringify(configuration.localizedPaths ?? [], null, 2)};\n`
268
+ : localizedPaths },
143
269
  { path: 'tsconfig.json', content: `${JSON.stringify({ extends: 'astro/tsconfigs/strict', include: ['.astro/types.d.ts', '**/*'], exclude: ['dist'] }, null, 2)}\n` },
144
270
  { path: '.gitignore', content: gitignore },
145
271
  ];
@@ -149,7 +275,7 @@ export const shellRecipe = {
149
275
  id: SHELL_RECIPE_ID,
150
276
  version: '1.5.0',
151
277
  protocolVersion: 1,
152
- compatibleCliRange: '^0.1.0 || ^0.2.0',
278
+ compatibleCliRange: '^0.1.0 || ^0.2.0 || ^0.3.0',
153
279
  compatibleRuntimeRange: '^1.5.0',
154
280
  provides: [SHELL_RECIPE_ID],
155
281
  requires: [],
@@ -163,6 +163,34 @@ describe('easyWebSeo integration factory', () => {
163
163
  );
164
164
  });
165
165
 
166
+ it('does not install the sitemap reconciliation hook when noIndex is enabled', () => {
167
+ const integration = easyWebSeo({
168
+ noIndex: true,
169
+ synchronizeRenderedAlternates: true,
170
+ localizedPaths: [{ de: '/', en: '/en/' }],
171
+ sitemapLocales: { de: 'de', en: 'en' },
172
+ });
173
+ const mockConfig = {
174
+ site: new URL('https://example.com'),
175
+ base: '/',
176
+ trailingSlash: 'always',
177
+ build: { format: 'directory' },
178
+ i18n: { locales: ['de', 'en'], defaultLocale: 'de', routing: {} },
179
+ integrations: [],
180
+ };
181
+ const updateConfig = vi.fn();
182
+
183
+ getConfigSetupHook(integration)({
184
+ config: mockConfig,
185
+ updateConfig,
186
+ injectRoute: vi.fn(),
187
+ logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
188
+ });
189
+
190
+ expect(process.env.EASY_WEB_SEO_NO_INDEX).toBe('true');
191
+ expect(updateConfig).not.toHaveBeenCalled();
192
+ });
193
+
166
194
  it('handles Astro path-style locales (objects with .path) when falling back to language-only tags', () => {
167
195
  const integration = easyWebSeo();
168
196
  const mockConfig = {