@open-mercato/cli 0.11.1-develop.8589.1.db1a76ea60 → 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 (285) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +3 -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-child-process.js +21 -3
  177. package/dist/lib/generate-child-process.js.map +2 -2
  178. package/dist/lib/generate-watch-events.js +135 -19
  179. package/dist/lib/generate-watch-events.js.map +2 -2
  180. package/dist/lib/generate-watch-plan.js +170 -0
  181. package/dist/lib/generate-watch-plan.js.map +7 -0
  182. package/dist/lib/generate-watch-runner.js +54 -0
  183. package/dist/lib/generate-watch-runner.js.map +7 -0
  184. package/dist/lib/generate-watch-structure.js +578 -203
  185. package/dist/lib/generate-watch-structure.js.map +3 -3
  186. package/dist/lib/generators/ast/writers.js +5 -1
  187. package/dist/lib/generators/ast/writers.js.map +2 -2
  188. package/dist/lib/generators/cache-providers.js +80 -0
  189. package/dist/lib/generators/cache-providers.js.map +7 -0
  190. package/dist/lib/generators/extensions/agent-files.js +1 -0
  191. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  192. package/dist/lib/generators/form-section-ast.js +156 -0
  193. package/dist/lib/generators/form-section-ast.js.map +7 -0
  194. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  195. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  196. package/dist/lib/generators/form-section-extension-source.js +245 -0
  197. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  198. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  199. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  200. package/dist/lib/generators/form-sections.js +773 -0
  201. package/dist/lib/generators/form-sections.js.map +7 -0
  202. package/dist/lib/generators/index.js +2 -0
  203. package/dist/lib/generators/index.js.map +2 -2
  204. package/dist/lib/generators/module-entities.js +21 -2
  205. package/dist/lib/generators/module-entities.js.map +2 -2
  206. package/dist/lib/generators/module-extension-facts.js +2 -1
  207. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  208. package/dist/lib/generators/module-facts.js +30 -1
  209. package/dist/lib/generators/module-facts.js.map +2 -2
  210. package/dist/lib/generators/module-override-targets.js +24 -2
  211. package/dist/lib/generators/module-override-targets.js.map +2 -2
  212. package/dist/lib/generators/module-registry.js +223 -194
  213. package/dist/lib/generators/module-registry.js.map +3 -3
  214. package/dist/lib/generators/openapi.js +51 -18
  215. package/dist/lib/generators/openapi.js.map +2 -2
  216. package/dist/lib/generators/web-research-adapters.js +54 -22
  217. package/dist/lib/generators/web-research-adapters.js.map +2 -2
  218. package/dist/lib/in-process-generate-watcher.js +98 -75
  219. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  220. package/dist/lib/post-generate-invalidation.js +20 -1
  221. package/dist/lib/post-generate-invalidation.js.map +2 -2
  222. package/dist/lib/resolver.js +195 -1
  223. package/dist/lib/resolver.js.map +3 -3
  224. package/dist/lib/single-instance-strategy-guard.js +26 -3
  225. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  226. package/dist/mercato.js +106 -50
  227. package/dist/mercato.js.map +2 -2
  228. package/jest.config.cjs +2 -0
  229. package/package.json +7 -7
  230. package/src/__tests__/mercato.test.ts +18 -0
  231. package/src/__tests__/rotation-json-output.test.ts +52 -0
  232. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  233. package/src/lib/__tests__/generate-child-process.test.ts +30 -0
  234. package/src/lib/__tests__/generate-watch-events.test.ts +377 -8
  235. package/src/lib/__tests__/generate-watch-plan.test.ts +99 -0
  236. package/src/lib/__tests__/generate-watch-runner.test.ts +138 -0
  237. package/src/lib/__tests__/generate-watch-structure.test.ts +556 -1
  238. package/src/lib/__tests__/in-process-generate-watcher.test.ts +393 -6
  239. package/src/lib/__tests__/module-inspection.test.ts +17 -11
  240. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  241. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  242. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  243. package/src/lib/cache-provider-manifest.ts +8 -0
  244. package/src/lib/generate-child-process.ts +26 -3
  245. package/src/lib/generate-watch-events.ts +189 -17
  246. package/src/lib/generate-watch-plan.ts +180 -0
  247. package/src/lib/generate-watch-runner.ts +63 -0
  248. package/src/lib/generate-watch-structure.ts +670 -227
  249. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  250. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  251. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  252. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  253. package/src/lib/generators/__tests__/incremental-registry.test.ts +262 -0
  254. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  255. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  256. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  257. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  258. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  259. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  260. package/src/lib/generators/__tests__/openapi.test.ts +147 -10
  261. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  262. package/src/lib/generators/__tests__/web-research-adapters.test.ts +298 -87
  263. package/src/lib/generators/ast/writers.ts +6 -1
  264. package/src/lib/generators/cache-providers.ts +111 -0
  265. package/src/lib/generators/extension.ts +2 -0
  266. package/src/lib/generators/extensions/agent-files.ts +1 -0
  267. package/src/lib/generators/form-section-ast.ts +166 -0
  268. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  269. package/src/lib/generators/form-section-extension-source.ts +308 -0
  270. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  271. package/src/lib/generators/form-sections.ts +896 -0
  272. package/src/lib/generators/index.ts +1 -0
  273. package/src/lib/generators/module-entities.ts +22 -4
  274. package/src/lib/generators/module-extension-facts.ts +1 -0
  275. package/src/lib/generators/module-facts.ts +40 -0
  276. package/src/lib/generators/module-override-targets.ts +19 -0
  277. package/src/lib/generators/module-registry.ts +246 -202
  278. package/src/lib/generators/openapi.ts +65 -20
  279. package/src/lib/generators/web-research-adapters.ts +76 -21
  280. package/src/lib/in-process-generate-watcher.ts +151 -96
  281. package/src/lib/post-generate-invalidation.ts +28 -1
  282. package/src/lib/resolver.ts +218 -0
  283. package/src/lib/single-instance-strategy-guard.ts +51 -1
  284. package/src/mercato.ts +117 -57
  285. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -0,0 +1,632 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { createHash } from 'node:crypto'
