better-supabase 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/dist/{agents-CMIB3802.d.ts → agents-CM_cCtcr.d.ts} +4 -4
  2. package/dist/{ai-cache-2LGgaT7F.d.ts → ai-cache-BTGqckta.d.ts} +4 -4
  3. package/dist/{ai-chat-BCaKsvLW.d.ts → ai-chat-B7_vQvxU.d.ts} +4 -4
  4. package/dist/{ai-schedules-yGZH-vQb.d.ts → ai-schedules-CZEfo-_M.d.ts} +5 -5
  5. package/dist/ai-sdk/agents/index.d.ts +6 -6
  6. package/dist/ai-sdk/batches/index.d.ts +3 -3
  7. package/dist/ai-sdk/cache/index.d.ts +1 -1
  8. package/dist/ai-sdk/chat/index.d.ts +1 -1
  9. package/dist/ai-sdk/embeddings/index.d.ts +2 -2
  10. package/dist/ai-sdk/files/index.d.ts +1 -1
  11. package/dist/ai-sdk/index.d.ts +5 -5
  12. package/dist/ai-sdk/mcp/index.d.ts +3 -3
  13. package/dist/ai-sdk/memory/index.d.ts +3 -3
  14. package/dist/ai-sdk/workflow/index.d.ts +3 -3
  15. package/dist/{api-B1OkIWdx.d.ts → api-59rv5hL6.d.ts} +5 -5
  16. package/dist/{api-keys-ClhKBDcc.d.ts → api-keys-JE-aykZE.d.ts} +4 -4
  17. package/dist/{app-tables-62GqZIhd.d.ts → app-tables-yyVncXEt.d.ts} +1 -1
  18. package/dist/{approvals-C5fmPLsH.d.ts → approvals-BfEafAzt.d.ts} +5 -5
  19. package/dist/{assistant-ndGdOBax.d.ts → assistant-B49qATbj.d.ts} +2 -2
  20. package/dist/astro/index.d.ts +7 -7
  21. package/dist/{authorization-BCG1v0iC.d.ts → authorization-CDU9tYA_.d.ts} +17 -3
  22. package/dist/{authorization-hooks-DtzreCAq.d.ts → authorization-hooks-BWhkMZfH.d.ts} +2 -2
  23. package/dist/better-result/index.d.ts +3 -3
  24. package/dist/{bind-C54jD0r3.d.ts → bind-p7asfI6H.d.ts} +7 -7
  25. package/dist/{block-env-CM-LFfj4.d.ts → block-env-B8wG3xeh.d.ts} +4 -4
  26. package/dist/{block-helpers-CRpAHrp_.d.ts → block-helpers-D5emQ2O6.d.ts} +1 -1
  27. package/dist/{block-hooks-DZN2w69m.d.ts → block-hooks-B8itxzEE.d.ts} +2 -2
  28. package/dist/{block-subjects-CphkQPxp.d.ts → block-subjects-C1_9DkSA.d.ts} +1 -1
  29. package/dist/{block-transport-DWZSJrwN.d.ts → block-transport-9EUA3q_I.d.ts} +2 -2
  30. package/dist/blocks/access-requests/index.d.ts +5 -5
  31. package/dist/blocks/activities/index.d.ts +10 -10
  32. package/dist/blocks/activities/index.js +1 -1
  33. package/dist/blocks/agents/index.d.ts +4 -4
  34. package/dist/blocks/ai-cache/index.d.ts +3 -3
  35. package/dist/blocks/ai-chat/index.d.ts +7 -7
  36. package/dist/blocks/ai-files/index.d.ts +3 -3
  37. package/dist/blocks/ai-keys/index.d.ts +4 -4
  38. package/dist/blocks/ai-schedules/index.d.ts +3 -3
  39. package/dist/blocks/announcements/index.d.ts +8 -8
  40. package/dist/blocks/api-keys/index.d.ts +6 -6
  41. package/dist/blocks/approvals/index.d.ts +4 -4
  42. package/dist/blocks/assets/index.d.ts +6 -6
  43. package/dist/blocks/assignment/index.d.ts +7 -7
  44. package/dist/blocks/attachments/index.d.ts +4 -4
  45. package/dist/blocks/audit/index.d.ts +13 -13
  46. package/dist/blocks/automations/index.d.ts +12 -12
  47. package/dist/blocks/billable-time/index.d.ts +6 -6
  48. package/dist/blocks/billing/index.d.ts +9 -9
  49. package/dist/blocks/bookings/index.d.ts +4 -4
  50. package/dist/blocks/bulk/index.d.ts +4 -4
  51. package/dist/blocks/calendar/index.d.ts +5 -5
  52. package/dist/blocks/calendar/index.js +1 -1
  53. package/dist/blocks/catalog/index.d.ts +6 -6
  54. package/dist/blocks/channels/index.d.ts +7 -7
  55. package/dist/blocks/collections/index.d.ts +12 -12
  56. package/dist/blocks/collections/index.js +1 -1
  57. package/dist/blocks/comments/index.d.ts +10 -10
  58. package/dist/blocks/compliance/index.d.ts +5 -5
  59. package/dist/blocks/connectors/index.d.ts +4 -4
  60. package/dist/blocks/contacts/index.d.ts +7 -7
  61. package/dist/blocks/contacts/index.js +1 -1
  62. package/dist/blocks/content/index.d.ts +5 -5
  63. package/dist/blocks/contracts/index.d.ts +6 -6
  64. package/dist/blocks/courses/index.d.ts +5 -5
  65. package/dist/blocks/created-by/index.d.ts +2 -2
  66. package/dist/blocks/custom-fields/index.d.ts +6 -6
  67. package/dist/blocks/data-lifecycle/index.d.ts +8 -8
  68. package/dist/blocks/deals/index.d.ts +6 -6
  69. package/dist/blocks/dispatch/index.d.ts +7 -7
  70. package/dist/blocks/documents/index.d.ts +4 -4
  71. package/dist/blocks/domains/index.d.ts +6 -6
  72. package/dist/blocks/donations/index.d.ts +6 -6
  73. package/dist/blocks/drive/index.d.ts +6 -6
  74. package/dist/blocks/employees/index.d.ts +8 -8
  75. package/dist/blocks/enrichment/index.d.ts +6 -6
  76. package/dist/blocks/enrollments/index.d.ts +6 -6
  77. package/dist/blocks/entitlements/index.d.ts +6 -6
  78. package/dist/blocks/expenses/index.d.ts +5 -5
  79. package/dist/blocks/field-history/index.d.ts +4 -4
  80. package/dist/blocks/flags/index.d.ts +5 -5
  81. package/dist/blocks/forecasts/index.d.ts +6 -6
  82. package/dist/blocks/forms/index.d.ts +6 -6
  83. package/dist/blocks/goals/index.d.ts +4 -4
  84. package/dist/blocks/guests/index.d.ts +6 -6
  85. package/dist/blocks/hiring/index.d.ts +7 -7
  86. package/dist/blocks/identities/index.d.ts +5 -5
  87. package/dist/blocks/imports/index.d.ts +5 -5
  88. package/dist/blocks/inbox/index.d.ts +10 -10
  89. package/dist/blocks/incidents/index.d.ts +5 -5
  90. package/dist/blocks/index.d.ts +9 -9
  91. package/dist/blocks/inventory/index.d.ts +7 -7
  92. package/dist/blocks/invoices/index.d.ts +8 -8
  93. package/dist/blocks/knowledge/index.d.ts +3 -3
  94. package/dist/blocks/lead-scoring/index.d.ts +7 -7
  95. package/dist/blocks/leases/index.d.ts +6 -6
  96. package/dist/blocks/leave/index.d.ts +5 -5
  97. package/dist/blocks/ledger/index.d.ts +6 -6
  98. package/dist/blocks/mail-sync/index.d.ts +5 -5
  99. package/dist/blocks/memberships/index.d.ts +2 -2
  100. package/dist/blocks/memory/index.d.ts +4 -4
  101. package/dist/blocks/messaging/index.d.ts +11 -11
  102. package/dist/blocks/metrics/index.d.ts +6 -6
  103. package/dist/blocks/mfa/index.d.ts +2 -2
  104. package/dist/blocks/moderation/index.d.ts +6 -6
  105. package/dist/blocks/notifications/index.d.ts +12 -12
  106. package/dist/blocks/notifications/index.js +1 -1
  107. package/dist/blocks/numbering/index.d.ts +4 -4
  108. package/dist/blocks/oauth-server/index.d.ts +5 -5
  109. package/dist/blocks/onboarding/index.d.ts +5 -5
  110. package/dist/blocks/orders/index.d.ts +7 -7
  111. package/dist/blocks/organizations/index.d.ts +8 -8
  112. package/dist/blocks/outbox/index.d.ts +4 -4
  113. package/dist/blocks/passes/index.d.ts +8 -8
  114. package/dist/blocks/permissions/index.d.ts +6 -6
  115. package/dist/blocks/pipelines/index.d.ts +6 -6
  116. package/dist/blocks/posts/index.d.ts +5 -5
  117. package/dist/blocks/profiles/index.d.ts +4 -4
  118. package/dist/blocks/promotions/index.d.ts +5 -5
  119. package/dist/blocks/push/index.d.ts +6 -6
  120. package/dist/blocks/queue/index.d.ts +6 -6
  121. package/dist/blocks/quotes/index.d.ts +8 -8
  122. package/dist/blocks/rank/index.d.ts +5 -5
  123. package/dist/blocks/reactions/index.d.ts +9 -9
  124. package/dist/blocks/relations/index.d.ts +7 -7
  125. package/dist/blocks/reminders/index.d.ts +8 -8
  126. package/dist/blocks/reminders/index.js +1 -1
  127. package/dist/blocks/reviews/index.d.ts +5 -5
  128. package/dist/blocks/saved-views/index.d.ts +6 -6
  129. package/dist/blocks/scores/index.d.ts +5 -5
  130. package/dist/blocks/search/index.d.ts +8 -8
  131. package/dist/blocks/security-events/index.d.ts +7 -7
  132. package/dist/blocks/segments/index.d.ts +8 -8
  133. package/dist/blocks/sequences/index.d.ts +6 -6
  134. package/dist/blocks/service-accounts/index.d.ts +5 -5
  135. package/dist/blocks/sessions/index.d.ts +2 -2
  136. package/dist/blocks/settings/index.d.ts +6 -6
  137. package/dist/blocks/share-links/index.d.ts +5 -5
  138. package/dist/blocks/shipments/index.d.ts +6 -6
  139. package/dist/blocks/signatures/index.d.ts +5 -5
  140. package/dist/blocks/signing-keys/index.d.ts +4 -4
  141. package/dist/blocks/sla/index.d.ts +7 -7
  142. package/dist/blocks/sso/index.d.ts +6 -6
  143. package/dist/blocks/state-machine/index.d.ts +5 -5
  144. package/dist/blocks/subjects/index.d.ts +6 -6
  145. package/dist/blocks/tags/index.d.ts +6 -6
  146. package/dist/blocks/tasks/index.d.ts +9 -9
  147. package/dist/blocks/teams/index.d.ts +4 -4
  148. package/dist/blocks/templates/index.d.ts +7 -7
  149. package/dist/blocks/time-tracking/index.d.ts +7 -7
  150. package/dist/blocks/timeline/index.d.ts +8 -8
  151. package/dist/blocks/trash/index.d.ts +6 -6
  152. package/dist/blocks/undo/index.d.ts +4 -4
  153. package/dist/blocks/updated-at/index.d.ts +2 -2
  154. package/dist/blocks/usage/index.d.ts +4 -4
  155. package/dist/blocks/vercel-marketplace/index.d.ts +5 -5
  156. package/dist/blocks/versions/index.d.ts +6 -6
  157. package/dist/blocks/waitlist/index.d.ts +5 -5
  158. package/dist/blocks/webhooks/index.d.ts +14 -14
  159. package/dist/blocks/webhooks/index.js +1 -1
  160. package/dist/blocks/workflow-editor/index.d.ts +9 -9
  161. package/dist/blocks/workflows/index.d.ts +7 -7
  162. package/dist/{bookings-CVw5-Q0Z.d.ts → bookings-xsmM2TA_.d.ts} +3 -3
  163. package/dist/{bucket-vc-QRrva.d.ts → bucket-SvRQwYS4.d.ts} +1 -1
  164. package/dist/chat-sdk/index.d.ts +6 -6
  165. package/dist/cli/add-BdhGOwkB.js +1 -0
  166. package/dist/cli/{add-DUyg9qna.js → add-D4w-Axib.js} +27 -85
  167. package/dist/cli/{add-BKcE_g9D.js → add-Dggyehsy.js} +2 -2
  168. package/dist/cli/{migrate-sVs1QYTM.js → app-table-files-CiGuwLkO.js} +90 -50
  169. package/dist/cli/{backfill-r9RELEEh.js → backfill-DjVjXW_P.js} +4 -4
  170. package/dist/cli/bin.js +1 -1
  171. package/dist/cli/{blocks-DTOFdrxL.js → blocks-Bbmb6W_F.js} +1 -1
  172. package/dist/cli/{blocks-k1OG8XDs.js → blocks-jRL9K1R8.js} +2 -2
  173. package/dist/cli/{cache-Czfw7Iow.js → cache-BuoIFlUJ.js} +1 -1
  174. package/dist/cli/{codemod-ClmbiLuL.js → codemod-DRavXBCb.js} +5 -5
  175. package/dist/cli/{command-CVzTJSLp.js → command-DIPmo0wh.js} +6 -1
  176. package/dist/cli/{completion-DxEXxFpz.js → completion-DxPxMtyP.js} +2 -2
  177. package/dist/cli/{completion-CNCqE-Gb.js → completion-DyLMSjOD.js} +1 -1
  178. package/dist/cli/{completion-Dpk6vh0p.js → completion-FUgqm2-N.js} +2 -2
  179. package/dist/cli/{config-EjNj3HfT.js → config-BfapErxs.js} +1 -1
  180. package/dist/cli/{config-KvV-sLZL.js → config-Cskysxp-.js} +38 -7
  181. package/dist/cli/{config-D2YUlzrl.js → config-Df5cXWNN.js} +1 -1
  182. package/dist/cli/{config-group-C8tjut39.js → config-group-CP-B9uRt.js} +2 -3
  183. package/dist/cli/{content-mapper-ez_mT0d4.js → content-mapper-BCtyfKXl.js} +2 -2
  184. package/dist/cli/{db-uYN6O5Eg.js → db-CWvH1_46.js} +3 -3
  185. package/dist/cli/{doctor-BD9oo4MG.js → doctor-Di2ZekfN.js} +57 -24
  186. package/dist/cli/{env-DEAtgGoj.js → env-B2CbnbzD.js} +2 -2
  187. package/dist/cli/env-CynGCICL.js +1 -0
  188. package/dist/cli/{gen-8Ya8n2sA.js → gen-STKC9vkK.js} +16 -16
  189. package/dist/cli/index.d.ts +9 -2
  190. package/dist/cli/index.js +8 -8
  191. package/dist/cli/{init-DgL3sDfQ.js → init-DW6_nIwj.js} +22 -10
  192. package/dist/cli/{keys-CsanNk-2.js → keys-V-HcO-21.js} +1 -1
  193. package/dist/cli/{live-CMMEct_F.js → live-0G4Plw3K.js} +2 -2
  194. package/dist/cli/{mcp-DEHtzAkq.js → mcp-flKS8iU5.js} +6 -14
  195. package/dist/cli/{metadata-BZh-cOzC.js → metadata-VARUbXEe.js} +3 -3
  196. package/dist/cli/migrate-Bkq07XcT.js +46 -0
  197. package/dist/cli/{migration-safety-ClnYNMdq.js → migration-safety-BfVeza5j.js} +2 -2
  198. package/dist/cli/{migrations-DWh38tO9.js → migrations-BCq7Zs2E.js} +2 -2
  199. package/dist/cli/{module-migration-CXfRJIV4.js → module-migration-lbeUrsYv.js} +2 -2
  200. package/dist/cli/{moved-Cnb4fp49.js → moved-DNOtp9LA.js} +1 -1
  201. package/dist/cli/{parse-BWM6IGhF.js → parse-BPf3kGnc.js} +1 -1
  202. package/dist/cli/{powersync-Dnyr-Wy5.js → powersync-B15CfH5Y.js} +4 -4
  203. package/dist/cli/powersync-DnBsDchT.js +1 -0
  204. package/dist/cli/{print-DJrSr56b.js → print-DjxpBRnv.js} +2 -2
  205. package/dist/cli/{providers-CpaISitn.js → providers-dyxcHQY3.js} +1 -1
  206. package/dist/cli/{remove-ChaieK3t.js → remove-BLq5gbal.js} +7 -7
  207. package/dist/cli/{render-DUNJ4Pss.js → render-CizUf3RW.js} +5 -5
  208. package/dist/cli/{run-CxFDjL1Q.js → run-ChEjR7yw.js} +3 -3
  209. package/dist/cli/{run-Cl9COGuy.js → run-ChOY6s4o.js} +9 -9
  210. package/dist/cli/{run-ChCQPYOh.js → run-MwM__teL.js} +41 -41
  211. package/dist/cli/seed-BOun22-k.js +1 -0
  212. package/dist/cli/{seed-BzVLTdRl.js → seed-CDnL4Tnc.js} +3 -3
  213. package/dist/cli/{shared-5uqc1GBj.js → shared-DV5wIv-7.js} +1 -1
  214. package/dist/cli/{skills-0gz_qjVb.js → skills-DM3oeIxY.js} +1 -1
  215. package/dist/cli/{snapshot-DdAP7LWO.js → snapshot-B5LXkVMC.js} +3 -3
  216. package/dist/cli/{source-2irbWSck.js → source-BoLNG_2A.js} +1 -1
  217. package/dist/cli/{source-args-DAcQt-Mh.js → source-args-v8ljFDfc.js} +1 -1
  218. package/dist/cli/{spec-_MS0ym5r.js → spec-D6QeE2Zx.js} +1 -1
  219. package/dist/cli/{spec-B7n4Rthp.js → spec-Dz-PGCaM.js} +3 -3
  220. package/dist/cli/{sql-layout-DYKkQw1k.js → sql-layout-zo02f3Dm.js} +2 -2
  221. package/dist/cli/{stack-CteM33gC.js → stack-ClESAZYf.js} +1 -1
  222. package/dist/cli/{stack-env-6hS-WEmh.js → stack-env-3ziggrU3.js} +1 -1
  223. package/dist/cli/{sync-DnSOrQuA.js → sync-m-oZ_SyI.js} +4 -4
  224. package/dist/cli/{table-DeH8X0qz.js → table-dyKddjwo.js} +1 -1
  225. package/dist/cli/{upgrade-CWdrC-K3.js → upgrade-C9sgVZ5z.js} +5 -5
  226. package/dist/cli/{upgrade-cMy5fKkg.js → upgrade-WwEJaX3i.js} +3 -3
  227. package/dist/cli/{version-C5RAWmrD.js → version-D2BQuqta.js} +1 -1
  228. package/dist/client/index.d.ts +6 -6
  229. package/dist/client/native/index.d.ts +5 -5
  230. package/dist/{cloud-event-DcJwder2.d.ts → cloud-event-0pQ9vFNS.d.ts} +1 -1
  231. package/dist/{compiler-D3UmE7ao.d.ts → compiler-BEeVWXPS.d.ts} +2 -2
  232. package/dist/{composite-CWJvZgni.d.ts → composite-BJ9s-IJJ.d.ts} +7 -7
  233. package/dist/config/index.d.ts +4 -4
  234. package/dist/config/index.js +3 -3
  235. package/dist/{config-CvJHIy5q.js → config-bqKaPjst.js} +6 -27
  236. package/dist/{config-CTeR7XHK.js → config-r7njjNgh.js} +1 -1
  237. package/dist/{connectors-CHGiffYH.d.ts → connectors-uC5baoFV.d.ts} +4 -4
  238. package/dist/{context-BFEX0b7H.d.ts → context-nbYYjv7U.d.ts} +46 -51
  239. package/dist/{controller-Cl6HmMBk.d.ts → controller-TRocodqG.d.ts} +1 -1
  240. package/dist/{conversion-DlfStnln.d.ts → conversion-g8HzH9My.d.ts} +1 -1
  241. package/dist/create/index.d.ts +3 -3
  242. package/dist/create/index.js +2 -2
  243. package/dist/create/lite/index.d.ts +4 -4
  244. package/dist/create/lite/index.js +1 -1
  245. package/dist/credentials/index.d.ts +4 -4
  246. package/dist/{data-engine-BWoz9lED.d.ts → data-engine-rvbR2C4F.d.ts} +1 -1
  247. package/dist/{define-BLP6XtoL.d.ts → define-D8_9X5fZ.d.ts} +5 -5
  248. package/dist/{define-block-DibVN37N.d.ts → define-block-DWVZSZv1.d.ts} +12 -12
  249. package/dist/{documents-Cup1rpjF.d.ts → documents-BbwYyynk.d.ts} +3 -3
  250. package/dist/edge/index.d.ts +9 -9
  251. package/dist/elysia/index.d.ts +1 -1
  252. package/dist/{embeddings-D_RsS6ow.d.ts → embeddings-I3s5sTDt.d.ts} +1 -1
  253. package/dist/{ended-B8RyuUXF.d.ts → ended-EZzN9QTM.d.ts} +2 -2
  254. package/dist/{entitlements-Y-n4RGAd.d.ts → entitlements-B1i1-wfe.d.ts} +2 -2
  255. package/dist/eve/index.d.ts +5 -5
  256. package/dist/{eve-B7jxYPCw.d.ts → eve-BfhVFV33.d.ts} +2 -2
  257. package/dist/events/index.d.ts +3 -3
  258. package/dist/{events-Cc9DDQWH.d.ts → events-B2qbZps6.d.ts} +1 -1
  259. package/dist/{executor-DNPm13a9.d.ts → executor-BfirBzOr.d.ts} +4 -4
  260. package/dist/{executor-C-Ox9eKq.d.ts → executor-BlS0kCrN.d.ts} +1 -1
  261. package/dist/{executor-hGjrop3A.d.ts → executor-DXQIx4sW.d.ts} +1 -1
  262. package/dist/expo/index.d.ts +4 -4
  263. package/dist/{field-errors-Btn3czyz.d.ts → field-errors-tJvehEFc.d.ts} +10 -10
  264. package/dist/{fields-C3q2ypnO.d.ts → fields-snbaZ14h.d.ts} +1 -1
  265. package/dist/{filter-evaluate-CPxeae5X.d.ts → filter-evaluate-BRpNiNPG.d.ts} +1 -1
  266. package/dist/{filter-query-BXLs72G9.d.ts → filter-query-DBt7OKuH.d.ts} +1 -1
  267. package/dist/{flags-C01PLMJ-.d.ts → flags-DDKTThrO.d.ts} +2 -2
  268. package/dist/flags-sdk/index.d.ts +1 -1
  269. package/dist/{framework-GlxXiotm.d.ts → framework-DVYTtQXA.d.ts} +7 -7
  270. package/dist/{gateway-DzI687yd.d.ts → gateway-Ve7cByEr.d.ts} +3 -3
  271. package/dist/h3/index.d.ts +1 -1
  272. package/dist/h3/v1/index.d.ts +1 -1
  273. package/dist/hono/index.d.ts +9 -9
  274. package/dist/{inbox-NDKwSk_H.d.ts → inbox-c8B86Trp.d.ts} +5 -5
  275. package/dist/{index-DPMVWm_Z.d.ts → index-8US7qlvW.d.ts} +5 -5
  276. package/dist/{index-C_qlBJ3k.d.ts → index-B4wttiLh.d.ts} +4 -4
  277. package/dist/{index-CAY7rIQs.d.ts → index-BKrxynq9.d.ts} +5 -5
  278. package/dist/{index-BfYDY6eh.d.ts → index-BM6NmKSc.d.ts} +5 -5
  279. package/dist/{index-8wOL81rB.d.ts → index-BkzXwuIN.d.ts} +4 -3
  280. package/dist/{index-k-SyCzcQ.d.ts → index-CWAQRWY8.d.ts} +4 -4
  281. package/dist/{index-CQhPHHDF.d.ts → index-Cxsnd-OL.d.ts} +1 -1
  282. package/dist/{index-D1ckLbUM.d.ts → index-pZn6S_iq.d.ts} +1 -1
  283. package/dist/{index-C0_cweyT.d.ts → index-zsgNmE8m.d.ts} +14 -14
  284. package/dist/index.d.ts +6 -6
  285. package/dist/{kit-Dxx3MT8m.d.ts → kit-B8yWCRN7.d.ts} +3 -3
  286. package/dist/{knowledge-F1IhRI4Q.d.ts → knowledge-CsLPACGJ.d.ts} +5 -5
  287. package/dist/lint/index.d.ts +1 -1
  288. package/dist/list/index.d.ts +3 -3
  289. package/dist/{list-query-XHoYDlRN.d.ts → list-query-BcU8NnNL.d.ts} +3 -3
  290. package/dist/mapper/bin.js +6 -6
  291. package/dist/mcp/index.d.ts +6 -6
  292. package/dist/mcp/sdk/index.d.ts +6 -6
  293. package/dist/{messaging-C_Pr9tGx.d.ts → messaging-DQP09JsY.d.ts} +4 -4
  294. package/dist/nestjs/index.d.ts +2 -2
  295. package/dist/next/client/index.d.ts +1 -1
  296. package/dist/next/index.d.ts +103 -28
  297. package/dist/next/index.js +189 -49
  298. package/dist/node/index.d.ts +2 -2
  299. package/dist/{operations-DE7SOBw-.d.ts → operations-CB9atU2e.d.ts} +1 -1
  300. package/dist/{options-C4LuqmdG.js → options-BKBy5wM_.js} +2 -1
  301. package/dist/orpc/index.d.ts +8 -8
  302. package/dist/otel/index.d.ts +2 -2
  303. package/dist/otel/index.js +4 -4
  304. package/dist/{outbox-DxZgoKwp.d.ts → outbox-BZ712Z3X.d.ts} +4 -4
  305. package/dist/{pool-wjbAMqc1.d.ts → pool-DDR1ndk7.d.ts} +3 -3
  306. package/dist/{ports-DP0bthUk.d.ts → ports-hpbyMySO.d.ts} +1 -1
  307. package/dist/postgres/index.d.ts +4 -4
  308. package/dist/{postgrest-z-T0l23T.d.ts → postgrest-AJc8hnJU.d.ts} +1 -1
  309. package/dist/powersync/index.d.ts +6 -6
  310. package/dist/preset/index.d.ts +3 -3
  311. package/dist/preset/index.js +2 -2
  312. package/dist/{preset-DwuWNBip.js → preset-DCdEnJj9.js} +8 -13
  313. package/dist/{project-Bo1vZqVs.js → project-B32wb5J6.js} +4 -4
  314. package/dist/{provider-ClrIplXa.d.ts → provider-CWjzAIX9.d.ts} +1 -1
  315. package/dist/{push-token-v3xCcVU7.d.ts → push-token-DQ1ycFPU.d.ts} +1 -1
  316. package/dist/query/index.d.ts +1 -1
  317. package/dist/react/index.d.ts +8 -8
  318. package/dist/react/native/index.d.ts +1 -1
  319. package/dist/react/server.d.ts +8 -8
  320. package/dist/react/session.d.ts +2 -2
  321. package/dist/react-router/index.d.ts +6 -6
  322. package/dist/realtime/index.d.ts +6 -6
  323. package/dist/realtime/index.js +1 -1
  324. package/dist/{record-form-D2-F4IwS.d.ts → record-form-CubgBrtI.d.ts} +1 -1
  325. package/dist/{recordings-BBSJt_YV.d.ts → recordings-DeZYx-Kv.d.ts} +1 -1
  326. package/dist/records/index.d.ts +9 -9
  327. package/dist/{refresh-CCKB1Wa6.d.ts → refresh-D02Pbf5B.d.ts} +1 -1
  328. package/dist/{refusal-D_tklIEb.d.ts → refusal-B0VmlAxF.d.ts} +2 -2
  329. package/dist/{resolve-Bj1qD7Dy.d.ts → resolve-CtX6T0c0.d.ts} +1 -1
  330. package/dist/{resource-D8pzB5Qf.d.ts → resource-WxN0IsvB.d.ts} +1 -1
  331. package/dist/{resource-execute-BSTIfp1D.d.ts → resource-execute-BzqR8DdD.d.ts} +2 -2
  332. package/dist/{resource-types-D5WEvYtV.d.ts → resource-types-BVbHgTPg.d.ts} +4 -4
  333. package/dist/{resources-CsZ7RhZC.d.ts → resources-BSbRa0Ab.d.ts} +2 -2
  334. package/dist/{respond-BzRG-0qc.d.ts → respond-Dzu_-EPH.d.ts} +1 -1
  335. package/dist/{sales-lines-KxxStRzU.d.ts → sales-lines-BsmrNHe9.d.ts} +1 -1
  336. package/dist/{scores-B2BiNuVJ.d.ts → scores-Y8TvyJi1.d.ts} +5 -5
  337. package/dist/server/index.d.ts +24 -24
  338. package/dist/server/index.js +2 -2
  339. package/dist/{server-types-BlDiY-ya.d.ts → server-types-BkTIxW_H.d.ts} +11 -11
  340. package/dist/{session-BGP98Rgj.d.ts → session-BOzx2qHC.d.ts} +6 -6
  341. package/dist/{session-status-C4t7kbSn.d.ts → session-status-BP8eYVnA.d.ts} +2 -2
  342. package/dist/sign-in-BzihC_8k.d.ts +50 -0
  343. package/dist/{sign-in-NO7LWlw4.js → sign-in-Cyj3ZlFX.js} +120 -25
  344. package/dist/{signers-BKgmVh6A.d.ts → signers-ZmxO1I05.d.ts} +4 -4
  345. package/dist/{signing-keys-BNDUxpQL.d.ts → signing-keys-udgP7Aod.d.ts} +2 -2
  346. package/dist/solid/index.d.ts +10 -10
  347. package/dist/solid-start/index.d.ts +6 -6
  348. package/dist/spec/index.d.ts +2 -2
  349. package/dist/sql/index.d.ts +4 -4
  350. package/dist/sql/index.js +2 -2
  351. package/dist/{sql-B7vBP9g0.js → sql-CyeDg3Yh.js} +321 -212
  352. package/dist/sqlite/index.d.ts +3 -3
  353. package/dist/{sso-B0Txid2-.d.ts → sso-CkU_4mtK.d.ts} +3 -3
  354. package/dist/ssr/index.d.ts +5 -5
  355. package/dist/storage/index.d.ts +3 -3
  356. package/dist/streams/index.d.ts +1 -1
  357. package/dist/{subject-readers-DJbzlm8a.d.ts → subject-readers-CB5Te02u.d.ts} +5 -5
  358. package/dist/{subject-readers-CeeJJOQ4.js → subject-readers-VHcrWhmq.js} +2 -2
  359. package/dist/{subjects-BpIEN1MS.d.ts → subjects-CiBNKy2y.d.ts} +4 -4
  360. package/dist/{support-D7CMbhRT.d.ts → support-BxyPOFk4.d.ts} +4 -4
  361. package/dist/{support-view-CIDXF3_H.d.ts → support-view-nqUWKHEs.d.ts} +1 -1
  362. package/dist/svelte/index.d.ts +9 -9
  363. package/dist/sveltekit/index.d.ts +7 -7
  364. package/dist/{tags-Dg4Ywmqp.d.ts → tags-Cm48BsOa.d.ts} +1 -1
  365. package/dist/tanstack-db/index.d.ts +3 -3
  366. package/dist/tanstack-start/index.d.ts +6 -6
  367. package/dist/{tenant-CyLEXgot.d.ts → tenant-C9YE_kqK.d.ts} +2 -2
  368. package/dist/testing/index.d.ts +25 -25
  369. package/dist/testing/index.js +1 -1
  370. package/dist/{timeline-Cjl-1hiA.d.ts → timeline-DvXtXq5q.d.ts} +5 -5
  371. package/dist/{topic-B_DGdAEs.d.ts → topic-breZqx_4.d.ts} +5 -5
  372. package/dist/{types-Dp3UCr1e.d.ts → types-B-D6fYx2.d.ts} +1 -1
  373. package/dist/{types-DF8JYEf5.d.ts → types-C3I7S51U.d.ts} +2 -2
  374. package/dist/{types-Czq9Xtpa.d.ts → types-CK2X2wCB.d.ts} +5 -5
  375. package/dist/{types-DFdg_4yN.d.ts → types-CPl9uJ0G.d.ts} +2 -2
  376. package/dist/{types-DR1MHh7N.d.ts → types-CwQgFo8c.d.ts} +4 -4
  377. package/dist/{types-Dr9wZgNy.d.ts → types-DMihLukJ.d.ts} +3 -3
  378. package/dist/{types-A4yyKEsg.d.ts → types-iCyZ3lMx.d.ts} +4 -4
  379. package/dist/{types-BdaBfYIw.d.ts → types-nspa5I-a.d.ts} +7 -7
  380. package/dist/{undo-B1jwnVyN.d.ts → undo-0HkWXASn.d.ts} +2 -2
  381. package/dist/{usage-Dp45V42p.d.ts → usage-BkWAPkg2.d.ts} +4 -4
  382. package/dist/{vault-BghaujrZ.d.ts → vault-BkdPmL7f.d.ts} +2 -2
  383. package/dist/vercel-connect/index.d.ts +1 -1
  384. package/dist/{verify-CI8LgSpv.d.ts → verify-41mZmspj.d.ts} +2 -2
  385. package/dist/{view-BvNA7EOC.d.ts → view-C8_xvD-j.d.ts} +1 -1
  386. package/dist/vue/index.d.ts +10 -10
  387. package/dist/{watch-topic-1zIAtiNM.d.ts → watch-topic-ItO3dz8m.d.ts} +1 -1
  388. package/dist/workflow-sdk/builder/index.d.ts +3 -3
  389. package/dist/workflow-sdk/index.d.ts +1 -1
  390. package/dist/workflow-sdk/world/index.d.ts +1 -1
  391. package/dist/workflow-sdk/world/index.js +1 -1
  392. package/dist/{workflow-sdk-CaEw822d.js → workflow-sdk-BWPsdzVK.js} +36 -8
  393. package/dist/{workflow-sdk-BNsZrcVg.d.ts → workflow-sdk-rg3IbCZC.d.ts} +3 -3
  394. package/dist/{workflows-B0ZPAQu0.d.ts → workflows-xL6t0TXx.d.ts} +7 -4
  395. package/dist/yjs/index.d.ts +2 -2
  396. package/package.json +1 -2
  397. package/schemas/config-v1.json +5 -352
  398. package/schemas/doctor-report-v1.json +1 -0
  399. package/skills/better-supabase/references/ui-recipes.md +5 -5
  400. package/skills/better-supabase-auth/SKILL.md +8 -1
  401. package/dist/cli/add-pDOlqWUa.js +0 -1
  402. package/dist/cli/env-Cy2lWBRC.js +0 -1
  403. package/dist/cli/powersync-DURhWDVc.js +0 -1
  404. package/dist/cli/seed-BJ7c-ktX.js +0 -1
  405. package/dist/sign-in-CAadgm33.d.ts +0 -24
