@thorprovider/storefront 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +621 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +346 -38
  11. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +26 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +18 -0
  16. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  17. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  18. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  21. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  33. package/assets/templates/features/checkout/handlers.ts +24 -4
  34. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  35. package/assets/templates/features/customer-addresses/state.ts +33 -0
  36. package/assets/templates/features/customer-auth/state.ts +10 -0
  37. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  38. package/assets/templates/features/customer-profile/state.ts +18 -0
  39. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  40. package/assets/templates/views/account/assembly/assembly.json +41 -0
  41. package/assets/templates/views/account/assembly/index.skeleton.tsx +229 -0
  42. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1116 -0
  43. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  44. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  45. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  46. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  50. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +5 -0
  51. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +1 -0
  53. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  56. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  63. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  67. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  70. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  73. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  76. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  79. package/assets/templates/views/account/content.ts +326 -0
  80. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  81. package/assets/templates/views/account/index.tsx +218 -35
  82. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  83. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  84. package/assets/templates/views/account/orders-advanced.client.tsx +166 -0
  85. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  86. package/assets/templates/views/account/registry.tsx +944 -369
  87. package/assets/templates/views/account/schema.ts +50 -0
  88. package/assets/templates/views/account/sections-data.ts +2 -0
  89. package/assets/templates/views/cart/content.ts +1 -0
  90. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  91. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  92. package/assets/templates/views/category/content.ts +2 -0
  93. package/assets/templates/views/category/index.tsx +2 -0
  94. package/assets/templates/views/category/sections-data.ts +2 -0
  95. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  96. package/assets/templates/views/checkout/content.ts +51 -0
  97. package/assets/templates/views/checkout/index.tsx +1 -1
  98. package/assets/templates/views/checkout/props.ts +10 -2
  99. package/assets/templates/views/checkout/registry.tsx +104 -42
  100. package/assets/templates/views/checkout/schema.ts +76 -1
  101. package/assets/templates/views/home/assembly/assembly.json +22 -1
  102. package/assets/templates/views/home/assembly/index.skeleton.tsx +1 -0
  103. package/assets/templates/views/home/content.ts +2 -0
  104. package/assets/templates/views/home/index.tsx +1 -0
  105. package/assets/templates/views/home/sections-data.ts +2 -0
  106. package/assets/templates/views/product/content.ts +1 -0
  107. package/assets/templates/views/static/content.ts +1 -0
  108. package/bin/storefront.js +343 -13
  109. package/package.json +2 -1
  110. package/recipes/adapter-surface.json +158 -0
  111. package/recipes/archetypes.json +38 -3
  112. package/recipes/catalog.json +138 -1
  113. package/recipes/feature.schema.json +9 -0
  114. package/recipes/features.json +72 -1
  115. package/recipes/manifest.schema.json +5 -0
  116. package/recipes/recipe.schema.json +13 -1
  117. package/recipes/recipes.json +34 -5
  118. package/recipes/section.schema.json +112 -0
  119. package/recipes/sections.json +281 -4
  120. package/recipes/validate.mjs +83 -1
  121. package/scripts/adapter-surface.mjs +41 -0
  122. package/scripts/agent-blocks.mjs +700 -0
  123. package/scripts/block-validator.mjs +45 -0
  124. package/scripts/candidate.mjs +5 -4
  125. package/scripts/composers.mjs +7 -2
  126. package/scripts/default-sections.mjs +78 -0
  127. package/scripts/file-classes.mjs +14 -0
  128. package/scripts/generate-adapter-surface.mjs +148 -0
  129. package/scripts/operations.mjs +100 -0
  130. package/scripts/reconcile.mjs +67 -39
  131. package/scripts/section-configure.mjs +316 -0
  132. package/scripts/sync-assets.mjs +1 -0
  133. package/scripts/view-assembly.mjs +101 -14
  134. package/skills/sf-feature/SKILL.md +19 -0
  135. package/skills/sf-view-gen/SKILL.md +73 -7
  136. package/skills/sf-view-gen/assets/recipes/archetypes.json +38 -3
  137. package/skills/sf-view-gen/assets/recipes/catalog.json +138 -1
  138. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  139. package/skills/sf-view-gen/assets/recipes/recipes.json +34 -5
  140. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  141. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  142. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  143. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  144. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  145. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  146. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  147. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  148. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  149. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  150. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  151. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -0,0 +1,700 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { lstat, readFile } from 'node:fs/promises'
