@open-mercato/cli 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8687.1.adb16f62b3

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 (327) hide show
  1. package/.turbo/turbo-build.log +6 -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 +11067 -7122
  9. package/dist/agentic/guides/module-facts.v2.json +11055 -7094
  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/exact-override-targets.md +1 -1
  63. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  64. package/dist/agentic/guides/modules/communication_channels/workers.md +1 -1
  65. package/dist/agentic/guides/modules/configs/index.md +1 -1
  66. package/dist/agentic/guides/modules/content/index.md +1 -1
  67. package/dist/agentic/guides/modules/currencies/active-extension-bindings.md +11 -0
  68. package/dist/agentic/guides/modules/currencies/di-registrations-rich.md +1 -1
  69. package/dist/agentic/guides/modules/currencies/di-service-tokens.md +1 -1
  70. package/dist/agentic/guides/modules/currencies/exact-override-targets.md +1 -1
  71. package/dist/agentic/guides/modules/currencies/index.md +3 -2
  72. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  73. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
  74. package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
  75. package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
  76. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  77. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
  78. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  79. package/dist/agentic/guides/modules/customers/index.md +3 -3
  80. package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
  81. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
  82. package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
  83. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
  84. package/dist/agentic/guides/modules/dashboards/index.md +2 -3
  85. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  86. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  87. package/dist/agentic/guides/modules/devices/index.md +1 -1
  88. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  89. package/dist/agentic/guides/modules/directory/index.md +1 -1
  90. package/dist/agentic/guides/modules/documents/index.md +1 -1
  91. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  92. package/dist/agentic/guides/modules/entities/index.md +1 -1
  93. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  94. package/dist/agentic/guides/modules/events/index.md +1 -1
  95. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  96. package/dist/agentic/guides/modules/forms/index.md +1 -1
  97. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  98. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  99. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  100. package/dist/agentic/guides/modules/generators/index.md +1 -1
  101. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  102. package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
  103. package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
  104. package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
  105. package/dist/agentic/guides/modules/integrations/index.md +2 -2
  106. package/dist/agentic/guides/modules/integrations/setup.md +1 -1
  107. package/dist/agentic/guides/modules/integrations/workers.md +3 -1
  108. package/dist/agentic/guides/modules/ledger/acl-features.md +16 -0
  109. package/dist/agentic/guides/modules/ledger/active-extension-bindings.md +11 -0
  110. package/dist/agentic/guides/modules/ledger/backend-pages.md +21 -0
  111. package/dist/agentic/guides/modules/ledger/domain-commands.md +22 -0
  112. package/dist/agentic/guides/modules/ledger/encryption.md +11 -0
  113. package/dist/agentic/guides/modules/ledger/entities.md +17 -0
  114. package/dist/agentic/guides/modules/ledger/events.md +19 -0
  115. package/dist/agentic/guides/modules/ledger/exact-override-targets.md +30 -0
  116. package/dist/agentic/guides/modules/ledger/index.md +22 -0
  117. package/dist/agentic/guides/modules/ledger/owned-contract-module-metadata.md +11 -0
  118. package/dist/agentic/guides/modules/ledger/setup.md +11 -0
  119. package/dist/agentic/guides/modules/ledger/umes-hosts.md +26 -0
  120. package/dist/agentic/guides/modules/messages/index.md +1 -1
  121. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  122. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  123. package/dist/agentic/guides/modules/payment_gateways/active-extension-bindings.md +1 -1
  124. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  125. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  126. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  127. package/dist/agentic/guides/modules/planner/index.md +1 -1
  128. package/dist/agentic/guides/modules/portal/index.md +1 -1
  129. package/dist/agentic/guides/modules/progress/index.md +1 -1
  130. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  131. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  132. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  133. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  134. package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
  135. package/dist/agentic/guides/modules/resources/index.md +1 -1
  136. package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
  137. package/dist/agentic/guides/modules/resources/setup.md +1 -1
  138. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
  139. package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
  140. package/dist/agentic/guides/modules/sales/index.md +3 -3
  141. package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
  142. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  143. package/dist/agentic/guides/modules/search/index.md +1 -1
  144. package/dist/agentic/guides/modules/security/index.md +1 -1
  145. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  146. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  147. package/dist/agentic/guides/modules/sso/index.md +1 -1
  148. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
  149. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
  150. package/dist/agentic/guides/modules/staff/index.md +1 -1
  151. package/dist/agentic/guides/modules/staff/workers.md +1 -1
  152. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  153. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  154. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  155. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  156. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  157. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  158. package/dist/agentic/guides/modules/translations/index.md +1 -1
  159. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  160. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  161. package/dist/agentic/guides/modules/wms/index.md +1 -1
  162. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  163. package/dist/agentic/guides/reference-module-facts.json +811 -21
  164. package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
  165. package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
  166. package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
  167. package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
  168. package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
  169. package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
  170. package/dist/agentic/guides/reference-modules/example/events.md +2 -1
  171. package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
  172. package/dist/agentic/guides/reference-modules/example/index.md +7 -7
  173. package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
  174. package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
  175. package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
  176. package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
  177. package/dist/agentic/guides/upstream/AGENTS.md +5 -4
  178. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
  179. package/dist/agentic/guides/upstream/manifest.json +3 -3
  180. package/dist/agentic/shared/AGENTS.md.template +12 -16
  181. package/dist/agentic/shared/ai/harness/README.md +4 -2
  182. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  183. package/dist/agentic/shared/ai/harness/cases.json +1420 -41
  184. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  185. package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
  186. package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
  187. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  188. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
  189. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
  190. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
  191. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
  192. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
  193. package/dist/lib/cache-provider-manifest.js +9 -0
  194. package/dist/lib/cache-provider-manifest.js.map +7 -0
  195. package/dist/lib/generate-watch-plan.js +4 -0
  196. package/dist/lib/generate-watch-plan.js.map +2 -2
  197. package/dist/lib/generate-watch-runner.js +1 -0
  198. package/dist/lib/generate-watch-runner.js.map +2 -2
  199. package/dist/lib/generate-watch-structure.js +2 -0
  200. package/dist/lib/generate-watch-structure.js.map +2 -2
  201. package/dist/lib/generators/ast/writers.js +5 -1
  202. package/dist/lib/generators/ast/writers.js.map +2 -2
  203. package/dist/lib/generators/cache-providers.js +80 -0
  204. package/dist/lib/generators/cache-providers.js.map +7 -0
  205. package/dist/lib/generators/form-section-ast.js +156 -0
  206. package/dist/lib/generators/form-section-ast.js.map +7 -0
  207. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  208. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  209. package/dist/lib/generators/form-section-extension-source.js +245 -0
  210. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  211. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  212. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  213. package/dist/lib/generators/form-sections.js +773 -0
  214. package/dist/lib/generators/form-sections.js.map +7 -0
  215. package/dist/lib/generators/index.js +2 -0
  216. package/dist/lib/generators/index.js.map +2 -2
  217. package/dist/lib/generators/module-entities.js +21 -2
  218. package/dist/lib/generators/module-entities.js.map +2 -2
  219. package/dist/lib/generators/module-extension-facts.js +2 -1
  220. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  221. package/dist/lib/generators/module-facts.js +30 -1
  222. package/dist/lib/generators/module-facts.js.map +2 -2
  223. package/dist/lib/generators/module-override-targets.js +24 -2
  224. package/dist/lib/generators/module-override-targets.js.map +2 -2
  225. package/dist/lib/generators/module-registry.js +75 -3
  226. package/dist/lib/generators/module-registry.js.map +2 -2
  227. package/dist/lib/generators/openapi.js +27 -17
  228. package/dist/lib/generators/openapi.js.map +2 -2
  229. package/dist/lib/post-generate-invalidation.js +20 -1
  230. package/dist/lib/post-generate-invalidation.js.map +2 -2
  231. package/dist/lib/resolver.js +195 -1
  232. package/dist/lib/resolver.js.map +3 -3
  233. package/dist/lib/scaffold/field-dsl.js +393 -0
  234. package/dist/lib/scaffold/field-dsl.js.map +7 -0
  235. package/dist/lib/scaffold/index.js +412 -0
  236. package/dist/lib/scaffold/index.js.map +7 -0
  237. package/dist/lib/scaffold/targets.js +42 -0
  238. package/dist/lib/scaffold/targets.js.map +7 -0
  239. package/dist/lib/scaffold/templates/create-page.js +52 -0
  240. package/dist/lib/scaffold/templates/create-page.js.map +7 -0
  241. package/dist/lib/scaffold/templates/detail-page.js +186 -0
  242. package/dist/lib/scaffold/templates/detail-page.js.map +7 -0
  243. package/dist/lib/scaffold/templates/form-config.js +42 -0
  244. package/dist/lib/scaffold/templates/form-config.js.map +7 -0
  245. package/dist/lib/scaffold/templates/index.js +27 -0
  246. package/dist/lib/scaffold/templates/index.js.map +7 -0
  247. package/dist/lib/scaffold/templates/list-page.js +190 -0
  248. package/dist/lib/scaffold/templates/list-page.js.map +7 -0
  249. package/dist/lib/scaffold/templates/metas.js +47 -0
  250. package/dist/lib/scaffold/templates/metas.js.map +7 -0
  251. package/dist/lib/scaffold/templates/module-files.js +85 -0
  252. package/dist/lib/scaffold/templates/module-files.js.map +7 -0
  253. package/dist/lib/single-instance-strategy-guard.js +26 -3
  254. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  255. package/dist/lib/testing/integration-discovery.js +32 -3
  256. package/dist/lib/testing/integration-discovery.js.map +2 -2
  257. package/dist/lib/testing/integration.js +232 -8
  258. package/dist/lib/testing/integration.js.map +2 -2
  259. package/dist/mercato.js +40 -7
  260. package/dist/mercato.js.map +2 -2
  261. package/jest.config.cjs +2 -0
  262. package/package.json +7 -7
  263. package/src/__tests__/mercato.test.ts +18 -0
  264. package/src/__tests__/rotation-json-output.test.ts +52 -0
  265. package/src/lib/__tests__/agentic-workflows-ownership.test.ts +79 -0
  266. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  267. package/src/lib/__tests__/generate-watch-plan.test.ts +3 -2
  268. package/src/lib/__tests__/generate-watch-runner.test.ts +13 -1
  269. package/src/lib/__tests__/generate-watch-structure.test.ts +34 -0
  270. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  271. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  272. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  273. package/src/lib/cache-provider-manifest.ts +8 -0
  274. package/src/lib/generate-watch-plan.ts +6 -3
  275. package/src/lib/generate-watch-runner.ts +1 -0
  276. package/src/lib/generate-watch-structure.ts +5 -1
  277. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  278. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  279. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  280. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  281. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  282. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  283. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  284. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  285. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  286. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  287. package/src/lib/generators/__tests__/openapi.test.ts +60 -13
  288. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  289. package/src/lib/generators/ast/writers.ts +6 -1
  290. package/src/lib/generators/cache-providers.ts +111 -0
  291. package/src/lib/generators/form-section-ast.ts +166 -0
  292. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  293. package/src/lib/generators/form-section-extension-source.ts +308 -0
  294. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  295. package/src/lib/generators/form-sections.ts +896 -0
  296. package/src/lib/generators/index.ts +1 -0
  297. package/src/lib/generators/module-entities.ts +22 -4
  298. package/src/lib/generators/module-extension-facts.ts +1 -0
  299. package/src/lib/generators/module-facts.ts +40 -0
  300. package/src/lib/generators/module-override-targets.ts +19 -0
  301. package/src/lib/generators/module-registry.ts +80 -4
  302. package/src/lib/generators/openapi.ts +31 -20
  303. package/src/lib/post-generate-invalidation.ts +28 -1
  304. package/src/lib/resolver.ts +218 -0
  305. package/src/lib/scaffold/__tests__/__snapshots__/scaffold-golden.test.ts.snap +1742 -0
  306. package/src/lib/scaffold/__tests__/helpers.ts +75 -0
  307. package/src/lib/scaffold/__tests__/scaffold-ds-contract.test.ts +248 -0
  308. package/src/lib/scaffold/__tests__/scaffold-golden.test.ts +267 -0
  309. package/src/lib/scaffold/__tests__/scaffold-runtime.test.tsx +193 -0
  310. package/src/lib/scaffold/field-dsl.ts +491 -0
  311. package/src/lib/scaffold/index.ts +531 -0
  312. package/src/lib/scaffold/targets.ts +68 -0
  313. package/src/lib/scaffold/templates/create-page.ts +52 -0
  314. package/src/lib/scaffold/templates/detail-page.ts +190 -0
  315. package/src/lib/scaffold/templates/form-config.ts +42 -0
  316. package/src/lib/scaffold/templates/index.ts +27 -0
  317. package/src/lib/scaffold/templates/list-page.ts +190 -0
  318. package/src/lib/scaffold/templates/metas.ts +48 -0
  319. package/src/lib/scaffold/templates/module-files.ts +87 -0
  320. package/src/lib/single-instance-strategy-guard.ts +51 -1
  321. package/src/lib/testing/__tests__/integration-app-only-playwright.test.ts +225 -0
  322. package/src/lib/testing/__tests__/integration-app-only.test.ts +320 -0
  323. package/src/lib/testing/__tests__/integration-discovery.test.ts +45 -1
  324. package/src/lib/testing/integration-discovery.ts +32 -2
  325. package/src/lib/testing/integration.ts +293 -11
  326. package/src/mercato.ts +39 -5
  327. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -1,8 +1,9 @@
