@easy-web/core 1.5.0 → 1.7.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 (149) hide show
  1. package/README.md +100 -2
  2. package/dist/contracts/capabilities.d.ts +38 -0
  3. package/dist/contracts/capabilities.d.ts.map +1 -1
  4. package/dist/contracts/content-composition.d.ts +144 -0
  5. package/dist/contracts/content-composition.d.ts.map +1 -0
  6. package/dist/contracts/content-composition.js +143 -0
  7. package/dist/contracts/content-composition.js.map +1 -0
  8. package/dist/contracts/index.d.ts +2 -0
  9. package/dist/contracts/index.d.ts.map +1 -1
  10. package/dist/contracts/index.js +2 -0
  11. package/dist/contracts/index.js.map +1 -1
  12. package/dist/contracts/traits.d.ts +98 -0
  13. package/dist/contracts/traits.d.ts.map +1 -0
  14. package/dist/contracts/traits.js +84 -0
  15. package/dist/contracts/traits.js.map +1 -0
  16. package/dist/demo/demo-content.d.ts +37 -0
  17. package/dist/demo/demo-content.d.ts.map +1 -0
  18. package/dist/demo/demo-content.js +171 -0
  19. package/dist/demo/demo-content.js.map +1 -0
  20. package/dist/demo/index.d.ts +3 -0
  21. package/dist/demo/index.d.ts.map +1 -0
  22. package/dist/demo/index.js +3 -0
  23. package/dist/demo/index.js.map +1 -0
  24. package/dist/demo/legal-shells.d.ts +18 -0
  25. package/dist/demo/legal-shells.d.ts.map +1 -0
  26. package/dist/demo/legal-shells.js +40 -0
  27. package/dist/demo/legal-shells.js.map +1 -0
  28. package/dist/i18n/cli-catalogs.d.ts +42 -0
  29. package/dist/i18n/cli-catalogs.d.ts.map +1 -0
  30. package/dist/i18n/cli-catalogs.js +29 -0
  31. package/dist/i18n/cli-catalogs.js.map +1 -0
  32. package/dist/i18n/create-localization.d.ts +37 -0
  33. package/dist/i18n/create-localization.d.ts.map +1 -0
  34. package/dist/i18n/create-localization.js +68 -0
  35. package/dist/i18n/create-localization.js.map +1 -0
  36. package/dist/i18n/explicit-formatters.d.ts +20 -0
  37. package/dist/i18n/explicit-formatters.d.ts.map +1 -0
  38. package/dist/i18n/explicit-formatters.js +18 -0
  39. package/dist/i18n/explicit-formatters.js.map +1 -0
  40. package/dist/i18n/index.d.ts +4 -0
  41. package/dist/i18n/index.d.ts.map +1 -1
  42. package/dist/i18n/index.js +4 -0
  43. package/dist/i18n/index.js.map +1 -1
  44. package/dist/i18n/locale-inputs.d.ts +18 -0
  45. package/dist/i18n/locale-inputs.d.ts.map +1 -0
  46. package/dist/i18n/locale-inputs.js +73 -0
  47. package/dist/i18n/locale-inputs.js.map +1 -0
  48. package/dist/index.d.ts +1 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/recipes/admission.d.ts +161 -0
  53. package/dist/recipes/admission.d.ts.map +1 -0
  54. package/dist/recipes/admission.js +85 -0
  55. package/dist/recipes/admission.js.map +1 -0
  56. package/dist/recipes/graph.d.ts +101 -0
  57. package/dist/recipes/graph.d.ts.map +1 -0
  58. package/dist/recipes/graph.js +166 -0
  59. package/dist/recipes/graph.js.map +1 -0
  60. package/dist/recipes/index.d.ts +9 -0
  61. package/dist/recipes/index.d.ts.map +1 -0
  62. package/dist/recipes/index.js +9 -0
  63. package/dist/recipes/index.js.map +1 -0
  64. package/dist/recipes/mermaid.d.ts +3 -0
  65. package/dist/recipes/mermaid.d.ts.map +1 -0
  66. package/dist/recipes/mermaid.js +79 -0
  67. package/dist/recipes/mermaid.js.map +1 -0
  68. package/dist/recipes/registry.d.ts +82 -0
  69. package/dist/recipes/registry.d.ts.map +1 -0
  70. package/dist/recipes/registry.js +40 -0
  71. package/dist/recipes/registry.js.map +1 -0
  72. package/dist/recipes/schema.d.ts +129 -0
  73. package/dist/recipes/schema.d.ts.map +1 -0
  74. package/dist/recipes/schema.js +41 -0
  75. package/dist/recipes/schema.js.map +1 -0
  76. package/dist/recipes/serialize.d.ts +20 -0
  77. package/dist/recipes/serialize.d.ts.map +1 -0
  78. package/dist/recipes/serialize.js +56 -0
  79. package/dist/recipes/serialize.js.map +1 -0
  80. package/dist/recipes/shell-recipe.d.ts +59 -0
  81. package/dist/recipes/shell-recipe.d.ts.map +1 -0
  82. package/dist/recipes/shell-recipe.js +145 -0
  83. package/dist/recipes/shell-recipe.js.map +1 -0
  84. package/dist/recipes/types.d.ts +72 -0
  85. package/dist/recipes/types.d.ts.map +1 -0
  86. package/dist/recipes/types.js +13 -0
  87. package/dist/recipes/types.js.map +1 -0
  88. package/dist/schemas/galleries.d.ts +2 -2
  89. package/dist/seo/build-info-manifest.d.ts +45 -0
  90. package/dist/seo/build-info-manifest.d.ts.map +1 -0
  91. package/dist/seo/build-info-manifest.js +39 -0
  92. package/dist/seo/build-info-manifest.js.map +1 -0
  93. package/dist/seo/build-info.d.ts +3 -0
  94. package/dist/seo/build-info.d.ts.map +1 -0
  95. package/dist/seo/build-info.js +45 -0
  96. package/dist/seo/build-info.js.map +1 -0
  97. package/dist/seo/index.d.ts +4 -0
  98. package/dist/seo/index.d.ts.map +1 -1
  99. package/dist/seo/index.js +25 -2
  100. package/dist/seo/index.js.map +1 -1
  101. package/dist/seo/routes/robots-txt.d.ts.map +1 -1
  102. package/dist/seo/routes/robots-txt.js +3 -1
  103. package/dist/seo/routes/robots-txt.js.map +1 -1
  104. package/dist/seo/routes/version-json.d.ts +4 -0
  105. package/dist/seo/routes/version-json.d.ts.map +1 -0
  106. package/dist/seo/routes/version-json.js +11 -0
  107. package/dist/seo/routes/version-json.js.map +1 -0
  108. package/package.json +17 -1
  109. package/src/components/DemoLegalShell.astro +36 -0
  110. package/src/contracts/__tests__/content-composition.test.ts +170 -0
  111. package/src/contracts/capabilities.ts +49 -0
  112. package/src/contracts/content-composition.ts +176 -0
  113. package/src/contracts/index.ts +2 -0
  114. package/src/contracts/traits.ts +107 -0
  115. package/src/demo/__tests__/demo-content.test.ts +107 -0
  116. package/src/demo/demo-content.ts +210 -0
  117. package/src/demo/index.ts +2 -0
  118. package/src/demo/legal-shells.ts +52 -0
  119. package/src/i18n/__tests__/create-localization.test.ts +138 -0
  120. package/src/i18n/__tests__/explicit-formatters.test.ts +82 -0
  121. package/src/i18n/cli-catalogs.ts +44 -0
  122. package/src/i18n/create-localization.ts +67 -0
  123. package/src/i18n/explicit-formatters.ts +36 -0
  124. package/src/i18n/index.ts +4 -0
  125. package/src/i18n/locale-inputs.ts +73 -0
  126. package/src/index.ts +1 -0
  127. package/src/recipes/__tests__/graph.test.ts +139 -0
  128. package/src/recipes/__tests__/protocol.test.ts +180 -0
  129. package/src/recipes/__tests__/serialize.test.ts +128 -0
  130. package/src/recipes/__tests__/shell-recipe.test.ts +75 -0
  131. package/src/recipes/admission.ts +77 -0
  132. package/src/recipes/graph.ts +244 -0
  133. package/src/recipes/index.ts +8 -0
  134. package/src/recipes/mermaid.ts +75 -0
  135. package/src/recipes/registry.ts +48 -0
  136. package/src/recipes/schema.ts +53 -0
  137. package/src/recipes/serialize.ts +77 -0
  138. package/src/recipes/shell-recipe.ts +162 -0
  139. package/src/recipes/types.ts +63 -0
  140. package/src/seo/__tests__/build-info-html.test.ts +19 -0
  141. package/src/seo/__tests__/build-info-integration.test.ts +107 -0
  142. package/src/seo/__tests__/build-info.test.ts +86 -0
  143. package/src/seo/__tests__/robots-txt.test.ts +8 -0
  144. package/src/seo/build-info-manifest.ts +49 -0
  145. package/src/seo/build-info.ts +44 -0
  146. package/src/seo/index.ts +28 -3
  147. package/src/seo/routes/robots-txt.ts +3 -1
  148. package/src/seo/routes/version-json.ts +13 -0
  149. package/src/seo/routes/version.astro +42 -0