@@ -12,7 +12,7 @@ import { t as isSqlType } from "./sql-type-iUSZpaUu.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-Drgg3v2J.js";
13
13
  import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-CTDNuxRv.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DKVQDz4o.js";
15
- import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-CaEw822d.js";
15
+ import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-BWPsdzVK.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-CfVPctAw.js";
17
17
  import { t as accessRequestsSqlOptions } from "./options-gUvfr3no.js";
18
18
  import { t as activitiesSqlOptions } from "./options-sU_zGkiV.js";
@@ -32,7 +32,7 @@ import { t as automationsSqlOptions } from "./options-DcHl59RC.js";
32
32
  import { t as billingSqlOptions } from "./options-DZHZYlpD.js";
33
33
  import { t as bookingsSqlOptions } from "./options-CZDmtsbV.js";
34
34
  import { t as bulkSqlOptions } from "./options-CTl8T88w.js";
35
- import { t as calendarSqlOptions } from "./options-C4LuqmdG.js";
35
+ import { t as calendarSqlOptions } from "./options-BKBy5wM_.js";
36
36
  import { t as catalogSqlOptions } from "./options-D0sj5abR.js";
37
37
  import { t as collectionsSqlOptions } from "./options-CyjL9lTf.js";
38
38
  import { t as commentsSqlOptions } from "./options-CoSPgWKy.js";
@@ -2564,6 +2564,22 @@ function valueMethods(input) {
2564
2564
  return `${sqlString(name)}, ${readValue(mapOf(table, logical), `${alias}.${sqlIdent(name)}`)}`;
2565
2565
  }).join(", ")})`;
2566
2566
  },
2567
+ rowJson(table, alias, options = {}) {
2568
+ const pairs = Object.entries(tables[table]?.columns ?? {}).flatMap(([logical, name]) => {
2569
+ const app = input.mapped(table, logical);
2570
+ const own = input.own(name);
2571
+ const labelled = changes(table, logical);
2572
+ if (app === null || app === own && !labelled) return [];
2573
+ const value = `${alias}.${sqlIdent(app)}`;
2574
+ const as = options.as?.[logical];
2575
+ if (labelled) {
2576
+ const label = readValue(mapOf(table, logical), value);
2577
+ return [...app === own ? [] : [`${sqlString(app)}, ${label}`], `${sqlString(own)}, ${label}`];
2578
+ }
2579
+ return [`${sqlString(own)}, ${as === void 0 ? value : as(value)}`];
2580
+ });
2581
+ return pairs.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${pairs.join(", ")}))`;
2582
+ },
2567
2583
  mapsValues: changes
2568
2584
  };
2569
2585
  }
@@ -2906,7 +2922,9 @@ function createModuleContext(module, namesOf, source = {}) {
2906
2922
  tables: names.tables,
2907
2923
  maps: checkedValueMaps(where, config.values, names.tables),
2908
2924
  cast: owned.cast,
2909
- column: requiredColumn
2925
+ column: requiredColumn,
2926
+ mapped: (table, logical) => config.tables[table] === null ? null : column(table, logical),
2927
+ own: (name) => naming.rename(name)
2910
2928
  }),
2911
2929
  names,
2912
2930
  installedModules: [...installed],
@@ -4943,12 +4961,12 @@ const ACCESS_REQUESTS = {
4943
4961
  };
4944
4962
  //#endregion
4945
4963
  //#region src/core/subject-permission.ts
4946
- /** A `config.records.<type>.permissions` entry as its parts. */
4964
+ /** A `config.subjects.<type>.permissions` entry as its parts. */
4947
4965
  function subjectPermissionOf(value) {
4948
4966
  return typeof value === "string" ? { key: value } : value;
4949
4967
  }
4950
4968
  /**
4951
- * The tenant permission key of a `config.records.<type>.permissions` entry, or
4969
+ * The tenant permission key of a `config.subjects.<type>.permissions` entry, or
4952
4970
  * `undefined` when the action is granted only per row or to an owner.
4953
4971
  */
