@open-mercato/core 0.7.0 → 0.7.1-develop.7103.1.41ff100d93

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 (847) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/helpers/integration/api.js +13 -1
  3. package/dist/helpers/integration/api.js.map +2 -2
  4. package/dist/helpers/integration/communicationChannelsFixtures.js +19 -0
  5. package/dist/helpers/integration/communicationChannelsFixtures.js.map +2 -2
  6. package/dist/modules/api_keys/api/keys/route.js +1 -1
  7. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  8. package/dist/modules/api_keys/backend/api-keys/page.js +3 -1
  9. package/dist/modules/api_keys/backend/api-keys/page.js.map +2 -2
  10. package/dist/modules/api_keys/di.js +9 -0
  11. package/dist/modules/api_keys/di.js.map +7 -0
  12. package/dist/modules/api_keys/services/principalService.js +31 -0
  13. package/dist/modules/api_keys/services/principalService.js.map +7 -0
  14. package/dist/modules/attachments/api/route.js +2 -2
  15. package/dist/modules/attachments/api/route.js.map +2 -2
  16. package/dist/modules/attachments/components/AttachmentLibrary.js +2 -0
  17. package/dist/modules/attachments/components/AttachmentLibrary.js.map +2 -2
  18. package/dist/modules/attachments/di.js +11 -1
  19. package/dist/modules/attachments/di.js.map +2 -2
  20. package/dist/modules/attachments/index.js.map +1 -1
  21. package/dist/modules/attachments/lib/attachment-service.js +313 -0
  22. package/dist/modules/attachments/lib/attachment-service.js.map +7 -0
  23. package/dist/modules/attachments/lib/scoped-upload-service.js +15 -2
  24. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  25. package/dist/modules/attachments/lib/upload-limits.js +6 -2
  26. package/dist/modules/attachments/lib/upload-limits.js.map +2 -2
  27. package/dist/modules/audit_logs/backend/audit-logs/page.js +6 -0
  28. package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
  29. package/dist/modules/audit_logs/lib/display-helpers.js +19 -11
  30. package/dist/modules/audit_logs/lib/display-helpers.js.map +2 -2
  31. package/dist/modules/audit_logs/services/actionLogService.js +57 -12
  32. package/dist/modules/audit_logs/services/actionLogService.js.map +3 -3
  33. package/dist/modules/auth/acl.js +30 -5
  34. package/dist/modules/auth/acl.js.map +2 -2
  35. package/dist/modules/auth/api/feature-check.js +8 -2
  36. package/dist/modules/auth/api/feature-check.js.map +2 -2
  37. package/dist/modules/auth/api/login.js +4 -1
  38. package/dist/modules/auth/api/login.js.map +2 -2
  39. package/dist/modules/auth/api/reset/validate.js +55 -0
  40. package/dist/modules/auth/api/reset/validate.js.map +7 -0
  41. package/dist/modules/auth/api/roles/acl/route.js +28 -33
  42. package/dist/modules/auth/api/roles/acl/route.js.map +2 -2
  43. package/dist/modules/auth/api/session/refresh.js +25 -1
  44. package/dist/modules/auth/api/session/refresh.js.map +2 -2
  45. package/dist/modules/auth/api/users/acl/route.js +96 -51
  46. package/dist/modules/auth/api/users/acl/route.js.map +2 -2
  47. package/dist/modules/auth/api/users/route.js +13 -5
  48. package/dist/modules/auth/api/users/route.js.map +2 -2
  49. package/dist/modules/auth/backend/roles/[id]/edit/page.meta.js +5 -1
  50. package/dist/modules/auth/backend/roles/[id]/edit/page.meta.js.map +2 -2
  51. package/dist/modules/auth/backend/roles/page.js +3 -1
  52. package/dist/modules/auth/backend/roles/page.js.map +2 -2
  53. package/dist/modules/auth/backend/users/[id]/edit/page.meta.js +5 -1
  54. package/dist/modules/auth/backend/users/[id]/edit/page.meta.js.map +2 -2
  55. package/dist/modules/auth/backend/users/page.js +2 -1
  56. package/dist/modules/auth/backend/users/page.js.map +2 -2
  57. package/dist/modules/auth/commands/acl.js +254 -0
  58. package/dist/modules/auth/commands/acl.js.map +7 -0
  59. package/dist/modules/auth/components/AclEditor.js +39 -30
  60. package/dist/modules/auth/components/AclEditor.js.map +2 -2
  61. package/dist/modules/auth/data/entities.js.map +2 -2
  62. package/dist/modules/auth/data/validators.js +5 -1
  63. package/dist/modules/auth/data/validators.js.map +2 -2
  64. package/dist/modules/auth/di.js +35 -9
  65. package/dist/modules/auth/di.js.map +2 -2
  66. package/dist/modules/auth/frontend/reset/[token]/page.js +46 -0
  67. package/dist/modules/auth/frontend/reset/[token]/page.js.map +2 -2
  68. package/dist/modules/auth/lib/grantChecks.js.map +2 -2
  69. package/dist/modules/auth/lib/userIdFilter.js +16 -0
  70. package/dist/modules/auth/lib/userIdFilter.js.map +7 -0
  71. package/dist/modules/auth/services/authService.js +16 -2
  72. package/dist/modules/auth/services/authService.js.map +2 -2
  73. package/dist/modules/auth/services/principalService.js +200 -0
  74. package/dist/modules/auth/services/principalService.js.map +7 -0
  75. package/dist/modules/auth/services/rbacService.js +67 -24
  76. package/dist/modules/auth/services/rbacService.js.map +3 -3
  77. package/dist/modules/auth/services/roleOrganizationScope.js +41 -0
  78. package/dist/modules/auth/services/roleOrganizationScope.js.map +7 -0
  79. package/dist/modules/business_rules/backend/logs/page.js +3 -1
  80. package/dist/modules/business_rules/backend/logs/page.js.map +2 -2
  81. package/dist/modules/business_rules/backend/rules/page.js +3 -1
  82. package/dist/modules/business_rules/backend/rules/page.js.map +2 -2
  83. package/dist/modules/business_rules/backend/sets/page.js +3 -1
  84. package/dist/modules/business_rules/backend/sets/page.js.map +2 -2
  85. package/dist/modules/business_rules/lib/expression-evaluator.js +9 -9
  86. package/dist/modules/business_rules/lib/expression-evaluator.js.map +2 -2
  87. package/dist/modules/business_rules/lib/rule-evaluator.js +10 -9
  88. package/dist/modules/business_rules/lib/rule-evaluator.js.map +2 -2
  89. package/dist/modules/catalog/ai-agents.js +1 -1
  90. package/dist/modules/catalog/ai-agents.js.map +1 -1
  91. package/dist/modules/catalog/ai-tools/merchandising-pack.js +2 -2
  92. package/dist/modules/catalog/ai-tools/merchandising-pack.js.map +2 -2
  93. package/dist/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.js +5 -2
  94. package/dist/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.js.map +2 -2
  95. package/dist/modules/catalog/components/categories/CategoriesDataTable.js +2 -0
  96. package/dist/modules/catalog/components/categories/CategoriesDataTable.js.map +2 -2
  97. package/dist/modules/catalog/components/products/ProductsDataTable.js +7 -1
  98. package/dist/modules/catalog/components/products/ProductsDataTable.js.map +2 -2
  99. package/dist/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.js +2 -0
  100. package/dist/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.js.map +2 -2
  101. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js +9 -1
  102. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js.map +2 -2
  103. package/dist/modules/communication_channels/api/post/test-seed/route.js +95 -10
  104. package/dist/modules/communication_channels/api/post/test-seed/route.js.map +2 -2
  105. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js +3 -0
  106. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js.map +2 -2
  107. package/dist/modules/communication_channels/commands/ingest-inbound-message.js +14 -1
  108. package/dist/modules/communication_channels/commands/ingest-inbound-message.js.map +2 -2
  109. package/dist/modules/communication_channels/di.js +7 -1
  110. package/dist/modules/communication_channels/di.js.map +2 -2
  111. package/dist/modules/communication_channels/lib/email-capabilities.js +4 -1
  112. package/dist/modules/communication_channels/lib/email-capabilities.js.map +2 -2
  113. package/dist/modules/communication_channels/lib/outbound-recipient.js +33 -0
  114. package/dist/modules/communication_channels/lib/outbound-recipient.js.map +7 -0
  115. package/dist/modules/communication_channels/lib/resolve-channel-type.js +51 -0
  116. package/dist/modules/communication_channels/lib/resolve-channel-type.js.map +7 -0
  117. package/dist/modules/communication_channels/lib/test-seed.js +41 -2
  118. package/dist/modules/communication_channels/lib/test-seed.js.map +2 -2
  119. package/dist/modules/configs/lib/system-status.js +9 -0
  120. package/dist/modules/configs/lib/system-status.js.map +2 -2
  121. package/dist/modules/currencies/backend/currencies/page.js +3 -1
  122. package/dist/modules/currencies/backend/currencies/page.js.map +2 -2
  123. package/dist/modules/currencies/backend/exchange-rates/page.js +3 -1
  124. package/dist/modules/currencies/backend/exchange-rates/page.js.map +2 -2
  125. package/dist/modules/currencies/services/rateFetchingService.js +6 -1
  126. package/dist/modules/currencies/services/rateFetchingService.js.map +2 -2
  127. package/dist/modules/customer_accounts/api/admin/domain-mappings.js +9 -0
  128. package/dist/modules/customer_accounts/api/admin/domain-mappings.js.map +2 -2
  129. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js +3 -1
  130. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js.map +2 -2
  131. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js +3 -1
  132. package/dist/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.js.map +2 -2
  133. package/dist/modules/customer_accounts/services/domainMappingService.js +10 -0
  134. package/dist/modules/customer_accounts/services/domainMappingService.js.map +2 -2
  135. package/dist/modules/customers/ai-tools/companies-pack.js +4 -1
  136. package/dist/modules/customers/ai-tools/companies-pack.js.map +2 -2
  137. package/dist/modules/customers/ai-tools/deal-analyzer-pack.js +13 -2
  138. package/dist/modules/customers/ai-tools/deal-analyzer-pack.js.map +2 -2
  139. package/dist/modules/customers/ai-tools/deals-pack.js +52 -6
  140. package/dist/modules/customers/ai-tools/deals-pack.js.map +2 -2
  141. package/dist/modules/customers/ai-tools/people-pack.js +4 -1
  142. package/dist/modules/customers/ai-tools/people-pack.js.map +2 -2
  143. package/dist/modules/customers/api/activities/route.js +48 -6
  144. package/dist/modules/customers/api/activities/route.js.map +2 -2
  145. package/dist/modules/customers/api/companies/[id]/people/route.js +20 -64
  146. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  147. package/dist/modules/customers/api/companies/[id]/route.js +17 -94
  148. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  149. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js +8 -5
  150. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js.map +2 -2
  151. package/dist/modules/customers/api/deals/[id]/companies/route.js +1 -1
  152. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  153. package/dist/modules/customers/api/deals/[id]/people/route.js +1 -1
  154. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  155. package/dist/modules/customers/api/deals/[id]/route.js +8 -25
  156. package/dist/modules/customers/api/deals/[id]/route.js.map +2 -2
  157. package/dist/modules/customers/api/deals/[id]/stats/route.js +3 -22
  158. package/dist/modules/customers/api/deals/[id]/stats/route.js.map +2 -2
  159. package/dist/modules/customers/api/deals/aggregate/route.js +14 -9
  160. package/dist/modules/customers/api/deals/aggregate/route.js.map +2 -2
  161. package/dist/modules/customers/api/deals/map/route.js +5 -5
  162. package/dist/modules/customers/api/deals/map/route.js.map +2 -2
  163. package/dist/modules/customers/api/deals/route.js +38 -1
  164. package/dist/modules/customers/api/deals/route.js.map +2 -2
  165. package/dist/modules/customers/api/entity-roles-factory.js +4 -4
  166. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  167. package/dist/modules/customers/api/interactions/route.js +3 -1
  168. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  169. package/dist/modules/customers/api/interactions/tasks/route.js +27 -4
  170. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  171. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +4 -3
  172. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  173. package/dist/modules/customers/api/people/[id]/companies/context.js +1 -1
  174. package/dist/modules/customers/api/people/[id]/companies/context.js.map +2 -2
  175. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +1 -1
  176. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  177. package/dist/modules/customers/api/people/[id]/route.js +11 -10
  178. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  179. package/dist/modules/customers/api/people/check-phone/route.js +51 -9
  180. package/dist/modules/customers/api/people/check-phone/route.js.map +2 -2
  181. package/dist/modules/customers/api/todos/route.js +30 -5
  182. package/dist/modules/customers/api/todos/route.js.map +2 -2
  183. package/dist/modules/customers/backend/customers/companies/page.js +4 -2
  184. package/dist/modules/customers/backend/customers/companies/page.js.map +2 -2
  185. package/dist/modules/customers/backend/customers/deals/[id]/page.js +6 -1
  186. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
  187. package/dist/modules/customers/backend/customers/deals/page.js +5 -2
  188. package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
  189. package/dist/modules/customers/backend/customers/deals/pipeline/components/Lane.js +4 -13
  190. package/dist/modules/customers/backend/customers/deals/pipeline/components/Lane.js.map +2 -2
  191. package/dist/modules/customers/backend/customers/deals/pipeline/components/StatusFilterPopover.js +85 -14
  192. package/dist/modules/customers/backend/customers/deals/pipeline/components/StatusFilterPopover.js.map +2 -2
  193. package/dist/modules/customers/backend/customers/deals/pipeline/components/toneClasses.js +18 -0
  194. package/dist/modules/customers/backend/customers/deals/pipeline/components/toneClasses.js.map +7 -0
  195. package/dist/modules/customers/backend/customers/people/page.js +4 -2
  196. package/dist/modules/customers/backend/customers/people/page.js.map +2 -2
  197. package/dist/modules/customers/backend/hooks/useEmailDuplicateCheck.js +9 -3
  198. package/dist/modules/customers/backend/hooks/useEmailDuplicateCheck.js.map +2 -2
  199. package/dist/modules/customers/commands/deals.js +21 -34
  200. package/dist/modules/customers/commands/deals.js.map +2 -2
  201. package/dist/modules/customers/commands/interactions.js.map +1 -1
  202. package/dist/modules/customers/commands/personCompanyLinks.js +131 -2
  203. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  204. package/dist/modules/customers/components/CustomerTodosTable.js +1 -0
  205. package/dist/modules/customers/components/CustomerTodosTable.js.map +2 -2
  206. package/dist/modules/customers/components/DealsKpiStrip.js +7 -6
  207. package/dist/modules/customers/components/DealsKpiStrip.js.map +2 -2
  208. package/dist/modules/customers/components/calendar/AgendaList.js +2 -2
  209. package/dist/modules/customers/components/calendar/AgendaList.js.map +2 -2
  210. package/dist/modules/customers/components/calendar/CalendarEventEditor.js +1 -1
  211. package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +2 -2
  212. package/dist/modules/customers/components/calendar/CalendarScreen.js +1 -1
  213. package/dist/modules/customers/components/calendar/CalendarScreen.js.map +2 -2
  214. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js +1 -1
  215. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js.map +2 -2
  216. package/dist/modules/customers/components/calendar/EventBlock.js +1 -1
  217. package/dist/modules/customers/components/calendar/EventBlock.js.map +2 -2
  218. package/dist/modules/customers/components/calendar/EventPeekPopover.js +3 -2
  219. package/dist/modules/customers/components/calendar/EventPeekPopover.js.map +2 -2
  220. package/dist/modules/customers/components/calendar/editor/PeopleField.js +40 -5
  221. package/dist/modules/customers/components/calendar/editor/PeopleField.js.map +2 -2
  222. package/dist/modules/customers/components/calendar/editor/hooks.js +2 -1
  223. package/dist/modules/customers/components/calendar/editor/hooks.js.map +2 -2
  224. package/dist/modules/customers/components/calendar/types.js +1 -1
  225. package/dist/modules/customers/components/calendar/types.js.map +2 -2
  226. package/dist/modules/customers/components/detail/CompanyKpiBar.js +5 -4
  227. package/dist/modules/customers/components/detail/CompanyKpiBar.js.map +2 -2
  228. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +3 -1
  229. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  230. package/dist/modules/customers/components/detail/DealForm.js +19 -7
  231. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  232. package/dist/modules/customers/components/detail/DealsSection.js +6 -5
  233. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  234. package/dist/modules/customers/components/detail/EntityTagsDialog.js +35 -11
  235. package/dist/modules/customers/components/detail/EntityTagsDialog.js.map +2 -2
  236. package/dist/modules/customers/components/detail/PersonCompaniesSection.js +3 -1
  237. package/dist/modules/customers/components/detail/PersonCompaniesSection.js.map +2 -2
  238. package/dist/modules/customers/components/detail/hooks/usePersonTasks.js +19 -13
  239. package/dist/modules/customers/components/detail/hooks/usePersonTasks.js.map +2 -2
  240. package/dist/modules/customers/components/detail/schedule/ParticipantsField.js +4 -4
  241. package/dist/modules/customers/components/detail/schedule/ParticipantsField.js.map +2 -2
  242. package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js +3 -3
  243. package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js.map +2 -2
  244. package/dist/modules/customers/components/detail/utils.js +5 -5
  245. package/dist/modules/customers/components/detail/utils.js.map +2 -2
  246. package/dist/modules/customers/data/entities.js.map +1 -1
  247. package/dist/modules/customers/data/validators.js +32 -3
  248. package/dist/modules/customers/data/validators.js.map +2 -2
  249. package/dist/modules/customers/events.js +5 -0
  250. package/dist/modules/customers/events.js.map +2 -2
  251. package/dist/modules/customers/lib/calendar/conflicts.js +8 -2
  252. package/dist/modules/customers/lib/calendar/conflicts.js.map +2 -2
  253. package/dist/modules/customers/lib/calendar/editorPayload.js +3 -2
  254. package/dist/modules/customers/lib/calendar/editorPayload.js.map +2 -2
  255. package/dist/modules/customers/lib/calendar/mapItem.js +8 -3
  256. package/dist/modules/customers/lib/calendar/mapItem.js.map +2 -2
  257. package/dist/modules/customers/lib/calendar/participantIdentity.js +9 -0
  258. package/dist/modules/customers/lib/calendar/participantIdentity.js.map +7 -0
  259. package/dist/modules/customers/lib/closureStage.js +45 -0
  260. package/dist/modules/customers/lib/closureStage.js.map +7 -0
  261. package/dist/modules/customers/lib/dealStatus.js +30 -0
  262. package/dist/modules/customers/lib/dealStatus.js.map +2 -2
  263. package/dist/modules/customers/lib/detailReadAccess.js +12 -0
  264. package/dist/modules/customers/lib/detailReadAccess.js.map +7 -0
  265. package/dist/modules/customers/lib/findPeopleByAddresses.js +1 -0
  266. package/dist/modules/customers/lib/findPeopleByAddresses.js.map +2 -2
  267. package/dist/modules/customers/lib/personCompanies.js +100 -2
  268. package/dist/modules/customers/lib/personCompanies.js.map +2 -2
  269. package/dist/modules/customers/lib/todoCompatibility.js +12 -0
  270. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  271. package/dist/modules/dashboards/lib/widgetScope.js +6 -1
  272. package/dist/modules/dashboards/lib/widgetScope.js.map +2 -2
  273. package/dist/modules/data_sync/backend/data-sync/page.js +3 -1
  274. package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
  275. package/dist/modules/data_sync/lib/abandoned-run.js +19 -0
  276. package/dist/modules/data_sync/lib/abandoned-run.js.map +7 -0
  277. package/dist/modules/data_sync/lib/sync-engine.js +72 -6
  278. package/dist/modules/data_sync/lib/sync-engine.js.map +2 -2
  279. package/dist/modules/data_sync/workers/sync-export.js +5 -1
  280. package/dist/modules/data_sync/workers/sync-export.js.map +2 -2
  281. package/dist/modules/data_sync/workers/sync-import.js +5 -1
  282. package/dist/modules/data_sync/workers/sync-import.js.map +2 -2
  283. package/dist/modules/devices/acl.js +9 -1
  284. package/dist/modules/devices/acl.js.map +2 -2
  285. package/dist/modules/devices/api/admin/devices/[id]/route.js +5 -32
  286. package/dist/modules/devices/api/admin/devices/[id]/route.js.map +2 -2
  287. package/dist/modules/devices/api/admin/devices/route.js +14 -1
  288. package/dist/modules/devices/api/admin/devices/route.js.map +2 -2
  289. package/dist/modules/devices/api/deviceList.js +99 -12
  290. package/dist/modules/devices/api/deviceList.js.map +2 -2
  291. package/dist/modules/devices/api/deviceSerialization.js +46 -0
  292. package/dist/modules/devices/api/deviceSerialization.js.map +7 -0
  293. package/dist/modules/devices/api/openapi.js +3 -1
  294. package/dist/modules/devices/api/openapi.js.map +2 -2
  295. package/dist/modules/devices/api/route.js +9 -1
  296. package/dist/modules/devices/api/route.js.map +2 -2
  297. package/dist/modules/devices/backend/devices/[id]/page.js +10 -26
  298. package/dist/modules/devices/backend/devices/[id]/page.js.map +2 -2
  299. package/dist/modules/devices/backend/devices/create/page.js +17 -1
  300. package/dist/modules/devices/backend/devices/create/page.js.map +2 -2
  301. package/dist/modules/devices/backend/devices/page.js +28 -34
  302. package/dist/modules/devices/backend/devices/page.js.map +2 -2
  303. package/dist/modules/devices/backend/devices/useDeviceUserLabels.js +34 -0
  304. package/dist/modules/devices/backend/devices/useDeviceUserLabels.js.map +7 -0
  305. package/dist/modules/devices/backend/devices/userOptions.js +52 -0
  306. package/dist/modules/devices/backend/devices/userOptions.js.map +7 -0
  307. package/dist/modules/devices/setup.js +6 -2
  308. package/dist/modules/devices/setup.js.map +2 -2
  309. package/dist/modules/directory/backend/directory/organizations/page.js +2 -1
  310. package/dist/modules/directory/backend/directory/organizations/page.js.map +2 -2
  311. package/dist/modules/directory/backend/directory/tenants/page.js +2 -1
  312. package/dist/modules/directory/backend/directory/tenants/page.js.map +2 -2
  313. package/dist/modules/directory/di.js +9 -0
  314. package/dist/modules/directory/di.js.map +2 -2
  315. package/dist/modules/directory/services/organizationHierarchyService.js +29 -0
  316. package/dist/modules/directory/services/organizationHierarchyService.js.map +7 -0
  317. package/dist/modules/directory/services/organizationScopeService.js +56 -0
  318. package/dist/modules/directory/services/organizationScopeService.js.map +7 -0
  319. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  320. package/dist/modules/entities/api/records.js +4 -2
  321. package/dist/modules/entities/api/records.js.map +2 -2
  322. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +3 -1
  323. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
  324. package/dist/modules/eudr/api/plots/route.js +5 -1
  325. package/dist/modules/eudr/api/plots/route.js.map +2 -2
  326. package/dist/modules/eudr/backend/eudr/evidence-submissions/page.js +3 -0
  327. package/dist/modules/eudr/backend/eudr/evidence-submissions/page.js.map +2 -2
  328. package/dist/modules/eudr/backend/eudr/plots/page.js +3 -0
  329. package/dist/modules/eudr/backend/eudr/plots/page.js.map +2 -2
  330. package/dist/modules/eudr/backend/eudr/product-mappings/page.js +3 -0
  331. package/dist/modules/eudr/backend/eudr/product-mappings/page.js.map +2 -2
  332. package/dist/modules/eudr/backend/eudr/risk-assessments/page.js +3 -0
  333. package/dist/modules/eudr/backend/eudr/risk-assessments/page.js.map +2 -2
  334. package/dist/modules/eudr/backend/eudr/statements/page.js +3 -0
  335. package/dist/modules/eudr/backend/eudr/statements/page.js.map +2 -2
  336. package/dist/modules/eudr/commands/statements.js +0 -3
  337. package/dist/modules/eudr/commands/statements.js.map +2 -2
  338. package/dist/modules/eudr/data/validators.js +4 -1
  339. package/dist/modules/eudr/data/validators.js.map +2 -2
  340. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js +1 -0
  341. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js.map +2 -2
  342. package/dist/modules/feature_toggles/components/OverridesTable.js +1 -0
  343. package/dist/modules/feature_toggles/components/OverridesTable.js.map +2 -2
  344. package/dist/modules/feature_toggles/defaults.json +0 -8
  345. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js +3 -0
  346. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js.map +2 -2
  347. package/dist/modules/inbox_ops/backend/inbox-ops/page.js +3 -0
  348. package/dist/modules/inbox_ops/backend/inbox-ops/page.js.map +2 -2
  349. package/dist/modules/inbox_ops/lib/htmlToPlainText.js +1 -12
  350. package/dist/modules/inbox_ops/lib/htmlToPlainText.js.map +2 -2
  351. package/dist/modules/integrations/api/[id]/credentials/route.js +6 -1
  352. package/dist/modules/integrations/api/[id]/credentials/route.js.map +2 -2
  353. package/dist/modules/integrations/backend/integrations/[id]/page.js +38 -29
  354. package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
  355. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js +36 -9
  356. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js.map +2 -2
  357. package/dist/modules/integrations/backend/integrations/credential-secret-fields.js +55 -0
  358. package/dist/modules/integrations/backend/integrations/credential-secret-fields.js.map +7 -0
  359. package/dist/modules/integrations/data/validators.js +11 -3
  360. package/dist/modules/integrations/data/validators.js.map +2 -2
  361. package/dist/modules/integrations/lib/credentials-masking.js +6 -2
  362. package/dist/modules/integrations/lib/credentials-masking.js.map +2 -2
  363. package/dist/modules/messages/api/[id]/route.js +29 -1
  364. package/dist/modules/messages/api/[id]/route.js.map +2 -2
  365. package/dist/modules/messages/api/openapi.js +17 -2
  366. package/dist/modules/messages/api/openapi.js.map +2 -2
  367. package/dist/modules/messages/api/route.js +17 -2
  368. package/dist/modules/messages/api/route.js.map +2 -2
  369. package/dist/modules/messages/components/MessagesInboxPageClient.js +7 -14
  370. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  371. package/dist/modules/messages/components/inboxFilters.js +15 -0
  372. package/dist/modules/messages/components/inboxFilters.js.map +2 -2
  373. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.js +11 -1
  374. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.js.map +2 -2
  375. package/dist/modules/messages/components/message-detail/panels/MessageHeader.js +3 -1
  376. package/dist/modules/messages/components/message-detail/panels/MessageHeader.js.map +2 -2
  377. package/dist/modules/messages/components/message-detail/panels/thread-panel.js +2 -1
  378. package/dist/modules/messages/components/message-detail/panels/thread-panel.js.map +2 -2
  379. package/dist/modules/messages/components/messageListLabels.js +14 -2
  380. package/dist/modules/messages/components/messageListLabels.js.map +2 -2
  381. package/dist/modules/messages/data/validators.js +18 -4
  382. package/dist/modules/messages/data/validators.js.map +2 -2
  383. package/dist/modules/messages/lib/channel-sender-identity.js +26 -0
  384. package/dist/modules/messages/lib/channel-sender-identity.js.map +7 -0
  385. package/dist/modules/messages/lib/composeSourceChannelType.js +41 -0
  386. package/dist/modules/messages/lib/composeSourceChannelType.js.map +7 -0
  387. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +4 -6
  388. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
  389. package/dist/modules/payment_gateways/backend/payment-gateways/page.js +3 -1
  390. package/dist/modules/payment_gateways/backend/payment-gateways/page.js.map +2 -2
  391. package/dist/modules/payment_gateways/lib/webhook-processor.js +7 -0
  392. package/dist/modules/payment_gateways/lib/webhook-processor.js.map +2 -2
  393. package/dist/modules/planner/backend/planner/availability-rulesets/page.js +3 -0
  394. package/dist/modules/planner/backend/planner/availability-rulesets/page.js.map +2 -2
  395. package/dist/modules/push_notifications/backend/push_notifications/page.js +3 -1
  396. package/dist/modules/push_notifications/backend/push_notifications/page.js.map +2 -2
  397. package/dist/modules/push_notifications/backend/push_notifications/send/page.js +1 -1
  398. package/dist/modules/push_notifications/backend/push_notifications/send/page.js.map +2 -2
  399. package/dist/modules/query_index/lib/engine.js +150 -51
  400. package/dist/modules/query_index/lib/engine.js.map +2 -2
  401. package/dist/modules/query_index/lib/search-entity-policy.js +14 -0
  402. package/dist/modules/query_index/lib/search-entity-policy.js.map +7 -0
  403. package/dist/modules/query_index/lib/search-tokens.js +79 -3
  404. package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
  405. package/dist/modules/resources/backend/resources/resource-types/page.js +3 -1
  406. package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
  407. package/dist/modules/resources/backend/resources/resources/page.js +3 -1
  408. package/dist/modules/resources/backend/resources/resources/page.js.map +2 -2
  409. package/dist/modules/sales/backend/sales/channels/offers/page.js +3 -0
  410. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  411. package/dist/modules/sales/backend/sales/channels/page.js +3 -0
  412. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  413. package/dist/modules/sales/backend/sales/documents/[id]/page.js +10 -8
  414. package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
  415. package/dist/modules/sales/commands/documents.js +79 -1
  416. package/dist/modules/sales/commands/documents.js.map +2 -2
  417. package/dist/modules/sales/components/PriceWithCurrency.js +7 -5
  418. package/dist/modules/sales/components/PriceWithCurrency.js.map +2 -2
  419. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js +3 -0
  420. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js.map +2 -2
  421. package/dist/modules/sales/components/documents/AdjustmentsSection.js +8 -6
  422. package/dist/modules/sales/components/documents/AdjustmentsSection.js.map +2 -2
  423. package/dist/modules/sales/components/documents/ItemsSection.js +51 -22
  424. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  425. package/dist/modules/sales/components/documents/LineItemDialog.js +83 -18
  426. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  427. package/dist/modules/sales/components/documents/PaymentsSection.js +23 -9
  428. package/dist/modules/sales/components/documents/PaymentsSection.js.map +2 -2
  429. package/dist/modules/sales/components/documents/ReturnsSection.js +8 -6
  430. package/dist/modules/sales/components/documents/ReturnsSection.js.map +2 -2
  431. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +68 -14
  432. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  433. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js +6 -5
  434. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js.map +2 -2
  435. package/dist/modules/sales/components/documents/ShipmentDialog.js +5 -4
  436. package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
  437. package/dist/modules/sales/components/documents/ShipmentsSection.js +8 -6
  438. package/dist/modules/sales/components/documents/ShipmentsSection.js.map +2 -2
  439. package/dist/modules/sales/components/documents/lineItemShipmentLock.js +54 -0
  440. package/dist/modules/sales/components/documents/lineItemShipmentLock.js.map +7 -0
  441. package/dist/modules/sales/components/documents/lineItemUtils.js +2 -2
  442. package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
  443. package/dist/modules/sales/data/entities.js +8 -2
  444. package/dist/modules/sales/data/entities.js.map +2 -2
  445. package/dist/modules/sales/extension-points.js +1 -0
  446. package/dist/modules/sales/extension-points.js.map +2 -2
  447. package/dist/modules/sales/lib/salesChannelsToggleSeed.js +33 -0
  448. package/dist/modules/sales/lib/salesChannelsToggleSeed.js.map +7 -0
  449. package/dist/modules/sales/migrations/Migration20260821120000_sales_notes_addresses_context_idx.js +32 -0
  450. package/dist/modules/sales/migrations/Migration20260821120000_sales_notes_addresses_context_idx.js.map +7 -0
  451. package/dist/modules/sales/setup.js +2 -0
  452. package/dist/modules/sales/setup.js.map +2 -2
  453. package/dist/modules/sales/widgets/injection/payment-gateway-status-column/widget.js +10 -2
  454. package/dist/modules/sales/widgets/injection/payment-gateway-status-column/widget.js.map +2 -2
  455. package/dist/modules/sales/widgets/injection-table.js +4 -7
  456. package/dist/modules/sales/widgets/injection-table.js.map +2 -2
  457. package/dist/modules/staff/backend/staff/leave-requests/page.js +3 -0
  458. package/dist/modules/staff/backend/staff/leave-requests/page.js.map +2 -2
  459. package/dist/modules/staff/backend/staff/my-leave-requests/page.js +3 -0
  460. package/dist/modules/staff/backend/staff/my-leave-requests/page.js.map +2 -2
  461. package/dist/modules/staff/backend/staff/team-members/page.js +3 -0
  462. package/dist/modules/staff/backend/staff/team-members/page.js.map +2 -2
  463. package/dist/modules/staff/backend/staff/team-roles/page.js +3 -0
  464. package/dist/modules/staff/backend/staff/team-roles/page.js.map +2 -2
  465. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +3 -0
  466. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
  467. package/dist/modules/staff/backend/staff/teams/page.js +3 -0
  468. package/dist/modules/staff/backend/staff/teams/page.js.map +2 -2
  469. package/dist/modules/staff/backend/staff/timesheets/page.js +29 -18
  470. package/dist/modules/staff/backend/staff/timesheets/page.js.map +2 -2
  471. package/dist/modules/staff/backend/staff/timesheets/projects/page.js +3 -0
  472. package/dist/modules/staff/backend/staff/timesheets/projects/page.js.map +2 -2
  473. package/dist/modules/sync_excel/lib/adapters/customers.js +1 -0
  474. package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
  475. package/dist/modules/warranty_claims/api/assignees/route.js +3 -3
  476. package/dist/modules/warranty_claims/api/assignees/route.js.map +2 -2
  477. package/dist/modules/warranty_claims/api/portal/attachments/route.js +2 -2
  478. package/dist/modules/warranty_claims/api/portal/attachments/route.js.map +2 -2
  479. package/dist/modules/warranty_claims/api/portal/claims/route.js +12 -9
  480. package/dist/modules/warranty_claims/api/portal/claims/route.js.map +2 -2
  481. package/dist/modules/warranty_claims/backend/page.js +3 -0
  482. package/dist/modules/warranty_claims/backend/page.js.map +2 -2
  483. package/dist/modules/warranty_claims/backend/warranty_claims/registrations/page.js +3 -0
  484. package/dist/modules/warranty_claims/backend/warranty_claims/registrations/page.js.map +2 -2
  485. package/dist/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.js +3 -0
  486. package/dist/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.js.map +2 -2
  487. package/dist/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.js +3 -0
  488. package/dist/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.js.map +2 -2
  489. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.js +3 -0
  490. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.js.map +2 -2
  491. package/dist/modules/wms/api/warehouseSearch.js +21 -0
  492. package/dist/modules/wms/api/warehouseSearch.js.map +7 -0
  493. package/dist/modules/wms/api/warehouses/route.js +13 -9
  494. package/dist/modules/wms/api/warehouses/route.js.map +2 -2
  495. package/dist/modules/wms/api/zones/route.js +15 -2
  496. package/dist/modules/wms/api/zones/route.js.map +2 -2
  497. package/dist/modules/wms/commands/configuration.js +121 -9
  498. package/dist/modules/wms/commands/configuration.js.map +2 -2
  499. package/dist/modules/wms/commands/inventory-actions.js +3 -0
  500. package/dist/modules/wms/commands/inventory-actions.js.map +2 -2
  501. package/dist/modules/wms/commands/shared.js +9 -1
  502. package/dist/modules/wms/commands/shared.js.map +2 -2
  503. package/dist/modules/wms/components/backend/WarehouseEditDialog.js +158 -0
  504. package/dist/modules/wms/components/backend/WarehouseEditDialog.js.map +7 -0
  505. package/dist/modules/wms/components/backend/WmsConfigurationPage.js +76 -111
  506. package/dist/modules/wms/components/backend/WmsConfigurationPage.js.map +3 -3
  507. package/dist/modules/wms/components/backend/WmsInventoryConsolePage.js +1 -0
  508. package/dist/modules/wms/components/backend/WmsInventoryConsolePage.js.map +2 -2
  509. package/dist/modules/wms/components/backend/WmsLotsListPage.js +1 -0
  510. package/dist/modules/wms/components/backend/WmsLotsListPage.js.map +2 -2
  511. package/dist/modules/wms/components/backend/inventoryMutationLoaders.js +27 -20
  512. package/dist/modules/wms/components/backend/inventoryMutationLoaders.js.map +2 -2
  513. package/dist/modules/wms/components/backend/warehouseFormOptions.js +66 -0
  514. package/dist/modules/wms/components/backend/warehouseFormOptions.js.map +7 -0
  515. package/dist/modules/workflows/backend/definitions/page.js +3 -1
  516. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  517. package/dist/modules/workflows/backend/events/page.js +3 -1
  518. package/dist/modules/workflows/backend/events/page.js.map +2 -2
  519. package/dist/modules/workflows/backend/instances/page.js +3 -1
  520. package/dist/modules/workflows/backend/instances/page.js.map +2 -2
  521. package/dist/modules/workflows/backend/tasks/page.js +3 -1
  522. package/dist/modules/workflows/backend/tasks/page.js.map +2 -2
  523. package/dist/modules/workflows/lib/activity-executor.js +4 -0
  524. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  525. package/package.json +9 -10
  526. package/src/helpers/integration/api.ts +33 -1
  527. package/src/helpers/integration/communicationChannelsFixtures.ts +69 -1
  528. package/src/modules/api_keys/api/keys/route.ts +3 -1
  529. package/src/modules/api_keys/backend/api-keys/page.tsx +4 -1
  530. package/src/modules/api_keys/di.ts +7 -0
  531. package/src/modules/api_keys/services/principalService.ts +33 -0
  532. package/src/modules/attachments/AGENTS.md +15 -0
  533. package/src/modules/attachments/api/route.ts +2 -2
  534. package/src/modules/attachments/components/AttachmentLibrary.tsx +3 -0
  535. package/src/modules/attachments/di.ts +16 -0
  536. package/src/modules/attachments/i18n/de.json +5 -0
  537. package/src/modules/attachments/i18n/en.json +5 -0
  538. package/src/modules/attachments/i18n/es.json +5 -0
  539. package/src/modules/attachments/i18n/ko.json +5 -0
  540. package/src/modules/attachments/i18n/pl.json +5 -0
  541. package/src/modules/attachments/index.ts +10 -0
  542. package/src/modules/attachments/lib/attachment-service.ts +468 -0
  543. package/src/modules/attachments/lib/scoped-upload-service.ts +46 -0
  544. package/src/modules/attachments/lib/upload-limits.ts +6 -2
  545. package/src/modules/audit_logs/backend/audit-logs/page.tsx +8 -0
  546. package/src/modules/audit_logs/lib/display-helpers.tsx +42 -32
  547. package/src/modules/audit_logs/services/actionLogService.ts +74 -11
  548. package/src/modules/auth/acl.ts +30 -6
  549. package/src/modules/auth/api/feature-check.ts +10 -3
  550. package/src/modules/auth/api/login.ts +9 -1
  551. package/src/modules/auth/api/reset/validate.ts +57 -0
  552. package/src/modules/auth/api/roles/acl/route.ts +42 -39
  553. package/src/modules/auth/api/session/refresh.ts +32 -1
  554. package/src/modules/auth/api/users/acl/route.ts +177 -53
  555. package/src/modules/auth/api/users/route.ts +18 -5
  556. package/src/modules/auth/backend/roles/[id]/edit/page.meta.ts +5 -2
  557. package/src/modules/auth/backend/roles/page.tsx +4 -2
  558. package/src/modules/auth/backend/users/[id]/edit/page.meta.ts +5 -2
  559. package/src/modules/auth/backend/users/page.tsx +3 -2
  560. package/src/modules/auth/commands/acl.ts +495 -0
  561. package/src/modules/auth/components/AclEditor.tsx +63 -33
  562. package/src/modules/auth/data/entities.ts +4 -1
  563. package/src/modules/auth/data/validators.ts +5 -0
  564. package/src/modules/auth/di.ts +46 -16
  565. package/src/modules/auth/frontend/reset/[token]/page.tsx +74 -0
  566. package/src/modules/auth/i18n/de.json +389 -0
  567. package/src/modules/auth/i18n/en.json +389 -0
  568. package/src/modules/auth/i18n/es.json +389 -0
  569. package/src/modules/auth/i18n/ko.json +389 -0
  570. package/src/modules/auth/i18n/pl.json +391 -2
  571. package/src/modules/auth/lib/grantChecks.ts +6 -0
  572. package/src/modules/auth/lib/userIdFilter.ts +31 -0
  573. package/src/modules/auth/services/authService.ts +18 -2
  574. package/src/modules/auth/services/principalService.ts +266 -0
  575. package/src/modules/auth/services/rbacService.ts +110 -24
  576. package/src/modules/auth/services/roleOrganizationScope.ts +70 -0
  577. package/src/modules/business_rules/backend/logs/page.tsx +4 -1
  578. package/src/modules/business_rules/backend/rules/page.tsx +4 -1
  579. package/src/modules/business_rules/backend/sets/page.tsx +4 -1
  580. package/src/modules/business_rules/lib/expression-evaluator.ts +9 -9
  581. package/src/modules/business_rules/lib/rule-evaluator.ts +10 -9
  582. package/src/modules/catalog/ai-agents.ts +1 -1
  583. package/src/modules/catalog/ai-tools/merchandising-pack.ts +2 -2
  584. package/src/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.tsx +12 -5
  585. package/src/modules/catalog/components/categories/CategoriesDataTable.tsx +3 -0
  586. package/src/modules/catalog/components/products/ProductsDataTable.tsx +7 -0
  587. package/src/modules/catalog/i18n/de.json +1 -0
  588. package/src/modules/catalog/i18n/en.json +1 -0
  589. package/src/modules/catalog/i18n/es.json +1 -0
  590. package/src/modules/catalog/i18n/ko.json +1 -0
  591. package/src/modules/catalog/i18n/pl.json +1 -0
  592. package/src/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.tsx +4 -0
  593. package/src/modules/communication_channels/api/post/channels/[id]/test-send/route.ts +17 -1
  594. package/src/modules/communication_channels/api/post/test-seed/route.ts +155 -16
  595. package/src/modules/communication_channels/backend/communication_channels/channels/page.tsx +4 -0
  596. package/src/modules/communication_channels/commands/ingest-inbound-message.ts +38 -1
  597. package/src/modules/communication_channels/di.ts +7 -0
  598. package/src/modules/communication_channels/lib/adapter.ts +14 -0
  599. package/src/modules/communication_channels/lib/email-capabilities.ts +4 -0
  600. package/src/modules/communication_channels/lib/outbound-recipient.ts +71 -0
  601. package/src/modules/communication_channels/lib/resolve-channel-type.ts +99 -0
  602. package/src/modules/communication_channels/lib/test-seed.ts +64 -4
  603. package/src/modules/configs/i18n/de.json +2 -0
  604. package/src/modules/configs/i18n/en.json +2 -0
  605. package/src/modules/configs/i18n/es.json +2 -0
  606. package/src/modules/configs/i18n/ko.json +2 -0
  607. package/src/modules/configs/i18n/pl.json +2 -0
  608. package/src/modules/configs/lib/system-status.ts +9 -0
  609. package/src/modules/currencies/AGENTS.md +3 -0
  610. package/src/modules/currencies/backend/currencies/page.tsx +4 -1
  611. package/src/modules/currencies/backend/exchange-rates/page.tsx +4 -1
  612. package/src/modules/currencies/services/README.md +45 -0
  613. package/src/modules/currencies/services/rateFetchingService.ts +6 -1
  614. package/src/modules/customer_accounts/api/admin/domain-mappings.ts +7 -0
  615. package/src/modules/customer_accounts/backend/customer_accounts/roles/page.tsx +4 -1
  616. package/src/modules/customer_accounts/backend/customer_accounts/users/PortalUsersPageClient.tsx +4 -1
  617. package/src/modules/customer_accounts/services/domainMappingService.ts +10 -0
  618. package/src/modules/customers/ai-tools/companies-pack.ts +4 -1
  619. package/src/modules/customers/ai-tools/deal-analyzer-pack.ts +17 -2
  620. package/src/modules/customers/ai-tools/deals-pack.ts +66 -1
  621. package/src/modules/customers/ai-tools/people-pack.ts +4 -1
  622. package/src/modules/customers/api/activities/route.ts +45 -0
  623. package/src/modules/customers/api/companies/[id]/people/route.ts +24 -73
  624. package/src/modules/customers/api/companies/[id]/route.ts +24 -107
  625. package/src/modules/customers/api/dashboard/widgets/customer-todos/route.ts +16 -8
  626. package/src/modules/customers/api/deals/[id]/companies/route.ts +4 -1
  627. package/src/modules/customers/api/deals/[id]/people/route.ts +4 -1
  628. package/src/modules/customers/api/deals/[id]/route.ts +17 -28
  629. package/src/modules/customers/api/deals/[id]/stats/route.ts +10 -25
  630. package/src/modules/customers/api/deals/aggregate/route.ts +17 -9
  631. package/src/modules/customers/api/deals/map/route.ts +4 -4
  632. package/src/modules/customers/api/deals/route.ts +50 -1
  633. package/src/modules/customers/api/entity-roles-factory.ts +8 -4
  634. package/src/modules/customers/api/interactions/route.ts +8 -2
  635. package/src/modules/customers/api/interactions/tasks/route.ts +24 -1
  636. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +12 -4
  637. package/src/modules/customers/api/people/[id]/companies/context.ts +4 -1
  638. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +4 -1
  639. package/src/modules/customers/api/people/[id]/route.ts +16 -11
  640. package/src/modules/customers/api/people/check-phone/route.ts +75 -10
  641. package/src/modules/customers/api/todos/route.ts +27 -2
  642. package/src/modules/customers/backend/customers/companies/page.tsx +5 -2
  643. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +7 -2
  644. package/src/modules/customers/backend/customers/deals/page.tsx +8 -2
  645. package/src/modules/customers/backend/customers/deals/pipeline/components/Lane.tsx +5 -14
  646. package/src/modules/customers/backend/customers/deals/pipeline/components/StatusFilterPopover.tsx +109 -27
  647. package/src/modules/customers/backend/customers/deals/pipeline/components/toneClasses.ts +21 -0
  648. package/src/modules/customers/backend/customers/people/page.tsx +5 -2
  649. package/src/modules/customers/backend/hooks/useEmailDuplicateCheck.ts +12 -4
  650. package/src/modules/customers/commands/deals.ts +34 -59
  651. package/src/modules/customers/commands/interactions.ts +1 -1
  652. package/src/modules/customers/commands/personCompanyLinks.ts +224 -8
  653. package/src/modules/customers/components/CustomerTodosTable.tsx +2 -0
  654. package/src/modules/customers/components/DealsKpiStrip.tsx +7 -7
  655. package/src/modules/customers/components/calendar/AgendaList.tsx +3 -3
  656. package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +1 -1
  657. package/src/modules/customers/components/calendar/CalendarScreen.tsx +1 -1
  658. package/src/modules/customers/components/calendar/CalendarSettingsModal.tsx +1 -1
  659. package/src/modules/customers/components/calendar/EventBlock.tsx +2 -2
  660. package/src/modules/customers/components/calendar/EventPeekPopover.tsx +4 -2
  661. package/src/modules/customers/components/calendar/editor/PeopleField.tsx +61 -5
  662. package/src/modules/customers/components/calendar/editor/hooks.ts +7 -1
  663. package/src/modules/customers/components/calendar/types.ts +2 -2
  664. package/src/modules/customers/components/detail/CompanyKpiBar.tsx +5 -4
  665. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +8 -1
  666. package/src/modules/customers/components/detail/DealForm.tsx +22 -2
  667. package/src/modules/customers/components/detail/DealsSection.tsx +11 -5
  668. package/src/modules/customers/components/detail/EntityTagsDialog.tsx +58 -12
  669. package/src/modules/customers/components/detail/PersonCompaniesSection.tsx +8 -1
  670. package/src/modules/customers/components/detail/hooks/usePersonTasks.ts +23 -14
  671. package/src/modules/customers/components/detail/schedule/ParticipantsField.tsx +5 -5
  672. package/src/modules/customers/components/detail/schedule/useScheduleFormState.ts +5 -5
  673. package/src/modules/customers/components/detail/types.ts +1 -1
  674. package/src/modules/customers/components/detail/utils.ts +15 -5
  675. package/src/modules/customers/data/entities.ts +1 -1
  676. package/src/modules/customers/data/validators.ts +50 -9
  677. package/src/modules/customers/events.ts +5 -0
  678. package/src/modules/customers/i18n/de.json +9 -1
  679. package/src/modules/customers/i18n/en.json +9 -1
  680. package/src/modules/customers/i18n/es.json +9 -1
  681. package/src/modules/customers/i18n/ko.json +9 -1
  682. package/src/modules/customers/i18n/pl.json +9 -1
  683. package/src/modules/customers/lib/calendar/conflicts.ts +10 -2
  684. package/src/modules/customers/lib/calendar/editorPayload.ts +4 -3
  685. package/src/modules/customers/lib/calendar/mapItem.ts +8 -3
  686. package/src/modules/customers/lib/calendar/participantIdentity.ts +17 -0
  687. package/src/modules/customers/lib/closureStage.ts +76 -0
  688. package/src/modules/customers/lib/dealStatus.ts +42 -0
  689. package/src/modules/customers/lib/detailReadAccess.ts +35 -0
  690. package/src/modules/customers/lib/findPeopleByAddresses.ts +8 -6
  691. package/src/modules/customers/lib/personCompanies.ts +136 -1
  692. package/src/modules/customers/lib/todoCompatibility.ts +19 -1
  693. package/src/modules/dashboards/i18n/es.json +4 -4
  694. package/src/modules/dashboards/i18n/pl.json +7 -7
  695. package/src/modules/dashboards/lib/widgetScope.ts +6 -0
  696. package/src/modules/data_sync/AGENTS.md +1 -1
  697. package/src/modules/data_sync/backend/data-sync/page.tsx +4 -1
  698. package/src/modules/data_sync/lib/abandoned-run.ts +56 -0
  699. package/src/modules/data_sync/lib/adapter.ts +36 -0
  700. package/src/modules/data_sync/lib/sync-engine.ts +113 -5
  701. package/src/modules/data_sync/workers/sync-export.ts +4 -0
  702. package/src/modules/data_sync/workers/sync-import.ts +4 -0
  703. package/src/modules/devices/AGENTS.md +20 -1
  704. package/src/modules/devices/acl.ts +9 -1
  705. package/src/modules/devices/api/admin/devices/[id]/route.ts +5 -34
  706. package/src/modules/devices/api/admin/devices/route.ts +14 -1
  707. package/src/modules/devices/api/deviceList.ts +135 -11
  708. package/src/modules/devices/api/deviceSerialization.ts +50 -0
  709. package/src/modules/devices/api/openapi.ts +9 -1
  710. package/src/modules/devices/api/route.ts +9 -1
  711. package/src/modules/devices/backend/devices/[id]/page.tsx +18 -32
  712. package/src/modules/devices/backend/devices/create/page.tsx +17 -1
  713. package/src/modules/devices/backend/devices/page.tsx +44 -45
  714. package/src/modules/devices/backend/devices/useDeviceUserLabels.ts +45 -0
  715. package/src/modules/devices/backend/devices/userOptions.ts +99 -0
  716. package/src/modules/devices/i18n/de.json +3 -2
  717. package/src/modules/devices/i18n/en.json +3 -2
  718. package/src/modules/devices/i18n/es.json +3 -2
  719. package/src/modules/devices/i18n/ko.json +3 -2
  720. package/src/modules/devices/i18n/pl.json +3 -2
  721. package/src/modules/devices/setup.ts +6 -2
  722. package/src/modules/directory/backend/directory/organizations/page.tsx +3 -1
  723. package/src/modules/directory/backend/directory/tenants/page.tsx +3 -1
  724. package/src/modules/directory/di.ts +14 -2
  725. package/src/modules/directory/services/organizationHierarchyService.ts +34 -0
  726. package/src/modules/directory/services/organizationScopeService.ts +85 -0
  727. package/src/modules/directory/utils/organizationScope.ts +4 -15
  728. package/src/modules/entities/api/records.ts +2 -0
  729. package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +4 -1
  730. package/src/modules/eudr/api/plots/route.ts +4 -0
  731. package/src/modules/eudr/backend/eudr/evidence-submissions/page.tsx +4 -0
  732. package/src/modules/eudr/backend/eudr/plots/page.tsx +4 -0
  733. package/src/modules/eudr/backend/eudr/product-mappings/page.tsx +4 -0
  734. package/src/modules/eudr/backend/eudr/risk-assessments/page.tsx +4 -0
  735. package/src/modules/eudr/backend/eudr/statements/page.tsx +4 -0
  736. package/src/modules/eudr/commands/statements.ts +0 -3
  737. package/src/modules/eudr/data/validators.ts +16 -1
  738. package/src/modules/feature_toggles/components/FeatureTogglesTable.tsx +2 -1
  739. package/src/modules/feature_toggles/components/OverridesTable.tsx +2 -1
  740. package/src/modules/feature_toggles/defaults.json +0 -8
  741. package/src/modules/inbox_ops/backend/inbox-ops/log/page.tsx +4 -0
  742. package/src/modules/inbox_ops/backend/inbox-ops/page.tsx +4 -0
  743. package/src/modules/inbox_ops/lib/htmlToPlainText.ts +1 -17
  744. package/src/modules/integrations/api/[id]/credentials/route.ts +6 -4
  745. package/src/modules/integrations/backend/integrations/[id]/page.tsx +61 -31
  746. package/src/modules/integrations/backend/integrations/bundle/[id]/page.tsx +44 -9
  747. package/src/modules/integrations/backend/integrations/credential-secret-fields.ts +84 -0
  748. package/src/modules/integrations/data/validators.ts +12 -2
  749. package/src/modules/integrations/i18n/de.json +1 -0
  750. package/src/modules/integrations/i18n/en.json +1 -0
  751. package/src/modules/integrations/i18n/es.json +1 -0
  752. package/src/modules/integrations/i18n/ko.json +1 -0
  753. package/src/modules/integrations/i18n/pl.json +1 -0
  754. package/src/modules/integrations/lib/credentials-masking.ts +10 -6
  755. package/src/modules/messages/api/[id]/route.ts +55 -1
  756. package/src/modules/messages/api/openapi.ts +20 -0
  757. package/src/modules/messages/api/route.ts +31 -2
  758. package/src/modules/messages/components/MessagesInboxPageClient.tsx +9 -16
  759. package/src/modules/messages/components/inboxFilters.ts +36 -0
  760. package/src/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.ts +14 -1
  761. package/src/modules/messages/components/message-detail/panels/MessageHeader.tsx +3 -1
  762. package/src/modules/messages/components/message-detail/panels/thread-panel.tsx +2 -1
  763. package/src/modules/messages/components/message-detail/types.ts +3 -0
  764. package/src/modules/messages/components/messageListLabels.ts +52 -3
  765. package/src/modules/messages/data/validators.ts +43 -4
  766. package/src/modules/messages/lib/channel-sender-identity.ts +55 -0
  767. package/src/modules/messages/lib/composeSourceChannelType.ts +95 -0
  768. package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +4 -6
  769. package/src/modules/payment_gateways/backend/payment-gateways/page.tsx +4 -1
  770. package/src/modules/payment_gateways/lib/webhook-processor.ts +11 -0
  771. package/src/modules/planner/backend/planner/availability-rulesets/page.tsx +4 -0
  772. package/src/modules/push_notifications/backend/push_notifications/page.tsx +4 -1
  773. package/src/modules/push_notifications/backend/push_notifications/send/page.tsx +4 -4
  774. package/src/modules/query_index/lib/engine.ts +249 -61
  775. package/src/modules/query_index/lib/search-entity-policy.ts +46 -0
  776. package/src/modules/query_index/lib/search-tokens.ts +135 -3
  777. package/src/modules/resources/backend/resources/resource-types/page.tsx +4 -1
  778. package/src/modules/resources/backend/resources/resources/page.tsx +4 -1
  779. package/src/modules/sales/backend/sales/channels/offers/page.tsx +4 -0
  780. package/src/modules/sales/backend/sales/channels/page.tsx +4 -0
  781. package/src/modules/sales/backend/sales/documents/[id]/page.tsx +14 -8
  782. package/src/modules/sales/commands/documents.ts +93 -0
  783. package/src/modules/sales/components/PriceWithCurrency.tsx +17 -5
  784. package/src/modules/sales/components/channels/SalesChannelOffersPanel.tsx +4 -0
  785. package/src/modules/sales/components/documents/AdjustmentsSection.tsx +6 -5
  786. package/src/modules/sales/components/documents/ItemsSection.tsx +56 -18
  787. package/src/modules/sales/components/documents/LineItemDialog.tsx +137 -20
  788. package/src/modules/sales/components/documents/PaymentsSection.tsx +20 -9
  789. package/src/modules/sales/components/documents/ReturnsSection.tsx +6 -5
  790. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +106 -14
  791. package/src/modules/sales/components/documents/SalesOrderDraftLines.tsx +6 -5
  792. package/src/modules/sales/components/documents/ShipmentDialog.tsx +5 -4
  793. package/src/modules/sales/components/documents/ShipmentsSection.tsx +6 -5
  794. package/src/modules/sales/components/documents/lineItemShipmentLock.ts +74 -0
  795. package/src/modules/sales/components/documents/lineItemUtils.ts +7 -2
  796. package/src/modules/sales/data/entities.ts +6 -0
  797. package/src/modules/sales/extension-points.ts +1 -0
  798. package/src/modules/sales/i18n/de.json +8 -0
  799. package/src/modules/sales/i18n/en.json +8 -0
  800. package/src/modules/sales/i18n/es.json +8 -0
  801. package/src/modules/sales/i18n/ko.json +8 -0
  802. package/src/modules/sales/i18n/pl.json +8 -0
  803. package/src/modules/sales/lib/salesChannelsToggleSeed.ts +42 -0
  804. package/src/modules/sales/migrations/.snapshot-open-mercato.json +60 -0
  805. package/src/modules/sales/migrations/Migration20260821120000_sales_notes_addresses_context_idx.ts +87 -0
  806. package/src/modules/sales/setup.ts +2 -0
  807. package/src/modules/sales/widgets/injection/payment-gateway-status-column/widget.ts +9 -1
  808. package/src/modules/sales/widgets/injection-table.ts +4 -7
  809. package/src/modules/staff/backend/staff/leave-requests/page.tsx +4 -0
  810. package/src/modules/staff/backend/staff/my-leave-requests/page.tsx +4 -0
  811. package/src/modules/staff/backend/staff/team-members/page.tsx +6 -0
  812. package/src/modules/staff/backend/staff/team-roles/page.tsx +4 -0
  813. package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +4 -0
  814. package/src/modules/staff/backend/staff/teams/page.tsx +4 -0
  815. package/src/modules/staff/backend/staff/timesheets/page.tsx +12 -1
  816. package/src/modules/staff/backend/staff/timesheets/projects/page.tsx +4 -0
  817. package/src/modules/sync_excel/lib/adapters/customers.ts +5 -0
  818. package/src/modules/warranty_claims/api/assignees/route.ts +3 -3
  819. package/src/modules/warranty_claims/api/portal/attachments/route.ts +2 -2
  820. package/src/modules/warranty_claims/api/portal/claims/route.ts +12 -9
  821. package/src/modules/warranty_claims/backend/page.tsx +4 -0
  822. package/src/modules/warranty_claims/backend/warranty_claims/registrations/page.tsx +4 -0
  823. package/src/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.tsx +4 -0
  824. package/src/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.tsx +4 -0
  825. package/src/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.tsx +4 -0
  826. package/src/modules/wms/api/warehouseSearch.ts +23 -0
  827. package/src/modules/wms/api/warehouses/route.ts +13 -9
  828. package/src/modules/wms/api/zones/route.ts +16 -0
  829. package/src/modules/wms/commands/configuration.ts +159 -10
  830. package/src/modules/wms/commands/inventory-actions.ts +3 -0
  831. package/src/modules/wms/commands/shared.ts +17 -0
  832. package/src/modules/wms/components/backend/WarehouseEditDialog.tsx +216 -0
  833. package/src/modules/wms/components/backend/WmsConfigurationPage.tsx +95 -141
  834. package/src/modules/wms/components/backend/WmsInventoryConsolePage.tsx +2 -0
  835. package/src/modules/wms/components/backend/WmsLotsListPage.tsx +2 -0
  836. package/src/modules/wms/components/backend/inventoryMutationLoaders.ts +36 -20
  837. package/src/modules/wms/components/backend/warehouseFormOptions.ts +72 -0
  838. package/src/modules/wms/i18n/de.json +2 -0
  839. package/src/modules/wms/i18n/en.json +2 -0
  840. package/src/modules/wms/i18n/es.json +2 -0
  841. package/src/modules/wms/i18n/ko.json +2 -0
  842. package/src/modules/wms/i18n/pl.json +2 -0
  843. package/src/modules/workflows/backend/definitions/page.tsx +4 -1
  844. package/src/modules/workflows/backend/events/page.tsx +4 -1
  845. package/src/modules/workflows/backend/instances/page.tsx +4 -1
  846. package/src/modules/workflows/backend/tasks/page.tsx +4 -1
  847. package/src/modules/workflows/lib/activity-executor.ts +9 -0