1
1
  import * as fs from "node:fs";
2
- import { randomBytes } from "node:crypto";
3
2
  import * as path from "node:path";
4
3
  import { getEnabledModuleIdentities } from "../module-identity.js";
5
4
  import { isModuleRouteFile } from "./scanner.js";
5
+ import { resolveNamedObjectExport } from "./module-registry.js";
6
+ import { generatedDerivedCrudRouteIndex, readDerivedCrudFormSectionRouteIndex } from "./form-sections.js";
6
7
  import {
7
8
  calculateChecksum,
8
9
  calculateStructureChecksum,
@@ -11,7 +12,7 @@ import {
11
12
  logGenerationResult,
12
13
  createGeneratorResult
13
14
  } from "../utils.js";
14
- const OPENAPI_INPUT_MANIFEST_VERSION = 1;
15
+ const OPENAPI_INPUT_MANIFEST_VERSION = 2;
15
16
  function createOpenApiInputContext(resolver) {
16
17
  const enabled = resolver.loadEnabledModules();
17
18
  const apiRoots = [];
@@ -78,6 +79,7 @@ function calculateOpenApiInputFingerprint(resolver, context, manifest) {
78
79
  const appDir = resolver.getAppDir();
79
80
  const configPaths = [
80
81
  resolver.getModulesConfigPath(),
82
+ path.join(resolver.getOutputDir(), generatedDerivedCrudRouteIndex),
81
83
  path.join(rootDir, "package.json"),
82
84
  path.join(rootDir, "yarn.lock"),
83
85
  path.join(rootDir, "package-lock.json"),
@@ -136,14 +138,25 @@ async function findApiRoutes(resolver, enabled) {
136
138
  }
137
139
  for (const [relativePath, fullPath] of filesByRelativePath) {
138
140
  const routeSegs = relativePath ? relativePath.split("/") : [];
139
- const apiPath = `/api/${modId}${routeSegs.length ? "/" + routeSegs.join("/") : ""}`.replace(/\[([^\]]+)\]/g, "{$1}");
141
+ const metadataPath = resolveNamedObjectExport(fullPath, "metadata")?.path;
142
+ const routePath = typeof metadataPath === "string" && metadataPath ? metadataPath : `/${modId}${routeSegs.length ? "/" + routeSegs.join("/") : ""}`;
143
+ const apiPath = `/api/${routePath.replace(/^\/+/, "")}`.replace(/\[([^\]]+)\]/g, "{$1}");
140
144
  routes.push({
141
145
  path: fullPath,
146
+ moduleId: modId,
142
147
  methods: await detectMethods(fullPath),
143
148
  openApiPath: apiPath
144
149
  });
145
150
  }
146
151
  }
152
+ const enabledIds = new Set(enabled.map(({ id }) => id));
153
+ const derived = readDerivedCrudFormSectionRouteIndex(resolver.getOutputDir());
154
+ routes.push(...derived.filter(({ moduleId }) => enabledIds.has(moduleId)).map(({ moduleId, routePath, methods, fileName }) => ({
155
+ moduleId,
156
+ methods,
157
+ path: path.join(resolver.getOutputDir(), fileName),
158
+ openApiPath: `/api${routePath}`.replace(/\[([^\]]+)\]/g, "{$1}")
159
+ })));
147
160
  return routes;
148
161
  }
149
162
  async function detectMethods(filePath) {
@@ -228,9 +241,6 @@ async function generateOpenApiViaBundle(routes, resolver, quiet) {
228
241
  }
229
242
  return { doc: null, inputPaths: [] };
230
243
  }
231
- const cacheDir = path.join(rootDir, "node_modules", ".cache");
232
- if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });
233
- const bundlePath = path.join(cacheDir, `_openapi-bundle-${process.pid}-${randomBytes(6).toString("hex")}.mjs`);
234
244
  let inputPaths = [];
235
245
  const importLines = [
236
246
  `import { buildOpenApiDocument } from ${JSON.stringify(generatorPath)};`
@@ -240,7 +250,7 @@ async function generateOpenApiViaBundle(routes, resolver, quiet) {
240
250
  const route = routes[i];
241
251
  importLines.push(`import * as R${i} from ${JSON.stringify(route.path)};`);
242
252
  const bracketPath = route.openApiPath.replace(/\{([^}]+)\}/g, "[$1]");
243
- routeMapLines.push(` [${JSON.stringify(bracketPath)}, R${i}],`);
253
+ routeMapLines.push(` [${JSON.stringify(bracketPath)}, ${JSON.stringify(route.moduleId)}, R${i}],`);
244
254
  }