4954
4972
  function subjectPermissionKey(value) {
@@ -4957,12 +4975,12 @@ function subjectPermissionKey(value) {
4957
4975
  //#endregion
4958
4976
  //#region src/sql/subject-registry.ts
4959
4977
  const TYPE$5 = SUBJECT_TYPE_PATTERN;
4960
- const COLUMN$9 = /^[a-z_][a-z0-9_]{0,62}$/;
4978
+ const COLUMN$10 = /^[a-z_][a-z0-9_]{0,62}$/;
4961
4979
  const ID_TYPE$2 = /^[a-z][a-z0-9_ ]{0,62}$/;
4962
4980
  const ACTION = /^[a-z][a-z0-9_.-]{0,62}$/;
4963
4981
  const PLACEHOLDER$1 = /\{([^}]*)\}/g;
4964
4982
  function column$2(where, value) {
4965
- if (typeof value !== "string" || !COLUMN$9.test(value)) throw new TypeError(`${where} must be a column name`);
4983
+ if (typeof value !== "string" || !COLUMN$10.test(value)) throw new TypeError(`${where} must be a column name`);
4966
4984
  return value;
4967
4985
  }
4968
4986
  const RESOURCE = /^[a-z][a-z0-9_]{0,62}$/;
@@ -5022,7 +5040,7 @@ function checkPermission(where, action, value) {
5022
5040
  if (key === void 0 && owner === void 0) throw new TypeError(`${where} needs a key or an owner column`);
5023
5041
  }
5024
5042
  /**
5025
- * `config.records`, checked: every entry with its table split and quoted. A
5043
+ * `config.subjects`, checked: every entry with its table split and quoted. A
5026
5044
  * subject without `tenant` gets the tenant column `naming` names
5027
5045
  * (`organization_id`, or `workspace_id` for
5028
5046
  * `blocks.memberships.names.organization: workspace`).
@@ -5078,8 +5096,9 @@ function registeredSubjects(subjects, naming = tenantNames()) {
5078
5096
  }
5079
5097
  /**
5080
5098
  * The tenant column of `table` (`schema.table`, or a table in `public`): the
5081
- * `tenant` of the `config.records` entry for that table, else the tenant column
5082
- * `naming` names. `undefined` when the entry says the table has no tenant.
5099
+ * `tenant` of the `config.subjects` entry for that table, else the tenant
5100
+ * column `naming` names. `undefined` when the entry says the table has no
5101
+ * tenant.
5083
5102
  */
5084
5103
  function tenantColumnOf(table, subjects, naming = tenantNames()) {
5085
5104
  const qualify = (name) => name.includes(".") ? name : `public.${name}`;
@@ -5138,9 +5157,9 @@ function urlExpression(template, alias = "s") {
5138
5157
  //#region src/sql/subject-check-sql.ts
5139
5158
  /**
5140
5159
  * SQL that is true when `type`/`id` (text expressions) names a record in
5141
- * `config.records` that belongs to tenant `tenant` and that the caller can read
5142
- * through `can_subject`. Types without a tenant column never match. The module
5143
- * must require `subjects`.
5160
+ * `config.subjects` that belongs to tenant `tenant` and that the caller can
5161
+ * read through `can_subject`. Types without a tenant column never match. The
5162
+ * module must require `subjects`.
5144
5163
  */
5145
5164
  function subjectInTenant(ctx, type, id, tenant) {
5146
5165
  const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
@@ -5152,7 +5171,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then exists (
5152
5171
  end and ${canSubject}(${type}, ${id}, 'read'))`;
5153
5172
  }
5154
5173
  /**
5155
- * SQL for the tenant (as text) of record `type`/`id` in `config.records`, or
5174
+ * SQL for the tenant (as text) of record `type`/`id` in `config.subjects`, or
5156
5175
  * null for an unknown record or type. Reads the table directly, so use it in
5157
5176
  * security definer code after checking the caller.
5158
5177
  */
@@ -5165,7 +5184,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select
5165
5184
  end)`;
5166
5185
  }
5167
5186
  /**
5168
- * SQL for the title (as text) of record `type`/`id` in `config.records`, from
5187
+ * SQL for the title (as text) of record `type`/`id` in `config.subjects`, from
5169
5188
  * the entry's `title` column, or null for an unknown record or a type without
5170
5189
  * one. Reads the table directly, so check the caller first.
5171
5190
  */
@@ -7763,13 +7782,13 @@ function rawSubjects(ctx, where, extraKeys, allow) {
7763
7782
  return Object.fromEntries(Object.entries(registry).filter(([, entry]) => tenantless || entry.tenant !== false).map(([type, entry]) => [type, fromRegistry(entry, extraKeys)]));
7764
7783
  }
7765
7784
  if (Array.isArray(raw)) {
7766
- if (raw.length === 0) throw new TypeError(`${where}: list at least one config.records type, or pass an object of subject type to { table, ... }`);
7785
+ if (raw.length === 0) throw new TypeError(`${where}: list at least one config.subjects type, or pass an object of subject type to { table, ... }`);
7767
7786
  return Object.fromEntries(raw.map((type) => {
7768
- if (typeof type !== "string" || !Object.hasOwn(registry, type)) throw new TypeError(`${where}: "${String(type)}" is not a subject type in config.records. Types: ${Object.keys(registry).join(", ") || "none"}`);
7787
+ if (typeof type !== "string" || !Object.hasOwn(registry, type)) throw new TypeError(`${where}: "${String(type)}" is not a subject type in config.subjects. Types: ${Object.keys(registry).join(", ") || "none"}`);
7769
7788
  return [type, fromRegistry(registry[type], extraKeys)];
7770
7789
  }));
7771
7790
  }
7772
- if (!isRecord$1(raw)) throw new TypeError(`${where}: pass a list of config.records types, or an object of subject type to { table, id?, tenant?, permission?, cascade? }`);
7791
+ if (!isRecord$1(raw)) throw new TypeError(`${where}: pass a list of config.subjects types, or an object of subject type to { table, id?, tenant?, permission?, cascade? }`);
7773
7792
  return Object.fromEntries(Object.entries(raw).map(([type, entry]) => {
7774
7793
  const registered = Object.hasOwn(registry, type) ? registry[type] : void 0;
7775
7794
  return [type, registered && isRecord$1(entry) ? {
@@ -7801,7 +7820,7 @@ function registeredRead(entry, permission) {
7801
7820
  /**
7802
7821
  * `blocks.<instance>.on`: subject type to `{ table, id?, tenant?, permission?,
7803
7822
  * cascade? }` plus the `extra` keys the module reads, falling back to the
7804
- * app-wide `config.records` registry.
7823
+ * app-wide `config.subjects` registry.
7805
7824
  */
7806
7825
  function subjectsOption(ctx, extraKeys = [], allow = {}) {
7807
7826
  const where = `blocks.${ctx.instance}.on`;
@@ -7840,8 +7859,8 @@ function subjectsOption(ctx, extraKeys = [], allow = {}) {
7840
7859
  }
7841
7860
  /**
7842
7861
  * The record types `blocks.<instance>.on` allows, checked against
7843
- * `config.records`, or `undefined` when `on` is unset and every registered type
7844
- * is allowed.
7862
+ * `config.subjects`, or `undefined` when `on` is unset and every registered
7863
+ * type is allowed.
7845
7864
  */
7846
7865
  function allowedSubjectTypes(ctx) {
7847
7866
  return ctx.on === void 0 ? void 0 : subjectsOption(ctx).map(([type]) => type);
@@ -7975,7 +7994,7 @@ function subjectReadable(ctx, subjects, args, options = {}) {
7975
7994
  }
7976
7995
  /**
7977
7996
  * Whether the caller may take `action` on subject `type`/`id`, for each of
7978
- * `subjects` whose `config.records` entry declares it (the first of `actions`
7997
+ * `subjects` whose `config.subjects` entry declares it (the first of `actions`
7979
7998
  * it declares): `can_subject(type, id, action)` as the caller, so a key, the
7980
7999
  * provider's per-row grants and an owner column all count. Other types pass.
7981
8000
  * `undefined` when no subject declares one of `actions` or the `subjects`
@@ -8453,8 +8472,8 @@ const NAMES$114 = {
8453
8472
  }
8454
8473
  } }
8455
8474
  };
8456
- const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
8457
- const isColumn = (value) => typeof value === "string" && COLUMN$8.test(value);
8475
+ const COLUMN$9 = /^[a-z_][a-z0-9_]*$/;
8476
+ const isColumn = (value) => typeof value === "string" && COLUMN$9.test(value);
8458
8477
  const isColumnList$1 = (value) => Array.isArray(value) && value.every(isColumn);
8459
8478
  const isChildInput = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8460
8479
  function childrenOf(value, where) {
@@ -9640,7 +9659,7 @@ $$;
9640
9659
  ${userGrant(`${fn("subject_titles")}(jsonb)`)}
9641
9660
 
9642
9661
  -- True when the caller can see the subject row and, for an action with a
9643
- -- key in config.records.<type>.permissions, holds that key in the
9662
+ -- key in config.subjects.<type>.permissions, holds that key in the
9644
9663
  -- subject's tenant (or on the record, through the subject's scope).
9645
9664
  create or replace function ${fn("can_subject")}(subject_type text, subject_id text, action text)
9646
9665
  returns boolean
@@ -9703,7 +9722,7 @@ ${userGrant(`${fn("record_summary")}(text, text, text[], timestamptz)`)}
9703
9722
 
9704
9723
  -- can_subject for another user, for server code that decides who receives
9705
9724
  -- an event. It reads the row past its policies and asks can_user for the
9706
- -- action's key in config.records.<type>.permissions, so an action without
9725
+ -- action's key in config.subjects.<type>.permissions, so an action without
9707
9726
  -- a key is false and a share-link grant never counts. A provider that
9708
9727
  -- can't answer for others (no idsWithFor) gives false.
9709
9728
  create or replace function ${fn("can_subject_for")}(member uuid, subject_type text, subject_id text, action text)
@@ -9864,7 +9883,7 @@ const SUBJECTS = {
9864
9883
  name: "subjects",
9865
9884
  scopes: ["tenant"],
9866
9885
  title: "Subjects",
9867
- description: "The app-wide subject registry from config.records: subject_title, subject_url, subject_titles, can_subject, can_subject_for and record_summary for every registered type, my_work across the installed blocks, and Realtime presence on presence:<type>:<id> for readers of the subject.",
9886
+ description: "The app-wide subject registry from config.subjects: subject_title, subject_url, subject_titles, can_subject, can_subject_for and record_summary for every registered type, my_work across the installed blocks, and Realtime presence on presence:<type>:<id> for readers of the subject.",
9868
9887
  requires: ["permissions"],
9869
9888
  target: "schema",
9870
9889
  modes: ["managed", "custom"],
@@ -13294,7 +13313,7 @@ function blockSubjects(ctx) {
13294
13313
  /**
13295
13314
  * Whether the subject a new link names exists in the link's tenant and the
13296
13315
  * caller may share it. Block-owned types come first; registered subjects
13297
- * (`config.records` or `on`) check the row's tenant and the subject's read
13316
+ * (`config.subjects` or `on`) check the row's tenant and the subject's read
13298
13317
  * permission. Any other type fails.
13299
13318
  */
13300
13319
  function subjectCheck(ctx) {
@@ -23004,7 +23023,7 @@ ${userGrant(`${ctx.fn("revert_audit_entries")}(text[])`)}`;
23004
23023
  //#endregion
23005
23024
  //#region src/sql/modules/audit-subjects.ts
23006
23025
  const HEADER = /^[a-z0-9-]+$/;
23007
- const COLUMN$7 = /^[a-z_][a-z0-9_]*$/;
23026
+ const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
23008
23027
  const CLAIM = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$/i;
23009
23028
  const UUID$3 = "'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'";
23010
23029
  /**
@@ -23076,7 +23095,7 @@ function subjectColumns$1(ctx, taken) {
23076
23095
  if (raw === void 0) return [];
23077
23096
  if (!isRecord$1(raw)) throw new TypeError(`${where} must map column names to { type, from }`);
23078
23097
  return Object.entries(raw).map(([name, entry]) => {
23079
- if (!COLUMN$7.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23098
+ if (!COLUMN$8.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23080
23099
  if (taken.includes(name)) throw new TypeError(`${where}: "${name}" is already a column of the audit log`);
23081
23100
  const type = isRecord$1(entry) ? entry["type"] : void 0;
23082
23101
  const from = isRecord$1(entry) ? entry["from"] ?? name : void 0;
@@ -25751,12 +25770,12 @@ const RULES = {
25751
25770
  };
25752
25771
  //#endregion
25753
25772
  //#region src/sql/subject-columns.ts
25754
- const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/u;
25773
+ const COLUMN$7 = /^[a-z_][a-z0-9_]{0,62}$/u;
25755
25774
  function boundSubjects$1(subjects, where) {
25756
25775
  return subjects.flatMap(([type, subject]) => {
25757
25776
  const column = subject.extra["column"];
25758
25777
  if (column === void 0) return [];
25759
- if (typeof column !== "string" || !COLUMN$6.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25778
+ if (typeof column !== "string" || !COLUMN$7.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25760
25779
  return [{
25761
25780
  type,
25762
25781
  column,
@@ -29816,6 +29835,31 @@ function appFunction(value, key) {
29816
29835
  if (typeof value !== "string" || !QUALIFIED$1.test(value)) throw new TypeError(`blocks.calendar.options.accessFunctions.${key} must be a schema-qualified function name, such as public.can_read_calendar`);
29817
29836
  return value.split(".").map(sqlIdent).join(".");
29818
29837
  }
29838
+ const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/;
29839
+ function ruleDialect(ctx) {
29840
+ const raw = ctx.option("ruleDialect");
29841
+ const at = "blocks.calendar.options.ruleDialect";
29842
+ if (raw === void 0) return {
29843
+ lower: false,
29844
+ scalarMonthDay: false
29845
+ };
29846
+ if (!isRecord$1(raw) || ctx.owns("rules") || ctx.has("rules", "rrule")) throw new TypeError(`${at} takes { weekdays, monthDay, ordinal } and needs your own rules table with columns.rules.rrule mapped to null`);
29847
+ const { weekdays = "upper", monthDay = "list", ordinal } = raw;
29848
+ if (weekdays !== "upper" && weekdays !== "lower" || monthDay !== "list" && monthDay !== "scalar") throw new TypeError(`${at}: weekdays is "upper" or "lower", monthDay is "list" or "scalar"`);
29849
+ if (ordinal === void 0) return {
29850
+ lower: weekdays === "lower",
29851
+ scalarMonthDay: monthDay === "scalar"
29852
+ };
29853
+ if (!isRecord$1(ordinal) || typeof ordinal["weekday"] !== "string" || typeof ordinal["position"] !== "string" || !COLUMN$6.test(ordinal["weekday"]) || !COLUMN$6.test(ordinal["position"])) throw new TypeError(`${at}.ordinal takes { weekday, position }, two column names of the rules table`);
29854
+ return {
29855
+ lower: weekdays === "lower",
29856
+ scalarMonthDay: monthDay === "scalar",
29857
+ ordinal: {
29858
+ weekday: sqlIdent(ordinal["weekday"]),
29859
+ position: sqlIdent(ordinal["position"])
29860
+ }
29861
+ };
29862
+ }
29819
29863
  function calendarFeatures(ctx) {
29820
29864
  const access = ctx.flag("access", false);
29821
29865
  const functions = ctx.option("accessFunctions");
@@ -29825,6 +29869,7 @@ function calendarFeatures(ctx) {
29825
29869
  const attendeeKey = ctx.text("attendeeKey", "email");
29826
29870
  if (attendeeKey !== "email" && attendeeKey !== "any") throw new TypeError("blocks.calendar.options.attendeeKey must be \"email\" or \"any\"");
29827
29871
  const table = recurrence === "table";
29872
+ if (ctx.option("ruleDialect") !== void 0) ruleDialect(ctx);
29828
29873
  if (table && (!ctx.hasTable("rules") || !ctx.hasTable("recurrenceDates"))) throw new TypeError("blocks.calendar.options.recurrence \"table\" needs the rules and recurrenceDates tables");
29829
29874
  const readFn = isRecord$1(functions) ? appFunction(functions["read"], "read") : void 0;
29830
29875
  const writeFn = isRecord$1(functions) ? appFunction(functions["write"], "write") : void 0;
@@ -30083,13 +30128,18 @@ ${userGrant(`${ctx.fn("list_calendar_grants")}(uuid)`)}
30083
30128
  function ruleText(ctx) {
30084
30129
  const r = (column) => `r.${ctx.col("rules", column)}`;
30085
30130
  if (ctx.has("rules", "rrule")) return r("rrule");
30131
+ const dialect = ruleDialect(ctx);
30086
30132
  const list = (key, column) => ctx.has("rules", column) ? [`'${key}=' || nullif(translate(${r(column)}::text, '{}" ', ''), '')`] : [];
30133
+ const days = ctx.has("rules", "byDay") ? `nullif(translate(${dialect.lower ? `upper(${r("byDay")}::text)` : `${r("byDay")}::text`}, '{}" ', ''), '')` : void 0;
30134
+ const ordinal = dialect.ordinal === void 0 ? void 0 : `r.${dialect.ordinal.position}::text || upper(r.${dialect.ordinal.weekday}::text)`;
30135
+ const dayParts = [days, ordinal].filter((part) => part !== void 0);
30136
+ const byDay = dialect.lower || ordinal !== void 0 ? dayParts.length === 0 ? [] : [`'BYDAY=' || ${dayParts.length === 1 ? dayParts[0] : `coalesce(${dayParts.join(", ")})`}`] : list("BYDAY", "byDay");
30087
30137
  return `nullif(concat_ws(';', ${[
30088
30138
  `'FREQ=' || upper(${ctx.label("rules", "freq", r("freq"))})`,
30089
30139
  ...ctx.has("rules", "interval") ? [`'INTERVAL=' || ${r("interval")}`] : [],
30090
30140
  ...ctx.has("rules", "count") ? [`'COUNT=' || ${r("count")}`] : [],
30091
30141
  ...ctx.has("rules", "until") ? [`'UNTIL=' || to_char(${r("until")}::timestamptz at time zone 'UTC', 'YYYYMMDD"T"HH24MISS"Z"')`] : [],
30092
- ...list("BYDAY", "byDay"),
30142
+ ...byDay,
30093
30143
  ...list("BYMONTHDAY", "byMonthDay"),
30094
30144
  ...list("BYMONTH", "byMonth"),
30095
30145
  ...list("BYSETPOS", "bySetPos")
@@ -30153,12 +30203,16 @@ function insertRule(ctx, id, tenant, source) {
30153
30203
  add("interval", () => `(${part("INTERVAL", "[0-9]+")})::integer`);
30154
30204
  add("count", () => `(${part("COUNT", "[0-9]+")})::integer`);
30155
30205
  add("until", () => `case when ${part("UNTIL")} is null then null else to_timestamp(rpad(translate(${part("UNTIL")}, 'TZ', ''), 14, '0'), 'YYYYMMDDHH24MISS')::timestamp at time zone 'UTC' end`);
30156
- for (const [column, key] of [
30157
- ["byDay", "BYDAY"],
30158
- ["byMonthDay", "BYMONTHDAY"],
30159
- ["byMonth", "BYMONTH"],
30160
- ["bySetPos", "BYSETPOS"]
30161
- ]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30206
+ const dialect = ruleDialect(ctx);
30207
+ const ordinalDay = `substring(upper(${source}) from '(?:^|;)BYDAY=([+-]?[0-9]+)[A-Z]{2}(?:;|$)')`;
30208
+ const weekdays = (value) => dialect.lower ? `lower(${value})` : value;
30209
+ add("byDay", () => ctx.cast("rules", "byDay", dialect.ordinal === void 0 ? `'{' || ${weekdays(part("BYDAY"))} || '}'` : `case when ${ordinalDay} is null then '{' || ${weekdays(part("BYDAY"))} || '}' end`));
30210
+ add("byMonthDay", () => ctx.cast("rules", "byMonthDay", dialect.scalarMonthDay ? part("BYMONTHDAY", "-?[0-9]+") : `'{' || ${part("BYMONTHDAY")} || '}'`));
30211
+ for (const [column, key] of [["byMonth", "BYMONTH"], ["bySetPos", "BYSETPOS"]]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30212
+ if (dialect.ordinal !== void 0) {
30213
+ columns.push(dialect.ordinal.position, dialect.ordinal.weekday);
30214
+ values.push(`(${ordinalDay})::integer`, weekdays(`substring(upper(${source}) from '(?:^|;)BYDAY=[+-]?[0-9]+([A-Z]{2})(?:;|$)')`));
30215
+ }
30162
30216
  }
30163
30217
  return `insert into ${rules} (${columns.join(", ")}) values (${values.join(", ")});`;
30164
30218
  }
@@ -31526,7 +31580,8 @@ const CALENDAR_NAMES = {
31526
31580
  "recurrence",
31527
31581
  "rdates",
31528
31582
  "attendeeKey",
31529
- "calendarDetails"
31583
+ "calendarDetails",
31584
+ "ruleDialect"
31530
31585
  ],
31531
31586
  tables: {
31532
31587
  calendars: {
@@ -31689,6 +31744,7 @@ const CALENDAR_NAMES = {
31689
31744
  bySetPos: "by_set_pos"
31690
31745
  },
31691
31746
  optional: [
31747
+ "id",
31692
31748
  "tenant",
31693
31749
  "rrule",
31694
31750
  "freq",
@@ -32762,7 +32818,7 @@ begin
32762
32818
  if exists (select 1 from ${ledger.table("accounts")} x join ${ledger.table("entries")} y on y.${le("account")} = x.${la("id")}
32763
32819
  where x.${la("tenant")} = v_tenant and x.${la("managedBy")} = 'inventory' and x.${la("kind")} = 'stock'
32764
32820
  and x.${la("metadata")} ->> 'locationId' = delete_location.location::text)
32765
- or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and x.${r("status")} = 'active') then
32821
+ or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])}) then
32766
32822
  ${fail$1("INVENTORY_LOCATION_IN_USE", "the location has stock history; deactivate it instead", "23503")}
32767
32823
  end if;
32768
32824
  delete from ${locations} x where x.${l("id")} = delete_location.location;
@@ -32960,9 +33016,9 @@ begin
32960
33016
  ])}
32961
33017
  ${lockLevel(ctx, "reserve_stock.variant", "reserve_stock.location")}
32962
33018
  with expired as (
32963
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now()
33019
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now()
32964
33020
  where x.${r("variant")} = reserve_stock.variant and x.${r("location")} = reserve_stock.location
32965
- and x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33021
+ and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
32966
33022
  returning x.${r("quantity")} as quantity
32967
33023
  )
32968
33024
  update ${levels} x set ${lv("reserved")} = greatest(x.${lv("reserved")} - (select coalesce(sum(e.quantity), 0)::integer from expired e), 0)
@@ -33011,7 +33067,7 @@ declare
33011
33067
  v_movement uuid;
33012
33068
  begin
33013
33069
  select x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33014
- x.${r("quantity")} as quantity, x.${r("status")} as status, x.${r("expiresAt")} as expires_at,
33070
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status, x.${r("expiresAt")} as expires_at,
33015
33071
  x.${r("referenceType")} as reference_type, x.${r("referenceId")} as reference_id
33016
33072
  into v_row from ${reservations} x where x.${r("id")} = commit_reservation.reservation for update;
33017
33073
  if not found then
@@ -33025,7 +33081,7 @@ begin
33025
33081
  ${fail$1("INVENTORY_RESERVATION_EXPIRED", "the reservation has expired", "55000")}
33026
33082
  end if;
33027
33083
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33028
- update ${reservations} x set ${r("status")} = 'committed', ${r("updatedAt")} = now()
33084
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "committed")}, ${r("updatedAt")} = now()
33029
33085
  where x.${r("id")} = commit_reservation.reservation;
33030
33086
  v_movement := ${moveStock(ctx, {
33031
33087
  tenant: "v_row.tenant",
@@ -33059,7 +33115,7 @@ declare
33059
33115
  v_row record;
33060
33116
  begin
33061
33117
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33062
- x.${r("quantity")} as quantity, x.${r("status")} as status
33118
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status
33063
33119
  into v_row from ${reservations} x where x.${r("id")} = release_reservation.reservation for update;
33064
33120
  if not found then
33065
33121
  return false;
@@ -33069,7 +33125,7 @@ begin
33069
33125
  return false;
33070
33126
  end if;
33071
33127
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33072
- update ${reservations} x set ${r("status")} = 'released', ${r("updatedAt")} = now()
33128
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "released")}, ${r("updatedAt")} = now()
33073
33129
  where x.${r("id")} = release_reservation.reservation;
33074
33130
  ${released("v_row.", "released")}
33075
33131
  return true;
@@ -33093,12 +33149,12 @@ begin
33093
33149
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant,
33094
33150
  x.${r("location")} as location, x.${r("quantity")} as quantity
33095
33151
  from ${reservations} x
33096
- where x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33152
+ where ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
33097
33153
  order by x.${r("expiresAt")}
33098
33154
  limit greatest(coalesce(expire_reservations.max_rows, 500), 1)
33099
33155
  for update skip locked
33100
33156
  loop
33101
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33157
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33102
33158
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33103
33159
  ${released("v_row.", "expired")}
33104
33160
  v_count := v_count + 1;
@@ -33202,12 +33258,12 @@ begin
33202
33258
  begin
33203
33259
  if v_created then
33204
33260
  insert into ${products} (${p("tenant")}, ${p("title")}, ${p("slug")}${desc ? `, ${p("description")}` : ""}${kind ? `, ${p("kind")}` : ""})
33205
- values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? ", coalesce(save_product.kind, 'physical')" : ""})
33206
- returning ${p("id")}, ${p("status")} into v_id, v_status;
33261
+ values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? `, ${ctx.cast("products", "kind", "coalesce(save_product.kind, 'physical')")}` : ""})
33262
+ returning ${p("id")}, ${ctx.label("products", "status", p("status"))} into v_id, v_status;
33207
33263
  else
33208
- update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(save_product.kind, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33264
+ update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(${ctx.cast("products", "kind", "save_product.kind")}, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33209
33265
  where x.${p("id")} = save_product.product and x.${p("tenant")} = save_product.tenant
33210
- returning x.${p("status")} into v_status;
33266
+ returning ${ctx.label("products", "status", `x.${p("status")}`)} into v_status;
33211
33267
  if not found then
33212
33268
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33213
33269
  end if;
@@ -33249,7 +33305,7 @@ declare
33249
33305
  v_tenant ${ctx.idType};
33250
33306
  v_from text;
33251
33307
  begin
33252
- select x.${p("tenant")}, x.${p("status")} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33308
+ select x.${p("tenant")}, ${ctx.label("products", "status", `x.${p("status")}`)} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33253
33309
  if v_tenant is null then
33254
33310
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33255
33311
  end if;
@@ -33941,7 +33997,7 @@ as $$
33941
33997
  select jsonb_build_object(
33942
33998
  'id', p.${p("id")},
33943
33999
  'slug', p.${p("slug")},
33944
- 'status', p.${p("status")},
34000
+ 'status', ${ctx.label("products", "status", `p.${p("status")}`)},
33945
34001
  'kind', ${kind ? `p.${p("kind")}` : "null"},
33946
34002
  'locale', ${locale},
33947
34003
  'title', ${title},
@@ -34917,7 +34973,7 @@ security definer
34917
34973
  set search_path = ''
34918
34974
  as $$
34919
34975
  select x.${p("id")} from ${products} x
34920
- where x.${p("status")} = 'active'
34976
+ where ${ctx.is("products", "status", `x.${p("status")}`, ["active"])}
34921
34977
  and x.${p("tenant")} in (select y.${s("tenant")} from ${storefronts} y where y.${s("publishedAt")} is not null)
34922
34978
  $$;
34923
34979
  revoke execute on function ${fn("storefront_products")}() from public;
@@ -35112,7 +35168,7 @@ const NAMES$94 = {
35112
35168
  updatedAt: "updated_at"
35113
35169
  },
35114
35170
  optional: ["description", "kind"],
35115
- typed: ["status"]
35171
+ typed: ["status", "kind"]
35116
35172
  },
35117
35173
  options: {
35118
35174
  name: "product_options",
@@ -35541,7 +35597,7 @@ function storefrontPolicies(ctx, names) {
35541
35597
  const t = (name) => ctx.table(name);
35542
35598
  const c = (table, column) => ctx.col(table, column);
35543
35599
  const publicTables = [
35544
- ["products", `${c("products", "status")} = 'active' and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35600
+ ["products", `${ctx.is("products", "status", c("products", "status"), ["active"])} and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35545
35601
  ["options", `${c("options", "product")} in (select ${names.fn("storefront_products")}())`],
35546
35602
  ["optionValues", `${c("optionValues", "option")} in (select o.${c("options", "id")} from ${t("options")} o where o.${c("options", "product")} in (select ${names.fn("storefront_products")}()))`],
35547
35603
  ["variants", `${c("variants", "product")} in (select ${names.fn("storefront_products")}())`],
@@ -37496,7 +37552,7 @@ begin
37496
37552
  ${fail$1("COLLECTION_INVALID", "scope must be user, team or tenant", "22023")}
37497
37553
  end if;
37498
37554
  if create_collection.subject_type is null or not (create_collection.subject_type = any (${names.subjectTypes})) then
37499
- ${fail$1("COLLECTION_SUBJECT_TYPE_UNKNOWN", "not a subject type in config.records", "22023")}
37555
+ ${fail$1("COLLECTION_SUBJECT_TYPE_UNKNOWN", "not a subject type in config.subjects", "22023")}
37500
37556
  end if;
37501
37557
  if v_name is null then
37502
37558
  ${fail$1("COLLECTION_NAME_REQUIRED", "a name is required", "23502")}
@@ -38406,7 +38462,7 @@ function build$91(ctx, layout) {
38406
38462
  return `${schemaPreamble(ctx)}
38407
38463
  -- Favorites (a member's starred records, ranked for a sidebar), lists (named,
38408
38464
  -- static collections of one subject type) and saved items (a member's records
38409
- -- to come back to, with a reminder) on config.records records.
38465
+ -- to come back to, with a reminder) on config.subjects records.
38410
38466
  ${tables$29(ctx, names)}${ctx.manages ? policies(ctx, names) : ""}${collectionFunctions(ctx, names)}${starFunctions(ctx, names)}${savedItemFunctions(ctx, names)}${subjectCascades(ctx, cascading(ctx), `delete from ${ctx.table("entries")} where ${en("subjectType")} = v_type and ${en("subjectId")} = v_id;
38411
38467
  delete from ${ctx.table("favorites")} where ${fa("subjectType")} = v_type and ${fa("subjectId")} = v_id;
38412
38468
  delete from ${ctx.table("savedItems")} where ${sv("subjectType")} = v_type and ${sv("subjectId")} = v_id;`)}`;
@@ -49494,6 +49550,7 @@ function lineItemsSql(ctx, items, options) {
49494
49550
  ["position", "x.ordinality::integer"]
49495
49551
  ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : value]);
49496
49552
  const extras = items.extras ?? [];
49553
+ const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
49497
49554
  return `${ctx.manages ? `create table if not exists ${t} (
49498
49555
  ${c("id")} uuid primary key default gen_random_uuid(),
49499
49556
  ${c("tenant")} ${ctx.idType} not null,
@@ -49603,8 +49660,8 @@ begin
49603
49660
  end if;
49604
49661
  delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${options.setter}.lines, '[]'))`};
49605
49662
  begin
49606
- insert into ${t} (${written.map(([column]) => c(column)).join(", ")})
49607
- select ${written.map(([, value]) => value).join(",\n ")}
49663
+ insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
49664
+ select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
49608
49665
  from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x${replaces ? "" : `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
49609
49666
  "tenant",
49610
49667
  "parent",
@@ -49771,20 +49828,26 @@ function sequenceFormatOf(ctx, entity, tenant) {
49771
49828
  if (!ctx.installed("numbering")) return;
49772
49829
  const entry = sequenceEntry(ctx.of("numbering"), entity);
49773
49830
  if (entry === void 0 || typeof entry["format"] !== "string") return;
49774
- return isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]);
49831
+ return {
49832
+ format: isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]),
49833
+ assigns: typeof entry["table"] === "string"
49834
+ };
49775
49835
  }
49776
49836
  /**
49777
49837
  * PL/pgSQL that assigns the next number of `entity` in `tenant` to `target.seq`
49778
49838
  * (bigint) and `target.identifier` (text): from `numbering` when it numbers the
49779
49839
  * entity, otherwise one more than the tenant's highest in `fallback.table`
49780
- * under a transaction lock, with `prefix` in front (`DEAL-4821`).
49840
+ * under a transaction lock, with `prefix` in front (`DEAL-4821`). When the
49841
+ * entity has a table, the number is marked as issued for the transaction, so
49842
+ * its assign trigger accepts it on the block's insert instead of refusing it.
49781
49843
  */
49782
49844
  function assignNumberSql(ctx, entity, tenant, target, fallback) {
49783
- const format = sequenceFormatOf(ctx, entity, tenant);
49784
- if (format !== void 0) {
49845
+ const sequence = sequenceFormatOf(ctx, entity, tenant);
49846
+ if (sequence !== void 0) {
49785
49847
  const next = ctx.of("numbering").fn("next_number");
49786
49848
  return `${target.seq} := ${next}(${tenant}, ${sqlString(entity)}, now());
49787
- ${target.identifier} := better_supabase.format_assigned_number(${format}, ${target.seq}, now());`;
49849
+ ${target.identifier} := better_supabase.format_assigned_number(${sequence.format}, ${target.seq}, now());${sequence.assigns ? `
49850
+ perform set_config('better_supabase.issued_number', ${sqlString(entity)} || chr(31) || ${target.seq}::text || chr(31) || ${target.identifier}, true);` : ""}`;
49788
49851
  }
49789
49852
  return `perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(${tenant}::text || ${sqlString(`:${entity}`)}, 0));
49790
49853
  select coalesce(max(x.${fallback.seq}), 0) + 1 into ${target.seq} from ${fallback.table} x where x.${fallback.tenant} = ${tenant};
@@ -54860,8 +54923,9 @@ function trigger$1(ctx, item) {
54860
54923
  const sequence = item.sequenceColumn === void 0 ? void 0 : sqlIdent(item.sequenceColumn);
54861
54924
  const fn = sqlIdent(`bsb_assign_number_${item.name}`);
54862
54925
  const manual = fail$1("NUMBER_MANUAL", "a number is assigned by the sequence, not set by hand", "42501");
54926
+ const issued = `coalesce(v_issued[1] = ${sqlString(item.name)} and new.${col}::text in (v_issued[2], v_issued[3])${sequence === void 0 ? "" : ` and new.${sequence}::text = v_issued[2]`}, false)`;
54863
54927
  const manualSequence = sequence === void 0 ? "" : `
54864
- if not (${SERVICE_CALLER$1}) then
54928
+ if not (${SERVICE_CALLER$1} or ${issued}) then
54865
54929
  if tg_op = 'INSERT' then
54866
54930
  if new.${sequence} is not null then
54867
54931
  ${manual}
@@ -54880,6 +54944,7 @@ as $$
54880
54944
  declare
54881
54945
  v_n bigint;
54882
54946
  v_at timestamptz;
54947
+ v_issued text[] := string_to_array(coalesce(current_setting('better_supabase.issued_number', true), ''), chr(31));
54883
54948
  begin
54884
54949
  if not (better_supabase.actor_may_write()) then
54885
54950
  ${fail$1("ACTOR_READ_ONLY", "This session is read-only")}
@@ -54892,7 +54957,9 @@ begin
54892
54957
  end if;
54893
54958
  -- A number is assigned here or by the service role, never sent by a client.${manualSequence}
54894
54959
  if new.${col} is not null then
54895
- if not (${SERVICE_CALLER$1}) then
54960
+ if ${issued} then
54961
+ perform set_config('better_supabase.issued_number', '', true);
54962
+ elsif not (${SERVICE_CALLER$1}) then
54896
54963
  ${manual}
54897
54964
  end if;
54898
54965
  return new;
@@ -57554,10 +57621,19 @@ function quoteFunctions(ctx, n) {
57554
57621
  ${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
57555
57622
  end if;`;
57556
57623
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.write)})`;
57557
- const open = (alias) => `${alias}.${q("status")} in ('draft', 'changes_requested')`;
57624
+ const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
57625
+ const sv = (label) => ctx.value("quotes", "status", label);
57626
+ const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
57627
+ const markViewed = () => viewed || has("viewedAt") ? ` if ${st(`v_row.${q("status")}`, ["sent"])}${viewed ? "" : ` and v_row.${q("viewedAt")} is null`} then
57628
+ update ${t("quotes")} x set ${viewed ? `${q("status")} = ${sv("viewed")}${has("viewedAt") ? ", " : ""}` : ""}${has("viewedAt") ? `${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57629
+ returning * into v_row;
57630
+ ${record("quote.viewed", "v_row")}
57631
+ end if;` : " null;";
57632
+ const open = (alias) => st(`${alias}.${q("status")}`, ["draft", "changes_requested"]);
57558
57633
  const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "ql", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "ql", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "ql", "taxCode")}, 'product', case when ${lineColumn(ctx, "lines", "ql", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(ctx, "lines", "ql", "productType")}, 'id', ${lineColumn(ctx, "lines", "ql", "productId")}) end${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
57559
57634
  const int8 = ["number", ...Object.keys(TOTAL_COLUMNS)].map(q);
57560
- const row = (alias) => `(to_jsonb(${alias}) - ${sqlString(q("tokenHash").replaceAll("\"", ""))}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57635
+ const int8As = Object.fromEntries(["number", ...Object.keys(TOTAL_COLUMNS)].map((logical) => [logical, (value) => `${value}::text`]));
57636
+ const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57561
57637
  const record = (type, alias, extra = "") => ctx.record({
57562
57638
  type,
57563
57639
  payload: `jsonb_build_object('organizationId', ${alias}.${q("tenant")}, 'quoteId', ${alias}.${q("id")}, 'subjectType', 'quote', 'subjectId', ${alias}.${q("id")}::text, 'identifier', ${alias}.${q("identifier")}${extra})`,
@@ -57792,7 +57868,7 @@ begin
57792
57868
  ${fail$1("QUOTE_EMPTY", "a quote needs a line before it is sent", "23514")}
57793
57869
  end if;
57794
57870
  ${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}
57795
- update ${t("quotes")} x set ${q("status")} = 'sent', ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57871
+ update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57796
57872
  ${q("decidedAt")} = null, ${q("decidedBy")} = null, ${has("decisionNote") ? `${q("decisionNote")} = null, ` : ""}${q("updatedAt")} = now()
57797
57873
  where x.${q("id")} = v_row.${q("id")}
57798
57874
  returning * into v_row;
@@ -57822,7 +57898,7 @@ begin
57822
57898
  if decide_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57823
57899
  ${fail$1("QUOTE_DECISION_INVALID", "decide accepted, rejected or changes_requested", "22023")}
57824
57900
  end if;
57825
- if v_row.${q("status")} not in ('sent', 'viewed') then
57901
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57826
57902
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote takes a decision", "55000")}
57827
57903
  end if;
57828
57904
  if decide_quote.decision = 'accepted' then
@@ -57852,7 +57928,7 @@ begin
57852
57928
  if v_old.${q("id")} is null then
57853
57929
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
57854
57930
  end if;
57855
- if v_old.${q("status")} = 'draft' then
57931
+ if ${st(`v_old.${q("status")}`, ["draft"])} then
57856
57932
  ${fail$1("QUOTE_NOT_SENT", "a draft is edited, not revised", "55000")}
57857
57933
  end if;
57858
57934
  if exists (select 1 from ${t("quotes")} x where x.${q("supersedes")} = v_old.${q("id")}) then
@@ -57908,8 +57984,8 @@ begin
57908
57984
  insert into ${t("lines")} (${lineCopyColumns(ctx, "lines").map(l).join(", ")})
57909
57985
  select ${lineCopyColumns(ctx, "lines").map((column) => column === "parent" ? `v_row.${q("id")}` : `x.${l(column)}`).join(", ")}
57910
57986
  from ${t("lines")} x where x.${l("parent")} = v_old.${q("id")};
57911
- if v_old.${q("status")} <> 'accepted' then
57912
- update ${t("quotes")} x set ${q("status")} = 'withdrawn', ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
57987
+ if ${st(`v_old.${q("status")}`, ["accepted"], true)} then
57988
+ update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
57913
57989
  end if;
57914
57990
  ${record("quote.revised", "v_old", `, 'revisionId', v_row.${q("id")}`)}
57915
57991
  return (select ${row("x")} from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")});
@@ -57932,14 +58008,10 @@ begin
57932
58008
  if v_row.${q("id")} is null then
57933
58009
  ${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
57934
58010
  end if;
57935
- if v_row.${q("status")} = 'sent' then
57936
- update ${t("quotes")} x set ${q("status")} = 'viewed'${has("viewedAt") ? `, ${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57937
- returning * into v_row;
57938
- ${record("quote.viewed", "v_row")}
57939
- end if;
58011
+ ${markViewed()}
57940
58012
  return jsonb_build_object(
57941
58013
  'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")}, 'title', v_row.${q("title")},
57942
- 'status', v_row.${q("status")}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
58014
+ 'status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
57943
58015
  'terms', ${or("v_row", "terms")}, 'subtotal', v_row.${q("subtotal")}::text, 'discountTotal', v_row.${q("discountTotal")}::text,
57944
58016
  'taxTotal', v_row.${q("taxTotal")}::text, 'total', v_row.${q("total")}::text, 'lines', ${lines("v_row")});
57945
58017
  end;
@@ -57967,11 +58039,11 @@ begin
57967
58039
  if respond_to_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57968
58040
  ${fail$1("QUOTE_DECISION_INVALID", "answer accepted, rejected or changes_requested", "22023")}
57969
58041
  end if;
57970
- if v_row.${q("status")} not in ('sent', 'viewed') then
58042
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57971
58043
  ${fail$1("QUOTE_NOT_OPEN", "this quote no longer takes an answer", "55000")}
57972
58044
  end if;
57973
58045
  if v_row.${q("validUntil")} < current_date then
57974
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
58046
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
57975
58047
  returning * into v_row;
57976
58048
  ${record("quote.expired", "v_row")}
57977
58049
  return jsonb_build_object('status', 'expired');
@@ -57985,7 +58057,7 @@ begin
57985
58057
  if respond_to_quote.decision = 'accepted' then
57986
58058
  ${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
57987
58059
  end if;
57988
- return jsonb_build_object('status', v_row.${q("status")}, 'identifier', v_row.${q("identifier")});
58060
+ return jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")});
57989
58061
  end;
57990
58062
  $$;
57991
58063
  revoke all on function ${fn("respond_to_quote")}(text, text, text, text) from public, anon, authenticated;
@@ -58003,8 +58075,8 @@ declare
58003
58075
  v_count integer := 0;
58004
58076
  begin
58005
58077
  for v_row in
58006
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now()
58007
- where x.${q("status")} in ('sent', 'viewed') and x.${q("validUntil")} < current_date
58078
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
58079
+ where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
58008
58080
  returning *
58009
58081
  loop
58010
58082
  ${record("quote.expired", "v_row")}
@@ -58441,7 +58513,7 @@ function fromApplication(ctx, n) {
58441
58513
  const jobType = asText$2(hiring, "jobs", hiring.label("jobs", "employmentType", `v_job.${j("employmentType")}`));
58442
58514
  return `
58443
58515
  -- The employee for a hired application, in preboarding: the name comes from
58444
- -- the candidate's record in config.records, and the job title, team and
58516
+ -- the candidate's record in config.subjects, and the job title, team and
58445
58517
  -- employment type from the job. attrs overrides any of them. Calling it
58446
58518
  -- again returns the same employee, and with the relations module the
58447
58519
  -- employee is created_from the application.
@@ -58576,7 +58648,7 @@ function privateSql(ctx, n, reader, load) {
58576
58648
  const address = pairs(ADDRESS_KEYS, alias);
58577
58649
  const contact = pairs(CONTACT_KEYS, alias);
58578
58650
  const parts = [...address === "" || has("address") ? [] : [`'address', nullif(jsonb_strip_nulls(jsonb_build_object(${address})), '{}'::jsonb)`], ...contact === "" || has("emergencyContacts") ? [] : [`'emergency_contacts', case when ${flat.includes("emergencyName") ? `${alias}.${p("emergencyName")} is null` : "true"} then '[]'::jsonb else jsonb_build_array(jsonb_strip_nulls(jsonb_build_object(${contact}))) end`]];
58579
- return parts.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${parts.join(", ")}))`;
58651
+ return parts.length === 0 ? ctx.rowJson("privateDetails", alias) : `(${ctx.rowJson("privateDetails", alias)} || jsonb_build_object(${parts.join(", ")}))`;
58580
58652
  };
58581
58653
  const sets = [
58582
58654
  ...DETAILS.filter((detail) => has(detail.column)).map((detail) => {
@@ -58660,7 +58732,9 @@ function contractsSql(ctx, n, reader, load) {
58660
58732
  const currency = has("currency");
58661
58733
  const major = majorSalary(ctx);
58662
58734
  const exponent = (code) => currency ? minorUnits(code) : "2";
58663
- const row = (alias) => salary ? major ? `to_jsonb(${alias}) || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, (${alias}.${k("salary")} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text)` : `to_jsonb(${alias}) || ${int8Text(alias, [k("salary")])}` : `to_jsonb(${alias})`;
58735
+ const minorText = (alias, value) => major ? `(${value} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text` : `${value}::text`;
58736
+ const json = (alias) => ctx.rowJson("contracts", alias, { as: { salary: (value) => minorText(alias, value) } });
58737
+ const row = (alias) => salary ? major ? `${json(alias)} || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, ${minorText(alias, `${alias}.${k("salary")}`)})` : `${json(alias)} || ${int8Text(alias, [k("salary")])}` : json(alias);
58664
58738
  const salaryValue = (minor, code) => major ? `(${minor})::numeric / power(10, ${exponent(code)})` : `(${minor})::bigint`;
58665
58739
  const arg = (key) => `add_employee_contract.attrs ->> ${sqlString(key)}`;
58666
58740
  const extras = ctx.extraColumns("contracts", [], "contractExtraColumns");
@@ -58690,6 +58764,14 @@ function contractsSql(ctx, n, reader, load) {
58690
58764
  ...has("note") ? [`nullif(trim(${arg("note")}), '')`] : [],
58691
58765
  ...has("createdBy") ? ["auth.uid()"] : []
58692
58766
  ];
58767
+ const insertWith = (skip) => `insert into ${table} (${columns.filter((column) => column !== skip).join(", ")}${required.columns})
58768
+ values (${values.filter((_, index) => columns[index] !== skip).join(", ")}${required.values})
58769
+ returning * into v_row;`;
58770
+ const insert = currency && !ctx.owns("contracts") ? `if add_employee_contract.attrs ? 'currency' then
58771
+ ${insertWith(void 0).replaceAll("\n ", "\n ")}
58772
+ else
58773
+ ${insertWith(k("currency")).replaceAll("\n ", "\n ")}
58774
+ end if;` : insertWith(void 0);
58693
58775
  const updated = ctx.record({
58694
58776
  type: "employee.updated",
58695
58777
  payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'fields', jsonb_build_array('contract'))`,
@@ -58741,9 +58823,7 @@ begin${load("add_employee_contract", "employee", contractWriter(ctx, n, "v_emplo
58741
58823
  end if;
58742
58824
  update ${table} x set ${k("endsOn")} = v_starts - 1
58743
58825
  where x.${k("employee")} = v_employee.${e("id")} and (x.${k("endsOn")} is null or x.${k("endsOn")} >= v_starts);`}
58744
- insert into ${table} (${columns.join(", ")}${required.columns})
58745
- values (${values.join(", ")}${required.values})
58746
- returning * into v_row;${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58826
+ ${insert}${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58747
58827
  exception when check_violation or not_null_violation or invalid_text_representation or invalid_datetime_format or datetime_field_overflow or numeric_value_out_of_range then
58748
58828
  ${fail$1("EMPLOYEE_CONTRACT_INVALID", "a contract field has an invalid value", "22023")}
58749
58829
  end;
@@ -59279,7 +59359,7 @@ function build$74(ctx) {
59279
59359
  service: "(auth.role() = 'service_role')",
59280
59360
  extras: ctx.extraColumns("employees", RESERVED$7),
59281
59361
  name: fullName,
59282
- json: (alias) => ctx.has("employees", "name") ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object('name', ${fullName(alias)}))`
59362
+ json: (alias) => ctx.has("employees", "name") ? ctx.rowJson("employees", alias) : `(${ctx.rowJson("employees", alias)} || jsonb_build_object('name', ${fullName(alias)}))`
59283
59363
  };
59284
59364
  return `${schemaPreamble(ctx)}
59285
59365
  -- Employees: the people an organization employs, with or without an
@@ -62061,14 +62141,14 @@ const NAMES$72 = { tables: { changes: {
62061
62141
  const COLUMN$5 = /^[a-z_][a-z0-9_]{0,62}$/u;
62062
62142
  /**
62063
62143
  * `blocks.field-history.on`, record type to `{ fields }`, checked against
62064
- * `config.records`.
62144
+ * `config.subjects`.
62065
62145
  */
62066
62146
  function historyBindings(ctx) {
62067
62147
  const registry = registeredSubjects(ctx.subjects, ctx.naming);
62068
62148
  return Object.entries(onSettings(ctx)).map(([type, settings]) => {
62069
62149
  const where = `blocks.field-history.on.${type}`;
62070
62150
  const subject = registry.find((item) => item.type === type);
62071
- if (subject?.tenant === void 0) throw new TypeError(`${where}: register "${type}" with a tenant column in config.records first`);
62151
+ if (subject?.tenant === void 0) throw new TypeError(`${where}: register "${type}" with a tenant column in config.subjects first`);
62072
62152
  const fields = isRecord$1(settings) ? settings["fields"] : void 0;
62073
62153
  if (!Array.isArray(fields) || fields.length === 0 || fields.some((field) => typeof field !== "string" || !COLUMN$5.test(field))) throw new TypeError(`${where}.fields must be a non-empty list of column names`);
62074
62154
  return {
@@ -67582,14 +67662,14 @@ function build$63(ctx) {
67582
67662
  const candidateType = (row) => hiringCandidate(ctx, row).type;
67583
67663
  const candidateId = (row) => hiringCandidate(ctx, row).id;
67584
67664
  const candidateValue = (value) => fixedCandidate ? asColumnType(t("applications"), ctx.colName("applications", "candidateId"), value) : value;
67585
- const applicationJson = (alias) => fixedCandidate ? `(to_jsonb(${alias}) || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : `to_jsonb(${alias})`;
67665
+ const applicationJson = (alias) => fixedCandidate ? `(${ctx.rowJson("applications", alias, { as: { candidateId: (value) => `${value}::text` } })} || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : ctx.rowJson("applications", alias);
67586
67666
  const interviewerOf = (row, user) => {
67587
67667
  const checks = [...ctx.has("interviews", "interviewers") ? [`${user} = any (${row}.${v("interviewers")})`] : [], ...interviewerRows ? [`exists (select 1 from ${t("interviewers")} z where z.${iv("interview")} = ${row}.${v("id")} and z.${iv("user")} = ${user})`] : []];
67588
67668
  if (checks.length <= 1) return checks[0];
67589
67669
  return `(${checks.join(" or ")})`;
67590
67670
  };
67591
- const interviewJson = (alias) => interviewerRows ? `(to_jsonb(${alias}) || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : `to_jsonb(${alias})`;
67592
- const scorecardJson = (alias) => scoreRows ? `(to_jsonb(${alias}) || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : `to_jsonb(${alias})`;
67671
+ const interviewJson = (alias) => interviewerRows ? `(${ctx.rowJson("interviews", alias)} || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : ctx.rowJson("interviews", alias);
67672
+ const scorecardJson = (alias) => scoreRows ? `(${ctx.rowJson("scorecards", alias)} || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : ctx.rowJson("scorecards", alias);
67593
67673
  const managerValue = managerEmployee && ctx.has("jobs", "hiringManager") ? asColumnType(t("jobs"), ctx.colName("jobs", "hiringManager"), "save_job.attrs ->> 'hiringManagerId'") : "(save_job.attrs ->> 'hiringManagerId')::uuid";
67594
67674
  const column = (table, logical, type) => ctx.has(table, logical) ? `\n ${ctx.col(table, logical)} ${type},` : "";
67595
67675
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
@@ -67817,12 +67897,12 @@ begin
67817
67897
  ${jobRecord("job.closed")}
67818
67898
  end if;
67819
67899
  end if;
67820
- return ${withExtraFields("to_jsonb(v_job)", "v_job", extras)};
67900
+ return ${withExtraFields(ctx.rowJson("jobs", "v_job"), "v_job", extras)};
67821
67901
  end;
67822
67902
  $$;
67823
67903
  ${userGrant(`${fn("save_job")}(${ctx.idType}, uuid, jsonb)`)}
67824
67904
 
67825
- -- An application of a candidate (a record in config.records, a person by
67905
+ -- An application of a candidate (a record in config.subjects, a person by
67826
67906
  -- default) to an open job. Applying again returns the same application.
67827
67907
  create or replace function ${fn("apply_to_job")}(job uuid, candidate jsonb, source text, owner uuid)
67828
67908
  returns jsonb
@@ -68150,7 +68230,7 @@ const HIRING = {
68150
68230
  name: "hiring",
68151
68231
  scopes: ["tenant"],
68152
68232
  title: "Hiring",
68153
- description: "Jobs and applications on a pipeline per job, candidates from config.records, scorecards per stage, interviews, and hire, reject and withdraw events for the app to act on.",
68233
+ description: "Jobs and applications on a pipeline per job, candidates from config.subjects, scorecards per stage, interviews, and hire, reject and withdraw events for the app to act on.",
68154
68234
  requires: [
68155
68235
  "memberships",
68156
68236
  "permissions",
@@ -73665,7 +73745,7 @@ function transferFunctions(ctx, names) {
73665
73745
  const t = columns$1(ctx, "transfers");
73666
73746
  const tl = columns$1(ctx, "transferLines");
73667
73747
  const l = locationsOf(ctx).col;
73668
- const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, x.${t("status")} as status
73748
+ const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, ${ctx.label("transfers", "status", `x.${t("status")}`)} as status
73669
73749
  into v_row from ${transfers} x where x.${t("id")} = ${name}.transfer for update;
73670
73750
  if not found then
73671
73751
  ${fail$1("INVENTORY_TRANSFER_NOT_FOUND", "transfer not found", "P0002")}
@@ -73736,7 +73816,7 @@ begin
73736
73816
  ${statusError}
73737
73817
  end if;
73738
73818
  ${move("ship_transfer", "v_row.from_location", "-", "transfer_out")}
73739
- update ${transfers} x set ${t("status")} = 'in_transit', ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73819
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "in_transit")}, ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73740
73820
  ${event("transfer.shipped", "ship_transfer", "'in_transit'")}
73741
73821
  return true;
73742
73822
  end;
@@ -73758,7 +73838,7 @@ begin
73758
73838
  ${statusError}
73759
73839
  end if;
73760
73840
  ${move("receive_transfer", "v_row.to_location", "", "transfer_in")}
73761
- update ${transfers} x set ${t("status")} = 'received', ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73841
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "received")}, ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73762
73842
  ${event("transfer.received", "receive_transfer", "'received'")}
73763
73843
  return true;
73764
73844
  end;
@@ -73782,7 +73862,7 @@ begin
73782
73862
  if v_row.status = 'in_transit' then
73783
73863
  ${move("cancel_transfer", "v_row.from_location", "", "transfer_in")}
73784
73864
  end if;
73785
- update ${transfers} x set ${t("status")} = 'cancelled' where x.${t("id")} = cancel_transfer.transfer;
73865
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "cancelled")} where x.${t("id")} = cancel_transfer.transfer;
73786
73866
  ${event("transfer.cancelled", "cancel_transfer", "'cancelled'")}
73787
73867
  return true;
73788
73868
  end;
@@ -73802,7 +73882,7 @@ function purchaseOrderFunctions(ctx, names) {
73802
73882
  const lv = columns$1(ctx, "levels");
73803
73883
  const l = locationsOf(ctx).col;
73804
73884
  const currencyUnits = ctx.of("catalog").fn("currency_minor_units");
73805
- const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, x.${po("status")} as status,
73885
+ const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, ${ctx.label("purchaseOrders", "status", `x.${po("status")}`)} as status,
73806
73886
  x.${po("supplierType")} as supplier_type, x.${po("supplierId")} as supplier_id
73807
73887
  into v_row from ${orders} x where x.${po("id")} = ${name}.purchase_order for update;
73808
73888
  if not found then
@@ -73820,7 +73900,7 @@ function purchaseOrderFunctions(ctx, names) {
73820
73900
  return `
73821
73901
  -- Creates a draft purchase order (purchase_order null) or replaces a draft's
73822
73902
  -- fields and lines. lines: [{ "variantId": uuid, "quantity": n, "unitCost": "minor units" }].
73823
- -- supplier_type and supplier_id name a config.records record, or are both null.
73903
+ -- supplier_type and supplier_id name a config.subjects record, or are both null.
73824
73904
  create or replace function ${fn("save_purchase_order")}(tenant ${ctx.idType}, purchase_order uuid, location uuid, supplier_type text, supplier_id text, currency text, expected_at timestamptz, lines jsonb, note text)
73825
73905
  returns jsonb
73826
73906
  language plpgsql
@@ -73855,7 +73935,7 @@ begin
73855
73935
  update ${orders} x set ${po("location")} = save_purchase_order.location, ${po("supplierType")} = save_purchase_order.supplier_type,
73856
73936
  ${po("supplierId")} = save_purchase_order.supplier_id, ${po("currency")} = save_purchase_order.currency,
73857
73937
  ${po("expectedAt")} = save_purchase_order.expected_at, ${po("note")} = save_purchase_order.note, ${po("updatedAt")} = now()
73858
- where x.${po("id")} = v_id and x.${po("status")} = 'draft';
73938
+ where x.${po("id")} = v_id and ${ctx.is("purchaseOrders", "status", `x.${po("status")}`, ["draft"])};
73859
73939
  if not found then
73860
73940
  ${fail$1("INVENTORY_PURCHASE_ORDER_LOCKED", "only a draft purchase order can change", "55000")}
73861
73941
  end if;
@@ -73888,7 +73968,7 @@ begin
73888
73968
  from ${lines} y where y.${pl("order")} = place_purchase_order.purchase_order
73889
73969
  on conflict (${lv("variant")}, ${lv("location")}) do update
73890
73970
  set ${lv("incoming")} = x.${lv("incoming")} + excluded.${lv("incoming")}, ${lv("updatedAt")} = now();
73891
- update ${orders} x set ${po("status")} = 'ordered', ${po("placedAt")} = now(), ${po("updatedAt")} = now()
73971
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "ordered")}, ${po("placedAt")} = now(), ${po("updatedAt")} = now()
73892
73972
  where x.${po("id")} = place_purchase_order.purchase_order;
73893
73973
  ${event("purchase_order.placed", "place_purchase_order", "'ordered'")}
73894
73974
  return true;
@@ -73974,7 +74054,7 @@ begin
73974
74054
  where y.${pl("order")} = cancel_purchase_order.purchase_order
73975
74055
  and x.${lv("variant")} = y.${pl("variant")} and x.${lv("location")} = v_row.location;
73976
74056
  end if;
73977
- update ${orders} x set ${po("status")} = 'cancelled', ${po("updatedAt")} = now()
74057
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "cancelled")}, ${po("updatedAt")} = now()
73978
74058
  where x.${po("id")} = cancel_purchase_order.purchase_order;
73979
74059
  ${event("purchase_order.cancelled", "cancel_purchase_order", "'cancelled'")}
73980
74060
  return true;
@@ -74136,7 +74216,8 @@ const NAMES$60 = {
74136
74216
  expiresAt: "expires_at",
74137
74217
  createdAt: "created_at",
74138
74218
  updatedAt: "updated_at"
74139
- }
74219
+ },
74220
+ typed: ["status"]
74140
74221
  },
74141
74222
  transfers: {
74142
74223
  name: "stock_transfers",
@@ -74153,7 +74234,8 @@ const NAMES$60 = {
74153
74234
  createdAt: "created_at",
74154
74235
  shippedAt: "shipped_at",
74155
74236
  receivedAt: "received_at"
74156
- }
74237
+ },
74238
+ typed: ["status"]
74157
74239
  },
74158
74240
  transferLines: {
74159
74241
  name: "stock_transfer_lines",
@@ -78078,6 +78160,8 @@ function invoiceFunctions(ctx, n) {
78078
78160
  ${fail$1(`INVOICE_${thing}_UNSUPPORTED`, `this invoices table has no ${what}`, "22023")}
78079
78161
  end if;`;
78080
78162
  const can = (alias, permission) => `(${n.service} or ${ctx.scope.can(`${alias}.${i("tenant")}`, permission)})`;
78163
+ const st = (value, labels, negate = false) => ctx.is("invoices", "status", value, labels, negate);
78164
+ const kd = (value, labels, negate = false) => ctx.is("invoices", "kind", value, labels, negate);
78081
78165
  const balance = (alias) => `(${alias}.${i("total")} - ${alias}.${i("creditedTotal")} - ${alias}.${i("paidTotal")})`;
78082
78166
  const int8 = [
78083
78167
  "number",
@@ -78085,9 +78169,15 @@ function invoiceFunctions(ctx, n) {
78085
78169
  "creditedTotal",
78086
78170
  ...Object.keys(TOTAL_COLUMNS)
78087
78171
  ].map(i);
78088
- const row = (alias) => `to_jsonb(${alias}) || ${int8Text(alias, int8)} || jsonb_build_object(
78172
+ const int8Text8 = Object.fromEntries([
78173
+ "number",
78174
+ "paidTotal",
78175
+ "creditedTotal",
78176
+ ...Object.keys(TOTAL_COLUMNS)
78177
+ ].map((logical) => [logical, (value) => `${value}::text`]));
78178
+ const row = (alias) => `${ctx.rowJson("invoices", alias, { as: int8Text8 })} || ${int8Text(alias, int8)} || jsonb_build_object(
78089
78179
  'balance', ${balance(alias)}::text,
78090
- 'overdue', ${alias}.${i("status")} in ('issued', 'partially_paid') and ${alias}.${i("dueOn")} < current_date,
78180
+ 'overdue', ${st(`${alias}.${i("status")}`, ["issued", "partially_paid"])} and ${alias}.${i("dueOn")} < current_date,
78091
78181
  'lines', coalesce((select jsonb_agg(jsonb_build_object('description', il.${l("description")}, 'quantity', il.${l("quantity")}, 'unitAmount', il.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "il", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "il", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "il", "taxCode")}${lineFieldsJson("il", n.lineExtras)}) order by il.${l("position")}) from ${t("lines")} il where il.${l("parent")} = ${alias}.${i("id")}), '[]'::jsonb),
78092
78182
  'payments', ${ledger.payments(alias)})`;
78093
78183
  const record = (type, alias, extra = "", audit = false) => ctx.record({
@@ -78119,7 +78209,11 @@ function invoiceFunctions(ctx, n) {
78119
78209
  when x.${i("paidTotal")} > 0 or x.${i("creditedTotal")} > 0 then 'partially_paid'
78120
78210
  else 'issued' end`)},
78121
78211
  ${i("paidAt")} = case when ${balance("x")} <= 0 then coalesce(x.${i("paidAt")}, now()) end
78122
- where x.${i("id")} = ${alias}.${i("id")} and x.${i("status")} in ('issued', 'partially_paid', 'paid')
78212
+ where x.${i("id")} = ${alias}.${i("id")} and ${st(`x.${i("status")}`, [
78213
+ "issued",
78214
+ "partially_paid",
78215
+ "paid"
78216
+ ])}
78123
78217
  returning * into ${alias};`;
78124
78218
  const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
78125
78219
  const fromQuote = quotes === void 0 ? "" : (() => {
@@ -78131,7 +78225,7 @@ function invoiceFunctions(ctx, n) {
78131
78225
  if invoice_from_quote.deposit_bps is null then
78132
78226
  select * into v_row from ${t("invoices")} x
78133
78227
  where x.${i("originType")} = 'quote' and x.${i("originId")} = v_quote.${q("id")}::text
78134
- and ${deposits ? `x.${i("depositBps")} is null and ` : ""}x.${i("status")} <> 'void' and x.${i("kind")} = 'invoice'
78228
+ and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
78135
78229
  limit 1;
78136
78230
  if v_row.${i("id")} is not null then
78137
78231
  return ${row("v_row")};
@@ -78145,7 +78239,7 @@ function invoiceFunctions(ctx, n) {
78145
78239
  'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
78146
78240
  into v_lines
78147
78241
  from ${t("invoices")} d
78148
- where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and d.${i("status")} not in ('draft', 'void');` : ""}
78242
+ where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
78149
78243
  else
78150
78244
  v_lines := jsonb_build_array(jsonb_build_object(
78151
78245
  'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
@@ -78178,7 +78272,7 @@ begin
78178
78272
  if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.write)}) then
78179
78273
  ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
78180
78274
  end if;
78181
- if v_quote.${q("status")} <> 'accepted' then
78275
+ if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
78182
78276
  ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
78183
78277
  end if;
78184
78278
  if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
@@ -78190,7 +78284,7 @@ $$;
78190
78284
  ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
78191
78285
  `;
78192
78286
  })();
78193
- const kindTable = (kind) => `(select * from ${t("invoices")} k where k.${i("kind")} = ${kind})`;
78287
+ const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
78194
78288
  return `
78195
78289
  -- Creates a draft invoice. attrs: title (required), currency, company and
78196
78290
  -- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
@@ -78246,7 +78340,7 @@ ${userGrant(`${fn("create_invoice")}(${ctx.idType}, jsonb, jsonb)`)}
78246
78340
  ${lineItemsSql(ctx, {
78247
78341
  lines: "lines",
78248
78342
  parent: "invoices",
78249
- frozen: `p.${i("status")} <> 'draft'`,
78343
+ frozen: st(`p.${i("status")}`, ["draft"], true),
78250
78344
  extras: n.lineExtras
78251
78345
  }, {
78252
78346
  setter: "set_invoice_lines",
@@ -78273,14 +78367,14 @@ begin
78273
78367
  if v_row.${i("id")} is null then
78274
78368
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78275
78369
  end if;
78276
- if v_row.${i("status")} <> 'draft' then
78370
+ if ${st(`v_row.${i("status")}`, ["draft"], true)} then
78277
78371
  ${fail$1("INVOICE_NOT_DRAFT", "the invoice was already issued", "55000")}
78278
78372
  end if;
78279
78373
  if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${i("id")}) then
78280
78374
  ${fail$1("INVOICE_EMPTY", "an invoice needs a line before it is issued", "23514")}
78281
78375
  end if;
78282
78376
  ${ctx.hook("before_invoice_issue", [["uuid", `v_row.${i("id")}`]])}
78283
- if v_row.${i("kind")} = 'credit_note' then
78377
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78284
78378
  select * into v_original from ${t("invoices")} x where x.${i("id")} = v_row.${i("original")} for update;
78285
78379
  if v_row.${i("total")} > ${balance("v_original")} then
78286
78380
  ${fail$1("INVOICE_CREDIT_TOO_LARGE", "a credit note can't exceed what is still owed", "23514")}
@@ -78289,7 +78383,7 @@ begin
78289
78383
  seq: "v_seq",
78290
78384
  identifier: "v_identifier"
78291
78385
  }, {
78292
- table: kindTable("'credit_note'"),
78386
+ table: kindTable("credit_note"),
78293
78387
  seq: i("number"),
78294
78388
  tenant: i("tenant"),
78295
78389
  prefix: n.creditPrefix
@@ -78299,25 +78393,25 @@ begin
78299
78393
  seq: "v_seq",
78300
78394
  identifier: "v_identifier"
78301
78395
  }, {
78302
- table: kindTable("'invoice'"),
78396
+ table: kindTable("invoice"),
78303
78397
  seq: i("number"),
78304
78398
  tenant: i("tenant"),
78305
78399
  prefix: n.prefix
78306
78400
  })}
78307
78401
  end if;
78308
- update ${t("invoices")} x set ${i("status")} = 'issued', ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78402
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "issued")}, ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78309
78403
  ${i("issuedOn")} = coalesce(issue_invoice.issued_on, current_date),
78310
78404
  ${i("dueOn")} = coalesce(issue_invoice.issued_on, current_date) + x.${i("termsDays")},
78311
78405
  ${i("updatedAt")} = now()
78312
78406
  where x.${i("id")} = v_row.${i("id")}
78313
78407
  returning * into v_row;
78314
78408
  ${record("invoice.issued", "v_row", `, 'total', v_row.${i("total")}::text, 'currency', v_row.${i("currency")}, 'dueOn', v_row.${i("dueOn")}`)}
78315
- if v_row.${i("kind")} = 'credit_note' then
78409
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78316
78410
  update ${t("invoices")} x set ${i("creditedTotal")} = x.${i("creditedTotal")} + v_row.${i("total")}, ${i("updatedAt")} = now()
78317
78411
  where x.${i("id")} = v_original.${i("id")}
78318
78412
  returning * into v_original;${settle("v_original")}
78319
78413
  ${record("invoice.credited", "v_original", `, 'creditNoteId', v_row.${i("id")}, 'amount', v_row.${i("total")}::text`)}
78320
- if v_original.${i("status")} = 'paid' then
78414
+ if ${st(`v_original.${i("status")}`, ["paid"])} then
78321
78415
  ${record("invoice.paid", "v_original", `, 'total', v_original.${i("total")}::text`)}
78322
78416
  end if;
78323
78417
  end if;
@@ -78348,7 +78442,11 @@ begin
78348
78442
  if v_row.${i("id")} is null then
78349
78443
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78350
78444
  end if;
78351
- if v_row.${i("kind")} <> 'invoice' or v_row.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78445
+ if ${kd(`v_row.${i("kind")}`, ["invoice"], true)} or ${st(`v_row.${i("status")}`, [
78446
+ "issued",
78447
+ "partially_paid",
78448
+ "paid"
78449
+ ], true)} then
78352
78450
  ${fail$1("INVOICE_NOT_PAYABLE", "only an issued invoice takes payments", "55000")}
78353
78451
  end if;
78354
78452
  if coalesce(record_invoice_payment.amount, 0) = 0 then
@@ -78372,7 +78470,7 @@ begin
78372
78470
  v_was := v_row.${i("status")};
78373
78471
  v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference")};${settle("v_row")}
78374
78472
  ${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
78375
- if v_row.${i("status")} = 'paid' and v_was <> 'paid' then
78473
+ if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
78376
78474
  ${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
78377
78475
  end if;
78378
78476
  ${ctx.hook("after_invoice_payment", [["uuid", `v_row.${i("id")}`], ["uuid", "v_payment"]])}
@@ -78397,7 +78495,11 @@ begin
78397
78495
  if v_original.${i("id")} is null then
78398
78496
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78399
78497
  end if;
78400
- if v_original.${i("kind")} <> 'invoice' or v_original.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78498
+ if ${kd(`v_original.${i("kind")}`, ["invoice"], true)} or ${st(`v_original.${i("status")}`, [
78499
+ "issued",
78500
+ "partially_paid",
78501
+ "paid"
78502
+ ], true)} then
78401
78503
  ${fail$1("INVOICE_NOT_CREDITABLE", "only an issued invoice is credited", "55000")}
78402
78504
  end if;
78403
78505
  insert into ${t("invoices")} (${valueLines(" ", [
@@ -78417,7 +78519,7 @@ begin
78417
78519
  ])})
78418
78520
  values (${valueLines(" ", [
78419
78521
  `v_original.${i("tenant")}`,
78420
- "'credit_note'",
78522
+ ctx.value("invoices", "kind", "credit_note"),
78421
78523
  `v_original.${i("id")}`,
78422
78524
  `'Credit for ' || coalesce(v_original.${i("identifier")}, v_original.${i("title")})`
78423
78525
  ], [
@@ -78460,10 +78562,10 @@ begin
78460
78562
  if v_row.${i("id")} is null then
78461
78563
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can manage", "P0002")}
78462
78564
  end if;
78463
- if v_row.${i("status")} not in ('draft', 'issued') or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78565
+ if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78464
78566
  ${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
78465
78567
  end if;
78466
- update ${t("invoices")} x set ${i("status")} = 'void', ${i("voidedAt")} = now(),
78568
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
78467
78569
  ${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
78468
78570
  where x.${i("id")} = v_row.${i("id")} returning * into v_row;
78469
78571
  ${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
@@ -78482,8 +78584,8 @@ as $$
78482
78584
  declare
78483
78585
  v_row ${t("invoices")};
78484
78586
  begin
78485
- update ${t("invoices")} x set ${i("status")} = 'uncollectible', ${i("updatedAt")} = now()
78486
- where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and x.${i("status")} in ('issued', 'partially_paid')
78587
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "uncollectible")}, ${i("updatedAt")} = now()
78588
+ where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78487
78589
  returning * into v_row;
78488
78590
  if v_row.${i("id")} is null then
78489
78591
  ${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
@@ -78507,7 +78609,7 @@ as $$
78507
78609
  select ${balance("x")} as balance, coalesce(invoice_aging.as_of, current_date) - x.${i("dueOn")} as late
78508
78610
  from ${t("invoices")} x
78509
78611
  where x.${i("tenant")} = invoice_aging.tenant and x.${i("currency")} = upper(invoice_aging.currency)
78510
- and x.${i("kind")} = 'invoice' and x.${i("status")} in ('issued', 'partially_paid')
78612
+ and ${kd(`x.${i("kind")}`, ["invoice"])} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78511
78613
  )
78512
78614
  select jsonb_build_object(
78513
78615
  'currency', upper(invoice_aging.currency),
@@ -92113,7 +92215,7 @@ as $$
92113
92215
  declare
92114
92216
  v_from text;
92115
92217
  begin
92116
- select x.${o("status")} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92218
+ select ${ctx.label("orders", "status", `x.${o("status")}`)} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92117
92219
  if v_from = p_to then
92118
92220
  return v_from;
92119
92221
  end if;${governed ? "" : `
@@ -92164,7 +92266,7 @@ function orderFields(ctx, alias) {
92164
92266
  ["tax_inclusive", "taxInclusive"],
92165
92267
  ["invoice_number", "invoiceNumber"],
92166
92268
  ["placed_at", "placedAt"]
92167
- ].map(([as, column]) => `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92269
+ ].map(([as, column]) => column === "status" ? `${ctx.label("orders", "status", `${alias}.${o(column)}`)} as ${as}` : `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92168
92270
  }
92169
92271
  //#endregion
92170
92272
  //#region src/sql/modules/orders-after-sale.ts
@@ -92236,13 +92338,13 @@ function afterSaleFunctions(ctx, names) {
92236
92338
  tenant: "v_order.tenant",
92237
92339
  audit: false
92238
92340
  });
92239
- const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, x.${f("status")} as status into v_fulfillment
92341
+ const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, ${ctx.label("fulfillments", "status", `x.${f("status")}`)} as status into v_fulfillment
92240
92342
  from ${fulfillments} x where x.${f("id")} = ${id} for update;
92241
92343
  if not found then
92242
92344
  ${fail$1("ORDERS_FULFILLMENT_NOT_FOUND", "fulfillment not found", "P0002")}
92243
92345
  end if;
92244
92346
  ${load("v_fulfillment.order_id")}`;
92245
- const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, x.${r("status")} as status into v_return
92347
+ const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, ${ctx.label("returns", "status", `x.${r("status")}`)} as status into v_return
92246
92348
  from ${returns} x where x.${r("id")} = ${id} for update;
92247
92349
  if not found then
92248
92350
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found", "P0002")}
@@ -92322,7 +92424,7 @@ begin
92322
92424
  if v_fulfillment.status <> 'pending' then
92323
92425
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a pending fulfillment can ship", "55000")}
92324
92426
  end if;${unsupported(trackingUrl, "ship_fulfillment.tracking_url", "ORDERS_TRACKING_URL_UNSUPPORTED", "this fulfillment table has no tracking URL column")}
92325
- update ${fulfillments} x set ${f("status")} = 'shipped', ${f("shippedAt")} = now(),
92427
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "shipped")}, ${f("shippedAt")} = now(),
92326
92428
  ${f("carrier")} = coalesce(ship_fulfillment.carrier, x.${f("carrier")}),
92327
92429
  ${f("trackingNumber")} = coalesce(ship_fulfillment.tracking_number, x.${f("trackingNumber")})${trackingUrl ? `,
92328
92430
  ${f("trackingUrl")} = coalesce(ship_fulfillment.tracking_url, x.${f("trackingUrl")})` : ""}
@@ -92330,7 +92432,7 @@ begin
92330
92432
  ${partEvent("fulfillment.shipped", "v_fulfillment.id", [["carrier", `(select x.${f("carrier")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`], ["trackingNumber", `(select x.${f("trackingNumber")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`]])}
92331
92433
  if v_order.status = 'paid'
92332
92434
  and not exists (select 1 from ${lines} l where l.${ol("order")} = v_order.id and l.${ol("fulfilled")} < l.${ol("quantity")})
92333
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} = 'pending') then
92435
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending"])}) then
92334
92436
  perform ${fn("order_transition")}(v_order.id, 'fulfilled');
92335
92437
  ${event("order.fulfilled", [])}
92336
92438
  end if;
@@ -92359,10 +92461,10 @@ begin
92359
92461
  if v_fulfillment.status <> 'shipped' then
92360
92462
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a shipped fulfillment can be delivered", "55000")}
92361
92463
  end if;
92362
- update ${fulfillments} x set ${f("status")} = 'delivered', ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92464
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "delivered")}, ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92363
92465
  ${partEvent("fulfillment.delivered", "v_fulfillment.id", [])}
92364
92466
  if v_order.status = 'fulfilled'
92365
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} in ('pending', 'shipped')) then
92467
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending", "shipped"])}) then
92366
92468
  perform ${fn("order_transition")}(v_order.id, 'completed');
92367
92469
  ${event("order.completed", [])}
92368
92470
  end if;
@@ -92393,7 +92495,7 @@ begin
92393
92495
  update ${lines} x set ${ol("fulfilled")} = x.${ol("fulfilled")} - y.${fl("quantity")}
92394
92496
  from ${fulfillmentLines} y
92395
92497
  where y.${fl("fulfillment")} = v_fulfillment.id and x.${ol("id")} = y.${fl("line")};
92396
- update ${fulfillments} x set ${f("status")} = 'cancelled' where x.${f("id")} = v_fulfillment.id;
92498
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "cancelled")} where x.${f("id")} = v_fulfillment.id;
92397
92499
  return true;
92398
92500
  end;
92399
92501
  $$;
@@ -92435,7 +92537,7 @@ begin
92435
92537
  end if;
92436
92538
  select coalesce(sum(y.${rl("quantity")}), 0) into v_open
92437
92539
  from ${returnLines} y join ${returns} z on z.${r("id")} = y.${rl("return")}
92438
- where y.${rl("line")} = v_item.line and z.${r("status")} = 'requested';
92540
+ where y.${rl("line")} = v_item.line and ${ctx.is("returns", "status", `z.${r("status")}`, ["requested"])};
92439
92541
  if not exists (select 1 from ${lines} l where l.${ol("id")} = v_item.line and l.${ol("order")} = v_order.id
92440
92542
  and l.${ol("fulfilled")} - l.${ol("returned")} - v_open >= v_item.quantity) then
92441
92543
  ${fail$1("ORDERS_RETURN_INVALID", "a line isn't on this order or has fewer fulfilled units left to return", "22023")}
@@ -92481,7 +92583,7 @@ begin
92481
92583
  update ${lines} x set ${ol("returned")} = x.${ol("returned")} + v_line.quantity where x.${ol("id")} = v_line.line;${restock(ctx)}
92482
92584
  v_units := v_units + v_line.quantity;
92483
92585
  end loop;
92484
- update ${returns} x set ${r("status")} = 'received', ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92586
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "received")}, ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92485
92587
  ${partEvent("return.received", "v_return.id", [["quantity", "v_units::text"]])}
92486
92588
  return true;
92487
92589
  end;
@@ -92503,7 +92605,7 @@ begin
92503
92605
  if v_return.status <> 'requested' then
92504
92606
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a requested return can be rejected", "55000")}
92505
92607
  end if;
92506
- update ${returns} x set ${r("status")} = 'rejected' where x.${r("id")} = v_return.id;
92608
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "rejected")} where x.${r("id")} = v_return.id;
92507
92609
  return true;
92508
92610
  end;
92509
92611
  $$;
@@ -92534,7 +92636,7 @@ begin
92534
92636
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found on this order", "P0002")}
92535
92637
  end if;
92536
92638
  select coalesce(sum(x.${rf("amount")}), 0) into v_pending from ${refunds} x
92537
- where x.${rf("order")} = v_order.id and x.${rf("status")} = 'pending';
92639
+ where x.${rf("order")} = v_order.id and ${ctx.is("refunds", "status", `x.${rf("status")}`, ["pending"])};
92538
92640
  v_left := v_order.paid_total - v_order.refunded_total - v_pending;
92539
92641
  v_amount := coalesce(create_refund.amount, v_left);
92540
92642
  if v_amount <= 0 or v_amount > v_left then
@@ -92542,9 +92644,9 @@ begin
92542
92644
  end if;
92543
92645
  select y.${p("id")} as id, y.${p("provider")} as provider, y.${p("reference")} as reference into v_payment
92544
92646
  from ${payments} y
92545
- where y.${p("order")} = v_order.id and y.${p("status")} = 'succeeded'
92647
+ where y.${p("order")} = v_order.id and ${ctx.is("payments", "status", `y.${p("status")}`, ["succeeded"])}
92546
92648
  and y.${p("captured")} - y.${p("refunded")} - coalesce((select sum(z.${rf("amount")}) from ${refunds} z
92547
- where z.${rf("payment")} = y.${p("id")} and z.${rf("status")} = 'pending'), 0) >= v_amount
92649
+ where z.${rf("payment")} = y.${p("id")} and ${ctx.is("refunds", "status", `z.${rf("status")}`, ["pending"])}), 0) >= v_amount
92548
92650
  order by y.${p("createdAt")} desc
92549
92651
  limit 1;
92550
92652
  if not found then
@@ -92581,7 +92683,7 @@ begin
92581
92683
  ${fail$1("ORDERS_REFUND_STATUS_INVALID", "status is pending, succeeded or failed", "22023")}
92582
92684
  end if;
92583
92685
  select x.${rf("id")} as id, x.${rf("order")} as order_id, x.${rf("payment")} as payment, x.${rf("amount")} as amount,
92584
- x.${rf("status")} as status
92686
+ ${ctx.label("refunds", "status", `x.${rf("status")}`)} as status
92585
92687
  into v_refund from ${refunds} x
92586
92688
  where (complete_refund.refund is not null and x.${rf("id")} = complete_refund.refund)
92587
92689
  or (complete_refund.refund is null and x.${rf("providerReference")} = complete_refund.provider_reference)
@@ -92610,12 +92712,12 @@ begin
92610
92712
  ["currency", "v_order.currency"],
92611
92713
  ["amount", "v_refund.amount::text"],
92612
92714
  ["refundedTotal", "v_total::text"],
92613
- ["status", `(select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id)`]
92715
+ ["status", `(select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id)`]
92614
92716
  ], "'order.refunded:' || v_refund.id::text")}
92615
92717
  end if;
92616
92718
  end if;
92617
- return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', x.${rf("status")},
92618
- 'amount', x.${rf("amount")}::text, 'orderStatus', y.${o("status")}, 'refundedTotal', y.${o("refundedTotal")}::text)
92719
+ return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', ${ctx.label("refunds", "status", `x.${rf("status")}`)},
92720
+ 'amount', x.${rf("amount")}::text, 'orderStatus', ${ctx.label("orders", "status", `y.${o("status")}`)}, 'refundedTotal', y.${o("refundedTotal")}::text)
92619
92721
  from ${refunds} x join ${orders} y on y.${o("id")} = x.${rf("order")} where x.${rf("id")} = v_refund.id);
92620
92722
  end;
92621
92723
  $$;
@@ -92642,7 +92744,7 @@ function addressCheck(address) {
92642
92744
  function ownCart(ctx, id, options = {}) {
92643
92745
  const c = columns(ctx, "carts");
92644
92746
  const readers = options.readers === void 0 ? "" : ` or ${ctx.scope.can("v_cart.tenant", options.readers)}`;
92645
- return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status,
92747
+ return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status,
92646
92748
  x.${c("currency")} as currency, x.${c("priceList")} as price_list, x.${c("shippingAddress")} as shipping_address
92647
92749
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = ${id}${options.lock ? " for update" : ""};
92648
92750
  if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()${readers}) then
@@ -92661,7 +92763,7 @@ function sellable(ctx, variant) {
92661
92763
  const p = columns(catalog, "products");
92662
92764
  return `if not exists (
92663
92765
  select 1 from ${catalog.table("variants")} cv join ${catalog.table("products")} cp on cp.${p("id")} = cv.${v("product")}
92664
- where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and cp.${p("status")} = 'active'
92766
+ where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and ${catalog.is("products", "status", `cp.${p("status")}`, ["active"])}
92665
92767
  ) then
92666
92768
  ${fail$1("ORDERS_VARIANT_UNAVAILABLE", "this variant is not for sale", "P0002")}
92667
92769
  end if;`;
@@ -92804,11 +92906,11 @@ declare
92804
92906
  begin
92805
92907
  select x.${c("tenant")} as tenant, x.${c("currency")} as currency, x.${c("priceList")} as price_list,
92806
92908
  x.${c("shippingAddress")} as shipping_address, x.${c("shippingRate")} as shipping_rate,
92807
- x.${c("user")} as owner, x.${c("status")} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
92909
+ x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
92808
92910
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = p_cart;
92809
92911
  for v_line in
92810
92912
  select l.${cl("id")} as id, l.${cl("variant")} as variant, l.${cl("quantity")} as quantity, l.${cl("unitAmount")} as unit_amount,
92811
- cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, cp.${p("status")} as status,
92913
+ cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, ${catalog.label("products", "status", `cp.${p("status")}`)} as status,
92812
92914
  ${kind} as kind, ${weight} as weight
92813
92915
  from ${ctx.table("cartLines")} l
92814
92916
  join ${catalog.table("variants")} cv on cv.${v("id")} = l.${cl("variant")}
@@ -92843,7 +92945,7 @@ begin
92843
92945
  from jsonb_array_elements(v_lines) with ordinality as e(l, n);
92844
92946
  v_country := v_cart.shipping_address ->> 'country';
92845
92947
  if v_ships and v_cart.shipping_rate is not null then
92846
- select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, x.${s("kind")} as kind,
92948
+ select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)} as kind,
92847
92949
  x.${s("amount")} as amount, x.${s("perKg")} as per_kg, ${or("shippingRates", "x", "freeOver", "bigint")} as free_over
92848
92950
  into v_rate from ${ctx.table("shippingRates")} x
92849
92951
  where x.${s("id")} = v_cart.shipping_rate and x.${s("active")} and x.${s("currency")} = v_cart.currency;
@@ -92922,7 +93024,7 @@ begin
92922
93024
  end if;`}
92923
93025
  insert into ${carts} as x (${c("tenant")}, ${c("user")}, ${c("currency")}, ${c("priceList")}${email ? `, ${c("email")}` : ""})
92924
93026
  values (create_cart.tenant, auth.uid(), create_cart.currency, create_cart.price_list${email ? ", create_cart.email" : ""})
92925
- on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open' do update
93027
+ on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])} do update
92926
93028
  set ${c("priceList")} = coalesce(excluded.${c("priceList")}, x.${c("priceList")}),${email ? `
92927
93029
  ${c("email")} = coalesce(excluded.${c("email")}, x.${c("email")}),` : ""} ${c("updatedAt")} = now()
92928
93030
  returning x.${c("id")} into v_id;
@@ -93076,10 +93178,10 @@ begin
93076
93178
  v_weight := (v_totals ->> 'weightGrams')::bigint;
93077
93179
  return coalesce((
93078
93180
  select jsonb_agg(jsonb_build_object(
93079
- 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', x.${s("kind")}, 'currency', x.${s("currency")},
93181
+ 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)}, 'currency', x.${s("currency")},
93080
93182
  'amount', (case
93081
93183
  ${ctx.has("shippingRates", "freeOver") ? ` when x.${s("freeOver")} is not null and v_after_discount >= x.${s("freeOver")} then 0
93082
- ` : ""} else x.${s("amount")} + case when x.${s("kind")} = 'weight' then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93184
+ ` : ""} else x.${s("amount")} + case when ${ctx.is("shippingRates", "kind", `x.${s("kind")}`, ["weight"])} then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93083
93185
  end)::text) order by x.${s("amount")}, x.${s("name")})
93084
93186
  from ${ctx.table("shippingRates")} x
93085
93187
  where x.${s("tenant")} = v_cart.tenant and x.${s("active")} and x.${s("currency")} = v_cart.currency
@@ -93128,12 +93230,12 @@ begin
93128
93230
  end if;
93129
93231
  for v_from in
93130
93232
  select x.${c("id")} as id, x.${c("tenant")} as tenant, x.${c("currency")} as currency
93131
- from ${carts} x where x.${c("user")} = merge_carts.from_user and x.${c("status")} = 'open'
93233
+ from ${carts} x where x.${c("user")} = merge_carts.from_user and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93132
93234
  for update
93133
93235
  loop
93134
93236
  select x.${c("id")} into v_to from ${carts} x
93135
93237
  where x.${c("user")} = merge_carts.to_user and x.${c("tenant")} = v_from.tenant
93136
- and x.${c("currency")} = v_from.currency and x.${c("status")} = 'open'
93238
+ and x.${c("currency")} = v_from.currency and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93137
93239
  for update;
93138
93240
  if v_to is null then
93139
93241
  update ${carts} x set ${c("user")} = merge_carts.to_user, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
@@ -93143,7 +93245,7 @@ begin
93143
93245
  from ${lines} l where l.${cl("cart")} = v_from.id
93144
93246
  on conflict (${cl("cart")}, ${cl("variant")}) do update
93145
93247
  set ${cl("quantity")} = least(x.${cl("quantity")} + excluded.${cl("quantity")}, ${MAX_QUANTITY}), ${cl("updatedAt")} = now();${moveCodes}
93146
- update ${carts} x set ${c("status")} = 'abandoned', ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93248
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "abandoned")}, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93147
93249
  end if;