@@ -0,0 +1,313 @@
1
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
2
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
3
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
4
+ import { createLogger } from "@open-mercato/shared/lib/logger";
5
+ import { Attachment, AttachmentPartition } from "../data/entities.js";
6
+ import { assertAttachmentScopeInvariant, checkAttachmentAccess } from "./access.js";
7
+ import { buildAttachmentFileUrl } from "./imageUrls.js";
8
+ import {
9
+ isScopedAttachmentUploadError
10
+ } from "./scoped-upload-service.js";
11
+ import { readAttachmentMetadata } from "./metadata.js";
12
+ import {
13
+ buildAttachmentContentDisposition,
14
+ canRenderInlineAttachment,
15
+ hasDangerousExecutableExtension
16
+ } from "./security.js";
17
+ import {
18
+ isMultipartRequestWithinUploadLimit,
19
+ resolveAttachmentMaxBytes,
20
+ resolveAttachmentMultipartMaxBytes
21
+ } from "./upload-limits.js";
22
+ const logger = createLogger("attachments").child({ component: "attachment-service" });
23
+ const SCOPED_UPLOAD_ERROR_MESSAGES = {
24
+ dangerous_executable: {
25
+ key: "attachments.errors.dangerousExecutable",
26
+ fallback: "Executable file types are not allowed as attachments."
27
+ },
28
+ max_upload_size: {
29
+ key: "attachments.errors.maxUploadSize",
30
+ fallback: "Attachment exceeds the maximum upload size."
31
+ },
32
+ active_content: {
33
+ key: "attachments.errors.activeContentBlocked",
34
+ fallback: "Active content uploads are not allowed."
35
+ },
36
+ partition_unavailable: {
37
+ key: "attachments.errors.partitionUnavailable",
38
+ fallback: "Attachment partition is not available for this scope."
39
+ },
40
+ quota_exceeded: {
41
+ key: "attachments.errors.quotaExceeded",
42
+ fallback: "Attachment storage quota exceeded for this tenant."
43
+ },
44
+ quota_target_exists: {
45
+ key: "attachments.errors.storagePathExists",
46
+ fallback: "The target storage path already exists."
47
+ },
48
+ quota_unavailable: {
49
+ key: "attachments.errors.quotaUnavailable",
50
+ fallback: "Storage quota accounting is unavailable."
51
+ },
52
+ quota_recovery_unsupported: {
53
+ key: "attachments.errors.quotaRecoveryUnsupported",
54
+ fallback: "Storage driver cannot participate in quota recovery."
55
+ },
56
+ storage_failed: {
57
+ key: "attachments.errors.storageFailed",
58
+ fallback: "Failed to store the attachment file."
59
+ },
60
+ persistence_failed: {
61
+ key: "attachments.errors.persistenceFailed",
62
+ fallback: "Failed to persist attachment."
63
+ }
64
+ };
65
+ const UPLOAD_FAILED_MESSAGE = {
66
+ key: "attachments.errors.uploadFailed",
67
+ fallback: "Attachment upload failed."
68
+ };
69
+ const UPLOAD_SERVICE_UNAVAILABLE_MESSAGE = {
70
+ key: "attachments.errors.uploadServiceUnavailable",
71
+ fallback: "The attachment upload service is not available."
72
+ };
73
+ async function translateAttachmentError(message) {
74
+ const { t } = await resolveTranslations();
75
+ return t(message.key, message.fallback);
76
+ }
77
+ async function readRequestBodyWithinLimit(request, maxBytes) {
78
+ const reader = request.body?.getReader();
79
+ if (!reader) throw new CrudHttpError(400, { error: "File is required" });
80
+ const chunks = [];
81
+ let totalBytes = 0;
82
+ try {
83
+ while (true) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ totalBytes += value.byteLength;
87
+ if (totalBytes > maxBytes) {
88
+ await reader.cancel();
89
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
90
+ }
91
+ chunks.push(value);
92
+ }
93
+ } finally {
94
+ reader.releaseLock();
95
+ }
96
+ const body = new Uint8Array(totalBytes);
97
+ let offset = 0;
98
+ for (const chunk of chunks) {
99
+ body.set(chunk, offset);
100
+ offset += chunk.byteLength;
101
+ }
102
+ return body;
103
+ }
104
+ function assignmentMatches(candidate, expected) {
105
+ return candidate.type === expected.type && candidate.id === expected.id;
106
+ }
107
+ function partitionMatchesScope(partition, tenantId, organizationId) {
108
+ const partitionTenantId = partition.tenantId ?? null;
109
+ const partitionOrganizationId = partition.organizationId ?? null;
110
+ if (partitionTenantId === null && partitionOrganizationId === null) return true;
111
+ if (partitionTenantId === null || partitionOrganizationId === null) return false;
112
+ return partitionTenantId === tenantId && partitionOrganizationId === organizationId;
113
+ }
114
+ class DefaultAttachmentService {
115
+ /**
116
+ * The scoped upload service is supplied as a *resolver*, not an instance:
117
+ * resolving it eagerly would drag its own dependencies (notably `dataEngine`)
118
+ * into every container that merely constructs an `attachmentService`, even
119
+ * one that never uploads. `createScoped` requires it — module uploads must
120
+ * share the one reservation ledger rather than run a parallel quota
121
+ * mechanism — so its absence surfaces there, at the call that needs it.
122
+ */
123
+ constructor(em, storageDriverFactory, resolveScopedUploadService) {
124
+ this.em = em;
125
+ this.storageDriverFactory = storageDriverFactory;
126
+ this.resolveScopedUploadService = resolveScopedUploadService;
127
+ }
128
+ validateUpload(input) {
129
+ if (!isMultipartRequestWithinUploadLimit(input.contentLength ?? null)) {
130
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
131
+ }
132
+ if (input.fileName && hasDangerousExecutableExtension(input.fileName)) {
133
+ throw new CrudHttpError(400, { error: "Executable file types are not allowed as attachments." });
134
+ }
135
+ if (typeof input.fileSize === "number" && input.fileSize > resolveAttachmentMaxBytes(null)) {
136
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
137
+ }
138
+ }
139
+ async readUploadForm(request) {
140
+ this.validateUpload({ contentLength: request.headers.get("content-length") });
141
+ const contentType = request.headers.get("content-type") ?? "";
142
+ if (!contentType.toLowerCase().includes("multipart/form-data")) {
143
+ throw new CrudHttpError(400, { error: "Expected multipart/form-data" });
144
+ }
145
+ const body = await readRequestBodyWithinLimit(request, resolveAttachmentMultipartMaxBytes());
146
+ const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
147
+ try {
148
+ return await new Response(responseBody, { headers: { "content-type": contentType } }).formData();
149
+ } catch {
150
+ throw new CrudHttpError(400, { error: "Invalid multipart/form-data" });
151
+ }
152
+ }
153
+ async createScoped(input) {
154
+ assertAttachmentScopeInvariant(input);
155
+ this.validateUpload({ fileName: input.fileName, fileSize: input.buffer.length });
156
+ let uploadService = null;
157
+ try {
158
+ uploadService = this.resolveScopedUploadService?.() ?? null;
159
+ } catch (error) {
160
+ logger.error("Scoped attachment upload service could not be resolved", { err: error });
161
+ }
162
+ if (!uploadService) {
163
+ throw new CrudHttpError(500, {
164
+ error: await translateAttachmentError(UPLOAD_SERVICE_UNAVAILABLE_MESSAGE)
165
+ });
166
+ }
167
+ let attachment;
168
+ try {
169
+ attachment = await uploadService.upload({
170
+ tenantId: input.tenantId,
171
+ organizationId: input.organizationId,
172
+ entityId: input.entityId,
173
+ recordId: input.recordId,
174
+ fileName: input.fileName,
175
+ buffer: input.buffer,
176
+ declaredMimeType: input.declaredMimeType ?? null,
177
+ assignments: input.assignments,
178
+ partitionCode: input.partitionCode,
179
+ requirePrivatePartition: true,
180
+ persistLink: input.persistLink
181
+ });
182
+ } catch (error) {
183
+ if (isScopedAttachmentUploadError(error)) {
184
+ const message = SCOPED_UPLOAD_ERROR_MESSAGES[error.code] ?? UPLOAD_FAILED_MESSAGE;
185
+ throw new CrudHttpError(error.status, { error: await translateAttachmentError(message) });
186
+ }
187
+ throw error;
188
+ }
189
+ return {
190
+ id: attachment.id,
191
+ url: attachment.url ?? buildAttachmentFileUrl(attachment.id),
192
+ fileName: attachment.fileName,
193
+ mimeType: attachment.mimeType,
194
+ fileSize: attachment.fileSize
195
+ };
196
+ }
197
+ async readScoped(input) {
198
+ const attachment = await findOneWithDecryption(
199
+ this.em,
200
+ Attachment,
201
+ {
202
+ id: input.attachmentId,
203
+ tenantId: input.auth.tenantId ?? null,
204
+ organizationId: input.auth.orgId ?? null
205
+ },
206
+ void 0,
207
+ { tenantId: input.auth.tenantId, organizationId: input.auth.orgId }
208
+ );
209
+ if (!attachment) throw new CrudHttpError(404, { error: "Attachment not found" });
210
+ const partition = await findOneWithDecryption(
211
+ this.em,
212
+ AttachmentPartition,
213
+ { code: attachment.partitionCode },
214
+ void 0,
215
+ { tenantId: input.auth.tenantId, organizationId: input.auth.orgId }
216
+ );
217
+ if (!partition) throw new CrudHttpError(500, { error: "Attachment partition is not configured" });
218
+ const access = checkAttachmentAccess(input.auth, attachment, partition, { requireAuthForPublic: true });
219
+ if (!access.ok) {
220
+ throw new CrudHttpError(access.status, { error: access.status === 401 ? "Unauthorized" : "Forbidden" });
221
+ }
222
+ if (!partitionMatchesScope(partition, input.auth.tenantId, input.auth.orgId)) {
223
+ throw new CrudHttpError(403, { error: "Attachment partition is not accessible for this scope" });
224
+ }
225
+ if (input.requirePrivatePartition && partition.isPublic) {
226
+ throw new CrudHttpError(403, { error: "Attachment partition is not accessible for this resource" });
227
+ }
228
+ if (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {
229
+ throw new CrudHttpError(404, { error: "Attachment not found" });
230
+ }
231
+ if (attachment.entityId !== input.expectedOwner.entityId || attachment.recordId !== input.expectedOwner.recordId) {
232
+ throw new CrudHttpError(404, { error: "Attachment not found" });
233
+ }
234
+ if (input.expectedAssignment) {
235
+ const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? [];
236
+ if (!assignments.some((candidate) => assignmentMatches(candidate, input.expectedAssignment))) {
237
+ throw new CrudHttpError(404, { error: "Attachment not found" });
238
+ }
239
+ }
240
+ const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, {
241
+ tenantId: attachment.tenantId ?? "",
242
+ organizationId: attachment.organizationId ?? ""
243
+ });
244
+ let result;
245
+ try {
246
+ result = await driver.read(attachment.partitionCode, attachment.storagePath);
247
+ } catch {
248
+ throw new CrudHttpError(404, { error: "File not available" });
249
+ }
250
+ const mimeType = attachment.mimeType || "application/octet-stream";
251
+ const renderInline = !input.forceDownload && canRenderInlineAttachment(mimeType);
252
+ return {
253
+ buffer: result.buffer,
254
+ contentType: renderInline ? result.contentType ?? mimeType : "application/octet-stream",
255
+ contentDisposition: buildAttachmentContentDisposition(
256
+ attachment.fileName,
257
+ renderInline ? "inline" : "attachment"
258
+ ),
259
+ fileName: attachment.fileName,
260
+ mimeType
261
+ };
262
+ }
263
+ async releaseScoped(input, options = {}) {
264
+ const em = options.em ?? this.em;
265
+ const expectedAssignment = input.expectedAssignment;
266
+ if (!expectedAssignment) {
267
+ throw new CrudHttpError(500, {
268
+ error: "Attachment release requires the expected assignment of the releasing record"
269
+ });
270
+ }
271
+ const isInTransaction = em.isInTransaction;
272
+ if (options.flush !== false && typeof isInTransaction === "function" && isInTransaction.call(em)) {
273
+ throw new CrudHttpError(500, {
274
+ error: "Attachment release inside an ambient transaction requires flush: false and deferred provider cleanup"
275
+ });
276
+ }
277
+ const scope = { tenantId: input.tenantId, organizationId: input.organizationId };
278
+ const attachment = await findOneWithDecryption(
279
+ em,
280
+ Attachment,
281
+ {
282
+ id: input.attachmentId,
283
+ tenantId: input.tenantId,
284
+ organizationId: input.organizationId
285
+ },
286
+ void 0,
287
+ scope
288
+ );
289
+ if (!attachment) throw new CrudHttpError(404, { error: "Attachment not found" });
290
+ if (attachment.entityId !== input.expectedOwner.entityId || attachment.recordId !== input.expectedOwner.recordId || input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {
291
+ throw new CrudHttpError(404, { error: "Attachment not found" });
292
+ }
293
+ const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? [];
294
+ if (!assignments.some((candidate) => assignmentMatches(candidate, expectedAssignment))) {
295
+ throw new CrudHttpError(409, { error: "Attachment is still referenced by another record" });
296
+ }
297
+ if (assignments.some((candidate) => !assignmentMatches(candidate, expectedAssignment))) {
298
+ throw new CrudHttpError(409, { error: "Attachment is still referenced by another record" });
299
+ }
300
+ const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, scope);
301
+ const deleteProviderBytes = () => driver.delete(attachment.partitionCode, attachment.storagePath);
302
+ em.remove(attachment);
303
+ if (options.flush === false) {
304
+ return deleteProviderBytes;
305
+ }
306
+ await em.flush();
307
+ await deleteProviderBytes();
308
+ }
309
+ }
310
+ export {
311
+ DefaultAttachmentService
312
+ };
313
+ //# sourceMappingURL=attachment-service.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/attachments/lib/attachment-service.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { assertAttachmentScopeInvariant, checkAttachmentAccess } from './access'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport {\n isScopedAttachmentUploadError,\n type ScopedAttachmentUploadErrorCode,\n type ScopedAttachmentUploadService,\n} from './scoped-upload-service'\nimport { readAttachmentMetadata, type AttachmentAssignment } from './metadata'\nimport {\n buildAttachmentContentDisposition,\n canRenderInlineAttachment,\n hasDangerousExecutableExtension,\n} from './security'\nimport {\n isMultipartRequestWithinUploadLimit,\n resolveAttachmentMaxBytes,\n resolveAttachmentMultipartMaxBytes,\n} from './upload-limits'\n\nconst logger = createLogger('attachments').child({ component: 'attachment-service' })\n\ntype AttachmentErrorMessage = {\n key: string\n fallback: string\n}\n\n/**\n * The scoped upload service reports failures as machine codes. Each maps to the\n * translation key the public attachment route uses for the same condition, and\n * the key is resolved server-side before it reaches the response body \u2014 clients\n * render the `error` field verbatim, so handing them a raw key would surface\n * `attachments.errors.quotaExceeded` as the user-facing message.\n */\nconst SCOPED_UPLOAD_ERROR_MESSAGES: Record<ScopedAttachmentUploadErrorCode, AttachmentErrorMessage> = {\n dangerous_executable: {\n key: 'attachments.errors.dangerousExecutable',\n fallback: 'Executable file types are not allowed as attachments.',\n },\n max_upload_size: {\n key: 'attachments.errors.maxUploadSize',\n fallback: 'Attachment exceeds the maximum upload size.',\n },\n active_content: {\n key: 'attachments.errors.activeContentBlocked',\n fallback: 'Active content uploads are not allowed.',\n },\n partition_unavailable: {\n key: 'attachments.errors.partitionUnavailable',\n fallback: 'Attachment partition is not available for this scope.',\n },\n quota_exceeded: {\n key: 'attachments.errors.quotaExceeded',\n fallback: 'Attachment storage quota exceeded for this tenant.',\n },\n quota_target_exists: {\n key: 'attachments.errors.storagePathExists',\n fallback: 'The target storage path already exists.',\n },\n quota_unavailable: {\n key: 'attachments.errors.quotaUnavailable',\n fallback: 'Storage quota accounting is unavailable.',\n },\n quota_recovery_unsupported: {\n key: 'attachments.errors.quotaRecoveryUnsupported',\n fallback: 'Storage driver cannot participate in quota recovery.',\n },\n storage_failed: {\n key: 'attachments.errors.storageFailed',\n fallback: 'Failed to store the attachment file.',\n },\n persistence_failed: {\n key: 'attachments.errors.persistenceFailed',\n fallback: 'Failed to persist attachment.',\n },\n}\n\nconst UPLOAD_FAILED_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadFailed',\n fallback: 'Attachment upload failed.',\n}\n\nconst UPLOAD_SERVICE_UNAVAILABLE_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadServiceUnavailable',\n fallback: 'The attachment upload service is not available.',\n}\n\nasync function translateAttachmentError(message: AttachmentErrorMessage): Promise<string> {\n const { t } = await resolveTranslations()\n return t(message.key, message.fallback)\n}\n\nexport type AttachmentOwner = {\n entityId: string\n recordId: string\n}\n\nexport type CreateScopedAttachmentInput = AttachmentOwner & {\n tenantId: string\n organizationId: string\n partitionCode: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n assignments?: AttachmentAssignment[]\n /**\n * Persists a module-owned link inside the same transaction as the Attachment\n * row. The callback receives only the generated id, never an Attachment\n * entity or storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\nexport type CreatedScopedAttachment = {\n id: string\n url: string\n fileName: string\n mimeType: string\n fileSize: number\n}\n\nexport type ReadScopedAttachmentInput = {\n attachmentId: string\n auth: NonNullable<AuthContext>\n expectedOwner: AttachmentOwner\n expectedAssignment?: AttachmentAssignment\n expectedPartitionCode?: string\n requirePrivatePartition?: boolean\n forceDownload?: boolean\n}\n\nexport type ReadScopedAttachmentResult = {\n buffer: Buffer\n contentType: string\n contentDisposition: string\n fileName: string\n mimeType: string\n}\n\nexport type ReleaseScopedAttachmentInput = {\n attachmentId: string\n tenantId: string\n organizationId: string\n expectedOwner: AttachmentOwner\n /**\n * Required: releasing an attachment deletes the row *and* the provider bytes,\n * so the caller must name the one assignment it owns. The release only\n * proceeds when that assignment is the attachment's sole reference.\n */\n expectedAssignment: AttachmentAssignment\n expectedPartitionCode?: string\n}\n\nexport type AttachmentProviderCleanup = () => Promise<void>\n\nexport interface AttachmentService {\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void\n readUploadForm?(request: Request): Promise<FormData>\n createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment>\n readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult>\n releaseScoped?(\n input: ReleaseScopedAttachmentInput,\n options?: { em?: EntityManager; flush?: boolean },\n ): Promise<AttachmentProviderCleanup | void>\n}\n\nasync function readRequestBodyWithinLimit(request: Request, maxBytes: number): Promise<Uint8Array> {\n const reader = request.body?.getReader()\n if (!reader) throw new CrudHttpError(400, { error: 'File is required' })\n const chunks: Uint8Array[] = []\n let totalBytes = 0\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n totalBytes += value.byteLength\n if (totalBytes > maxBytes) {\n await reader.cancel()\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n const body = new Uint8Array(totalBytes)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n\nfunction assignmentMatches(candidate: AttachmentAssignment, expected: AttachmentAssignment): boolean {\n return candidate.type === expected.type && candidate.id === expected.id\n}\n\nfunction partitionMatchesScope(\n partition: AttachmentPartition,\n tenantId: string | null | undefined,\n organizationId: string | null | undefined,\n): boolean {\n const partitionTenantId = partition.tenantId ?? null\n const partitionOrganizationId = partition.organizationId ?? null\n if (partitionTenantId === null && partitionOrganizationId === null) return true\n if (partitionTenantId === null || partitionOrganizationId === null) return false\n return partitionTenantId === tenantId && partitionOrganizationId === organizationId\n}\n\nexport class DefaultAttachmentService implements AttachmentService {\n /**\n * The scoped upload service is supplied as a *resolver*, not an instance:\n * resolving it eagerly would drag its own dependencies (notably `dataEngine`)\n * into every container that merely constructs an `attachmentService`, even\n * one that never uploads. `createScoped` requires it \u2014 module uploads must\n * share the one reservation ledger rather than run a parallel quota\n * mechanism \u2014 so its absence surfaces there, at the call that needs it.\n */\n constructor(\n private readonly em: EntityManager,\n private readonly storageDriverFactory: StorageDriverFactory,\n private readonly resolveScopedUploadService?: (() => ScopedAttachmentUploadService | null) | null,\n ) {}\n\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void {\n if (!isMultipartRequestWithinUploadLimit(input.contentLength ?? null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n if (input.fileName && hasDangerousExecutableExtension(input.fileName)) {\n throw new CrudHttpError(400, { error: 'Executable file types are not allowed as attachments.' })\n }\n if (typeof input.fileSize === 'number' && input.fileSize > resolveAttachmentMaxBytes(null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n }\n\n async readUploadForm(request: Request): Promise<FormData> {\n this.validateUpload({ contentLength: request.headers.get('content-length') })\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n throw new CrudHttpError(400, { error: 'Expected multipart/form-data' })\n }\n const body = await readRequestBodyWithinLimit(request, resolveAttachmentMultipartMaxBytes())\n const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer\n try {\n return await new Response(responseBody, { headers: { 'content-type': contentType } }).formData()\n } catch {\n throw new CrudHttpError(400, { error: 'Invalid multipart/form-data' })\n }\n }\n\n async createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment> {\n assertAttachmentScopeInvariant(input)\n this.validateUpload({ fileName: input.fileName, fileSize: input.buffer.length })\n\n // Delegate to the platform's scoped upload service rather than repeating its\n // work. It owns the fenced quota lease (reserve \u2192 storing \u2192 stored \u2192\n // complete) that the recovery worker reconciles, writes to the provider\n // outside the database transaction, and emits the attachment CRUD side\n // effects. The previous implementation here ran a *second*, independent\n // quota mechanism on a different advisory-lock key that counted only\n // committed rows, so it could not see an in-flight reservation from the\n // public attachment route and the two paths could jointly exceed a tenant's\n // quota \u2014 and it wrote to storage inside the transaction, so a crash before\n // commit left bytes nothing accounted for.\n let uploadService: ScopedAttachmentUploadService | null = null\n try {\n uploadService = this.resolveScopedUploadService?.() ?? null\n } catch (error) {\n logger.error('Scoped attachment upload service could not be resolved', { err: error })\n }\n if (!uploadService) {\n throw new CrudHttpError(500, {\n error: await translateAttachmentError(UPLOAD_SERVICE_UNAVAILABLE_MESSAGE),\n })\n }\n\n let attachment: Attachment\n try {\n attachment = await uploadService.upload({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n entityId: input.entityId,\n recordId: input.recordId,\n fileName: input.fileName,\n buffer: input.buffer,\n declaredMimeType: input.declaredMimeType ?? null,\n assignments: input.assignments,\n partitionCode: input.partitionCode,\n requirePrivatePartition: true,\n persistLink: input.persistLink,\n })\n } catch (error) {\n if (isScopedAttachmentUploadError(error)) {\n const message = SCOPED_UPLOAD_ERROR_MESSAGES[error.code] ?? UPLOAD_FAILED_MESSAGE\n throw new CrudHttpError(error.status, { error: await translateAttachmentError(message) })\n }\n throw error\n }\n\n return {\n id: attachment.id,\n url: attachment.url ?? buildAttachmentFileUrl(attachment.id),\n fileName: attachment.fileName,\n mimeType: attachment.mimeType,\n fileSize: attachment.fileSize,\n }\n }\n\n async readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult> {\n // Scope the lookup at the database boundary so a foreign-tenant row is\n // never materialized, then keep checkAttachmentAccess below as defense in\n // depth. This service only ever stores fully scoped rows, so global rows\n // and super-admin status deliberately do not widen the requested scope \u2014\n // a super admin reads another tenant's attachment by switching scope, not\n // by bypassing the filter.\n const attachment = await findOneWithDecryption(\n this.em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.auth.tenantId ?? null,\n organizationId: input.auth.orgId ?? null,\n },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n const partition = await findOneWithDecryption(\n this.em,\n AttachmentPartition,\n { code: attachment.partitionCode },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!partition) throw new CrudHttpError(500, { error: 'Attachment partition is not configured' })\n\n const access = checkAttachmentAccess(input.auth, attachment, partition, { requireAuthForPublic: true })\n if (!access.ok) {\n throw new CrudHttpError(access.status, { error: access.status === 401 ? 'Unauthorized' : 'Forbidden' })\n }\n if (!partitionMatchesScope(partition, input.auth.tenantId, input.auth.orgId)) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this scope' })\n }\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this resource' })\n }\n if (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (\n attachment.entityId !== input.expectedOwner.entityId ||\n attachment.recordId !== input.expectedOwner.recordId\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (input.expectedAssignment) {\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, input.expectedAssignment!))) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, {\n tenantId: attachment.tenantId ?? '',\n organizationId: attachment.organizationId ?? '',\n })\n let result: Awaited<ReturnType<typeof driver.read>>\n try {\n result = await driver.read(attachment.partitionCode, attachment.storagePath)\n } catch {\n throw new CrudHttpError(404, { error: 'File not available' })\n }\n\n const mimeType = attachment.mimeType || 'application/octet-stream'\n const renderInline = !input.forceDownload && canRenderInlineAttachment(mimeType)\n return {\n buffer: result.buffer,\n contentType: renderInline ? result.contentType ?? mimeType : 'application/octet-stream',\n contentDisposition: buildAttachmentContentDisposition(\n attachment.fileName,\n renderInline ? 'inline' : 'attachment',\n ),\n fileName: attachment.fileName,\n mimeType,\n }\n }\n\n async releaseScoped(\n input: ReleaseScopedAttachmentInput,\n options: { em?: EntityManager; flush?: boolean } = {},\n ): Promise<AttachmentProviderCleanup | void> {\n const em = options.em ?? this.em\n // The type makes `expectedAssignment` mandatory, but this service is handed\n // out through untyped DI resolution and consumed through structural ports in\n // other packages, so the shared-reference guard is enforced at runtime too:\n // without it a caller could destroy an attachment other records still link.\n const expectedAssignment = input.expectedAssignment\n if (!expectedAssignment) {\n throw new CrudHttpError(500, {\n error: 'Attachment release requires the expected assignment of the releasing record',\n })\n }\n const isInTransaction = (em as { isInTransaction?: () => boolean }).isInTransaction\n if (\n options.flush !== false\n && typeof isInTransaction === 'function'\n && isInTransaction.call(em)\n ) {\n throw new CrudHttpError(500, {\n error: 'Attachment release inside an ambient transaction requires flush: false and deferred provider cleanup',\n })\n }\n const scope = { tenantId: input.tenantId, organizationId: input.organizationId }\n const attachment = await findOneWithDecryption(\n em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n undefined,\n scope,\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n if (\n attachment.entityId !== input.expectedOwner.entityId\n || attachment.recordId !== input.expectedOwner.recordId\n || (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode)\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n if (assignments.some((candidate) => !assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, scope)\n const deleteProviderBytes = () => driver.delete(attachment.partitionCode, attachment.storagePath)\n em.remove(attachment)\n if (options.flush === false) {\n return deleteProviderBytes\n }\n await em.flush()\n await deleteProviderBytes()\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAAgC,6BAA6B;AAEtE,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,8BAAyD;AAClE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAcpF,MAAM,+BAAgG;AAAA,EACpG,sBAAsB;AAAA,IACpB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,iBAAiB;AAAA,IACf,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,gBAAgB;AAAA,IACd,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,uBAAuB;AAAA,IACrB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,gBAAgB;AAAA,IACd,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,qBAAqB;AAAA,IACnB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,mBAAmB;AAAA,IACjB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,4BAA4B;AAAA,IAC1B,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,gBAAgB;AAAA,IACd,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,oBAAoB;AAAA,IAClB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AACF;AAEA,MAAM,wBAAgD;AAAA,EACpD,KAAK;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;AAC/E,UAAM,aAAa,MAAM;AAAA,MACvB;AAAA,MACA;AAAA,MACA;AAAA,QACE,IAAI,MAAM;AAAA,QACV,UAAU,MAAM;AAAA,QAChB,gBAAgB,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,QAAI,CAAC,WAAY,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAC/E,QACE,WAAW,aAAa,MAAM,cAAc,YACzC,WAAW,aAAa,MAAM,cAAc,YAC3C,MAAM,yBAAyB,WAAW,kBAAkB,MAAM,uBACtE;AACA,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,IAChE;AACA,UAAM,cAAc,uBAAuB,WAAW,eAAe,EAAE,eAAe,CAAC;AACvF,QAAI,CAAC,YAAY,KAAK,CAAC,cAAc,kBAAkB,WAAW,kBAAkB,CAAC,GAAG;AACtF,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,mDAAmD,CAAC;AAAA,IAC5F;AACA,QAAI,YAAY,KAAK,CAAC,cAAc,CAAC,kBAAkB,WAAW,kBAAkB,CAAC,GAAG;AACtF,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,mDAAmD,CAAC;AAAA,IAC5F;AAEA,UAAM,SAAS,MAAM,KAAK,qBAAqB,oBAAoB,WAAW,eAAe,KAAK;AAClG,UAAM,sBAAsB,MAAM,OAAO,OAAO,WAAW,eAAe,WAAW,WAAW;AAChG,OAAG,OAAO,UAAU;AACpB,QAAI,QAAQ,UAAU,OAAO;AAC3B,aAAO;AAAA,IACT;AACA,UAAM,GAAG,MAAM;AACf,UAAM,oBAAoB;AAAA,EAC5B;AACF;",
6
+ "names": []
7
+ }
@@ -1,5 +1,7 @@
1
+ var _a, _b;
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { emitCrudSideEffects } from "@open-mercato/shared/lib/commands/helpers";
4
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
5
  import { createLogger } from "@open-mercato/shared/lib/logger";