3
+ import { relative, resolve, sep } from 'node:path'
4
+ import { loadRecipes, loadSections } from '../recipes/validate.mjs'
5
+ import { resolveBlockValidator } from './block-validator.mjs'
6
+ import { validateAgainstSchema } from './schema-validate.mjs'
7
+ import { isEditorialSectionEntry } from './section-compat.mjs'
8
+
9
+ const EXEMPTION_KINDS = new Set([
10
+ 'pending-card',
11
+ 'host-only',
12
+ 'requiresPort',
13
+ 'not-user-configurable',
14
+ 'internal',
15
+ ])
16
+ const FIELD_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array', 'enum'])
17
+ const SURFACE_KINDS = new Set(['section', 'shell', 'route', 'feature'])
18
+ const SECTION_SCHEMA = JSON.parse(
19
+ readFileSync(new URL('../recipes/section.schema.json', import.meta.url), 'utf8'),
20
+ )
21
+
22
+ function isObject(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
24
+ }
25
+
26
+ function nonEmptyString(value) {
27
+ return typeof value === 'string' && value.trim().length > 0
28
+ }
29
+
30
+ function isRouteOnlyCard(card) {
31
+ return Array.isArray(card?.surfaces) && card.surfaces.length > 0 &&
32
+ card.surfaces.every((surface) => surface?.kind === 'route')
33
+ }
34
+
35
+ function registryEntries(sections) {
36
+ if (Array.isArray(sections)) return sections
37
+ return isObject(sections) && Array.isArray(sections.sections) ? sections.sections : []
38
+ }
39
+
40
+ function makeSectionsById(entries) {
41
+ return new Map(
42
+ entries
43
+ .filter((entry) => isObject(entry) && nonEmptyString(entry.name))
44
+ .map((entry) => [entry.name, entry]),
45
+ )
46
+ }
47
+
48
+ function mapHas(map, key) {
49
+ return map instanceof Map
50
+ ? map.has(key)
51
+ : isObject(map) && Object.prototype.hasOwnProperty.call(map, key)
52
+ }
53
+
54
+ function isIsoDate(value) {
55
+ if (!nonEmptyString(value)) return false
56
+ if (!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2}))?$/.test(value)) {
57
+ return false
58
+ }
59
+ const [year, month, day] = value.slice(0, 10).split('-').map(Number)
60
+ const calendarDate = new Date(Date.UTC(year, month - 1, day))
61
+ if (
62
+ calendarDate.getUTCFullYear() !== year ||
63
+ calendarDate.getUTCMonth() !== month - 1 ||
64
+ calendarDate.getUTCDate() !== day
65
+ ) {
66
+ return false
67
+ }
68
+ return Number.isFinite(Date.parse(value))
69
+ }
70
+
71
+ /**
72
+ * Validate both the section schema and the semantic rules the schema cannot
73
+ * express. `sections` may be the full registry document or its entry array;
74
+ * `sectionsById` is the authoritative set of known section names when supplied;
75
+ * `clock` makes exemption-expiry checks deterministic in tests and callers;
76
+ * `schema` lets tests inject a focused section-registry schema.
77
+ */
78
+ export function validateSectionRegistry(sections, {
79
+ sectionsById,
80
+ clock = () => new Date(),
81
+ schema = SECTION_SCHEMA,
82
+ } = {}) {
83
+ const entries = registryEntries(sections)
84
+ const errors = []
85
+ const knownSections = sectionsById ?? makeSectionsById(entries)
86
+ const addError = (section, path, message, code = 'E_AGENT_CARD_INVALID') =>
87
+ errors.push({ code, section, path, message })
88
+
89
+ if (!Array.isArray(sections) && (!isObject(sections) || !Array.isArray(sections.sections))) {
90
+ addError('<registry>', 'sections', 'The section registry must contain a sections array.')
91
+ }
92
+
93
+ const schemaDocument = Array.isArray(sections)
94
+ ? { version: '1.0.0', description: 'Section registry entries', sections }
95
+ : sections
96
+ for (const message of validateAgainstSchema(schemaDocument, schema)) {
97
+ const path = /^(.*?) (?:must|is missing|has unknown|uses) /.exec(message)?.[1] ?? '<schema>'
98
+ const sectionIndex = /^sections\[(\d+)\](?:\.|$)/.exec(path)?.[1]
99
+ const index = sectionIndex === undefined ? -1 : Number(sectionIndex)
100
+ const entry = index >= 0 ? entries[index] : undefined
101
+ const section = isObject(entry) && nonEmptyString(entry.name) ? entry.name : '<registry>'
102
+ addError(section, path, message, 'E_AGENT_CARD_INVALID')
103
+ }
104
+
105
+ entries.forEach((entry, index) => {
106
+ const sectionName = isObject(entry) && nonEmptyString(entry.name) ? entry.name : `<section-${index}>`
107
+ const base = `sections[${index}]`
108
+ if (!isObject(entry)) {
109
+ addError(sectionName, base, 'A section entry must be an object.')
110
+ return
111
+ }
112
+
113
+ if (entry.status !== 'executable' && entry.status !== 'held') {
114
+ addError(sectionName, `${base}.status`, 'Section status must be executable or held.')
115
+ }
116
+
117
+ if (entry.status !== 'executable') return
118
+
119
+ const card = entry.agent
120
+ if (!isObject(card)) {
121
+ addError(sectionName, `${base}.agent`, 'Executable sections need a ready card or an exemption.', 'E_AGENT_CARD_MISSING')
122
+ return
123
+ }
124
+
125
+ const cardBase = `${base}.agent`
126
+ if (!['ready', 'pending', 'exempt'].includes(card.status)) {
127
+ addError(sectionName, `${cardBase}.status`, 'Agent status must be ready, pending, or exempt.')
128
+ }
129
+
130
+ const requiredIdentityString = (field) => {
131
+ if (!nonEmptyString(card[field])) {
132
+ addError(sectionName, `${cardBase}.${field}`, `An agent card needs a non-empty ${field}.`)
133
+ }
134
+ }
135
+ requiredIdentityString('section')
136
+ requiredIdentityString('elementType')
137
+ if (nonEmptyString(card.section)) {
138
+ if (!mapHas(knownSections, card.section)) {
139
+ addError(sectionName, `${cardBase}.section`, `Unknown agent-card section "${card.section}".`, 'E_AGENT_CARD_STALE')
140
+ }
141
+ if (card.section !== entry.name) {
142
+ addError(sectionName, `${cardBase}.section`, `Card section must match registry name "${entry.name}".`, 'E_AGENT_CARD_STALE')
143
+ }
144
+ }
145
+ if (nonEmptyString(card.elementType) && card.elementType !== entry.elementType) {
146
+ addError(sectionName, `${cardBase}.elementType`, `Card elementType must match "${entry.elementType}".`, 'E_AGENT_CARD_STALE')
147
+ }
148
+ if (!Array.isArray(card.variants) || card.variants.length === 0) {
149
+ addError(sectionName, `${cardBase}.variants`, 'An agent card needs a non-empty variants array.')
150
+ } else {
151
+ if (card.variants.some((variant) => !nonEmptyString(variant))) {
152
+ addError(sectionName, `${cardBase}.variants`, 'Card variants must be non-empty strings.')
153
+ }
154
+ if (JSON.stringify(card.variants) !== JSON.stringify(entry.variants)) {
155
+ addError(sectionName, `${cardBase}.variants`, 'Card variants must match the registry variants.', 'E_AGENT_CARD_STALE')
156
+ }
157
+ }
158
+
159
+ if (card.status === 'pending' || card.status === 'exempt') {
160
+ if (!EXEMPTION_KINDS.has(card.kind)) {
161
+ addError(sectionName, `${cardBase}.kind`, 'Exemption kind must be a known agent-card kind.', 'E_AGENT_EXEMPTION_INVALID')
162
+ }
163
+ if (!nonEmptyString(card.reason)) {
164
+ addError(sectionName, `${cardBase}.reason`, 'An exemption needs a non-empty reason.', 'E_AGENT_EXEMPTION_INVALID')
165
+ }
166
+ if (!nonEmptyString(card.owner)) {
167
+ addError(sectionName, `${cardBase}.owner`, 'An exemption needs a non-empty owner.', 'E_AGENT_EXEMPTION_INVALID')
168
+ }
169
+ if (card.expires !== undefined && !isIsoDate(card.expires)) {
170
+ addError(sectionName, `${cardBase}.expires`, 'Exemption expiry must be an ISO date or timestamp.', 'E_AGENT_EXEMPTION_INVALID')
171
+ } else if (card.expires !== undefined && Date.parse(card.expires) <= clock().getTime()) {
172
+ addError(sectionName, `${cardBase}.expires`, 'Exemption has expired.', 'E_AGENT_EXEMPTION_EXPIRED')
173
+ }
174
+ return
175
+ }
176
+
177
+ const requiredString = (field) => {
178
+ if (!nonEmptyString(card[field])) {
179
+ addError(sectionName, `${cardBase}.${field}`, `A ready card needs a non-empty ${field}.`)
180
+ }
181
+ }
182
+ requiredString('label')
183
+ requiredString('purpose')
184
+
185
+ for (const field of ['useWhen', 'avoidWhen']) {
186
+ if (!Array.isArray(card[field]) || card[field].length === 0) {
187
+ addError(sectionName, `${cardBase}.${field}`, `A ready card needs a non-empty ${field} array.`)
188
+ } else if (card[field].some((item) => !nonEmptyString(item))) {
189
+ addError(sectionName, `${cardBase}.${field}`, `${field} entries must be non-empty strings.`)
190
+ }
191
+ }
192
+
193
+ if (!Array.isArray(card.surfaces) || card.surfaces.length === 0) {
194
+ addError(sectionName, `${cardBase}.surfaces`, 'A ready card needs at least one surface.')
195
+ } else {
196
+ card.surfaces.forEach((surface, surfaceIndex) => {
197
+ const path = `${cardBase}.surfaces[${surfaceIndex}]`
198
+ if (!isObject(surface) || !SURFACE_KINDS.has(surface.kind)) {
199
+ addError(sectionName, `${path}.kind`, 'Surface kind must be section, shell, route, or feature.')
200
+ }
201
+ if (!Array.isArray(surface?.hosts) || surface.hosts.length === 0 || surface.hosts.some((host) => !nonEmptyString(host))) {
202
+ addError(sectionName, `${path}.hosts`, 'A surface needs a non-empty hosts array.')
203
+ }
204
+ })
205
+ }
206
+
207
+ if (typeof card.editable !== 'boolean') {
208
+ addError(sectionName, `${cardBase}.editable`, 'A ready card needs an editable boolean.')
209
+ }
210
+
211
+ if (!Array.isArray(card.fields) || card.fields.length === 0) {
212
+ addError(sectionName, `${cardBase}.fields`, 'A ready card needs at least one field definition.')
213
+ } else {
214
+ card.fields.forEach((field, fieldIndex) => {
215
+ const path = `${cardBase}.fields[${fieldIndex}]`
216
+ if (!isObject(field)) {
217
+ addError(sectionName, path, 'Field definitions must be objects.')
218
+ return
219
+ }
220
+ for (const key of ['path', 'description']) {
221
+ if (!nonEmptyString(field[key])) addError(sectionName, `${path}.${key}`, `Field ${key} must be non-empty.`)
222
+ }
223
+ if (!FIELD_TYPES.has(field.type)) addError(sectionName, `${path}.type`, 'Field type must be a supported field type.')
224
+ if (typeof field.required !== 'boolean') addError(sectionName, `${path}.required`, 'Field required must be a boolean.')
225
+ })
226
+ }
227
+
228
+ if (!Array.isArray(card.hostOnly)) {
229
+ addError(sectionName, `${cardBase}.hostOnly`, 'A ready card needs a hostOnly array.')
230
+ } else {
231
+ card.hostOnly.forEach((field, fieldIndex) => {
232
+ const path = `${cardBase}.hostOnly[${fieldIndex}]`
233
+ if (!isObject(field)) {
234
+ addError(sectionName, path, 'Host-only declarations must be objects.')
235
+ return
236
+ }
237
+ for (const key of ['path', 'reason']) {
238
+ if (!nonEmptyString(field[key])) addError(sectionName, `${path}.${key}`, `Host-only ${key} must be non-empty.`)
239
+ }
240
+ })
241
+ }
242
+
243
+ if (!Array.isArray(card.examples) || card.examples.length === 0) {
244
+ addError(sectionName, `${cardBase}.examples`, 'A ready card needs at least one example.')
245
+ } else {
246
+ card.examples.forEach((example, exampleIndex) => {
247
+ const path = `${cardBase}.examples[${exampleIndex}]`
248
+ if (!isObject(example)) {
249
+ addError(sectionName, path, 'Examples must be objects.')
250
+ return
251
+ }
252
+ for (const key of ['name', 'description']) {
253
+ if (!nonEmptyString(example[key])) addError(sectionName, `${path}.${key}`, `Example ${key} must be non-empty.`)
254
+ }
255
+ if (!isObject(example.data)) addError(sectionName, `${path}.data`, 'Example data must be a validator input object.')
256
+ })
257
+ }
258
+
259
+ if (!isObject(card.validator) || !nonEmptyString(card.validator.export)) {
260
+ if (!isRouteOnlyCard(card)) {
261
+ addError(
262
+ sectionName,
263
+ `${cardBase}.validator.export`,
264
+ 'A ready card needs a validator export unless every surface is a route.',
265
+ )
266
+ }
267
+ }
268
+ })
269
+
270
+ return { ok: errors.length === 0, errors }
271
+ }
272
+
273
+ export function loadAgentBlocks({ recipes = loadRecipes(), sections = loadSections(), manifest } = {}) {
274
+ const normalizedManifest = !isObject(manifest)
275
+ ? { views: [] }
276
+ : Array.isArray(manifest.views) && manifest.views.every((view) =>
277
+ isObject(view) && Array.isArray(view.sections),
278
+ )
279
+ ? manifest
280
+ : {
281
+ ...manifest,
282
+ views: Array.isArray(manifest.views)
283
+ ? manifest.views.filter(isObject).map((view) => ({
284
+ ...view,
285
+ sections: Array.isArray(view.sections) ? view.sections.filter(isObject) : [],
286
+ }))
287
+ : [],
288
+ }
289
+ const entries = registryEntries(sections)
290
+ return {
291
+ recipes,
292
+ sections,
293
+ manifest: normalizedManifest,
294
+ entries,
295
+ cards: entries
296
+ .filter((entry) => entry?.status === 'executable' && isObject(entry.agent))
297
+ .map((entry) => ({ section: entry.name, ...entry.agent })),
298
+ }
299
+ }
300
+
301
+ export function listAgentBlocks(options = {}) {
302
+ const { entries, recipes, manifest } = loadAgentBlocks(options)
303
+ const hasInstalledManifest = isObject(options.manifest)
304
+ const installedViews = new Set(manifest.views.map((view) => view.name))
305
+ const recipeByName = new Map((recipes?.views ?? []).map((recipe) => [recipe.name, recipe]))
306
+ const blocks = []
307
+ const unavailable = []
308
+
309
+ for (const entry of entries) {
310
+ if (entry?.status !== 'executable' || !isObject(entry.agent)) continue
311
+ const card = entry.agent
312
+ const allowedHosts = hasInstalledManifest
313
+ ? manifest.views
314
+ .filter((view) => installedViews.has(view.name))
315
+ .filter((view) => recipeByName.get(view.name)?.allowedSections?.includes(entry.name))
316
+ .map((view) => view.name)
317
+ : (recipes?.views ?? [])
318
+ .filter((recipe) => recipe.allowedSections?.includes(entry.name))
319
+ .map((recipe) => recipe.name)
320
+
321
+ if (card.status === 'ready') {
322
+ const routeOnly = isRouteOnlyCard(card)
323
+ const hosts = [...new Set(
324
+ (card.surfaces ?? [])
325
+ .filter((surface) => surface?.kind === (routeOnly ? 'route' : 'section') && Array.isArray(surface.hosts))
326
+ .flatMap((surface) => surface.hosts)
327
+ .filter((host) => routeOnly || allowedHosts.includes(host)),
328
+ )]
329
+ if (hosts.length === 0) continue
330
+ blocks.push({
331
+ section: card.section,
332
+ label: card.label,
333
+ purpose: card.purpose,
334
+ useWhen: card.useWhen,
335
+ avoidWhen: card.avoidWhen,
336
+ hosts,
337
+ ...(routeOnly ? { surfaceKind: 'route', host: hosts[0] } : {}),
338
+ variants: card.variants,
339
+ editable: card.editable,
340
+ ...(!routeOnly ? { validator: card.validator?.export } : {}),
341
+ })
342
+ } else if (hasInstalledManifest && ['pending', 'exempt'].includes(card.status) && allowedHosts.length > 0) {
343
+ unavailable.push({
344
+ section: card.section,
345
+ status: card.status,
346
+ kind: card.kind,
347
+ reason: card.reason,
348
+ owner: card.owner,
349
+ })
350
+ }
351
+ }
352
+
353
+ Object.defineProperties(blocks, {
354
+ blocks: { value: blocks },
355
+ unavailable: { value: unavailable },
356
+ })
357
+ return blocks
358
+ }
359
+
360
+ export function showAgentBlock(type, options = {}) {
361
+ if (!nonEmptyString(type)) return null
362
+ const { entries, manifest } = loadAgentBlocks(options)
363
+ const entry = entries.find((candidate) =>
364
+ candidate?.name === type || candidate?.elementType === type || candidate?.agent?.section === type,
365
+ )
366
+ if (!entry) return null
367
+
368
+ const card = entry.agent
369
+ if (entry.status !== 'executable') {
370
+ return {
371
+ section: entry.name,
372
+ elementType: entry.elementType,
373
+ status: 'held',
374
+ reason: entry.reason,
375
+ selectable: false,
376
+ }
377
+ }
378
+ if (!isObject(card)) return null
379
+ if (card.status !== 'ready') {
380
+ if (options.includeUnavailable !== true) return null
381
+ return {
382
+ section: card.section,
383
+ elementType: card.elementType,
384
+ status: card.status,
385
+ kind: card.kind,
386
+ reason: card.reason,
387
+ owner: card.owner,
388
+ variants: card.variants,
389
+ selectable: false,
390
+ }
391
+ }
392
+
393
+ const routeOnly = isRouteOnlyCard(card)
394
+ const instances = routeOnly ? [] : manifest.views.flatMap((view) =>
395
+ view.sections
396
+ .filter((section) => isEditorialSectionEntry(section) && section.type === card.section)
397
+ .map((section) => ({
398
+ id: section.id,
399
+ view: view.name,
400
+ ...(section.variant === undefined ? {} : { variant: section.variant }),
401
+ })),
402
+ )
403
+ const hosts = [...new Set((card.surfaces ?? [])
404
+ .filter((surface) => surface?.kind === (routeOnly ? 'route' : 'section') && Array.isArray(surface.hosts))
405
+ .flatMap((surface) => surface.hosts))]
406
+ return {
407
+ section: card.section,
408
+ elementType: card.elementType,
409
+ status: card.status,
410
+ label: card.label,
411
+ purpose: card.purpose,
412
+ useWhen: card.useWhen,
413
+ avoidWhen: card.avoidWhen,
414
+ surfaces: card.surfaces,
415
+ hosts,
416
+ ...(routeOnly ? { surfaceKind: 'route', ...(hosts[0] ? { host: hosts[0] } : {}) } : {}),
417
+ variants: card.variants,
418
+ editable: card.editable,
419
+ fields: card.fields,
420
+ hostOnly: card.hostOnly,
421
+ examples: card.examples,
422
+ ...(!routeOnly ? { validator: card.validator?.export } : {}),
423
+ instances,
424
+ }
425
+ }
426
+
427
+ export function checkAgentBlocks(options = {}) {
428
+ const { sections, entries } = loadAgentBlocks(options)
429
+ const sectionsById = options.sectionsById ?? makeSectionsById(entries)
430
+ const validation = validateSectionRegistry(sections, {
431
+ sectionsById,
432
+ clock: options.clock,
433
+ schema: options.schema,
434
+ })
435
+ const summary = { ready: 0, pending: 0, exempt: 0 }
436
+ const exemptions = []
437
+ for (const entry of entries) {
438
+ if (entry?.status !== 'executable') continue
439
+ const status = entry.agent?.status
440
+ if (status === 'ready' || status === 'pending' || status === 'exempt') summary[status]++
441
+ if (status === 'pending' || status === 'exempt') {
442
+ exemptions.push({
443
+ section: entry.name,
444
+ status,
445
+ kind: entry.agent.kind,
446
+ owner: entry.agent.owner,
447
+ reason: entry.agent.reason,
448
+ })
449
+ }
450
+ }
451
+ return { ...validation, summary, exemptions }
452
+ }
453
+
454
+ async function validatorStatus(projectDir, exportName) {
455
+ const resolved = await resolveBlockValidator(projectDir, exportName)
456
+ if (resolved.ok) return 'available'
457
+ return ['package-missing', 'subpath-missing', 'export-missing'].includes(resolved.error.reason)
458
+ ? 'missing'
459
+ : 'invalid'
460
+ }
461
+
462
+ async function addValidatorStatus(projectDir, card) {
463
+ if (card.surfaceKind === 'route') return card
464
+ return { ...card, validatorStatus: await validatorStatus(projectDir, card.validator) }
465
+ }
466
+
467
+ export async function listAgentBlocksWithValidatorStatus(options, projectDir) {
468
+ const projection = listAgentBlocks(options)
469
+ const withStatus = await Promise.all(
470
+ projection.blocks.map((card) => addValidatorStatus(projectDir, card)),
471
+ )
472
+ projection.blocks.splice(0, projection.blocks.length, ...withStatus)
473
+ return projection
474
+ }
475
+
476
+ export async function showAgentBlockWithValidatorStatus(type, options, projectDir) {
477
+ const card = showAgentBlock(type, options)
478
+ if (!card || card.status !== 'ready') return card
479
+ return addValidatorStatus(projectDir, card)
480
+ }
481
+
482
+ export async function checkAgentBlocksWithValidatorStatus(options, projectDir) {
483
+ const result = checkAgentBlocks(options)
484
+ const { entries } = loadAgentBlocks(options)
485
+ const validatorResolver = options?.validatorResolver ?? resolveBlockValidator
486
+ const errors = [...result.errors]
487
+ const validators = []
488
+ const examples = []
489
+
490
+ for (const entry of entries) {
491
+ if (entry?.status !== 'executable' || entry.agent?.status !== 'ready') continue
492
+ const card = entry.agent
493
+ if (isRouteOnlyCard(card)) continue
494
+ const exportName = card.validator?.export
495
+ let resolved
496
+ try {
497
+ resolved = await validatorResolver(projectDir, exportName)
498
+ } catch (error) {
499
+ resolved = { ok: false, error: { message: error instanceof Error ? error.message : String(error) } }
500
+ }
501
+
502
+ const available = resolved?.ok === true && typeof resolved.validate === 'function'
503
+ const unavailableReason = resolved?.error?.message ?? `Validator export "${String(exportName)}" is unavailable.`
504
+ const status = available
505
+ ? 'available'
506
+ : ['package-missing', 'subpath-missing', 'export-missing'].includes(resolved?.error?.reason)
507
+ ? 'missing'
508
+ : 'invalid'
509
+ validators.push({ section: entry.name, validator: exportName, status, ...(available ? {} : { message: unavailableReason }) })
510
+
511
+ if (!available) {
512
+ errors.push({
513
+ code: 'E_BLOCK_VALIDATOR_UNAVAILABLE',
514
+ section: entry.name,
515
+ path: 'agent.validator',
516
+ message: unavailableReason,
517
+ })
518
+ for (const [index] of (Array.isArray(card.examples) ? card.examples : []).entries()) {
519
+ examples.push({ section: entry.name, index, status: 'unavailable' })
520
+ }
521
+ continue
522
+ }
523
+
524
+ for (const [index, example] of (Array.isArray(card.examples) ? card.examples : []).entries()) {
525
+ const exampleErrors = []
526
+ let validation
527
+ try {
528
+ validation = await resolved.validate(example?.data)
529
+ } catch {
530
+ exampleErrors.push({ path: '', message: 'The validator threw while validating this example.' })
531
+ }
532
+ if (exampleErrors.length === 0 && validation?.ok !== true) {
533
+ const details = Array.isArray(validation?.errors) && validation.errors.length > 0
534
+ ? validation.errors
535
+ : [{ path: '', message: 'The validator rejected this example.' }]
536
+ for (const detail of details) {
537
+ const validatorPath = isObject(detail) && typeof detail.path === 'string' ? detail.path : ''
538
+ const suffix = validatorPath.replace(/^\$\.?/, '').replace(/^\.+/, '')
539
+ exampleErrors.push({
540
+ path: suffix,
541
+ message: isObject(detail) && nonEmptyString(detail.message)
542
+ ? detail.message
543
+ : 'The validator rejected this example.',
544
+ })
545
+ }
546
+ }
547
+ examples.push({ section: entry.name, index, status: exampleErrors.length === 0 ? 'valid' : 'invalid' })
548
+ for (const detail of exampleErrors) {
549
+ errors.push({
550
+ code: 'E_AGENT_EXAMPLE_INVALID',
551
+ section: entry.name,
552
+ path: `agent.examples[${index}].data${detail.path ? `.${detail.path}` : ''}`,
553
+ message: detail.message,
554
+ })
555
+ }
556
+ }
557
+ }
558
+
559
+ return { ...result, ok: errors.length === 0, errors, validators, examples }
560
+ }
561
+
562
+ function safeSidecarSegment(value) {
563
+ return typeof value === 'string' && value.trim().length > 0 && value !== '.' && value !== '..' &&
564
+ !value.includes('..') && !value.includes('/') && !value.includes('\\') && !value.startsWith('slot:')
565
+ }
566
+
567
+ function sidecarDiagnostic(code, file, instanceId, path, message) {
568
+ return { code, severity: 'error', file, instanceId, path, message }
569
+ }
570
+
571
+ async function inspectSidecarDirectory(projectRoot, manifestName, viewName) {
572
+ let current = projectRoot
573
+ for (const segment of ['lib', manifestName, 'views', viewName, 'sections']) {
574
+ current = resolve(current, segment)
575
+ try {
576
+ const stat = await lstat(current)
577
+ if (!stat.isDirectory()) return { invalid: true }
578
+ } catch (error) {
579
+ if (error?.code === 'ENOENT') return { missing: true }
580
+ throw error
581
+ }
582
+ }
583
+ return { ready: true }
584
+ }
585
+
586
+ /**
587
+ * Validate existing user-owned section sidecars without modifying the project.
588
+ * Only ready editorial cards are audited; absent sidecars use the renderer's
589
+ * content/default fallback and are intentionally not diagnostics.
590
+ */
591
+ export async function auditSectionSidecars({
592
+ dir,
593
+ manifest,
594
+ validatorResolver = resolveBlockValidator,
595
+ } = {}) {
596
+ if (!manifest || typeof manifest !== 'object' || !Array.isArray(manifest.views)) {
597
+ return { diagnostics: [] }
598
+ }
599
+ if (!safeSidecarSegment(manifest.name)) return { diagnostics: [] }
600
+
601
+ const projectRoot = resolve(dir ?? '.')
602
+ const entries = registryEntries(loadSections())
603
+ const sectionsByName = new Map(entries.map((entry) => [entry?.name, entry]))
604
+ const validators = new Map()
605
+ const diagnostics = []
606
+
607
+ for (const view of manifest.views) {
608
+ if (!isObject(view) || !safeSidecarSegment(view.name) || !Array.isArray(view.sections)) continue
609
+ for (const instance of view.sections) {
610
+ if (!isEditorialSectionEntry(instance) || !safeSidecarSegment(instance.id)) continue
611
+ const card = sectionsByName.get(instance.type)?.agent
612
+ if (card?.status !== 'ready' || isRouteOnlyCard(card)) continue
613
+
614
+ let directory
615
+ try {
616
+ directory = await inspectSidecarDirectory(projectRoot, manifest.name, view.name)
617
+ } catch {
618
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', `lib/${manifest.name}/views/${view.name}/sections/${instance.id}.json`, instance.id, '$', 'Could not inspect the section sidecar directory.'))
619
+ continue
620
+ }
621
+ const sidecarPath = resolve(projectRoot, 'lib', manifest.name, 'views', view.name, 'sections', `${instance.id}.json`)
622
+ const file = relative(projectRoot, sidecarPath).split(sep).join('/')
623
+ if (directory.invalid) {
624
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, '$', 'Section sidecar directory must be a regular directory.'))
625
+ continue
626
+ }
627
+ if (directory.missing) {
628
+ continue
629
+ }
630
+ let stat
631
+ try {
632
+ stat = await lstat(sidecarPath)
633
+ } catch (error) {
634
+ if (error?.code === 'ENOENT') continue
635
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, '$', 'Could not inspect the section sidecar.'))
636
+ continue
637
+ }
638
+ if (!stat.isFile()) {
639
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, '$', 'Section sidecar must be a regular file.'))
640
+ continue
641
+ }
642
+
643
+ let parsed
644
+ try {
645
+ parsed = JSON.parse(await readFile(sidecarPath, 'utf8'))
646
+ } catch {
647
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, '$', 'Section sidecar is not valid JSON.'))
648
+ continue
649
+ }
650
+ if (!isObject(parsed) || !Object.prototype.hasOwnProperty.call(parsed, 'data')) {
651
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, 'data', 'Section sidecar must contain a data property.'))
652
+ continue
653
+ }
654
+
655
+ const exportName = card.validator?.export
656
+ if (!validators.has(exportName)) {
657
+ try {
658
+ validators.set(exportName, await validatorResolver(projectRoot, exportName))
659
+ } catch (error) {
660
+ validators.set(exportName, { ok: false, error })
661
+ }
662
+ }
663
+ const resolved = validators.get(exportName)
664
+ if (resolved?.ok !== true || typeof resolved.validate !== 'function') {
665
+ diagnostics.push(sidecarDiagnostic(
666
+ 'E_BLOCK_VALIDATOR_UNAVAILABLE',
667
+ file,
668
+ instance.id,
669
+ 'validator',
670
+ resolved?.error?.message ?? `Validator export "${String(exportName)}" is unavailable.`,
671
+ ))
672
+ continue
673
+ }
674
+
675
+ let validation
676
+ try {
677
+ validation = await resolved.validate(parsed.data)
678
+ } catch {
679
+ diagnostics.push(sidecarDiagnostic('E_SECTION_DATA_INVALID', file, instance.id, '$', 'The section data validator failed.'))
680
+ continue
681
+ }
682
+ if (validation?.ok === true) continue
683
+ const errors = Array.isArray(validation?.errors) && validation.errors.length > 0
684
+ ? validation.errors
685
+ : [{ path: '$', message: 'The section data validator rejected this data.' }]
686
+ for (const error of errors) {
687
+ const detail = isObject(error) ? error : {}
688
+ diagnostics.push(sidecarDiagnostic(
689
+ 'E_SECTION_DATA_INVALID',
690
+ file,
691
+ instance.id,
692
+ typeof detail.path === 'string' ? detail.path : '$',
693
+ typeof detail.message === 'string' ? detail.message : 'The section data validator rejected this data.',
694
+ ))
695
+ }
696
+ }
697
+ }
698
+
699
+ return { diagnostics }
700
+ }