@pilotiq/pilotiq 0.7.1 → 0.8.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 (367) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/CHANGELOG.md +154 -0
  3. package/CLAUDE.md +59 -3
  4. package/dist/Pilotiq.d.ts +83 -0
  5. package/dist/Pilotiq.d.ts.map +1 -1
  6. package/dist/Pilotiq.js +39 -0
  7. package/dist/Pilotiq.js.map +1 -1
  8. package/dist/actions/Action.d.ts +27 -99
  9. package/dist/actions/Action.d.ts.map +1 -1
  10. package/dist/actions/Action.js +52 -754
  11. package/dist/actions/Action.js.map +1 -1
  12. package/dist/actions/bulkFactories.d.ts +46 -0
  13. package/dist/actions/bulkFactories.d.ts.map +1 -0
  14. package/dist/actions/bulkFactories.js +144 -0
  15. package/dist/actions/bulkFactories.js.map +1 -0
  16. package/dist/actions/crudFactories.d.ts +94 -0
  17. package/dist/actions/crudFactories.d.ts.map +1 -0
  18. package/dist/actions/crudFactories.js +209 -0
  19. package/dist/actions/crudFactories.js.map +1 -0
  20. package/dist/actions/factoryHelpers.d.ts +108 -0
  21. package/dist/actions/factoryHelpers.d.ts.map +1 -0
  22. package/dist/actions/factoryHelpers.js +138 -0
  23. package/dist/actions/factoryHelpers.js.map +1 -0
  24. package/dist/actions/m2mFactories.d.ts +47 -0
  25. package/dist/actions/m2mFactories.d.ts.map +1 -0
  26. package/dist/actions/m2mFactories.js +173 -0
  27. package/dist/actions/m2mFactories.js.map +1 -0
  28. package/dist/actions/relationFactories.d.ts +93 -0
  29. package/dist/actions/relationFactories.d.ts.map +1 -0
  30. package/dist/actions/relationFactories.js +321 -0
  31. package/dist/actions/relationFactories.js.map +1 -0
  32. package/dist/elements/dispatchForm.js +1 -1
  33. package/dist/elements/dispatchForm.js.map +1 -1
  34. package/dist/elements/dispatchTable.js +1 -1
  35. package/dist/elements/dispatchTable.js.map +1 -1
  36. package/dist/fields/Field.d.ts +31 -0
  37. package/dist/fields/Field.d.ts.map +1 -1
  38. package/dist/fields/Field.js +25 -0
  39. package/dist/fields/Field.js.map +1 -1
  40. package/dist/pageData/breadcrumbs.d.ts +42 -0
  41. package/dist/pageData/breadcrumbs.d.ts.map +1 -0
  42. package/dist/pageData/breadcrumbs.js +172 -0
  43. package/dist/pageData/breadcrumbs.js.map +1 -0
  44. package/dist/pageData/forms.d.ts +137 -0
  45. package/dist/pageData/forms.d.ts.map +1 -0
  46. package/dist/pageData/forms.js +427 -0
  47. package/dist/pageData/forms.js.map +1 -0
  48. package/dist/pageData/helpers.d.ts +239 -0
  49. package/dist/pageData/helpers.d.ts.map +1 -0
  50. package/dist/pageData/helpers.js +703 -0
  51. package/dist/pageData/helpers.js.map +1 -0
  52. package/dist/pageData/misc.d.ts +76 -0
  53. package/dist/pageData/misc.d.ts.map +1 -0
  54. package/dist/pageData/misc.js +263 -0
  55. package/dist/pageData/misc.js.map +1 -0
  56. package/dist/pageData/navigation.d.ts +292 -0
  57. package/dist/pageData/navigation.d.ts.map +1 -0
  58. package/dist/pageData/navigation.js +591 -0
  59. package/dist/pageData/navigation.js.map +1 -0
  60. package/dist/pageData/relationPages.d.ts +172 -0
  61. package/dist/pageData/relationPages.d.ts.map +1 -0
  62. package/dist/pageData/relationPages.js +867 -0
  63. package/dist/pageData/relationPages.js.map +1 -0
  64. package/dist/pageData/relationTabs.d.ts +65 -0
  65. package/dist/pageData/relationTabs.d.ts.map +1 -0
  66. package/dist/pageData/relationTabs.js +258 -0
  67. package/dist/pageData/relationTabs.js.map +1 -0
  68. package/dist/pageData/resourcePages.d.ts +48 -0
  69. package/dist/pageData/resourcePages.d.ts.map +1 -0
  70. package/dist/pageData/resourcePages.js +504 -0
  71. package/dist/pageData/resourcePages.js.map +1 -0
  72. package/dist/pageData.d.ts +12 -792
  73. package/dist/pageData.d.ts.map +1 -1
  74. package/dist/pageData.js +24 -3797
  75. package/dist/pageData.js.map +1 -1
  76. package/dist/react/AppShell.d.ts +8 -0
  77. package/dist/react/AppShell.d.ts.map +1 -1
  78. package/dist/react/AppShell.js +11 -1
  79. package/dist/react/AppShell.js.map +1 -1
  80. package/dist/react/CollabExtensionFactoryRegistry.d.ts +47 -0
  81. package/dist/react/CollabExtensionFactoryRegistry.d.ts.map +1 -0
  82. package/dist/react/CollabExtensionFactoryRegistry.js +14 -0
  83. package/dist/react/CollabExtensionFactoryRegistry.js.map +1 -0
  84. package/dist/react/CollabRoomContext.d.ts +37 -0
  85. package/dist/react/CollabRoomContext.d.ts.map +1 -0
  86. package/dist/react/CollabRoomContext.js +12 -0
  87. package/dist/react/CollabRoomContext.js.map +1 -0
  88. package/dist/react/FormCollabBindingRegistry.d.ts +62 -0
  89. package/dist/react/FormCollabBindingRegistry.d.ts.map +1 -0
  90. package/dist/react/FormCollabBindingRegistry.js +14 -0
  91. package/dist/react/FormCollabBindingRegistry.js.map +1 -0
  92. package/dist/react/RecordWrapperGate.d.ts +25 -0
  93. package/dist/react/RecordWrapperGate.d.ts.map +1 -0
  94. package/dist/react/RecordWrapperGate.js +30 -0
  95. package/dist/react/RecordWrapperGate.js.map +1 -0
  96. package/dist/react/RecordWrapperRegistry.d.ts +31 -0
  97. package/dist/react/RecordWrapperRegistry.d.ts.map +1 -0
  98. package/dist/react/RecordWrapperRegistry.js +15 -0
  99. package/dist/react/RecordWrapperRegistry.js.map +1 -0
  100. package/dist/react/SchemaRenderer.d.ts +17 -23
  101. package/dist/react/SchemaRenderer.d.ts.map +1 -1
  102. package/dist/react/SchemaRenderer.js +71 -3647
  103. package/dist/react/SchemaRenderer.js.map +1 -1
  104. package/dist/react/component-slots.d.ts +103 -0
  105. package/dist/react/component-slots.d.ts.map +1 -0
  106. package/dist/react/component-slots.js +18 -0
  107. package/dist/react/component-slots.js.map +1 -0
  108. package/dist/react/fields/BuilderInput.d.ts.map +1 -1
  109. package/dist/react/fields/BuilderInput.js +21 -117
  110. package/dist/react/fields/BuilderInput.js.map +1 -1
  111. package/dist/react/fields/MarkdownInput.d.ts.map +1 -1
  112. package/dist/react/fields/MarkdownInput.js +1 -3
  113. package/dist/react/fields/MarkdownInput.js.map +1 -1
  114. package/dist/react/fields/RepeaterInput.d.ts.map +1 -1
  115. package/dist/react/fields/RepeaterInput.js +22 -127
  116. package/dist/react/fields/RepeaterInput.js.map +1 -1
  117. package/dist/react/fields/rowState.d.ts +40 -0
  118. package/dist/react/fields/rowState.d.ts.map +1 -0
  119. package/dist/react/fields/rowState.js +60 -0
  120. package/dist/react/fields/rowState.js.map +1 -0
  121. package/dist/react/fields/useRowReorderDnd.d.ts +28 -0
  122. package/dist/react/fields/useRowReorderDnd.d.ts.map +1 -0
  123. package/dist/react/fields/useRowReorderDnd.js +51 -0
  124. package/dist/react/fields/useRowReorderDnd.js.map +1 -0
  125. package/dist/react/index.d.ts +9 -0
  126. package/dist/react/index.d.ts.map +1 -1
  127. package/dist/react/index.js +8 -0
  128. package/dist/react/index.js.map +1 -1
  129. package/dist/react/layouts/SidebarLayout.d.ts +1 -1
  130. package/dist/react/layouts/SidebarLayout.d.ts.map +1 -1
  131. package/dist/react/layouts/SidebarLayout.js +10 -2
  132. package/dist/react/layouts/SidebarLayout.js.map +1 -1
  133. package/dist/react/layouts/TopbarLayout.d.ts +1 -1
  134. package/dist/react/layouts/TopbarLayout.d.ts.map +1 -1
  135. package/dist/react/layouts/TopbarLayout.js +19 -11
  136. package/dist/react/layouts/TopbarLayout.js.map +1 -1
  137. package/dist/react/parseRecordEditUrl.d.ts +29 -0
  138. package/dist/react/parseRecordEditUrl.d.ts.map +1 -0
  139. package/dist/react/parseRecordEditUrl.js +25 -0
  140. package/dist/react/parseRecordEditUrl.js.map +1 -0
  141. package/dist/react/persistedState.d.ts +19 -0
  142. package/dist/react/persistedState.d.ts.map +1 -0
  143. package/dist/react/persistedState.js +51 -0
  144. package/dist/react/persistedState.js.map +1 -0
  145. package/dist/react/schemaRenderer/AlertRenderer.d.ts +12 -0
  146. package/dist/react/schemaRenderer/AlertRenderer.d.ts.map +1 -0
  147. package/dist/react/schemaRenderer/AlertRenderer.js +61 -0
  148. package/dist/react/schemaRenderer/AlertRenderer.js.map +1 -0
  149. package/dist/react/schemaRenderer/EntryRenderer.d.ts +13 -0
  150. package/dist/react/schemaRenderer/EntryRenderer.d.ts.map +1 -0
  151. package/dist/react/schemaRenderer/EntryRenderer.js +277 -0
  152. package/dist/react/schemaRenderer/EntryRenderer.js.map +1 -0
  153. package/dist/react/schemaRenderer/SectionRenderer.d.ts +16 -0
  154. package/dist/react/schemaRenderer/SectionRenderer.d.ts.map +1 -0
  155. package/dist/react/schemaRenderer/SectionRenderer.js +62 -0
  156. package/dist/react/schemaRenderer/SectionRenderer.js.map +1 -0
  157. package/dist/react/schemaRenderer/SimpleElements.d.ts +25 -0
  158. package/dist/react/schemaRenderer/SimpleElements.d.ts.map +1 -0
  159. package/dist/react/schemaRenderer/SimpleElements.js +147 -0
  160. package/dist/react/schemaRenderer/SimpleElements.js.map +1 -0
  161. package/dist/react/schemaRenderer/TabsRenderer.d.ts +17 -0
  162. package/dist/react/schemaRenderer/TabsRenderer.d.ts.map +1 -0
  163. package/dist/react/schemaRenderer/TabsRenderer.js +31 -0
  164. package/dist/react/schemaRenderer/TabsRenderer.js.map +1 -0
  165. package/dist/react/schemaRenderer/WizardRenderer.d.ts +34 -0
  166. package/dist/react/schemaRenderer/WizardRenderer.d.ts.map +1 -0
  167. package/dist/react/schemaRenderer/WizardRenderer.js +208 -0
  168. package/dist/react/schemaRenderer/WizardRenderer.js.map +1 -0
  169. package/dist/react/schemaRenderer/action/ActionGroupTrigger.d.ts +21 -0
  170. package/dist/react/schemaRenderer/action/ActionGroupTrigger.d.ts.map +1 -0
  171. package/dist/react/schemaRenderer/action/ActionGroupTrigger.js +82 -0
  172. package/dist/react/schemaRenderer/action/ActionGroupTrigger.js.map +1 -0
  173. package/dist/react/schemaRenderer/action/ActionModalDialog.d.ts +30 -0
  174. package/dist/react/schemaRenderer/action/ActionModalDialog.d.ts.map +1 -0
  175. package/dist/react/schemaRenderer/action/ActionModalDialog.js +182 -0
  176. package/dist/react/schemaRenderer/action/ActionModalDialog.js.map +1 -0
  177. package/dist/react/schemaRenderer/action/ConfirmActionDialog.d.ts +17 -0
  178. package/dist/react/schemaRenderer/action/ConfirmActionDialog.d.ts.map +1 -0
  179. package/dist/react/schemaRenderer/action/ConfirmActionDialog.js +19 -0
  180. package/dist/react/schemaRenderer/action/ConfirmActionDialog.js.map +1 -0
  181. package/dist/react/schemaRenderer/action/HandlerActionButton.d.ts +16 -0
  182. package/dist/react/schemaRenderer/action/HandlerActionButton.d.ts.map +1 -0
  183. package/dist/react/schemaRenderer/action/HandlerActionButton.js +16 -0
  184. package/dist/react/schemaRenderer/action/HandlerActionButton.js.map +1 -0
  185. package/dist/react/schemaRenderer/action/MethodActionButton.d.ts +22 -0
  186. package/dist/react/schemaRenderer/action/MethodActionButton.d.ts.map +1 -0
  187. package/dist/react/schemaRenderer/action/MethodActionButton.js +26 -0
  188. package/dist/react/schemaRenderer/action/MethodActionButton.js.map +1 -0
  189. package/dist/react/schemaRenderer/action/buttons.d.ts +18 -0
  190. package/dist/react/schemaRenderer/action/buttons.d.ts.map +1 -0
  191. package/dist/react/schemaRenderer/action/buttons.js +74 -0
  192. package/dist/react/schemaRenderer/action/buttons.js.map +1 -0
  193. package/dist/react/schemaRenderer/action/helpers.d.ts +26 -0
  194. package/dist/react/schemaRenderer/action/helpers.d.ts.map +1 -0
  195. package/dist/react/schemaRenderer/action/helpers.js +126 -0
  196. package/dist/react/schemaRenderer/action/helpers.js.map +1 -0
  197. package/dist/react/schemaRenderer/action/renderAction.d.ts +21 -0
  198. package/dist/react/schemaRenderer/action/renderAction.d.ts.map +1 -0
  199. package/dist/react/schemaRenderer/action/renderAction.js +102 -0
  200. package/dist/react/schemaRenderer/action/renderAction.js.map +1 -0
  201. package/dist/react/schemaRenderer/columnFormat.d.ts +10 -0
  202. package/dist/react/schemaRenderer/columnFormat.d.ts.map +1 -0
  203. package/dist/react/schemaRenderer/columnFormat.js +76 -0
  204. package/dist/react/schemaRenderer/columnFormat.js.map +1 -0
  205. package/dist/react/schemaRenderer/constants.d.ts +8 -0
  206. package/dist/react/schemaRenderer/constants.d.ts.map +1 -0
  207. package/dist/react/schemaRenderer/constants.js +45 -0
  208. package/dist/react/schemaRenderer/constants.js.map +1 -0
  209. package/dist/react/schemaRenderer/form/FormRenderer.d.ts +29 -0
  210. package/dist/react/schemaRenderer/form/FormRenderer.d.ts.map +1 -0
  211. package/dist/react/schemaRenderer/form/FormRenderer.js +152 -0
  212. package/dist/react/schemaRenderer/form/FormRenderer.js.map +1 -0
  213. package/dist/react/schemaRenderer/form/renderField.d.ts +6 -0
  214. package/dist/react/schemaRenderer/form/renderField.d.ts.map +1 -0
  215. package/dist/react/schemaRenderer/form/renderField.js +239 -0
  216. package/dist/react/schemaRenderer/form/renderField.js.map +1 -0
  217. package/dist/react/schemaRenderer/helpers.d.ts +32 -0
  218. package/dist/react/schemaRenderer/helpers.d.ts.map +1 -0
  219. package/dist/react/schemaRenderer/helpers.js +52 -0
  220. package/dist/react/schemaRenderer/helpers.js.map +1 -0
  221. package/dist/react/schemaRenderer/table/CardsLayoutBody.d.ts +60 -0
  222. package/dist/react/schemaRenderer/table/CardsLayoutBody.d.ts.map +1 -0
  223. package/dist/react/schemaRenderer/table/CardsLayoutBody.js +189 -0
  224. package/dist/react/schemaRenderer/table/CardsLayoutBody.js.map +1 -0
  225. package/dist/react/schemaRenderer/table/TableRenderer.d.ts +29 -0
  226. package/dist/react/schemaRenderer/table/TableRenderer.d.ts.map +1 -0
  227. package/dist/react/schemaRenderer/table/TableRenderer.js +85 -0
  228. package/dist/react/schemaRenderer/table/TableRenderer.js.map +1 -0
  229. package/dist/react/schemaRenderer/table/TableRendererBody.d.ts +18 -0
  230. package/dist/react/schemaRenderer/table/TableRendererBody.d.ts.map +1 -0
  231. package/dist/react/schemaRenderer/table/TableRendererBody.js +555 -0
  232. package/dist/react/schemaRenderer/table/TableRendererBody.js.map +1 -0
  233. package/dist/react/schemaRenderer/table/filters.d.ts +263 -0
  234. package/dist/react/schemaRenderer/table/filters.d.ts.map +1 -0
  235. package/dist/react/schemaRenderer/table/filters.js +497 -0
  236. package/dist/react/schemaRenderer/table/filters.js.map +1 -0
  237. package/dist/react/schemaRenderer/table/formatCell.d.ts +11 -0
  238. package/dist/react/schemaRenderer/table/formatCell.d.ts.map +1 -0
  239. package/dist/react/schemaRenderer/table/formatCell.js +172 -0
  240. package/dist/react/schemaRenderer/table/formatCell.js.map +1 -0
  241. package/dist/react/schemaRenderer/table/links.d.ts +42 -0
  242. package/dist/react/schemaRenderer/table/links.d.ts.map +1 -0
  243. package/dist/react/schemaRenderer/table/links.js +55 -0
  244. package/dist/react/schemaRenderer/table/links.js.map +1 -0
  245. package/dist/react/schemaRenderer/table/renderRowActions.d.ts +13 -0
  246. package/dist/react/schemaRenderer/table/renderRowActions.d.ts.map +1 -0
  247. package/dist/react/schemaRenderer/table/renderRowActions.js +25 -0
  248. package/dist/react/schemaRenderer/table/renderRowActions.js.map +1 -0
  249. package/dist/react/schemaRenderer/table/url.d.ts +41 -0
  250. package/dist/react/schemaRenderer/table/url.d.ts.map +1 -0
  251. package/dist/react/schemaRenderer/table/url.js +114 -0
  252. package/dist/react/schemaRenderer/table/url.js.map +1 -0
  253. package/dist/routes/globals.d.ts +13 -0
  254. package/dist/routes/globals.d.ts.map +1 -0
  255. package/dist/routes/globals.js +131 -0
  256. package/dist/routes/globals.js.map +1 -0
  257. package/dist/routes/helpers.d.ts +217 -0
  258. package/dist/routes/helpers.d.ts.map +1 -0
  259. package/dist/routes/helpers.js +498 -0
  260. package/dist/routes/helpers.js.map +1 -0
  261. package/dist/routes/pages.d.ts +15 -0
  262. package/dist/routes/pages.d.ts.map +1 -0
  263. package/dist/routes/pages.js +145 -0
  264. package/dist/routes/pages.js.map +1 -0
  265. package/dist/routes/panel.d.ts +19 -0
  266. package/dist/routes/panel.d.ts.map +1 -0
  267. package/dist/routes/panel.js +191 -0
  268. package/dist/routes/panel.js.map +1 -0
  269. package/dist/routes/relations.d.ts +21 -0
  270. package/dist/routes/relations.d.ts.map +1 -0
  271. package/dist/routes/relations.js +1239 -0
  272. package/dist/routes/relations.js.map +1 -0
  273. package/dist/routes/resources.d.ts +28 -0
  274. package/dist/routes/resources.d.ts.map +1 -0
  275. package/dist/routes/resources.js +741 -0
  276. package/dist/routes/resources.js.map +1 -0
  277. package/dist/routes/theme.d.ts +12 -0
  278. package/dist/routes/theme.d.ts.map +1 -0
  279. package/dist/routes/theme.js +82 -0
  280. package/dist/routes/theme.js.map +1 -0
  281. package/dist/routes.d.ts.map +1 -1
  282. package/dist/routes.js +64 -3078
  283. package/dist/routes.js.map +1 -1
  284. package/dist/vite.d.ts +1 -0
  285. package/dist/vite.d.ts.map +1 -1
  286. package/dist/vite.js +31 -10
  287. package/dist/vite.js.map +1 -1
  288. package/package.json +2 -1
  289. package/src/Pilotiq.ts +95 -0
  290. package/src/actions/Action.ts +79 -723
  291. package/src/actions/bulkFactories.ts +168 -0
  292. package/src/actions/crudFactories.ts +220 -0
  293. package/src/actions/factoryHelpers.ts +177 -0
  294. package/src/actions/m2mFactories.ts +193 -0
  295. package/src/actions/relationFactories.ts +372 -0
  296. package/src/elements/dispatchForm.ts +1 -1
  297. package/src/elements/dispatchTable.ts +1 -1
  298. package/src/fields/Field.ts +39 -0
  299. package/src/pageData/breadcrumbs.ts +288 -0
  300. package/src/pageData/forms.ts +578 -0
  301. package/src/pageData/helpers.ts +764 -0
  302. package/src/pageData/misc.ts +347 -0
  303. package/src/pageData/navigation.ts +779 -0
  304. package/src/pageData/relationPages.ts +1246 -0
  305. package/src/pageData/relationTabs.ts +286 -0
  306. package/src/pageData/resourcePages.ts +593 -0
  307. package/src/pageData.ts +122 -4731
  308. package/src/react/AppShell.tsx +27 -1
  309. package/src/react/CollabExtensionFactoryRegistry.ts +55 -0
  310. package/src/react/CollabRoomContext.ts +42 -0
  311. package/src/react/FormCollabBindingRegistry.ts +72 -0
  312. package/src/react/RecordWrapperGate.tsx +40 -0
  313. package/src/react/RecordWrapperRegistry.ts +39 -0
  314. package/src/react/SchemaRenderer.tsx +230 -6479
  315. package/src/react/component-slots.test.ts +103 -0
  316. package/src/react/component-slots.ts +116 -0
  317. package/src/react/fields/BuilderInput.tsx +29 -117
  318. package/src/react/fields/MarkdownInput.tsx +0 -1
  319. package/src/react/fields/RepeaterInput.tsx +29 -130
  320. package/src/react/fields/rowState.ts +106 -0
  321. package/src/react/fields/useRowReorderDnd.ts +78 -0
  322. package/src/react/index.ts +38 -0
  323. package/src/react/layouts/SidebarLayout.tsx +39 -28
  324. package/src/react/layouts/TopbarLayout.tsx +70 -57
  325. package/src/react/parseRecordEditUrl.test.ts +75 -0
  326. package/src/react/parseRecordEditUrl.ts +55 -0
  327. package/src/react/persistedState.ts +40 -0
  328. package/src/react/schemaRenderer/AlertRenderer.tsx +112 -0
  329. package/src/react/schemaRenderer/EntryRenderer.tsx +501 -0
  330. package/src/react/schemaRenderer/SectionRenderer.tsx +120 -0
  331. package/src/react/schemaRenderer/SimpleElements.tsx +306 -0
  332. package/src/react/schemaRenderer/TabsRenderer.tsx +62 -0
  333. package/src/react/schemaRenderer/WizardRenderer.tsx +338 -0
  334. package/src/react/schemaRenderer/action/ActionGroupTrigger.tsx +177 -0
  335. package/src/react/schemaRenderer/action/ActionModalDialog.tsx +273 -0
  336. package/src/react/schemaRenderer/action/ConfirmActionDialog.tsx +61 -0
  337. package/src/react/schemaRenderer/action/HandlerActionButton.tsx +43 -0
  338. package/src/react/schemaRenderer/action/MethodActionButton.tsx +64 -0
  339. package/src/react/schemaRenderer/action/buttons.tsx +99 -0
  340. package/src/react/schemaRenderer/action/helpers.ts +140 -0
  341. package/src/react/schemaRenderer/action/renderAction.tsx +245 -0
  342. package/src/react/schemaRenderer/columnFormat.ts +65 -0
  343. package/src/react/schemaRenderer/constants.ts +50 -0
  344. package/src/react/schemaRenderer/form/FormRenderer.tsx +233 -0
  345. package/src/react/schemaRenderer/form/renderField.tsx +511 -0
  346. package/src/react/schemaRenderer/helpers.tsx +81 -0
  347. package/src/react/schemaRenderer/table/CardsLayoutBody.tsx +308 -0
  348. package/src/react/schemaRenderer/table/TableRenderer.tsx +123 -0
  349. package/src/react/schemaRenderer/table/TableRendererBody.tsx +974 -0
  350. package/src/react/schemaRenderer/table/filters.tsx +1233 -0
  351. package/src/react/schemaRenderer/table/formatCell.tsx +264 -0
  352. package/src/react/schemaRenderer/table/links.tsx +112 -0
  353. package/src/react/schemaRenderer/table/renderRowActions.tsx +52 -0
  354. package/src/react/schemaRenderer/table/url.tsx +143 -0
  355. package/src/routes/globals.ts +154 -0
  356. package/src/routes/helpers.ts +668 -0
  357. package/src/routes/pages.ts +173 -0
  358. package/src/routes/panel.ts +204 -0
  359. package/src/routes/relations.ts +1219 -0
  360. package/src/routes/resources.ts +786 -0
  361. package/src/routes/theme.ts +109 -0
  362. package/src/routes.test.ts +1 -1
  363. package/src/routes.ts +64 -3176
  364. package/src/schema/TableWidget.test.ts +2 -2
  365. package/src/theme/migrate.test.ts +178 -0
  366. package/src/vite.test.ts +184 -0
  367. package/src/vite.ts +31 -9