4
6
  import { Attachment, AttachmentPartition } from "../data/entities.js";
5
7
  import { attachmentCrudEvents, attachmentCrudIndexer } from "./crud.js";
@@ -21,14 +23,19 @@ import {
21
23
  } from "./security.js";
22
24
  import { resolveAttachmentMaxBytes } from "./upload-limits.js";
23
25
  const logger = createLogger("attachments");
24
- class ScopedAttachmentUploadError extends Error {
26
+ const SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/ScopedAttachmentUploadError");
27
+ class ScopedAttachmentUploadError extends (_b = Error, _a = SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER, _b) {
25
28
  constructor(code, status) {
26
29
  super(code);
27
30
  this.code = code;
28
31
  this.status = status;
32
+ this[_a] = true;
29
33
  this.name = "ScopedAttachmentUploadError";
30
34
  }
31
35
  }
36
+ function isScopedAttachmentUploadError(error) {
37
+ return Boolean(error) && typeof error === "object" && error[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true;
38
+ }
32
39
  class ScopedAttachmentUploadService {
33
40
  constructor(deps) {
34
41
  this.deps = deps;
@@ -56,6 +63,9 @@ class ScopedAttachmentUploadService {
56
63
  ]
57
64
  });
58
65
  if (!partition) throw new ScopedAttachmentUploadError("partition_unavailable", 400);
66
+ if (input.requirePrivatePartition && partition.isPublic) {
67
+ throw new ScopedAttachmentUploadError("partition_unavailable", 403);
68
+ }
59
69
  const driver = await storageDriverFactory.resolveForPartition(partition.code, {
60
70
  tenantId: input.tenantId,
61
71
  organizationId: input.organizationId
@@ -157,11 +167,13 @@ class ScopedAttachmentUploadService {
157
167
  });
158
168
  assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId });
159
169
  await tx.persist(attachment).flush();
170
+ await input.persistLink?.(tx, attachmentId);
160
171
  await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx);
