@open-mercato/cli 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8665.1.2455b2503c

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 (263) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +2 -0
  3. package/dist/agentic/guides/architecture.md +2 -2
  4. package/dist/agentic/guides/extensions.md +7 -2
  5. package/dist/agentic/guides/framework-extension-points.md +1 -0
  6. package/dist/agentic/guides/infrastructure-providers.md +20 -0
  7. package/dist/agentic/guides/integrations.md +2 -2
  8. package/dist/agentic/guides/module-facts.json +2564 -265
  9. package/dist/agentic/guides/module-facts.v2.json +2580 -265
  10. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  11. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  13. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  14. package/dist/agentic/guides/modules/assisted_selling/acl-features.md +16 -0
  15. package/dist/agentic/guides/modules/assisted_selling/contribution-resolutions.md +21 -0
  16. package/dist/agentic/guides/modules/assisted_selling/domain-commands.md +11 -0
  17. package/dist/agentic/guides/modules/assisted_selling/entities.md +11 -0
  18. package/dist/agentic/guides/modules/assisted_selling/events.md +22 -0
  19. package/dist/agentic/guides/modules/assisted_selling/exact-override-targets.md +17 -0
  20. package/dist/agentic/guides/modules/assisted_selling/index.md +21 -0
  21. package/dist/agentic/guides/modules/assisted_selling/owned-contract-module-metadata.md +11 -0
  22. package/dist/agentic/guides/modules/assisted_selling/setup.md +11 -0
  23. package/dist/agentic/guides/modules/assisted_selling/umes-contributions.md +21 -0
  24. package/dist/agentic/guides/modules/assisted_selling/umes-hosts.md +23 -0
  25. package/dist/agentic/guides/modules/attachments/exact-override-targets.md +1 -1
  26. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  27. package/dist/agentic/guides/modules/attachments/workers.md +1 -1
  28. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  29. package/dist/agentic/guides/modules/auth/index.md +1 -1
  30. package/dist/agentic/guides/modules/availability/index.md +1 -1
  31. package/dist/agentic/guides/modules/backups/di-registrations-rich.md +11 -0
  32. package/dist/agentic/guides/modules/backups/di-service-tokens.md +11 -0
  33. package/dist/agentic/guides/modules/backups/exact-override-targets.md +11 -0
  34. package/dist/agentic/guides/modules/backups/index.md +5 -2
  35. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  36. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  37. package/dist/agentic/guides/modules/cart/index.md +1 -1
  38. package/dist/agentic/guides/modules/catalog/acl-features.md +2 -1
  39. package/dist/agentic/guides/modules/catalog/active-extension-bindings.md +2 -0
  40. package/dist/agentic/guides/modules/catalog/backend-pages.md +1 -0
  41. package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +5 -0
  42. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +8 -7
  43. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -4
  44. package/dist/agentic/guides/modules/catalog/domain-commands.md +2 -0
  45. package/dist/agentic/guides/modules/catalog/entities.md +1 -0
  46. package/dist/agentic/guides/modules/catalog/events.md +4 -1
  47. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +13 -7
  48. package/dist/agentic/guides/modules/catalog/index.md +9 -9
  49. package/dist/agentic/guides/modules/catalog/umes-contributions.md +5 -0
  50. package/dist/agentic/guides/modules/catalog/umes-hosts.md +4 -0
  51. package/dist/agentic/guides/modules/catalog/workers.md +1 -0
  52. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  53. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  54. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  55. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  56. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  57. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  58. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  59. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  60. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  61. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  62. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  63. package/dist/agentic/guides/modules/configs/index.md +1 -1
  64. package/dist/agentic/guides/modules/content/index.md +1 -1
  65. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  66. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  67. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
  68. package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
  69. package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
  70. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  71. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
  72. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  73. package/dist/agentic/guides/modules/customers/index.md +3 -3
  74. package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
  75. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
  76. package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
  77. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
  78. package/dist/agentic/guides/modules/dashboards/index.md +2 -3
  79. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  80. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  81. package/dist/agentic/guides/modules/devices/index.md +1 -1
  82. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  83. package/dist/agentic/guides/modules/directory/index.md +1 -1
  84. package/dist/agentic/guides/modules/documents/index.md +1 -1
  85. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  86. package/dist/agentic/guides/modules/entities/index.md +1 -1
  87. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  88. package/dist/agentic/guides/modules/events/index.md +1 -1
  89. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  90. package/dist/agentic/guides/modules/forms/index.md +1 -1
  91. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  92. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  93. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  94. package/dist/agentic/guides/modules/generators/index.md +1 -1
  95. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  96. package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
  97. package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
  98. package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
  99. package/dist/agentic/guides/modules/integrations/index.md +2 -2
  100. package/dist/agentic/guides/modules/integrations/setup.md +1 -1
  101. package/dist/agentic/guides/modules/integrations/workers.md +3 -1
  102. package/dist/agentic/guides/modules/messages/index.md +1 -1
  103. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  104. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  105. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  106. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  107. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  108. package/dist/agentic/guides/modules/planner/index.md +1 -1
  109. package/dist/agentic/guides/modules/portal/index.md +1 -1
  110. package/dist/agentic/guides/modules/progress/index.md +1 -1
  111. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  112. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  113. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  114. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  115. package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
  116. package/dist/agentic/guides/modules/resources/index.md +1 -1
  117. package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
  118. package/dist/agentic/guides/modules/resources/setup.md +1 -1
  119. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
  120. package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
  121. package/dist/agentic/guides/modules/sales/index.md +3 -3
  122. package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
  123. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  124. package/dist/agentic/guides/modules/search/index.md +1 -1
  125. package/dist/agentic/guides/modules/security/index.md +1 -1
  126. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  127. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  128. package/dist/agentic/guides/modules/sso/index.md +1 -1
  129. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
  130. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
  131. package/dist/agentic/guides/modules/staff/index.md +1 -1
  132. package/dist/agentic/guides/modules/staff/workers.md +1 -1
  133. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  134. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  135. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  136. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  137. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  138. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  139. package/dist/agentic/guides/modules/translations/index.md +1 -1
  140. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  141. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  142. package/dist/agentic/guides/modules/wms/index.md +1 -1
  143. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  144. package/dist/agentic/guides/reference-module-facts.json +811 -21
  145. package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
  146. package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
  147. package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
  148. package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
  149. package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
  150. package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
  151. package/dist/agentic/guides/reference-modules/example/events.md +2 -1
  152. package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
  153. package/dist/agentic/guides/reference-modules/example/index.md +7 -7
  154. package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
  155. package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
  156. package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
  157. package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
  158. package/dist/agentic/guides/upstream/AGENTS.md +5 -4
  159. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
  160. package/dist/agentic/guides/upstream/manifest.json +3 -3
  161. package/dist/agentic/shared/AGENTS.md.template +11 -15
  162. package/dist/agentic/shared/ai/harness/README.md +4 -2
  163. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  164. package/dist/agentic/shared/ai/harness/cases.json +1420 -41
  165. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  166. package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
  167. package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
  168. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  169. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
  170. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
  171. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
  172. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
  173. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
  174. package/dist/lib/cache-provider-manifest.js +9 -0
  175. package/dist/lib/cache-provider-manifest.js.map +7 -0
  176. package/dist/lib/generate-watch-plan.js +4 -0
  177. package/dist/lib/generate-watch-plan.js.map +2 -2
  178. package/dist/lib/generate-watch-runner.js +1 -0
  179. package/dist/lib/generate-watch-runner.js.map +2 -2
  180. package/dist/lib/generate-watch-structure.js +2 -0
  181. package/dist/lib/generate-watch-structure.js.map +2 -2
  182. package/dist/lib/generators/ast/writers.js +5 -1
  183. package/dist/lib/generators/ast/writers.js.map +2 -2
  184. package/dist/lib/generators/cache-providers.js +80 -0
  185. package/dist/lib/generators/cache-providers.js.map +7 -0
  186. package/dist/lib/generators/form-section-ast.js +156 -0
  187. package/dist/lib/generators/form-section-ast.js.map +7 -0
  188. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  189. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  190. package/dist/lib/generators/form-section-extension-source.js +245 -0
  191. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  192. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  193. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  194. package/dist/lib/generators/form-sections.js +773 -0
  195. package/dist/lib/generators/form-sections.js.map +7 -0
  196. package/dist/lib/generators/index.js +2 -0
  197. package/dist/lib/generators/index.js.map +2 -2
  198. package/dist/lib/generators/module-entities.js +21 -2
  199. package/dist/lib/generators/module-entities.js.map +2 -2
  200. package/dist/lib/generators/module-extension-facts.js +2 -1
  201. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  202. package/dist/lib/generators/module-facts.js +30 -1
  203. package/dist/lib/generators/module-facts.js.map +2 -2
  204. package/dist/lib/generators/module-override-targets.js +24 -2
  205. package/dist/lib/generators/module-override-targets.js.map +2 -2
  206. package/dist/lib/generators/module-registry.js +75 -3
  207. package/dist/lib/generators/module-registry.js.map +2 -2
  208. package/dist/lib/generators/openapi.js +27 -17
  209. package/dist/lib/generators/openapi.js.map +2 -2
  210. package/dist/lib/post-generate-invalidation.js +20 -1
  211. package/dist/lib/post-generate-invalidation.js.map +2 -2
  212. package/dist/lib/resolver.js +195 -1
  213. package/dist/lib/resolver.js.map +3 -3
  214. package/dist/lib/single-instance-strategy-guard.js +26 -3
  215. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  216. package/dist/mercato.js +34 -6
  217. package/dist/mercato.js.map +2 -2
  218. package/jest.config.cjs +2 -0
  219. package/package.json +7 -7
  220. package/src/__tests__/mercato.test.ts +18 -0
  221. package/src/__tests__/rotation-json-output.test.ts +52 -0
  222. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  223. package/src/lib/__tests__/generate-watch-plan.test.ts +3 -2
  224. package/src/lib/__tests__/generate-watch-runner.test.ts +13 -1
  225. package/src/lib/__tests__/generate-watch-structure.test.ts +34 -0
  226. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  227. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  228. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  229. package/src/lib/cache-provider-manifest.ts +8 -0
  230. package/src/lib/generate-watch-plan.ts +6 -3
  231. package/src/lib/generate-watch-runner.ts +1 -0
  232. package/src/lib/generate-watch-structure.ts +5 -1
  233. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  234. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  235. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  236. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  237. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  238. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  239. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  240. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  241. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  242. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  243. package/src/lib/generators/__tests__/openapi.test.ts +60 -13
  244. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  245. package/src/lib/generators/ast/writers.ts +6 -1
  246. package/src/lib/generators/cache-providers.ts +111 -0
  247. package/src/lib/generators/form-section-ast.ts +166 -0
  248. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  249. package/src/lib/generators/form-section-extension-source.ts +308 -0
  250. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  251. package/src/lib/generators/form-sections.ts +896 -0
  252. package/src/lib/generators/index.ts +1 -0
  253. package/src/lib/generators/module-entities.ts +22 -4
  254. package/src/lib/generators/module-extension-facts.ts +1 -0
  255. package/src/lib/generators/module-facts.ts +40 -0
  256. package/src/lib/generators/module-override-targets.ts +19 -0
  257. package/src/lib/generators/module-registry.ts +80 -4
  258. package/src/lib/generators/openapi.ts +31 -20
  259. package/src/lib/post-generate-invalidation.ts +28 -1
  260. package/src/lib/resolver.ts +218 -0
  261. package/src/lib/single-instance-strategy-guard.ts +51 -1
  262. package/src/mercato.ts +32 -4
  263. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -295,6 +295,7 @@ describe('module extension facts', () => {
295
295
  ['module-override:encryption.maps', 'disable-replace'],
296
296
  ['module-override:enrichers', 'disable-replace'],
297
297
  ['module-override:events.subscribers', 'disable-replace'],
298
+ ['module-override:forms.sections', 'disable-replace'],
298
299
  ['module-override:guards', 'disable-replace'],
299
300
  ['module-override:interceptors', 'disable-replace'],
300
301
  ['module-override:nav.groupOrder', 'additive'],
@@ -72,7 +72,7 @@ describe('module-facts BC resolve guard (T2)', () => {
72
72
  expect(legacySecurity?.kind === 'component-override' ? legacySecurity.details.mode : null).toBe('replace')
73
73
  expect(v2Security?.kind === 'component-override' ? v2Security.details.mode : null).toBe('wrapper')
74
74
 
75
- const recoveredContribution = 'catalog.injection.product-bulk-delete@data-table:catalog.products.list:bulk-actions'
75
+ const recoveredContribution = 'catalog.injection.product-seo@crud-form:catalog.catalog_product'
76
76
  expect(legacyFactsByModule.catalog.extensionSurfaces?.contributions.map((entry) => entry.id))
77
77
  .not.toContain(recoveredContribution)
78
78
  expect(factsByModule.catalog.extensionSurfaces?.contributions.map((entry) => entry.id))
@@ -196,12 +196,14 @@ describe('module-facts BC resolve guard (T2)', () => {
196
196
  // so uniform growth across all four is the evidence that this is repo size,
197
197
  // not a duplicated payload. The headroom ratio is kept at the ~1.15 the
198
198
  // previous raise used, so the guard keeps the same detection power it had.
199
+ // Re-measured on the merged tree (`yarn jest module-facts.bc-guard`), which
200
+ // carries both the catalog AI categorization surfaces (routes, pages,
201
+ // bulk-action widget, worker, subscriber, events, ACL feature) and
202
+ // whatever `main` had accumulated since this branch forked:
203
+ // completeJson 5,573,265 · legacy delta 2,438,777 · markdown 2,110,921 ·
204
+ // directory markdown 2,300,284.
205
+ // The caps below keep the usual ~15% headroom over that measurement.
199
206
  expect(Buffer.byteLength(completeJson)).toBeLessThan(6_380_000)
200
- // Measured on the current merged tree (`yarn jest module-facts.bc-guard`):
201
- // completeJson 5,547,284 · legacy delta 2,425,489 · markdown 2,100,437 ·
202
- // directory markdown 2,289,693.
203
- // The four measures grew uniformly since the previous baseline
204
- // (+15.0% / +14.9% / +15.4% / +15.3%), preserving the linear-growth signal.
205
207
  expect(Buffer.byteLength(completeJson) - Buffer.byteLength(legacyJson)).toBeLessThan(2_790_000)
206
208
  // Markdown cap raised with the source-link contract: entities, events, ACL
207
209
  // features, DI tokens, search entities, notifications, UMES hosts and UMES
@@ -9,6 +9,7 @@ import {
9
9
  countModuleFactCoverage,
10
10
  extractAllModuleFacts,
11
11
  extractModuleFacts,
12
+ prepareReferenceFormSectionContributions,
12
13
  type ModuleFactCoverageFamily,
13
14
  type ModuleFactCoverageRow,
14
15
  type ModuleFacts,
@@ -33,6 +34,7 @@ import {
33
34
  } from '@open-mercato/shared/modules/widgets/extension-points'
34
35
  import {
35
36
  ALL_OVERRIDE_DOMAINS,
37
+ computeOverrideTargetId,
36
38
  MODULE_OVERRIDE_MODES,
37
39
  MODULE_OVERRIDE_TARGET_DIAGNOSTIC_CODES,
38
40
  MODULE_OVERRIDE_TARGET_NOTES,
@@ -82,11 +84,17 @@ function exampleRegistrySource(): string {
82
84
  }
83
85
 
84
86
  function extractExampleFacts(registrySource?: string): ModuleFacts {
85
- return extractModuleFacts({
87
+ const source = {
86
88
  moduleId: 'example',
87
89
  moduleRoot: path.join(findRepoRoot(), 'apps', 'mercato', 'src', 'modules', 'example'),
88
90
  portableSourceRoot: 'src/modules/example',
89
- ...(registrySource === undefined ? {} : { registrySource }),
91
+ }
92
+ return extractModuleFacts({
93
+ ...source,
94
+ ...(registrySource === undefined ? {} : {
95
+ registrySource,
96
+ formSectionContributions: prepareReferenceFormSectionContributions(source).get(source.moduleId),
97
+ }),
90
98
  })
91
99
  }
92
100
 
@@ -350,16 +358,13 @@ describe('factCoverage ledger — checked against the real example extraction',
350
358
  expect(fs.existsSync(path.join(findRepoRoot(), 'apps/mercato/src/modules/example/generators.ts'))).toBe(true)
351
359
  })
352
360
 
353
- it('emits a real override target for all fifteen module-owned domains and none for framework-only nav', () => {
361
+ it('emits targets for the example-backed override domains', () => {
354
362
  const domainCounts = counts.ModuleOverrideDomain
355
- for (const domain of ALL_OVERRIDE_DOMAINS) {
356
- if (domain === 'nav') {
357
- expect(domainCounts[domain] ?? 0).toBe(0)
358
- continue
359
- }
360
- expect(domainCounts[domain] ?? 0).toBeGreaterThan(0)
361
- }
362
- expect(Object.keys(domainCounts)).toHaveLength(ALL_OVERRIDE_DOMAINS.length - 1)
363
+ const emitted = familyOf(ledger, 'ModuleOverrideDomain').rows
364
+ .filter((row) => row.status === 'emitted-example' && !row.requiresGeneratedRegistry)
365
+ .map((row) => row.value)
366
+ expect(Object.keys(domainCounts).sort()).toEqual(emitted.sort())
367
+ for (const domain of emitted) expect(domainCounts[domain]).toBeGreaterThan(0)
363
368
  })
364
369
 
365
370
  it('round-trips all three modes and both closed notes through real targets', () => {
@@ -424,7 +429,8 @@ describe('factCoverage ledger — checked against the real example extraction',
424
429
  describe('requiresGeneratedRegistry — the only skip out of the non-zero proof is itself proven', () => {
425
430
  const ledger = buildModuleFactCoverageLedger()
426
431
  const sourceOnlyCounts = countModuleFactCoverage(extractExampleFacts())
427
- const registryBackedCounts = countModuleFactCoverage(extractExampleFacts(exampleRegistrySource()))
432
+ const registryBacked = extractExampleFacts(exampleRegistrySource())
433
+ const registryBackedCounts = countModuleFactCoverage(registryBacked)
428
434
  const claims = ledger.flatMap((family) =>
429
435
  family.rows
430
436
  .filter((row) => row.requiresGeneratedRegistry)
@@ -434,7 +440,7 @@ describe('requiresGeneratedRegistry — the only skip out of the non-zero proof
434
440
  `${claim.family}.${claim.row.value}`
435
441
 
436
442
  it('is claimed by exactly the rows the rest of this suite proves', () => {
437
- expect(claims.map(label)).toEqual(['ModuleFactSourceKind.api-route'])
443
+ expect(claims.map(label).sort()).toEqual(['ModuleFactSourceKind.api-route', 'ModuleOverrideDomain.forms'])
438
444
  })
439
445
 
440
446
  it('is claimed only where it changes anything: on an emitted-example row', () => {
@@ -455,6 +461,24 @@ describe('requiresGeneratedRegistry — the only skip out of the non-zero proof
455
461
  expect(stillZeroWithRegistry).toEqual([])
456
462
  })
457
463
 
464
+ it('projects exactly the occupied showcase addresses with portable contribution provenance', () => {
465
+ const sections = ['brand', 'details', 'erp', 'observer', 'season', 'status', 'title']
466
+ const keys = ['create', 'update'].flatMap((operation) =>
467
+ sections.map((section) => `example.todo/showcase/${operation}/${section}`))
468
+ const targets = registryBacked.overrideTargets?.filter(({ domain }) => domain === 'forms') ?? []
469
+ expect(targets.map(({ key }) => key).sort()).toEqual(keys)
470
+ for (const target of targets) {
471
+ const fact = registryBacked.formSectionContributions?.find(({ id }) => id === target.factRef.factKey)
472
+ const source = { sourcePath: 'src/modules/example/form-sections.ts', exportName: 'crudFormExtensions' }
473
+ expect(fact).toMatchObject({ key: target.key, source })
474
+ expect(target).toMatchObject({
475
+ modes: ['disable-replace'], source, path: ['forms', 'sections', target.key],
476
+ id: computeOverrideTargetId('example', 'forms', target.path),
477
+ })
478
+ expect(target.factRef.factSection).toBe('formSectionContributions')
479
+ }
480
+ })
481
+
458
482
  it('drives the registry-backed count from a route the example module really ships', () => {
459
483
  expect(fs.existsSync(path.join(findRepoRoot(), REGISTRY_BACKED_ROUTE.sourceFile))).toBe(true)
460
484
  expect(registryBackedCounts.ModuleFactSourceKind['api-route']).toBe(1)
@@ -403,6 +403,19 @@ describe('local-reference projection of the canonical example module', () => {
403
403
  }
404
404
  })
405
405
 
406
+ it('emits exact section targets from template sources with no app registry input', () => {
407
+ const reference = discoverLocalReferenceModuleSource({ appRoot: templateRoot, moduleId: 'example' })
408
+ expect(reference).not.toBeNull()
409
+ const { entry } = extractLocalReferenceModuleFacts({ packageSources: [], reference: reference! })
410
+ expect(entry).toMatchObject({ runtimeSelected: false, sourceKind: 'local-reference' })
411
+ const forms = entry.facts.overrideTargets?.filter(({ domain }) => domain === 'forms') ?? []
412
+ expect(forms).toHaveLength(14)
413
+ expect(forms.map(({ key }) => key)).toEqual(expect.arrayContaining([
414
+ 'example.todo/showcase/create/title', 'example.todo/showcase/update/observer',
415
+ ]))
416
+ expect(forms.every(({ source }) => source.sourcePath === 'src/modules/example/form-sections.ts')).toBe(true)
417
+ })
418
+
406
419
  it('fingerprints the authoring and template example trees identically', () => {
407
420
  const authoring = discoverLocalReferenceModuleSource({ appRoot: authoringRoot, moduleId: 'example' })
408
421
  const template = discoverLocalReferenceModuleSource({ appRoot: templateRoot, moduleId: 'example' })
@@ -86,9 +86,8 @@ describe('module override targets — adapter registry coverage', () => {
86
86
  for (const adapter of MODULE_OVERRIDE_TARGET_ADAPTERS) {
87
87
  expect(ALL_OVERRIDE_DOMAINS).toContain(adapter.domain)
88
88
  }
89
- // exactly the 16 runtime domains, one adapter each
90
- expect(ALL_OVERRIDE_DOMAINS).toHaveLength(16)
91
- expect(MODULE_OVERRIDE_TARGET_ADAPTERS).toHaveLength(16)
89
+ expect(ALL_OVERRIDE_DOMAINS).toHaveLength(17)
90
+ expect(MODULE_OVERRIDE_TARGET_ADAPTERS).toHaveLength(ALL_OVERRIDE_DOMAINS.length)
92
91
  })
93
92
 
94
93
  it('classifies nav as framework-only (never a module target)', () => {
@@ -426,7 +426,7 @@ describe('generateModuleRegistry with module subsets', () => {
426
426
  methods: [
427
427
  "GET"
428
428
  ],
429
- load: async () => import("@open-mercato/core/modules/orders/api/orders/route")
429
+ load: async (): ReturnType<ApiRouteManifestEntry['load']> => import("@open-mercato/core/modules/orders/api/orders/route")
430
430
  }
431
431
  ];
432
432
 
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import type { ModuleEntry, PackageResolver } from '../../resolver'
5
5
  import { runGenerateWatchSuite } from '../../generate-watch-runner'
6
6
  import { generateOpenApi, getOpenApiGeneratorDependencies, getOpenApiWatchInputs } from '../openapi'
7
+ import { generatedDerivedCrudRouteIndex } from '../form-sections'
7
8
 
8
9
  describe('resolveOpenApiGeneratorProjectRoot', () => {
9
10
  it('resolves the monorepo root from a POSIX module URL', async () => {
@@ -115,6 +116,28 @@ export function buildOpenApiDocument(modules: any[], options: any) {
115
116
  fs.rmSync(tmpDir, { recursive: true, force: true })
116
117
  })
117
118
 
119
+ it('loads generated section-policy docs and fails closed when the qualified route cannot load', async () => {
120
+ const resolver = createMockResolver([{ id: 'example', from: '@app' }])
121
+ const outputDir = resolver.getOutputDir()
122
+ const fileName = 'crud-form-section-route-0123456789abcdef.generated.ts'
123
+ touchFile(path.join(outputDir, generatedDerivedCrudRouteIndex), JSON.stringify([{
124
+ moduleId: 'example', routePath: '/example/records/section-policy', fileName, methods: ['PUT'],
125
+ }]))
126
+ const routePath = path.join(outputDir, fileName)
127
+ touchFile(routePath, `
128
+ export const metadata = { PUT: { requireAuth: true } }
129
+ export const PUT = () => new Response()
130
+ export const openApi = { PUT: { summary: 'Update the bound record', requestBody: { required: true } } }
131
+ `)
132
+ await generateOpenApi({ resolver, quiet: true })
133
+ const generated = JSON.parse(fs.readFileSync(path.join(outputDir, 'openapi.generated.json'), 'utf8'))
134
+ expect(generated.paths['/api/example/records/section-policy']).toEqual({
135
+ put: { summary: 'Update the bound record', requestBody: { required: true } },
136
+ })
137
+ touchFile(routePath, "throw new Error('Cannot derive CrudForm section host: fixture qualifier failed')")
138
+ await expect(generateOpenApi({ resolver, quiet: true })).rejects.toThrow(/fixture qualifier failed/)
139
+ })
140
+
118
141
  it('watches transitive sources, including deleted inputs, without watching generated outputs', () => {
119
142
  const delegate = createMockResolver([{ id: 'demo', from: '@open-mercato/core' }])
120
143
  const packageGeneratedRoot = path.join(tmpDir, 'packages', 'core', 'generated')
@@ -127,7 +150,7 @@ export function buildOpenApiDocument(modules: any[], options: any) {
127
150
  const similarlyNamedSource = path.join(tmpDir, 'packages', 'core', 'generated-sources', 'schema.ts')
128
151
  touchFile(source, 'export const schema = {}')
129
152
  touchFile(path.join(resolver.getOutputDir(), 'openapi.generated.inputs.json'), JSON.stringify({
130
- version: 1,
153
+ version: 2,
131
154
  inputPaths: [
132
155
  source,
133
156
  path.join(resolver.getOutputDir(), 'entities.generated.ts'),
@@ -150,12 +173,12 @@ export function buildOpenApiDocument(modules: any[], options: any) {
150
173
  expect(getOpenApiGeneratorDependencies(resolver)).toBeNull()
151
174
  touchFile(manifestPath, '{')
152
175
  expect(getOpenApiWatchInputs(resolver)).toEqual([])
153
- touchFile(manifestPath, JSON.stringify({ version: 2, inputPaths: ['/stale.ts'] }))
176
+ touchFile(manifestPath, JSON.stringify({ version: 1, inputPaths: ['/stale.ts'] }))
154
177
  expect(getOpenApiWatchInputs(resolver)).toEqual([])
155
- touchFile(manifestPath, JSON.stringify({ version: 1, inputPaths: [123] }))
178
+ touchFile(manifestPath, JSON.stringify({ version: 2, inputPaths: [123] }))
156
179
  expect(getOpenApiWatchInputs(resolver)).toEqual([])
157
180
  expect(getOpenApiGeneratorDependencies(resolver)).toBeNull()
158
- touchFile(manifestPath, JSON.stringify({ version: 1, inputPaths: [] }))
181
+ touchFile(manifestPath, JSON.stringify({ version: 2, inputPaths: [] }))
159
182
  expect(getOpenApiGeneratorDependencies(resolver)).toEqual([])
160
183
  })
161
184
 
@@ -205,28 +228,52 @@ export function buildOpenApiDocument(modules: any[], options: any) {
205
228
  expect(openApiDoc.paths['/api/demo/details']?.get?.summary).toBe('package details')
206
229
  })
207
230
 
208
- it('bundles into a per-run file and leaves no bundle behind', async () => {
231
+ it('uses the runtime metadata path for routes published outside their module prefix', async () => {
232
+ touchFile(
233
+ path.join(tmpDir, 'packages', 'core', 'src', 'modules', 'demo', 'api', 'policy', 'route.ts'),
234
+ [
235
+ 'export async function POST() { return new Response() }',
236
+ "export const metadata = { path: '/extensions/example/resolve', POST: { requireAuth: true } }",
237
+ "export const openApi = { POST: { summary: 'resolve example policy' } }",
238
+ ].join('\n'),
239
+ )
240
+ const resolver = createMockResolver([{ id: 'demo', from: '@open-mercato/core' }])
241
+ const result = await generateOpenApi({ resolver, quiet: true })
242
+ expect(result.errors).toEqual([])
243
+ const generatedPath = path.join(tmpDir, 'output', 'generated', 'openapi.generated.json')
244
+ const document = JSON.parse(fs.readFileSync(generatedPath, 'utf8')) as {
245
+ paths: Record<string, { post?: { summary?: string } }>
246
+ }
247
+ expect(document.paths['/api/extensions/example/resolve']?.post?.summary).toBe('resolve example policy')
248
+ expect(document.paths['/api/demo/policy']).toBeUndefined()
249
+ })
250
+
251
+ it('bundles from generated output and leaves the protected dependency cache untouched', async () => {
252
+ const dependency = path.join(tmpDir, 'node_modules', 'openapi-fixture')
253
+ touchFile(path.join(dependency, 'package.json'), '{"type":"module","exports":"./index.js"}')
254
+ touchFile(path.join(dependency, 'index.js'), "export const summary = 'package health'\n")
209
255
  touchFile(
210
256
  path.join(tmpDir, 'packages', 'core', 'src', 'modules', 'demo', 'api', 'health', 'route.ts'),
211
257
  [
258
+ "import { summary } from 'openapi-fixture'",
212
259
  'export async function GET() { return new Response("pkg-health") }',
213
- 'export const openApi = {',
214
- " GET: { summary: 'package health' }",
215
- '}',
260
+ 'export const openApi = { GET: { summary } }',
216
261
  '',
217
262
  ].join('\n'),
218
263
  )
219
- const cacheDir = path.join(tmpDir, 'node_modules', '.cache')
220
- touchFile(path.join(cacheDir, '_openapi-bundle.mjs'), 'export {}\n')
264
+ const dependencyCache = path.join(tmpDir, 'node_modules', '.cache')
265
+ touchFile(dependencyCache, 'protected dependency cache')
266
+ const resolver = createMockResolver([{ id: 'demo', from: '@open-mercato/core' }])
221
267
 
222
- const result = await generateOpenApi({ resolver: createMockResolver([{ id: 'demo', from: '@open-mercato/core' }]), quiet: true })
268
+ const result = await generateOpenApi({ resolver, quiet: true })
223
269
 
224
270
  expect(result.errors).toEqual([])
225
271
  const openApiDoc = JSON.parse(
226
- fs.readFileSync(path.join(tmpDir, 'output', 'generated', 'openapi.generated.json'), 'utf8'),
272
+ fs.readFileSync(path.join(resolver.getOutputDir(), 'openapi.generated.json'), 'utf8'),
227
273
  ) as { paths: Record<string, { get?: { summary?: string } }> }
228
274
  expect(openApiDoc.paths['/api/demo/health']?.get?.summary).toBe('package health')
229
- expect(fs.readdirSync(cacheDir).filter((name) => name.startsWith('_openapi-bundle'))).toEqual([])
275
+ expect(fs.readFileSync(dependencyCache, 'utf8')).toBe('protected dependency cache')
276
+ expect(fs.readdirSync(resolver.getOutputDir()).filter((name) => name.startsWith('.openapi-'))).toEqual([])
230
277
  })
231
278
 
232
279
  it('skips route discovery and bundling when all tracked inputs are unchanged', async () => {
@@ -639,9 +639,9 @@ describe('api-routes.generated.ts', () => {
639
639
  expect(content).toMatch(/methods:\s*\[\s*"GET",\s*"POST",\s*"PUT",\s*"DELETE",?\s*\]/)
640
640
  })
641
641
 
642
- it('keeps API handler imports lazy in route entries', () => {
642
+ it('keeps API handler imports lazy with the shared manifest loader type', () => {
643
643
  expect(content).toContain('@open-mercato/core/modules/orders/api')
644
- expect(content).toContain('load: async () => import(')
644
+ expect(content).toContain("load: async (): ReturnType<ApiRouteManifestEntry['load']> => import(")
645
645
  })
646
646
  })
647
647
 
@@ -449,6 +449,7 @@ export function objectFromEntries(value: GeneratedValue): WriterFunction {
449
449
  export function arrowFunction(options: {
450
450
  async?: boolean
451
451
  parameters?: string[]
452
+ returnType?: string
452
453
  body: WriterFunction
453
454
  }): WriterFunction {
454
455
  return (writer) => {
@@ -457,7 +458,11 @@ export function arrowFunction(options: {
457
458
  }
458
459
  writer.write('(')
459
460
  writeCommaSeparated(writer, options.parameters ?? [], (currentWriter, parameter) => currentWriter.write(parameter))
460
- writer.write(') => ')
461
+ writer.write(')')
462
+ if (options.returnType) {
463
+ writer.write(`: ${options.returnType}`)
464
+ }
465
+ writer.write(' => ')
461
466
  options.body(writer)
462
467
  }
463
468
  }
@@ -0,0 +1,111 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import type { PackageResolver } from '../resolver'
4
+ import { calculateStructureChecksum, createGeneratorResult, type GeneratorResult, writeGeneratedFile } from '../utils'
5
+
6
+ /**
7
+ * App cache-provider manifest generator.
8
+ *
9
+ * An app opts into third-party cache providers with `<app root>/src/providers/cache.ts`
10
+ * (or `src/providers/cache.js`). The file must
11
+ * export a named array:
12
+ *
13
+ * ```ts
14
+ * import type { CacheProviderRegistration } from '@open-mercato/cache/provider'
15
+ *
16
+ * export const cacheProviders: CacheProviderRegistration[] = [
17
+ * { id: 'acme/example', load: () => import('@acme/cache-example').then((mod) => mod.default), settings: () => ({}) },
18
+ * ]
19
+ * ```
20
+ *
21
+ * The generator only checks that the file exists — it never evaluates it — and
22
+ * writes `cache-providers.generated.ts`, which re-exports `cacheProviders` through a
23
+ * literal relative import (so bundlers and Next build tracing follow it) or, when
24
+ * the app has no manifest, exports an empty list.
25
+ */
26
+
27
+ export const CACHE_PROVIDERS_GENERATED_FILE = 'cache-providers.generated.ts'
28
+ export const CACHE_PROVIDERS_CHECKSUM_FILE = 'cache-providers.generated.checksum'
29
+ const CACHE_MANIFEST_BASENAME = 'src/providers/cache'
30
+
31
+ const SUPPORTED_MANIFEST_EXTENSIONS = ['.ts', '.js'] as const
32
+ const UNSUPPORTED_MANIFEST_EXTENSIONS = ['.tsx', '.mts', '.cts', '.mjs', '.cjs'] as const
33
+
34
+ export interface CacheProvidersOptions {
35
+ resolver: PackageResolver
36
+ quiet?: boolean
37
+ }
38
+
39
+ function manifestPaths(appDir: string, extensions: readonly string[]): string[] {
40
+ return extensions.map((extension) => path.join(appDir, `${CACHE_MANIFEST_BASENAME}${extension}`))
41
+ }
42
+
43
+ export function getCacheProviderManifestPaths(appDir: string): string[] {
44
+ return manifestPaths(appDir, [...SUPPORTED_MANIFEST_EXTENSIONS, ...UNSUPPORTED_MANIFEST_EXTENSIONS])
45
+ }
46
+
47
+ function manifestCandidates(appDir: string, extensions: readonly string[]): string[] {
48
+ return manifestPaths(appDir, extensions)
49
+ .filter((candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile())
50
+ }
51
+
52
+ export function findCacheProviderManifest(appDir: string): string | null {
53
+ const unsupported = manifestCandidates(appDir, UNSUPPORTED_MANIFEST_EXTENSIONS)
54
+ if (unsupported.length > 0) {
55
+ throw new Error(
56
+ `[internal] Unsupported cache provider manifest ${unsupported.map((file) => path.relative(appDir, file)).join(', ')}: ` +
57
+ `rename it to ${CACHE_MANIFEST_BASENAME}.ts (or ${CACHE_MANIFEST_BASENAME}.js).`,
58
+ )
59
+ }
60
+ const supported = manifestCandidates(appDir, SUPPORTED_MANIFEST_EXTENSIONS)
61
+ if (supported.length > 1) {
62
+ throw new Error(
63
+ `[internal] Multiple cache provider manifests found (${supported.map((file) => path.relative(appDir, file)).join(', ')}): keep exactly one.`,
64
+ )
65
+ }
66
+ return supported[0] ?? null
67
+ }
68
+
69
+ function toImportSpecifier(fromDir: string, manifestFile: string): string {
70
+ const withoutExtension = manifestFile.slice(0, -path.extname(manifestFile).length)
71
+ const relative = path.relative(fromDir, withoutExtension).split(path.sep).join('/')
72
+ return relative.startsWith('.') ? relative : `./${relative}`
73
+ }
74
+
75
+ export function renderCacheProvidersRegistry(outputDir: string, manifestFile: string | null): string {
76
+ const header = `// AUTO-GENERATED — do not edit by hand.
77
+ // Source: <app root>/${CACHE_MANIFEST_BASENAME}.ts (optional)
78
+ // Regenerate with: yarn generate
79
+ import type { CacheProviderRegistration } from '@open-mercato/cache/provider'
80
+ `
81
+ if (!manifestFile) {
82
+ return `${header}
83
+ export const cacheProviders: CacheProviderRegistration[] = []
84
+ `
85
+ }
86
+ return `${header}import { cacheProviders as appCacheProviders } from '${toImportSpecifier(outputDir, manifestFile)}'
87
+
88
+ export const cacheProviders: CacheProviderRegistration[] = appCacheProviders
89
+ `
90
+ }
91
+
92
+ export async function generateCacheProviders(options: CacheProvidersOptions): Promise<GeneratorResult> {
93
+ const { resolver, quiet } = options
94
+ const result = createGeneratorResult()
95
+ const outputDir = resolver.getOutputDir()
96
+ const appDir = resolver.getAppDir()
97
+ const manifestFile = findCacheProviderManifest(appDir)
98
+
99
+ writeGeneratedFile({
100
+ outFile: path.join(outputDir, CACHE_PROVIDERS_GENERATED_FILE),
101
+ checksumFile: path.join(outputDir, CACHE_PROVIDERS_CHECKSUM_FILE),
102
+ content: renderCacheProvidersRegistry(outputDir, manifestFile),
103
+ structureChecksum: calculateStructureChecksum(
104
+ manifestPaths(appDir, SUPPORTED_MANIFEST_EXTENSIONS),
105
+ ),
106
+ result,
107
+ quiet,
108
+ })
109
+
110
+ return result
111
+ }
@@ -0,0 +1,166 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript-js'
4
+ import { MODULE_CODE_EXTENSIONS, stripModuleCodeExtension } from './scanner'
5
+
6
+ export function unwrap(expression: ts.Expression): ts.Expression {
7
+ while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression)) {
8
+ expression = expression.expression
9
+ }
10
+ return expression
11
+ }
12
+
13
+ export function exportedDeclaration(source: ts.SourceFile, name: string): ts.Expression | undefined {
14
+ const exportedNames = new Set<string>()
15
+ for (const statement of source.statements) {
16
+ if (!ts.isExportDeclaration(statement) || statement.isTypeOnly || statement.moduleSpecifier || !statement.exportClause) continue
17
+ if (!ts.isNamedExports(statement.exportClause)) continue
18
+ for (const entry of statement.exportClause.elements) {
19
+ if (!entry.isTypeOnly && entry.name.text === name) exportedNames.add((entry.propertyName ?? entry.name).text)
20
+ }
21
+ }
22
+ for (const statement of source.statements) {
23
+ if (!ts.isVariableStatement(statement)) continue
24
+ const direct = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
25
+ for (const declaration of statement.declarationList.declarations) {
26
+ if (!ts.isIdentifier(declaration.name)) continue
27
+ if ((direct && declaration.name.text === name) || exportedNames.has(declaration.name.text)) return declaration.initializer
28
+ }
29
+ }
30
+ return undefined
31
+ }
32
+
33
+ export function fieldsOf(node: ts.Expression, invalid: (reason: string) => never): Map<string, ts.Expression> {
34
+ const literal = unwrap(node)
35
+ if (!ts.isObjectLiteralExpression(literal)) return invalid('expected an object literal')
36
+ const fields = new Map<string, ts.Expression>()
37
+ for (const property of literal.properties) {
38
+ if (!ts.isPropertyAssignment(property) || !(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))) {
39
+ return invalid('expected literal property assignments')
40
+ }
41
+ const name = property.name.text
42
+ if (fields.has(name)) return invalid(`duplicate property "${name}"`)
43
+ fields.set(name, property.initializer)
44
+ }
45
+ return fields
46
+ }
47
+
48
+ export function literalData(node: ts.Expression, invalid: (reason: string) => never): unknown {
49
+ const value = unwrap(node)
50
+ if (ts.isStringLiteralLike(value)) return value.text
51
+ if (ts.isNumericLiteral(value)) return Number(value.text)
52
+ if (value.kind === ts.SyntaxKind.NullKeyword) return null
53
+ if (value.kind === ts.SyntaxKind.TrueKeyword) return true
54
+ if (value.kind === ts.SyntaxKind.FalseKeyword) return false
55
+ if (ts.isArrayLiteralExpression(value)) return value.elements.map((element) => literalData(element, invalid))
56
+ if (ts.isObjectLiteralExpression(value)) {
57
+ return Object.fromEntries([...fieldsOf(value, invalid)]
58
+ .map(([key, entry]) => [key, literalData(entry, invalid)]))
59
+ }
60
+ return invalid('expected JSON-serializable client facts')
61
+ }
62
+
63
+ export function literalValue(node: ts.Expression | undefined, name: string, invalid: (reason: string) => never): string {
64
+ if (!node) return invalid(`missing literal ${name}`)
65
+ const literal = unwrap(node)
66
+ if (!ts.isStringLiteralLike(literal) || !literal.text) return invalid(`expected a non-empty literal ${name}`)
67
+ return literal.text
68
+ }
69
+
70
+ export function readIdentity(fields: ReadonlyMap<string, ts.Expression>, invalid: (reason: string) => never) {
71
+ const id = literalValue(fields.get('id'), 'id', invalid)
72
+ const roundTripId = literalValue(fields.get('roundTripId'), 'roundTripId', invalid)
73
+ const separator = roundTripId.lastIndexOf('@v')
74
+ if (separator < 0 || roundTripId.slice(0, separator) !== id || !/^[1-9][0-9]*$/.test(roundTripId.slice(separator + 2))) {
75
+ return invalid(`roundTripId "${roundTripId}" must be "${id}@v<positive-integer>"`)
76
+ }
77
+ return { id, roundTripId }
78
+ }
79
+
80
+ export function arrayField(
81
+ fields: ReadonlyMap<string, ts.Expression>,
82
+ name: string,
83
+ invalid: (reason: string) => never,
84
+ ): readonly ts.Expression[] {
85
+ const initializer = fields.get(name)
86
+ if (!initializer) return []
87
+ const literal = unwrap(initializer)
88
+ if (!ts.isArrayLiteralExpression(literal)) return invalid(`expected a literal ${name} array`)
89
+ return literal.elements
90
+ }
91
+
92
+ export function helperArgument(node: ts.Expression, name: string, invalid: (reason: string) => never): ts.Expression {
93
+ const call = unwrap(node)
94
+ if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression) || call.expression.text !== name || call.arguments.length !== 1) {
95
+ return invalid(`expected ${name} with one argument`)
96
+ }
97
+ return call.arguments[0]
98
+ }
99
+
100
+ export function getLocalSectionInitializer(source: ts.SourceFile, name: string): ts.Expression | undefined {
101
+ for (const statement of source.statements) {
102
+ if (!ts.isVariableStatement(statement)) continue
103
+ for (const declaration of statement.declarationList.declarations) {
104
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer
105
+ }
106
+ }
107
+ return undefined
108
+ }
109
+
110
+ export function readSectionBuilder(node: ts.Expression, invalid: (reason: string) => never): {
111
+ name: string
112
+ args: readonly ts.Expression[]
113
+ } {
114
+ const call = unwrap(node)
115
+ if (!ts.isCallExpression(call)) return invalid('expected a section builder call')
116
+ const builder = call.expression
117
+ if (ts.isIdentifier(builder)) return { name: builder.text, args: call.arguments }
118
+ if (ts.isPropertyAccessExpression(builder) && ts.isIdentifier(builder.expression)) {
119
+ return { name: builder.expression.text + '.' + builder.name.text, args: call.arguments }
120
+ }
121
+ return invalid('expected a named section builder')
122
+ }
123
+
124
+ export function readSectionRuntimeFields(
125
+ initializer: ts.Expression, source: ts.SourceFile, invalid: (reason: string) => never, seen: ReadonlySet<string> = new Set(),
126
+ sourceRoot?: string,
127
+ ): Map<string, ts.Expression> {
128
+ const value = unwrap(initializer)
129
+ if (ts.isIdentifier(value)) {
130
+ const key = source.fileName + ':' + value.text
131
+ if (seen.has(key)) return invalid(`cyclic section runtime "${value.text}"`)
132
+ const visited = new Set([...seen, key])
133
+ const local = getLocalSectionInitializer(source, value.text)
134
+ if (local) return readSectionRuntimeFields(local, source, invalid, visited, sourceRoot)
135
+ if (sourceRoot) {
136
+ for (const statement of source.statements) {
137
+ if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly
138
+ || !ts.isStringLiteral(statement.moduleSpecifier)) continue
139
+ const bindings = statement.importClause?.namedBindings
140
+ if (!bindings || !ts.isNamedImports(bindings)) continue
141
+ const imported = bindings.elements.find(({ name, isTypeOnly }) => !isTypeOnly && name.text === value.text)
142
+ if (!imported) continue
143
+ const specifier = statement.moduleSpecifier.text
144
+ if (!specifier.startsWith('./') || !stripModuleCodeExtension(specifier).endsWith('.client')) break
145
+ const base = path.resolve(path.dirname(source.fileName), stripModuleCodeExtension(specifier))
146
+ const candidate = MODULE_CODE_EXTENSIONS.map((extension) => base + extension)
147
+ .find((filename) => fs.statSync(filename, { throwIfNoEntry: false })?.isFile())
148
+ if (!candidate) break
149
+ const filename = fs.realpathSync(candidate)
150
+ const relative = path.relative(fs.realpathSync(sourceRoot), filename)
151
+ if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) break
152
+ const dependency = ts.createSourceFile(filename, fs.readFileSync(filename, 'utf8'), ts.ScriptTarget.Latest, true)
153
+ const declaration = exportedDeclaration(dependency, (imported.propertyName ?? imported.name).text)
154
+ if (declaration) return readSectionRuntimeFields(declaration, dependency, invalid, visited, sourceRoot)
155
+ break
156
+ }
157
+ }
158
+ return invalid(`section runtime "${value.text}" must have a local static declaration`)
159
+ }
160
+ if (!ts.isCallExpression(value)) return fieldsOf(value, invalid)
161
+ const { name, args } = readSectionBuilder(value, invalid)
162
+ if (!['defineCrudFormSectionRuntime', 'defineCrudFormFieldGranularSection'].includes(name) || args.length !== 1) {
163
+ return invalid('expected a supported static base section runtime')
164
+ }
165
+ return fieldsOf(args[0], invalid)
166
+ }