4
+ import ts from 'typescript-js'
5
+ import { escapeGeneratedJsonLiteral, stringLiteral } from './ast/writers'
6
+ import {
7
+ applyCrudFormSectionPlacements, canonicalSectionJson, compareSectionIds, crudFormSectionHostKey,
8
+ } from '@open-mercato/shared/lib/crud/form-sections/composition'
9
+ import { derivedCrudFormSectionRetryFact, projectCrudFormSectionClientMutationFact } from '@open-mercato/shared/lib/crud/form-sections/client-mutation-facts'
10
+ import type { CustomFieldDefinition, CustomFieldSet } from '@open-mercato/shared/modules/entities'
11
+ import type { CompiledCrudFormAlternative, CompiledCrudFormCustomField } from '@open-mercato/shared/lib/crud/form-sections/compiled-extensions'
12
+ import type { CrudFormSectionAddress, CrudFormSectionContributionFact, CrudFormSectionSurfaceAlternativeFact } from '@open-mercato/shared/modules/form-section-facts'
13
+ import type { CrudFormSectionClientHostFact } from '@open-mercato/shared/modules/form-sections'
14
+ import type { FormSectionOverride, FormSectionOverridesMap } from '@open-mercato/shared/modules/overrides'
15
+ import { InjectionPosition } from '@open-mercato/shared/modules/widgets/injection-position'
16
+ import { arrayField, exportedDeclaration, fieldsOf, literalData, literalValue, readIdentity, readSectionRuntimeFields } from './form-section-ast'
17
+ import {
18
+ sectionSymbol, type SectionExtensionChange, type SectionExtensionField, type SectionExtensionSource, type SectionBrowserLoader,
19
+ } from './form-section-extension-source'
20
+ import { hashCompiledSectionSource } from './form-section-runtime-revisions'
21
+
22
+ const maximumAlternatives = 128
23
+ const revisionFilename = 'form-sections.revisions.json'
24
+
25
+ type Invalid = (reason: string) => never
26
+ type Ownership = CrudFormSectionSurfaceAlternativeFact['ownershipFacts'][number]
27
+ type Revision = { n: number; baseRoundTripId: string | null; patchHash: string }
28
+ type Runtime = { source: ts.SourceFile; runtimePath: string }
29
+ type Write = { filename: string; content: string }
30
+
31
+ export type CompilerModule = {
32
+ moduleId: string
33
+ derivedRoutes?: readonly { index: number; hostDescriptorId: string; routePath: string; outboxRetry: boolean }[]
34
+ importPath: string
35
+ sourceBase: string
36
+ authoredSource: boolean
37
+ extensionSources: readonly SectionExtensionSource[]
38
+ clientHosts: CrudFormSectionClientHostFact[]
39
+ contributedOverrides: FormSectionOverridesMap
40
+ runtimeSources: ReadonlyMap<string, Runtime>
41
+ customFieldSeedEntities: ReadonlyMap<string, Readonly<Record<string, string>>>
42
+ primitiveContributions: readonly Pick<CrudFormSectionContributionFact, 'id' | 'address' | 'operation'>[]
43
+ }
44
+ type AuthoredChange = { module: CompilerModule; extension: SectionExtensionSource; change: SectionExtensionChange }
45
+ type CompiledField = { authored: AuthoredChange; field: SectionExtensionField; payloadPath?: string; customField?: CompiledCrudFormCustomField; seed?: CustomFieldDefinition }
46
+ type CompiledChange = {
47
+ id: string
48
+ source: AuthoredChange
49
+ target: Omit<CrudFormSectionAddress, 'sectionId'>
50
+ override: FormSectionOverride
51
+ ownership?: Ownership
52
+ contribution: CrudFormSectionContributionFact
53
+ file: string
54
+ fields: CompiledField[]
55
+ sinks: { id: string; roundTripId: string; capabilityId: string; hostDetailEntityId: string; fields: CompiledField[] }[]
56
+ defaults: { owner: AuthoredChange; id: string; payloadPath: string; readsPayloadPaths: readonly string[]; scoped: boolean }[]
57
+ }
58
+
59
+ export type CompiledSectionExtensions = {
60
+ contributionsByModule: ReadonlyMap<string, readonly CompiledChange[]>
61
+ alternativesByModule: ReadonlyMap<string, readonly CompiledCrudFormAlternative[]>
62
+ runtimeFiles: readonly { name: string; content: string }[]
63
+ revisionWrites: readonly Write[]
64
+ fallbacks: FormSectionOverridesMap
65
+ customFieldSetsByModule: ReadonlyMap<string, readonly CustomFieldSet[]>
66
+ }
67
+
68
+ function includesDefaultTarget(targets: SectionExtensionSource['defaults'][number]['targets'], target: Omit<CrudFormSectionAddress, 'sectionId'>): boolean {
69
+ return !targets || targets.some(({ formVariant, formOperation }) =>
70
+ formVariant === target.formVariant && formOperation === target.formOperation)
71
+ }
72
+
73
+ function digest(value: unknown): string {
74
+ return createHash('sha256').update(canonicalSectionJson(value)).digest('hex')
75
+ }
76
+
77
+ function validPath(value: string): boolean {
78
+ return /^[a-zA-Z0-9_:-]+(?:\.[a-zA-Z0-9_:-]+)*$/.test(value)
79
+ && !value.split('.').some((component) => ['constructor', 'prototype', '__proto__'].includes(component))
80
+ }
81
+
82
+ function readRevisions(module: CompilerModule, invalid: Invalid) {
83
+ const filename = path.join(module.sourceBase, revisionFilename)
84
+ const stats = fs.lstatSync(filename, { throwIfNoEntry: false })
85
+ const original = stats?.isFile() ? fs.readFileSync(filename, 'utf8') : ''
86
+ let values: unknown
87
+ try { values = original ? JSON.parse(original) : {} } catch { return invalid(`invalid ${revisionFilename}`) }
88
+ if ((stats && !stats.isFile()) || !values || typeof values !== 'object' || Array.isArray(values)) return invalid(`invalid ${revisionFilename}`)
89
+ const revisions = new Map<string, Revision>()
90
+ for (const [id, value] of Object.entries(values)) {
91
+ if (!value || typeof value !== 'object' || !Number.isSafeInteger(value.n) || value.n < 1
92
+ || (value.baseRoundTripId !== null && typeof value.baseRoundTripId !== 'string')
93
+ || typeof value.patchHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.patchHash)) {
94
+ return invalid(`invalid revision for "${id}" in ${revisionFilename}`)
95
+ }
96
+ revisions.set(id, value)
97
+ }
98
+ return { filename, original, revisions }
99
+ }
100
+
101
+ function runtimeFields(runtime: Runtime, invalid: Invalid) {
102
+ const initializer = exportedDeclaration(runtime.source, 'crudFormSectionRuntime')
103
+ if (!initializer) return invalid('missing crudFormSectionRuntime')
104
+ return readSectionRuntimeFields(initializer, runtime.source, invalid)
105
+ }
106
+
107
+ function granularFields(base: Map<string, ts.Expression>, invalid: Invalid): Map<string, string[]> {
108
+ const paths = base.get('fieldPayloadPaths')
109
+ if (!paths || !base.has('fieldSchemas') || !base.has('projectField')) return invalid('modify requires a field-granular base descriptor')
110
+ return new Map([...fieldsOf(paths, invalid)].map(([field, entry]) => {
111
+ const values = literalData(entry, invalid)
112
+ if (!Array.isArray(values) || values.some((value: unknown) => typeof value !== 'string' || !validPath(value))) {
113
+ return invalid(`invalid payload paths for base field "${field}"`)
114
+ }
115
+ return [field, values as string[]]
116
+ }))
117
+ }
118
+
119
+ function baseDescriptor(runtime: Runtime, sectionId: string, invalid: Invalid, sourceRoot: string) {
120
+ const fields = runtimeFields(runtime, invalid)
121
+ const section = (fields.has('sectionDescriptors')
122
+ ? arrayField(fields, 'sectionDescriptors', invalid).map((entry) => readSectionRuntimeFields(entry, runtime.source, invalid, new Set(), sourceRoot))
123
+ : [fields]).find((entry) => {
124
+ const group = entry.get('group')
125
+ return group && literalData(fieldsOf(group, invalid).get('id')!, invalid) === sectionId
126
+ })
127
+ if (!section) return invalid(`host did not publish a runtime descriptor for section "${sectionId}"`)
128
+ return section
129
+ }
130
+
131
+ function exactPaths(values: readonly string[]) {
132
+ return [...values].sort(compareSectionIds)
133
+ }
134
+
135
+ function matchingPaths(left: readonly string[], right: readonly string[]): boolean {
136
+ return canonicalSectionJson(exactPaths(left)) === canonicalSectionJson(exactPaths(right))
137
+ }
138
+
139
+ function pathsOverlap(paths: readonly string[]): boolean {
140
+ const ordered = exactPaths(paths)
141
+ return ordered.some((entry, index) => ordered.slice(index + 1).some((other) => other === entry || other.startsWith(entry + '.')))
142
+ }
143
+
144
+ function explicitPlacement(change: SectionExtensionChange): FormSectionOverride & { operation: 'add' } {
145
+ const relativeTo = change.before ?? change.after
146
+ const position = change.before ? InjectionPosition.Before : change.after ? InjectionPosition.After : InjectionPosition.Last
147
+ return { operation: 'add', contributionId: '', ...(relativeTo ? { placement: { relativeTo, position } } : {}) }
148
+ }
149
+
150
+ function overrideKey({ hostId, formVariant, formOperation, sectionId }: CrudFormSectionAddress) {
151
+ return [hostId, formVariant, formOperation, sectionId].join('/')
152
+ }
153
+
154
+ function renderBrowserRuntime(candidate: CompiledChange, hostRuntime: Runtime, customDefinitionSet: string | undefined): string {
155
+ const { contribution, source, fields } = candidate
156
+ const identity = { id: contribution.id, roundTripId: contribution.roundTripId }
157
+ const { change } = source
158
+ const output = ['// Auto-generated by yarn generate. Do not edit.']
159
+ const identityLiteral = escapeGeneratedJsonLiteral(JSON.stringify(identity))
160
+ if (change.operation === 'hide') return [...output, `export const crudFormSectionRuntime = ${identityLiteral} as const`, ''].join('\n')
161
+ if (change.replacement) {
162
+ return [...output,
163
+ `import { crudFormSectionRuntime as replacement } from ${stringLiteral(change.replacement.importPath)}`,
164
+ `export const crudFormSectionRuntime = { ...replacement, ...${identityLiteral} }`, '',
165
+ ].join('\n')
166
+ }
167
+ const helpers = [
168
+ 'deriveCrudFormFieldGranularSection',
169
+ ...(change.operation === 'modify' ? ['getCrudFormFieldGranularBase'] : []),
170
+ ...(fields.some(({ field }) => field.loaders.options) ? ['crudFormExtensionOptionsLoader'] : []),
171
+ ]
172
+ output.push(`import { ${helpers.join(', ')} } from '@open-mercato/ui/backend/crud-form-field-granular'`)
173
+ if (change.operation === 'modify') {
174
+ output.push(`import { crudFormSectionRuntime as hostRuntime } from ${stringLiteral(hostRuntime.runtimePath)}`)
175
+ output.push(`const base = getCrudFormFieldGranularBase(hostRuntime, ${stringLiteral(change.id)})`)
176
+ }
177
+ const imports: string[] = []
178
+ const prepared: string[] = []
179
+ const address = escapeGeneratedJsonLiteral(JSON.stringify(contribution.address))
180
+ for (const [index, item] of fields.entries()) {
181
+ const { field, payloadPath } = item
182
+ const fieldId = stringLiteral(field.id)
183
+ const payloadPathLiteral = payloadPath === undefined ? 'undefined' : stringLiteral(payloadPath)
184
+ const settings: string[] = []
185
+ for (const [kind, loader] of Object.entries(field.loaders)) {
186
+ const variable = `field${index}${kind}`
187
+ imports.push(`import ${variable} from ${stringLiteral((loader as SectionBrowserLoader).importPath)}`)
188
+ if (kind === 'options') settings.push(`loadOptions: crudFormExtensionOptionsLoader(${variable}, () => ({ address: ${address}, fieldId: ${fieldId}, payloadPath: ${payloadPathLiteral}, values: {} }))`)
189
+ else settings.push(`${kind}: ${variable}`)
190
+ }
191
+ if (field.loaders.clientRule) settings.push(`validationPayloadPath: ${payloadPathLiteral}`)
192
+ if (settings.length) prepared.push(`${fieldId}: { ${settings.join(', ')} }`)
193
+ }
194
+ output.push(...imports)
195
+ const changes = Object.fromEntries(fields.map(({ field }) => [field.id, field.operation === 'remove' ? { operation: 'remove' }
196
+ : { operation: field.operation, [field.operation === 'add' ? 'definition' : 'patch']: field.browser }]))
197
+ const added = Object.fromEntries(fields.filter(({ field }) => field.operation === 'add').map(({ field, payloadPath }) => [field.id, payloadPath]))
198
+ output.push('export const crudFormSectionRuntime = deriveCrudFormFieldGranularSection({',
199
+ ` identity: ${identityLiteral}, address: ${address},`,
200
+ ...(change.operation === 'modify' ? [' base,'] : []),
201
+ ...(change.titleKey ? [` titleKey: ${stringLiteral(change.titleKey)},`] : []),
202
+ ...(customDefinitionSet ? [` customFieldDefinitionSetId: ${stringLiteral(customDefinitionSet)},`] : []),
203
+ ` changes: ${escapeGeneratedJsonLiteral(JSON.stringify(changes))}, addedPayloadPaths: ${escapeGeneratedJsonLiteral(JSON.stringify(added))},`,
204
+ ` prepared: { ${prepared.join(', ')} },`, '})', '')
205
+ return output.join('\n')
206
+ }
207
+
208
+ function surfaceKey(surface: CrudFormSectionSurfaceAlternativeFact): string | null {
209
+ return surface.hostId === null ? null : crudFormSectionHostKey({ ...surface, hostId: surface.hostId })
210
+ }
211
+
212
+ function chooseProof(host: CrudFormSectionClientHostFact, baseline: CrudFormSectionSurfaceAlternativeFact) {
213
+ if (baseline.clientMutationSurfaces?.some(({ kind }) => kind === 'parent-submit')) return baseline
214
+ const proofs = host.alternatives.filter((surface) => surfaceKey(surface) === surfaceKey(baseline)
215
+ && surface.clientMutationSurfaces?.some(({ kind }) => kind === 'parent-submit'))
216
+ const signatures = new Set(proofs.map(({ clientMutationSurfaces }) => canonicalSectionJson(clientMutationSurfaces)))
217
+ return signatures.size === 1 ? proofs[0] : undefined
218
+ }
219
+
220
+ export function compileCrudFormSectionExtensions(
221
+ modules: readonly CompilerModule[], configured: Readonly<FormSectionOverridesMap>,
222
+ ): CompiledSectionExtensions {
223
+ const contributionsByModule = new Map<string, CompiledChange[]>()
224
+ const alternativesByModule = new Map<string, CompiledCrudFormAlternative[]>()
225
+ const runtimeFiles: { name: string; content: string }[] = []
226
+ const ledgers = new Map<string, ReturnType<typeof readRevisions>>()
227
+ const fallbacks: FormSectionOverridesMap = {}
228
+ const primitiveOverrides = Object.assign({}, ...modules.map(({ contributedOverrides }) => contributedOverrides)) as FormSectionOverridesMap
229
+ const primitiveClaims = new Map(modules.flatMap(({ primitiveContributions }) =>
230
+ primitiveContributions.map((fact) => [fact.id, fact] as const)))
231
+ const ids = new Set<string>()
232
+ const extensionIds = new Set<string>()
233
+ const seeds = new Map<string, { moduleId: string; entity: string; field: CustomFieldDefinition }>()
234
+ const tuples = new Map<string, { target: CompiledChange['target']; changes: AuthoredChange[] }>()
235
+ const diagnostics = (module: CompilerModule, reason: string): never => {
236
+ throw new Error(`[generate] crudFormExtensions for "${module.moduleId}" (${module.sourceBase}): ${reason}`)
237
+ }
238
+ for (const module of modules) for (const extension of module.extensionSources) {
239
+ if (extensionIds.has(extension.id)) diagnostics(module, `duplicate extension id "${extension.id}"`)
240
+ extensionIds.add(extension.id)
241
+ for (const target of extension.targets) {
242
+ const address = { hostId: extension.hostId, ...target }
243
+ const key = crudFormSectionHostKey(address)
244
+ const current = tuples.get(key) ?? { target: address, changes: [] }
245
+ current.changes.push(...extension.changes.map((change) => ({ module, extension, change })))
246
+ tuples.set(key, current)
247
+ }
248
+ }
249
+ for (const [key, { target, changes }] of [...tuples.entries()].sort(([left], [right]) => compareSectionIds(left, right))) {
250
+ const invalid: Invalid = (reason) => diagnostics(changes[0].module, reason)
251
+ const matches = modules.flatMap((module) => module.clientHosts.flatMap((host) => host.alternatives
252
+ .filter((surface) => !surface.contributionIds.length && surfaceKey(surface) === key)
253
+ .map((baseline) => ({ module, host, baseline }))))
254
+ if (matches.length !== 1) return invalid(`expected one published host and baseline for ${key}`)
255
+ const [{ module: hostModule, host, baseline }] = matches
256
+ const runtime = hostModule.runtimeSources.get(host.id)
257
+ const seedEntities = hostModule.customFieldSeedEntities.get(host.id) ?? {}
258
+ if (!runtime) return invalid(`host runtime missing for ${key}`)
259
+ const needsMutation = changes.some(({ change }) => change.operation !== 'add' || change.fields.length > 0)
260
+ const proof = needsMutation ? chooseProof(host, baseline) : baseline
261
+ if (!proof) return invalid(`host ${key} has no unambiguous parent-submit façade proof`)
262
+ const mutationIds = proof.clientMutationSurfaces?.filter(({ kind, requestOperation }) =>
263
+ kind === 'parent-submit' && requestOperation === target.formOperation).map(({ id }) => id) ?? []
264
+ if (needsMutation && mutationIds.length !== 1) return invalid(`host ${key} requires one exact parent-submit surface`)
265
+ const groups = new Map<string, AuthoredChange[]>()
266
+ for (const authored of changes) {
267
+ const { change } = authored
268
+ const owners = groups.get(change.id) ?? []
269
+ owners.push(authored)
270
+ groups.set(change.id, owners)
271
+ }
272
+
273
+ function compile(source: AuthoredChange, members: readonly AuthoredChange[], declarationId: string): CompiledChange {
274
+ const { module, change } = source
275
+ const invalid: Invalid = (reason) => diagnostics(module, reason)
276
+ const id = sectionSymbol(declarationId, 'derived descriptor ID', invalid)
277
+ if (ids.has(id)) invalid(`duplicate derived section "${id}"`)
278
+ ids.add(id)
279
+ const address = { ...target, sectionId: change.id }
280
+ if (baseline.orderedSectionIds.includes(change.id) === (change.operation === 'add')) invalid(`invalid section target "${change.id}" for "${id}"`)
281
+ const ownership = baseline.ownershipFacts.find(({ sectionId }) => sectionId === change.id)
282
+ const base = change.operation === 'add' ? undefined : baseDescriptor(runtime!, change.id, invalid, hostModule.sourceBase)
283
+ const baseRoundTripId = base ? readIdentity(base, invalid).roundTripId : null
284
+ let descriptor = base
285
+ const standardPaths = new Set(ownership?.payloadPaths)
286
+ const authoredCustom = ownership?.customFieldOwnership ?? { mode: 'none' }
287
+ const customKeys = new Set(authoredCustom.mode === 'ids' ? authoredCustom.ids : [])
288
+ const customDefinitionSets = new Set(baseline.ownershipFacts.flatMap(({ customFieldOwnership }) =>
289
+ customFieldOwnership.mode !== 'none' && customFieldOwnership.definitionSetId ? [customFieldOwnership.definitionSetId] : []))
290
+ const definitionSet = authoredCustom.mode !== 'none' && authoredCustom.definitionSetId
291
+ ? authoredCustom.definitionSetId : customDefinitionSets.size === 1 ? [...customDefinitionSets][0]
292
+ : Object.keys(seedEntities).length === 1 ? Object.keys(seedEntities)[0] : undefined
293
+ const byField = change.operation === 'modify' && base ? granularFields(base, invalid) : new Map<string, string[]>()
294
+ if (byField.size && (!matchingPaths([...byField.values()].flat().filter((leaf) => !leaf.startsWith('customFields.')), [...standardPaths])
295
+ || [...byField.values()].flat().some((leaf) => leaf.startsWith('customFields.') && !customKeys.has(leaf.slice('customFields.'.length))))) {
296
+ return invalid(`granular section "${change.id}" diverges from published payload ownership`)
297
+ }
298
+ const changedFields = members.flatMap((authored): CompiledField[] => authored.change.fields.map((field) => ({ field, authored })))
299
+ const removed = new Set(changedFields.filter(({ field }) => field.operation === 'remove').map(({ field }) => field.id))
300
+ if (base && removed.size) for (const entry of arrayField(base, 'refinements', invalid)) {
301
+ const refinement = fieldsOf(entry, invalid)
302
+ const mandatory = refinement.get('mandatory')
303
+ if (!mandatory || literalData(mandatory, invalid) !== true) continue
304
+ if (arrayField(refinement, 'fieldPaths', invalid).some((field) => removed.has(literalValue(field, 'refinement field', invalid)))) {
305
+ invalid(`removal intersects mandatory refinement "${literalValue(refinement.get('id'), 'refinement id', invalid)}"`)
306
+ }
307
+ }
308
+ if (change.replacement) {
309
+ const alternate = runtimeFields({ source: change.replacement.source, runtimePath: change.replacement.importPath }, invalid)
310
+ descriptor = alternate
311
+ const group = alternate.get('group')
312
+ if (!group || literalValue(fieldsOf(group, invalid).get('id'), 'replacement group', invalid) !== change.id) invalid('replacement group does not match the base section')
313
+ const ownedPaths = alternate.get('ownedPayloadPaths') ?? alternate.get('ownedFieldPaths')
314
+ const alternativePaths = alternate.has('fieldPayloadPaths') ? [...granularFields(alternate, invalid).values()].flat()
315
+ : ownedPaths ? literalData(ownedPaths, invalid) : undefined
316
+ if (!Array.isArray(alternativePaths) || !matchingPaths(alternativePaths.filter((leaf) => typeof leaf === 'string' && !leaf.startsWith('customFields.')), [...standardPaths])) {
317
+ invalid(`replacement must preserve exact payload ownership for "${change.id}"`)
318
+ }
319
+ const custom = alternate.get('ownedCustomFieldIds')
320
+ const keys = custom ? literalData(custom, invalid) : []
321
+ const replacementSet = alternate.get('customFieldDefinitionSetId')
322
+ if ((authoredCustom.mode !== 'none' && authoredCustom.definitionSetId !== (replacementSet && literalData(replacementSet, invalid)))
323
+ || (authoredCustom.mode === 'all' ? keys !== 'all' : !Array.isArray(keys) || !matchingPaths(keys, [...customKeys]))) {
324
+ invalid(`replacement must preserve exact custom-field ownership for "${change.id}"`)
325
+ }
326
+ }
327
+ for (const item of changedFields) {
328
+ const { field, authored } = item
329
+ const prior = byField.get(field.id)
330
+ if (field.operation === 'add') {
331
+ if (prior) invalid(`field "${field.id}" is already declared`)
332
+ if (!validPath(field.id)) invalid(`invalid added payload key "${field.id}"`)
333
+ const store = field.store!
334
+ if (store.kind === 'customField') {
335
+ if (!definitionSet || authoredCustom.mode === 'all') invalid(`custom field "${field.id}" requires a bounded host definition set`)
336
+ const fieldKey = store.key ?? field.id
337
+ if (!/^[a-z0-9_]{1,100}$/.test(fieldKey) || customKeys.has(fieldKey)) invalid(`invalid or duplicate snake_case custom field "${fieldKey}"`)
338
+ const entityId = definitionSet && Object.hasOwn(seedEntities, definitionSet) ? seedEntities[definitionSet] : undefined
339
+ if (!entityId || !definitionSet) return invalid(`custom field "${field.id}" needs a published host customFieldSeedEntities binding`)
340
+ const type = field.browser.type
341
+ const kind = type === 'number' ? 'float' : type === 'textarea' ? 'multiline' : type
342
+ if (kind !== 'text' && kind !== 'multiline' && kind !== 'float' && kind !== 'boolean' && kind !== 'date' && kind !== 'select') {
343
+ return invalid(`custom field "${field.id}" requires a supported custom-field kind`)
344
+ }
345
+ const options = field.browser.options
346
+ if (kind === 'select' && (!Array.isArray(options) || !options.length || field.loaders.options
347
+ || options.some((entry) => !entry || typeof entry.value !== 'string' || typeof entry.labelKey !== 'string'))) {
348
+ return invalid(`custom-field select "${field.id}" requires literal options and label keys`)
349
+ }
350
+ const label = typeof field.browser.labelKey === 'string' ? field.browser.labelKey : `${id}.fields.${field.id}`
351
+ item.customField = { definitionSetId: definitionSet, entityId, key: fieldKey, kind }
352
+ item.seed = { key: fieldKey, kind, label, required: field.browser.required === true, formEditable: true, sectionOnly: true, listVisible: false,
353
+ ...(kind === 'select' && Array.isArray(options) ? { options: options.map(({ value, labelKey }) => ({ value, label: labelKey })) } : {}) }
354
+ customKeys.add(fieldKey)
355
+ item.payloadPath = `customFields.${fieldKey}`
356
+ } else {
357
+ if (!store.entityId?.startsWith(authored.module.moduleId + ':')) invalid(`store target "${store.entityId}" must be owned by "${authored.module.moduleId}"`)
358
+ if (field.id.includes('.') || !validPath(authored.module.moduleId)) invalid('extension sink keys must be literal single segments')
359
+ item.payloadPath = `extensions.${authored.module.moduleId}.${field.id}`
360
+ if (standardPaths.has(item.payloadPath)) invalid(`duplicate payload path "${item.payloadPath}"`)
361
+ standardPaths.add(item.payloadPath)
362
+ }
363
+ } else {
364
+ if (!prior) return invalid(`unknown base field "${field.id}"`)
365
+ if (field.operation === 'remove') for (const leaf of prior) {
366
+ if (leaf.startsWith('customFields.')) customKeys.delete(leaf.slice('customFields.'.length))
367
+ else standardPaths.delete(leaf)
368
+ }
369
+ if (field.loaders.clientRule || field.loaders.options || field.server || field.rules.some(({ enforce }) => enforce === 'client-and-server')) {
370
+ if (prior.length !== 1) invalid(`field "${field.id}" needs one exact rule or option payload path`)
371
+ item.payloadPath = prior[0]
372
+ }
373
+ }
374
+ }
375
+ const resultOwnership: Ownership | undefined = change.operation === 'hide' ? undefined : {
376
+ sectionId: change.id, payloadPaths: exactPaths([...standardPaths]),
377
+ customFieldOwnership: authoredCustom.mode === 'all' ? authoredCustom : customKeys.size
378
+ ? { mode: 'ids', ids: exactPaths([...customKeys]), ...(definitionSet ? { definitionSetId: definitionSet } : {}) } : { mode: 'none' },
379
+ }
380
+ const baseSyntax = base?.get('group')?.parent.parent
381
+ const patchHash = digest({
382
+ base: baseSyntax && ts.isObjectLiteralExpression(baseSyntax) ? hashCompiledSectionSource(baseSyntax, hostModule.sourceBase) : null,
383
+ changes: members.map(({ module: owner, extension, change: changed }) => ({
384
+ module: owner.moduleId,
385
+ source: hashCompiledSectionSource(changed.syntax, owner.sourceBase),
386
+ defaults: extension.defaults.map(({ syntax }) => hashCompiledSectionSource(syntax, owner.sourceBase)),
387
+ replacement: changed.replacement ? hashCompiledSectionSource(exportedDeclaration(changed.replacement.source, 'crudFormSectionRuntime')!, owner.sourceBase) : null,
388
+ })),
389
+ })
390
+ const ledger = ledgers.get(module.moduleId) ?? readRevisions(module, invalid)
391
+ ledgers.set(module.moduleId, ledger)
392
+ const previous = ledger.revisions.get(id)
393
+ if (!module.authoredSource && (!previous || previous.baseRoundTripId !== baseRoundTripId)) {
394
+ return invalid('packaged extension requires its reviewed revision ledger and a matching base revision')
395
+ }
396
+ const current = previous && (!module.authoredSource || (previous.baseRoundTripId === baseRoundTripId && previous.patchHash === patchHash))
397
+ ? previous : { n: (previous?.n ?? 0) + 1, baseRoundTripId, patchHash }
398
+ if (!Number.isSafeInteger(current.n)) invalid('descriptor revision exhausted')
399
+ ledger.revisions.set(id, current)
400
+ const roundTripId = `${id}@v${current.n}`
401
+ const operation = change.operation === 'modify' ? 'replace' : change.operation
402
+ const file = `crud-form-section-extension-${digest(id).slice(0, 20)}.generated.ts`
403
+ const sinkGroups = new Map<string, CompiledField[]>()
404
+ for (const item of changedFields) {
405
+ const { authored, field } = item
406
+ if (!field.store || field.store.kind === 'customField') continue
407
+ const key = canonicalSectionJson([authored.module.moduleId,
408
+ field.store.kind === 'table' ? field.store.entityId : authored.extension.id,
409
+ field.store.kind === 'table' ? null : field.store.fieldOverride ? field.id : null])
410
+ const group = sinkGroups.get(key) ?? []
411
+ group.push(item)
412
+ sinkGroups.set(key, group)
413
+ }
414
+ const sinks = [...sinkGroups.entries()].map(([key, group]) => {
415
+ const sinkId = `${id}.sink-${digest(key).slice(0, 12)}`
416
+ if (!host.hostResourceKind) return invalid('sink requires an exact host detail resource')
417
+ return { id: sinkId, roundTripId: `${sinkId}@v${current.n}`, capabilityId: `${sinkId}.capability`,
418
+ hostDetailEntityId: host.hostResourceKind, fields: group }
419
+ })
420
+ const displayOnly = change.operation === 'add' && !changedFields.length
421
+ const requiredSectionIds = descriptor && operation !== 'hide'
422
+ ? arrayField(descriptor, 'requiredSectionIds', invalid).map((entry) => literalValue(entry, 'required section id', invalid)) : []
423
+ const requiredDataContractIds = descriptor && operation !== 'hide'
424
+ ? arrayField(descriptor, 'requiredDataContractIds', invalid).map((entry) => literalValue(entry, 'required data contract id', invalid)) : []
425
+ const contribution: CrudFormSectionContributionFact = {
426
+ id, address, operation, roundTripId,
427
+ ...(requiredSectionIds.length ? { requiredSectionIds } : {}),
428
+ ...(requiredDataContractIds.length ? { requiredDataContractIds } : {}),
429
+ requiredCapabilities: [{ capabilityId: `${id}.compiled`, protocol: 'crud-form-sections/v1',
430
+ modes: displayOnly ? ['display-only'] : ['domain-adapter'], mutationSurfaceIds: displayOnly ? [] : mutationIds,
431
+ payloadPaths: (resultOwnership?.payloadPaths ?? []).filter((path) => !path.startsWith('extensions.')),
432
+ customFieldOwnership: resultOwnership?.customFieldOwnership ?? { mode: 'none' } },
433
+ ...sinks.map(({ capabilityId, fields }): CrudFormSectionContributionFact['requiredCapabilities'][number] => ({
434
+ capabilityId, protocol: 'crud-form-sections/v1', modes: ['extension-sink'], mutationSurfaceIds: mutationIds,
435
+ payloadPaths: fields.map(({ payloadPath }) => payloadPath!), allowAfterCommitSink: true,
436
+ }))],
437
+ }
438
+ const dropped = (ownership?.payloadPaths ?? []).filter((leaf) => !resultOwnership?.payloadPaths.includes(leaf))
439
+ const defaults = members.flatMap((owner) => owner.extension.defaults.filter(({ payloadPath, targets }) =>
440
+ dropped.includes(payloadPath) && includesDefaultTarget(targets, target)).map(({ payloadPath, readsPayloadPaths, targets }) => ({
441
+ owner, payloadPath, readsPayloadPaths, scoped: !!targets, id: `${id}.default-${digest(payloadPath).slice(0, 12)}`,
442
+ })))
443
+ const override: FormSectionOverride = change.operation === 'add'
444
+ ? { ...explicitPlacement(change), contributionId: id } : { operation: operation as 'hide' | 'replace', contributionId: id }
445
+ const result: CompiledChange = { id, source, target, override, ownership: displayOnly ? undefined : resultOwnership, contribution, file, defaults, sinks, fields: changedFields }
446
+ const moduleContributions = contributionsByModule.get(module.moduleId) ?? []
447
+ moduleContributions.push(result)
448
+ contributionsByModule.set(module.moduleId, moduleContributions)
449
+ const ownedDefinitionSet = resultOwnership?.customFieldOwnership.mode !== 'none'
450
+ ? resultOwnership?.customFieldOwnership.definitionSetId : undefined
451
+ runtimeFiles.push({ name: file, content: renderBrowserRuntime(result, runtime!, ownedDefinitionSet) })
452
+ return result
453
+ }
454
+
455
+ const published = host.alternatives.filter((surface) => surfaceKey(surface) === key)
456
+ const selections: CompiledChange[][] = []
457
+ const effective: CompiledChange[] = []
458
+ for (const [sectionId, authors] of [...groups.entries()].sort(([left], [right]) => compareSectionIds(left, right))) {
459
+ authors.sort((left, right) => compareSectionIds(left.module.moduleId, right.module.moduleId))
460
+ const alternatives = authors.map((author) => {
461
+ const extensionId = author.extension.targets.length === 1 ? author.extension.id
462
+ : `${author.extension.id}.${target.formVariant}.${target.formOperation}`
463
+ return compile(author, [author], `${extensionId}.${sectionId}`)
464
+ })
465
+ const fieldIds = authors.flatMap(({ change }) => change.fields.map(({ id }) => id))
466
+ const addedLeaves = alternatives.flatMap(({ fields }) => fields.flatMap(({ field, payloadPath }) =>
467
+ field.operation === 'add' && payloadPath ? [payloadPath] : []))
468
+ const canCompose = authors.length > 1 && authors.every(({ change }) => change.operation === 'modify')
469
+ && new Set(fieldIds).size === fieldIds.length && !pathsOverlap(addedLeaves)
470
+ const first = authors[0]
471
+ const fallback = canCompose
472
+ ? compile(first, authors, `${first.extension.id}.combined-${digest(alternatives.map(({ id }) => id)).slice(0, 12)}.${sectionId}`)
473
+ : alternatives.length === 1 ? alternatives[0] : undefined
474
+ const canonicalKey = overrideKey({ ...target, sectionId })
475
+ const authoredResolutions = configured[canonicalKey]
476
+ const explicit = Object.hasOwn(configured, canonicalKey)
477
+ const choices = fallback && canCompose ? [...alternatives, fallback] : alternatives
478
+ selections.push(choices)
479
+ const choice = explicit
480
+ ? authoredResolutions && choices.find(({ override }) => override.contributionId === authoredResolutions.contributionId
481
+ && override.operation === authoredResolutions.operation)
482
+ : fallback
483
+ const selectedPrimitive = authoredResolutions
484
+ ? primitiveClaims.get(authoredResolutions.contributionId) : undefined
485
+ const selectsPrimitive = selectedPrimitive && overrideKey(selectedPrimitive.address) === canonicalKey
486
+ && selectedPrimitive.operation === authoredResolutions?.operation
487
+ if ((explicit && authoredResolutions && !choice && !selectsPrimitive) || (!explicit && !choice)) {
488
+ invalid(`conflicting form section "${canonicalKey}" from ${authors.map(({ module }) => module.moduleId).join(', ')} requires an exact modules.ts selector or null`)
489
+ }
490
+ if (fallback) fallbacks[canonicalKey] = fallback.override
491
+ if (choice) effective.push(choice)
492
+ }
493
+
494
+ for (const candidate of effective) for (const { customField, seed, authored } of candidate.fields) {
495
+ if (!customField || !seed) continue
496
+ const identity = canonicalSectionJson([customField.entityId, customField.key])
497
+ const previous = seeds.get(identity)
498
+ if (previous && (previous.moduleId !== authored.module.moduleId || canonicalSectionJson(previous.field) !== canonicalSectionJson(seed))) {
499
+ invalid(`conflicting custom field seed "${customField.entityId}/${customField.key}" from ${previous.moduleId} and ${authored.module.moduleId}`)
500
+ }
501
+ seeds.set(identity, { moduleId: authored.module.moduleId, entity: customField.entityId, field: seed })
502
+ }
503
+
504
+ const effectiveDefaultKeys = new Set<string>()
505
+ for (const candidate of effective) for (const value of candidate.defaults) {
506
+ if (effectiveDefaultKeys.has(value.payloadPath)) invalid(`conflicting default for "${value.payloadPath}" in ${key}`)
507
+ effectiveDefaultKeys.add(value.payloadPath)
508
+ }
509
+ for (const { extension } of changes) for (const { payloadPath: leaf, targets } of extension.defaults) {
510
+ if (!includesDefaultTarget(targets, target)) continue
511
+ if (!selections.flat().some(({ defaults }) => defaults.some(({ owner, payloadPath }) => owner.extension === extension && payloadPath === leaf))) {
512
+ invalid(`default "${leaf}" is not bound to an omitted leaf of ${key}`)
513
+ }
514
+ }
515
+ const numberOfSelections = selections.reduce((total, choices) => total * (choices.length + 1), published.length)
516
+ if (numberOfSelections > maximumAlternatives) invalid(`host ${key} exceeds the ${maximumAlternatives} finite alternative limit (${numberOfSelections})`)
517
+ const generated = alternativesByModule.get(hostModule.moduleId) ?? []
518
+ const emitted = new Set<string>()
519
+ function addAlternative(
520
+ chosen: readonly CompiledChange[], original: CrudFormSectionSurfaceAlternativeFact,
521
+ manual: ReadonlyMap<string, FormSectionOverride>, effectiveSelection = false,
522
+ ): boolean {
523
+ if (!chosen.length) return true
524
+ if (chosen.some(({ contribution }) => manual.has(contribution.address.sectionId))) return false
525
+ const overrides = new Map([...manual, ...chosen.map(({ contribution, override }) => [contribution.address.sectionId,
526
+ effectiveSelection && configured[overrideKey(contribution.address)] || override] as const)])
527
+ const orderedSectionIds = applyCrudFormSectionPlacements(baseline.orderedSectionIds, overrides)
528
+ const active = new Map(original.ownershipFacts.map((item) => [item.sectionId, item]))
529
+ for (const { ownership, contribution } of chosen) {
530
+ if (ownership) active.set(ownership.sectionId, ownership)
531
+ else active.delete(contribution.address.sectionId)
532
+ }
533
+ const ownershipFacts = [...active.values()]
534
+ const custom = ownershipFacts.flatMap(({ customFieldOwnership }, index) => customFieldOwnership.mode === 'ids'
535
+ ? customFieldOwnership.ids.map((id) => `customFields.${id}`)
536
+ : customFieldOwnership.mode === 'all' ? [`customFields\u0000${index}`] : [])
537
+ const rules = chosen.flatMap(({ defaults }) => defaults)
538
+ const genericTableTargets = chosen.flatMap(({ sinks }) => sinks.flatMap(({ fields }) =>
539
+ fields[0].field.store?.kind === 'table' ? [fields[0].field.store.entityId] : []))
540
+ if (new Set(genericTableTargets).size !== genericTableTargets.length) return false
541
+ if (!orderedSectionIds || chosen.some(({ contribution }) => contribution.requiredSectionIds
542
+ ?.some((sectionId) => !orderedSectionIds.includes(sectionId)))
543
+ || pathsOverlap([...ownershipFacts.flatMap(({ payloadPaths }) => payloadPaths), ...custom])
544
+ || (custom.some((name) => name.startsWith('customFields\u0000')) && custom.length > 1)
545
+ || new Set(rules.map(({ payloadPath }) => payloadPath)).size !== rules.length
546
+ || rules.some(({ readsPayloadPaths }) => readsPayloadPaths.some((path) =>
547
+ !ownershipFacts.some(({ payloadPaths }) => payloadPaths.includes(path))))) return false
548
+ const contributionIds = [...original.contributionIds, ...chosen.map(({ id }) => id)].sort(compareSectionIds)
549
+ const signature = canonicalSectionJson(contributionIds)
550
+ if (emitted.has(signature)) return true
551
+ emitted.add(signature)
552
+ const selectedProof = original.clientMutationSurfaces?.some(({ kind }) => kind === 'parent-submit') ? original : proof!
553
+ if (mutationIds.some((id) => !selectedProof.mutationSurfaceIds.includes(id))) return false
554
+ const retryRoute = hostModule.derivedRoutes?.find(({ hostDescriptorId, outboxRetry }) => hostDescriptorId === host.id && outboxRetry)
555
+ const outboxRetrySinkIds = retryRoute ? chosen.flatMap(({ sinks }) => sinks.flatMap(({ id, fields }) =>
556
+ fields[0].field.store?.kind === 'external' ? [id] : [])) : []
557
+ const retryFacts = outboxRetrySinkIds.map((sinkId) => projectCrudFormSectionClientMutationFact(
558
+ derivedCrudFormSectionRetryFact({ sinkId, route: retryRoute!.routePath, resourceKind: host.hostResourceKind! })))
559
+ const surface = {
560
+ ...original, id: `${baseline.id}.compiled-${digest(contributionIds).slice(0, 12)}`,
561
+ orderedSectionIds, contributionIds, ownershipFacts,
562
+ mutationSurfaceIds: [...selectedProof.mutationSurfaceIds, ...retryFacts.map(({ id }) => id)],
563
+ clientMutationSurfaces: retryFacts.length ? [...selectedProof.clientMutationSurfaces ?? [], ...retryFacts] : selectedProof.clientMutationSurfaces,
564
+ dependencies: [...original.dependencies, ...chosen.flatMap(({ contribution }) => {
565
+ const { id, requiredSectionIds = [], requiredDataContractIds = [] } = contribution
566
+ return requiredSectionIds.length || requiredDataContractIds.length
567
+ ? [{ consumerContributionId: id, requiredSectionIds, requiredDataContractIds }] : []
568
+ })],
569
+ }
570
+ generated.push({ hostDescriptorId: host.id, proofAlternativeId: selectedProof.id, surface, defaultProviders: rules.map(({ id, payloadPath }) => ({ id, payloadPath })),
571
+ ...(outboxRetrySinkIds.length ? { outboxRetrySinkIds } : {}) })
572
+ host.alternatives = [...host.alternatives, surface]
573
+ return true
574
+ }
575
+ function manualOverrides(original: CrudFormSectionSurfaceAlternativeFact): Map<string, FormSectionOverride> | null {
576
+ const result = new Map<string, FormSectionOverride>()
577
+ for (const id of original.contributionIds) {
578
+ const claim = primitiveClaims.get(id)
579
+ if (!claim || crudFormSectionHostKey(claim.address) !== key || result.has(claim.address.sectionId)) return null
580
+ const address = overrideKey(claim.address)
581
+ const configuredChoice = configured[address]
582
+ const contributedChoice = primitiveOverrides[address]
583
+ const selector = configuredChoice?.contributionId === id ? configuredChoice
584
+ : contributedChoice?.contributionId === id ? contributedChoice
585
+ : claim.operation === 'add' ? undefined : { operation: claim.operation, contributionId: id }
586
+ if (!selector || selector.operation !== claim.operation) return null
587
+ result.set(claim.address.sectionId, selector)
588
+ }
589
+ return canonicalSectionJson(applyCrudFormSectionPlacements(baseline.orderedSectionIds, result))
590
+ === canonicalSectionJson(original.orderedSectionIds) ? result : null
591
+ }
592
+ const rawEffective = { ...primitiveOverrides, ...fallbacks, ...configured }
593
+ const effectiveManual = Object.entries(rawEffective).flatMap(([address, override]) => {
594
+ const claim = override && primitiveClaims.get(override.contributionId)
595
+ return claim && crudFormSectionHostKey(claim.address) === key && overrideKey(claim.address) === address ? [claim.id] : []
596
+ }).sort(compareSectionIds)
597
+ const effectiveOriginal = published.find(({ contributionIds }) =>
598
+ canonicalSectionJson([...contributionIds].sort(compareSectionIds)) === canonicalSectionJson(effectiveManual))
599
+ const manual = effectiveOriginal && manualOverrides(effectiveOriginal)
600
+ if (effective.length && (!effectiveOriginal || !manual || !addAlternative(effective, effectiveOriginal, manual, true))) {
601
+ invalid(`effective alternatives for ${key} have conflicting fields, defaults, placement or unpublished handwritten contributions`)
602
+ }
603
+ for (const original of published) {
604
+ const manual = manualOverrides(original)
605
+ if (!manual) continue
606
+ function walk(index: number, chosen: CompiledChange[]) {
607
+ if (index === selections.length) {
608
+ addAlternative(chosen, original, manual!)
609
+ return
610
+ }
611
+ walk(index + 1, chosen)
612
+ for (const candidate of selections[index]) walk(index + 1, [...chosen, candidate])
613
+ }
614
+ walk(0, [])
615
+ }
616
+ alternativesByModule.set(hostModule.moduleId, generated)
617
+ }
618
+ const revisionWrites = [...ledgers].flatMap(([moduleId, ledger]) => {
619
+ const module = modules.find((entry) => entry.moduleId === moduleId)!
620
+ const content = JSON.stringify(Object.fromEntries([...ledger.revisions.keys()].sort(compareSectionIds).map((id) => [id, ledger.revisions.get(id)])), null, 2) + '\n'
621
+ return module.authoredSource && content !== ledger.original ? [{ filename: ledger.filename, content }] : []
622
+ })
623
+ const customFieldSetsByModule = new Map<string, CustomFieldSet[]>()
624
+ for (const { moduleId, entity, field } of seeds.values()) {
625
+ const sets = customFieldSetsByModule.get(moduleId) ?? []
626
+ const existing = sets.find((entry) => entry.entity === entity)
627
+ if (existing) existing.fields.push(field)
628
+ else sets.push({ entity, fields: [field], source: moduleId })
629
+ customFieldSetsByModule.set(moduleId, sets)
630
+ }
631
+ return { contributionsByModule, alternativesByModule, runtimeFiles, revisionWrites, fallbacks, customFieldSetsByModule }
632
+ }