161
172
  });
162
173
  } catch (error) {
163
174
  await this.compensateStorage(driver, partition.code, storedPath, reservation);
164
175
  logger.error("Scoped attachment persistence failed", { err: error });
176
+ if (isCrudHttpError(error)) throw error;
165
177
  throw new ScopedAttachmentUploadError("persistence_failed", 500);
166
178
  }
167
179
  if (useLlmOcr) {
@@ -197,6 +209,7 @@ class ScopedAttachmentUploadService {
197
209
  }
198
210
  export {
199
211
  ScopedAttachmentUploadError,
200
- ScopedAttachmentUploadService
212
+ ScopedAttachmentUploadService,
213
+ isScopedAttachmentUploadError
201
214
  };
202
215
  //# sourceMappingURL=scoped-upload-service.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/scoped-upload-service.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\nexport class ScopedAttachmentUploadError extends Error {\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n requestOcrProcessing(em, attachment, driver, storedPath).catch((error) => {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n })\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAG3B,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,sBAAsB,6BAA6B;AAE5D,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAG1C,MAAM,SAAS,aAAa,aAAa;AAclC,MAAM,oCAAoC,MAAM;AAAA,EACrD,YACkB,MACA,QAChB;AACA,UAAM,IAAI;AAHM;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAqBO,MAAM,8BAA8B;AAAA,EACzC,YAA6B,MAM1B;AAN0B;AAAA,EAMzB;AAAA,EAEJ,MAAM,OAAO,OAAyD;AACpE,UAAM,WAAW,yBAAyB,MAAM,QAAQ;AACxD,QAAI,gCAAgC,QAAQ,GAAG;AAC7C,YAAM,IAAI,4BAA4B,wBAAwB,GAAG;AAAA,IACnE;AACA,QAAI,MAAM,OAAO,UAAU,MAAM,YAAY,0BAA0B,IAAI;AACzE,YAAM,IAAI,4BAA4B,mB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AAM,KAAK,kBAAkB,QAAQ,UAAU,MAAM,YAAY,WAAW;AAC5E,aAAO,MAAM,wCAAwC,EAAE,KAAK,MAAM,CAAC;AACnE,YAAM,IAAI,4BAA4B,sBAAsB,GAAG;AAAA,IACjE;AAEA,QAAI,WAAW;AACb,2BAAqB,IAAI,YAAY,QAAQ,UAAU,EAAE,MAAM,CAAC,UAAU;AACxE,eAAO,MAAM,2CAA2C,EAAE,KAAK,MAAM,CAAC;AAAA,MACxE,CAAC;AAAA,IACH;AACA,QAAI,KAAK,KAAK,YAAY;AACxB,YAAM,oBAAoB;AAAA,QACxB,YAAY,KAAK,KAAK;AAAA,QACtB,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries. The production build emits this module into several server\n// chunks, so a consumer's `instanceof` compares against a different copy of the\n// class than the DI-resolved service threw from: the check silently fails, the\n// error escapes the caller's catch, and a deliberate 400/413 surfaces as a 500.\nconst SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = Symbol.for('@open-mercato/ScopedAttachmentUploadError')\n\nexport class ScopedAttachmentUploadError extends Error {\n readonly [SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] = true\n\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\n/**\n * Bundle-safe check for `ScopedAttachmentUploadError`. Prefer this over\n * `instanceof` at every call site \u2014 the class is duplicated across server\n * chunks, so `instanceof` is only reliable inside this module.\n */\nexport function isScopedAttachmentUploadError(error: unknown): error is ScopedAttachmentUploadError {\n return Boolean(error)\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n /**\n * Reject a partition flagged public, so a module-owned upload (documents,\n * warranty claims) never lands where an anonymous reader can reach it. The\n * tenant/organization half of that guarantee is not this flag's job: the\n * partition lookup below already matches only a global partition or one owned\n * by this tenant and organization, whether or not the flag is set.\n */\n requirePrivatePartition?: boolean\n /**\n * Persists a module-owned link row inside the same transaction as the\n * Attachment, so a link failure cannot leave a committed orphan attachment.\n * The callback receives only the generated id, never the entity or the\n * storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new ScopedAttachmentUploadError('partition_unavailable', 403)\n }\n\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await input.persistLink?.(tx, attachmentId)\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n // `persistLink` is where callers run their own authorization (the\n // documents module re-checks the edit capability inside this\n // transaction), so a deliberate HTTP error from it must reach the route\n // with its own status. Flattening it to 500 turns a documented 403 into\n // an apparent server fault.\n if (isCrudHttpError(error)) throw error\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n requestOcrProcessing(em, attachment, driver, storedPath).catch((error) => {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n })\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
5
+ "mappings": "AAAA;AAAA,SAAS,kBAAkB;AAG3B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,sBAAsB,6BAA6B;AAE5D,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,i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Q;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -33,11 +33,14 @@ function resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb) {
33
33
  }