93148
93250
  v_to := null;
93149
93251
  v_count := v_count + 1;
@@ -93193,7 +93295,11 @@ function orderInvoice(ctx) {
93193
93295
  }
93194
93296
  const PAYMENT_STATUSES = "('requires_action', 'processing', 'authorized', 'succeeded', 'failed', 'canceled')";
93195
93297
  /** Payment statuses a late webhook can't move a payment back from. */
93196
- const SETTLED = "('succeeded', 'failed', 'canceled')";
93298
+ const SETTLED = [
93299
+ "succeeded",
93300
+ "failed",
93301
+ "canceled"
93302
+ ];
93197
93303
  /**
93198
93304
  * `order_json(order)`: the order with its lines, payments, fulfillments,
93199
93305
  * returns and refunds.
@@ -93221,7 +93327,7 @@ set search_path = ''
93221
93327
  as $$
93222
93328
  select jsonb_build_object(
93223
93329
  'id', x.${o("id")}, 'organizationId', x.${o("tenant")}, 'number', x.${o("number")}, 'cartId', x.${o("cart")},
93224
- 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', x.${o("status")}, 'currency', x.${o("currency")},
93330
+ 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', ${ctx.label("orders", "status", `x.${o("status")}`)}, 'currency', x.${o("currency")},
93225
93331
  'subtotal', ${text("x", o("subtotal"))}, 'discountTotal', ${text("x", o("discountTotal"))},
93226
93332
  'shippingTotal', ${text("x", o("shippingTotal"))}, 'taxTotal', ${text("x", o("taxTotal"))}, 'total', ${text("x", o("total"))},
93227
93333
  'paidTotal', ${text("x", o("paidTotal"))}, 'refundedTotal', ${text("x", o("refundedTotal"))}, 'taxInclusive', x.${o("taxInclusive")},
@@ -93239,26 +93345,26 @@ as $$
93239
93345
  'backordered', l.${ol("backordered")}) order by l.${ol("position")})
93240
93346
  from ${ctx.table("orderLines")} l where l.${ol("order")} = x.${o("id")}), '[]'::jsonb),
93241
93347
  'payments', coalesce((select jsonb_agg(jsonb_build_object(
93242
- 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', y.${p("status")},
93348
+ 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', ${ctx.label("payments", "status", `y.${p("status")}`)},
93243
93349
  'amount', ${text("y", p("amount"))}, 'captured', ${text("y", p("captured"))}, 'refunded', ${text("y", p("refunded"))},
93244
93350
  'createdAt', y.${p("createdAt")}) order by y.${p("createdAt")})
93245
93351
  from ${ctx.table("payments")} y where y.${p("order")} = x.${o("id")}), '[]'::jsonb),
93246
93352
  'fulfillments', coalesce((select jsonb_agg(jsonb_build_object(
93247
- 'id', y.${f("id")}, 'status', y.${f("status")}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93353
+ 'id', y.${f("id")}, 'status', ${ctx.label("fulfillments", "status", `y.${f("status")}`)}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93248
93354
  'trackingNumber', y.${f("trackingNumber")}, 'trackingUrl', ${or("fulfillments", "y", "trackingUrl")}, 'createdAt', y.${f("createdAt")},
93249
93355
  'shippedAt', y.${f("shippedAt")}, 'deliveredAt', y.${f("deliveredAt")},
93250
93356
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${fl("line")}, 'quantity', z.${fl("quantity")}))
93251
93357
  from ${ctx.table("fulfillmentLines")} z where z.${fl("fulfillment")} = y.${f("id")}), '[]'::jsonb)) order by y.${f("createdAt")})
93252
93358
  from ${ctx.table("fulfillments")} y where y.${f("order")} = x.${o("id")}), '[]'::jsonb),
93253
93359
  'returns', coalesce((select jsonb_agg(jsonb_build_object(
93254
- 'id', y.${r("id")}, 'status', y.${r("status")}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93360
+ 'id', y.${r("id")}, 'status', ${ctx.label("returns", "status", `y.${r("status")}`)}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93255
93361
  'receivedAt', y.${r("receivedAt")},
93256
93362
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${rl("line")}, 'quantity', z.${rl("quantity")}))
93257
93363
  from ${ctx.table("returnLines")} z where z.${rl("return")} = y.${r("id")}), '[]'::jsonb)) order by y.${r("createdAt")})
93258
93364
  from ${ctx.table("returns")} y where y.${r("order")} = x.${o("id")}), '[]'::jsonb),
93259
93365
  'refunds', coalesce((select jsonb_agg(jsonb_build_object(
93260
93366
  'id', y.${rf("id")}, 'paymentId', y.${rf("payment")}, 'returnId', y.${rf("return")}, 'amount', ${text("y", rf("amount"))},
93261
- 'status', y.${rf("status")}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93367
+ 'status', ${ctx.label("refunds", "status", `y.${rf("status")}`)}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93262
93368
  'createdAt', y.${rf("createdAt")}, 'completedAt', y.${rf("completedAt")}) order by y.${rf("createdAt")})
93263
93369
  from ${ctx.table("refunds")} y where y.${rf("order")} = x.${o("id")}), '[]'::jsonb)${extraFieldsJson("x", names.extras)})
93264
93370
  from ${ctx.table("orders")} x where x.${o("id")} = p_order
@@ -93356,6 +93462,7 @@ function releaseLines(ctx) {
93356
93462
  function checkoutFunctions(ctx, names) {
93357
93463
  const { fn } = names;
93358
93464
  const minutes = paymentWindow(ctx);
93465
+ const settled = (value, negate = false) => ctx.is("payments", "status", value, SETTLED, negate);
93359
93466
  const carts = ctx.table("carts");
93360
93467
  const orders = ctx.table("orders");
93361
93468
  const payments = ctx.table("payments");
@@ -93415,7 +93522,7 @@ declare
93415
93522
  v_claims text;
93416
93523
  begin
93417
93524
  ${serviceOnlyGuard()}
93418
- select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status, x.${c("currency")} as currency,
93525
+ select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, x.${c("currency")} as currency,
93419
93526
  ${cartOr("email", "text")} as email, x.${c("shippingAddress")} as shipping_address, ${cartOr("billingAddress", "jsonb")} as billing_address
93420
93527
  into v_cart from ${carts} x where x.${c("id")} = place_order.cart for update;
93421
93528
  if not found then
@@ -93478,7 +93585,7 @@ begin
93478
93585
  from jsonb_array_elements(v_priced -> 'lines') with ordinality as e(l, n);
93479
93586
  ${load("v_id", false)}${reserveLines(ctx, minutes)}${promotions === void 0 ? "" : `
93480
93587
  perform ${promotions.fn("redeem_promotions")}(v_order.id, v_priced -> 'promotions');`}
93481
- update ${carts} x set ${c("status")} = 'converted', ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93588
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "converted")}, ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93482
93589
  where x.${c("id")} = place_order.cart;
93483
93590
  ${ctx.record({
93484
93591
  type: "order.placed",
@@ -93550,7 +93657,7 @@ begin
93550
93657
  values (v_order.tenant, v_order.id, record_payment.provider, record_payment.reference, ${ctx.cast("payments", "status", "record_payment.status")}, record_payment.currency,
93551
93658
  record_payment.amount, coalesce(record_payment.captured, 0), coalesce(record_payment.refunded, 0))
93552
93659
  on conflict (${p("provider")}, ${p("reference")}) do update set
93553
- ${p("status")} = case when x.${p("status")} in ${SETTLED} and excluded.${p("status")} not in ${SETTLED} then x.${p("status")} else excluded.${p("status")} end,
93660
+ ${p("status")} = case when ${settled(`x.${p("status")}`)} and ${settled(`excluded.${p("status")}`, true)} then x.${p("status")} else excluded.${p("status")} end,
93554
93661
  ${p("amount")} = excluded.${p("amount")},
93555
93662
  ${p("captured")} = greatest(x.${p("captured")}, excluded.${p("captured")}),
93556
93663
  ${p("refunded")} = greatest(x.${p("refunded")}, excluded.${p("refunded")}),
@@ -93560,7 +93667,7 @@ begin
93560
93667
  ${fail$1("ORDERS_PAYMENT_CONFLICT", "this payment reference belongs to another order", "23505")}
93561
93668
  end if;
93562
93669
  select coalesce(sum(x.${p("captured")}), 0) into v_paid from ${payments} x
93563
- where x.${p("order")} = v_order.id and x.${p("status")} = 'succeeded';
93670
+ where x.${p("order")} = v_order.id and ${ctx.is("payments", "status", `x.${p("status")}`, ["succeeded"])};
93564
93671
  update ${orders} x set ${o("paidTotal")} = v_paid, ${o("updatedAt")} = now() where x.${o("id")} = v_order.id;
93565
93672
  if v_order.status = 'pending_payment' and v_paid >= v_order.total then
93566
93673
  perform ${fn("order_transition")}(v_order.id, 'paid');${commitLines(ctx)}
@@ -93587,7 +93694,7 @@ begin
93587
93694
  })}
93588
93695
  v_newly := true;
93589
93696
  end if;
93590
- return jsonb_build_object('orderId', v_order.id, 'status', (select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id),
93697
+ return jsonb_build_object('orderId', v_order.id, 'status', (select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id),
93591
93698
  'paidTotal', v_paid::text, 'newlyPaid', v_newly,
93592
93699
  'invoiceNumber', coalesce(v_number, v_order.invoice_number)${invoice ? `, 'invoiceId', v_invoice ->> ${sqlString(invoice.id)}` : ""});
93593
93700
  end;
@@ -93678,7 +93785,7 @@ begin
93678
93785
  ${serviceOnlyGuard()}
93679
93786
  for v_id in
93680
93787
  select x.${o("id")} from ${orders} x
93681
- where x.${o("status")} = 'pending_payment' and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
93788
+ where ${ctx.is("orders", "status", `x.${o("status")}`, ["pending_payment"])} and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
93682
93789
  order by x.${o("placedAt")}
93683
93790
  limit greatest(coalesce(expire_orders.max_rows, 100), 1)
93684
93791
  for update skip locked
@@ -94183,7 +94290,7 @@ as $$
94183
94290
  'orderId', o.${o("id")},
94184
94291
  'number', o.${o("number")},
94185
94292
  'customerId', o.${o("customer")},
94186
- 'status', o.${o("status")},
94293
+ 'status', ${ctx.label("orders", "status", `o.${o("status")}`)},
94187
94294
  'state', (${STATES})[min(${rank(stateOf("p"))})],
94188
94295
  'sentAt', min(p.${lp("queuedAt")}),
94189
94296
  'readyAt', case when bool_and(p.${lp("readyAt")} is not null) then max(p.${lp("readyAt")}) end,
@@ -94681,7 +94788,7 @@ create table if not exists ${t("carts")} (
94681
94788
  ${c("updatedAt")} timestamptz not null default now(),
94682
94789
  ${c("convertedAt")} timestamptz
94683
94790
  );
94684
- create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open';
94791
+ create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])};
94685
94792
  create index if not exists ${ctx.naming.rename("carts_user_idx")} on ${t("carts")} (${c("user")});
94686
94793
  create index if not exists ${ctx.naming.rename("carts_rate_idx")} on ${t("carts")} (${c("shippingRate")});
94687
94794
  ${c("priceList") && priceList ? `create index if not exists ${ctx.naming.rename("carts_price_list_idx")} on ${t("carts")} (${c("priceList")});\n` : ""}${lockModuleTable(ctx, "carts", { read: true })}
@@ -98383,7 +98490,7 @@ function pipelineBindings(ctx) {
98383
98490
  return Object.entries(raw).map(([type, entry]) => {
98384
98491
  const where = `blocks.${ctx.instance}.on.${type}`;
98385
98492
  const subject = registry.find((item) => item.type === type);
98386
- if (subject === void 0) throw new TypeError(`${where}: register "${type}" in config.records first`);
98493
+ if (subject === void 0) throw new TypeError(`${where}: register "${type}" in config.subjects first`);
98387
98494
  if (subject.tenant === void 0) throw new TypeError(`${where}: config.subjects.${type} needs a tenant column`);
98388
98495
  if (!isRecord$1(entry)) throw new TypeError(`${where} must be an object`);
98389
98496
  const categories = categoriesOf(where, entry["categories"]);
@@ -99489,8 +99596,8 @@ ${renderPolicy(policy$1({
99489
99596
  * the ones the app lacks.
99490
99597
  */
