@easy-web/core 1.7.1 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -1
- package/dist/contracts/props.d.ts +4 -0
- package/dist/contracts/props.d.ts.map +1 -1
- package/dist/recipes/content-site.d.ts +75 -0
- package/dist/recipes/content-site.d.ts.map +1 -0
- package/dist/recipes/content-site.js +198 -0
- package/dist/recipes/content-site.js.map +1 -0
- package/dist/recipes/index.d.ts +1 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +1 -0
- package/dist/recipes/index.js.map +1 -1
- package/dist/recipes/shell-recipe.d.ts +8 -1
- package/dist/recipes/shell-recipe.d.ts.map +1 -1
- package/dist/recipes/shell-recipe.js +21 -16
- package/dist/recipes/shell-recipe.js.map +1 -1
- package/package.json +1 -1
- package/src/components/Card.astro +2 -2
- package/src/components/GalleryLightboxGrid.astro +1 -1
- package/src/components/Header.astro +1 -1
- package/src/components/HeaderCentered.astro +1 -1
- package/src/components/HeaderFlyout.astro +2 -2
- package/src/components/HeaderHideOnScroll.astro +1 -1
- package/src/components/PageShell.astro +1 -1
- package/src/components/SeoHead.astro +22 -4
- package/src/components/__tests__/Card.test.ts +16 -0
- package/src/contracts/props.ts +4 -0
- package/src/recipes/__tests__/content-site.test.ts +66 -0
- package/src/recipes/__tests__/shell-recipe.test.ts +3 -1
- package/src/recipes/content-site.ts +225 -0
- package/src/recipes/index.ts +1 -0
- package/src/recipes/shell-recipe.ts +29 -17
- package/src/seo/__tests__/__snapshots__/legacy-baseline.test.ts.snap +1 -1
- package/src/seo/__tests__/legacy-baseline.test.ts +2 -1
- package/src/seo/__tests__/og-locales.test.ts +55 -0
- package/src/type-tests/card-props.ts +10 -0
|
@@ -110,7 +110,7 @@ const dropdownIdPrefix = `${navId}-dropdown`;
|
|
|
110
110
|
.ew-header-flyout {
|
|
111
111
|
position: sticky;
|
|
112
112
|
top: 0;
|
|
113
|
-
z-index:
|
|
113
|
+
z-index: var(--ew-z-sticky, 1100);
|
|
114
114
|
background: var(--ew-surface);
|
|
115
115
|
border-bottom: 1px solid var(--ew-border);
|
|
116
116
|
}
|
|
@@ -217,7 +217,7 @@ const dropdownIdPrefix = `${navId}-dropdown`;
|
|
|
217
217
|
padding: var(--ew-space-2);
|
|
218
218
|
list-style: none;
|
|
219
219
|
margin: 0;
|
|
220
|
-
z-index:
|
|
220
|
+
z-index: var(--ew-z-dropdown, 1000);
|
|
221
221
|
}
|
|
222
222
|
.ew-header-flyout__dropdown[data-open] {
|
|
223
223
|
display: block;
|
|
@@ -66,7 +66,7 @@ const logoImage = !logo ? undefined : typeof logo === 'string' ? { src: logo, al
|
|
|
66
66
|
top: 0;
|
|
67
67
|
left: 0;
|
|
68
68
|
right: 0;
|
|
69
|
-
z-index:
|
|
69
|
+
z-index: var(--ew-z-sticky, 1100);
|
|
70
70
|
transition: transform 0.3s ease;
|
|
71
71
|
background: var(--ew-surface);
|
|
72
72
|
border-bottom: 1px solid var(--ew-border);
|
|
@@ -56,7 +56,7 @@ const { mainId = 'main-content', skipLabel = labels.skipToMainContent, class: cl
|
|
|
56
56
|
position: absolute;
|
|
57
57
|
left: -9999px;
|
|
58
58
|
top: 0;
|
|
59
|
-
z-index:
|
|
59
|
+
z-index: var(--ew-z-overlay, 1200);
|
|
60
60
|
padding: var(--ew-space-2) var(--ew-space-4);
|
|
61
61
|
background: var(--ew-surface);
|
|
62
62
|
color: var(--ew-on-surface);
|
|
@@ -77,9 +77,27 @@ const shouldNoIndex = (noIndex ?? policyNoIndex) || isNotFoundRoute;
|
|
|
77
77
|
|
|
78
78
|
const canonical = new URL(servedPath, site).href;
|
|
79
79
|
const absoluteOgImage = ogImage ? new URL(ogImage, site).href : undefined;
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
const
|
|
80
|
+
function toOgLocale(value: string): string {
|
|
81
|
+
const [language, ...subtags] = value.replaceAll('_', '-').split('-');
|
|
82
|
+
const normalizedLanguage = language.toLowerCase();
|
|
83
|
+
// Preserve the historical defaults for unqualified German and English.
|
|
84
|
+
if (subtags.length === 0) {
|
|
85
|
+
return normalizedLanguage === 'en' ? 'en_US' : normalizedLanguage === 'de' ? 'de_DE' : normalizedLanguage;
|
|
86
|
+
}
|
|
87
|
+
return [normalizedLanguage, ...subtags.map((subtag) =>
|
|
88
|
+
subtag.length === 4
|
|
89
|
+
? subtag[0].toUpperCase() + subtag.slice(1).toLowerCase()
|
|
90
|
+
: subtag.toUpperCase()
|
|
91
|
+
)].join('_');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const ogLocale = toOgLocale(locale);
|
|
95
|
+
const ogLocaleAlternates = [...new Set(
|
|
96
|
+
alternates
|
|
97
|
+
.filter(({ hreflang }) => hreflang.toLowerCase() !== 'x-default')
|
|
98
|
+
.map(({ hreflang }) => toOgLocale(hreflang))
|
|
99
|
+
.filter((alternate) => alternate !== ogLocale)
|
|
100
|
+
)];
|
|
83
101
|
---
|
|
84
102
|
<title>{title}</title>
|
|
85
103
|
{description && <meta name="description" content={description} />}
|
|
@@ -93,7 +111,7 @@ const ogLocaleAlternate = locale === 'en' ? 'de_DE' : 'en_US';
|
|
|
93
111
|
<meta property="og:url" content={canonical} />
|
|
94
112
|
<meta property="og:type" content={ogType} />
|
|
95
113
|
<meta property="og:locale" content={ogLocale} />
|
|
96
|
-
<meta property="og:locale:alternate" content={
|
|
114
|
+
{ogLocaleAlternates.map((alternate) => <meta property="og:locale:alternate" content={alternate} />)}
|
|
97
115
|
<meta property="og:site_name" content={siteName} />
|
|
98
116
|
{absoluteOgImage && <meta property="og:image" content={absoluteOgImage} />}
|
|
99
117
|
<!-- Twitter Cards -->
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
2
|
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
|
|
3
3
|
import type { ImageMetadata } from 'astro';
|
|
4
|
+
import type { CardProps } from '../../contracts/index.js';
|
|
4
5
|
import BlogPostCard from '../BlogPostCard.astro';
|
|
5
6
|
import Card from '../Card.astro';
|
|
6
7
|
import CardGrid from '../CardGrid.astro';
|
|
@@ -36,6 +37,21 @@ const imgTag = (html: string) => html.match(/<img\b[^>]*>/)?.[0] ?? '';
|
|
|
36
37
|
const scopeOf = (tag: string) => tag.match(/data-astro-cid-[a-z0-9]+/)?.[0];
|
|
37
38
|
|
|
38
39
|
describe('<Card item>', () => {
|
|
40
|
+
it.each(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const)('renders a typed %s title on both prop paths', async (headingLevel) => {
|
|
41
|
+
const variants: CardProps[] = [
|
|
42
|
+
{ item: { title: 'Gallery', href: '/gallery/' }, headingLevel },
|
|
43
|
+
{ title: 'Gallery', headingLevel },
|
|
44
|
+
];
|
|
45
|
+
for (const props of variants) {
|
|
46
|
+
const html = await render(Card, props);
|
|
47
|
+
expect(html).toContain(`<${headingLevel} class="ew-card__title">Gallery</${headingLevel}>`);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('defaults the legacy title to h3', async () => {
|
|
52
|
+
expect(await render(Card, { title: 'Gallery' })).toContain('<h3 class="ew-card__title">Gallery</h3>');
|
|
53
|
+
});
|
|
54
|
+
|
|
39
55
|
it('renders a local image through Media with srcset and the given sizes, and links the card', async () => {
|
|
40
56
|
const html = await render(Card, {
|
|
41
57
|
item: {
|
package/src/contracts/props.ts
CHANGED
|
@@ -23,6 +23,8 @@ export type GalleryItem = Image & {
|
|
|
23
23
|
*/
|
|
24
24
|
export interface ItemCardProps {
|
|
25
25
|
item: Item & Partial<Linkable>;
|
|
26
|
+
/** Title heading tag. Defaults to `h3`; use `h2` directly below a page heading. */
|
|
27
|
+
headingLevel?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
|
26
28
|
/**
|
|
27
29
|
* `sizes` attribute of the responsive image. Only `ImageMetadata` sources
|
|
28
30
|
* get a `srcset`; a string source renders a plain `<img>` and ignores it.
|
|
@@ -38,6 +40,8 @@ export interface ItemCardProps {
|
|
|
38
40
|
|
|
39
41
|
/** `Card` rendered from individual props, exactly as before the content contracts. */
|
|
40
42
|
export interface LegacyCardProps {
|
|
43
|
+
/** Title heading tag, with the same `h3` default as the item API. */
|
|
44
|
+
headingLevel?: ItemCardProps['headingLevel'];
|
|
41
45
|
/** @deprecated Pass `item`; `item.title` is rendered. */
|
|
42
46
|
title: string;
|
|
43
47
|
/** @deprecated Pass `item`; `item.description` is rendered. */
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createContentSiteRecipes, generatedContentCompositionSchema } from '../content-site.js';
|
|
3
|
+
import { resolveCapabilityGraph } from '../graph.js';
|
|
4
|
+
import { shellRecipe } from '../shell-recipe.js';
|
|
5
|
+
|
|
6
|
+
const type = {
|
|
7
|
+
id: 'entries', primary: true, labels: { en: 'Entries' }, routes: { en: '/entries/' },
|
|
8
|
+
traits: ['title', 'slug', 'summary', 'image', 'body'],
|
|
9
|
+
bindings: ['list', 'detail', 'navigation'],
|
|
10
|
+
};
|
|
11
|
+
const composition = { contentLocales: ['en'], contentTypes: [type] };
|
|
12
|
+
|
|
13
|
+
describe('content site recipes', () => {
|
|
14
|
+
it('resolves content roles, rendering bindings and routes with shell navigation', async () => {
|
|
15
|
+
const recipes = createContentSiteRecipes(composition);
|
|
16
|
+
const graph = resolveCapabilityGraph([recipes.content, recipes.shell]);
|
|
17
|
+
expect(graph.ok).toBe(true);
|
|
18
|
+
if (!graph.ok) throw new Error(JSON.stringify(graph.error));
|
|
19
|
+
expect(graph.value.contentTypes.primary?.id).toBe('content.type.entries');
|
|
20
|
+
expect(graph.value.contributions.filter(({ kind }) => kind === 'binding')).toHaveLength(3);
|
|
21
|
+
expect(graph.value.fixedPages.map(({ target }) => target)).toEqual(expect.arrayContaining(['/entries/', '/entries/[slug]']));
|
|
22
|
+
const shell = await recipes.shell.generate({ options: shellRecipe.optionsSchema.parse({}), capabilities: [], contributions: [] });
|
|
23
|
+
expect(shell.files.find(({ path }) => path === 'src/layouts/Base.astro')?.content).toContain('"href":"/entries/"');
|
|
24
|
+
const content = await recipes.content.generate({ options: {}, capabilities: [], contributions: [] });
|
|
25
|
+
expect(content.files.find(({ path }) => path === 'src/content/definitions.ts')?.content).toContain('image()');
|
|
26
|
+
expect(content.files.find(({ path }) => path === 'src/lib/content/entries.ts')?.content).toContain("assertImplements<Entry['data'], HasTitle & HasSlug & HasSummary & HasImage>()");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('omits optional image/summary fields and navigation rather than inventing capabilities', async () => {
|
|
30
|
+
const recipes = createContentSiteRecipes({ ...composition, contentTypes: [{ ...type, traits: ['title', 'slug', 'body'], bindings: ['list', 'detail'] }] });
|
|
31
|
+
const content = await recipes.content.generate({ options: {}, capabilities: [], contributions: [] });
|
|
32
|
+
expect(content.files.some(({ path }) => path.endsWith('.svg'))).toBe(false);
|
|
33
|
+
expect(content.files.find(({ path }) => path === 'src/lib/content/entries.ts')?.content).not.toContain('data.summary');
|
|
34
|
+
expect(recipes.content.outputContributions.some(({ id }) => id.endsWith('.navigation'))).toBe(false);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('uses bracket access for kebab-case collection IDs and nested route imports', async () => {
|
|
38
|
+
const recipes = createContentSiteRecipes({ ...composition, contentTypes: [{ ...type, id: 'example-entry', routes: { en: '/library/entries' } }] });
|
|
39
|
+
const content = await recipes.content.generate({ options: {}, capabilities: [], contributions: [] });
|
|
40
|
+
expect(content.files.find(({ path }) => path === 'src/pages/library/entries/index.astro')?.content).toContain("../../../lib/content/example-entry");
|
|
41
|
+
expect(content.files.find(({ path }) => path === 'src/content/definitions.ts')?.content).toContain('"example-entry": defineCollection');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it.each([
|
|
45
|
+
{ traits: ['title', 'slug', 'body', 'photos'] },
|
|
46
|
+
{ traits: ['title', 'slug', 'body', 'money'], currency: 'EUR' },
|
|
47
|
+
{ bindings: ['homepage', 'list', 'detail'], traits: ['title', 'slug', 'image', 'featured', 'body'] },
|
|
48
|
+
{ bindings: ['list'] },
|
|
49
|
+
{ traits: ['title', 'slug'] },
|
|
50
|
+
{ routes: { en: '/admin/imports/' } },
|
|
51
|
+
{ routes: { en: '/404/examples/' } },
|
|
52
|
+
{ routes: { en: '/x/[slug]/' } },
|
|
53
|
+
{ routes: { en: '/x/../y/' } },
|
|
54
|
+
])('rejects unsupported composition changes %j', (change) => {
|
|
55
|
+
expect(generatedContentCompositionSchema.safeParse({ ...composition, reservedRoutes: [], contentTypes: [{ ...type, ...change }] }).success).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('rejects overlapping routes before producing recipes', () => {
|
|
59
|
+
expect(() => createContentSiteRecipes({ ...composition, contentTypes: [type, { ...type, id: 'other', primary: false, routes: { en: '/entries/example/' } }] })).toThrow('overlap');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('rejects multiple locales and empty content selections', () => {
|
|
63
|
+
expect(generatedContentCompositionSchema.safeParse({ contentLocales: ['en'], contentTypes: [] }).success).toBe(false);
|
|
64
|
+
expect(generatedContentCompositionSchema.safeParse({ contentLocales: ['en', 'de'], contentTypes: [] }).success).toBe(false);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -10,7 +10,7 @@ const CONTRIBUTION_FILE_PATH: Record<string, string> = {
|
|
|
10
10
|
'shell.home': 'src/pages/index.astro',
|
|
11
11
|
'shell.404': 'src/pages/404.astro',
|
|
12
12
|
'shell.localized-paths': 'src/lib/localized-paths.ts',
|
|
13
|
-
'shell.
|
|
13
|
+
'shell.tsconfig': 'tsconfig.json',
|
|
14
14
|
'shell.gitignore': '.gitignore',
|
|
15
15
|
};
|
|
16
16
|
|
|
@@ -38,6 +38,8 @@ describe('shell recipe', () => {
|
|
|
38
38
|
const files = buildShellFiles({ noIndex: true });
|
|
39
39
|
const config = files.find((file) => file.path === 'astro.config.mjs')!;
|
|
40
40
|
expect(config.content).toContain('noIndex: true');
|
|
41
|
+
expect(files.find((file) => file.path === 'src/layouts/Base.astro')!.content).toContain('<SeoHead');
|
|
42
|
+
expect(files.some((file) => file.path === 'public/robots.txt')).toBe(false);
|
|
41
43
|
});
|
|
42
44
|
|
|
43
45
|
it('never emits a real domain', () => {
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { z } from 'astro/zod';
|
|
2
|
+
import { posix } from 'node:path';
|
|
3
|
+
import { contentCompositionSchema, defaultReservedContentRoutes } from '../contracts/content-composition.js';
|
|
4
|
+
import type { ContentComposition, ContentTypeDefinition } from '../contracts/content-composition.js';
|
|
5
|
+
import { buildShellFiles, shellRecipe } from './shell-recipe.js';
|
|
6
|
+
import type { ShellConfiguration, ShellRecipeOptions } from './shell-recipe.js';
|
|
7
|
+
import type { RecipeGeneratedFile, RecipeMetadata } from './types.js';
|
|
8
|
+
import type { RecipeOutputContribution } from './schema.js';
|
|
9
|
+
|
|
10
|
+
const supportedTraits = new Set(['title', 'slug', 'summary', 'image', 'body']);
|
|
11
|
+
const supportedBindings = new Set(['list', 'detail', 'navigation', 'cms-admin']);
|
|
12
|
+
|
|
13
|
+
export interface ContentSiteOptions {
|
|
14
|
+
readonly mediaFolder?: string;
|
|
15
|
+
readonly shellConfiguration?: ShellConfiguration;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const generatedContentCompositionSchema = contentCompositionSchema.superRefine((composition, context) => {
|
|
19
|
+
if (composition.contentLocales.length !== 1) {
|
|
20
|
+
context.addIssue({ code: 'custom', path: ['contentLocales'], message: 'Content generation currently requires exactly one locale' });
|
|
21
|
+
}
|
|
22
|
+
if (!composition.contentTypes.length) {
|
|
23
|
+
context.addIssue({ code: 'custom', path: ['contentTypes'], message: 'Content generation requires at least one content type' });
|
|
24
|
+
}
|
|
25
|
+
const routes: string[] = [];
|
|
26
|
+
composition.contentTypes.forEach((type, index) => {
|
|
27
|
+
const path = ['contentTypes', index];
|
|
28
|
+
for (const trait of type.traits) {
|
|
29
|
+
if (!supportedTraits.has(trait)) context.addIssue({ code: 'custom', path: [...path, 'traits'], message: `Content generation does not yet support trait "${trait}"` });
|
|
30
|
+
}
|
|
31
|
+
for (const binding of type.bindings) {
|
|
32
|
+
if (!supportedBindings.has(binding)) context.addIssue({ code: 'custom', path: [...path, 'bindings'], message: `Content generation does not yet support binding "${binding}"` });
|
|
33
|
+
}
|
|
34
|
+
if (!type.bindings.includes('list') || !type.bindings.includes('detail')) {
|
|
35
|
+
context.addIssue({ code: 'custom', path: [...path, 'bindings'], message: 'Content generation requires both list and detail bindings' });
|
|
36
|
+
}
|
|
37
|
+
for (const route of Object.values(type.routes)) {
|
|
38
|
+
const base = route.replace(/\/$/, '');
|
|
39
|
+
if (!/^\/[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/.test(base)
|
|
40
|
+
|| defaultReservedContentRoutes.some((reserved) => reserved !== '/' && `${base}/`.startsWith(reserved))) {
|
|
41
|
+
context.addIssue({ code: 'custom', path: [...path, 'routes'], message: `Unsupported generated content route "${route}"; use non-reserved lowercase path segments` });
|
|
42
|
+
}
|
|
43
|
+
if (routes.some((other) => base.startsWith(`${other}/`) || other.startsWith(`${base}/`))) {
|
|
44
|
+
context.addIssue({ code: 'custom', path: [...path, 'routes'], message: `Generated list/detail routes overlap at "${route}"` });
|
|
45
|
+
}
|
|
46
|
+
routes.push(base);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
function routeBase(type: ContentTypeDefinition, locale: string): string {
|
|
52
|
+
return type.routes[locale]!.replace(/\/$/, '');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function collectionSchema(type: ContentTypeDefinition): string {
|
|
56
|
+
const shapes = ['...titleTraitSchema.unwrap().shape', '...slugTraitSchema.unwrap().shape'];
|
|
57
|
+
if (type.traits.includes('summary')) shapes.push('...summaryTraitSchema.unwrap().shape');
|
|
58
|
+
if (type.traits.includes('image')) {
|
|
59
|
+
shapes.push('image: imageTraitSchema.unwrap().shape.image.unwrap().extend({ src: image() })');
|
|
60
|
+
}
|
|
61
|
+
// File-based IDs keep duplicate public slugs visible to route validation.
|
|
62
|
+
return `${JSON.stringify(type.id)}: defineCollection({
|
|
63
|
+
loader: glob({ pattern: '**/*.md', base: ${JSON.stringify(`./src/content/${type.id}`)}, generateId: ({ entry }) => entry.replace(/\\.md$/, '') }),
|
|
64
|
+
schema: ${type.traits.includes('image') ? '({ image }) => ' : ''}z.object({ ${shapes.join(', ')} }).strict(),
|
|
65
|
+
})`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function adapterSource(type: ContentTypeDefinition, locale: string, index: number): string {
|
|
69
|
+
const contracts = ['HasTitle', 'HasSlug', ...(type.traits.includes('summary') ? ['HasSummary'] : []), ...(type.traits.includes('image') ? ['HasImage'] : [])];
|
|
70
|
+
return `import type { CollectionEntry } from 'astro:content';
|
|
71
|
+
import { assertImplements, type Item, type Linkable, ${contracts.map((name) => `type ${name}`).join(', ')} } from '@easy-web/core/contracts';
|
|
72
|
+
import { composition } from '../../content/definitions';
|
|
73
|
+
|
|
74
|
+
type Entry = CollectionEntry<${JSON.stringify(type.id)}>;
|
|
75
|
+
assertImplements<Entry['data'], ${contracts.join(' & ')}>();
|
|
76
|
+
|
|
77
|
+
export function toItem(entry: Entry): Item & Linkable {
|
|
78
|
+
const data = entry.data;
|
|
79
|
+
return {
|
|
80
|
+
title: data.title,
|
|
81
|
+
${type.traits.includes('summary') ? 'description: data.summary,' : ''}
|
|
82
|
+
${type.traits.includes('image') ? 'image: data.image,' : ''}
|
|
83
|
+
href: composition.contentTypes[${index}].routes[${JSON.stringify(locale)}].replace(/\\/$/, '') + '/' + data.slug + '/',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function listSource(type: ContentTypeDefinition, locale: string): string {
|
|
90
|
+
const prefix = '../'.repeat(routeBase(type, locale).split('/').length);
|
|
91
|
+
return `---
|
|
92
|
+
import { getCollection } from 'astro:content';
|
|
93
|
+
import Base from '${prefix}layouts/Base.astro';
|
|
94
|
+
import { toItem } from '${prefix}lib/content/${type.id}';
|
|
95
|
+
import Card from '@easy-web/core/components/Card.astro';
|
|
96
|
+
import CardGrid from '@easy-web/core/components/CardGrid.astro';
|
|
97
|
+
|
|
98
|
+
const items = (await getCollection(${JSON.stringify(type.id)}))
|
|
99
|
+
.map(toItem).sort((left, right) => left.href < right.href ? -1 : left.href > right.href ? 1 : 0);
|
|
100
|
+
---
|
|
101
|
+
<Base title={${JSON.stringify(type.labels[locale])}}>
|
|
102
|
+
<h1>{${JSON.stringify(type.labels[locale])}}</h1>
|
|
103
|
+
<CardGrid>
|
|
104
|
+
{items.map((item) => <Card item={item} />)}
|
|
105
|
+
</CardGrid>
|
|
106
|
+
</Base>
|
|
107
|
+
`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function detailSource(type: ContentTypeDefinition, locale: string): string {
|
|
111
|
+
const prefix = '../'.repeat(routeBase(type, locale).split('/').length);
|
|
112
|
+
return `---
|
|
113
|
+
import { getCollection, render, type CollectionEntry } from 'astro:content';
|
|
114
|
+
import type { Rendered, Item, Linkable } from '@easy-web/core/contracts';
|
|
115
|
+
import Base from '${prefix}layouts/Base.astro';
|
|
116
|
+
import { toItem } from '${prefix}lib/content/${type.id}';
|
|
117
|
+
import Prose from '@easy-web/core/components/Prose.astro';
|
|
118
|
+
${type.traits.includes('image') ? "import Media from '@easy-web/core/components/Media.astro';" : ''}
|
|
119
|
+
|
|
120
|
+
export async function getStaticPaths() {
|
|
121
|
+
const entries = await getCollection(${JSON.stringify(type.id)});
|
|
122
|
+
const seen = new Set<string>();
|
|
123
|
+
return entries.map((entry) => {
|
|
124
|
+
if (seen.has(entry.data.slug)) throw new Error('Duplicate content slug: ' + entry.data.slug);
|
|
125
|
+
seen.add(entry.data.slug);
|
|
126
|
+
return { params: { slug: entry.data.slug }, props: { entry } };
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface Props { entry: CollectionEntry<${JSON.stringify(type.id)}> }
|
|
131
|
+
const { entry } = Astro.props;
|
|
132
|
+
const rendered: Rendered<Item & Linkable> = { ...toItem(entry), ...(await render(entry)) };
|
|
133
|
+
const { Content } = rendered;
|
|
134
|
+
---
|
|
135
|
+
<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)}' : ''}>
|
|
136
|
+
<Prose>
|
|
137
|
+
<h1>{rendered.title}</h1>
|
|
138
|
+
{rendered.description && <p>{rendered.description}</p>}
|
|
139
|
+
${type.traits.includes('image') ? '{rendered.image && <Media image={rendered.image} />}' : ''}
|
|
140
|
+
<Content />
|
|
141
|
+
</Prose>
|
|
142
|
+
</Base>
|
|
143
|
+
`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function contentFiles(composition: ContentComposition, options: ContentSiteOptions): readonly RecipeGeneratedFile[] {
|
|
147
|
+
const locale = composition.contentLocales[0]!;
|
|
148
|
+
const mediaFolder = z.string().regex(/^src\/assets(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/)
|
|
149
|
+
.parse(options.mediaFolder ?? 'src/assets');
|
|
150
|
+
const exampleImage = `${mediaFolder}/content-example.svg`;
|
|
151
|
+
const files: RecipeGeneratedFile[] = [
|
|
152
|
+
{ path: 'src/content/definitions.ts', content: `import { defineCollection, z } from 'astro:content';
|
|
153
|
+
import { glob } from 'astro/loaders';
|
|
154
|
+
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';
|
|
155
|
+
|
|
156
|
+
export const composition = ${JSON.stringify(composition, null, 2)} as const;
|
|
157
|
+
|
|
158
|
+
export const collections = {
|
|
159
|
+
${composition.contentTypes.map(collectionSchema).join(',\n ')},
|
|
160
|
+
};
|
|
161
|
+
` },
|
|
162
|
+
{ path: 'src/content.config.ts', content: "export { collections } from './content/definitions';\n" },
|
|
163
|
+
];
|
|
164
|
+
if (composition.contentTypes.some((type) => type.traits.includes('image'))) {
|
|
165
|
+
files.push({ path: 'package.json', content: `${JSON.stringify({ dependencies: { sharp: '^0.35.0' } }, null, 2)}\n` });
|
|
166
|
+
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' });
|
|
167
|
+
}
|
|
168
|
+
for (const [index, type] of composition.contentTypes.entries()) {
|
|
169
|
+
const data = {
|
|
170
|
+
title: `${type.labels[locale]} - ${locale === 'de' ? 'Beispiel' : 'Example'}`,
|
|
171
|
+
slug: 'example',
|
|
172
|
+
...(type.traits.includes('summary') ? { summary: locale === 'de' ? 'Generierter Beispielinhalt.' : 'Generated example content.' } : {}),
|
|
173
|
+
...(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' } } : {}),
|
|
174
|
+
};
|
|
175
|
+
const base = routeBase(type, locale).slice(1);
|
|
176
|
+
files.push(
|
|
177
|
+
{ 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` },
|
|
178
|
+
{ path: `src/lib/content/${type.id}.ts`, content: adapterSource(type, locale, index) },
|
|
179
|
+
{ path: `src/pages/${base}/index.astro`, content: listSource(type, locale) },
|
|
180
|
+
{ path: `src/pages/${base}/[slug].astro`, content: detailSource(type, locale) },
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return files;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Bind package-owned content generation to a validated composition, independently of a CMS. */
|
|
187
|
+
export function createContentSiteRecipes(rawComposition: unknown, options: ContentSiteOptions = {}): {
|
|
188
|
+
readonly shell: RecipeMetadata<ShellRecipeOptions>;
|
|
189
|
+
readonly content: RecipeMetadata;
|
|
190
|
+
} {
|
|
191
|
+
const composition = generatedContentCompositionSchema.parse(rawComposition);
|
|
192
|
+
const locale = composition.contentLocales[0]!;
|
|
193
|
+
const files = contentFiles(composition, options);
|
|
194
|
+
const contributions: RecipeOutputContribution[] = files
|
|
195
|
+
.filter(({ path }) => !path.startsWith('src/pages/'))
|
|
196
|
+
.map(({ path }, index) => ({ kind: path === 'package.json' ? 'dependency' : 'file', id: `content.file.${index}`, target: path }));
|
|
197
|
+
for (const type of composition.contentTypes) {
|
|
198
|
+
contributions.push(
|
|
199
|
+
{ kind: 'content', id: `content.type.${type.id}`, target: type.primary ? 'primary' : 'additional' },
|
|
200
|
+
{ kind: 'route', id: `content.list.${type.id}`, target: `${routeBase(type, locale)}/` },
|
|
201
|
+
{ kind: 'route', id: `content.detail.${type.id}`, target: `${routeBase(type, locale)}/[slug]` },
|
|
202
|
+
...type.bindings.map((binding) => ({ kind: 'binding' as const, id: `content.binding.${type.id}.${binding}`, target: `content.type.${type.id}` })),
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
const navigation = composition.contentTypes.filter((type) => type.bindings.includes('navigation'))
|
|
206
|
+
.map((type) => ({ label: type.labels[locale]!, href: `${routeBase(type, locale)}/` }));
|
|
207
|
+
return {
|
|
208
|
+
shell: {
|
|
209
|
+
...shellRecipe,
|
|
210
|
+
validators: [{
|
|
211
|
+
id: 'shell.content-locale', phase: 'options',
|
|
212
|
+
validate: ({ options }) => options.defaultLocale === locale ? [] : [{ code: 'CONTENT_LOCALE_MISMATCH', message: 'shell.defaultLocale must match the content composition locale' }],
|
|
213
|
+
}],
|
|
214
|
+
generate: ({ options: shellOptions }) => ({ files: buildShellFiles(shellOptions, navigation, options.shellConfiguration) }),
|
|
215
|
+
},
|
|
216
|
+
content: {
|
|
217
|
+
id: 'content.pages', version: '1.7.1', protocolVersion: 1,
|
|
218
|
+
compatibleCliRange: '^0.1.0 || ^0.2.0', compatibleRuntimeRange: '^1.7.1',
|
|
219
|
+
provides: ['content.pages', 'content.typed-definitions'], requires: ['site.shell'], conflicts: [],
|
|
220
|
+
order: { priority: 10, key: 'content' }, optionsSchema: z.strictObject({}),
|
|
221
|
+
outputContributions: contributions, validators: [],
|
|
222
|
+
generate: () => ({ files }),
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
package/src/recipes/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'astro/zod';
|
|
2
2
|
import type { RecipeMetadata } from './types.js';
|
|
3
|
+
import type { NavItem } from '../contracts/types.js';
|
|
3
4
|
|
|
4
5
|
export const SHELL_RECIPE_ID = 'site.shell';
|
|
5
6
|
|
|
@@ -13,14 +14,24 @@ export type ShellRecipeOptions = z.infer<typeof shellOptionsSchema>;
|
|
|
13
14
|
|
|
14
15
|
const PLACEHOLDER_SITE_URL = 'https://replace-with-your-domain.example';
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
/** Source expressions supplied by first-party recipes, never by CLI configuration. */
|
|
18
|
+
export interface ShellConfiguration {
|
|
19
|
+
readonly imports?: readonly string[];
|
|
20
|
+
readonly integrations?: readonly string[];
|
|
21
|
+
readonly markdownProcessor?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function astroConfig(options: ShellRecipeOptions, configuration: ShellConfiguration): string {
|
|
17
25
|
return `import { defineConfig } from 'astro/config';
|
|
18
26
|
import easyWebSeo from '@easy-web/core/seo';
|
|
27
|
+
${(configuration.imports ?? []).join('\n')}
|
|
19
28
|
|
|
20
29
|
export default defineConfig({
|
|
21
30
|
site: ${JSON.stringify(PLACEHOLDER_SITE_URL)},
|
|
31
|
+
${configuration.markdownProcessor ? `markdown: { processor: ${configuration.markdownProcessor} },` : ''}
|
|
22
32
|
integrations: [
|
|
23
33
|
easyWebSeo({ noIndex: ${options.noIndex ? 'true' : 'false'} }),
|
|
34
|
+
${(configuration.integrations ?? []).map((integration) => `${integration},`).join('\n ')}
|
|
24
35
|
],
|
|
25
36
|
});
|
|
26
37
|
`;
|
|
@@ -28,9 +39,9 @@ export default defineConfig({
|
|
|
28
39
|
|
|
29
40
|
const packageJsonFragment = `${JSON.stringify({
|
|
30
41
|
type: 'module',
|
|
31
|
-
scripts: { dev: 'astro dev', build: 'astro build', preview: 'astro preview' },
|
|
42
|
+
scripts: { dev: 'astro dev', typecheck: 'astro check', build: 'astro build', preview: 'astro preview' },
|
|
32
43
|
dependencies: { '@easy-web/core': '^1.5.0', astro: '^7.3.5' },
|
|
33
|
-
devDependencies: { typescript: '^5.5.0' },
|
|
44
|
+
devDependencies: { '@astrojs/check': '^0.9.4', typescript: '^5.5.0' },
|
|
34
45
|
}, null, 2)}\n`;
|
|
35
46
|
|
|
36
47
|
const pnpmWorkspace = `allowBuilds:
|
|
@@ -38,26 +49,31 @@ const pnpmWorkspace = `allowBuilds:
|
|
|
38
49
|
sharp: true
|
|
39
50
|
`;
|
|
40
51
|
|
|
41
|
-
function baseLayout(options: ShellRecipeOptions): string {
|
|
52
|
+
function baseLayout(options: ShellRecipeOptions, navigation: readonly NavItem[]): string {
|
|
42
53
|
return `---
|
|
43
54
|
import PageShell from '@easy-web/core/components/PageShell.astro';
|
|
44
55
|
import Header from '@easy-web/core/components/Header.astro';
|
|
45
56
|
import Footer from '@easy-web/core/components/Footer.astro';
|
|
57
|
+
import SeoHead from '@easy-web/core/components/SeoHead.astro';
|
|
58
|
+
import '@easy-web/core/styles/tokens.css';
|
|
46
59
|
|
|
47
60
|
interface Props {
|
|
48
61
|
title: string;
|
|
62
|
+
description?: string;
|
|
63
|
+
image?: string;
|
|
49
64
|
}
|
|
50
|
-
const { title } = Astro.props;
|
|
65
|
+
const { title, description, image } = Astro.props;
|
|
51
66
|
const siteName = ${JSON.stringify(options.siteName)};
|
|
52
67
|
const currentLang = ${JSON.stringify(options.defaultLocale)};
|
|
53
|
-
const navItems = [{ label: 'Home', href: '/' }];
|
|
68
|
+
const navItems = ${JSON.stringify([{ label: options.defaultLocale === 'de' ? 'Startseite' : 'Home', href: '/' }, ...navigation])};
|
|
54
69
|
---
|
|
55
70
|
<!doctype html>
|
|
56
71
|
<html lang=${JSON.stringify(options.defaultLocale)}>
|
|
57
72
|
<head>
|
|
58
73
|
<meta charset="utf-8" />
|
|
59
74
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
60
|
-
<title
|
|
75
|
+
<SeoHead title={title} description={description} ogImage={image}
|
|
76
|
+
pathname={Astro.url.pathname} locale={currentLang} siteName={siteName} />
|
|
61
77
|
</head>
|
|
62
78
|
<body>
|
|
63
79
|
<PageShell lang={currentLang}>
|
|
@@ -109,26 +125,22 @@ const localizedPaths = `import type { LocalizedPathGroup } from '@easy-web/core/
|
|
|
109
125
|
export const localizedPaths: readonly LocalizedPathGroup[] = [];
|
|
110
126
|
`;
|
|
111
127
|
|
|
112
|
-
const robotsTxt = `Disallow: /admin/
|
|
113
|
-
Sitemap: ${PLACEHOLDER_SITE_URL}/sitemap-index.xml
|
|
114
|
-
`;
|
|
115
|
-
|
|
116
128
|
const gitignore = `node_modules
|
|
117
129
|
dist
|
|
118
130
|
.astro
|
|
119
131
|
`;
|
|
120
132
|
|
|
121
|
-
export function buildShellFiles(rawOptions: unknown): readonly { path: string; content: string }[] {
|
|
133
|
+
export function buildShellFiles(rawOptions: unknown, navigation: readonly NavItem[] = [], configuration: ShellConfiguration = {}): readonly { path: string; content: string }[] {
|
|
122
134
|
const options = shellOptionsSchema.parse(rawOptions ?? {});
|
|
123
135
|
return [
|
|
124
|
-
{ path: 'astro.config.mjs', content: astroConfig(options) },
|
|
136
|
+
{ path: 'astro.config.mjs', content: astroConfig(options, configuration) },
|
|
125
137
|
{ path: 'package.json', content: packageJsonFragment },
|
|
126
138
|
{ path: 'pnpm-workspace.yaml', content: pnpmWorkspace },
|
|
127
|
-
{ path: 'src/layouts/Base.astro', content: baseLayout(options) },
|
|
139
|
+
{ path: 'src/layouts/Base.astro', content: baseLayout(options, navigation) },
|
|
128
140
|
{ path: 'src/pages/index.astro', content: homePage(options) },
|
|
129
141
|
{ path: 'src/pages/404.astro', content: notFoundPage(options) },
|
|
130
142
|
{ path: 'src/lib/localized-paths.ts', content: localizedPaths },
|
|
131
|
-
{ path: '
|
|
143
|
+
{ path: 'tsconfig.json', content: `${JSON.stringify({ extends: 'astro/tsconfigs/strict', include: ['.astro/types.d.ts', '**/*'], exclude: ['dist'] }, null, 2)}\n` },
|
|
132
144
|
{ path: '.gitignore', content: gitignore },
|
|
133
145
|
];
|
|
134
146
|
}
|
|
@@ -137,7 +149,7 @@ export const shellRecipe = {
|
|
|
137
149
|
id: SHELL_RECIPE_ID,
|
|
138
150
|
version: '1.5.0',
|
|
139
151
|
protocolVersion: 1,
|
|
140
|
-
compatibleCliRange: '^0.1.0',
|
|
152
|
+
compatibleCliRange: '^0.1.0 || ^0.2.0',
|
|
141
153
|
compatibleRuntimeRange: '^1.5.0',
|
|
142
154
|
provides: [SHELL_RECIPE_ID],
|
|
143
155
|
requires: [],
|
|
@@ -152,7 +164,7 @@ export const shellRecipe = {
|
|
|
152
164
|
{ kind: 'route', id: 'shell.home', target: '/' },
|
|
153
165
|
{ kind: 'route', id: 'shell.404', target: '/404' },
|
|
154
166
|
{ kind: 'file', id: 'shell.localized-paths', target: 'src/lib/localized-paths.ts' },
|
|
155
|
-
{ kind: '
|
|
167
|
+
{ kind: 'configuration', id: 'shell.tsconfig', target: 'tsconfig.json' },
|
|
156
168
|
{ kind: 'file', id: 'shell.gitignore', target: '.gitignore' },
|
|
157
169
|
],
|
|
158
170
|
validators: [],
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
|
2
2
|
|
|
3
|
-
exports[`SeoHead legacy rendering baseline > renders the minimal props (darts/party200 style, noIndex) 1`] = `"<title>Start</title><link rel="canonical" href="https://example.com/"><meta name="robots" content="noindex, nofollow"><!-- Open Graph --><meta property="og:title" content="Start"><meta property="og:url" content="https://example.com/"><meta property="og:type" content="website"><meta property="og:locale" content="en_US"><meta property="og:
|
|
3
|
+
exports[`SeoHead legacy rendering baseline > renders the minimal props (darts/party200 style, noIndex) 1`] = `"<title>Start</title><link rel="canonical" href="https://example.com/"><meta name="robots" content="noindex, nofollow"><!-- Open Graph --><meta property="og:title" content="Start"><meta property="og:url" content="https://example.com/"><meta property="og:type" content="website"><meta property="og:locale" content="en_US"><meta property="og:site_name" content="Example Site"><!-- Twitter Cards --><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Start"><!-- hreflang alternates -->"`;
|
|
4
4
|
|
|
5
5
|
exports[`SeoHead legacy rendering baseline > renders the props the sites pass (dev.ismaili.de style) 1`] = `"<title>Kontakt</title><meta name="description" content="Get in touch"><link rel="canonical" href="https://example.com/kontakt/"><meta name="theme-color" content="#6366f1"><link rel="manifest" href="/manifest.json"><!-- Open Graph --><meta property="og:title" content="Kontakt"><meta property="og:description" content="Get in touch"><meta property="og:url" content="https://example.com/kontakt/"><meta property="og:type" content="website"><meta property="og:locale" content="de_DE"><meta property="og:locale:alternate" content="en_US"><meta property="og:site_name" content="Example Site"><!-- Twitter Cards --><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Kontakt"><meta name="twitter:description" content="Get in touch"><!-- hreflang alternates --><link rel="alternate" hreflang="de" href="https://example.com/kontakt/"><link rel="alternate" hreflang="en" href="https://example.com/en/contact/">"`;
|
|
@@ -5,7 +5,8 @@ import { normalizeHtml } from './normalize-html';
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Baseline: how today's <SeoHead> renders with today's props. A change to
|
|
8
|
-
* these snapshots
|
|
8
|
+
* these snapshots requires an intentional behavior change. The single-language
|
|
9
|
+
* baseline now omits the formerly invented OG alternate; all other tags stay fixed.
|
|
9
10
|
*/
|
|
10
11
|
const site = 'https://example.com';
|
|
11
12
|
|