@@ -0,0 +1,53 @@
1
+ import { z } from 'astro/zod';
2
+
3
+ /** Increment only for a breaking recipe protocol change, independently of package semver. */
4
+ export const RECIPE_PROTOCOL_VERSION = 1 as const;
5
+
6
+ export const recipeIdSchema = z.string().regex(/^[a-zA-Z][a-zA-Z0-9]*(?:[./:-][a-zA-Z0-9]+)*$/);
7
+ export const recipeVersionSchema = z.string().regex(
8
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/,
9
+ );
10
+ /** Semver range syntax and satisfaction are checked by the resolver's semver policy. */
11
+ export const recipeCompatibilityRangeSchema = z.string().trim().min(1);
12
+
13
+ export const recipeOutputContributionSchema = z.strictObject({
14
+ kind: z.enum(['file', 'dependency', 'route', 'content', 'binding', 'configuration']),
15
+ id: recipeIdSchema,
16
+ /** Logical destination; filesystem path safety belongs to the generation boundary. */
17
+ target: z.string().min(1),
18
+ }).readonly();
19
+
20
+ export const recipeValidatorDescriptorSchema = z.strictObject({
21
+ id: recipeIdSchema,
22
+ phase: z.enum(['options', 'output']),
23
+ }).readonly();
24
+
25
+ export const recipeMetadataFields = {
26
+ id: recipeIdSchema,
27
+ version: recipeVersionSchema,
28
+ protocolVersion: z.literal(RECIPE_PROTOCOL_VERSION),
29
+ compatibleCliRange: recipeCompatibilityRangeSchema,
30
+ compatibleRuntimeRange: recipeCompatibilityRangeSchema,
31
+ // Like HasImage/Linkable, capabilities express traits, not customer/domain identities.
32
+ provides: z.array(recipeIdSchema).min(1).readonly(),
33
+ requires: z.array(recipeIdSchema).readonly(),
34
+ conflicts: z.array(recipeIdSchema).readonly(),
35
+ /** Lower priority first, then key, then recipe id; dependencies precede consumers. */
36
+ order: z.strictObject({ priority: z.number().int(), key: recipeIdSchema }).readonly(),
37
+ outputContributions: z.array(recipeOutputContributionSchema).readonly(),
38
+ };
39
+
40
+ /** Serializable projection: executable hooks and Zod instances are deliberately excluded. */
41
+ export const recipeMetadataDescriptorSchema = z.strictObject({
42
+ ...recipeMetadataFields,
43
+ optionsSchema: z.record(z.string(), z.json()),
44
+ validators: z.array(recipeValidatorDescriptorSchema).readonly(),
45
+ generate: z.literal('direct'),
46
+ }).readonly();
47
+
48
+ export type RecipeMetadataDescriptor = z.infer<typeof recipeMetadataDescriptorSchema>;
49
+ export type RecipeOutputContribution = z.infer<typeof recipeOutputContributionSchema>;
50
+ export type RecipeValidatorDescriptor = z.infer<typeof recipeValidatorDescriptorSchema>;
51
+
52
+ /** Import from @easy-web/core/recipes/schema without evaluating the core barrel. */
53
+ export const recipeMetadataJsonSchema = z.toJSONSchema(recipeMetadataDescriptorSchema);
@@ -0,0 +1,77 @@
1
+ import type { GraphResult, ResolvedCapabilityGraph, ResolvedContributionNode } from './graph.js';
2
+
3
+ export const CAPABILITY_GRAPH_SCHEMA_VERSION = 1 as const;
4
+
5
+ export interface CapabilityGraphDocument {
6
+ readonly schemaVersion: 1;
7
+ readonly recipes: ResolvedCapabilityGraph['recipes'];
8
+ readonly capabilities: ResolvedCapabilityGraph['capabilities'];
9
+ readonly requirements: ResolvedCapabilityGraph['requirements'];
10
+ readonly contentTypes: ResolvedCapabilityGraph['contentTypes'];
11
+ readonly fixedPages: readonly ResolvedContributionNode[];
12
+ readonly bindings: readonly ResolvedContributionNode[];
13
+ readonly adaptations: ResolvedCapabilityGraph['adaptations'];
14
+ }
15
+
16
+ export type GraphSerializationError = { readonly code: 'private-value-detected'; readonly path: string };
17
+
18
+ const PRIVATE_PATTERNS: readonly RegExp[] = [
19
+ /[^\s@]+@[^\s@]+\.[^\s@]+/,
20
+ /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/,
21
+ /[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,
22
+ /[A-Za-z0-9]{40,}/,
23
+ ];
24
+
25
+ function scanForPrivateValues(value: unknown, path: string): string | undefined {
26
+ if (typeof value === 'string') {
27
+ for (const pattern of PRIVATE_PATTERNS) if (pattern.test(value)) return path;
28
+ return undefined;
29
+ }
30
+ if (Array.isArray(value)) {
31
+ for (let i = 0; i < value.length; i++) {
32
+ const hit = scanForPrivateValues(value[i], `${path}[${i}]`);
33
+ if (hit) return hit;
34
+ }
35
+ return undefined;
36
+ }
37
+ if (value && typeof value === 'object') {
38
+ for (const [key, val] of Object.entries(value)) {
39
+ const hit = scanForPrivateValues(val, path ? `${path}.${key}` : key);
40
+ if (hit) return hit;
41
+ }
42
+ }
43
+ return undefined;
44
+ }
45
+
46
+ /** Pure projection of a resolved graph into a stable, inspectable document. Excludes file/dependency/configuration contributions. */
47
+ export function toCapabilityGraphDocument(
48
+ graph: ResolvedCapabilityGraph,
49
+ ): GraphResult<CapabilityGraphDocument, GraphSerializationError> {
50
+ const isAdaptationTarget = new Set(graph.adaptations.map((adaptation) => adaptation.id));
51
+ const nonFileContributions = graph.contributions.filter(
52
+ (contribution) => contribution.kind !== 'file' && contribution.kind !== 'dependency' && contribution.kind !== 'configuration',
53
+ );
54
+ const fixedPages = nonFileContributions.filter((contribution) => contribution.kind === 'route');
55
+ const bindings = nonFileContributions.filter(
56
+ (contribution) => contribution.kind === 'binding' && !isAdaptationTarget.has(contribution.id),
57
+ );
58
+
59
+ const document: CapabilityGraphDocument = {
60
+ schemaVersion: CAPABILITY_GRAPH_SCHEMA_VERSION,
61
+ recipes: graph.recipes,
62
+ capabilities: graph.capabilities,
63
+ requirements: graph.requirements,
64
+ contentTypes: graph.contentTypes,
65
+ fixedPages,
66
+ bindings,
67
+ adaptations: graph.adaptations,
68
+ };
69
+
70
+ const hitPath = scanForPrivateValues(document, '');
71
+ if (hitPath) return { ok: false, error: { code: 'private-value-detected', path: hitPath } };
72
+ return { ok: true, value: document };
73
+ }
74
+
75
+ export function serializeCapabilityGraphJson(document: CapabilityGraphDocument): string {
76
+ return JSON.stringify(document, null, 2);
77
+ }
@@ -0,0 +1,162 @@
1
+ import { z } from 'astro/zod';
2
+ import type { RecipeMetadata } from './types.js';
3
+
4
+ export const SHELL_RECIPE_ID = 'site.shell';
5
+
6
+ const shellOptionsSchema = z.strictObject({
7
+ siteName: z.string().min(1).default('Example Site'),
8
+ defaultLocale: z.string().default('en'),
9
+ noIndex: z.boolean().default(false),
10
+ });
11
+
12
+ export type ShellRecipeOptions = z.infer<typeof shellOptionsSchema>;
13
+
14
+ const PLACEHOLDER_SITE_URL = 'https://replace-with-your-domain.example';
15
+
16
+ function astroConfig(options: ShellRecipeOptions): string {
17
+ return `import { defineConfig } from 'astro/config';
18
+ import easyWebSeo from '@easy-web/core/seo';
19
+
20
+ export default defineConfig({
21
+ site: ${JSON.stringify(PLACEHOLDER_SITE_URL)},
22
+ integrations: [
23
+ easyWebSeo({ noIndex: ${options.noIndex ? 'true' : 'false'} }),
24
+ ],
25
+ });
26
+ `;
27
+ }
28
+
29
+ const packageJsonFragment = `${JSON.stringify({
30
+ type: 'module',
31
+ scripts: { dev: 'astro dev', build: 'astro build', preview: 'astro preview' },
32
+ dependencies: { '@easy-web/core': '^1.5.0', astro: '^7.3.5' },
33
+ devDependencies: { typescript: '^5.5.0' },
34
+ }, null, 2)}\n`;
35
+
36
+ const pnpmWorkspace = `allowBuilds:
37
+ esbuild: true
38
+ sharp: true
39
+ `;
40
+
41
+ function baseLayout(options: ShellRecipeOptions): string {
42
+ return `---
43
+ import PageShell from '@easy-web/core/components/PageShell.astro';
44
+ import Header from '@easy-web/core/components/Header.astro';
45
+ import Footer from '@easy-web/core/components/Footer.astro';
46
+
47
+ interface Props {
48
+ title: string;
49
+ }
50
+ const { title } = Astro.props;
51
+ const siteName = ${JSON.stringify(options.siteName)};
52
+ const currentLang = ${JSON.stringify(options.defaultLocale)};
53
+ const navItems = [{ label: 'Home', href: '/' }];
54
+ ---
55
+ <!doctype html>
56
+ <html lang=${JSON.stringify(options.defaultLocale)}>
57
+ <head>
58
+ <meta charset="utf-8" />
59
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
60
+ <title>{title}</title>
61
+ </head>
62
+ <body>
63
+ <PageShell lang={currentLang}>
64
+ <Header
65
+ slot="header"
66
+ lang={currentLang}
67
+ siteName={siteName}
68
+ navItems={navItems}
69
+ currentLang={currentLang}
70
+ pathname={Astro.url.pathname}
71
+ brandHref="/"
72
+ locales={[currentLang]}
73
+ />
74
+ <slot />
75
+ <Footer slot="footer" lang={currentLang} siteName={siteName} legalLinks={[
76
+ { label: 'Imprint (sample)', href: '/imprint' },
77
+ { label: 'Privacy (sample)', href: '/privacy' },
78
+ ]} />
79
+ </PageShell>
80
+ </body>
81
+ </html>
82
+ `;
83
+ }
84
+
85
+ function homePage(options: ShellRecipeOptions): string {
86
+ return `---
87
+ import Base from '../layouts/Base.astro';
88
+ ---
89
+ <Base title=${JSON.stringify(options.siteName)}>
90
+ <h1>Welcome</h1>
91
+ <p>This is a generated placeholder home page. Replace this content before production.</p>
92
+ </Base>
93
+ `;
94
+ }
95
+
96
+ function notFoundPage(options: ShellRecipeOptions): string {
97
+ return `---
98
+ import Base from '../layouts/Base.astro';
99
+ import NotFound from '@easy-web/core/components/NotFound.astro';
100
+ ---
101
+ <Base title="Page not found">
102
+ <NotFound currentLang=${JSON.stringify(options.defaultLocale)} defaultLocale=${JSON.stringify(options.defaultLocale)} />
103
+ </Base>
104
+ `;
105
+ }
106
+
107
+ const localizedPaths = `import type { LocalizedPathGroup } from '@easy-web/core/i18n';
108
+
109
+ export const localizedPaths: readonly LocalizedPathGroup[] = [];
110
+ `;
111
+
112
+ const robotsTxt = `Disallow: /admin/
113
+ Sitemap: ${PLACEHOLDER_SITE_URL}/sitemap-index.xml
114
+ `;
115
+
116
+ const gitignore = `node_modules
117
+ dist
118
+ .astro
119
+ `;
120
+
121
+ export function buildShellFiles(rawOptions: unknown): readonly { path: string; content: string }[] {
122
+ const options = shellOptionsSchema.parse(rawOptions ?? {});
123
+ return [
124
+ { path: 'astro.config.mjs', content: astroConfig(options) },
125
+ { path: 'package.json', content: packageJsonFragment },
126
+ { path: 'pnpm-workspace.yaml', content: pnpmWorkspace },
127
+ { path: 'src/layouts/Base.astro', content: baseLayout(options) },
128
+ { path: 'src/pages/index.astro', content: homePage(options) },
129
+ { path: 'src/pages/404.astro', content: notFoundPage(options) },
130
+ { path: 'src/lib/localized-paths.ts', content: localizedPaths },
131
+ { path: 'public/robots.txt', content: robotsTxt },
132
+ { path: '.gitignore', content: gitignore },
133
+ ];
134
+ }
135
+
136
+ export const shellRecipe = {
137
+ id: SHELL_RECIPE_ID,
138
+ version: '1.5.0',
139
+ protocolVersion: 1,
140
+ compatibleCliRange: '^0.1.0',
141
+ compatibleRuntimeRange: '^1.5.0',
142
+ provides: [SHELL_RECIPE_ID],
143
+ requires: [],
144
+ conflicts: [],
145
+ order: { priority: 0, key: 'shell' },
146
+ optionsSchema: shellOptionsSchema,
147
+ outputContributions: [
148
+ { kind: 'configuration', id: 'shell.astro-config', target: 'astro.config.mjs' },
149
+ { kind: 'dependency', id: 'shell.dependencies', target: 'package.json' },
150
+ { kind: 'configuration', id: 'shell.pnpm-workspace', target: 'pnpm-workspace.yaml' },
151
+ { kind: 'file', id: 'shell.base-layout', target: 'src/layouts/Base.astro' },
152
+ { kind: 'route', id: 'shell.home', target: '/' },
153
+ { kind: 'route', id: 'shell.404', target: '/404' },
154
+ { kind: 'file', id: 'shell.localized-paths', target: 'src/lib/localized-paths.ts' },
155
+ { kind: 'file', id: 'shell.robots', target: 'public/robots.txt' },
156
+ { kind: 'file', id: 'shell.gitignore', target: '.gitignore' },
157
+ ],
158
+ validators: [],
159
+ generate: (context: { options?: unknown }) => ({ files: buildShellFiles(context.options) }),
160
+ } satisfies RecipeMetadata<ShellRecipeOptions>;
161
+
162
+ export default shellRecipe;
@@ -0,0 +1,63 @@
1
+ import { z } from 'astro/zod';
2
+ import {
3
+ recipeMetadataFields,
4
+ recipeValidatorDescriptorSchema,
5
+ } from './schema.js';
6
+ import type { RecipeOutputContribution } from './schema.js';
7
+
8
+ export interface RecipeGeneratedFile {
9
+ readonly path: string;
10
+ readonly content: string | Uint8Array;
11
+ }
12
+
13
+ /** Hooks return output data; they receive no filesystem/process/target-node_modules access. */
14
+ export interface RecipeGenerationContext<Options = unknown> {
15
+ readonly options: Options;
16
+ readonly capabilities: readonly string[];
17
+ readonly contributions: readonly RecipeOutputContribution[];
18
+ }
19
+
20
+ export interface RecipeGenerationOutput {
21
+ readonly files: readonly RecipeGeneratedFile[];
22
+ }
23
+
24
+ export type RecipeGenerateHook<Options = unknown> = (
25
+ context: RecipeGenerationContext<Options>,
26
+ ) => RecipeGenerationOutput | Promise<RecipeGenerationOutput>;
27
+
28
+ export interface RecipeValidationContext<Options = unknown> extends RecipeGenerationContext<Options> {
29
+ readonly output?: RecipeGenerationOutput;
30
+ }
31
+
32
+ export interface RecipeValidationIssue {
33
+ readonly code: string;
34
+ readonly message: string;
35
+ readonly path?: string;
36
+ }
37
+
38
+ export type RecipeValidateHook<Options = unknown> = (
39
+ context: RecipeValidationContext<Options>,
40
+ ) => readonly RecipeValidationIssue[] | Promise<readonly RecipeValidationIssue[]>;
41
+
42
+ const validatorSchema = recipeValidatorDescriptorSchema.unwrap().extend({
43
+ validate: z.custom<RecipeValidateHook>((value) => typeof value === 'function'),
44
+ }).readonly();
45
+
46
+ /** Shape admission never calls options parsing, validators or generation hooks. */
47
+ export const recipeMetadataSchema = z.strictObject({
48
+ ...recipeMetadataFields,
49
+ optionsSchema: z.instanceof(z.ZodType),
50
+ validators: z.array(validatorSchema).readonly(),
51
+ generate: z.custom<RecipeGenerateHook>((value) => typeof value === 'function'),
52
+ }).readonly();
53
+
54
+ /** Typed recipe implementations can use their own inferred Zod options. */
55
+ export type RecipeMetadata<Options = unknown> = Omit<
56
+ z.infer<typeof recipeMetadataSchema>, 'optionsSchema' | 'generate' | 'validators'
57
+ > & {
58
+ readonly optionsSchema: z.ZodType<Options>;
59
+ readonly generate: RecipeGenerateHook<Options>;
60
+ readonly validators: readonly (z.infer<typeof recipeValidatorDescriptorSchema> & {
61
+ readonly validate: RecipeValidateHook<Options>;
62
+ })[];
63
+ };
@@ -0,0 +1,19 @@
1
+ import { experimental_AstroContainer as AstroContainer } from 'astro/container';
2
+ import { afterEach, expect, it, vi } from 'vitest';
3
+ import VersionPage from '../routes/version.astro';
4
+
5
+ afterEach(() => vi.unstubAllEnvs());
6
+
7
+ it('renders escaped manifest values in an accessible zero-hydration document', async () => {
8
+ // Given a manifest whose public labels need HTML escaping
9
+ vi.stubEnv('EASY_WEB_SEO_BUILD_INFO', JSON.stringify({ schema: 'easy-web/build-info', schemaVersion: 1, site: '<script>alert(1)</script>', releaseId: 'release<&>', easyWeb: { version: '1.2.3', packages: ['core'] } }));
10
+ const container = await AstroContainer.create();
11
+ // When rendering the actual shipped route
12
+ const html = await container.renderToString(VersionPage);
13
+ // Then structured document semantics and safe text survive without client code
14
+ expect(html).toMatch(/<meta name="robots" content="noindex,nofollow"/);
15
+ expect(html).toMatch(/<h1[^>]*>Build information<\/h1>/);
16
+ expect(html).toContain('&lt;script&gt;');
17
+ expect(html).toContain('@easy-web/core');
18
+ expect(html).not.toMatch(/<script|astro-island/);
19
+ });
@@ -0,0 +1,107 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import easyWebSeo, { type Options } from '../index.js';
3
+ import { GET as robots } from '../routes/robots-txt.js';
4
+ import { GET as version } from '../routes/version-json.js';
5
+
6
+ const { sitemapSpy } = vi.hoisted(() => ({ sitemapSpy: vi.fn() }));
7
+ vi.mock('@astrojs/sitemap', () => ({ default: (options: unknown) => {
8
+ sitemapSpy(options);
9
+ return { name: '@astrojs/sitemap', hooks: {} };
10
+ } }));
11
+
12
+ function setup(options: Options = {}, base = '/') {
13
+ const integration = easyWebSeo(options);
14
+ const injectRoute = vi.fn();
15
+ const hook = integration.hooks['astro:config:setup'];
16
+ if (!hook) throw new Error('Missing setup hook');
17
+ Reflect.apply(hook, undefined, [{
18
+ config: { root: new URL('../../../../../apps/contract-fixture/', import.meta.url), site: 'https://example.com', base, trailingSlash: 'ignore', build: { format: 'directory' }, integrations: [] },
19
+ updateConfig: vi.fn(), injectRoute, logger: { warn: vi.fn(), error: vi.fn() },
20
+ }]);
21
+ return injectRoute;
22
+ }
23
+
24
+ afterEach(() => {
25
+ vi.unstubAllEnvs();
26
+ delete process.env.EASY_WEB_SEO_BUILD_INFO;
27
+ delete process.env.EASY_WEB_SEO_BUILD_INFO_JSON;
28
+ delete process.env.EASY_WEB_SEO_BASE;
29
+ delete process.env.EASY_WEB_SEO_NO_INDEX;
30
+ delete process.env.EASY_WEB_SEO_TRAILING_SLASH;
31
+ sitemapSpy.mockClear();
32
+ });
33
+
34
+ describe('opt-in build-info routes', () => {
35
+ it('injects both routes as prerendered when enabled', () => {
36
+ // Given explicit opt-in
37
+ const options = { buildInfo: { site: 'Public', json: true } };
38
+ // When setting up SEO
39
+ const routes = setup(options).mock.calls.map(([route]) => route);
40
+ // Then Astro receives both static route declarations
41
+ expect(routes).toEqual(expect.arrayContaining([
42
+ expect.objectContaining({ pattern: '/version', prerender: true }),
43
+ expect.objectContaining({ pattern: '/version.json', prerender: true }),
44
+ ]));
45
+ });
46
+
47
+ it('serves the exact shared manifest with safe JSON headers', async () => {
48
+ // Given opt-in setup and unrelated private environment state
49
+ vi.stubEnv('PRIVATE_TENANT', 'secret-tenant');
50
+ setup({ buildInfo: { site: 'Public', releaseId: 'release-42', json: true } });
51
+ const expected = process.env.EASY_WEB_SEO_BUILD_INFO;
52
+ // When requesting the machine endpoint
53
+ const response = await Reflect.apply(version, undefined, [{}]);
54
+ // Then bytes match the immutable handoff, with no framework/private additions
55
+ expect(await response.text()).toBe(expected);
56
+ expect(response.headers.get('Content-Type')).toBe('application/json; charset=utf-8');
57
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
58
+ expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff');
59
+ expect(response.headers.get('X-Robots-Tag')).toBe('noindex, nofollow');
60
+ expect(expected).not.toContain('secret-tenant');
61
+ });
62
+
63
+ it('retains prior robots bytes and route set when omitted after an enabled build', async () => {
64
+ // Given an earlier enabled build in the same process
65
+ setup({ buildInfo: { site: 'Earlier' } });
66
+ // When setting up a site without the feature
67
+ const routes = setup().mock.calls.map(([route]) => route.pattern);
68
+ const response = await Reflect.apply(robots, undefined, [{ site: new URL('https://example.com') }]);
69
+ // Then the old public behavior is byte-equivalent and no manifest survives
70
+ expect(routes).toEqual(['/robots.txt']);
71
+ expect(process.env.EASY_WEB_SEO_BUILD_INFO).toBeUndefined();
72
+ expect(await response.text()).toBe('User-agent: *\nDisallow: /admin/\nAllow: /\n\nSitemap: https://example.com/sitemap-index.xml\n');
73
+ const filter = sitemapSpy.mock.lastCall?.[0].filter;
74
+ expect(filter('https://example.com/version/')).toBe(true);
75
+ });
76
+
77
+ it('keeps JSON disabled unless the host explicitly supports its response headers', () => {
78
+ const routes = setup({ buildInfo: { site: 'Public' } }).mock.calls.map(([route]) => route.pattern);
79
+
80
+ expect(routes).toContain('/version');
81
+ expect(routes).not.toContain('/version.json');
82
+ expect(process.env.EASY_WEB_SEO_BUILD_INFO_JSON).toBe('false');
83
+ });
84
+
85
+ it.each(['/', '/sub/'])('excludes both routes from the sitemap while leaving noindex discoverable under base %s', async (base) => {
86
+ // Given public opt-in with a caller filter that allows everything
87
+ setup({ buildInfo: { site: 'Public' }, filter: () => true }, base);
88
+ // When evaluating sitemap URLs and robots
89
+ const filter = sitemapSpy.mock.lastCall?.[0].filter;
90
+ const response = await Reflect.apply(robots, undefined, [{ site: new URL('https://example.com') }]);
91
+ // Then neither version surface is advertised, but robots does not hide
92
+ // the routes from crawlers that must read their noindex directives.
93
+ for (const route of ['version', 'version/', 'version.json']) expect(filter(`https://example.com${base}${route}`)).toBe(false);
94
+ expect(filter(`https://example.com${base}version-history/`)).toBe(true);
95
+ expect(await response.text()).toBe(`User-agent: *\nDisallow: /admin/\nAllow: /\n\nSitemap: https://example.com${base}sitemap-index.xml\n`);
96
+ });
97
+
98
+ it('keeps noIndex policy global without redundant route rules', async () => {
99
+ // Given a wholly unindexed site
100
+ setup({ noIndex: true, buildInfo: { site: 'Public' } });
101
+ // When rendering robots
102
+ const response = await Reflect.apply(robots, undefined, [{ site: new URL('https://example.com') }]);
103
+ // Then the global rule is unchanged
104
+ expect(await response.text()).toBe('User-agent: *\nDisallow: /\n');
105
+ expect(sitemapSpy).not.toHaveBeenCalled();
106
+ });
107
+ });
@@ -0,0 +1,86 @@
1
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { buildInfoManifest } from '../build-info.js';
7
+ import { serializeBuildInfo } from '../build-info-manifest.js';
8
+
9
+ const core = JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'));
10
+ const roots: string[] = [];
11
+ function fixture(packages: Readonly<Record<string, string>> = {}): URL {
12
+ const root = mkdtempSync(join(tmpdir(), 'easy-web-build-info-'));
13
+ roots.push(root);
14
+ writeFileSync(join(root, 'package.json'), JSON.stringify({ dependencies: { '@easy-web/core': '^0.0.1' } }));
15
+ for (const [id, version] of Object.entries(packages)) {
16
+ const folder = join(root, 'node_modules', '@easy-web', id);
17
+ mkdirSync(folder, { recursive: true });
18
+ writeFileSync(join(folder, 'package.json'), JSON.stringify({ name: `@easy-web/${id}`, version, exports: { '.': { import: './index.js' } } }));
19
+ writeFileSync(join(folder, 'index.js'), 'throw new Error("must not execute packages");');
20
+ }
21
+ return pathToFileURL(`${root}/`);
22
+ }
23
+ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true }); });
24
+
25
+ describe('public build-info manifest', () => {
26
+ it('uses the core artifact version rather than the site dependency range', () => {
27
+ // Given a consumer claiming a different dependency range
28
+ const root = fixture();
29
+ // When building the default manifest
30
+ const manifest = buildInfoManifest({ site: 'Public site' }, root);
31
+ // Then only the exact public contract is emitted
32
+ expect(serializeBuildInfo(manifest)).toBe(`{"schema":"easy-web/build-info","schemaVersion":1,"site":"Public site","easyWeb":{"version":"${core.version}","packages":["core"]}}\n`);
33
+ });
34
+
35
+ it('sorts and deduplicates configured packages and freezes every container', () => {
36
+ // Given installed fixed-family add-ons, with no executable code allowed
37
+ const root = fixture({ swa: core.version, auth: core.version, 'cms-adapters': core.version });
38
+ // When options are supplied out of order
39
+ const manifest = buildInfoManifest({ site: 'Public', releaseId: 'release-42', packages: ['swa', 'core', 'auth', 'cms-adapters', 'auth'] }, root);
40
+ // Then a single family version and immutable package selection are published
41
+ expect(manifest).toEqual({ schema: 'easy-web/build-info', schemaVersion: 1, site: 'Public', releaseId: 'release-42', easyWeb: { version: core.version, packages: ['auth', 'cms-adapters', 'core', 'swa'] } });
42
+ expect([manifest, manifest.easyWeb, manifest.easyWeb.packages].every(Object.isFrozen)).toBe(true);
43
+ });
44
+
45
+ it.each(['brand', 'cli', 'create', 'seo', 'Card', 'react'])('rejects forbidden package %s', (id) => {
46
+ // Given an unsupported package id
47
+ const options = { site: 'Public', packages: [id] };
48
+ // When crossing the configuration boundary, then reject it
49
+ expect(() => buildInfoManifest(options, fixture())).toThrow(/buildInfo/);
50
+ });
51
+
52
+ it.each(['version', 'metadata', 'timestamp', 'gitSha', 'branch', 'pipelineUrl', 'tenant', 'environment'])('rejects forbidden option %s', (field) => {
53
+ // Given extra data that must never be copied into public output
54
+ const options = { site: 'Public', [field]: 'private' };
55
+ // When crossing the configuration boundary, then reject it
56
+ expect(() => buildInfoManifest(options, fixture())).toThrow(/buildInfo/);
57
+ });
58
+
59
+ it.each(['', ' leading', 'trailing ', 'line\nbreak', 'tab\t', 'nul\0', '\u007f', '\u0085', '\u202e', 'x'.repeat(121)])('rejects unsafe or unbounded site strings %j', (site) => {
60
+ // Given a non-public-label string
61
+ const root = fixture();
62
+ // When building, then validation fails
63
+ expect(() => buildInfoManifest({ site }, root)).toThrow(/buildInfo/);
64
+ });
65
+
66
+ it.each(['', ' release', 'release\n42', 'x'.repeat(121)])('rejects unsafe release labels %j', (releaseId) => {
67
+ // Given an invalid optional opaque label
68
+ const root = fixture();
69
+ // When building, then validation fails
70
+ expect(() => buildInfoManifest({ site: 'Public', releaseId }, root)).toThrow(/buildInfo/);
71
+ });
72
+
73
+ it('fails clearly when a configured add-on is not installed', () => {
74
+ // Given a site without auth
75
+ const root = fixture();
76
+ // When enabling auth, then fail instead of claiming it is enabled
77
+ expect(() => buildInfoManifest({ site: 'Public', packages: ['auth'] }, root)).toThrow(/@easy-web\/auth.*installed/);
78
+ });
79
+
80
+ it.each(['0.0.1', '^1.6.0', 'not-a-version'])('rejects mismatched or inexact installed versions %s', (version) => {
81
+ // Given an incompatible artifact
82
+ const root = fixture({ swa: version });
83
+ // When enabling it, then fixed-family drift is a configuration failure
84
+ expect(() => buildInfoManifest({ site: 'Public', packages: ['swa'] }, root)).toThrow(/@easy-web\/swa.*version/);
85
+ });
86
+ });
@@ -13,6 +13,7 @@ const runGET = (ctx: Partial<APIContext>): Response => {
13
13
  describe('robots-txt GET handler', () => {
14
14
  afterEach(() => {
15
15
  delete process.env.EASY_WEB_SEO_NO_INDEX;
16
+ delete process.env.EASY_WEB_SEO_BASE;
16
17
  });
17
18
 
18
19
  it('returns public robots.txt with Sitemap when EASY_WEB_SEO_NO_INDEX is "false"', async () => {
@@ -63,4 +64,11 @@ describe('robots-txt GET handler', () => {
63
64
  expect(text).toContain('Sitemap: https://example.com/sitemap-index.xml');
64
65
  expect(text).toContain('Disallow: /admin/');
65
66
  });
67
+
68
+ it('includes Astro base in the sitemap URL', async () => {
69
+ process.env.EASY_WEB_SEO_BASE = '/easy-web/';
70
+ const response = runGET({ site: new URL('https://example.com') });
71
+
72
+ expect(await response.text()).toContain('Sitemap: https://example.com/easy-web/sitemap-index.xml');
73
+ });
66
74
  });
@@ -0,0 +1,49 @@
1
+ import { z } from 'astro/zod';
2
+
3
+ const packageIdSchema = z.enum(['core', 'auth', 'cms-adapters', 'swa']);
4
+ const publicLabelSchema = z.string().min(1).max(120)
5
+ .refine((value) => value === value.trim() && !/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(value), 'must be trimmed printable text');
6
+
7
+ export const buildInfoOptionsSchema = z.strictObject({
8
+ site: publicLabelSchema,
9
+ packages: z.array(packageIdSchema).readonly().optional(),
10
+ releaseId: publicLabelSchema.optional(),
11
+ json: z.boolean().optional(),
12
+ }).readonly();
13
+
14
+ export type BuildInfoPackageId = z.infer<typeof packageIdSchema>;
15
+ export type BuildInfoOptions = z.infer<typeof buildInfoOptionsSchema>;
16
+
17
+ export const exactVersionSchema = z.string().regex(
18
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/,
19
+ );
20
+
21
+ const manifestSchema = z.strictObject({
22
+ schema: z.literal('easy-web/build-info'),
23
+ schemaVersion: z.literal(1),
24
+ site: publicLabelSchema,
25
+ releaseId: publicLabelSchema.optional(),
26
+ easyWeb: z.strictObject({
27
+ version: exactVersionSchema,
28
+ packages: z.array(packageIdSchema).readonly(),
29
+ }).readonly(),
30
+ }).readonly();
31
+
32
+ export type BuildInfoManifest = z.infer<typeof manifestSchema>;
33
+
34
+ export class BuildInfoError extends Error {
35
+ constructor(readonly detail: string) {
36
+ super(`@easy-web/core: buildInfo ${detail}`);
37
+ this.name = 'BuildInfoError';
38
+ }
39
+ }
40
+
41
+ export function serializeBuildInfo(manifest: BuildInfoManifest): string {
42
+ return `${JSON.stringify(manifest)}\n`;
43
+ }
44
+
45
+ export function readBuildInfo(): BuildInfoManifest {
46
+ const serialized = process.env.EASY_WEB_SEO_BUILD_INFO;
47
+ if (!serialized) throw new BuildInfoError('manifest is unavailable; enable easyWebSeo({ buildInfo }).');
48
+ return manifestSchema.parse(JSON.parse(serialized));
49
+ }