99491
99598
  function rowJson(ctx, table, alias) {
99492
- if (ctx.owns(table)) return `to_jsonb(${alias})`;
99493
- return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? `${alias}.${ctx.col(table, logical)}` : "null"}`).join(", ")})`;
99599
+ if (ctx.owns(table)) return ctx.rowJson(table, alias);
99600
+ return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? ctx.label(table, logical, `${alias}.${ctx.col(table, logical)}`) : "null"}`).join(", ")})`;
99494
99601
  }
99495
99602
  /**
99496
99603
  * `options.extraColumns`, added to the pipelines table. `stages` is reserved:
@@ -103667,7 +103774,7 @@ function build$33(ctx) {
103667
103774
  if (ctx.mode === "custom") return "";
103668
103775
  const subjects = ranked(ctx);
103669
103776
  const fn = (name) => ctx.fn(name);
103670
- const unknown = fail$1("RANK_SUBJECT_UNKNOWN", "this subject type has no rank column in config.records", "22023");
103777
+ const unknown = fail$1("RANK_SUBJECT_UNKNOWN", "this subject type has no rank column in config.subjects", "22023");
103671
103778
  const invalid = (arg) => `if ${arg} is not null and ${arg} !~ '^[0-9A-Za-z]*[1-9A-Za-z]$' then
103672
103779
  ${fail$1("RANK_KEY_INVALID", "not a rank key", "22023")}
103673
103780
  end if;`;
@@ -103834,7 +103941,7 @@ const RANK = {
103834
103941
  name: "rank",
103835
103942
  scopes: ["tenant"],
103836
103943
  title: "Rank",
103837
- description: "Fractional rank keys: rank_between, move() for every config.records entry with a rank column (through the caller's policies and any state-machine trigger), and a rebalance job.",
103944
+ description: "Fractional rank keys: rank_between, move() for every config.subjects entry with a rank column (through the caller's policies and any state-machine trigger), and a rebalance job.",
103838
103945
  requires: ["permissions", "subjects"],
103839
103946
  integrates: ["queue"],
103840
103947
  target: "schema",
@@ -109357,7 +109464,7 @@ begin
109357
109464
  case search_refresh.subject_type
109358
109465
  ${cases}
109359
109466
  else
109360
- ${fail$1("SEARCH_SUBJECT_UNKNOWN", "this subject type has no search entry in config.records", "22023")}
109467
+ ${fail$1("SEARCH_SUBJECT_UNKNOWN", "this subject type has no search entry in config.subjects", "22023")}
109361
109468
  end case;
109362
109469
  if not v_found then
109363
109470
  delete from ${docs}
@@ -109513,7 +109620,7 @@ const SEARCH = {
109513
109620
  name: "search",
109514
109621
  scopes: ["tenant"],
109515
109622
  title: "Search",
109516
- description: "A search_documents index kept up by triggers from each config.records search entry, with search(q) as the caller (websearch, trigram prefixes, can_subject, hybrid with embeddings), and recents and favorites from the share-links user state.",
109623
+ description: "A search_documents index kept up by triggers from each config.subjects search entry, with search(q) as the caller (websearch, trigram prefixes, can_subject, hybrid with embeddings), and recents and favorites from the share-links user state.",
109517
109624
  requires: [
109518
109625
  "memberships",
109519
109626
  "permissions",
@@ -110364,7 +110471,7 @@ function matchingIds(ctx, n) {
110364
110471
  limit ${String(n.maxMembers + 1)}
110365
110472
  ) x;`;
110366
110473
  };
110367
- const unknown = fail$1("SEGMENT_SUBJECT_UNKNOWN", "The segment's subject type is not registered in config.records", "22023");
110474
+ const unknown = fail$1("SEGMENT_SUBJECT_UNKNOWN", "The segment's subject type is not registered in config.subjects", "22023");
110368
110475
  if (n.subjects.length === 0) return unknown;
110369
110476
  return `${n.subjects.map(branch).join("\n els")}
110370
110477
  else
@@ -110441,7 +110548,7 @@ begin
110441
110548
  end if;
110442
110549
  v_type := coalesce(v_old.${s("subjectType")}, segment ->> 'subjectType');
110443
110550
  if v_type is null or v_type not in ${knownList} then
110444
- ${fail$1("SEGMENT_SUBJECT_UNKNOWN", "subjectType must be a type in config.records", "22023")}
110551
+ ${fail$1("SEGMENT_SUBJECT_UNKNOWN", "subjectType must be a type in config.subjects", "22023")}
110445
110552
  end if;
110446
110553
  v_name := coalesce(nullif(trim(segment ->> 'name'), ''), v_old.${s("name")});
110447
110554
  if v_name is null or length(v_name) > 200 then
@@ -113368,8 +113475,9 @@ function functions$1(ctx, extras) {
113368
113475
  const fields = extraFieldsArg(extras);
113369
113476
  const linked = ctx.has("shipments", "subjectType") && ctx.has("shipments", "subjectId");
113370
113477
  const location = ctx.has("shipments", "fromLocation");
113371
- const shipStatus = (row) => asText$2(ctx, "shipments", `${row}.${h("status")}`);
113372
- const eventStatus = (row) => asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113478
+ const shipStatus = (row) => ctx.mapsValues("shipments", "status") ? ctx.label("shipments", "status", `${row}.${h("status")}`) : asText$2(ctx, "shipments", `${row}.${h("status")}`);
113479
+ const eventStatus = (row) => ctx.mapsValues("trackingEvents", "status") ? ctx.label("trackingEvents", "status", `${row}.${e("status")}`) : asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113480
+ const st = (row, labels, negate = false) => ctx.is("shipments", "status", `${row}.${h("status")}`, labels, negate);
113373
113481
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
113374
113482
  const also = (table, logical) => ctx.has(table, logical) ? `, ${ctx.col(table, logical)}` : "";
113375
113483
  const alsoValue = (table, logical, value) => ctx.has(table, logical) ? `, ${value}` : "";
@@ -113377,8 +113485,8 @@ function functions$1(ctx, extras) {
113377
113485
  const lines = (...groups) => groups.map((group) => group.filter((value) => value !== void 0).join(", ")).filter((line) => line !== "").join(",\n ");
113378
113486
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
113379
113487
  const packagesJson = (row) => `(select coalesce(jsonb_agg(jsonb_build_object('id', pk.${p("id")}, 'position', pk.${p("position")}, 'weightGrams', pk.${p("weight")}, 'lengthMm', ${or("packages", "pk", "length")}, 'widthMm', ${or("packages", "pk", "width")}, 'heightMm', ${or("packages", "pk", "height")}, 'reference', ${or("packages", "pk", "reference")}) order by pk.${p("position")}), '[]'::jsonb) from ${packages} pk where pk.${p("shipment")} = ${row}.${h("id")})`;
113380
- const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${row}.${h("status")}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113381
- const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${row}.${e("status")}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113488
+ const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${ctx.label("shipments", "status", `${row}.${h("status")}`)}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113489
+ const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${ctx.label("trackingEvents", "status", `${row}.${e("status")}`)}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113382
113490
  const subject = (row) => `'shipments/' || ${row}.${h("id")}::text`;
113383
113491
  const base = (row) => `'organizationId', ${row}.${h("tenant")}::text, 'id', ${row}.${h("id")}`;
113384
113492
  const audited = (row, summary) => ({
@@ -113405,7 +113513,7 @@ function functions$1(ctx, extras) {
113405
113513
  end;`;
113406
113514
  const statusRecord = ctx.record({
113407
113515
  type: "shipment.status_changed",
113408
- payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', v_ship.${h("status")}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113516
+ payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113409
113517
  subject: subject("v_ship"),
113410
113518
  tenant: `v_ship.${h("tenant")}`,
113411
113519
  audit: false
@@ -113415,8 +113523,8 @@ function functions$1(ctx, extras) {
113415
113523
  where t.${e("shipment")} = v_ship.${h("id")}
113416
113524
  order by t.${e("occurredAt")} desc, array_position(array[${list(TRACKING_STATUSES)}]::text[], ${eventStatus("t")}) desc
113417
113525
  limit 1;
113418
- if v_status is not null and v_ship.${h("status")} <> 'cancelled' and v_status <> ${shipStatus("v_ship")} then
113419
- v_from := v_ship.${h("status")};
113526
+ if v_status is not null and ${st("v_ship", ["cancelled"], true)} and v_status <> ${shipStatus("v_ship")} then
113527
+ v_from := ${ctx.label("shipments", "status", `v_ship.${h("status")}`)};
113420
113528
  update ${shipments} x set
113421
113529
  ${h("status")} = ${ctx.cast("shipments", "status", "v_status")},
113422
113530
  ${h("deliveredAt")} = case when v_status = 'delivered' then v_at end,
@@ -113588,7 +113696,7 @@ declare
113588
113696
  v_ship ${shipments}%rowtype;${syncDeclare}
113589
113697
  begin
113590
113698
  ${findForWrite("set_shipment_label.shipment_id")}
113591
- if v_ship.${h("status")} <> 'draft' then
113699
+ if ${st("v_ship", ["draft"], true)} then
113592
113700
  ${fail$1("SHIPMENT_NOT_DRAFT", "only a draft shipment gets a label", "55000")}
113593
113701
  end if;
113594
113702
  begin
@@ -113614,7 +113722,7 @@ ${findForWrite("set_shipment_label.shipment_id")}
113614
113722
  ${fail$1("SHIPMENT_LABEL_INVALID", "a label needs a carrier, service, tracking number, label id, a cost of zero or more and a currency", "22023")}
113615
113723
  end if;
113616
113724
  insert into ${events} (${e("tenant")}, ${e("shipment")}, ${e("externalId")}, ${e("status")}, ${e("occurredAt")}${also("trackingEvents", "description")}, ${e("source")})
113617
- values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, 'label_created', now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113725
+ values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, ${ctx.value("trackingEvents", "status", "label_created")}, now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113618
113726
  on conflict (${e("shipment")}, ${e("externalId")}) do nothing;
113619
113727
  ${ctx.record({
113620
113728
  type: "shipment.labeled",
@@ -113678,7 +113786,7 @@ begin
113678
113786
  end if;
113679
113787
  ${insertEvents("ingest_tracking_events.events", "'webhook'")}
113680
113788
  ${syncStatus}
113681
- return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', v_ship.${h("status")}, 'recorded', v_count);
113789
+ return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'recorded', v_count);
113682
113790
  end;
113683
113791
  $$;
113684
113792
  ${serviceGrant(`${fn("ingest_tracking_events")}(text, text, jsonb)`)}
@@ -113696,11 +113804,11 @@ declare
113696
113804
  v_ship ${shipments}%rowtype;
113697
113805
  begin
113698
113806
  ${findForWrite("cancel_shipment.shipment_id")}
113699
- if v_ship.${h("status")} not in ('draft', 'label_created') then
113807
+ if ${st("v_ship", ["draft", "label_created"], true)} then
113700
113808
  ${fail$1("SHIPMENT_SHIPPED", "only a draft or a shipment that hasn't left gets cancelled", "55000")}
113701
113809
  end if;
113702
113810
  update ${shipments} x set
113703
- ${h("status")} = 'cancelled',
113811
+ ${h("status")} = ${ctx.value("shipments", "status", "cancelled")},
113704
113812
  ${h("cancelledAt")} = now(),
113705
113813
  ${h("updatedAt")} = now()
113706
113814
  where x.${h("id")} = v_ship.${h("id")}
@@ -115336,8 +115444,9 @@ function workItemFunctions(ctx, n) {
115336
115444
  if ${attrs} ->> ${sqlString(key)} is not null then
115337
115445
  ${fail$1("WORK_ITEM_FIELD_UNSUPPORTED", `this ${ctx.tableName(table).name} table has no ${logical} column`, "22023")}
115338
115446
  end if;`).join("");
115447
+ const extrasInsert = insertExtraColumns(t("items"), n.extras, "(create_work_item.attrs -> 'fields')");
115339
115448
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${w("tenant")}`, n.write)})`;
115340
- const row = (alias) => `to_jsonb(${alias})${ctx.labelsJson("items", alias)} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115449
+ const row = (alias) => `${ctx.rowJson("items", alias, { as: { number: (v) => `${v}::text` } })} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115341
115450
  const record = (type, alias, extra = "") => ctx.record({
115342
115451
  type,
115343
115452
  payload: `jsonb_build_object('organizationId', ${alias}.${w("tenant")}, 'workItemId', ${alias}.${w("id")}, 'subjectType', ${item}, 'subjectId', ${alias}.${w("id")}::text, 'title', ${alias}.${w("title")}${extra})`,
@@ -115433,7 +115542,7 @@ ${["startOn", "targetOn"].flatMap((key) => ctx.has("projects", key) ? [`
115433
115542
  when check_violation or not_null_violation then
115434
115543
  ${fail$1("WORK_ITEM_PROJECT_INVALID", "a project needs a key of capitals and a name, and ends after it starts", "22023")}
115435
115544
  end;
115436
- return (select to_jsonb(x) || jsonb_build_object('progress', ${has("project") ? `(
115545
+ return (select ${ctx.rowJson("projects", "x")} || jsonb_build_object('progress', ${has("project") ? `(
115437
115546
  select case when count(*) = 0 then null else round(100.0 * count(*) filter (where ${state(`y.${w("state")}`, ["completed"])}) / count(*) filter (where ${state(`y.${w("state")}`, ["canceled"], true)})) end
115438
115547
  from ${t("items")} y where y.${w("project")} = x.${p("id")} and y.${w("archivedAt")} is null
115439
115548
  )` : "null"}) from ${t("projects")} x where x.${p("id")} = v_id);
@@ -115473,7 +115582,7 @@ begin
115473
115582
  exception when check_violation or not_null_violation then
115474
115583
  ${fail$1("WORK_ITEM_ITERATION_INVALID", "an iteration needs a name and ends on or after it starts", "22023")}
115475
115584
  end;
115476
- return (select to_jsonb(x) from ${t("iterations")} x where x.${i("id")} = v_id);
115585
+ return (select ${ctx.rowJson("iterations", "x")} from ${t("iterations")} x where x.${i("id")} = v_id);
115477
115586
  end;
115478
115587
  $$;
115479
115588
  ${userGrant(`${fn("save_iteration")}(${ctx.idType}, uuid, jsonb)`)}
@@ -115541,7 +115650,7 @@ begin
115541
115650
  w("pipeline"),
115542
115651
  w("stage"),
115543
115652
  column("createdBy")
115544
- ])})
115653
+ ])}${extrasInsert.columns})
115545
115654
  values (${lines(" ", [
115546
115655
  "create_work_item.tenant",
115547
115656
  "v_seq",
@@ -115560,7 +115669,7 @@ begin
115560
115669
  "(create_work_item.attrs ->> 'pipelineId')::uuid",
115561
115670
  "(create_work_item.attrs ->> 'stageId')::uuid",
115562
115671
  present("items", "createdBy", "auth.uid()")
115563
- ])})
115672
+ ])}${extrasInsert.values})
115564
115673
  returning ${w("id")} into v_id;
115565
115674
  exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range or foreign_key_violation then
115566
115675
  ${fail$1("WORK_ITEM_ATTRS_INVALID", "a work item field has an invalid value", "22023")}
@@ -116535,7 +116644,7 @@ function bindings(ctx) {
116535
116644
  return Object.entries(onSettings(ctx)).map(([type, entry]) => {
116536
116645
  const where = `blocks.${ctx.instance}.on.${type}`;
116537
116646
  const subject = registry.find((item) => item.type === type);
116538
- if (subject?.tenant === void 0) throw new TypeError(`${where}: register "${type}" with a tenant column in config.records first`);
116647
+ if (subject?.tenant === void 0) throw new TypeError(`${where}: register "${type}" with a tenant column in config.subjects first`);
116539
116648
  if (!isRecord$1(entry)) throw new TypeError(`${where} must be an object`);
116540
116649
  const status = entry["status"];
116541
116650
  const priority = entry["priority"];
@@ -118643,7 +118752,7 @@ function machine(name, entry, registry, naming) {
118643
118752
  const order = statusList(record["order"], `${where}.order`);
118644
118753
  for (const status of order) if (!statuses.has(status)) throw new TypeError(`${where}.order: ${status} is not a status`);
118645
118754
  const tenantColumn = typeof record["tenant"] === "string" ? record["tenant"] : tenantColumnOf(table, registry, naming);
118646
- if (tenantColumn === void 0) throw new TypeError(`${where}: ${table} has no tenant column in config.records, which a machine needs`);
118755
+ if (tenantColumn === void 0) throw new TypeError(`${where}: ${table} has no tenant column in config.subjects, which a machine needs`);
118647
118756
  const history = historyOf(record["history"], where, tenantColumn);
118648
118757
  return {
118649
118758
  name,
@@ -119397,7 +119506,7 @@ const STATE_MACHINE = {
119397
119506
  name: "state-machine",
119398
119507
  scopes: ["tenant"],
119399
119508
  title: "State machine",
119400
- description: "Allowed status transitions as the caller, a history row and a status.changed event. A machine can also write a stages timeline and keep a lifecycle row (pause, flags, pinned version). Each machine is a subject table named in options.machines, or a config.records type.",
119509
+ description: "Allowed status transitions as the caller, a history row and a status.changed event. A machine can also write a stages timeline and keep a lifecycle row (pause, flags, pinned version). Each machine is a subject table named in options.machines, or a config.subjects type.",
119401
119510
  requires: ["memberships", "permissions"],
119402
119511
  integrates: [
119403
119512
  "outbox",
@@ -134929,7 +135038,7 @@ function columnAccessRefusals(table) {
134929
135038
  */