245
255
  const entryScript = `${importLines.join("\n")}
246
256
 
@@ -249,8 +259,7 @@ ${routeMapLines.join("\n")}
249
259
  ];
250
260
 
251
261
  const modules = new Map();
252
- for (const [apiPath, mod] of routeEntries) {
253
- const moduleId = apiPath.replace(/^\\/api\\//, '').split('/')[0];
262
+ for (const [apiPath, moduleId, mod] of routeEntries) {
254
263
  if (!modules.has(moduleId)) modules.set(moduleId, { id: moduleId, apis: [] });
255
264
  modules.get(moduleId).apis.push({
256
265
  path: apiPath,
@@ -422,6 +431,8 @@ process.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>
422
431
  }));
423
432
  }
424
433
  };
434
+ const bundleDir = fs.mkdtempSync(path.join(resolver.getOutputDir(), ".openapi-"));
435
+ const bundlePath = path.join(bundleDir, "bundle.mjs");
425
436
  try {
426
437
  const buildResult = await esbuild.build({
427
438
  stdin: {
@@ -487,22 +498,18 @@ process.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>
487
498
  }
488
499
  }
489
500
  }
490
- return { doc: null, inputPaths };
501
+ const qualifierFailure = /Cannot derive CrudForm section host: [^\r\n]+/.exec(`${errMsg}
502
+ ${String(stderr ?? "")}`)?.[0];
503
+ return { doc: null, inputPaths, qualifierFailure };
491
504
  } finally {
492
505
  try {
493
506
  await esbuild.stop();
494
507
  } catch {
495
508
  }
496
509
  try {
497
- fs.unlinkSync(bundlePath);
510
+ fs.rmSync(bundleDir, { recursive: true, force: true });
498
511
  } catch {
499
512
  }
500
- for (const file of ["_openapi-bundle.mjs", "_openapi-register.mjs", "_openapi-loader.mjs", "_next-stub.cjs"]) {
501
- try {
502
- fs.unlinkSync(path.join(cacheDir, file));
503
- } catch {
504
- }
505
- }
506
513
  }
507
514
  }
508
515
  function buildOpenApiPaths(routes) {
@@ -560,6 +567,9 @@ async function generateOpenApi(options) {
560
567
  }
561
568
  const bundleResult = await generateOpenApiViaBundle(routes, resolver, quiet);
562
569
  let doc = bundleResult.doc;
570
+ if (!doc && readDerivedCrudFormSectionRouteIndex(outputDir).length) {
571
+ throw new Error(bundleResult.qualifierFailure ?? "[generate] Could not validate generated CrudForm section-policy OpenAPI schemas");
572
+ }
563
573
  if (!doc) {
564
574
  if (!quiet) {
565
575
  console.warn(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/generators/openapi.ts"],
4
- "sourcesContent": ["/**\n * OpenAPI JSON Generator\n *\n * Generates a static openapi.generated.json file at build time.\n * This allows CLI tools (like MCP dev server) to access API endpoint\n * information without requiring a running Next.js app.\n */\n\nimport * as fs from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport * as path from 'node:path'\nimport type { ModuleEntry, PackageResolver } from '../resolver'\nimport { getEnabledModuleIdentities } from '../module-identity'\nimport { isModuleRouteFile } from './scanner'\nimport {\n calculateChecksum,\n calculateStructureChecksum,\n readChecksumRecord,\n writeChecksumRecord,\n logGenerationResult,\n type GeneratorResult,\n createGeneratorResult,\n} from '../utils'\n\nexport interface GenerateOpenApiOptions {\n resolver: PackageResolver\n quiet?: boolean\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\ninterface ApiRouteInfo {\n path: string\n methods: HttpMethod[]\n openApiPath: string\n}\n\ninterface OpenApiInputManifest {\n version: 1\n inputPaths: string[]\n}\n\ninterface OpenApiInputContext {\n enabled: ModuleEntry[]\n apiRoots: string[]\n moduleIdentity: Array<{\n id: string\n from: string\n appBase: string\n pkgBase: string\n }>\n}\n\ninterface OpenApiBundleResult {\n doc: Record<string, any> | null\n inputPaths: string[]\n}\n\nconst OPENAPI_INPUT_MANIFEST_VERSION = 1\n\nfunction createOpenApiInputContext(resolver: PackageResolver): OpenApiInputContext {\n const enabled = resolver.loadEnabledModules()\n const apiRoots: string[] = []\n const moduleIdentity = enabled.map((entry) => {\n const roots = resolver.getModulePaths(entry)\n apiRoots.push(path.join(roots.appBase, 'api'), path.join(roots.pkgBase, 'api'))\n return {\n id: entry.id,\n from: entry.from ?? '@open-mercato/core',\n appBase: path.resolve(roots.appBase),\n pkgBase: path.resolve(roots.pkgBase),\n }\n })\n return { enabled, apiRoots, moduleIdentity }\n}\n\nfunction readOpenApiInputManifest(filePath: string): OpenApiInputManifest | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<OpenApiInputManifest>\n if (\n parsed.version !== OPENAPI_INPUT_MANIFEST_VERSION\n || !Array.isArray(parsed.inputPaths)\n || parsed.inputPaths.some((entry) => typeof entry !== 'string')\n ) {\n return null\n }\n return {\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n inputPaths: Array.from(new Set(parsed.inputPaths.map((entry) => path.resolve(entry))))\n .sort((a, b) => a.localeCompare(b)),\n }\n } catch {\n return null\n }\n}\n\n/** All successful bundle inputs, including generated producers; null means unknown. */\nexport function getOpenApiGeneratorDependencies(resolver: PackageResolver): readonly string[] | null {\n return readOpenApiInputManifest(\n path.join(resolver.getOutputDir(), 'openapi.generated.inputs.json'),\n )?.inputPaths ?? null\n}\n\n/**\n * Returns source inputs from the last successful bundle, including paths since\n * deleted. An empty result does not prove that no dependencies exist: missing or\n * invalid manifests require the watcher's conservative unknown-change fallback.\n */\nexport function getOpenApiWatchInputs(resolver: PackageResolver): string[] {\n const inputPaths = getOpenApiGeneratorDependencies(resolver)\n if (!inputPaths) return []\n\n const packageNames = new Set([\n '@open-mercato/core',\n ...resolver.loadEnabledModules().map((entry) => entry.from ?? '@open-mercato/core'),\n ])\n const generatedRoots = Array.from(new Set([\n path.resolve(resolver.getOutputDir()),\n ...Array.from(packageNames, (name) => path.resolve(resolver.getPackageOutputDir(name))),\n ]))\n return inputPaths.filter((inputPath) => !generatedRoots.some((root) => {\n const relative = path.relative(root, inputPath)\n return relative === '' || (\n relative !== '..'\n && !relative.startsWith(`..${path.sep}`)\n && !path.isAbsolute(relative)\n )\n }))\n}\n\nfunction trackedPathRecord(filePath: string): string {\n try {\n const stat = fs.statSync(filePath)\n if (stat.isFile()) {\n return `${path.resolve(filePath)}:${calculateChecksum(fs.readFileSync(filePath, 'utf8'))}`\n }\n return `${path.resolve(filePath)}:${stat.size}:${stat.mtimeMs}`\n } catch {\n return `missing:${path.resolve(filePath)}`\n }\n}\n\nfunction calculateOpenApiInputFingerprint(\n resolver: PackageResolver,\n context: OpenApiInputContext,\n manifest: OpenApiInputManifest,\n): string {\n const rootDir = resolver.getRootDir()\n const appDir = resolver.getAppDir()\n const configPaths = [\n resolver.getModulesConfigPath(),\n path.join(rootDir, 'package.json'),\n path.join(rootDir, 'yarn.lock'),\n path.join(rootDir, 'package-lock.json'),\n path.join(rootDir, 'pnpm-lock.yaml'),\n path.join(rootDir, 'tsconfig.json'),\n path.join(rootDir, 'tsconfig.base.json'),\n path.join(appDir, 'package.json'),\n path.join(appDir, 'tsconfig.json'),\n ]\n const trackedRecords = [...manifest.inputPaths, ...configPaths]\n .map(trackedPathRecord)\n .sort((a, b) => a.localeCompare(b))\n return calculateChecksum(JSON.stringify({\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n modules: context.moduleIdentity,\n routeStructure: calculateStructureChecksum(context.apiRoots),\n trackedRecords,\n environment: {\n node: process.version,\n nodeEnv: process.env.NODE_ENV ?? '',\n publicAppUrl: process.env.NEXT_PUBLIC_APP_URL ?? '',\n },\n }))\n}\n\nfunction resolveExistingPath(paths: string[]): string | null {\n for (const candidate of paths) {\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\n/**\n * Find all API route files and extract their OpenAPI specs.\n */\nasync function findApiRoutes(\n resolver: PackageResolver,\n enabled: ModuleEntry[],\n): Promise<ApiRouteInfo[]> {\n const routes: ApiRouteInfo[] = []\n\n for (const entry of enabled) {\n const modId = entry.id\n const roots = resolver.getModulePaths(entry)\n\n const apiApp = path.join(roots.appBase, 'api')\n const apiPkg = path.join(roots.pkgBase, 'api')\n\n // Scan route files\n const routeFiles: Array<{ relativePath: string; fullPath: string }> = []\n\n const walkDir = (dir: string, rel: string[] = []) => {\n if (!fs.existsSync(dir)) return\n for (const e of fs.readdirSync(dir, { withFileTypes: true })) {\n if (e.isDirectory()) {\n if (e.name === '__tests__' || e.name === '__mocks__') continue\n walkDir(path.join(dir, e.name), [...rel, e.name])\n } else if (e.isFile() && isModuleRouteFile(e.name)) {\n routeFiles.push({\n relativePath: [...rel].join('/'),\n fullPath: path.join(dir, e.name),\n })\n }\n }\n }\n\n // Scan package first, then app (app overrides)\n if (fs.existsSync(apiPkg)) walkDir(apiPkg)\n if (fs.existsSync(apiApp)) walkDir(apiApp)\n\n // Process unique routes (later app files overwrite earlier package files)\n const filesByRelativePath = new Map<string, string>()\n for (const { relativePath, fullPath } of routeFiles) {\n filesByRelativePath.set(relativePath, fullPath)\n }\n\n for (const [relativePath, fullPath] of filesByRelativePath) {\n\n // Build API path\n const routeSegs = relativePath ? relativePath.split('/') : []\n const apiPath = `/api/${modId}${routeSegs.length ? '/' + routeSegs.join('/') : ''}`\n // Convert [param] to {param} for OpenAPI format\n .replace(/\\[([^\\]]+)\\]/g, '{$1}')\n\n routes.push({\n path: fullPath,\n methods: await detectMethods(fullPath),\n openApiPath: apiPath,\n })\n }\n }\n\n return routes\n}\n\n/**\n * Detect which HTTP methods are exported from a route file.\n */\nasync function detectMethods(filePath: string): Promise<HttpMethod[]> {\n const methods: HttpMethod[] = []\n const content = fs.readFileSync(filePath, 'utf-8')\n\n const methodPatterns: HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n for (const method of methodPatterns) {\n // Check for export { GET }, export const GET, export async function GET\n const patterns = [\n new RegExp(`export\\\\s+(const|async\\\\s+function|function)\\\\s+${method}\\\\b`),\n new RegExp(`export\\\\s*\\\\{[^}]*\\\\b${method}\\\\b[^}]*\\\\}`),\n ]\n if (patterns.some((p) => p.test(content))) {\n methods.push(method)\n }\n }\n\n return methods\n}\n\n/**\n * Parse openApi export from route file source code statically.\n * This extracts basic operation info without needing to compile the file.\n */\nfunction parseOpenApiFromSource(filePath: string): Record<string, any> | null {\n try {\n const content = fs.readFileSync(filePath, 'utf-8')\n\n // Check if file exports openApi\n if (!content.includes('export const openApi') && !content.includes('export { openApi')) {\n return null\n }\n\n // Extract operationId, summary, description from the source\n const result: Record<string, any> = {}\n const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n\n for (const method of methods) {\n // Look for method specs in the openApi object\n // Pattern: GET: { operationId: '...', summary: '...', ... }\n const methodPattern = new RegExp(\n `${method}\\\\s*:\\\\s*\\\\{([^}]+(?:\\\\{[^}]*\\\\}[^}]*)*)\\\\}`,\n 's'\n )\n const methodMatch = content.match(methodPattern)\n\n if (methodMatch) {\n const methodContent = methodMatch[1]\n const spec: Record<string, any> = {}\n\n // Extract operationId\n const opIdMatch = methodContent.match(/operationId\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (opIdMatch) spec.operationId = opIdMatch[1]\n\n // Extract summary\n const summaryMatch = methodContent.match(/summary\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (summaryMatch) spec.summary = summaryMatch[1]\n\n // Extract description\n const descMatch = methodContent.match(/description\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (descMatch) spec.description = descMatch[1]\n\n // Extract tags\n const tagsMatch = methodContent.match(/tags\\s*:\\s*\\[([^\\]]*)\\]/)\n if (tagsMatch) {\n const tagsContent = tagsMatch[1]\n const tags = tagsContent.match(/['\"]([^'\"]+)['\"]/g)\n if (tags) {\n spec.tags = tags.map(t => t.replace(/['\"]/g, ''))\n }\n }\n\n if (Object.keys(spec).length > 0) {\n result[method] = spec\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : null\n } catch {\n return null\n }\n}\n\n/**\n * Generate a complete OpenAPI document by bundling route files with esbuild\n * and executing the bundle to call buildOpenApiDocument from @open-mercato/shared.\n *\n * esbuild compiles TypeScript with legacy decorator support (reads experimentalDecorators\n * from tsconfig.json), avoiding the TC39 decorator mismatch that breaks tsx-based imports.\n * External packages (zod, mikro-orm, etc.) are resolved from node_modules at runtime.\n */\nasync function generateOpenApiViaBundle(\n routes: ApiRouteInfo[],\n resolver: PackageResolver,\n quiet: boolean\n): Promise<OpenApiBundleResult> {\n let esbuild: typeof import('esbuild')\n try {\n esbuild = await import('esbuild')\n } catch {\n if (!quiet) console.log('[OpenAPI] esbuild not available, skipping bundle approach')\n return { doc: null, inputPaths: [] }\n }\n\n const { execFileSync } = await import('node:child_process')\n\n const rootDir = resolver.getRootDir()\n const appDir = resolver.getAppDir()\n const sharedPackageRoot = resolver.getPackageRoot('@open-mercato/shared')\n const corePackageRoot = resolver.getPackageRoot('@open-mercato/core')\n const tsconfigPath = resolveExistingPath([\n path.join(appDir, 'tsconfig.json'),\n path.join(rootDir, 'tsconfig.base.json'),\n path.join(rootDir, 'tsconfig.json'),\n ])\n const generatorPath = path.join(sharedPackageRoot, 'src', 'lib', 'openapi', 'generator.ts')\n const coreGeneratedRoot = path.join(corePackageRoot, 'generated')\n\n if (!fs.existsSync(generatorPath)) {\n if (!quiet) {\n console.log(`[OpenAPI] Generator source not found at ${generatorPath}, skipping bundle approach`)\n }\n return { doc: null, inputPaths: [] }\n }\n\n const cacheDir = path.join(rootDir, 'node_modules', '.cache')\n if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true })\n\n // Per-run file: `yarn dev`'s watcher and a CLI `generate` (e.g. after\n // create-mercato-module init) can bundle concurrently, and a shared path let\n // one process execute the other's half-written bundle (\"Unexpected end of input\").\n const bundlePath = path.join(cacheDir, `_openapi-bundle-${process.pid}-${randomBytes(6).toString('hex')}.mjs`)\n let inputPaths: string[] = []\n\n // Build the entry script that imports all routes and calls buildOpenApiDocument\n const importLines: string[] = [\n `import { buildOpenApiDocument } from ${JSON.stringify(generatorPath)};`,\n ]\n const routeMapLines: string[] = []\n\n for (let i = 0; i < routes.length; i++) {\n const route = routes[i]\n importLines.push(`import * as R${i} from ${JSON.stringify(route.path)};`)\n // Use [param] format so normalizePath in buildOpenApiDocument extracts path params\n const bracketPath = route.openApiPath.replace(/\\{([^}]+)\\}/g, '[$1]')\n routeMapLines.push(` [${JSON.stringify(bracketPath)}, R${i}],`)\n }\n\n const entryScript = `${importLines.join('\\n')}\n\nconst routeEntries = [\n${routeMapLines.join('\\n')}\n];\n\nconst modules = new Map();\nfor (const [apiPath, mod] of routeEntries) {\n const moduleId = apiPath.replace(/^\\\\/api\\\\//, '').split('/')[0];\n if (!modules.has(moduleId)) modules.set(moduleId, { id: moduleId, apis: [] });\n modules.get(moduleId).apis.push({\n path: apiPath,\n handlers: mod,\n metadata: mod.metadata,\n });\n}\n\nconst doc = buildOpenApiDocument([...modules.values()], {\n title: 'Open Mercato API',\n version: '1.0.0',\n description: 'Auto-generated OpenAPI specification',\n servers: [{ url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' }],\n});\n\n// Deep-clone to break shared object references before serializing.\n// The zodToJsonSchema memo cache returns the same object instance for\n// fields like currencyCode that appear on both parent and child schemas.\n// A naive WeakSet-based circular-ref guard would drop the second occurrence,\n// causing properties to vanish from the generated spec (while the field\n// still appears in the 'required' array, since those are plain strings).\nconst deepClone = (v, ancestors = []) => {\n if (v === null || typeof v !== 'object') return v;\n if (typeof v === 'bigint') return Number(v);\n if (typeof v === 'function') return undefined;\n if (ancestors.includes(v)) return undefined; // true circular ref\n const next = [...ancestors, v];\n if (Array.isArray(v)) return v.map((item) => deepClone(item, next));\n const out = {};\n for (const [k, val] of Object.entries(v)) {\n const cloned = deepClone(val, next);\n if (cloned !== undefined) out[k] = cloned;\n }\n return out;\n};\nprocess.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>\n typeof v === 'bigint' ? Number(v) : v\n));\n`\n\n // Plugin: stub next/* imports (not available outside Next.js app context)\n const stubNextPlugin = {\n name: 'stub-next',\n setup(build: any) {\n build.onResolve({ filter: /^next($|\\/)/ }, () => ({\n path: 'next-stub',\n namespace: 'next-stub',\n }))\n build.onLoad({ filter: /.*/, namespace: 'next-stub' }, () => ({\n contents: [\n 'const p = new Proxy(function(){}, {',\n ' get(_, k) { return k === \"__esModule\" ? true : k === \"default\" ? p : p; },',\n ' apply() { return p; },',\n ' construct() { return p; },',\n '});',\n 'export default p;',\n 'export const NextRequest = p, NextResponse = p, headers = p, cookies = p;',\n 'export const redirect = p, notFound = p, useRouter = p, usePathname = p;',\n 'export const useSearchParams = p, permanentRedirect = p, revalidatePath = p;',\n ].join('\\n'),\n loader: 'js' as const,\n }))\n },\n }\n\n // Plugin: resolve workspace imports, aliases, and subpath imports\n const resolveProjectImportsPlugin = {\n name: 'resolve-project-imports',\n setup(build: any) {\n // @open-mercato/<pkg>/<path> \u2192 packageRoot/src/<path>.ts\n build.onResolve({ filter: /^@open-mercato\\// }, (args: any) => {\n const withoutScope = args.path.slice('@open-mercato/'.length)\n const slashIdx = withoutScope.indexOf('/')\n const pkg = slashIdx === -1 ? withoutScope : withoutScope.slice(0, slashIdx)\n const rest = slashIdx === -1 ? '' : withoutScope.slice(slashIdx + 1)\n const packageName = `@open-mercato/${pkg}`\n const packageRoot = resolver.getPackageRoot(packageName)\n\n const base = rest\n ? path.join(packageRoot, 'src', rest)\n : path.join(packageRoot, 'src', 'index')\n\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // @/.mercato/* \u2192 app/.mercato/* (tsconfig paths)\n build.onResolve({ filter: /^@\\/\\.mercato\\// }, (args: any) => {\n const rest = args.path.slice('@/'.length) // '.mercato/generated/...'\n const base = path.join(appDir, rest)\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx', '']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // @/* \u2192 app/src/* (tsconfig paths)\n build.onResolve({ filter: /^@\\// }, (args: any) => {\n const rest = args.path.slice('@/'.length)\n const base = path.join(appDir, 'src', rest)\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // #generated/* \u2192 core package generated/* (Node subpath imports)\n build.onResolve({ filter: /^#generated\\// }, (args: any) => {\n const rest = args.path.slice('#generated/'.length)\n const base = path.join(coreGeneratedRoot, rest)\n for (const ext of ['.ts', '/index.ts']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n },\n }\n\n // Plugin: externalize installed packages, stub missing ones\n const nodeBuiltins = new Set([\n 'assert', 'buffer', 'child_process', 'cluster', 'console', 'constants',\n 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'http2',\n 'https', 'module', 'net', 'os', 'path', 'perf_hooks', 'process',\n 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder',\n 'sys', 'timers', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'wasi',\n 'worker_threads', 'zlib', 'async_hooks', 'diagnostics_channel', 'inspector',\n 'trace_events',\n ])\n const externalNonWorkspacePlugin = {\n name: 'external-non-workspace',\n setup(build: any) {\n build.onResolve({ filter: /^[^./]/ }, (args: any) => {\n if (path.isAbsolute(args.path)) return undefined\n if (args.path.startsWith('@open-mercato/')) return undefined\n if (args.path.startsWith('@/')) return undefined\n if (args.path.startsWith('#generated/')) return undefined\n if (args.path.startsWith('next')) return undefined\n // Let esbuild handle Node builtins (with or without node: prefix)\n if (args.path.startsWith('node:')) return undefined\n const topLevel = args.path.split('/')[0]\n if (nodeBuiltins.has(topLevel)) return undefined\n\n // Extract package name (handle scoped packages like @mikro-orm/core)\n const pkgName = args.path.startsWith('@')\n ? args.path.split('/').slice(0, 2).join('/')\n : topLevel\n const pkgDir = path.join(rootDir, 'node_modules', pkgName)\n if (fs.existsSync(pkgDir)) return { external: true }\n\n // Package not installed \u2014 provide CJS stub (allows any named import)\n return { path: args.path, namespace: 'missing-pkg' }\n })\n build.onLoad({ filter: /.*/, namespace: 'missing-pkg' }, () => ({\n contents: 'var h={get:(_,k)=>k===\"__esModule\"?true:p};var p=new Proxy(function(){return p},{get:h.get,apply:()=>p,construct:()=>p});module.exports=p;',\n loader: 'js' as const,\n }))\n },\n }\n\n try {\n const buildResult = await esbuild.build({\n stdin: {\n contents: entryScript,\n resolveDir: appDir,\n sourcefile: 'openapi-entry.ts',\n loader: 'ts',\n },\n bundle: true,\n metafile: true,\n absWorkingDir: rootDir,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: bundlePath,\n write: true,\n ...(tsconfigPath ? { tsconfig: tsconfigPath } : {}),\n logLevel: 'silent',\n jsx: 'automatic',\n plugins: [stubNextPlugin, resolveProjectImportsPlugin, externalNonWorkspacePlugin],\n })\n\n inputPaths = Object.keys(buildResult.metafile?.inputs ?? {})\n .filter((inputPath) => !inputPath.startsWith('<'))\n .map((inputPath) => path.resolve(rootDir, inputPath))\n .filter((inputPath) => fs.existsSync(inputPath))\n .sort((a, b) => a.localeCompare(b))\n\n const stdout = execFileSync(process.execPath, [bundlePath], {\n timeout: 60_000,\n maxBuffer: 20 * 1024 * 1024,\n encoding: 'utf-8',\n env: { ...process.env, NODE_NO_WARNINGS: '1' },\n cwd: rootDir,\n })\n\n const lastLine = stdout.trim().split('\\n').pop()!\n const doc = JSON.parse(lastLine) as Record<string, any>\n\n if (!quiet) {\n const pathCount = Object.keys(doc.paths || {}).length\n const withBody = Object.values(doc.paths || {}).reduce((n: number, methods: any) => {\n for (const m of Object.values(methods)) {\n if ((m as any)?.requestBody) n++\n }\n return n\n }, 0)\n console.log(`[OpenAPI] Bundle approach: ${pathCount} paths, ${withBody} with requestBody schemas`)\n }\n\n return { doc, inputPaths }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err)\n const stderr = (err as any)?.stderr\n const esbuildErrors = (err as any)?.errors as Array<{ text: string; location?: { file: string } }> | undefined\n if (!quiet) {\n console.log(`[OpenAPI] Bundle approach failed, will use static fallback: ${errMsg.split('\\n')[0]}`)\n if (esbuildErrors?.length) {\n const unique = new Map<string, string>()\n for (const e of esbuildErrors) {\n const key = e.text\n if (!unique.has(key)) unique.set(key, e.location?.file ?? '')\n }\n for (const [text, file] of [...unique.entries()].slice(0, 10)) {\n console.log(`[OpenAPI] ${text}${file ? ` (${path.basename(file)})` : ''}`)\n }\n if (unique.size > 10) console.log(`[OpenAPI] ... and ${unique.size - 10} more`)\n }\n if (stderr) {\n for (const line of String(stderr).trim().split('\\n').slice(0, 3)) {\n console.log(`[OpenAPI] ${line}`)\n }\n }\n }\n return { doc: null, inputPaths }\n } finally {\n // Shut down esbuild's persistent Go service so it does not deadlock at\n // process exit when a plugin request is still in flight.\n try { await esbuild.stop() } catch {}\n // Clean up old files from previous tsx-based approach\n try { fs.unlinkSync(bundlePath) } catch {}\n for (const file of ['_openapi-bundle.mjs', '_openapi-register.mjs', '_openapi-loader.mjs', '_next-stub.cjs']) {\n try { fs.unlinkSync(path.join(cacheDir, file)) } catch {}\n }\n }\n}\n\n/**\n * Build OpenAPI paths from discovered routes.\n * Extracts basic operation info from route files statically.\n */\nfunction buildOpenApiPaths(routes: ApiRouteInfo[]): Record<string, any> {\n const paths: Record<string, any> = {}\n\n for (const route of routes) {\n const pathEntry: Record<string, any> = {}\n\n // Try to extract OpenAPI specs from source\n const openApiSpec = parseOpenApiFromSource(route.path)\n\n for (const method of route.methods) {\n const methodLower = method.toLowerCase()\n const spec = openApiSpec?.[method]\n\n // Generate a default operationId if not found\n const pathSegments = route.openApiPath\n .replace(/^\\/api\\//, '')\n .replace(/\\{[^}]+\\}/g, 'by_id')\n .split('/')\n .filter(Boolean)\n .join('_')\n const defaultOperationId = `${methodLower}_${pathSegments}`\n\n pathEntry[methodLower] = {\n operationId: spec?.operationId || defaultOperationId,\n summary: spec?.summary || `${method} ${route.openApiPath}`,\n description: spec?.description || `${method} operation for ${route.openApiPath}`,\n tags: spec?.tags || [route.openApiPath.split('/')[2] || 'api'],\n responses: {\n '200': {\n description: 'Successful response',\n },\n },\n }\n }\n\n if (Object.keys(pathEntry).length > 0) {\n paths[route.openApiPath] = pathEntry\n }\n }\n\n return paths\n}\n\n/**\n * Generate the OpenAPI JSON file.\n */\nexport async function generateOpenApi(options: GenerateOpenApiOptions): Promise<GeneratorResult> {\n const { resolver, quiet = false } = options\n const result = createGeneratorResult()\n\n const outputDir = resolver.getOutputDir()\n const outFile = path.join(outputDir, 'openapi.generated.json')\n const checksumFile = path.join(outputDir, 'openapi.generated.checksum')\n const inputManifestFile = path.join(outputDir, 'openapi.generated.inputs.json')\n\n getEnabledModuleIdentities(resolver, resolver.loadEnabledModules())\n\n // Ensure output directory exists\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true })\n }\n\n const inputContext = createOpenApiInputContext(resolver)\n const existingChecksums = readChecksumRecord(checksumFile)\n const existingManifest = readOpenApiInputManifest(inputManifestFile)\n\n if (\n existingChecksums?.structure\n && existingManifest\n && fs.existsSync(outFile)\n && calculateChecksum(fs.readFileSync(outFile, 'utf8')) === existingChecksums.content\n && calculateOpenApiInputFingerprint(resolver, inputContext, existingManifest) === existingChecksums.structure\n ) {\n result.filesUnchanged.push(outFile)\n if (!quiet) {\n console.log(`[OpenAPI] Skipped (inputs unchanged): ${outFile}`)\n }\n return result\n }\n\n // Find all API routes\n const routes = await findApiRoutes(resolver, inputContext.enabled)\n\n if (!quiet) {\n console.log(`[OpenAPI] Found ${routes.length} API route files`)\n }\n\n // Determine project root (cli package is at packages/cli/src/lib/generators/)\n // Try esbuild bundle approach first \u2014 produces full requestBody/response schemas\n const bundleResult = await generateOpenApiViaBundle(routes, resolver, quiet)\n let doc: Record<string, any> | null = bundleResult.doc\n\n // Fallback to static regex approach (extracts operationId/summary/tags but no schemas)\n if (!doc) {\n if (!quiet) {\n console.warn(\n '[OpenAPI] \u26A0 Bundling failed; falling back to static regex extraction \u2014 '\n + 'request/response schemas are OMITTED from the generated document. '\n + 'The usual cause is a route file importing a module specifier that does not resolve.',\n )\n }\n const paths = buildOpenApiPaths(routes)\n doc = {\n openapi: '3.1.0',\n info: {\n title: 'Open Mercato API',\n version: '1.0.0',\n description: 'Auto-generated OpenAPI specification',\n },\n servers: [\n { url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' },\n ],\n paths,\n components: {\n securitySchemes: {\n bearerAuth: {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n description: 'Send an `Authorization: Bearer <token>` header with a valid API token.',\n },\n },\n },\n }\n }\n\n const output = JSON.stringify(doc, null, 2)\n const checksum = calculateChecksum(output)\n let structureChecksum = ''\n\n if (bundleResult.doc && bundleResult.inputPaths.length > 0) {\n const manifest: OpenApiInputManifest = {\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n inputPaths: Array.from(new Set(bundleResult.inputPaths)).sort((a, b) => a.localeCompare(b)),\n }\n fs.writeFileSync(inputManifestFile, `${JSON.stringify(manifest, null, 2)}\\n`)\n structureChecksum = calculateOpenApiInputFingerprint(resolver, inputContext, manifest)\n } else {\n try { fs.unlinkSync(inputManifestFile) } catch {}\n }\n\n // Check if unchanged\n const existingOutputMatches = fs.existsSync(outFile)\n && calculateChecksum(fs.readFileSync(outFile, 'utf8')) === checksum\n if (existingChecksums && existingChecksums.content === checksum && existingOutputMatches) {\n if (existingChecksums.structure !== structureChecksum) {\n writeChecksumRecord(checksumFile, { content: checksum, structure: structureChecksum })\n }\n result.filesUnchanged.push(outFile)\n if (!quiet) {\n console.log(`[OpenAPI] Skipped (unchanged): ${outFile}`)\n }\n return result\n }\n\n // Write the file\n fs.writeFileSync(outFile, output)\n writeChecksumRecord(checksumFile, { content: checksum, structure: structureChecksum })\n\n result.filesWritten.push(outFile)\n\n if (!quiet) {\n logGenerationResult(outFile, true)\n const pathCount = Object.keys(doc.paths || {}).length\n console.log(`[OpenAPI] Generated ${pathCount} API paths`)\n }\n\n return result\n}\n"],
5
- "mappings": "AAQA,YAAY,QAAQ;AACpB,SAAS,mBAAmB;AAC5B,YAAY,UAAU;AAEtB,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AAoCP,MAAM,iCAAiC;AAEvC,SAAS,0BAA0B,UAAgD;AACjF,QAAM,UAAU,SAAS,mBAAmB;AAC5C,QAAM,WAAqB,CAAC;AAC5B,QAAM,iBAAiB,QAAQ,IAAI,CAAC,UAAU;AAC5C,UAAM,QAAQ,SAAS,eAAe,KAAK;AAC3C,aAAS,KAAK,KAAK,KAAK,MAAM,SAAS,KAAK,GAAG,KAAK,KAAK,MAAM,SAAS,KAAK,CAAC;AAC9E,WAAO;AAAA,MACL,IAAI,MAAM;AAAA,MACV,MAAM,MAAM,QAAQ;AAAA,MACpB,SAAS,KAAK,QAAQ,MAAM,OAAO;AAAA,MACnC,SAAS,KAAK,QAAQ,MAAM,OAAO;AAAA,IACrC;AAAA,EACF,CAAC;AACD,SAAO,EAAE,SAAS,UAAU,eAAe;AAC7C;AAEA,SAAS,yBAAyB,UAA+C;AAC/E,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,GAAG,aAAa,UAAU,MAAM,CAAC;AAC3D,QACE,OAAO,YAAY,kCAChB,CAAC,MAAM,QAAQ,OAAO,UAAU,KAChC,OAAO,WAAW,KAAK,CAAC,UAAU,OAAO,UAAU,QAAQ,GAC9D;AACA,aAAO;AAAA,IACT;AACA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,YAAY,MAAM,KAAK,IAAI,IAAI,OAAO,WAAW,IAAI,CAAC,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC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SAAS,GAAG;AAC1D,UAAM,WAAiC;AAAA,MACrC,SAAS;AAAA,MACT,YAAY,MAAM,KAAK,IAAI,IAAI,aAAa,UAAU,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC;AAAA,IAC5F;AACA,OAAG,cAAc,mBAAmB,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AAC5E,wBAAoB,iCAAiC,UAAU,cAAc,QAAQ;AAAA,EACvF,OAAO;AACL,QAAI;AAAE,SAAG,WAAW,iBAAiB;AAAA,IAAE,QAAQ;AAAA,IAAC;AAAA,EAClD;AAGA,QAAM,wBAAwB,GAAG,WAAW,OAAO,KAC9C,kBAAkB,GAAG,aAAa,SAAS,MAAM,CAAC,MAAM;AAC7D,MAAI,qBAAqB,kBAAkB,YAAY,YAAY,uBAAuB;AACxF,QAAI,kBAAkB,cAAc,mBAAmB;AACrD,0BAAoB,cAAc,EAAE,SAAS,UAAU,WAAW,kBAAkB,CAAC;AAAA,IACvF;AACA,WAAO,eAAe,KAAK,OAAO;AAClC,QAAI,CAAC,OAAO;AACV,cAAQ,IAAI,kCAAkC,OAAO,EAAE;AAAA,IACzD;AACA,WAAO;AAAA,EACT;AAGA,KAAG,cAAc,SAAS,MAAM;AAChC,sBAAoB,cAAc,EAAE,SAAS,UAAU,WAAW,kBAAkB,CAAC;AAErF,SAAO,aAAa,KAAK,OAAO;AAEhC,MAAI,CAAC,OAAO;AACV,wBAAoB,SAAS,IAAI;AACjC,UAAM,YAAY,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,EAAE;AAC/C,YAAQ,IAAI,uBAAuB,SAAS,YAAY;AAAA,EAC1D;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * OpenAPI JSON Generator\n *\n * Generates a static openapi.generated.json file at build time.\n * This allows CLI tools (like MCP dev server) to access API endpoint\n * information without requiring a running Next.js app.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport type { ModuleEntry, PackageResolver } from '../resolver'\nimport { getEnabledModuleIdentities } from '../module-identity'\nimport { isModuleRouteFile } from './scanner'\nimport { resolveNamedObjectExport } from './module-registry'\nimport { generatedDerivedCrudRouteIndex, readDerivedCrudFormSectionRouteIndex } from './form-sections'\nimport {\n calculateChecksum,\n calculateStructureChecksum,\n readChecksumRecord,\n writeChecksumRecord,\n logGenerationResult,\n type GeneratorResult,\n createGeneratorResult,\n} from '../utils'\n\nexport interface GenerateOpenApiOptions {\n resolver: PackageResolver\n quiet?: boolean\n}\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\ninterface ApiRouteInfo {\n path: string\n moduleId: string\n methods: HttpMethod[]\n openApiPath: string\n}\n\ninterface OpenApiInputManifest {\n version: 2\n inputPaths: string[]\n}\n\ninterface OpenApiInputContext {\n enabled: ModuleEntry[]\n apiRoots: string[]\n moduleIdentity: Array<{\n id: string\n from: string\n appBase: string\n pkgBase: string\n }>\n}\n\ninterface OpenApiBundleResult {\n doc: Record<string, any> | null\n inputPaths: string[]\n qualifierFailure?: string\n}\n\nconst OPENAPI_INPUT_MANIFEST_VERSION = 2\n\nfunction createOpenApiInputContext(resolver: PackageResolver): OpenApiInputContext {\n const enabled = resolver.loadEnabledModules()\n const apiRoots: string[] = []\n const moduleIdentity = enabled.map((entry) => {\n const roots = resolver.getModulePaths(entry)\n apiRoots.push(path.join(roots.appBase, 'api'), path.join(roots.pkgBase, 'api'))\n return {\n id: entry.id,\n from: entry.from ?? '@open-mercato/core',\n appBase: path.resolve(roots.appBase),\n pkgBase: path.resolve(roots.pkgBase),\n }\n })\n return { enabled, apiRoots, moduleIdentity }\n}\n\nfunction readOpenApiInputManifest(filePath: string): OpenApiInputManifest | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<OpenApiInputManifest>\n if (\n parsed.version !== OPENAPI_INPUT_MANIFEST_VERSION\n || !Array.isArray(parsed.inputPaths)\n || parsed.inputPaths.some((entry) => typeof entry !== 'string')\n ) {\n return null\n }\n return {\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n inputPaths: Array.from(new Set(parsed.inputPaths.map((entry) => path.resolve(entry))))\n .sort((a, b) => a.localeCompare(b)),\n }\n } catch {\n return null\n }\n}\n\n/** All successful bundle inputs, including generated producers; null means unknown. */\nexport function getOpenApiGeneratorDependencies(resolver: PackageResolver): readonly string[] | null {\n return readOpenApiInputManifest(\n path.join(resolver.getOutputDir(), 'openapi.generated.inputs.json'),\n )?.inputPaths ?? null\n}\n\n/**\n * Returns source inputs from the last successful bundle, including paths since\n * deleted. An empty result does not prove that no dependencies exist: missing or\n * invalid manifests require the watcher's conservative unknown-change fallback.\n */\nexport function getOpenApiWatchInputs(resolver: PackageResolver): string[] {\n const inputPaths = getOpenApiGeneratorDependencies(resolver)\n if (!inputPaths) return []\n\n const packageNames = new Set([\n '@open-mercato/core',\n ...resolver.loadEnabledModules().map((entry) => entry.from ?? '@open-mercato/core'),\n ])\n const generatedRoots = Array.from(new Set([\n path.resolve(resolver.getOutputDir()),\n ...Array.from(packageNames, (name) => path.resolve(resolver.getPackageOutputDir(name))),\n ]))\n return inputPaths.filter((inputPath) => !generatedRoots.some((root) => {\n const relative = path.relative(root, inputPath)\n return relative === '' || (\n relative !== '..'\n && !relative.startsWith(`..${path.sep}`)\n && !path.isAbsolute(relative)\n )\n }))\n}\n\nfunction trackedPathRecord(filePath: string): string {\n try {\n const stat = fs.statSync(filePath)\n if (stat.isFile()) {\n return `${path.resolve(filePath)}:${calculateChecksum(fs.readFileSync(filePath, 'utf8'))}`\n }\n return `${path.resolve(filePath)}:${stat.size}:${stat.mtimeMs}`\n } catch {\n return `missing:${path.resolve(filePath)}`\n }\n}\n\nfunction calculateOpenApiInputFingerprint(\n resolver: PackageResolver,\n context: OpenApiInputContext,\n manifest: OpenApiInputManifest,\n): string {\n const rootDir = resolver.getRootDir()\n const appDir = resolver.getAppDir()\n const configPaths = [\n resolver.getModulesConfigPath(),\n path.join(resolver.getOutputDir(), generatedDerivedCrudRouteIndex),\n path.join(rootDir, 'package.json'),\n path.join(rootDir, 'yarn.lock'),\n path.join(rootDir, 'package-lock.json'),\n path.join(rootDir, 'pnpm-lock.yaml'),\n path.join(rootDir, 'tsconfig.json'),\n path.join(rootDir, 'tsconfig.base.json'),\n path.join(appDir, 'package.json'),\n path.join(appDir, 'tsconfig.json'),\n ]\n const trackedRecords = [...manifest.inputPaths, ...configPaths]\n .map(trackedPathRecord)\n .sort((a, b) => a.localeCompare(b))\n return calculateChecksum(JSON.stringify({\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n modules: context.moduleIdentity,\n routeStructure: calculateStructureChecksum(context.apiRoots),\n trackedRecords,\n environment: {\n node: process.version,\n nodeEnv: process.env.NODE_ENV ?? '',\n publicAppUrl: process.env.NEXT_PUBLIC_APP_URL ?? '',\n },\n }))\n}\n\nfunction resolveExistingPath(paths: string[]): string | null {\n for (const candidate of paths) {\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\n/**\n * Find all API route files and extract their OpenAPI specs.\n */\nasync function findApiRoutes(\n resolver: PackageResolver,\n enabled: ModuleEntry[],\n): Promise<ApiRouteInfo[]> {\n const routes: ApiRouteInfo[] = []\n\n for (const entry of enabled) {\n const modId = entry.id\n const roots = resolver.getModulePaths(entry)\n\n const apiApp = path.join(roots.appBase, 'api')\n const apiPkg = path.join(roots.pkgBase, 'api')\n\n // Scan route files\n const routeFiles: Array<{ relativePath: string; fullPath: string }> = []\n\n const walkDir = (dir: string, rel: string[] = []) => {\n if (!fs.existsSync(dir)) return\n for (const e of fs.readdirSync(dir, { withFileTypes: true })) {\n if (e.isDirectory()) {\n if (e.name === '__tests__' || e.name === '__mocks__') continue\n walkDir(path.join(dir, e.name), [...rel, e.name])\n } else if (e.isFile() && isModuleRouteFile(e.name)) {\n routeFiles.push({\n relativePath: [...rel].join('/'),\n fullPath: path.join(dir, e.name),\n })\n }\n }\n }\n\n // Scan package first, then app (app overrides)\n if (fs.existsSync(apiPkg)) walkDir(apiPkg)\n if (fs.existsSync(apiApp)) walkDir(apiApp)\n\n // Process unique routes (later app files overwrite earlier package files)\n const filesByRelativePath = new Map<string, string>()\n for (const { relativePath, fullPath } of routeFiles) {\n filesByRelativePath.set(relativePath, fullPath)\n }\n\n for (const [relativePath, fullPath] of filesByRelativePath) {\n\n // Build API path\n const routeSegs = relativePath ? relativePath.split('/') : []\n const metadataPath = resolveNamedObjectExport(fullPath, 'metadata')?.path\n const routePath = typeof metadataPath === 'string' && metadataPath\n ? metadataPath\n : `/${modId}${routeSegs.length ? '/' + routeSegs.join('/') : ''}`\n const apiPath = `/api/${routePath.replace(/^\\/+/, '')}`\n // Convert [param] to {param} for OpenAPI format\n .replace(/\\[([^\\]]+)\\]/g, '{$1}')\n\n routes.push({\n path: fullPath,\n moduleId: modId,\n methods: await detectMethods(fullPath),\n openApiPath: apiPath,\n })\n }\n }\n\n const enabledIds = new Set(enabled.map(({ id }) => id))\n const derived = readDerivedCrudFormSectionRouteIndex(resolver.getOutputDir())\n routes.push(...derived.filter(({ moduleId }) => enabledIds.has(moduleId)).map(({ moduleId, routePath, methods, fileName }) => ({\n moduleId, methods,\n path: path.join(resolver.getOutputDir(), fileName),\n openApiPath: `/api${routePath}`.replace(/\\[([^\\]]+)\\]/g, '{$1}'),\n })))\n return routes\n}\n\n/**\n * Detect which HTTP methods are exported from a route file.\n */\nasync function detectMethods(filePath: string): Promise<HttpMethod[]> {\n const methods: HttpMethod[] = []\n const content = fs.readFileSync(filePath, 'utf-8')\n\n const methodPatterns: HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n for (const method of methodPatterns) {\n // Check for export { GET }, export const GET, export async function GET\n const patterns = [\n new RegExp(`export\\\\s+(const|async\\\\s+function|function)\\\\s+${method}\\\\b`),\n new RegExp(`export\\\\s*\\\\{[^}]*\\\\b${method}\\\\b[^}]*\\\\}`),\n ]\n if (patterns.some((p) => p.test(content))) {\n methods.push(method)\n }\n }\n\n return methods\n}\n\n/**\n * Parse openApi export from route file source code statically.\n * This extracts basic operation info without needing to compile the file.\n */\nfunction parseOpenApiFromSource(filePath: string): Record<string, any> | null {\n try {\n const content = fs.readFileSync(filePath, 'utf-8')\n\n // Check if file exports openApi\n if (!content.includes('export const openApi') && !content.includes('export { openApi')) {\n return null\n }\n\n // Extract operationId, summary, description from the source\n const result: Record<string, any> = {}\n const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n\n for (const method of methods) {\n // Look for method specs in the openApi object\n // Pattern: GET: { operationId: '...', summary: '...', ... }\n const methodPattern = new RegExp(\n `${method}\\\\s*:\\\\s*\\\\{([^}]+(?:\\\\{[^}]*\\\\}[^}]*)*)\\\\}`,\n 's'\n )\n const methodMatch = content.match(methodPattern)\n\n if (methodMatch) {\n const methodContent = methodMatch[1]\n const spec: Record<string, any> = {}\n\n // Extract operationId\n const opIdMatch = methodContent.match(/operationId\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (opIdMatch) spec.operationId = opIdMatch[1]\n\n // Extract summary\n const summaryMatch = methodContent.match(/summary\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (summaryMatch) spec.summary = summaryMatch[1]\n\n // Extract description\n const descMatch = methodContent.match(/description\\s*:\\s*['\"]([^'\"]+)['\"]/)\n if (descMatch) spec.description = descMatch[1]\n\n // Extract tags\n const tagsMatch = methodContent.match(/tags\\s*:\\s*\\[([^\\]]*)\\]/)\n if (tagsMatch) {\n const tagsContent = tagsMatch[1]\n const tags = tagsContent.match(/['\"]([^'\"]+)['\"]/g)\n if (tags) {\n spec.tags = tags.map(t => t.replace(/['\"]/g, ''))\n }\n }\n\n if (Object.keys(spec).length > 0) {\n result[method] = spec\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : null\n } catch {\n return null\n }\n}\n\n/**\n * Generate a complete OpenAPI document by bundling route files with esbuild\n * and executing the bundle to call buildOpenApiDocument from @open-mercato/shared.\n *\n * esbuild compiles TypeScript with legacy decorator support (reads experimentalDecorators\n * from tsconfig.json), avoiding the TC39 decorator mismatch that breaks tsx-based imports.\n * External packages (zod, mikro-orm, etc.) are resolved from node_modules at runtime.\n */\nasync function generateOpenApiViaBundle(\n routes: ApiRouteInfo[],\n resolver: PackageResolver,\n quiet: boolean\n): Promise<OpenApiBundleResult> {\n let esbuild: typeof import('esbuild')\n try {\n esbuild = await import('esbuild')\n } catch {\n if (!quiet) console.log('[OpenAPI] esbuild not available, skipping bundle approach')\n return { doc: null, inputPaths: [] }\n }\n\n const { execFileSync } = await import('node:child_process')\n\n const rootDir = resolver.getRootDir()\n const appDir = resolver.getAppDir()\n const sharedPackageRoot = resolver.getPackageRoot('@open-mercato/shared')\n const corePackageRoot = resolver.getPackageRoot('@open-mercato/core')\n const tsconfigPath = resolveExistingPath([\n path.join(appDir, 'tsconfig.json'),\n path.join(rootDir, 'tsconfig.base.json'),\n path.join(rootDir, 'tsconfig.json'),\n ])\n const generatorPath = path.join(sharedPackageRoot, 'src', 'lib', 'openapi', 'generator.ts')\n const coreGeneratedRoot = path.join(corePackageRoot, 'generated')\n\n if (!fs.existsSync(generatorPath)) {\n if (!quiet) {\n console.log(`[OpenAPI] Generator source not found at ${generatorPath}, skipping bundle approach`)\n }\n return { doc: null, inputPaths: [] }\n }\n\n let inputPaths: string[] = []\n\n // Build the entry script that imports all routes and calls buildOpenApiDocument\n const importLines: string[] = [\n `import { buildOpenApiDocument } from ${JSON.stringify(generatorPath)};`,\n ]\n const routeMapLines: string[] = []\n\n for (let i = 0; i < routes.length; i++) {\n const route = routes[i]\n importLines.push(`import * as R${i} from ${JSON.stringify(route.path)};`)\n // Use [param] format so normalizePath in buildOpenApiDocument extracts path params\n const bracketPath = route.openApiPath.replace(/\\{([^}]+)\\}/g, '[$1]')\n routeMapLines.push(` [${JSON.stringify(bracketPath)}, ${JSON.stringify(route.moduleId)}, R${i}],`)\n }\n\n const entryScript = `${importLines.join('\\n')}\n\nconst routeEntries = [\n${routeMapLines.join('\\n')}\n];\n\nconst modules = new Map();\nfor (const [apiPath, moduleId, mod] of routeEntries) {\n if (!modules.has(moduleId)) modules.set(moduleId, { id: moduleId, apis: [] });\n modules.get(moduleId).apis.push({\n path: apiPath,\n handlers: mod,\n metadata: mod.metadata,\n });\n}\n\nconst doc = buildOpenApiDocument([...modules.values()], {\n title: 'Open Mercato API',\n version: '1.0.0',\n description: 'Auto-generated OpenAPI specification',\n servers: [{ url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' }],\n});\n\n// Deep-clone to break shared object references before serializing.\n// The zodToJsonSchema memo cache returns the same object instance for\n// fields like currencyCode that appear on both parent and child schemas.\n// A naive WeakSet-based circular-ref guard would drop the second occurrence,\n// causing properties to vanish from the generated spec (while the field\n// still appears in the 'required' array, since those are plain strings).\nconst deepClone = (v, ancestors = []) => {\n if (v === null || typeof v !== 'object') return v;\n if (typeof v === 'bigint') return Number(v);\n if (typeof v === 'function') return undefined;\n if (ancestors.includes(v)) return undefined; // true circular ref\n const next = [...ancestors, v];\n if (Array.isArray(v)) return v.map((item) => deepClone(item, next));\n const out = {};\n for (const [k, val] of Object.entries(v)) {\n const cloned = deepClone(val, next);\n if (cloned !== undefined) out[k] = cloned;\n }\n return out;\n};\nprocess.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>\n typeof v === 'bigint' ? Number(v) : v\n));\n`\n\n // Plugin: stub next/* imports (not available outside Next.js app context)\n const stubNextPlugin = {\n name: 'stub-next',\n setup(build: any) {\n build.onResolve({ filter: /^next($|\\/)/ }, () => ({\n path: 'next-stub',\n namespace: 'next-stub',\n }))\n build.onLoad({ filter: /.*/, namespace: 'next-stub' }, () => ({\n contents: [\n 'const p = new Proxy(function(){}, {',\n ' get(_, k) { return k === \"__esModule\" ? true : k === \"default\" ? p : p; },',\n ' apply() { return p; },',\n ' construct() { return p; },',\n '});',\n 'export default p;',\n 'export const NextRequest = p, NextResponse = p, headers = p, cookies = p;',\n 'export const redirect = p, notFound = p, useRouter = p, usePathname = p;',\n 'export const useSearchParams = p, permanentRedirect = p, revalidatePath = p;',\n ].join('\\n'),\n loader: 'js' as const,\n }))\n },\n }\n\n // Plugin: resolve workspace imports, aliases, and subpath imports\n const resolveProjectImportsPlugin = {\n name: 'resolve-project-imports',\n setup(build: any) {\n // @open-mercato/<pkg>/<path> \u2192 packageRoot/src/<path>.ts\n build.onResolve({ filter: /^@open-mercato\\// }, (args: any) => {\n const withoutScope = args.path.slice('@open-mercato/'.length)\n const slashIdx = withoutScope.indexOf('/')\n const pkg = slashIdx === -1 ? withoutScope : withoutScope.slice(0, slashIdx)\n const rest = slashIdx === -1 ? '' : withoutScope.slice(slashIdx + 1)\n const packageName = `@open-mercato/${pkg}`\n const packageRoot = resolver.getPackageRoot(packageName)\n\n const base = rest\n ? path.join(packageRoot, 'src', rest)\n : path.join(packageRoot, 'src', 'index')\n\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // @/.mercato/* \u2192 app/.mercato/* (tsconfig paths)\n build.onResolve({ filter: /^@\\/\\.mercato\\// }, (args: any) => {\n const rest = args.path.slice('@/'.length) // '.mercato/generated/...'\n const base = path.join(appDir, rest)\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx', '']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // @/* \u2192 app/src/* (tsconfig paths)\n build.onResolve({ filter: /^@\\// }, (args: any) => {\n const rest = args.path.slice('@/'.length)\n const base = path.join(appDir, 'src', rest)\n for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n\n // #generated/* \u2192 core package generated/* (Node subpath imports)\n build.onResolve({ filter: /^#generated\\// }, (args: any) => {\n const rest = args.path.slice('#generated/'.length)\n const base = path.join(coreGeneratedRoot, rest)\n for (const ext of ['.ts', '/index.ts']) {\n if (fs.existsSync(base + ext)) return { path: base + ext }\n }\n return undefined\n })\n },\n }\n\n // Plugin: externalize installed packages, stub missing ones\n const nodeBuiltins = new Set([\n 'assert', 'buffer', 'child_process', 'cluster', 'console', 'constants',\n 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'http2',\n 'https', 'module', 'net', 'os', 'path', 'perf_hooks', 'process',\n 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder',\n 'sys', 'timers', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'wasi',\n 'worker_threads', 'zlib', 'async_hooks', 'diagnostics_channel', 'inspector',\n 'trace_events',\n ])\n const externalNonWorkspacePlugin = {\n name: 'external-non-workspace',\n setup(build: any) {\n build.onResolve({ filter: /^[^./]/ }, (args: any) => {\n if (path.isAbsolute(args.path)) return undefined\n if (args.path.startsWith('@open-mercato/')) return undefined\n if (args.path.startsWith('@/')) return undefined\n if (args.path.startsWith('#generated/')) return undefined\n if (args.path.startsWith('next')) return undefined\n // Let esbuild handle Node builtins (with or without node: prefix)\n if (args.path.startsWith('node:')) return undefined\n const topLevel = args.path.split('/')[0]\n if (nodeBuiltins.has(topLevel)) return undefined\n\n // Extract package name (handle scoped packages like @mikro-orm/core)\n const pkgName = args.path.startsWith('@')\n ? args.path.split('/').slice(0, 2).join('/')\n : topLevel\n const pkgDir = path.join(rootDir, 'node_modules', pkgName)\n if (fs.existsSync(pkgDir)) return { external: true }\n\n // Package not installed \u2014 provide CJS stub (allows any named import)\n return { path: args.path, namespace: 'missing-pkg' }\n })\n build.onLoad({ filter: /.*/, namespace: 'missing-pkg' }, () => ({\n contents: 'var h={get:(_,k)=>k===\"__esModule\"?true:p};var p=new Proxy(function(){return p},{get:h.get,apply:()=>p,construct:()=>p});module.exports=p;',\n loader: 'js' as const,\n }))\n },\n }\n\n const bundleDir = fs.mkdtempSync(path.join(resolver.getOutputDir(), '.openapi-'))\n const bundlePath = path.join(bundleDir, 'bundle.mjs')\n try {\n const buildResult = await esbuild.build({\n stdin: {\n contents: entryScript,\n resolveDir: appDir,\n sourcefile: 'openapi-entry.ts',\n loader: 'ts',\n },\n bundle: true,\n metafile: true,\n absWorkingDir: rootDir,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: bundlePath,\n write: true,\n ...(tsconfigPath ? { tsconfig: tsconfigPath } : {}),\n logLevel: 'silent',\n jsx: 'automatic',\n plugins: [stubNextPlugin, resolveProjectImportsPlugin, externalNonWorkspacePlugin],\n })\n\n inputPaths = Object.keys(buildResult.metafile?.inputs ?? {})\n .filter((inputPath) => !inputPath.startsWith('<'))\n .map((inputPath) => path.resolve(rootDir, inputPath))\n .filter((inputPath) => fs.existsSync(inputPath))\n .sort((a, b) => a.localeCompare(b))\n\n const stdout = execFileSync(process.execPath, [bundlePath], {\n timeout: 60_000,\n maxBuffer: 20 * 1024 * 1024,\n encoding: 'utf-8',\n env: { ...process.env, NODE_NO_WARNINGS: '1' },\n cwd: rootDir,\n })\n\n const lastLine = stdout.trim().split('\\n').pop()!\n const doc = JSON.parse(lastLine) as Record<string, any>\n\n if (!quiet) {\n const pathCount = Object.keys(doc.paths || {}).length\n const withBody = Object.values(doc.paths || {}).reduce((n: number, methods: any) => {\n for (const m of Object.values(methods)) {\n if ((m as any)?.requestBody) n++\n }\n return n\n }, 0)\n console.log(`[OpenAPI] Bundle approach: ${pathCount} paths, ${withBody} with requestBody schemas`)\n }\n\n return { doc, inputPaths }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err)\n const stderr = (err as any)?.stderr\n const esbuildErrors = (err as any)?.errors as Array<{ text: string; location?: { file: string } }> | undefined\n if (!quiet) {\n console.log(`[OpenAPI] Bundle approach failed, will use static fallback: ${errMsg.split('\\n')[0]}`)\n if (esbuildErrors?.length) {\n const unique = new Map<string, string>()\n for (const e of esbuildErrors) {\n const key = e.text\n if (!unique.has(key)) unique.set(key, e.location?.file ?? '')\n }\n for (const [text, file] of [...unique.entries()].slice(0, 10)) {\n console.log(`[OpenAPI] ${text}${file ? ` (${path.basename(file)})` : ''}`)\n }\n if (unique.size > 10) console.log(`[OpenAPI] ... and ${unique.size - 10} more`)\n }\n if (stderr) {\n for (const line of String(stderr).trim().split('\\n').slice(0, 3)) {\n console.log(`[OpenAPI] ${line}`)\n }\n }\n }\n const qualifierFailure = /Cannot derive CrudForm section host: [^\\r\\n]+/.exec(`${errMsg}\\n${String(stderr ?? '')}`)?.[0]\n return { doc: null, inputPaths, qualifierFailure }\n } finally {\n // Shut down esbuild's persistent Go service so it does not deadlock at\n // process exit when a plugin request is still in flight.\n try { await esbuild.stop() } catch {}\n try { fs.rmSync(bundleDir, { recursive: true, force: true }) } catch {}\n }\n}\n\n/**\n * Build OpenAPI paths from discovered routes.\n * Extracts basic operation info from route files statically.\n */\nfunction buildOpenApiPaths(routes: ApiRouteInfo[]): Record<string, any> {\n const paths: Record<string, any> = {}\n\n for (const route of routes) {\n const pathEntry: Record<string, any> = {}\n\n // Try to extract OpenAPI specs from source\n const openApiSpec = parseOpenApiFromSource(route.path)\n\n for (const method of route.methods) {\n const methodLower = method.toLowerCase()\n const spec = openApiSpec?.[method]\n\n // Generate a default operationId if not found\n const pathSegments = route.openApiPath\n .replace(/^\\/api\\//, '')\n .replace(/\\{[^}]+\\}/g, 'by_id')\n .split('/')\n .filter(Boolean)\n .join('_')\n const defaultOperationId = `${methodLower}_${pathSegments}`\n\n pathEntry[methodLower] = {\n operationId: spec?.operationId || defaultOperationId,\n summary: spec?.summary || `${method} ${route.openApiPath}`,\n description: spec?.description || `${method} operation for ${route.openApiPath}`,\n tags: spec?.tags || [route.openApiPath.split('/')[2] || 'api'],\n responses: {\n '200': {\n description: 'Successful response',\n },\n },\n }\n }\n\n if (Object.keys(pathEntry).length > 0) {\n paths[route.openApiPath] = pathEntry\n }\n }\n\n return paths\n}\n\n/**\n * Generate the OpenAPI JSON file.\n */\nexport async function generateOpenApi(options: GenerateOpenApiOptions): Promise<GeneratorResult> {\n const { resolver, quiet = false } = options\n const result = createGeneratorResult()\n\n const outputDir = resolver.getOutputDir()\n const outFile = path.join(outputDir, 'openapi.generated.json')\n const checksumFile = path.join(outputDir, 'openapi.generated.checksum')\n const inputManifestFile = path.join(outputDir, 'openapi.generated.inputs.json')\n\n getEnabledModuleIdentities(resolver, resolver.loadEnabledModules())\n\n // Ensure output directory exists\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true })\n }\n\n const inputContext = createOpenApiInputContext(resolver)\n const existingChecksums = readChecksumRecord(checksumFile)\n const existingManifest = readOpenApiInputManifest(inputManifestFile)\n\n if (\n existingChecksums?.structure\n && existingManifest\n && fs.existsSync(outFile)\n && calculateChecksum(fs.readFileSync(outFile, 'utf8')) === existingChecksums.content\n && calculateOpenApiInputFingerprint(resolver, inputContext, existingManifest) === existingChecksums.structure\n ) {\n result.filesUnchanged.push(outFile)\n if (!quiet) {\n console.log(`[OpenAPI] Skipped (inputs unchanged): ${outFile}`)\n }\n return result\n }\n\n // Find all API routes\n const routes = await findApiRoutes(resolver, inputContext.enabled)\n\n if (!quiet) {\n console.log(`[OpenAPI] Found ${routes.length} API route files`)\n }\n\n // Determine project root (cli package is at packages/cli/src/lib/generators/)\n // Try esbuild bundle approach first \u2014 produces full requestBody/response schemas\n const bundleResult = await generateOpenApiViaBundle(routes, resolver, quiet)\n let doc: Record<string, any> | null = bundleResult.doc\n\n if (!doc && readDerivedCrudFormSectionRouteIndex(outputDir).length) {\n throw new Error(bundleResult.qualifierFailure ?? '[generate] Could not validate generated CrudForm section-policy OpenAPI schemas')\n }\n\n // Fallback to static regex approach (extracts operationId/summary/tags but no schemas)\n if (!doc) {\n if (!quiet) {\n console.warn(\n '[OpenAPI] \u26A0 Bundling failed; falling back to static regex extraction \u2014 '\n + 'request/response schemas are OMITTED from the generated document. '\n + 'The usual cause is a route file importing a module specifier that does not resolve.',\n )\n }\n const paths = buildOpenApiPaths(routes)\n doc = {\n openapi: '3.1.0',\n info: {\n title: 'Open Mercato API',\n version: '1.0.0',\n description: 'Auto-generated OpenAPI specification',\n },\n servers: [\n { url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' },\n ],\n paths,\n components: {\n securitySchemes: {\n bearerAuth: {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n description: 'Send an `Authorization: Bearer <token>` header with a valid API token.',\n },\n },\n },\n }\n }\n\n const output = JSON.stringify(doc, null, 2)\n const checksum = calculateChecksum(output)\n let structureChecksum = ''\n\n if (bundleResult.doc && bundleResult.inputPaths.length > 0) {\n const manifest: OpenApiInputManifest = {\n version: OPENAPI_INPUT_MANIFEST_VERSION,\n inputPaths: Array.from(new Set(bundleResult.inputPaths)).sort((a, b) => a.localeCompare(b)),\n }\n fs.writeFileSync(inputManifestFile, `${JSON.stringify(manifest, null, 2)}\\n`)\n structureChecksum = calculateOpenApiInputFingerprint(resolver, inputContext, manifest)\n } else {\n try { fs.unlinkSync(inputManifestFile) } catch {}\n }\n\n // Check if unchanged\n const existingOutputMatches = fs.existsSync(outFile)\n && calculateChecksum(fs.readFileSync(outFile, 'utf8')) === checksum\n if (existingChecksums && existingChecksums.content === checksum && existingOutputMatches) {\n if (existingChecksums.structure !== structureChecksum) {\n writeChecksumRecord(checksumFile, { content: checksum, structure: structureChecksum })\n }\n result.filesUnchanged.push(outFile)\n if (!quiet) {\n console.log(`[OpenAPI] Skipped (unchanged): ${outFile}`)\n }\n return result\n }\n\n // Write the file\n fs.writeFileSync(outFile, output)\n writeChecksumRecord(checksumFile, { content: checksum, structure: structureChecksum })\n\n result.filesWritten.push(outFile)\n\n if (!quiet) {\n logGenerationResult(outFile, true)\n const pathCount = Object.keys(doc.paths || {}).length\n console.log(`[OpenAPI] Generated ${pathCount} API paths`)\n }\n\n return result\n}\n"],
5
+ "mappings": "AAQA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAEtB,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,gCAAgC,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AAK,OAAO;AAEhC,MAAI,CAAC,OAAO;AACV,wBAAoB,SAAS,IAAI;AACjC,UAAM,YAAY,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,EAAE;AAC/C,YAAQ,IAAI,uBAAuB,SAAS,YAAY;AAAA,EAC1D;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { purgeConfiguredCachePatternsAcrossTenantScopes } from "@open-mercato/shared/lib/cache/maintenance";
4
+ import {
5
+ CacheProviderError,
6
+ isCacheProviderError,
7
+ prepareCacheProviderSelection,
8
+ readSelectedCacheProviderId
9
+ } from "@open-mercato/shared/lib/cache/providers";
10
+ import { loadCacheProviderManifest } from "./cache-provider-manifest.js";
4
11
  const STRUCTURAL_CACHE_PATTERNS = [
5
12
  "nav:*",
6
13
  "crud|*|*|*/admin/nav|*",
@@ -21,6 +28,18 @@ function touchGeneratedFiles(appDir) {
21
28
  }
22
29
  return touched;
23
30
  }
31
+ async function purgeStructuralCacheEntries(appDir) {
32
+ const providerId = readSelectedCacheProviderId(process.env);
33
+ if (!providerId) return purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
34
+ try {
35
+ await loadCacheProviderManifest(appDir);
36
+ await prepareCacheProviderSelection();
37
+ return await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
38
+ } catch (error) {
39
+ if (isCacheProviderError(error)) throw error;
40
+ throw new CacheProviderError("unavailable", "Cache provider structural purge failed", { cause: error });
41
+ }
42
+ }
24
43
  async function runPostGenerateStructuralInvalidation(appDir) {
25
44
  let cacheEntriesDeleted = 0;
26
45
  let generatedFilesTouched = [];
@@ -32,7 +51,7 @@ async function runPostGenerateStructuralInvalidation(appDir) {
32
51
  generatedFilesError = error;
33
52
  }
34
53
  try {
35
- cacheEntriesDeleted = await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
54
+ cacheEntriesDeleted = await purgeStructuralCacheEntries(appDir);
36
55
  } catch (error) {
37
56
  cacheError = error;
38
57
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/post-generate-invalidation.ts"],
4
- "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { purgeConfiguredCachePatternsAcrossTenantScopes } from '@open-mercato/shared/lib/cache/maintenance'\n\nconst STRUCTURAL_CACHE_PATTERNS = [\n 'nav:*',\n 'crud|*|*|*/admin/nav|*',\n 'crud|*|*|*/portal/nav|*',\n]\nconst TOUCHABLE_GENERATED_FILE_PATTERN = /\\.generated(?:\\.[a-z0-9]+)?(?:\\.ts|\\.checksum)$/i\n\nexport type PostGenerateStructuralInvalidationResult = {\n cacheEntriesDeleted: number\n generatedFilesTouched: string[]\n cacheError: unknown | null\n generatedFilesError: unknown | null\n}\n\nfunction touchGeneratedFiles(appDir: string): string[] {\n const generatedDir = path.join(appDir, '.mercato', 'generated')\n if (!fs.existsSync(generatedDir) || !fs.statSync(generatedDir).isDirectory()) return []\n\n const touched: string[] = []\n // `utimes` advances mtime without opening the file for writing. Rewriting the\n // identical bytes would truncate multi-megabyte registries first, and Turbopack\n // reads them concurrently during a dev compile \u2014 it can observe the empty window.\n const touchedAt = new Date()\n const entries = fs.readdirSync(generatedDir, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n for (const entry of entries) {\n if (!entry.isFile() || !TOUCHABLE_GENERATED_FILE_PATTERN.test(entry.name)) continue\n const filePath = path.join(generatedDir, entry.name)\n fs.utimesSync(filePath, touchedAt, touchedAt)\n touched.push(filePath)\n }\n return touched\n}\n\nexport async function runPostGenerateStructuralInvalidation(\n appDir: string,\n): Promise<PostGenerateStructuralInvalidationResult> {\n let cacheEntriesDeleted = 0\n let generatedFilesTouched: string[] = []\n let cacheError: unknown | null = null\n let generatedFilesError: unknown | null = null\n\n try {\n generatedFilesTouched = touchGeneratedFiles(appDir)\n } catch (error) {\n generatedFilesError = error\n }\n\n try {\n cacheEntriesDeleted = await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n } catch (error) {\n cacheError = error\n }\n\n return {\n cacheEntriesDeleted,\n generatedFilesTouched,\n cacheError,\n generatedFilesError,\n }\n}\n"],
5
- "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,sDAAsD;AAE/D,MAAM,4BAA4B;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mCAAmC;AASzC,SAAS,oBAAoB,QAA0B;AACrD,QAAM,eAAe,KAAK,KAAK,QAAQ,YAAY,WAAW;AAC9D,MAAI,CAAC,GAAG,WAAW,YAAY,KAAK,CAAC,GAAG,SAAS,YAAY,EAAE,YAAY,EAAG,QAAO,CAAC;AAEtF,QAAM,UAAoB,CAAC;AAI3B,QAAM,YAAY,oBAAI,KAAK;AAC3B,QAAM,UAAU,GAAG,YAAY,cAAc,EAAE,eAAe,KAAK,CAAC,EACjE,KAAK,CAAC,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC;AAC5D,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,MAAM,OAAO,KAAK,CAAC,iCAAiC,KAAK,MAAM,IAAI,EAAG;AAC3E,UAAM,WAAW,KAAK,KAAK,cAAc,MAAM,IAAI;AACnD,OAAG,WAAW,UAAU,WAAW,SAAS;AAC5C,YAAQ,KAAK,QAAQ;AAAA,EACvB;AACA,SAAO;AACT;AAEA,eAAsB,sCACpB,QACmD;AACnD,MAAI,sBAAsB;AAC1B,MAAI,wBAAkC,CAAC;AACvC,MAAI,aAA6B;AACjC,MAAI,sBAAsC;AAE1C,MAAI;AACF,4BAAwB,oBAAoB,MAAM;AAAA,EACpD,SAAS,OAAO;AACd,0BAAsB;AAAA,EACxB;AAEA,MAAI;AACF,0BAAsB,MAAM,+CAA+C,yBAAyB;AAAA,EACtG,SAAS,OAAO;AACd,iBAAa;AAAA,EACf;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { purgeConfiguredCachePatternsAcrossTenantScopes } from '@open-mercato/shared/lib/cache/maintenance'\nimport {\n CacheProviderError,\n isCacheProviderError,\n prepareCacheProviderSelection,\n readSelectedCacheProviderId,\n} from '@open-mercato/shared/lib/cache/providers'\nimport { loadCacheProviderManifest } from './cache-provider-manifest'\n\nconst STRUCTURAL_CACHE_PATTERNS = [\n 'nav:*',\n 'crud|*|*|*/admin/nav|*',\n 'crud|*|*|*/portal/nav|*',\n]\nconst TOUCHABLE_GENERATED_FILE_PATTERN = /\\.generated(?:\\.[a-z0-9]+)?(?:\\.ts|\\.checksum)$/i\n\nexport type PostGenerateStructuralInvalidationResult = {\n cacheEntriesDeleted: number\n generatedFilesTouched: string[]\n cacheError: unknown | null\n generatedFilesError: unknown | null\n}\n\nfunction touchGeneratedFiles(appDir: string): string[] {\n const generatedDir = path.join(appDir, '.mercato', 'generated')\n if (!fs.existsSync(generatedDir) || !fs.statSync(generatedDir).isDirectory()) return []\n\n const touched: string[] = []\n // `utimes` advances mtime without opening the file for writing. Rewriting the\n // identical bytes would truncate multi-megabyte registries first, and Turbopack\n // reads them concurrently during a dev compile \u2014 it can observe the empty window.\n const touchedAt = new Date()\n const entries = fs.readdirSync(generatedDir, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n for (const entry of entries) {\n if (!entry.isFile() || !TOUCHABLE_GENERATED_FILE_PATTERN.test(entry.name)) continue\n const filePath = path.join(generatedDir, entry.name)\n fs.utimesSync(filePath, touchedAt, touchedAt)\n touched.push(filePath)\n }\n return touched\n}\n\n/**\n * Purge the structural patterns through the effective cache selection. With a registered\n * provider (`CACHE_PROVIDER`) the generated manifest is loaded and the same provider the app\n * resolves is prepared first; the purge closes its maintenance client itself. Provider\n * failures are reduced to a `CacheProviderError` so driver messages (which may embed\n * endpoints or credentials) never reach the CLI diagnostics.\n */\nasync function purgeStructuralCacheEntries(appDir: string): Promise<number> {\n const providerId = readSelectedCacheProviderId(process.env)\n if (!providerId) return purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n try {\n await loadCacheProviderManifest(appDir)\n await prepareCacheProviderSelection()\n return await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n } catch (error) {\n if (isCacheProviderError(error)) throw error\n throw new CacheProviderError('unavailable', 'Cache provider structural purge failed', { cause: error })\n }\n}\n\nexport async function runPostGenerateStructuralInvalidation(\n appDir: string,\n): Promise<PostGenerateStructuralInvalidationResult> {\n let cacheEntriesDeleted = 0\n let generatedFilesTouched: string[] = []\n let cacheError: unknown | null = null\n let generatedFilesError: unknown | null = null\n\n try {\n generatedFilesTouched = touchGeneratedFiles(appDir)\n } catch (error) {\n generatedFilesError = error\n }\n\n try {\n cacheEntriesDeleted = await purgeStructuralCacheEntries(appDir)\n } catch (error) {\n cacheError = error\n }\n\n return {\n cacheEntriesDeleted,\n generatedFilesTouched,\n cacheError,\n generatedFilesError,\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,sDAAsD;AAC/D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAE1C,MAAM,4BAA4B;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mCAAmC;AASzC,SAAS,oBAAoB,QAA0B;AACrD,QAAM,eAAe,KAAK,KAAK,QAAQ,YAAY,WAAW;AAC9D,MAAI,CAAC,GAAG,WAAW,YAAY,KAAK,CAAC,GAAG,SAAS,YAAY,EAAE,YAAY,EAAG,QAAO,CAAC;AAEtF,QAAM,UAAoB,CAAC;AAI3B,QAAM,YAAY,oBAAI,KAAK;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