@thorprovider/storefront 0.7.0 → 0.10.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 (164) 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 +677 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +477 -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__/fulfillment-evidence-port.ts +31 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +21 -4
  15. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +6 -2
  16. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +642 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +25 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +28 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  21. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  22. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  37. package/assets/templates/features/checkout/handlers.ts +24 -4
  38. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  39. package/assets/templates/features/customer-addresses/state.ts +33 -0
  40. package/assets/templates/features/customer-auth/state.ts +10 -0
  41. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  42. package/assets/templates/features/customer-profile/state.ts +18 -0
  43. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  44. package/assets/templates/views/account/assembly/assembly.json +36 -0
  45. package/assets/templates/views/account/assembly/index.skeleton.tsx +277 -0
  46. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1057 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  50. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  51. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  53. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  56. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  63. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  67. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  70. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  73. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  76. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  79. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  80. package/assets/templates/views/account/content.ts +326 -0
  81. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  82. package/assets/templates/views/account/fulfillment-evidence.client.tsx +34 -0
  83. package/assets/templates/views/account/fulfillment-evidence.defaults.ts +145 -0
  84. package/assets/templates/views/account/fulfillment-evidence.schema.ts +15 -0
  85. package/assets/templates/views/account/index.tsx +259 -38
  86. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  87. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  88. package/assets/templates/views/account/orders-advanced.client.tsx +77 -0
  89. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  90. package/assets/templates/views/account/registry.tsx +935 -420
  91. package/assets/templates/views/account/schema.ts +50 -0
  92. package/assets/templates/views/account/sections-data.ts +2 -0
  93. package/assets/templates/views/cart/content.ts +1 -0
  94. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  95. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  96. package/assets/templates/views/category/content.ts +2 -0
  97. package/assets/templates/views/category/index.tsx +2 -0
  98. package/assets/templates/views/category/sections-data.ts +2 -0
  99. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  100. package/assets/templates/views/checkout/content.ts +51 -0
  101. package/assets/templates/views/checkout/index.tsx +1 -1
  102. package/assets/templates/views/checkout/props.ts +10 -2
  103. package/assets/templates/views/checkout/registry.tsx +104 -42
  104. package/assets/templates/views/checkout/schema.ts +76 -1
  105. package/assets/templates/views/home/assembly/assembly.json +23 -2
  106. package/assets/templates/views/home/assembly/index.skeleton.tsx +4 -1
  107. package/assets/templates/views/home/assembly/registry.skeleton.tsx +1 -0
  108. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/binding.json +5 -0
  109. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/catalog.part +4 -0
  110. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/element.part +4 -0
  111. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +10 -0
  112. package/assets/templates/views/home/content.ts +247 -1
  113. package/assets/templates/views/home/data.ts +10 -1
  114. package/assets/templates/views/home/index.tsx +8 -6
  115. package/assets/templates/views/home/props.ts +7 -1
  116. package/assets/templates/views/home/registry.tsx +11 -28
  117. package/assets/templates/views/home/schema.ts +163 -0
  118. package/assets/templates/views/home/sections-data.ts +2 -0
  119. package/assets/templates/views/product/content.ts +1 -0
  120. package/assets/templates/views/static/content.ts +1 -0
  121. package/bin/storefront.js +356 -27
  122. package/package.json +2 -1
  123. package/recipes/adapter-surface.json +159 -0
  124. package/recipes/archetypes.json +43 -4
  125. package/recipes/catalog.json +147 -2
  126. package/recipes/feature.schema.json +9 -0
  127. package/recipes/features.json +72 -1
  128. package/recipes/manifest.schema.json +5 -0
  129. package/recipes/recipe.schema.json +13 -1
  130. package/recipes/recipes.json +37 -7
  131. package/recipes/section.schema.json +112 -0
  132. package/recipes/sections.json +281 -4
  133. package/recipes/validate.mjs +83 -1
  134. package/scripts/adapter-surface.mjs +41 -0
  135. package/scripts/agent-blocks.mjs +700 -0
  136. package/scripts/block-validator.mjs +45 -0
  137. package/scripts/candidate.mjs +56 -14
  138. package/scripts/composers.mjs +7 -2
  139. package/scripts/default-sections.mjs +78 -0
  140. package/scripts/file-classes.mjs +18 -0
  141. package/scripts/generate-adapter-surface.mjs +148 -0
  142. package/scripts/operations.mjs +100 -0
  143. package/scripts/reconcile.mjs +67 -39
  144. package/scripts/section-configure.mjs +316 -0
  145. package/scripts/sync-assets.mjs +1 -0
  146. package/scripts/view-assembly.mjs +101 -14
  147. package/skills/sf-feature/SKILL.md +19 -0
  148. package/skills/sf-view-gen/SKILL.md +73 -7
  149. package/skills/sf-view-gen/assets/recipes/archetypes.json +43 -4
  150. package/skills/sf-view-gen/assets/recipes/catalog.json +147 -2
  151. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  152. package/skills/sf-view-gen/assets/recipes/recipes.json +37 -7
  153. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  154. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  155. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  156. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  157. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  158. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  159. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  160. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  161. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  162. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  163. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  164. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -15,7 +15,7 @@ import {
15
15
  injectGlobals,
16
16
  } from './render-templates.mjs'