34
34
  return Math.min(defaultMaxBytes, Math.floor(fieldMaxAttachmentSizeMb * 1024 * 1024));
35
35
  }
36
+ function resolveAttachmentMultipartMaxBytes() {
37
+ return resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES;
38
+ }
36
39
  function isMultipartRequestWithinUploadLimit(contentLengthHeader) {
37
40
  if (!contentLengthHeader) return true;
38
41
  const contentLength = Number(contentLengthHeader);
39
- if (!Number.isFinite(contentLength) || contentLength <= 0) return true;
40
- return contentLength <= resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES;
42
+ if (!Number.isSafeInteger(contentLength) || contentLength <= 0) return false;
43
+ return contentLength <= resolveAttachmentMultipartMaxBytes();
41
44
  }
42
45
  class MultipartUploadLimitError extends Error {
43
46
  constructor() {
@@ -78,6 +81,7 @@ export {
78
81
  isMultipartUploadLimitError,
79
82
  parseMultipartFormDataWithinUploadLimit,
80
83
  resolveAttachmentMaxBytes,
84
+ resolveAttachmentMultipartMaxBytes,
81
85
  resolveAttachmentTenantQuotaBytes,
82
86
  resolveDefaultAttachmentMaxUploadBytes,
83
87
  willExceedAttachmentTenantQuota
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/upload-limits.ts"],
4
- "sourcesContent": ["const DEFAULT_ATTACHMENT_MAX_UPLOAD_MB = 25\nconst DEFAULT_ATTACHMENT_TENANT_QUOTA_MB = 512\nconst MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES = 1024 * 1024\nconst ATTACHMENT_MAX_UPLOAD_MB_ENV_KEYS = [\n 'OM_ATTACHMENT_MAX_UPLOAD_MB',\n 'OPENMERCATO_ATTACHMENT_MAX_UPLOAD_MB',\n] as const\nconst ATTACHMENT_TENANT_QUOTA_MB_ENV_KEYS = [\n 'OM_ATTACHMENT_TENANT_QUOTA_MB',\n 'OPENMERCATO_ATTACHMENT_TENANT_QUOTA_MB',\n] as const\n\nfunction readEnvValue(names: readonly string[]): string | undefined {\n return names.map((name) => process.env[name]).find((value) => typeof value === 'string')\n}\n\nfunction parseMegabytesEnv(names: readonly string[], fallbackMb: number): number {\n const raw = readEnvValue(names)\n const parsed = raw ? Number(raw) : NaN\n if (Number.isFinite(parsed) && parsed > 0) {\n return parsed\n }\n return fallbackMb\n}\n\nexport function resolveDefaultAttachmentMaxUploadBytes(): number {\n return Math.floor(parseMegabytesEnv(ATTACHMENT_MAX_UPLOAD_MB_ENV_KEYS, DEFAULT_ATTACHMENT_MAX_UPLOAD_MB) * 1024 * 1024)\n}\n\nexport function resolveAttachmentTenantQuotaBytes(): number {\n return Math.floor(parseMegabytesEnv(ATTACHMENT_TENANT_QUOTA_MB_ENV_KEYS, DEFAULT_ATTACHMENT_TENANT_QUOTA_MB) * 1024 * 1024)\n}\n\nexport function resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb?: number | null): number {\n const defaultMaxBytes = resolveDefaultAttachmentMaxUploadBytes()\n if (typeof fieldMaxAttachmentSizeMb !== 'number' || fieldMaxAttachmentSizeMb <= 0) {\n return defaultMaxBytes\n }\n return Math.min(defaultMaxBytes, Math.floor(fieldMaxAttachmentSizeMb * 1024 * 1024))\n}\n\nexport function isMultipartRequestWithinUploadLimit(contentLengthHeader: string | null): boolean {\n if (!contentLengthHeader) return true\n const contentLength = Number(contentLengthHeader)\n if (!Number.isFinite(contentLength) || contentLength <= 0) return true\n return contentLength <= (resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES)\n}\n\nexport class MultipartUploadLimitError extends Error {\n constructor() {\n super('Multipart request exceeds the maximum upload size.')\n this.name = 'MultipartUploadLimitError'\n }\n}\n\nexport function isMultipartUploadLimitError(error: unknown): error is MultipartUploadLimitError {\n return error instanceof MultipartUploadLimitError\n}\n\nexport async function parseMultipartFormDataWithinUploadLimit(request: Request): Promise<FormData> {\n if (!isMultipartRequestWithinUploadLimit(request.headers.get('content-length'))) {\n throw new MultipartUploadLimitError()\n }\n\n if (!request.body) return request.formData()\n\n const maxBytes = resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES\n let consumedBytes = 0\n const boundedBody = request.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n consumedBytes += chunk.byteLength\n if (consumedBytes > maxBytes) {\n controller.error(new MultipartUploadLimitError())\n return\n }\n controller.enqueue(chunk)\n },\n }))\n const contentType = request.headers.get('content-type')\n const headers = contentType ? { 'content-type': contentType } : undefined\n return new Response(boundedBody, { headers }).formData()\n}\n\nexport function willExceedAttachmentTenantQuota(currentUsageBytes: number, incomingFileBytes: number): boolean {\n return (currentUsageBytes + incomingFileBytes) > resolveAttachmentTenantQuotaBytes()\n}\n"],
5
- "mappings": "AAAA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,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MAAI,CAAC,oCAAoC,QAAQ,QAAQ,IAAI,gBAAgB,CAAC,GAAG;AAC/E,UAAM,IAAI,0BAA0B;AAAA,EACtC;AAEA,MAAI,CAAC,QAAQ,KAAM,QAAO,QAAQ,SAAS;AAE3C,QAAM,WAAW,uCAAuC,IAAI;AAC5D,MAAI,gBAAgB;AACpB,QAAM,cAAc,QAAQ,KAAK,YAAY,IAAI,gBAAwC;AAAA,IACvF,UAAU,OAAO,YAAY;AAC3B,uBAAiB,MAAM;AACvB,UAAI,gBAAgB,UAAU;AAC5B,mBAAW,MAAM,IAAI,0BAA0B,CAAC;AAChD;AAAA,MACF;AACA,iBAAW,QAAQ,KAAK;AAAA,IAC1B;AAAA,EACF,CAAC,CAAC;AACF,QAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc;AACtD,QAAM,UAAU,cAAc,EAAE,gBAAgB,YAAY,IAAI;AAChE,SAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,CAAC,EAAE,SAAS;AACzD;AAEO,SAAS,gCAAgC,mBAA2B,mBAAoC;AAC7G,SAAQ,oBAAoB,oBAAqB,kCAAkC;AACrF;",
4
+ "sourcesContent": ["const DEFAULT_ATTACHMENT_MAX_UPLOAD_MB = 25\nconst DEFAULT_ATTACHMENT_TENANT_QUOTA_MB = 512\nconst MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES = 1024 * 1024\nconst ATTACHMENT_MAX_UPLOAD_MB_ENV_KEYS = [\n 'OM_ATTACHMENT_MAX_UPLOAD_MB',\n 'OPENMERCATO_ATTACHMENT_MAX_UPLOAD_MB',\n] as const\nconst ATTACHMENT_TENANT_QUOTA_MB_ENV_KEYS = [\n 'OM_ATTACHMENT_TENANT_QUOTA_MB',\n 'OPENMERCATO_ATTACHMENT_TENANT_QUOTA_MB',\n] as const\n\nfunction readEnvValue(names: readonly string[]): string | undefined {\n return names.map((name) => process.env[name]).find((value) => typeof value === 'string')\n}\n\nfunction parseMegabytesEnv(names: readonly string[], fallbackMb: number): number {\n const raw = readEnvValue(names)\n const parsed = raw ? Number(raw) : NaN\n if (Number.isFinite(parsed) && parsed > 0) {\n return parsed\n }\n return fallbackMb\n}\n\nexport function resolveDefaultAttachmentMaxUploadBytes(): number {\n return Math.floor(parseMegabytesEnv(ATTACHMENT_MAX_UPLOAD_MB_ENV_KEYS, DEFAULT_ATTACHMENT_MAX_UPLOAD_MB) * 1024 * 1024)\n}\n\nexport function resolveAttachmentTenantQuotaBytes(): number {\n return Math.floor(parseMegabytesEnv(ATTACHMENT_TENANT_QUOTA_MB_ENV_KEYS, DEFAULT_ATTACHMENT_TENANT_QUOTA_MB) * 1024 * 1024)\n}\n\nexport function resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb?: number | null): number {\n const defaultMaxBytes = resolveDefaultAttachmentMaxUploadBytes()\n if (typeof fieldMaxAttachmentSizeMb !== 'number' || fieldMaxAttachmentSizeMb <= 0) {\n return defaultMaxBytes\n }\n return Math.min(defaultMaxBytes, Math.floor(fieldMaxAttachmentSizeMb * 1024 * 1024))\n}\n\nexport function resolveAttachmentMultipartMaxBytes(): number {\n return resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES\n}\n\nexport function isMultipartRequestWithinUploadLimit(contentLengthHeader: string | null): boolean {\n if (!contentLengthHeader) return true\n const contentLength = Number(contentLengthHeader)\n if (!Number.isSafeInteger(contentLength) || contentLength <= 0) return false\n return contentLength <= resolveAttachmentMultipartMaxBytes()\n}\n\nexport class MultipartUploadLimitError extends Error {\n constructor() {\n super('Multipart request exceeds the maximum upload size.')\n this.name = 'MultipartUploadLimitError'\n }\n}\n\nexport function isMultipartUploadLimitError(error: unknown): error is MultipartUploadLimitError {\n return error instanceof MultipartUploadLimitError\n}\n\nexport async function parseMultipartFormDataWithinUploadLimit(request: Request): Promise<FormData> {\n if (!isMultipartRequestWithinUploadLimit(request.headers.get('content-length'))) {\n throw new MultipartUploadLimitError()\n }\n\n if (!request.body) return request.formData()\n\n const maxBytes = resolveDefaultAttachmentMaxUploadBytes() + MULTIPART_CONTENT_LENGTH_OVERHEAD_BYTES\n let consumedBytes = 0\n const boundedBody = request.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n consumedBytes += chunk.byteLength\n if (consumedBytes > maxBytes) {\n controller.error(new MultipartUploadLimitError())\n return\n }\n controller.enqueue(chunk)\n },\n }))\n const contentType = request.headers.get('content-type')\n const headers = contentType ? { 'content-type': contentType } : undefined\n return new Response(boundedBody, { headers }).formData()\n}\n\nexport function willExceedAttachmentTenantQuota(currentUsageBytes: number, incomingFileBytes: number): boolean {\n return (currentUsageBytes + incomingFileBytes) > resolveAttachmentTenantQuotaBytes()\n}\n"],
5
+ "mappings": "AAAA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,0CAA0C,OAAO;AACvD,MAAM,oCAAoC;AAAA,EACxC;AAAA,EACA;AACF;AACA,MAAM,sCAAsC;AAAA,EAC1C;AAAA,EACA;AACF;AAEA,SAAS,aAAa,OAA8C;AAClE,SAAO,MAAM,IAAI,CAAC,SAAS,QAAQ,IAAI,IAAI,CAAC,EAAE,KAAK,CAAC,UAAU,OAAO,UAAU,QAAQ;AACzF;AAEA,SAAS,kBAAkB,OAA0B,YAA4B;AAC/E,QAAM,MAAM,aAAa,KAAK;AAC9B,QAAM,SAAS,MAAM,OAAO,GAAG,IAAI;AACnC,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,GAAG;AACzC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,SAAS,yCAAiD;AAC/D,SAAO,KAAK,MAAM,kBAAkB,mCAAmC,gCAAgC,IAAI,OAAO,IAAI;AACxH;AAEO,SAAS,oCAA4C;AAC1D,SAAO,KAAK,MAAM,kBAAkB,qCAAqC,kCAAkC,IAAI,OAAO,IAAI;AAC5H;AAEO,SAAS,0BAA0B,0BAAkD;AAC1F,QAAM,kBAAkB,uCAAuC;AAC/D,MAAI,O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7G,SAAQ,oBAAoB,oBAAqB,kCAAkC;AACrF;",
6
6
  "names": []
7
7
  }
@@ -23,11 +23,13 @@ function AuditLogsPage() {
23
23
  const [actionsPageSize, setActionsPageSize] = React.useState(DEFAULT_PAGE_SIZE);
24
24
  const [actionsTotal, setActionsTotal] = React.useState(0);
25
25
  const [actionsTotalPages, setActionsTotalPages] = React.useState(1);
26
+ const [actionsTotalIsCapped, setActionsTotalIsCapped] = React.useState(false);
26
27
  const actionsPageSizeRef = React.useRef(DEFAULT_PAGE_SIZE);
27
28
  const [accessPage, setAccessPage] = React.useState(1);
28
29
  const [accessPageSize, setAccessPageSize] = React.useState(DEFAULT_PAGE_SIZE);
29
30
  const [accessTotal, setAccessTotal] = React.useState(0);
30
31
  const [accessTotalPages, setAccessTotalPages] = React.useState(1);
32
+ const [accessTotalIsCapped, setAccessTotalIsCapped] = React.useState(false);
31
33
  const accessPageSizeRef = React.useRef(DEFAULT_PAGE_SIZE);
32
34
  const fetchActions = React.useCallback(async (page, pageSize) => {
33
35
  const params = new URLSearchParams();
@@ -64,6 +66,7 @@ function AuditLogsPage() {
64
66
  });
65
67
  setActionsTotal(actionsRes.total ?? (actionsRes.items?.length ?? 0));
66
68
  setActionsTotalPages(actionsRes.totalPages ?? 1);
69
+ setActionsTotalIsCapped(actionsRes.totalIsCapped === true);
67
70
  setAccessLogs(accessRes.items ?? []);
68
71
  const resolvedPage = accessRes.page ?? accessPageNum;
69
72
  const resolvedPageSize = accessRes.pageSize ?? accessPageSizeNum;
@@ -80,6 +83,7 @@ function AuditLogsPage() {
80
83
  });
81
84
  setAccessTotal(resolvedTotal);
82
85
  setAccessTotalPages(resolvedTotalPages);
86
+ setAccessTotalIsCapped(accessRes.totalIsCapped === true);
83
87
  }, [fetchActions, fetchAccess]);
84
88
  const loadWithState = React.useCallback(async (actionPage, actionPageSize, accessPageNum, accessPageSizeNum) => {
85
89
  setLoading(true);
@@ -168,6 +172,7 @@ function AuditLogsPage() {
168
172
  pageSize: actionsPageSize,
169
173
  total: actionsTotal,
170
174
  totalPages: actionsTotalPages,
175
+ totalIsCapped: actionsTotalIsCapped,
171
176
  onPageChange: handleActionsPageChange
172
177
  }
173
178
  }
@@ -183,6 +188,7 @@ function AuditLogsPage() {
183
188
  pageSize: accessPageSize,
184
189
  total: accessTotal,
185
190
  totalPages: accessTotalPages,
191
+ totalIsCapped: accessTotalIsCapped,
186
192
  onPageChange: handleAccessPageChange
187
193
  }
188
194
  }