@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,82 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ createExplicitFormatters, currencyCodeSchema, dateOnlySchema,
4
+ formatLocaleSchema, ianaTimeZoneSchema,
5
+ } from '../index.js'
6
+
7
+ const context = {
8
+ locale: formatLocaleSchema.parse('en-GB'),
9
+ timeZone: ianaTimeZoneSchema.parse('America/Los_Angeles'),
10
+ }
11
+ const currency = currencyCodeSchema.parse('EUR')
12
+ const date = dateOnlySchema.parse('2024-03-10')
13
+ const instant = Date.UTC(2024, 2, 10, 7, 30)
14
+
15
+ afterEach(() => vi.unstubAllEnvs())
16
+
17
+ describe('explicit formatters', () => {
18
+ it('produces identical dates, instants, numbers and money when the host timezone changes', () => {
19
+ // Given
20
+ const outputs = (host: string) => {
21
+ vi.stubEnv('TZ', host)
22
+ const format = createExplicitFormatters(context)
23
+ return [format.dateOnly(date), format.instant(instant), format.number(1234.5), format.currency(12.5, currency)]
24
+ }
25
+ // When
26
+ const utc = outputs('UTC')
27
+ const newYork = outputs('America/New_York')
28
+ // Then
29
+ expect(newYork).toEqual(utc)
30
+ expect(utc).toEqual(['10 Mar 2024', '9 Mar 2024, 23:30', '1,234.5', '€12.50'])
31
+ })
32
+
33
+ it('preserves the civil date when the explicit timezone crosses midnight', () => {
34
+ // Given
35
+ const format = createExplicitFormatters(context)
36
+ // When
37
+ const result = format.dateOnly(date, { year: 'numeric', month: '2-digit', day: '2-digit' })
38
+ // Then
39
+ expect(result).toBe('10/03/2024')
40
+ })
41
+
42
+ it('uses the explicit timezone including daylight saving when formatting an instant', () => {
43
+ // Given
44
+ const format = createExplicitFormatters(context)
45
+ // When
46
+ const result = format.instant(Date.UTC(2024, 2, 10, 10, 30))
47
+ // Then
48
+ expect(result).toBe('10 Mar 2024, 03:30')
49
+ })
50
+
51
+ it('honors a format locale different from content language when formatting numbers', () => {
52
+ // Given
53
+ const format = createExplicitFormatters({ ...context, locale: formatLocaleSchema.parse('de-AT') })
54
+ // When
55
+ const result = format.number(1234.5)
56
+ // Then
57
+ expect(result).toBe('1\u00a0234,5')
58
+ })
59
+
60
+ it('honors the supplied currency rather than locale currency when formatting money', () => {
61
+ // Given
62
+ const format = createExplicitFormatters(context)
63
+ // When
64
+ const result = format.currency(12.5, currencyCodeSchema.parse('JPY'), { currencyDisplay: 'code' })
65
+ // Then
66
+ expect(result).toMatch(/^JPY\s13$/)
67
+ })
68
+
69
+ it.each(['2023-02-29', '2024-02-30', '2024-13-01', '03/10/2024', '2024-03-10T00:00:00'])('rejects invalid civil dates when given %s', (value) => {
70
+ // Given / When
71
+ const result = dateOnlySchema.safeParse(value)
72
+ // Then
73
+ expect(result.success).toBe(false)
74
+ })
75
+
76
+ it('accepts a real leap date when parsing a civil date', () => {
77
+ // Given / When
78
+ const result = dateOnlySchema.parse('2024-02-29')
79
+ // Then
80
+ expect(result).toBe('2024-02-29')
81
+ })
82
+ })
@@ -0,0 +1,44 @@
1
+ import type { CliUiLocale } from './locale-inputs.js'
2
+
3
+ export type LocalizationInterviewLabels = {
4
+ readonly cliUiLocale: string
5
+ readonly contentLocales: string
6
+ readonly defaultContentLocale: string
7
+ readonly localizedLabels: string
8
+ readonly localizedPaths: string
9
+ readonly formatMode: string
10
+ readonly sharedFormatLocale: string
11
+ readonly perLanguageFormatLocales: string
12
+ readonly timeZone: string
13
+ readonly moneyCurrency: string
14
+ readonly invalidInput: string
15
+ }
16
+
17
+ export const localizationInterviewCatalogs = {
18
+ en: {
19
+ cliUiLocale: 'Interview language',
20
+ contentLocales: 'Site content languages (BCP47)',
21
+ defaultContentLocale: 'Default content language',
22
+ localizedLabels: 'Translated site labels',
23
+ localizedPaths: 'Translated public routes (only differing slugs)',
24
+ formatMode: 'Shared or per-language regional formatting',
25
+ sharedFormatLocale: 'Shared format locale (for example en-GB)',
26
+ perLanguageFormatLocales: 'Format locale for each content language',
27
+ timeZone: 'IANA timezone (for example Europe/London)',
28
+ moneyCurrency: 'Currency for money content (ISO 4217)',
29
+ invalidInput: 'Invalid explicit localization input',
30
+ },
31
+ de: {
32
+ cliUiLocale: 'Sprache des Interviews',
33
+ contentLocales: 'Inhaltssprachen der Website (BCP47)',
34
+ defaultContentLocale: 'Standard-Inhaltssprache',
35
+ localizedLabels: 'Übersetzte Website-Beschriftungen',
36
+ localizedPaths: 'Übersetzte öffentliche Routen (nur unterschiedliche Slugs)',
37
+ formatMode: 'Gemeinsame oder sprachabhängige regionale Formatierung',
38
+ sharedFormatLocale: 'Gemeinsames Format-Gebietsschema (zum Beispiel de-AT)',
39
+ perLanguageFormatLocales: 'Format-Gebietsschema je Inhaltssprache',
40
+ timeZone: 'IANA-Zeitzone (zum Beispiel Europe/Vienna)',
41
+ moneyCurrency: 'Währung für Geldinhalte (ISO 4217)',
42
+ invalidInput: 'Ungültige explizite Lokalisierungseingabe',
43
+ },
44
+ } as const satisfies Readonly<Record<CliUiLocale, LocalizationInterviewLabels>>
@@ -0,0 +1,67 @@
1
+ import { z } from 'astro/zod'
2
+ import { cliUiLocaleSchema, contentLocaleSchema, formatLocaleSchema, ianaTimeZoneSchema } from './locale-inputs.js'
3
+ import { validateLocalizedPaths } from './localized-paths.js'
4
+ import type { ExplicitFormatContext } from './explicit-formatters.js'
5
+
6
+ export const formatLocalesSchema = z.discriminatedUnion('mode', [
7
+ z.object({ mode: z.literal('shared'), locale: formatLocaleSchema }).strict().readonly(),
8
+ z.object({ mode: z.literal('per-language'), locales: z.record(z.string(), formatLocaleSchema).readonly() }).strict().readonly(),
9
+ ])
10
+ export type FormatLocales = z.infer<typeof formatLocalesSchema>
11
+
12
+ /** Interview language is not site content; regional presentation is not route identity. */
13
+ export const createLocalizationSchema = z.object({
14
+ cliUiLocale: cliUiLocaleSchema,
15
+ contentLocales: z.array(contentLocaleSchema).min(1).readonly(),
16
+ defaultContentLocale: contentLocaleSchema,
17
+ localizedLabels: z.record(z.string(), z.record(z.string(), z.string()).readonly()).readonly(),
18
+ // Same complete public paths consumed by createI18n and easyWebSeo, not slug fragments.
19
+ localizedPaths: z.array(z.record(z.string(), z.string()).readonly()).readonly(),
20
+ formatLocales: formatLocalesSchema,
21
+ timeZone: ianaTimeZoneSchema,
22
+ }).strict().superRefine((input, ctx) => {
23
+ const add = (path: string, message: string) => ctx.addIssue({ code: z.ZodIssueCode.custom, path: [path], message })
24
+ const localeKeys = input.contentLocales.map((locale) => locale.toLowerCase())
25
+ if (new Set(localeKeys).size !== localeKeys.length) add('contentLocales', 'Content locales must be unique')
26
+ if (!input.contentLocales.includes(input.defaultContentLocale)) add('defaultContentLocale', 'Default must be a selected content locale')
27
+ const checkKeys = (path: string, keys: readonly string[]) => {
28
+ if (keys.length !== input.contentLocales.length || keys.some((key) => !input.contentLocales.some((locale) => locale === key))) {
29
+ add(path, 'Declare exactly the selected content locales')
30
+ }
31
+ }
32
+ checkKeys('localizedLabels', Object.keys(input.localizedLabels))
33
+ const labelSets = Object.values(input.localizedLabels).map((labels) => Object.keys(labels).sort().join('\0'))
34
+ if (new Set(labelSets).size > 1) add('localizedLabels', 'Translate the same label keys in every content locale')
35
+ for (const problem of validateLocalizedPaths(input.localizedPaths, input.contentLocales)) add('localizedPaths', problem)
36
+ if (input.formatLocales.mode === 'per-language') checkKeys('formatLocales', Object.keys(input.formatLocales.locales))
37
+ }).readonly()
38
+
39
+ export type CreateLocalization = z.infer<typeof createLocalizationSchema>
40
+
41
+ export function parseCreateLocalization(input: unknown): CreateLocalization {
42
+ return createLocalizationSchema.parse(input)
43
+ }
44
+
45
+ export class UnselectedContentLocaleError extends RangeError {
46
+ constructor(readonly locale: string) {
47
+ super(`Content locale was not selected: ${locale}`)
48
+ this.name = 'UnselectedContentLocaleError'
49
+ }
50
+ }
51
+
52
+ export function resolveFormatContext(input: CreateLocalization, contentLocale: string): ExplicitFormatContext {
53
+ if (!input.contentLocales.some((locale) => locale === contentLocale)) throw new UnselectedContentLocaleError(contentLocale)
54
+ switch (input.formatLocales.mode) {
55
+ case 'shared':
56
+ return { locale: input.formatLocales.locale, timeZone: input.timeZone }
57
+ case 'per-language': {
58
+ const locale = input.formatLocales.locales[contentLocale]
59
+ if (locale === undefined) throw new UnselectedContentLocaleError(contentLocale)
60
+ return { locale, timeZone: input.timeZone }
61
+ }
62
+ default: {
63
+ const exhaustive: never = input.formatLocales
64
+ return exhaustive
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,36 @@
1
+ import { z } from 'astro/zod'
2
+ import type { CurrencyCode, FormatLocale, IanaTimeZone } from './locale-inputs.js'
3
+
4
+ export type ExplicitFormatContext = {
5
+ readonly locale: FormatLocale
6
+ readonly timeZone: IanaTimeZone
7
+ }
8
+
9
+ /** A civil date is not an instant: never shift it across dates in the site's timezone. */
10
+ export const dateOnlySchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
11
+ const date = new Date(`${value}T00:00:00.000Z`)
12
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
13
+ }, 'Invalid Gregorian date').brand<'DateOnly'>()
14
+ export type DateOnly = z.infer<typeof dateOnlySchema>
15
+
16
+ export type DateOnlyFormatOptions = Pick<Intl.DateTimeFormatOptions,
17
+ 'dateStyle' | 'year' | 'month' | 'day' | 'weekday' | 'era' | 'calendar' | 'numberingSystem'>
18
+ export type InstantFormatOptions = Omit<Intl.DateTimeFormatOptions, 'timeZone'>
19
+ export type DecimalFormatOptions = Omit<Intl.NumberFormatOptions, 'style' | 'currency' | 'unit'>
20
+ export type CurrencyFormatOptions = Omit<Intl.NumberFormatOptions, 'style' | 'currency'>
21
+
22
+ export function createExplicitFormatters(context: ExplicitFormatContext) {
23
+ return {
24
+ dateOnly: (value: DateOnly, options: DateOnlyFormatOptions = { dateStyle: 'medium' }): string =>
25
+ new Intl.DateTimeFormat(context.locale, { ...options, timeZone: 'UTC' })
26
+ .format(new Date(`${value}T00:00:00.000Z`)),
27
+ // Date/epoch inputs represent absolute instants; local datetime strings are intentionally excluded.
28
+ instant: (value: Date | number, options: InstantFormatOptions = { dateStyle: 'medium', timeStyle: 'short' }): string =>
29
+ new Intl.DateTimeFormat(context.locale, { ...options, timeZone: context.timeZone }).format(value),
30
+ number: (value: number, options: DecimalFormatOptions = {}): string =>
31
+ new Intl.NumberFormat(context.locale, { ...options, style: 'decimal' }).format(value),
32
+ // Currency is always a required argument, never guessed from locale or timezone.
33
+ currency: (value: number, currency: CurrencyCode, options: CurrencyFormatOptions = {}): string =>
34
+ new Intl.NumberFormat(context.locale, { ...options, style: 'currency', currency }).format(value),
35
+ }
36
+ }
package/src/i18n/index.ts CHANGED
@@ -3,3 +3,7 @@ export * from './formatters.js'
3
3
  export * from './localized-paths.js'
4
4
  export * from './routing.js'
5
5
  export * from './seo.js'
6
+ export * from './locale-inputs.js'
7
+ export * from './create-localization.js'
8
+ export * from './cli-catalogs.js'
9
+ export * from './explicit-formatters.js'
@@ -0,0 +1,73 @@
1
+ import { z } from 'astro/zod'
2
+
3
+ // RFC 5646 language tags, including private-use and grandfathered tags.
4
+ const languageTag = /^(?:[a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4}|[a-z]{5,8})(?:-[a-z]{4})?(?:-[a-z]{2}|-\d{3})?(?:-(?:[a-z\d]{5,8}|\d[a-z\d]{3}))*(?:-[a-wy-z\d](?:-[a-z\d]{2,8})+)*(?:-x(?:-[a-z\d]{1,8})+)?$|^x(?:-[a-z\d]{1,8})+$|^(?:en-GB-oed|i-(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)|sgn-(?:BE-FR|BE-NL|CH-DE)|art-lojban|cel-gaulish|no-bok|no-nyn|zh-(?:guoyu|hakka|min|min-nan|xiang))$/i
5
+
6
+ function isContentLocale(value: string): boolean {
7
+ if (!languageTag.test(value)) return false
8
+ const segments = value.toLowerCase().split('-')
9
+ if (segments[0] === 'x' || /^(i-|sgn-|en-gb-oed$)/.test(value.toLowerCase())) return true
10
+ const extensions = new Set<string>()
11
+ const variants = new Set<string>()
12
+ for (const segment of segments.slice(1)) {
13
+ if (segment === 'x') break
14
+ if (segment.length === 1) {
15
+ if (extensions.has(segment)) return false
16
+ extensions.add(segment)
17
+ } else if (extensions.size === 0 && /^(?:[a-z\d]{5,8}|\d[a-z\d]{3})$/.test(segment)) {
18
+ if (variants.has(segment)) return false
19
+ variants.add(segment)
20
+ }
21
+ }
22
+ return true
23
+ }
24
+
25
+ function supportsFormatLocale(value: string): boolean {
26
+ try {
27
+ return Intl.DateTimeFormat.supportedLocalesOf(value, { localeMatcher: 'lookup' }).length === 1
28
+ && Intl.NumberFormat.supportedLocalesOf(value, { localeMatcher: 'lookup' }).length === 1
29
+ } catch (error) {
30
+ if (error instanceof RangeError) return false
31
+ throw error
32
+ }
33
+ }
34
+
35
+ function isTimeZone(value: string): boolean {
36
+ // Intl also accepts numeric offsets; the create contract accepts named IANA zones only.
37
+ if (!/^[A-Za-z][A-Za-z\d._+-]*(?:\/[A-Za-z\d._+-]+)*$/.test(value)) return false
38
+ try {
39
+ new Intl.DateTimeFormat('en', { timeZone: value })
40
+ return true
41
+ } catch (error) {
42
+ if (error instanceof RangeError) return false
43
+ throw error
44
+ }
45
+ }
46
+
47
+ export const cliUiLocaleSchema = z.enum(['en', 'de'])
48
+ export type CliUiLocale = z.infer<typeof cliUiLocaleSchema>
49
+ export const contentLocaleSchema = z.string().refine(isContentLocale, 'Invalid BCP47 content locale').brand<'ContentLocale'>()
50
+ export type ContentLocale = z.infer<typeof contentLocaleSchema>
51
+ export const formatLocaleSchema = z.string().refine(supportsFormatLocale, 'Unsupported or malformed format locale').brand<'FormatLocale'>()
52
+ export type FormatLocale = z.infer<typeof formatLocaleSchema>
53
+ export const ianaTimeZoneSchema = z.string().refine(isTimeZone, 'Invalid IANA timezone').brand<'IanaTimeZone'>()
54
+ export type IanaTimeZone = z.infer<typeof ianaTimeZoneSchema>
55
+
56
+ // Intl accepts any three-letter code, so check its ISO 4217 catalog as well as shape.
57
+ export const currencyCodeSchema = z.string().regex(/^[A-Z]{3}$/).refine(
58
+ (value) => Intl.supportedValuesOf('currency').includes(value),
59
+ 'Unsupported ISO 4217 currency',
60
+ ).brand<'CurrencyCode'>()
61
+ export type CurrencyCode = z.infer<typeof currencyCodeSchema>
62
+ export const optionalCurrencyCodeSchema = currencyCodeSchema.optional()
63
+
64
+ /** Only auto-detected interview languages fall back; explicit input uses cliUiLocaleSchema. */
65
+ export function resolveDetectedCliUiLocale(detected: string | undefined): CliUiLocale {
66
+ if (detected === undefined) return 'en'
67
+ try {
68
+ return new Intl.Locale(detected).language === 'de' ? 'de' : 'en'
69
+ } catch (error) {
70
+ if (error instanceof RangeError) return 'en'
71
+ throw error
72
+ }
73
+ }
package/src/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './contracts/index.js';
2
+ export * from './recipes/index.js';
@@ -0,0 +1,139 @@
1
+ import { z } from 'astro/zod';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { resolveCapabilityGraph } from '../graph.js';
4
+ import type { RecipeMetadata, RecipeOutputContribution } from '../index.js';
5
+
6
+ type RecipeFixtureOptions = {
7
+ readonly provides?: readonly string[];
8
+ readonly requires?: readonly string[];
9
+ readonly conflicts?: readonly string[];
10
+ readonly priority?: number;
11
+ readonly key?: string;
12
+ readonly contributions?: readonly RecipeOutputContribution[];
13
+ };
14
+
15
+ function recipe(id: string, options: RecipeFixtureOptions = {}): RecipeMetadata {
16
+ return {
17
+ id,
18
+ version: '1.5.0',
19
+ protocolVersion: 1,
20
+ compatibleCliRange: '^0.1.0',
21
+ compatibleRuntimeRange: '^1.5.0',
22
+ provides: options.provides ?? [id],
23
+ requires: options.requires ?? [],
24
+ conflicts: options.conflicts ?? [],
25
+ order: { priority: options.priority ?? 0, key: options.key ?? id },
26
+ optionsSchema: z.strictObject({}),
27
+ outputContributions: options.contributions ?? [],
28
+ validators: [],
29
+ generate: vi.fn(() => ({ files: [] })),
30
+ };
31
+ }
32
+
33
+ describe('capability graph resolution', () => {
34
+ it('resolves requirements, content roles, fixed pages, adaptations and provenance', () => {
35
+ // Given
36
+ const shell = recipe('shell', {
37
+ priority: 10,
38
+ contributions: [
39
+ { kind: 'route', id: 'page.privacy', target: '/privacy/' },
40
+ { kind: 'file', id: 'shell.layout', target: 'src/layouts/Base.astro' },
41
+ ],
42
+ });
43
+ const article = recipe('article', {
44
+ provides: ['content.article'], requires: ['shell'], priority: 5,
45
+ contributions: [{ kind: 'content', id: 'content.article', target: 'primary' }],
46
+ });
47
+ const gallery = recipe('gallery', {
48
+ provides: ['content.gallery'], requires: ['content.article'],
49
+ contributions: [{ kind: 'content', id: 'content.gallery', target: 'additional' }],
50
+ });
51
+ const theme = recipe('theme', {
52
+ priority: 30,
53
+ contributions: [
54
+ { kind: 'binding', id: 'adaptation.shell-theme', target: 'shell.layout' },
55
+ { kind: 'binding', id: 'adaptation.missing-auth', target: 'auth.shell' },
56
+ ],
57
+ });
58
+
59
+ // When
60
+ const result = resolveCapabilityGraph([gallery, theme, shell, article]);
61
+
62
+ // Then
63
+ expect(result.ok).toBe(true);
64
+ if (!result.ok) return;
65
+ expect(result.value.recipes.map((node) => node.id)).toEqual(['shell', 'article', 'gallery', 'theme']);
66
+ expect(result.value.recipes.map((node) => node.provenance.inclusion)).toEqual([
67
+ { kind: 'transitive', requiredBy: ['article'] },
68
+ { kind: 'transitive', requiredBy: ['gallery'] },
69
+ { kind: 'direct' },
70
+ { kind: 'direct' },
71
+ ]);
72
+ expect(result.value.fixedPages.map((page) => page.target)).toEqual(['/privacy/']);
73
+ expect(result.value.contentTypes.primary?.id).toBe('content.article');
74
+ expect(result.value.contentTypes.additional.map((node) => node.id)).toEqual(['content.gallery']);
75
+ expect(result.value.adaptations.map((node) => node.id)).toEqual(['adaptation.shell-theme']);
76
+ expect(result.value.adaptations[0]?.targetContributionId).toBe('shell.layout');
77
+ expect([shell, article, gallery, theme].every((item) => vi.mocked(item.generate).mock.calls.length === 0)).toBe(true);
78
+ });
79
+
80
+ it('produces byte-identical output for every permutation of the same recipes', () => {
81
+ // Given
82
+ const shell = recipe('shell', { priority: 20 });
83
+ const content = recipe('content', { requires: ['shell'], priority: 10 });
84
+ const cms = recipe('cms', { requires: ['content'], priority: 0 });
85
+ const permutations = [
86
+ [shell, content, cms], [shell, cms, content], [content, shell, cms],
87
+ [content, cms, shell], [cms, shell, content], [cms, content, shell],
88
+ ];
89
+
90
+ // When
91
+ const serialized = permutations.map((items) => JSON.stringify(resolveCapabilityGraph(items)));
92
+
93
+ // Then
94
+ expect(new Set(serialized)).toHaveLength(1);
95
+ });
96
+
97
+ it.each([
98
+ ['dependency-cycle', [
99
+ recipe('alpha', { requires: ['beta'] }),
100
+ recipe('beta', { requires: ['alpha'] }),
101
+ ]],
102
+ ['output-conflict', [
103
+ recipe('privacy', { contributions: [{ kind: 'route', id: 'page.privacy', target: '/privacy/' }] }),
104
+ recipe('legal', { contributions: [{ kind: 'route', id: 'page.legal', target: '/privacy/' }] }),
105
+ ]],
106
+ ['conflicting-capability', [
107
+ recipe('analytics', { conflicts: ['consent'] }),
108
+ recipe('consent'),
109
+ ]],
110
+ ['multiple-primary-content', [
111
+ recipe('article', { contributions: [{ kind: 'content', id: 'content.article', target: 'primary' }] }),
112
+ recipe('event', { contributions: [{ kind: 'content', id: 'content.event', target: 'primary' }] }),
113
+ ]],
114
+ ] as const)('returns a typed %s failure without a partial graph', (code, recipes) => {
115
+ // When
116
+ const result = resolveCapabilityGraph(recipes);
117
+
118
+ // Then
119
+ expect(result).toMatchObject({ ok: false, error: { code } });
120
+ expect('value' in result).toBe(false);
121
+ });
122
+
123
+ it('reports a missing transitive requirement with the consumer and capability', () => {
124
+ // Given
125
+ const recipes = [
126
+ recipe('site', { requires: ['cms'] }),
127
+ recipe('cms', { requires: ['content'] }),
128
+ ];
129
+
130
+ // When
131
+ const result = resolveCapabilityGraph(recipes);
132
+
133
+ // Then
134
+ expect(result).toEqual({
135
+ ok: false,
136
+ error: { code: 'missing-requirement', recipeId: 'cms', capability: 'content' },
137
+ });
138
+ });
139
+ });
@@ -0,0 +1,180 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { z } from 'astro/zod';
3
+ import {
4
+ createRecipeAdmissionSchema, recipeMetadataDescriptorSchema, recipeMetadataJsonSchema,
5
+ recipeMetadataSchema, recipeRegistryManifestSchema,
6
+ } from '../index.js';
7
+ import type { RecipeMetadata, RecipeRegistryPin } from '../index.js';
8
+
9
+ const integrity = `sha512-${'A'.repeat(86)}==`;
10
+ const otherIntegrity = `sha512-${'B'.repeat(86)}==`;
11
+
12
+ function fixture() {
13
+ const generate = vi.fn(() => ({ files: [] }));
14
+ const validate = vi.fn(() => []);
15
+ const recipe = {
16
+ id: 'shell', version: '1.5.0', protocolVersion: 1,
17
+ compatibleCliRange: '^0.1.0', compatibleRuntimeRange: '^1.5.0',
18
+ provides: ['shell'], requires: [], conflicts: [],
19
+ order: { priority: 0, key: 'shell' },
20
+ optionsSchema: z.strictObject({ title: z.string() }),
21
+ outputContributions: [{ kind: 'file', id: 'shell.layout', target: 'src/layouts/Base.astro' }],
22
+ validators: [{ id: 'shell.options', phase: 'options', validate }], generate,
23
+ } satisfies RecipeMetadata<{ title: string }>;
24
+ const pin = {
25
+ packageName: '@easy-web/core', version: '1.5.0', integrity, exportPath: './recipes/shell',
26
+ } satisfies RecipeRegistryPin;
27
+ const artifact = { recipe, receipt: { source: 'bundled', pin, verifiedIntegrity: integrity } };
28
+ const input = { registry: { protocolVersion: 1, recipes: [pin] }, artifacts: [artifact] };
29
+ const schema = createRecipeAdmissionSchema({
30
+ cliVersion: '0.1.0', runtimeVersion: '1.5.0',
31
+ // Bounded fake policy; production semver syntax/satisfaction belongs to todo 4.
32
+ satisfies: (version, range) => range === `^${version}`,
33
+ });
34
+ return { generate, validate, recipe, pin, artifact, input, schema };
35
+ }
36
+
37
+ describe('recipe protocol admission', () => {
38
+ it('admits valid capability combinations without running hooks', () => {
39
+ // Given
40
+ const f = fixture();
41
+ const pin = { ...f.pin, exportPath: './recipes/navigation' };
42
+ const input = {
43
+ registry: { ...f.input.registry, recipes: [f.pin, pin] },
44
+ artifacts: [f.artifact, {
45
+ receipt: { ...f.artifact.receipt, pin },
46
+ recipe: { ...f.recipe, id: 'navigation', provides: ['Linkable'], requires: ['shell'] },
47
+ }],
48
+ };
49
+ // When
50
+ const result = f.schema.safeParse(input);
51
+ // Then
52
+ expect(result.success).toBe(true);
53
+ expect(f.generate).not.toHaveBeenCalled();
54
+ expect(f.validate).not.toHaveBeenCalled();
55
+ });
56
+
57
+ it.each([
58
+ ['duplicate-provider-id', { id: 'navigation', provides: ['shell'], requires: [] }],
59
+ ['missing-requirement', { id: 'navigation', provides: ['Linkable'], requires: ['HasImage'] }],
60
+ ['dependency-cycle', { id: 'navigation', provides: ['Linkable'], requires: ['shell'] }],
61
+ ['conflicting-capability', { id: 'navigation', provides: ['Linkable'], requires: [], conflicts: ['shell'] }],
62
+ ])('rejects %s before generation', (code, patch) => {
63
+ // Given
64
+ const f = fixture();
65
+ const pin = { ...f.pin, exportPath: './recipes/navigation' };
66
+ const input = {
67
+ registry: { ...f.input.registry, recipes: [f.pin, pin] },
68
+ artifacts: [{ ...f.artifact, recipe: {
69
+ ...f.recipe, requires: code === 'dependency-cycle' ? ['Linkable'] : [],
70
+ } }, {
71
+ receipt: { ...f.artifact.receipt, pin }, recipe: { ...f.recipe, ...patch },
72
+ }],
73
+ };
74
+ // When
75
+ const result = f.schema.safeParse(input);
76
+ // Then
77
+ expect(result.success).toBe(false);
78
+ if (!result.success) expect(result.error.issues.map((issue) => issue.message)).toContain(code);
79
+ expect(f.generate).not.toHaveBeenCalled();
80
+ expect(f.validate).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it.each([
84
+ ['protocol version', { protocolVersion: 2 }],
85
+ ['invalid shape', { provides: 'shell' }],
86
+ ['invalid generation hook', { generate: 'direct' }],
87
+ ['invalid option schema', { optionsSchema: {} }],
88
+ ['invalid validator', { validators: [{ id: 'shell.options', phase: 'options', validate: 42 }] }],
89
+ ['CLI compatibility range', { compatibleCliRange: '^9.0.0' }],
90
+ ['runtime compatibility range', { compatibleRuntimeRange: '^2.0.0' }],
91
+ ['invalid semver range', { compatibleRuntimeRange: 'not-semver' }],
92
+ ['artifact version', { version: '1.6.0' }],
93
+ ['self requirement', { requires: ['shell'] }],
94
+ ])('rejects incompatible or malformed %s before generation', (_name, patch) => {
95
+ // Given
96
+ const f = fixture();
97
+ const input = { ...f.input, artifacts: [{ ...f.artifact, recipe: { ...f.recipe, ...patch } }] };
98
+ // When
99
+ const result = f.schema.safeParse(input);
100
+ // Then
101
+ expect(result.success).toBe(false);
102
+ expect(f.generate).not.toHaveBeenCalled();
103
+ expect(f.validate).not.toHaveBeenCalled();
104
+ });
105
+
106
+ it.each([
107
+ ['tampered integrity', { verifiedIntegrity: otherIntegrity }],
108
+ ['target node_modules', { source: 'target-node-modules' }],
109
+ ['third-party package', { pin: { packageName: '@other/recipe' } }],
110
+ ['unregistered first-party package', { pin: { packageName: '@easy-web/unregistered' } }],
111
+ ['non-pinned export', { pin: { exportPath: './recipes/other' } }],
112
+ ['non-pinned version', { pin: { version: '1.6.0' } }],
113
+ ['non-pinned integrity', { pin: { integrity: otherIntegrity }, verifiedIntegrity: otherIntegrity }],
114
+ ])('rejects %s receipts before generation', (_name, patch) => {
115
+ // Given
116
+ const f = fixture();
117
+ const receipt = { ...f.artifact.receipt, ...patch, pin: { ...f.pin, ...patch.pin } };
118
+ // When
119
+ const result = f.schema.safeParse({ ...f.input, artifacts: [{ ...f.artifact, receipt }] });
120
+ // Then
121
+ expect(result.success).toBe(false);
122
+ expect(f.generate).not.toHaveBeenCalled();
123
+ expect(f.validate).not.toHaveBeenCalled();
124
+ });
125
+ });
126
+
127
+ describe('recipe descriptor and registry schemas', () => {
128
+ it('accepts a serializable projection independently of executable metadata', () => {
129
+ // Given
130
+ const f = fixture();
131
+ const descriptor = {
132
+ ...f.recipe, generate: 'direct', optionsSchema: z.toJSONSchema(f.recipe.optionsSchema),
133
+ validators: [{ id: 'shell.options', phase: 'options' }],
134
+ };
135
+ // When
136
+ const result = recipeMetadataDescriptorSchema.safeParse(JSON.parse(JSON.stringify(descriptor)));
137
+ // Then
138
+ expect(result.success).toBe(true);
139
+ expect(recipeMetadataJsonSchema.properties?.['protocolVersion']).toMatchObject({ const: 1 });
140
+ expect(recipeMetadataJsonSchema.additionalProperties).toBe(false);
141
+ });
142
+
143
+ it('keeps the parsed options schema capable of rejecting invalid options', () => {
144
+ // Given
145
+ const f = fixture();
146
+ // When
147
+ const recipe = recipeMetadataSchema.parse(f.recipe);
148
+ // Then
149
+ expect(recipe.optionsSchema.safeParse({ title: 42 }).success).toBe(false);
150
+ expect(recipe.optionsSchema.safeParse({ title: 'Example' }).success).toBe(true);
151
+ });
152
+
153
+ it.each([
154
+ ['range instead of exact version', { version: '^1.5.0' }],
155
+ ['malformed version', { version: '01.5.0' }],
156
+ ['malformed integrity', { integrity: 'sha512-invalid' }],
157
+ ['path traversal', { exportPath: './../recipe' }],
158
+ ['absolute export', { exportPath: 'C:/target/node_modules/recipe' }],
159
+ ])('rejects registry %s', (_name, patch) => {
160
+ // Given
161
+ const f = fixture();
162
+ // When
163
+ const result = recipeRegistryManifestSchema.safeParse({
164
+ ...f.input.registry, recipes: [{ ...f.pin, ...patch }],
165
+ });
166
+ // Then
167
+ expect(result.success).toBe(false);
168
+ });
169
+
170
+ it('rejects ambiguous duplicate pins', () => {
171
+ // Given
172
+ const f = fixture();
173
+ // When
174
+ const result = recipeRegistryManifestSchema.safeParse({
175
+ ...f.input.registry, recipes: [f.pin, { ...f.pin, version: '1.6.0' }],
176
+ });
177
+ // Then
178
+ expect(result.success).toBe(false);
179
+ });
180
+ });