17
17
  import { buildStateComposer, buildHandlersComposer, buildCompositionComposer, buildFeatureAdapter } from './composers.mjs'
18
- import { hasViewAssembly, isAssemblyRel, writeViewAssembly } from './view-assembly.mjs'
18
+ import { hasViewAssembly, isAssemblyRel, writeSectionsData, writeViewAssembly } from './view-assembly.mjs'
19
19
  import {
20
20
  resolveFeatureMountOverrides,
21
21
  resolveViewGenerationSelection,
@@ -55,16 +55,18 @@ async function walkFiles(dir, base = dir, out = []) {
55
55
 
56
56
  // Render a template tree into the project, writing every derived file but only
57
57
  // seeding user-owned files that do not exist yet, so reconcile never clobbers a
58
- // hand edit. `classifyRel` maps a template-relative path to its file class.
58
+ // hand edit. `derivedOnly` skips every non-derived class for scoped callers.
59
+ // `classifyRel` maps a template-relative path to its file class.
59
60
  // With `dryRun`, no file is written; `changed` still lists the files that would
60
61
  // change, so callers (doctor) can report drift without mutating the project.
61
- async function renderDerivedTree(fromDir, toDir, subs, classifyRel, changed, skip, dryRun) {
62
+ async function renderDerivedTree(fromDir, toDir, subs, classifyRel, changed, skip, dryRun, derivedOnly = false) {
62
63
  if (!existsSync(fromDir)) return
63
64
  const files = await walkFiles(fromDir)
64
65
  for (const rel of files) {
65
66
  if (skip && skip(rel)) continue
66
67
  const dest = path.join(toDir, rel.replaceAll('__STOREFRONT__', subs.name))
67
68
  const fileClass = classifyRel(rel)
69
+ if (derivedOnly && fileClass !== 'derived') continue
68
70
  if (fileClass === 'user-owned' && existsSync(dest)) continue
69
71
  const raw = await readFile(path.join(fromDir, rel), 'utf8')
70
72
  const next = replacePlaceholders(raw, subs)
@@ -147,7 +149,7 @@ export async function removeViewFiles(
147
149
  projectDir,
148
150
  manifest,
149
151
  viewName,
150
- { dryRun = false, legacyDerivedFiles = null } = {},
152
+ { dryRun = false, legacyDerivedFiles = null, derivedOnly = false } = {},
151
153
  ) {
152
154
  const name = manifest.name
153
155
  const viewDir = path.join(projectDir, 'lib', name, 'views', viewName)
@@ -169,6 +171,10 @@ export async function removeViewFiles(
169
171
  const abs = path.join(viewDir, rel)
170
172
  const posixRel = rel.split(path.sep).join('/')
171
173
  const fileClass = classifyFile(path.posix.join('views', viewName, posixRel))
174
+ if (derivedOnly && fileClass !== 'derived') {
175
+ preserved.push(abs)
176
+ continue
177
+ }
172
178
  const templatePath = templateDir ? path.join(templateDir, rel) : null
173
179
  const known = Boolean((templatePath && existsSync(templatePath)) || legacySet.has(posixRel))
174
180
  const maybeAuthored = !known || fileClass === 'user-owned'
@@ -227,7 +233,7 @@ export async function customizedViewFiles(projectDir, manifest, viewName) {
227
233
  // does not match a shipped template (customized or unknown) is preserved and
228
234
  // its location returned; pristine template files and the generated adapter are
229
235
  // removed so a pure add/remove round-trip restores the tree exactly.
230
- export async function removeFeatureFiles(projectDir, manifest, featureName, { dryRun = false } = {}) {
236
+ export async function removeFeatureFiles(projectDir, manifest, featureName, { dryRun = false, derivedOnly = false } = {}) {
231
237
  const name = manifest.name
232
238
  const featureDir = path.join(projectDir, 'lib', name, 'features', featureName)
233
239
  if (!existsSync(featureDir)) return { removed: [], preserved: [] }
@@ -242,6 +248,10 @@ export async function removeFeatureFiles(projectDir, manifest, featureName, { dr
242
248
  for (const rel of await walkFiles(featureDir)) {
243
249
  const abs = path.join(featureDir, rel)
244
250
  const posixRel = rel.split(path.sep).join('/')
251
+ if (derivedOnly && classifyFile(path.posix.join('features', featureName, posixRel)) !== 'derived') {
252
+ preserved.push(abs)
253
+ continue
254
+ }
245
255
  if (posixRel === 'adapter.ts') {
246
256
  if (!dryRun) await rm(abs, { force: true })
247
257
  removed.push(abs)
@@ -267,8 +277,10 @@ export async function removeFeatureFiles(projectDir, manifest, featureName, { dr
267
277
 
268
278
  // Reconcile a storefront project to its manifest: regenerate every derived
269
279
  // structural file from the versioned templates, seed any missing user-owned
270
- // file, and leave existing user-owned files untouched. Idempotent by design.
271
- export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
280
+ // file, and leave existing user-owned files untouched. `derivedOnly` excludes
281
+ // user-owned/external files and root guidance while preserving derived outputs.
282
+ // Idempotent by design.
283
+ export async function reconcile(projectDir, manifest, { dryRun = false, derivedOnly = false } = {}) {
272
284
  // A manifest that is not a supported composition is never reconciled, not
273
285
  // even in dry-run: report it and write nothing so a diagnostic cannot
274
286
  // silently proceed as if the input were valid.
@@ -314,6 +326,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
314
326
  changed,
315
327
  undefined,
316
328
  dryRun,
329
+ derivedOnly,
317
330
  )
318
331
 
319
332
  await renderDerivedTree(
@@ -333,11 +346,14 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
333
346
  )
334
347
  },
335
348
  dryRun,
349
+ derivedOnly,
336
350
  )
337
351
 
338
352
  const featuresDir = path.join(projectDir, 'lib', name, 'features')
339
353
  const featureNames = manifest.features.map((feature) => feature.name).sort()
340
- if (!dryRun) await mkdir(featuresDir, { recursive: true })
354
+ if (!dryRun && (!derivedOnly || featureNames.length > 0 || existsSync(featuresDir))) {
355
+ await mkdir(featuresDir, { recursive: true })
356
+ }
341
357
  for (const featureName of featureNames) {
342
358
  await renderDerivedTree(
343
359
  path.join(templatesRoot, 'features', featureName),
@@ -347,6 +363,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
347
363
  changed,
348
364
  undefined,
349
365
  dryRun,
366
+ derivedOnly,
350
367
  )
351
368
  // Adapter needs are declared by the feature recipe, not templated, so the
352
369
  // generated file always matches the registry the CLI validates against. A
@@ -373,7 +390,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
373
390
  const installed = new Set(featureNames)
374
391
  for (const entry of await readdir(featuresDir, { withFileTypes: true })) {
375
392
  if (!entry.isDirectory() || installed.has(entry.name)) continue
376
- const removal = await removeFeatureFiles(projectDir, manifest, entry.name, { dryRun })
393
+ const removal = await removeFeatureFiles(projectDir, manifest, entry.name, { dryRun, derivedOnly })
377
394
  for (const rel of removal.removed) changed.push(path.join(projectDir, rel))
378
395
  preserved.push(...removal.preserved)
379
396
  }
@@ -390,7 +407,11 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
390
407
  const skip = (rel) => {
391
408
  const normalized = rel.split(path.sep).join('/')
392
409
  if (isAssemblyRel(rel)) return true
393
- return assembled && (normalized === 'index.tsx' || normalized === 'registry.tsx')
410
+ return assembled && (
411
+ normalized === 'index.tsx' ||
412
+ normalized === 'registry.tsx' ||
413
+ normalized === 'sections-data.ts'
414
+ )
394
415
  }
395
416
  await renderDerivedTree(
396
417
  src,
@@ -400,6 +421,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
400
421
  changed,
401
422
  skip,
402
423
  dryRun,
424
+ derivedOnly,
403
425
  )
404
426
  if (assembled) {
405
427
  const resolved = viewSelections.get(view.name)
@@ -412,6 +434,12 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
412
434
  dryRun,
413
435
  })
414
436
  for (const abs of written) changed.push(abs)
437
+ const sectionsData = await writeSectionsData({
438
+ viewDir: path.join(viewsDir, view.name),
439
+ sections: resolved?.sections ?? [],
440
+ dryRun,
441
+ })
442
+ for (const abs of sectionsData) changed.push(abs)
415
443
  }
416
444
  }
417
445
 
@@ -430,7 +458,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
430
458
  for (const entry of await readdir(viewsDir, { withFileTypes: true })) {
431
459
  if (!entry.isDirectory() || installedViews.has(entry.name)) continue
432
460
  if (!registeredViews.has(entry.name)) continue
433
- const removal = await removeViewFiles(projectDir, manifest, entry.name, { dryRun })
461
+ const removal = await removeViewFiles(projectDir, manifest, entry.name, { dryRun, derivedOnly })
434
462
  for (const rel of removal.removed) changed.push(path.join(projectDir, rel))
435
463
  preserved.push(...removal.preserved)
436
464
  }
@@ -459,35 +487,35 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
459
487
  changed.push(clientBarrelPath)
460
488
  }
461
489
 
462
- const layoutResult = await ensureLayoutAppend(projectDir, name, siteName, mode, dryRun)
463
- if (layoutResult.conflict) {
464
- return { ok: false, errors: [layoutResult.conflict], views: [], changed: [] }
465
- }
466
- if (layoutResult.changed) {
467
- changed.push(path.join(projectDir, 'app', 'layout.tsx'))
468
- }
469
- if (await ensureGlobalsAppend(projectDir, name, siteName, dryRun)) {
470
- changed.push(path.join(projectDir, 'app', 'globals.css'))
471
- }
472
- for (const seoFile of ['sitemap.ts', 'robots.ts']) {
473
- if (await ensureSeedFile(projectDir, seoFile, subs, dryRun)) {
474
- changed.push(path.join(projectDir, 'app', seoFile))
490
+ if (!derivedOnly) {
491
+ const layoutResult = await ensureLayoutAppend(projectDir, name, siteName, mode, dryRun)
492
+ if (layoutResult.conflict) {
493
+ return { ok: false, errors: [layoutResult.conflict], views: [], changed: [] }
494
+ }
495
+ if (layoutResult.changed) {
496
+ changed.push(path.join(projectDir, 'app', 'layout.tsx'))
497
+ }
498
+ if (await ensureGlobalsAppend(projectDir, name, siteName, dryRun)) {
499
+ changed.push(path.join(projectDir, 'app', 'globals.css'))
500
+ }
501
+ for (const seoFile of ['sitemap.ts', 'robots.ts']) {
502
+ if (await ensureSeedFile(projectDir, seoFile, subs, dryRun)) {
503
+ changed.push(path.join(projectDir, 'app', seoFile))
504
+ }
475
505
  }
476
- }
477
506
 
478
- // The managed root guidance file is derived: rendered from the package
479
- // template with the project placeholders, refreshed by sync, and reported as
480
- // drift by doctor's dry-run. It is never seeded-and-frozen (not user-owned),
481
- // so the rules a store enforces always match the installed CLI generation.
482
- if (classifyFile('AGENTS.md') === 'derived') {
483
- const agentsTemplate = path.join(templatesRoot, 'AGENTS.md')
484
- if (existsSync(agentsTemplate)) {
485
- const agentsPath = path.join(projectDir, 'AGENTS.md')
486
- const nextAgents = replacePlaceholders(await readFile(agentsTemplate, 'utf8'), subs)
487
- const prevAgents = existsSync(agentsPath) ? await readFile(agentsPath, 'utf8') : null
488
- if (prevAgents !== nextAgents) {
489
- if (!dryRun) await writeFile(agentsPath, nextAgents)
490
- changed.push(agentsPath)
507
+ // The managed root guidance file is reconciled by full sync, but excluded
508
+ // from configure's derived-only pass along with external app files.
509
+ if (classifyFile('AGENTS.md') === 'derived') {
510
+ const agentsTemplate = path.join(templatesRoot, 'AGENTS.md')
511
+ if (existsSync(agentsTemplate)) {
512
+ const agentsPath = path.join(projectDir, 'AGENTS.md')
513
+ const nextAgents = replacePlaceholders(await readFile(agentsTemplate, 'utf8'), subs)
514
+ const prevAgents = existsSync(agentsPath) ? await readFile(agentsPath, 'utf8') : null
515
+ if (prevAgents !== nextAgents) {
516
+ if (!dryRun) await writeFile(agentsPath, nextAgents)
517
+ changed.push(agentsPath)
518
+ }
491
519
  }
492
520
  }
493
521
  }
@@ -501,7 +529,7 @@ export async function reconcile(projectDir, manifest, { dryRun = false } = {}) {
501
529
  for (const [composerPath, content] of [
502
530
  [path.join(projectDir, 'lib', name, 'state.ts'), buildStateComposer(stateFeatures)],
503
531
  [path.join(projectDir, 'lib', name, 'handlers.ts'), buildHandlersComposer(handlerFeatures)],
504
- [path.join(projectDir, 'lib', name, 'composition.ts'), buildCompositionComposer(manifest.features, manifest.views)],
532
+ [path.join(projectDir, 'lib', name, 'composition.ts'), buildCompositionComposer(manifest.features, manifest.views, Array.isArray(manifest.capabilities) ? manifest.capabilities : [])],
505
533
  ]) {
506
534
  const prev = existsSync(composerPath) ? await readFile(composerPath, 'utf8') : null
507
535
  if (prev === content) continue
@@ -0,0 +1,316 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { open, mkdir, readFile, realpath, rename, unlink } from 'node:fs/promises'
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+ import { sectionDefinitionByName } from '../recipes/validate.mjs'
5
+ import { normalizeViewSectionsForView } from './section-compat.mjs'
6
+ import { resolveBlockValidator } from './block-validator.mjs'
7
+ import { resultEnvelope } from './plan-apply.mjs'
8
+ import { reconcile } from './reconcile.mjs'
9
+
10
+ const missingPath = (error) => error?.code === 'ENOENT'
11
+
12
+ function diagnostic(code, message, extra = {}) {
13
+ return { code, severity: 'error', message, ...extra }
14
+ }
15
+
16
+ function safePathSegment(value) {
17
+ return typeof value === 'string' && value.trim().length > 0 && value !== '.' && value !== '..' &&
18
+ !value.includes('/') && !value.includes('\\') && !value.includes('..')
19
+ }
20
+
21
+ function safeId(id) {
22
+ return safePathSegment(id) && !id.startsWith('slot:')
23
+ }
24
+
25
+ async function canonicalSectionsDir(sectionsDir) {
26
+ let existing = sectionsDir
27
+ while (true) {
28
+ try {
29
+ const real = await realpath(existing)
30
+ return resolve(real, relative(existing, sectionsDir))
31
+ } catch (error) {
32
+ if (!missingPath(error)) throw error
33
+ const parent = dirname(existing)
34
+ if (parent === existing) throw error
35
+ existing = parent
36
+ }
37
+ }
38
+ }
39
+
40
+ function isWithin(parent, candidate) {
41
+ const rel = relative(parent, candidate)
42
+ return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
43
+ }
44
+
45
+ async function verifyTargetPath(projectRoot, libRoot, sectionsDir, targetPath) {
46
+ const relativeTarget = relative(sectionsDir, targetPath)
47
+ if (!relativeTarget || relativeTarget.startsWith(`..${sep}`) || relativeTarget === '..' || isAbsolute(relativeTarget)) {
48
+ return false
49
+ }
50
+
51
+ if (!isWithin(projectRoot, libRoot) || !isWithin(libRoot, sectionsDir) || !isWithin(libRoot, targetPath)) {
52
+ return false
53
+ }
54
+
55
+ const [canonicalProject, canonicalLib, canonicalSections, canonicalTarget] = await Promise.all([
56
+ canonicalSectionsDir(projectRoot),
57
+ canonicalSectionsDir(libRoot),
58
+ canonicalSectionsDir(sectionsDir),
59
+ canonicalSectionsDir(targetPath),
60
+ ])
61
+ const expectedCanonicalLib = resolve(canonicalProject, 'lib')
62
+ const expectedCanonicalSections = resolve(expectedCanonicalLib, relative(libRoot, sectionsDir))
63
+ return canonicalLib === expectedCanonicalLib && canonicalSections === expectedCanonicalSections &&
64
+ isWithin(canonicalProject, canonicalLib) && isWithin(canonicalLib, canonicalSections) &&
65
+ isWithin(canonicalLib, canonicalTarget)
66
+ }
67
+
68
+ export async function writeSidecarAtomically(targetPath, contents, io = {}) {
69
+ const fs = { open, mkdir, rename, unlink, ...io }
70
+ const directory = dirname(targetPath)
71
+ await fs.mkdir(directory, { recursive: true })
72
+
73
+ const tempPath = join(directory, `.${targetPath.split(sep).pop()}.${randomUUID()}.tmp`)
74
+ let file
75
+ try {
76
+ file = await fs.open(tempPath, 'wx', 0o600)
77
+ await file.writeFile(contents, 'utf8')
78
+ await file.sync()
79
+ await file.close()
80
+ file = null
81
+ await fs.rename(tempPath, targetPath)
82
+
83
+ // Persist the directory entry when the platform permits directory fsync.
84
+ try {
85
+ const dirHandle = await fs.open(directory, 'r')
86
+ try {
87
+ await dirHandle.sync()
88
+ } finally {
89
+ await dirHandle.close()
90
+ }
91
+ } catch {
92
+ // Some platforms/filesystems do not support syncing directories.
93
+ }
94
+ } catch (error) {
95
+ if (file) await file.close().catch(() => {})
96
+ await fs.unlink(tempPath).catch(() => {})
97
+ throw error
98
+ }
99
+ }
100
+
101
+ async function readInput(dataPath, stdin) {
102
+ if (dataPath === '-') {
103
+ const chunks = []
104
+ for await (const chunk of stdin) chunks.push(Buffer.from(chunk))
105
+ return Buffer.concat(chunks).toString('utf8')
106
+ }
107
+ return readFile(dataPath, 'utf8')
108
+ }
109
+
110
+ function response(ok, exitCode, diagnostics, result = null, message = null) {
111
+ return {
112
+ envelope: resultEnvelope('section', ok, exitCode, diagnostics, result),
113
+ message,
114
+ }
115
+ }
116
+
117
+ function causeMessage(cause) {
118
+ if (cause instanceof Error) return cause.message || cause.name
119
+ if (typeof cause === 'string') return cause
120
+ if (cause == null) return ''
121
+ try {
122
+ return JSON.stringify(cause)
123
+ } catch {
124
+ return String(cause)
125
+ }
126
+ }
127
+
128
+ function reconcileFailure(result) {
129
+ const errors = Array.isArray(result?.errors)
130
+ ? result.errors
131
+ : result?.error === undefined ? [] : [result.error]
132
+ const details = errors.map(causeMessage).filter(Boolean)
133
+ return details.length > 0 ? details.join('; ') : 'reconcile returned ok: false without details'
134
+ }
135
+
136
+ export async function configureSection({
137
+ target,
138
+ view,
139
+ id,
140
+ dataPath,
141
+ dryRun = false,
142
+ stdin = process.stdin,
143
+ readManifestOrError,
144
+ validatorResolver = resolveBlockValidator,
145
+ reconcileFn = reconcile,
146
+ }) {
147
+ const fail = (code, message, extra = {}) => response(false, 1, [diagnostic(code, message, extra)])
148
+
149
+ if (dataPath == null) {
150
+ return fail('E_SECTION_DATA_REQUIRED', 'storefront section configure requires --data <file|->.')
151
+ }
152
+ if (!safeId(id)) {
153
+ return fail('E_SECTION_ID_UNSAFE', 'Section id must be non-empty, non-slot, and contain no path separators or "..".')
154
+ }
155
+
156
+ const manifestResult = readManifestOrError(target)
157
+ if (manifestResult.error) {
158
+ return fail('E_INVALID_COMPOSITION', manifestResult.error, { path: 'storefront.config.json' })
159
+ }
160
+ const manifest = manifestResult.manifest
161
+ if (!manifest) return fail('E_NO_MANIFEST', 'No storefront.config.json found. Run `storefront sync` first.')
162
+ if (!safePathSegment(manifest.name)) {
163
+ return fail('E_SECTION_ID_UNSAFE', 'Storefront name must be a non-empty single path segment.', { path: 'storefront.config.json' })
164
+ }
165
+
166
+ const installedView = manifest.views?.find((entry) => entry.name === view)
167
+ if (!installedView) {
168
+ return fail('E_SECTION_NOT_FOUND', `View "${view}" is not installed or section "${id}" was not found.`)
169
+ }
170
+ if (!safePathSegment(installedView.name)) {
171
+ return fail('E_SECTION_ID_UNSAFE', 'View name must be a non-empty single path segment.', { path: 'storefront.config.json' })
172
+ }
173
+
174
+ const rawInstance = installedView.sections?.find((entry) =>
175
+ entry && typeof entry === 'object' && !Array.isArray(entry) && entry.id === id &&
176
+ typeof entry.type === 'string' && entry.type.length > 0,
177
+ )
178
+ if (!rawInstance) {
179
+ return fail('E_SECTION_NOT_FOUND', `Section "${id}" is not an explicit editorial instance in view "${view}".`)
180
+ }
181
+ const normalized = normalizeViewSectionsForView(view, installedView.sections ?? [])
182
+ const instance = normalized.ok ? normalized.sections.find((entry) => entry.id === id) : null
183
+ if (!instance) {
184
+ return fail('E_SECTION_NOT_FOUND', `Section "${id}" was not found in installed view "${view}".`)
185
+ }
186
+ if (instance.type !== rawInstance.type) {
187
+ return fail('E_SECTION_TYPE_MISMATCH', `Section instance "${id}" type does not match its raw manifest entry.`)
188
+ }
189
+
190
+ const definition = sectionDefinitionByName(instance.type)
191
+ const card = definition?.agent
192
+ if (definition && card?.status === 'ready' &&
193
+ (card.section !== instance.type || card.elementType !== definition.elementType)) {
194
+ return fail('E_SECTION_TYPE_MISMATCH', `Section instance "${id}" type "${instance.type}" does not match its ready agent card.`)
195
+ }
196
+ if (!definition || card?.status !== 'ready') {
197
+ return fail('E_SECTION_TYPE_MISMATCH', `Section type "${instance.type}" is not agent-configurable; it has no ready agent card.`)
198
+ }
199
+
200
+ const projectRoot = resolve(target)
201
+ const libRoot = resolve(projectRoot, 'lib')
202
+ const sectionsDir = resolve(libRoot, manifest.name, 'views', installedView.name, 'sections')
203
+ const targetPath = resolve(sectionsDir, `${id}.json`)
204
+ if (!(await verifyTargetPath(projectRoot, libRoot, sectionsDir, targetPath))) {
205
+ return fail('E_SECTION_ID_UNSAFE', 'Section id resolves outside its sections directory.')
206
+ }
207
+ const projectPath = relative(target, targetPath).split(sep).join('/')
208
+
209
+ let input
210
+ try {
211
+ input = JSON.parse(await readInput(dataPath, stdin))
212
+ } catch (error) {
213
+ const detail = error instanceof SyntaxError ? 'input is not valid JSON' : 'could not read the data input'
214
+ return fail('E_SECTION_DATA_INVALID', `Section data ${detail}.`, { path: projectPath })
215
+ }
216
+
217
+ const resolved = await validatorResolver(target, card.validator?.export)
218
+ if (!resolved.ok) {
219
+ return fail('E_BLOCK_VALIDATOR_UNAVAILABLE', resolved.error.message, { path: projectPath })
220
+ }
221
+
222
+ let validation
223
+ try {
224
+ validation = await resolved.validate(input)
225
+ } catch {
226
+ return fail('E_SECTION_DATA_INVALID', 'The section data validator failed.', { path: projectPath })
227
+ }
228
+ if (!validation || validation.ok !== true) {
229
+ const errors = Array.isArray(validation?.errors) && validation.errors.length > 0
230
+ ? validation.errors
231
+ : [{ path: '', message: 'The validator rejected this data.' }]
232
+ return response(
233
+ false,
234
+ 1,
235
+ errors.map((error) => diagnostic('E_SECTION_DATA_INVALID', error.message, {
236
+ ...(typeof error.path === 'string' ? { path: error.path } : {}),
237
+ })),
238
+ )
239
+ }
240
+
241
+ const validatedValue = Object.prototype.hasOwnProperty.call(validation, 'value') && validation.value !== undefined
242
+ ? validation.value
243
+ : input
244
+ if (Object.prototype.hasOwnProperty.call(validation, 'value') && validation.value === undefined) {
245
+ return fail('E_SECTION_DATA_INVALID', 'The section data validator returned an undefined value.', { path: projectPath })
246
+ }
247
+ const result = {
248
+ action: 'configure',
249
+ view,
250
+ id,
251
+ path: projectPath,
252
+ dryRun,
253
+ validation: { ok: true },
254
+ changed: [],
255
+ }
256
+ if (dryRun) {
257
+ return response(true, 0, [], result, `Validated section "${id}" in view "${view}" (dry run).\n Sidecar: ${projectPath}`)
258
+ }
259
+
260
+ const contents = `${JSON.stringify({ data: validatedValue }, null, 2)}\n`
261
+ let previousContents = null
262
+ try {
263
+ previousContents = await readFile(targetPath)
264
+ } catch (error) {
265
+ if (!missingPath(error)) {
266
+ return fail('E_SECTION_WRITE_FAILED', `Could not read the previous section sidecar "${projectPath}".`, { path: projectPath })
267
+ }
268
+ }
269
+ try {
270
+ await writeSidecarAtomically(targetPath, contents)
271
+ } catch {
272
+ return fail('E_SECTION_WRITE_FAILED', `Could not write section sidecar "${projectPath}".`, { path: projectPath })
273
+ }
274
+
275
+ let regeneration
276
+ let regenerationFailure = null
277
+ try {
278
+ regeneration = await reconcileFn(target, manifest, { derivedOnly: true })
279
+ if (regeneration?.ok !== true) regenerationFailure = reconcileFailure(regeneration)
280
+ } catch (error) {
281
+ regenerationFailure = causeMessage(error) || 'reconcile threw an unknown error'
282
+ }
283
+ if (regenerationFailure !== null) {
284
+ const rollbackFailures = []
285
+ try {
286
+ if (previousContents === null) await unlink(targetPath)
287
+ else await writeSidecarAtomically(targetPath, previousContents)
288
+ } catch (error) {
289
+ rollbackFailures.push(`sidecar restore failed: ${causeMessage(error) || 'unknown error'}`)
290
+ }
291
+ try {
292
+ const restored = await reconcileFn(target, manifest, { derivedOnly: true })
293
+ if (restored?.ok !== true) rollbackFailures.push(`rollback reconciliation failed: ${reconcileFailure(restored)}`)
294
+ } catch (error) {
295
+ rollbackFailures.push(`rollback reconciliation threw: ${causeMessage(error) || 'unknown error'}`)
296
+ }
297
+ if (rollbackFailures.length > 0) {
298
+ return fail(
299
+ 'E_SECTION_ROLLBACK_FAILED',
300
+ `Section regeneration failed: ${regenerationFailure}. Rollback failed: ${rollbackFailures.join('; ')}.`,
301
+ { path: projectPath },
302
+ )
303
+ }
304
+ return fail(
305
+ 'E_SECTION_REGENERATION_FAILED',
306
+ `Section regeneration failed: ${regenerationFailure}. The previous sidecar and derived state were restored.`,
307
+ { path: projectPath },
308
+ )
309
+ }
310
+
311
+ const changed = (Array.isArray(regeneration.changed) ? regeneration.changed : [])
312
+ .map((entry) => relative(target, isAbsolute(entry) ? entry : resolve(target, entry)).split(sep).join('/'))
313
+ result.changed = changed
314
+
315
+ return response(true, 0, [], result, `Configured section "${id}" in view "${view}".\n Sidecar: ${projectPath}`)
316
+ }
@@ -25,6 +25,7 @@ const MANIFEST = [
25
25
  ['recipes/recipes.json', 'skills/sf-view-gen/assets/recipes/recipes.json'],
26
26
  ['recipes/archetypes.json', 'skills/sf-view-gen/assets/recipes/archetypes.json'],
27
27
  ['recipes/sections.json', 'skills/sf-view-gen/assets/recipes/sections.json'],
28
+ ['recipes/section.schema.json', 'skills/sf-view-gen/assets/recipes/section.schema.json'],
28
29
  ['recipes/features.json', 'skills/sf-view-gen/assets/recipes/features.json'],
29
30
  ['recipes/catalog.json', 'skills/sf-view-gen/assets/recipes/catalog.json'],
30
31
  ['recipes/catalog.schema.json', 'skills/sf-view-gen/assets/recipes/catalog.schema.json'],