@easy-web/core 1.5.0 → 1.6.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 (120) hide show
  1. package/README.md +42 -1
  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/package.json +17 -1
  90. package/src/components/DemoLegalShell.astro +36 -0
  91. package/src/contracts/__tests__/content-composition.test.ts +170 -0
  92. package/src/contracts/capabilities.ts +49 -0
  93. package/src/contracts/content-composition.ts +176 -0
  94. package/src/contracts/index.ts +2 -0
  95. package/src/contracts/traits.ts +107 -0
  96. package/src/demo/__tests__/demo-content.test.ts +107 -0
  97. package/src/demo/demo-content.ts +210 -0
  98. package/src/demo/index.ts +2 -0
  99. package/src/demo/legal-shells.ts +52 -0
  100. package/src/i18n/__tests__/create-localization.test.ts +138 -0
  101. package/src/i18n/__tests__/explicit-formatters.test.ts +82 -0
  102. package/src/i18n/cli-catalogs.ts +44 -0
  103. package/src/i18n/create-localization.ts +67 -0
  104. package/src/i18n/explicit-formatters.ts +36 -0
  105. package/src/i18n/index.ts +4 -0
  106. package/src/i18n/locale-inputs.ts +73 -0
  107. package/src/index.ts +1 -0
  108. package/src/recipes/__tests__/graph.test.ts +139 -0
  109. package/src/recipes/__tests__/protocol.test.ts +180 -0
  110. package/src/recipes/__tests__/serialize.test.ts +128 -0
  111. package/src/recipes/__tests__/shell-recipe.test.ts +75 -0
  112. package/src/recipes/admission.ts +77 -0
  113. package/src/recipes/graph.ts +244 -0
  114. package/src/recipes/index.ts +8 -0
  115. package/src/recipes/mermaid.ts +75 -0
  116. package/src/recipes/registry.ts +48 -0
  117. package/src/recipes/schema.ts +53 -0
  118. package/src/recipes/serialize.ts +77 -0
  119. package/src/recipes/shell-recipe.ts +162 -0
  120. package/src/recipes/types.ts +63 -0
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ cliUiLocaleSchema, contentLocaleSchema, currencyCodeSchema, formatLocaleSchema,
4
+ ianaTimeZoneSchema, localizationInterviewCatalogs, optionalCurrencyCodeSchema,
5
+ parseCreateLocalization, resolveDetectedCliUiLocale, resolveFormatContext,
6
+ createI18n, UnselectedContentLocaleError,
7
+ } from '../index.js'
8
+
9
+ const input = {
10
+ cliUiLocale: 'en',
11
+ contentLocales: ['de', 'fr'],
12
+ defaultContentLocale: 'de',
13
+ localizedLabels: { de: { contact: 'Kontakt' }, fr: { contact: 'Contact' } },
14
+ localizedPaths: [{ de: '/kontakt/', fr: '/fr/contact/' }],
15
+ formatLocales: { mode: 'shared', locale: 'de-AT' },
16
+ timeZone: 'Europe/Vienna',
17
+ } as const
18
+
19
+ describe('create-time localization', () => {
20
+ it('keeps interview, content, labels/routes, formatting and timezone independent when parsed', () => {
21
+ // Given
22
+ const configuration = input
23
+ // When
24
+ const result = parseCreateLocalization(configuration)
25
+ // Then
26
+ expect(result).toEqual(configuration)
27
+ expect(resolveFormatContext(result, 'fr')).toEqual({ locale: 'de-AT', timeZone: 'Europe/Vienna' })
28
+ })
29
+
30
+ it('uses the existing route convention when passed to createI18n', () => {
31
+ // Given
32
+ const parsed = parseCreateLocalization(input)
33
+ // When
34
+ const links = createI18n({
35
+ locales: parsed.contentLocales, defaultLocale: parsed.defaultContentLocale,
36
+ localizedPaths: parsed.localizedPaths, baseUrl: 'https://example.test',
37
+ }).getAlternateLinks('/kontakt/')
38
+ // Then
39
+ expect(links).toContainEqual({ hreflang: 'fr', href: 'https://example.test/fr/contact/' })
40
+ })
41
+
42
+ it('selects each regional format locale when per-language formatting is selected', () => {
43
+ // Given
44
+ const parsed = parseCreateLocalization({ ...input, formatLocales: { mode: 'per-language', locales: { de: 'de-AT', fr: 'fr-CA' } } })
45
+ // When
46
+ const context = resolveFormatContext(parsed, 'fr')
47
+ // Then
48
+ expect(context).toEqual({ locale: 'fr-CA', timeZone: 'Europe/Vienna' })
49
+ })
50
+
51
+ it.each([
52
+ { contentLocales: [] }, { contentLocales: ['de', 'DE'] }, { defaultContentLocale: 'en' },
53
+ { cliUiLocale: 'fr' }, { timeZone: undefined }, { currency: 'EUR' },
54
+ { formatLocales: { mode: 'shared', locale: '' } },
55
+ { formatLocales: { mode: 'per-language', locales: { de: 'de-DE' } } },
56
+ { formatLocales: { mode: 'per-language', locales: { de: 'de-DE', fr: 'fr-FR', en: 'en-US' } } },
57
+ { localizedLabels: { de: { contact: 'Kontakt' } } },
58
+ { localizedLabels: { de: { contact: 'Kontakt' }, fr: { about: 'À propos' } } },
59
+ { localizedPaths: [{ de: '/kontakt/' }] },
60
+ { localizedPaths: [{ de: '//example.test', fr: '/fr/contact/' }] },
61
+ ])('rejects inconsistent or inferred inputs when given %j', (override) => {
62
+ // Given
63
+ const invalid = { ...input, ...override }
64
+ // When / Then
65
+ expect(() => parseCreateLocalization(invalid)).toThrow()
66
+ })
67
+
68
+ it('rejects an unselected content language when resolving a shared format', () => {
69
+ // Given
70
+ const parsed = parseCreateLocalization(input)
71
+ // When / Then
72
+ expect(() => resolveFormatContext(parsed, 'en')).toThrow(UnselectedContentLocaleError)
73
+ })
74
+ })
75
+
76
+ describe('locale and currency boundaries', () => {
77
+ it.each(['fr', 'zh-Hant-TW', 'sr-Latn-RS', 'es-419', 'de-DE-u-co-phonebk', 'x-site', 'i-klingon'])('accepts arbitrary BCP47 content when given %s', (tag) => {
78
+ // Given / When
79
+ const result = contentLocaleSchema.safeParse(tag)
80
+ // Then
81
+ expect(result.success).toBe(true)
82
+ })
83
+ it.each(['', 'de_DE', 'en--US', 'en-a', 'en-u-ca-gregory-u-nu-latn', 'de-1901-1901', 'not a locale'])('rejects malformed content when given %s', (tag) => {
84
+ // Given / When
85
+ const result = contentLocaleSchema.safeParse(tag)
86
+ // Then
87
+ expect(result.success).toBe(false)
88
+ })
89
+ it.each(['', 'zz-ZZ', 'de_DE'])('rejects unsupported explicit formatting when given %s', (tag) => {
90
+ // Given / When
91
+ const result = formatLocaleSchema.safeParse(tag)
92
+ // Then
93
+ expect(result.success).toBe(false)
94
+ })
95
+ it.each(['', 'Mars/Olympus', '+01:00', 'Europe/Berlin '])('rejects non-IANA timezones when given %s', (zone) => {
96
+ // Given / When
97
+ const result = ianaTimeZoneSchema.safeParse(zone)
98
+ // Then
99
+ expect(result.success).toBe(false)
100
+ })
101
+ it.each(['UTC', 'Europe/Berlin', 'America/New_York', 'Asia/Kathmandu'])('accepts named zones when given %s', (zone) => {
102
+ // Given / When
103
+ const result = ianaTimeZoneSchema.safeParse(zone)
104
+ // Then
105
+ expect(result.success).toBe(true)
106
+ })
107
+ it.each(['EUR', 'USD', 'JPY', 'CHF'])('accepts an explicit ISO currency when given %s', (code) => {
108
+ // Given / When
109
+ const result = currencyCodeSchema.safeParse(code)
110
+ // Then
111
+ expect(result.success).toBe(true)
112
+ })
113
+ it.each(['', 'eur', 'EURO', 'ZZZ', 'XXX'])('rejects malformed or unsupported currencies when given %s', (code) => {
114
+ // Given / When
115
+ const result = currencyCodeSchema.safeParse(code)
116
+ // Then
117
+ expect(result.success).toBe(false)
118
+ })
119
+ it('does not infer currency when the optional primitive is absent', () => {
120
+ // Given / When
121
+ const result = optionalCurrencyCodeSchema.parse(undefined)
122
+ // Then
123
+ expect(result).toBeUndefined()
124
+ })
125
+ it.each([['de-AT', 'de'], ['fr-CA', 'en'], ['bad_tag', 'en'], [undefined, 'en']] as const)('falls back safely when auto-detected UI locale is %s', (detected, expected) => {
126
+ // Given / When
127
+ const result = resolveDetectedCliUiLocale(detected)
128
+ // Then
129
+ expect(result).toBe(expected)
130
+ expect(Object.keys(localizationInterviewCatalogs[result])).toEqual(Object.keys(localizationInterviewCatalogs.en))
131
+ })
132
+ it('rejects unsupported UI input rather than applying detection fallback when explicit', () => {
133
+ // Given / When
134
+ const result = cliUiLocaleSchema.safeParse('fr')
135
+ // Then
136
+ expect(result.success).toBe(false)
137
+ })
138
+ })
@@ -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
+ });