134930
135039
  function constraintChecks(column, ident) {
134931
135040
  const conditions = [];
134932
- const format = column.format === void 0 ? void 0 : FIELD_FORMATS[column.format];
135041
+ const format = column.format === void 0 || column.domain !== void 0 ? void 0 : FIELD_FORMATS[column.format];
134933
135042
  if (format?.pattern !== void 0) conditions.push(`${ident} ~* ${sqlString(format.pattern)}`);
134934
135043
  if (column.options !== void 0) {
134935
135044
  const list = column.options.map((option) => sqlString(option)).join(", ");
@@ -135521,7 +135630,7 @@ function referenceSql(where, reference, ctx) {
135521
135630
  function columnSql(table, name, column) {
135522
135631
  const notNull = column.nullable === false && (table.enrich === void 0 || column.default !== void 0 || column.identity === true);
135523
135632
  return [
135524
- `${sqlIdent(name)} ${column.encrypted === true ? "text" : column.type}`,
135633
+ `${sqlIdent(name)} ${column.encrypted === true ? "text" : column.domain ?? column.type}`,
135525
135634
  column.identity === true ? " generated by default as identity" : "",
135526
135635
  notNull ? " not null" : "",
135527
135636
  column.default === void 0 ? "" : ` default ${column.default}`,