@@ -0,0 +1,1246 @@
1
+ import type { Pilotiq, PilotiqConfig } from '../Pilotiq.js'
2
+ import type { ResourceClass } from '../Resource.js'
3
+ import { resourceBasePath } from '../clusterPaths.js'
4
+ import { Element } from '../schema/Element.js'
5
+ import { resolveSchema, type SchemaContext } from '../schema/resolveSchema.js'
6
+ import { Form } from '../elements/Form.js'
7
+ import { Table } from '../elements/Table.js'
8
+ import { Column } from '../Column.js'
9
+ import { findForms } from '../elements/dispatchForm.js'
10
+ import { Filter } from '../filters/Filter.js'
11
+ import { TrashedFilter } from '../filters/TrashedFilter.js'
12
+ import { loadTableRecords } from '../elements/dispatchTable.js'
13
+ import { consumeFlashedNotifications } from '../notifications/flash.js'
14
+ import { serializeIcon, type SerializedIcon } from '../icons/types.js'
15
+ import {
16
+ RelationManager,
17
+ safeManagerPolicy as safeManagerPolicyImpl,
18
+ type ManagerCanMethod as ManagerCanMethodType,
19
+ type RelationManagerContext,
20
+ } from '../RelationManager.js'
21
+ import { RelationTabs } from '../schema/RelationTabs.js'
22
+ import {
23
+ findRecord,
24
+ getMorphRelationDescriptor,
25
+ getPrimaryKey,
26
+ getRelationType,
27
+ modelLoadRecord,
28
+ modelRelationTableRecords,
29
+ modelSave,
30
+ type ModelLike,
31
+ type ModelQuery,
32
+ } from '../orm/modelDefaults.js'
33
+ import { normalizeRelationMode, type RelationMode } from '../RelationManager.js'
34
+ import {
35
+ nestedRelationCreateBreadcrumbs,
36
+ nestedRelationEditBreadcrumbs,
37
+ nestedRelationListBreadcrumbs,
38
+ nestedRelationViewBreadcrumbs,
39
+ relationCreateBreadcrumbs,
40
+ relationEditBreadcrumbs,
41
+ relationListBreadcrumbs,
42
+ relationViewBreadcrumbs,
43
+ type RelationChainStep,
44
+ } from './breadcrumbs.js'
45
+ import {
46
+ applyFillPipeline,
47
+ applyRelationshipBuilderFill,
48
+ applyRelationshipRepeaterFill,
49
+ callPageSchema,
50
+ resolveServerDataElements,
51
+ tagActionDispatch,
52
+ tagCellEditUrls,
53
+ tagFormActions,
54
+ tagTableDeferred,
55
+ tagTableReorderUrls,
56
+ tagWidgetUrls,
57
+ uploadCtx,
58
+ userCtx,
59
+ } from './helpers.js'
60
+ import {
61
+ applyRoleHooks,
62
+ panelInfo,
63
+ type PanelInfoRoute,
64
+ } from './navigation.js'
65
+ import {
66
+ buildNestedRelationTabs,
67
+ buildRelationTabs,
68
+ deriveParentTitle,
69
+ safeBool,
70
+ } from './relationTabs.js'
71
+
72
+ // ─── Plan #11 relation-manager data builders ────────────────
73
+ //
74
+ // Depth-1 + depth-2 relation manager URL roles (list / create / view /
75
+ // edit) for a parent record's manager-scoped projection. Each builder
76
+ // loads the parent + manager + (optionally) child, runs the two-layer
77
+ // policy gate (parent canAccess+canEdit, then manager-scope canX), and
78
+ // resolves a tab strip + form/table from the manager's configurators.
79
+ // Submit-side handlers live in `routes.ts`.
80
+
81
+
82
+
83
+
84
+ // ─── Plan #11 relation-manager data builder ─────────────────
85
+
86
+ /**
87
+ * Plan #11 — three scopes a single relation-manager URL space resolves to:
88
+ *
89
+ * list: GET {base}/{slug}/:id/{rel}
90
+ * create: GET {base}/{slug}/:id/{rel}/create
91
+ * edit: GET {base}/{slug}/:id/{rel}/{childId}/edit
92
+ *
93
+ * Each carries enough state for `relationManagerData` to load the right
94
+ * parent + (for edit) child + form/table context. Submit-side handlers
95
+ * live in `routes.ts` and reuse `dispatchFormSubmit`.
96
+ */
97
+ export type RelationManagerScope =
98
+ | { kind: 'relation-list'; slug: string; recordId: string; relationship: string; query?: Record<string, string> }
99
+ | { kind: 'relation-create'; slug: string; recordId: string; relationship: string; prefill?: { values?: Record<string, unknown>; errors?: Record<string, string[]> } }
100
+ | { kind: 'relation-view'; slug: string; recordId: string; relationship: string; childId: string }
101
+ | { kind: 'relation-edit'; slug: string; recordId: string; relationship: string; childId: string; prefill?: { values?: Record<string, unknown>; errors?: Record<string, string[]> } }
102
+ // Phase B nested resources — the leaf is one manager deeper than the
103
+ // depth-1 variants. The two-step `chain` carries the (recordId,
104
+ // relationship) for each layer; the trailing `childId` (when present)
105
+ // is the leaf record's id under chain[1].
106
+ | { kind: 'nested-relation-list'; slug: string; chain: [RelationChainStep, RelationChainStep]; query?: Record<string, string> }
107
+ | { kind: 'nested-relation-create'; slug: string; chain: [RelationChainStep, RelationChainStep]; prefill?: { values?: Record<string, unknown>; errors?: Record<string, string[]> } }
108
+ | { kind: 'nested-relation-view'; slug: string; chain: [RelationChainStep, RelationChainStep]; childId: string }
109
+ | { kind: 'nested-relation-edit'; slug: string; chain: [RelationChainStep, RelationChainStep]; childId: string; prefill?: { values?: Record<string, unknown>; errors?: Record<string, string[]> } }
110
+
111
+ /** Phase B — one parent layer in a nested-resources URL chain. The list
112
+ * of these identifies a path through the manager tree:
113
+ * `[ { recordId: '123', relationship: 'comments' } ]` picks comment
114
+ * "456 under post 123" when paired with `childId: '456'`. */
115
+ // `RelationChainStep` now lives in `./pageData/breadcrumbs.ts` since
116
+ // both the breadcrumb builders and the depth-2 relation manager
117
+ // builders consume it. Re-exported below for back-compat with any
118
+ // external callsite that imports through `pageData.js`.
119
+
120
+ /**
121
+ * Failure outcomes the data builder discriminates back to the route
122
+ * handler, which decides between 403 / 404 / HTML / JSON shapes.
123
+ *
124
+ * `null` — unknown panel / parent / manager / child;
125
+ * route returns 404
126
+ * `{ ok: false, status: 403 }` — policy denied; route returns 403
127
+ *
128
+ * Success returns the schemaData payload directly (a record, not
129
+ * tagged) for parity with `resourceIndexData / resourceCreateData`.
130
+ */
131
+ export type RelationManagerResult =
132
+ | Record<string, unknown>
133
+ | { ok: false; status: 403 }
134
+ | null
135
+
136
+ /**
137
+ * Discover the related Resource for a manager. Order:
138
+ * 1. `M.relatedResource` explicit override (skip discovery).
139
+ * 2. Rudder ORM convention: walk
140
+ * `R.model.relations[manager.relationship].model()` and find
141
+ * `cfg.resources[i].model === relatedModel`.
142
+ * 3. Otherwise undefined — caller must error or fall back.
143
+ *
144
+ * A returned Resource is the one whose `model` backs the related
145
+ * table. Callers use it for `Related.model.find(childId)`,
146
+ * `Related.canEdit(user, child)`, and the auto-wired form save handler.
147
+ */
148
+ export function findRelatedResource(
149
+ M: typeof RelationManager,
150
+ R: ResourceClass,
151
+ cfg: ReturnType<Pilotiq['getConfig']>,
152
+ ): ResourceClass | undefined {
153
+ if (M.relatedResource) return M.relatedResource
154
+ const ParentModel = R.model as unknown as { relations?: Record<string, { model?: () => unknown }> } | undefined
155
+ if (!ParentModel) return undefined
156
+ const def = ParentModel.relations?.[M.getRelationship()]
157
+ const RelatedModel = typeof def?.model === 'function' ? def.model() : undefined
158
+ if (!RelatedModel) return undefined
159
+ return cfg.resources.find(r => (r.model as unknown) === RelatedModel)
160
+ }
161
+
162
+ /** Find a registered manager on a Resource by its relationship key.
163
+ * Throws on unknown manager — so the route can 404 cleanly. */
164
+ function findManager(
165
+ R: ResourceClass,
166
+ relationship: string,
167
+ ): typeof RelationManager | undefined {
168
+ return R.relations().find(M => {
169
+ try { return M.getRelationship() === relationship } catch { return false }
170
+ })
171
+ }
172
+
173
+ /**
174
+ * Verify a child record actually belongs to the given parent under the
175
+ * declared relationship. Anti-IDOR — without this an attacker can swap
176
+ * the `:childId` segment to load any related-model row regardless of
177
+ * whether it's actually owned by the parent.
178
+ *
179
+ * Strategy: re-resolve the parent's relation query and check whether
180
+ * the child's primary key shows up in `where(pk, '=', childId).paginate(1, 1)`.
181
+ * Yes, it's a second round-trip — but it's the single point of trust
182
+ * for IDOR safety, and it fits naturally into the same query path
183
+ * `modelRelationTableRecords` uses.
184
+ */
185
+ async function childBelongsToParent(
186
+ parentModel: ModelLike,
187
+ parent: unknown,
188
+ relationship: string,
189
+ childPk: string,
190
+ childId: string,
191
+ ): Promise<boolean> {
192
+ try {
193
+ const q: ModelQuery = (parentModel.relatedQuery
194
+ ? parentModel.relatedQuery(parent, relationship)
195
+ : (parent as { related: (n: string) => ModelQuery }).related(relationship))
196
+ const result = await q.where(childPk, '=', childId).paginate(1, 1)
197
+ return result.total > 0
198
+ } catch {
199
+ return false
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Auto-wire the manager's table records loader against the parent's
205
+ * relation query when the user didn't set `Table.records()` themselves.
206
+ * Mirrors `defaultPages`'s wiring of `Table.records()` from `R.model`
207
+ * for the resource list page.
208
+ */
209
+ function autoWireManagerTable(
210
+ table: Table,
211
+ parentModel: ModelLike,
212
+ parent: unknown,
213
+ relationship: string,
214
+ ): void {
215
+ if (table.getRecords()) return // user wired it explicitly
216
+ table.records(modelRelationTableRecords(parentModel, parent, relationship, table))
217
+ }
218
+
219
+ /**
220
+ * Plan #13 polish — auto-inject `TrashedFilter` on a relation manager's
221
+ * table when the **related** Resource opts into soft deletes. Mirrors the
222
+ * resource-list pattern in `defaultPages.applyTableDefaults`. The check
223
+ * is on the related Resource (not the manager), because soft-delete is a
224
+ * model-level capability — if the child model supports trashing, the
225
+ * manager's table should expose the toggle.
226
+ *
227
+ * No-op when:
228
+ * - the related Resource hasn't set `softDeletes = true`
229
+ * - the user already attached a `TrashedFilter` in `M.table()`
230
+ */
231
+ function injectManagerTrashedFilter(
232
+ table: Table,
233
+ Related: ResourceClass | undefined,
234
+ ): void {
235
+ if (!Related?.softDeletes) return
236
+ const children = table.getChildren() ?? []
237
+ const hasTrashed = children.some(c => c instanceof TrashedFilter)
238
+ if (hasTrashed) return
239
+ const existing = children.filter(c => c instanceof Filter) as Filter[]
240
+ table.filters([...existing, TrashedFilter.make()])
241
+ }
242
+
243
+ /**
244
+ * Auto-wire the manager's form save + loadRecord handlers against the
245
+ * **related** Resource's `model` when the user didn't set them. The
246
+ * route handler is responsible for stamping the parent context
247
+ * (parent, parentRecord, parentId, relationship) onto the
248
+ * `FormContext` so user-supplied `mutateDataBeforeCreate` etc. can
249
+ * read them.
250
+ */
251
+ function autoWireManagerForm(form: Form, Related: ResourceClass): void {
252
+ const RelatedModel = Related.model
253
+ if (!RelatedModel) return
254
+ if (!form.getSave()) form.save(modelSave(RelatedModel))
255
+ if (!form.getLoadRecord()) form.loadRecord(modelLoadRecord(Related))
256
+ }
257
+
258
+ /** Plan #11 — authorization predicate names a `RelationManager` carries.
259
+ * Re-exported from `RelationManager.ts`. */
260
+ export type ManagerCanMethod = ManagerCanMethodType
261
+
262
+ /** Plan #11 — authorize a relation-manager action with sensible defaults.
263
+ * Re-exported from `RelationManager.ts` so external callers (route
264
+ * handlers, third-party plugins) keep their existing import path. */
265
+ export const safeManagerPolicy = safeManagerPolicyImpl
266
+
267
+ /**
268
+ * Plan #11 — render data for the three relation-manager URL scopes.
269
+ * Mirrors the resource* builders' shape so routes and Vike +data hooks
270
+ * consume identical props. Authorization runs inline (parent
271
+ * `canAccess + canEdit(parent)` then manager-scoped predicate); IDOR
272
+ * check on `relation-edit` runs against the parent's relation query.
273
+ *
274
+ * Returns:
275
+ * - `null` when panel / parent / manager / child don't exist.
276
+ * - `{ ok: false, status: 403 }` when authorization denies.
277
+ * - the props record on success (route picks SSR view / SPA prop
278
+ * downstream).
279
+ */
280
+ export async function relationManagerData(
281
+ pilotiq: Pilotiq,
282
+ scope: RelationManagerScope,
283
+ req?: unknown,
284
+ ): Promise<RelationManagerResult> {
285
+ // Phase B nested-relation-* scopes split out into their own pipeline
286
+ // — the chain walking + per-layer auth differs enough from the
287
+ // depth-1 path that interleaving them would mostly hurt readability.
288
+ if (scope.kind === 'nested-relation-list'
289
+ || scope.kind === 'nested-relation-create'
290
+ || scope.kind === 'nested-relation-view'
291
+ || scope.kind === 'nested-relation-edit') {
292
+ return nestedRelationManagerData(pilotiq, scope, req)
293
+ }
294
+
295
+ const cfg = pilotiq.getConfig()
296
+
297
+ const R = cfg.resources.find(r => r.getSlug() === scope.slug)
298
+ if (!R) return null
299
+
300
+ const M = findManager(R, scope.relationship)
301
+ if (!M) return null
302
+
303
+ const user = await pilotiq.resolveUser(req)
304
+
305
+ // Layer 1: parent access. canAccess gates the resource entirely;
306
+ // canEdit gates managing its relations (managers are read-write
307
+ // surfaces — read-only inline views opt in by overriding the
308
+ // manager's can*). Cluster gate composes with R.canAccess — both
309
+ // must pass when the parent resource is inside a cluster.
310
+ const [clusterOk, accessOk] = await Promise.all([
311
+ R.cluster ? safeBool(() => R.cluster!.canAccess(user)) : Promise.resolve(true),
312
+ safeBool(() => R.canAccess(user)),
313
+ ])
314
+ if (!clusterOk || !accessOk) return { ok: false, status: 403 }
315
+
316
+ if (!R.model) {
317
+ // Without a model on the parent we can't load the parent record,
318
+ // and without that we can't IDOR-check children. Point users at
319
+ // the missing wiring rather than silent 500s.
320
+ throw new Error(
321
+ `[Pilotiq] Resource "${R.name}" has relations(${M.name}) but no static model. ` +
322
+ `Set Resource.model = … to enable relation managers, or remove the manager.`,
323
+ )
324
+ }
325
+
326
+ const parentRecord = await findRecord(R, scope.recordId, { user }).catch(() => undefined)
327
+ if (!parentRecord) return null
328
+
329
+ if (!await safeBool(() => R.canEdit(user, parentRecord))) return { ok: false, status: 403 }
330
+
331
+ // Read the relation type off the parent's relations map once,
332
+ // normalize to the six-way `RelationMode` the manager-side logic
333
+ // uses. `belongsToMany` / `morphToMany` (owning polymorphic) /
334
+ // `morphedByMany` (inverse polymorphic) all flip into pivot-mutation
335
+ // mode (attach / detach / sync — same accessor surface), `morphMany|
336
+ // morphOne` collapses to `'morphMany'` (parent-side polymorphic —
337
+ // auto-fills morph columns on create), `morphTo` is the child-side
338
+ // polymorphic (no auto-actions; requires explicit `M.relatedResource`).
339
+ // Everything else collapses to `'hasMany'`.
340
+ const relationType = getRelationType(R.model, scope.relationship)
341
+ const mode: RelationMode = normalizeRelationMode(relationType)
342
+
343
+ const Related = findRelatedResource(M, R, cfg)
344
+ // Related Resource is required for: edit/create form auto-wire,
345
+ // child loading on edit, related URL generation. Throw when missing
346
+ // *only* if we'd otherwise need it — for `relation-list` it's
347
+ // optional (the table can be hand-wired by the user).
348
+ const needRelated = scope.kind !== 'relation-list'
349
+ if (needRelated && !Related) {
350
+ throw new Error(
351
+ `[Pilotiq] RelationManager ${M.name} on ${R.name} could not resolve its related Resource. ` +
352
+ `Set static relatedResource on the manager, or ensure the parent's model declares relations[${JSON.stringify(M.getRelationship())}].`,
353
+ )
354
+ }
355
+
356
+ switch (scope.kind) {
357
+ case 'relation-list':
358
+ return buildRelationListData(pilotiq, R, M, Related, parentRecord, scope, req, user, mode)
359
+ case 'relation-create':
360
+ return buildRelationCreateData(pilotiq, R, M, Related!, parentRecord, scope, req, user, mode)
361
+ case 'relation-view':
362
+ return buildRelationViewData(pilotiq, R, M, Related!, parentRecord, scope, req, user, mode)
363
+ case 'relation-edit':
364
+ return buildRelationEditData(pilotiq, R, M, Related!, parentRecord, scope, req, user, mode)
365
+ }
366
+ }
367
+
368
+ async function buildRelationListData(
369
+ pilotiq: Pilotiq,
370
+ R: ResourceClass,
371
+ M: typeof RelationManager,
372
+ Related: ResourceClass | undefined,
373
+ parentRecord: unknown,
374
+ scope: Extract<RelationManagerScope, { kind: 'relation-list' }>,
375
+ req: unknown,
376
+ user: unknown,
377
+ mode: RelationMode,
378
+ ): Promise<RelationManagerResult> {
379
+ if (!await safeManagerPolicy(M, 'canViewAny', Related, user, parentRecord)) return { ok: false, status: 403 }
380
+
381
+ const cfg = pilotiq.getConfig()
382
+ const base = cfg.path
383
+ const resourceBase = resourceBasePath(base, R)
384
+ const listUrl = `${resourceBase}/${scope.recordId}/${scope.relationship}`
385
+
386
+ // Build a single Table by piping a fresh Table through M.table(table, ctx).
387
+ // Context lets the user wire `Action.relationCreate / relationEdit /
388
+ // relationDelete(M, ctx)` factories inside `static table()` to template
389
+ // URLs without threading basePath / parentId by hand.
390
+ const managerCtx = buildRelationManagerCtx(base, scope, parentRecord, Related, mode)
391
+ const table = M.table(Table.make(), managerCtx)
392
+ autoWireManagerTable(table, R.model as ModelLike, parentRecord, scope.relationship)
393
+ injectManagerTrashedFilter(table, Related)
394
+
395
+ const ctx: SchemaContext = uploadCtx(userCtx({
396
+ mode: 'table',
397
+ basePath: base,
398
+ record: parentRecord,
399
+ }, user), cfg)
400
+
401
+ const elements: Element[] = [table]
402
+ tagActionDispatch(elements, listUrl)
403
+ // Independent work — records load against the parent's relation
404
+ // accessor; tabs probe per-tab `safeManagerPolicy` predicates that
405
+ // don't touch the records pipeline.
406
+ const [, tabs] = await Promise.all([
407
+ loadTableRecords(elements, scope.query ?? {}, listUrl, user),
408
+ buildRelationTabs(R, scope.recordId, base, scope.relationship, user, parentRecord),
409
+ ])
410
+ if (tabs) elements.unshift(tabs)
411
+
412
+ const breadcrumbs = relationListBreadcrumbs(
413
+ cfg, R, M, scope.recordId, deriveParentTitle(R, parentRecord),
414
+ )
415
+ if (breadcrumbs) elements.unshift(breadcrumbs)
416
+
417
+ const relationListRoute: PanelInfoRoute = { resource: R, recordId: scope.recordId }
418
+ const [panel, schemaData] = await Promise.all([
419
+ panelInfo(pilotiq, req, relationListRoute),
420
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-list', metas, relationListRoute)),
421
+ ])
422
+
423
+ return {
424
+ pageType: 'relation-list',
425
+ panel,
426
+ resource: { name: R.name, label: R.label, labelSingular: R.labelSingular, slug: scope.slug, icon: serializeIcon(R.icon, R.name) },
427
+ relation: {
428
+ name: M.name,
429
+ label: M.getLabel(),
430
+ labelSingular: M.getLabelSingular(),
431
+ relationship: scope.relationship,
432
+ icon: M.getIcon() ? serializeIcon(M.getIcon()!, M.name) : undefined,
433
+ relatedSlug: Related?.getSlug(),
434
+ },
435
+ parent: {
436
+ id: scope.recordId,
437
+ title: deriveParentTitle(R, parentRecord),
438
+ },
439
+ basePath: base,
440
+ layout: cfg.layout,
441
+ schemaData,
442
+ notifications: consumeFlashedNotifications(req),
443
+ }
444
+ }
445
+
446
+ async function buildRelationCreateData(
447
+ pilotiq: Pilotiq,
448
+ R: ResourceClass,
449
+ M: typeof RelationManager,
450
+ Related: ResourceClass,
451
+ parentRecord: unknown,
452
+ scope: Extract<RelationManagerScope, { kind: 'relation-create' }>,
453
+ req: unknown,
454
+ user: unknown,
455
+ mode: RelationMode,
456
+ ): Promise<RelationManagerResult> {
457
+ if (!await safeManagerPolicy(M, 'canCreate', Related, user, parentRecord)) return { ok: false, status: 403 }
458
+
459
+ const cfg = pilotiq.getConfig()
460
+ const base = cfg.path
461
+ const resourceBase = resourceBasePath(base, R)
462
+ const createUrl = `${resourceBase}/${scope.recordId}/${scope.relationship}/create`
463
+
464
+ const managerCtx = buildRelationManagerCtx(base, scope, parentRecord, Related, mode)
465
+ const form = M.form(Form.make(), managerCtx)
466
+ if (Related.model) autoWireManagerForm(form, Related)
467
+
468
+ const elements: Element[] = [form]
469
+ tagFormActions(elements, createUrl)
470
+
471
+ if (scope.prefill) {
472
+ if (scope.prefill.values) form.withValues(scope.prefill.values)
473
+ if (scope.prefill.errors) form.withErrors(scope.prefill.errors)
474
+ }
475
+
476
+ const tabs = await buildRelationTabs(R, scope.recordId, base, scope.relationship, user, parentRecord)
477
+ if (tabs) elements.unshift(tabs)
478
+
479
+ const breadcrumbs = relationCreateBreadcrumbs(
480
+ cfg, R, M, scope.recordId, deriveParentTitle(R, parentRecord),
481
+ )
482
+ if (breadcrumbs) elements.unshift(breadcrumbs)
483
+
484
+ const ctx: SchemaContext = uploadCtx(userCtx({
485
+ mode: 'create',
486
+ basePath: base,
487
+ record: parentRecord,
488
+ }, user), cfg)
489
+
490
+ const relationCreateRoute: PanelInfoRoute = { resource: R, recordId: scope.recordId }
491
+ const [panel, schemaData] = await Promise.all([
492
+ panelInfo(pilotiq, req, relationCreateRoute),
493
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-create', metas, relationCreateRoute)),
494
+ ])
495
+
496
+ return {
497
+ pageType: 'relation-create',
498
+ panel,
499
+ resource: { name: R.name, label: R.labelSingular, slug: scope.slug, icon: serializeIcon(R.icon, R.name) },
500
+ relation: {
501
+ name: M.name,
502
+ label: M.getLabel(),
503
+ labelSingular: M.getLabelSingular(),
504
+ relationship: scope.relationship,
505
+ icon: M.getIcon() ? serializeIcon(M.getIcon()!, M.name) : undefined,
506
+ relatedSlug: Related.getSlug(),
507
+ },
508
+ parent: {
509
+ id: scope.recordId,
510
+ title: deriveParentTitle(R, parentRecord),
511
+ },
512
+ mode: 'create' as const,
513
+ basePath: base,
514
+ layout: cfg.layout,
515
+ schemaData,
516
+ notifications: consumeFlashedNotifications(req),
517
+ ...(scope.prefill?.errors ? { hasErrors: true } : {}),
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Phase A — read-only view page for a related record at depth-2:
523
+ * `${base}/${slug}/:id/${rel}/:childId`. Mirrors `buildRelationEditData`'s
524
+ * IDOR + auth posture but resolves the manager's `static detail(child,
525
+ * parent)` instead of its form. The default `detail()` returns `[]` —
526
+ * managers opt in by overriding it; the chrome (RelationTabs strip)
527
+ * still renders so users can sideways-nav between sibling managers.
528
+ */
529
+ async function buildRelationViewData(
530
+ pilotiq: Pilotiq,
531
+ R: ResourceClass,
532
+ M: typeof RelationManager,
533
+ Related: ResourceClass,
534
+ parentRecord: unknown,
535
+ scope: Extract<RelationManagerScope, { kind: 'relation-view' }>,
536
+ req: unknown,
537
+ user: unknown,
538
+ _mode: RelationMode,
539
+ ): Promise<RelationManagerResult> {
540
+ if (!Related.model) {
541
+ throw new Error(
542
+ `[Pilotiq] Cannot load child record for ${M.name}: Related Resource ${Related.name} has no static model.`,
543
+ )
544
+ }
545
+ const childPk = getPrimaryKey(Related.model)
546
+
547
+ const [belongs, child] = await Promise.all([
548
+ childBelongsToParent(R.model as ModelLike, parentRecord, scope.relationship, childPk, scope.childId),
549
+ findRecord(Related, scope.childId, { user }).catch(() => undefined),
550
+ ])
551
+ if (!belongs || !child) return null
552
+
553
+ if (!await safeManagerPolicy(M, 'canView', Related, user, parentRecord, child)) return { ok: false, status: 403 }
554
+
555
+ const cfg = pilotiq.getConfig()
556
+ const base = cfg.path
557
+
558
+ const elements: Element[] = M.detail(child, parentRecord)
559
+
560
+ // Phase B polish — when M declares nested managers, surface them on
561
+ // this page too. The strip lists the leaf parent's view tab plus one
562
+ // tab per sibling nested manager so users can jump from the Phase A
563
+ // view straight into a grandchild list / create / view / edit page.
564
+ // Active key `'__view'` because the user is currently viewing the
565
+ // leaf parent record itself, not any nested manager.
566
+ const nestedTabs = await buildNestedRelationTabs(
567
+ R, M, base,
568
+ { recordId: scope.recordId, relationship: scope.relationship },
569
+ scope.childId,
570
+ '__view',
571
+ user, child,
572
+ )
573
+ if (nestedTabs) elements.unshift(nestedTabs)
574
+
575
+ const tabs = await buildRelationTabs(R, scope.recordId, base, scope.relationship, user, parentRecord)
576
+ if (tabs) elements.unshift(tabs)
577
+
578
+ const breadcrumbs = relationViewBreadcrumbs(
579
+ cfg, R, M, scope.recordId,
580
+ deriveParentTitle(R, parentRecord),
581
+ deriveParentTitle(Related, child, M),
582
+ )
583
+ if (breadcrumbs) elements.unshift(breadcrumbs)
584
+
585
+ const ctx: SchemaContext = uploadCtx(userCtx({
586
+ mode: 'view',
587
+ basePath: base,
588
+ record: child,
589
+ recordId: scope.childId,
590
+ }, user), cfg)
591
+
592
+ const relationViewRoute: PanelInfoRoute = { resource: R, recordId: scope.childId }
593
+ const [panel, schemaData] = await Promise.all([
594
+ panelInfo(pilotiq, req, relationViewRoute),
595
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-view', metas, relationViewRoute)),
596
+ ])
597
+
598
+ return {
599
+ pageType: 'relation-view',
600
+ panel,
601
+ resource: { name: R.name, label: R.labelSingular, slug: scope.slug, icon: serializeIcon(R.icon, R.name) },
602
+ relation: {
603
+ name: M.name,
604
+ label: M.getLabel(),
605
+ labelSingular: M.getLabelSingular(),
606
+ relationship: scope.relationship,
607
+ icon: M.getIcon() ? serializeIcon(M.getIcon()!, M.name) : undefined,
608
+ relatedSlug: Related.getSlug(),
609
+ },
610
+ parent: {
611
+ id: scope.recordId,
612
+ title: deriveParentTitle(R, parentRecord),
613
+ },
614
+ mode: 'view' as const,
615
+ childId: scope.childId,
616
+ basePath: base,
617
+ layout: cfg.layout,
618
+ schemaData,
619
+ notifications: consumeFlashedNotifications(req),
620
+ }
621
+ }
622
+
623
+ async function buildRelationEditData(
624
+ pilotiq: Pilotiq,
625
+ R: ResourceClass,
626
+ M: typeof RelationManager,
627
+ Related: ResourceClass,
628
+ parentRecord: unknown,
629
+ scope: Extract<RelationManagerScope, { kind: 'relation-edit' }>,
630
+ req: unknown,
631
+ user: unknown,
632
+ mode: RelationMode,
633
+ ): Promise<RelationManagerResult> {
634
+ if (!Related.model) {
635
+ throw new Error(
636
+ `[Pilotiq] Cannot load child record for ${M.name}: Related Resource ${Related.name} has no static model.`,
637
+ )
638
+ }
639
+ const childPk = getPrimaryKey(Related.model)
640
+
641
+ // IDOR check + child load in parallel. Both fail-paths collapse to
642
+ // the same `return null` so behavior matches the serial version; the
643
+ // independent queries (parent's relation accessor vs related model's
644
+ // find) save one RTT on every relation-edit request.
645
+ const [belongs, child] = await Promise.all([
646
+ childBelongsToParent(R.model as ModelLike, parentRecord, scope.relationship, childPk, scope.childId),
647
+ findRecord(Related, scope.childId, { user }).catch(() => undefined),
648
+ ])
649
+ if (!belongs || !child) return null
650
+
651
+ if (!await safeManagerPolicy(M, 'canEdit', Related, user, parentRecord, child)) return { ok: false, status: 403 }
652
+
653
+ const cfg = pilotiq.getConfig()
654
+ const base = cfg.path
655
+ const resourceBase = resourceBasePath(base, R)
656
+ const editUrl = `${resourceBase}/${scope.recordId}/${scope.relationship}/${scope.childId}/edit`
657
+
658
+ const managerCtx = buildRelationManagerCtx(base, scope, parentRecord, Related, mode)
659
+ const form = M.form(Form.make(), managerCtx)
660
+ autoWireManagerForm(form, Related)
661
+
662
+ const elements: Element[] = [form]
663
+ tagFormActions(elements, editUrl)
664
+
665
+ // Prefill values: explicit prefill (re-render after 422) wins,
666
+ // otherwise pipe the loaded child through Form's fill pipeline.
667
+ if (scope.prefill?.values) {
668
+ form.withValues(scope.prefill.values)
669
+ if (scope.prefill.errors) form.withErrors(scope.prefill.errors)
670
+ } else if (child != null) {
671
+ const values = await applyFillPipeline(form, child)
672
+ form.withValues(values)
673
+ }
674
+
675
+ const tabs = await buildRelationTabs(R, scope.recordId, base, scope.relationship, user, parentRecord)
676
+ if (tabs) elements.unshift(tabs)
677
+
678
+ const breadcrumbs = relationEditBreadcrumbs(
679
+ cfg, R, M, scope.recordId,
680
+ deriveParentTitle(R, parentRecord),
681
+ scope.childId,
682
+ deriveParentTitle(Related, child, M),
683
+ )
684
+ if (breadcrumbs) elements.unshift(breadcrumbs)
685
+
686
+ const ctx: SchemaContext = uploadCtx(userCtx({
687
+ mode: 'edit',
688
+ basePath: base,
689
+ record: child,
690
+ recordId: scope.childId,
691
+ }, user), cfg)
692
+
693
+ const relationEditRoute: PanelInfoRoute = { resource: R, recordId: scope.childId }
694
+ const [panel, schemaData] = await Promise.all([
695
+ panelInfo(pilotiq, req, relationEditRoute),
696
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-edit', metas, relationEditRoute)),
697
+ ])
698
+
699
+ return {
700
+ pageType: 'relation-edit',
701
+ panel,
702
+ resource: { name: R.name, label: R.labelSingular, slug: scope.slug, icon: serializeIcon(R.icon, R.name) },
703
+ relation: {
704
+ name: M.name,
705
+ label: M.getLabel(),
706
+ labelSingular: M.getLabelSingular(),
707
+ relationship: scope.relationship,
708
+ icon: M.getIcon() ? serializeIcon(M.getIcon()!, M.name) : undefined,
709
+ relatedSlug: Related.getSlug(),
710
+ },
711
+ parent: {
712
+ id: scope.recordId,
713
+ title: deriveParentTitle(R, parentRecord),
714
+ },
715
+ mode: 'edit' as const,
716
+ childId: scope.childId,
717
+ basePath: base,
718
+ layout: cfg.layout,
719
+ schemaData,
720
+ notifications: consumeFlashedNotifications(req),
721
+ ...(scope.prefill?.errors ? { hasErrors: true } : {}),
722
+ }
723
+ }
724
+
725
+ // ─── Phase B nested-relation pipeline ────────────────────────
726
+
727
+ /**
728
+ * Phase B — narrow `scope` discriminator for nested-relation-*. Lets
729
+ * the helpers below avoid restating the union for every parameter.
730
+ */
731
+ type NestedRelationScope = Extract<RelationManagerScope, { kind: `nested-relation-${string}` }>
732
+
733
+ /**
734
+ * Phase B — chain walk result. Resolved layer-by-layer in
735
+ * `resolveRelationChain`; nested builders consume it. Failures bubble
736
+ * up as the same `{ ok: false, status: 403 }` / `null` shape the
737
+ * depth-1 path uses.
738
+ */
739
+ export interface ResolvedChain {
740
+ R: ResourceClass
741
+ parentRecord: unknown
742
+ M1: typeof RelationManager
743
+ Related1: ResourceClass
744
+ child1: unknown
745
+ child1Mode: RelationMode
746
+ M2: typeof RelationManager
747
+ Related2: ResourceClass | undefined
748
+ child2Mode: RelationMode
749
+ }
750
+
751
+ /**
752
+ * Phase B — resolve a depth-2 chain, running every auth + IDOR layer:
753
+ * Layer 0 — top-level Resource: cluster gate, R.canAccess.
754
+ * Layer 1 — parent record: R.canEdit(parent) (Phase A gate to manage relations).
755
+ * Layer 2 — first manager M1: relationship discovered, related resource discovered.
756
+ * IDOR #1 — child1 (the leaf parent) must belong to parentRecord under chain[0].relationship.
757
+ * Layer 3 — M1.canView(child1, parent) (Filament-style: must be allowed
758
+ * to view the child to drill into its sub-relations).
759
+ * Layer 4 — second manager M2 lookup; relation type read off Related1.model.
760
+ *
761
+ * The leaf manager's per-scope predicate (canViewAny / canCreate /
762
+ * canView / canEdit) runs inside the per-scope builders below, since
763
+ * each predicate has different arguments.
764
+ */
765
+ export async function resolveRelationChain(
766
+ pilotiq: Pilotiq,
767
+ scope: NestedRelationScope,
768
+ user: unknown,
769
+ ): Promise<ResolvedChain | { ok: false; status: 403 } | null> {
770
+ const cfg = pilotiq.getConfig()
771
+
772
+ const R = cfg.resources.find(r => r.getSlug() === scope.slug)
773
+ if (!R) return null
774
+
775
+ // Layer 0 — same gates as the depth-1 pipeline.
776
+ const [clusterOk, accessOk] = await Promise.all([
777
+ R.cluster ? safeBool(() => R.cluster!.canAccess(user)) : Promise.resolve(true),
778
+ safeBool(() => R.canAccess(user)),
779
+ ])
780
+ if (!clusterOk || !accessOk) return { ok: false, status: 403 }
781
+
782
+ if (!R.model) {
783
+ throw new Error(
784
+ `[Pilotiq] Resource "${R.name}" has nested relations but no static model. ` +
785
+ `Set Resource.model = … or remove the manager.`,
786
+ )
787
+ }
788
+
789
+ const [step0, step1] = scope.chain
790
+ const parentRecord = await findRecord(R, step0.recordId, { user }).catch(() => undefined)
791
+ if (!parentRecord) return null
792
+
793
+ // Layer 1 — parent record gate.
794
+ if (!await safeBool(() => R.canEdit(user, parentRecord))) return { ok: false, status: 403 }
795
+
796
+ // Layer 2 — first manager M1.
797
+ const M1 = findManager(R, step0.relationship)
798
+ if (!M1) return null
799
+ const Related1 = findRelatedResource(M1, R, cfg)
800
+ if (!Related1) {
801
+ throw new Error(
802
+ `[Pilotiq] RelationManager ${M1.name} on ${R.name} could not resolve its related Resource. ` +
803
+ `Set static relatedResource on the manager, or ensure the parent's model declares relations[${JSON.stringify(M1.getRelationship())}].`,
804
+ )
805
+ }
806
+ if (!Related1.model) {
807
+ throw new Error(
808
+ `[Pilotiq] Related Resource ${Related1.name} has no static model — ` +
809
+ `cannot resolve nested manager chain through it.`,
810
+ )
811
+ }
812
+ const child1Mode: RelationMode = normalizeRelationMode(getRelationType(R.model, step0.relationship))
813
+
814
+ // IDOR #1 + child1 load in parallel — confirm the leaf parent
815
+ // (`step1.recordId`) actually belongs to the top parent under the
816
+ // first relationship key. Independent queries.
817
+ const child1Pk = getPrimaryKey(Related1.model)
818
+ const [belongs1, child1] = await Promise.all([
819
+ childBelongsToParent(R.model as ModelLike, parentRecord, step0.relationship, child1Pk, step1.recordId),
820
+ findRecord(Related1, step1.recordId, { user }).catch(() => undefined),
821
+ ])
822
+ if (!belongs1 || !child1) return null
823
+
824
+ // Layer 3 — M1.canView(child1, parent) gate. Filament-style: viewing
825
+ // the child is the prerequisite for entering its nested manager strip.
826
+ if (!await safeManagerPolicy(M1, 'canView', Related1, user, parentRecord, child1)) return { ok: false, status: 403 }
827
+
828
+ // Layer 4 — second manager M2 declared under M1.relations().
829
+ const M2 = M1.relations().find(N => {
830
+ try { return N.getRelationship() === step1.relationship } catch { return false }
831
+ })
832
+ if (!M2) return null
833
+ const Related2 = findRelatedResource(M2, Related1, cfg)
834
+ const child2Mode: RelationMode = normalizeRelationMode(getRelationType(Related1.model, step1.relationship))
835
+
836
+ return { R, parentRecord, M1, Related1, child1, child1Mode, M2, Related2, child2Mode }
837
+ }
838
+
839
+ /**
840
+ * Phase B dispatcher — splits the four nested scopes onto their builders
841
+ * after the shared chain walk. Mirrors the depth-1 `relationManagerData`
842
+ * function shape.
843
+ */
844
+ async function nestedRelationManagerData(
845
+ pilotiq: Pilotiq,
846
+ scope: NestedRelationScope,
847
+ req?: unknown,
848
+ ): Promise<RelationManagerResult> {
849
+ const user = await pilotiq.resolveUser(req)
850
+ const resolved = await resolveRelationChain(pilotiq, scope, user)
851
+ if (resolved === null) return null
852
+ if ('ok' in resolved) return resolved
853
+
854
+ // For create / view / edit we strictly need a registered Related2 so
855
+ // we can load the leaf record + auto-wire the form save.
856
+ const needRelated2 = scope.kind !== 'nested-relation-list'
857
+ if (needRelated2 && !resolved.Related2) {
858
+ throw new Error(
859
+ `[Pilotiq] Nested RelationManager ${resolved.M2.name} under ${resolved.M1.name} ` +
860
+ `on ${resolved.R.name} could not resolve its related Resource. ` +
861
+ `Set static relatedResource on the manager, or ensure the parent's model declares ` +
862
+ `relations[${JSON.stringify(resolved.M2.getRelationship())}].`,
863
+ )
864
+ }
865
+
866
+ switch (scope.kind) {
867
+ case 'nested-relation-list':
868
+ return buildNestedRelationListData(pilotiq, scope, resolved, req, user)
869
+ case 'nested-relation-create':
870
+ return buildNestedRelationCreateData(pilotiq, scope, resolved, req, user)
871
+ case 'nested-relation-view':
872
+ return buildNestedRelationViewData(pilotiq, scope, resolved, req, user)
873
+ case 'nested-relation-edit':
874
+ return buildNestedRelationEditData(pilotiq, scope, resolved, req, user)
875
+ }
876
+ }
877
+
878
+ /** Phase B — build the manager context for a nested leaf manager. The
879
+ * parent here is `child1` (the chain's leaf parent record); the URL
880
+ * prefix comes from `scope.chain[0]` via `Action.relation*` factories
881
+ * reading `ctx.chain`. */
882
+ /** Depth-1 manager context constructor — mirror of `nestedManagerCtx` for
883
+ * the four `relation-*` page roles. Three call sites (list / create / edit)
884
+ * build identical shapes; the helper keeps them in lock-step. */
885
+ function buildRelationManagerCtx(
886
+ base: string,
887
+ scope: { slug: string; recordId: string; relationship: string },
888
+ parentRecord: unknown,
889
+ Related: ResourceClass | undefined,
890
+ mode: RelationMode,
891
+ ): RelationManagerContext {
892
+ return {
893
+ basePath: base,
894
+ parentSlug: scope.slug,
895
+ parentId: scope.recordId,
896
+ relationship: scope.relationship,
897
+ parentRecord,
898
+ related: Related,
899
+ mode,
900
+ }
901
+ }
902
+
903
+ function nestedManagerCtx(
904
+ base: string,
905
+ scope: NestedRelationScope,
906
+ resolved: ResolvedChain,
907
+ ): RelationManagerContext {
908
+ const [step0, step1] = scope.chain
909
+ return {
910
+ basePath: base,
911
+ parentSlug: resolved.R.getSlug(),
912
+ parentId: step1.recordId, // immediate parent = child1's id
913
+ relationship: step1.relationship, // leaf manager's relationship
914
+ parentRecord: resolved.child1, // immediate parent record = child1
915
+ related: resolved.Related2,
916
+ mode: resolved.child2Mode,
917
+ chain: [{
918
+ slug: resolved.R.getSlug(),
919
+ recordId: step0.recordId,
920
+ relationship: step0.relationship,
921
+ }],
922
+ }
923
+ }
924
+
925
+ /** Phase B — assemble the response shape that mirrors the depth-1
926
+ * builders but adds a `chain` array so renderers can build breadcrumbs
927
+ * and back-links without re-deriving them. */
928
+ function nestedResponseEnvelope(
929
+ pageType: 'nested-relation-list' | 'nested-relation-create' | 'nested-relation-view' | 'nested-relation-edit',
930
+ pilotiq: Pilotiq,
931
+ base: string,
932
+ scope: NestedRelationScope,
933
+ resolved: ResolvedChain,
934
+ req: unknown,
935
+ ): {
936
+ pageType: typeof pageType
937
+ resource: { name: string; label?: string | undefined; slug: string; icon?: SerializedIcon | undefined }
938
+ parentRelation: { name: string; relationship: string; label: string; relatedSlug?: string | undefined }
939
+ parentChild: { id: string; title: string }
940
+ relation: { name: string; relationship: string; label: string; labelSingular: string; icon?: SerializedIcon | undefined; relatedSlug?: string | undefined }
941
+ parent: { id: string; title: string }
942
+ basePath: string
943
+ layout: PilotiqConfig['layout']
944
+ notifications: ReturnType<typeof consumeFlashedNotifications>
945
+ } {
946
+ const { R, M1, Related1, child1, M2, Related2 } = resolved
947
+ const [step0, step1] = scope.chain
948
+ const parentChildTitle = deriveParentTitle(Related1, child1, M1)
949
+
950
+ return {
951
+ pageType,
952
+ resource: { name: R.name, label: R.labelSingular, slug: R.getSlug(), icon: serializeIcon(R.icon, R.name) },
953
+ parentRelation: {
954
+ name: M1.name,
955
+ relationship: step0.relationship,
956
+ label: M1.getLabel(),
957
+ relatedSlug: Related1.getSlug(),
958
+ },
959
+ parentChild: {
960
+ id: step1.recordId,
961
+ title: parentChildTitle,
962
+ },
963
+ relation: {
964
+ name: M2.name,
965
+ relationship: step1.relationship,
966
+ label: M2.getLabel(),
967
+ labelSingular: M2.getLabelSingular(),
968
+ icon: M2.getIcon() ? serializeIcon(M2.getIcon()!, M2.name) : undefined,
969
+ relatedSlug: Related2?.getSlug(),
970
+ },
971
+ parent: {
972
+ // Top-of-chain record — same shape the depth-1 builders ship as
973
+ // `parent` so renderers can reuse the back-to-resource link.
974
+ id: step0.recordId,
975
+ title: deriveParentTitle(R, resolved.parentRecord),
976
+ },
977
+ basePath: base,
978
+ layout: pilotiq.getConfig().layout,
979
+ notifications: consumeFlashedNotifications(req),
980
+ }
981
+ }
982
+
983
+ async function buildNestedRelationListData(
984
+ pilotiq: Pilotiq,
985
+ scope: Extract<NestedRelationScope, { kind: 'nested-relation-list' }>,
986
+ resolved: ResolvedChain,
987
+ req: unknown,
988
+ user: unknown,
989
+ ): Promise<RelationManagerResult> {
990
+ const { Related1, child1, M2, Related2 } = resolved
991
+
992
+ if (!await safeManagerPolicy(M2, 'canViewAny', Related2, user, child1)) return { ok: false, status: 403 }
993
+
994
+ const cfg = pilotiq.getConfig()
995
+ const base = cfg.path
996
+ const [step0, step1] = scope.chain
997
+ const resourceBase = resourceBasePath(base, resolved.R)
998
+ const listUrl = `${resourceBase}/${step0.recordId}/${step0.relationship}/${step1.recordId}/${step1.relationship}`
999
+
1000
+ const managerCtx = nestedManagerCtx(base, scope, resolved)
1001
+ const table = M2.table(Table.make(), managerCtx)
1002
+ if (Related1.model) {
1003
+ autoWireManagerTable(table, Related1.model as ModelLike, child1, step1.relationship)
1004
+ }
1005
+ injectManagerTrashedFilter(table, Related2)
1006
+
1007
+ const ctx: SchemaContext = uploadCtx(userCtx({
1008
+ mode: 'table',
1009
+ basePath: base,
1010
+ record: child1,
1011
+ }, user), cfg)
1012
+
1013
+ const elements: Element[] = [table]
1014
+ tagActionDispatch(elements, listUrl)
1015
+ const [, tabs] = await Promise.all([
1016
+ loadTableRecords(elements, scope.query ?? {}, listUrl, user),
1017
+ buildNestedRelationTabs(resolved.R, resolved.M1, base, scope.chain[0], scope.chain[1].recordId, scope.chain[1].relationship, user, resolved.child1),
1018
+ ])
1019
+ if (tabs) elements.unshift(tabs)
1020
+
1021
+ const breadcrumbs = nestedRelationListBreadcrumbs(
1022
+ cfg, resolved.R, resolved.M1, M2, scope.chain[0],
1023
+ deriveParentTitle(resolved.R, resolved.parentRecord),
1024
+ scope.chain[1].recordId,
1025
+ deriveParentTitle(Related1, child1, resolved.M1),
1026
+ )
1027
+ if (breadcrumbs) elements.unshift(breadcrumbs)
1028
+
1029
+ const nestedListRoute: PanelInfoRoute = { resource: resolved.R, recordId: scope.chain[1].recordId }
1030
+ const [panel, schemaData] = await Promise.all([
1031
+ panelInfo(pilotiq, req, nestedListRoute),
1032
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-list', metas, nestedListRoute)),
1033
+ ])
1034
+
1035
+ return {
1036
+ ...nestedResponseEnvelope('nested-relation-list', pilotiq, base, scope, resolved, req),
1037
+ panel,
1038
+ schemaData,
1039
+ }
1040
+ }
1041
+
1042
+ async function buildNestedRelationCreateData(
1043
+ pilotiq: Pilotiq,
1044
+ scope: Extract<NestedRelationScope, { kind: 'nested-relation-create' }>,
1045
+ resolved: ResolvedChain,
1046
+ req: unknown,
1047
+ user: unknown,
1048
+ ): Promise<RelationManagerResult> {
1049
+ const { child1, M2, Related2 } = resolved
1050
+
1051
+ if (!await safeManagerPolicy(M2, 'canCreate', Related2, user, child1)) return { ok: false, status: 403 }
1052
+
1053
+ const cfg = pilotiq.getConfig()
1054
+ const base = cfg.path
1055
+ const [step0, step1] = scope.chain
1056
+ const resourceBase = resourceBasePath(base, resolved.R)
1057
+ const createUrl = `${resourceBase}/${step0.recordId}/${step0.relationship}/${step1.recordId}/${step1.relationship}/create`
1058
+
1059
+ const managerCtx = nestedManagerCtx(base, scope, resolved)
1060
+ const form = M2.form(Form.make(), managerCtx)
1061
+ if (Related2?.model) autoWireManagerForm(form, Related2)
1062
+
1063
+ const elements: Element[] = [form]
1064
+ tagFormActions(elements, createUrl)
1065
+
1066
+ if (scope.prefill) {
1067
+ if (scope.prefill.values) form.withValues(scope.prefill.values)
1068
+ if (scope.prefill.errors) form.withErrors(scope.prefill.errors)
1069
+ }
1070
+
1071
+ const tabs = await buildNestedRelationTabs(resolved.R, resolved.M1, base, scope.chain[0], scope.chain[1].recordId, scope.chain[1].relationship, user, resolved.child1)
1072
+ if (tabs) elements.unshift(tabs)
1073
+
1074
+ const breadcrumbs = nestedRelationCreateBreadcrumbs(
1075
+ cfg, resolved.R, resolved.M1, M2, scope.chain[0],
1076
+ deriveParentTitle(resolved.R, resolved.parentRecord),
1077
+ scope.chain[1].recordId,
1078
+ deriveParentTitle(resolved.Related1, child1, resolved.M1),
1079
+ )
1080
+ if (breadcrumbs) elements.unshift(breadcrumbs)
1081
+
1082
+ const ctx: SchemaContext = uploadCtx(userCtx({
1083
+ mode: 'create',
1084
+ basePath: base,
1085
+ record: child1,
1086
+ }, user), cfg)
1087
+
1088
+ const nestedCreateRoute: PanelInfoRoute = { resource: resolved.R, recordId: scope.chain[1].recordId }
1089
+ const [panel, schemaData] = await Promise.all([
1090
+ panelInfo(pilotiq, req, nestedCreateRoute),
1091
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-create', metas, nestedCreateRoute)),
1092
+ ])
1093
+
1094
+ return {
1095
+ ...nestedResponseEnvelope('nested-relation-create', pilotiq, base, scope, resolved, req),
1096
+ panel,
1097
+ mode: 'create' as const,
1098
+ schemaData,
1099
+ ...(scope.prefill?.errors ? { hasErrors: true } : {}),
1100
+ }
1101
+ }
1102
+
1103
+ async function buildNestedRelationViewData(
1104
+ pilotiq: Pilotiq,
1105
+ scope: Extract<NestedRelationScope, { kind: 'nested-relation-view' }>,
1106
+ resolved: ResolvedChain,
1107
+ req: unknown,
1108
+ user: unknown,
1109
+ ): Promise<RelationManagerResult> {
1110
+ const { Related1, child1, M2, Related2 } = resolved
1111
+ if (!Related2?.model) {
1112
+ throw new Error(
1113
+ `[Pilotiq] Cannot load child record for nested manager ${M2.name}: ` +
1114
+ `Related Resource ${Related2?.name ?? '(none)'} has no static model.`,
1115
+ )
1116
+ }
1117
+ const [, step1] = scope.chain
1118
+ const child2Pk = getPrimaryKey(Related2.model)
1119
+
1120
+ const [belongs2, child2] = await Promise.all([
1121
+ childBelongsToParent(Related1.model as ModelLike, child1, step1.relationship, child2Pk, scope.childId),
1122
+ findRecord(Related2, scope.childId, { user }).catch(() => undefined),
1123
+ ])
1124
+ if (!belongs2 || !child2) return null
1125
+
1126
+ if (!await safeManagerPolicy(M2, 'canView', Related2, user, child1, child2)) return { ok: false, status: 403 }
1127
+
1128
+ const cfg = pilotiq.getConfig()
1129
+ const base = cfg.path
1130
+
1131
+ const elements: Element[] = M2.detail(child2, child1)
1132
+
1133
+ const tabs = await buildNestedRelationTabs(resolved.R, resolved.M1, base, scope.chain[0], scope.chain[1].recordId, scope.chain[1].relationship, user, resolved.child1)
1134
+ if (tabs) elements.unshift(tabs)
1135
+
1136
+ const breadcrumbs = nestedRelationViewBreadcrumbs(
1137
+ cfg, resolved.R, resolved.M1, M2, scope.chain[0],
1138
+ deriveParentTitle(resolved.R, resolved.parentRecord),
1139
+ scope.chain[1].recordId,
1140
+ deriveParentTitle(Related1, child1, resolved.M1),
1141
+ deriveParentTitle(Related2, child2, M2),
1142
+ )
1143
+ if (breadcrumbs) elements.unshift(breadcrumbs)
1144
+
1145
+ const ctx: SchemaContext = uploadCtx(userCtx({
1146
+ mode: 'view',
1147
+ basePath: base,
1148
+ record: child2,
1149
+ recordId: scope.childId,
1150
+ }, user), cfg)
1151
+
1152
+ const nestedViewRoute: PanelInfoRoute = { resource: resolved.R, recordId: scope.childId }
1153
+ const [panel, schemaData] = await Promise.all([
1154
+ panelInfo(pilotiq, req, nestedViewRoute),
1155
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-view', metas, nestedViewRoute)),
1156
+ ])
1157
+
1158
+ return {
1159
+ ...nestedResponseEnvelope('nested-relation-view', pilotiq, base, scope, resolved, req),
1160
+ panel,
1161
+ mode: 'view' as const,
1162
+ childId: scope.childId,
1163
+ schemaData,
1164
+ }
1165
+ }
1166
+
1167
+ async function buildNestedRelationEditData(
1168
+ pilotiq: Pilotiq,
1169
+ scope: Extract<NestedRelationScope, { kind: 'nested-relation-edit' }>,
1170
+ resolved: ResolvedChain,
1171
+ req: unknown,
1172
+ user: unknown,
1173
+ ): Promise<RelationManagerResult> {
1174
+ const { Related1, child1, M2, Related2 } = resolved
1175
+ if (!Related2?.model) {
1176
+ throw new Error(
1177
+ `[Pilotiq] Cannot load child record for nested manager ${M2.name}: ` +
1178
+ `Related Resource ${Related2?.name ?? '(none)'} has no static model.`,
1179
+ )
1180
+ }
1181
+ const [step0, step1] = scope.chain
1182
+ const child2Pk = getPrimaryKey(Related2.model)
1183
+
1184
+ const [belongs2, child2] = await Promise.all([
1185
+ childBelongsToParent(Related1.model as ModelLike, child1, step1.relationship, child2Pk, scope.childId),
1186
+ findRecord(Related2, scope.childId, { user }).catch(() => undefined),
1187
+ ])
1188
+ if (!belongs2 || !child2) return null
1189
+
1190
+ if (!await safeManagerPolicy(M2, 'canEdit', Related2, user, child1, child2)) return { ok: false, status: 403 }
1191
+
1192
+ const cfg = pilotiq.getConfig()
1193
+ const base = cfg.path
1194
+ const resourceBase = resourceBasePath(base, resolved.R)
1195
+ const editUrl = `${resourceBase}/${step0.recordId}/${step0.relationship}/${step1.recordId}/${step1.relationship}/${scope.childId}/edit`
1196
+
1197
+ const managerCtx = nestedManagerCtx(base, scope, resolved)
1198
+ const form = M2.form(Form.make(), managerCtx)
1199
+ autoWireManagerForm(form, Related2)
1200
+
1201
+ const elements: Element[] = [form]
1202
+ tagFormActions(elements, editUrl)
1203
+
1204
+ if (scope.prefill?.values) {
1205
+ form.withValues(scope.prefill.values)
1206
+ if (scope.prefill.errors) form.withErrors(scope.prefill.errors)
1207
+ } else if (child2 != null) {
1208
+ const values = await applyFillPipeline(form, child2)
1209
+ form.withValues(values)
1210
+ }
1211
+
1212
+ const tabs = await buildNestedRelationTabs(resolved.R, resolved.M1, base, scope.chain[0], scope.chain[1].recordId, scope.chain[1].relationship, user, resolved.child1)
1213
+ if (tabs) elements.unshift(tabs)
1214
+
1215
+ const breadcrumbs = nestedRelationEditBreadcrumbs(
1216
+ cfg, resolved.R, resolved.M1, M2, scope.chain[0],
1217
+ deriveParentTitle(resolved.R, resolved.parentRecord),
1218
+ scope.chain[1].recordId,
1219
+ deriveParentTitle(Related1, child1, resolved.M1),
1220
+ scope.childId,
1221
+ deriveParentTitle(Related2, child2, M2),
1222
+ )
1223
+ if (breadcrumbs) elements.unshift(breadcrumbs)
1224
+
1225
+ const ctx: SchemaContext = uploadCtx(userCtx({
1226
+ mode: 'edit',
1227
+ basePath: base,
1228
+ record: child2,
1229
+ recordId: scope.childId,
1230
+ }, user), cfg)
1231
+
1232
+ const nestedEditRoute: PanelInfoRoute = { resource: resolved.R, recordId: scope.childId }
1233
+ const [panel, schemaData] = await Promise.all([
1234
+ panelInfo(pilotiq, req, nestedEditRoute),
1235
+ resolveSchema(elements, ctx).then(metas => applyRoleHooks(pilotiq, user, 'relation-edit', metas, nestedEditRoute)),
1236
+ ])
1237
+
1238
+ return {
1239
+ ...nestedResponseEnvelope('nested-relation-edit', pilotiq, base, scope, resolved, req),
1240
+ panel,
1241
+ mode: 'edit' as const,
1242
+ childId: scope.childId,
1243
+ schemaData,
1244
+ ...(scope.prefill?.errors ? { hasErrors: true } : {}),
1245
+ }
1246
+ }