reactiveadmin 0.2.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 (260) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +88 -0
  3. data/LICENSE +21 -0
  4. data/README.md +81 -0
  5. data/app/assets/reactive_admin/bridge.js +89 -0
  6. data/app/controllers/reactive_admin/api_controller.rb +30 -0
  7. data/app/controllers/reactive_admin/client_errors_controller.rb +38 -0
  8. data/app/controllers/reactive_admin/manifest_controller.rb +10 -0
  9. data/app/controllers/reactive_admin/mcp_controller.rb +48 -0
  10. data/app/controllers/reactive_admin/openapi_controller.rb +13 -0
  11. data/app/controllers/reactive_admin/session_controller.rb +11 -0
  12. data/app/views/layouts/reactive_admin/embed.html.erb +30 -0
  13. data/lib/generators/reactiveadmin/install/install_generator.rb +341 -0
  14. data/lib/generators/reactiveadmin/install/templates/menu.rb.tt +25 -0
  15. data/lib/generators/reactiveadmin/install/templates/reactive_admin.rb.tt +53 -0
  16. data/lib/generators/reactiveadmin/install/templates/reactive_admin_annotated.rb.tt +110 -0
  17. data/lib/reactive_admin/aa/v3/controller.rb +76 -0
  18. data/lib/reactive_admin/aa/v3/forms.rb +29 -0
  19. data/lib/reactive_admin/aa/v3/inputs/filters/typeahead_input.rb +51 -0
  20. data/lib/reactive_admin/aa/v3/inputs/typeahead_input.rb +8 -0
  21. data/lib/reactive_admin/aa/v3/install.rb +36 -0
  22. data/lib/reactive_admin/aa/v3/menu.rb +67 -0
  23. data/lib/reactive_admin/aa/v3/presenters.rb +102 -0
  24. data/lib/reactive_admin/aa/v3/registry.rb +78 -0
  25. data/lib/reactive_admin/aa/v3/views.rb +63 -0
  26. data/lib/reactive_admin/aa/v3.rb +23 -0
  27. data/lib/reactive_admin/aa/v4.rb +59 -0
  28. data/lib/reactive_admin/aa.rb +46 -0
  29. data/lib/reactive_admin/action_items.rb +39 -0
  30. data/lib/reactive_admin/action_links.rb +197 -0
  31. data/lib/reactive_admin/action_safety.rb +19 -0
  32. data/lib/reactive_admin/actions.rb +95 -0
  33. data/lib/reactive_admin/api_errors.rb +116 -0
  34. data/lib/reactive_admin/api_fallback.rb +15 -0
  35. data/lib/reactive_admin/api_guards.rb +445 -0
  36. data/lib/reactive_admin/audit.rb +72 -0
  37. data/lib/reactive_admin/auth/guard.rb +68 -0
  38. data/lib/reactive_admin/auth/token_requests.rb +15 -0
  39. data/lib/reactive_admin/auth.rb +135 -0
  40. data/lib/reactive_admin/authorizer.rb +47 -0
  41. data/lib/reactive_admin/background_requests.rb +33 -0
  42. data/lib/reactive_admin/batch_actions.rb +57 -0
  43. data/lib/reactive_admin/choices.rb +289 -0
  44. data/lib/reactive_admin/client_error.rb +70 -0
  45. data/lib/reactive_admin/composite_keys.rb +12 -0
  46. data/lib/reactive_admin/configuration.rb +221 -0
  47. data/lib/reactive_admin/controller_extension.rb +229 -0
  48. data/lib/reactive_admin/csv_injection.rb +26 -0
  49. data/lib/reactive_admin/date_bound.rb +31 -0
  50. data/lib/reactive_admin/degradation.rb +72 -0
  51. data/lib/reactive_admin/diagnostics.rb +16 -0
  52. data/lib/reactive_admin/doctor.rb +466 -0
  53. data/lib/reactive_admin/dry_run.rb +147 -0
  54. data/lib/reactive_admin/dry_run_flag.rb +18 -0
  55. data/lib/reactive_admin/embed.rb +73 -0
  56. data/lib/reactive_admin/engine.rb +47 -0
  57. data/lib/reactive_admin/error_keys.rb +23 -0
  58. data/lib/reactive_admin/exposure.rb +86 -0
  59. data/lib/reactive_admin/filters.rb +165 -0
  60. data/lib/reactive_admin/fixtures/scrubber.rb +1075 -0
  61. data/lib/reactive_admin/fixtures.rb +161 -0
  62. data/lib/reactive_admin/form_content.rb +78 -0
  63. data/lib/reactive_admin/form_field.rb +279 -0
  64. data/lib/reactive_admin/form_has_many.rb +116 -0
  65. data/lib/reactive_admin/form_lock.rb +71 -0
  66. data/lib/reactive_admin/form_payload.rb +57 -0
  67. data/lib/reactive_admin/form_recorder.rb +192 -0
  68. data/lib/reactive_admin/form_schema.rb +160 -0
  69. data/lib/reactive_admin/frame.rb +97 -0
  70. data/lib/reactive_admin/html_nodes.rb +390 -0
  71. data/lib/reactive_admin/html_policy.rb +338 -0
  72. data/lib/reactive_admin/html_rich.rb +186 -0
  73. data/lib/reactive_admin/implicit_defaults.rb +102 -0
  74. data/lib/reactive_admin/index_options.rb +41 -0
  75. data/lib/reactive_admin/index_payload.rb +259 -0
  76. data/lib/reactive_admin/index_recorder.rb +115 -0
  77. data/lib/reactive_admin/index_views.rb +85 -0
  78. data/lib/reactive_admin/inline_style.rb +125 -0
  79. data/lib/reactive_admin/labels_payload.rb +34 -0
  80. data/lib/reactive_admin/ladder.rb +268 -0
  81. data/lib/reactive_admin/layout_classes.rb +167 -0
  82. data/lib/reactive_admin/legacy_inventory.rb +547 -0
  83. data/lib/reactive_admin/location.rb +22 -0
  84. data/lib/reactive_admin/lookup_audit.rb +30 -0
  85. data/lib/reactive_admin/lookup_payload.rb +41 -0
  86. data/lib/reactive_admin/manifest.rb +36 -0
  87. data/lib/reactive_admin/masked_json.rb +62 -0
  88. data/lib/reactive_admin/masking.rb +100 -0
  89. data/lib/reactive_admin/mcp/access.rb +111 -0
  90. data/lib/reactive_admin/mcp/api.rb +123 -0
  91. data/lib/reactive_admin/mcp/count_tool.rb +22 -0
  92. data/lib/reactive_admin/mcp/layout.rb +175 -0
  93. data/lib/reactive_admin/mcp/output.rb +46 -0
  94. data/lib/reactive_admin/mcp/prompts.rb +111 -0
  95. data/lib/reactive_admin/mcp/server.rb +134 -0
  96. data/lib/reactive_admin/mcp/shapes.rb +164 -0
  97. data/lib/reactive_admin/mcp/tools.rb +386 -0
  98. data/lib/reactive_admin/mcp.rb +53 -0
  99. data/lib/reactive_admin/media_nodes.rb +34 -0
  100. data/lib/reactive_admin/menu.rb +90 -0
  101. data/lib/reactive_admin/menu_overlay.rb +291 -0
  102. data/lib/reactive_admin/node_registry.rb +47 -0
  103. data/lib/reactive_admin/open_api/builder.rb +156 -0
  104. data/lib/reactive_admin/open_api/context.rb +46 -0
  105. data/lib/reactive_admin/open_api/core.rb +51 -0
  106. data/lib/reactive_admin/open_api/operation_ids.rb +18 -0
  107. data/lib/reactive_admin/open_api/page_doc.rb +75 -0
  108. data/lib/reactive_admin/open_api/parts.rb +86 -0
  109. data/lib/reactive_admin/open_api/resource_doc.rb +423 -0
  110. data/lib/reactive_admin/open_api/security.rb +55 -0
  111. data/lib/reactive_admin/open_api/write_schema.rb +104 -0
  112. data/lib/reactive_admin/open_api.rb +41 -0
  113. data/lib/reactive_admin/option_source.rb +36 -0
  114. data/lib/reactive_admin/option_sources.rb +14 -0
  115. data/lib/reactive_admin/options_payload.rb +61 -0
  116. data/lib/reactive_admin/page_controller_extension.rb +112 -0
  117. data/lib/reactive_admin/page_forms.rb +181 -0
  118. data/lib/reactive_admin/page_payload.rb +120 -0
  119. data/lib/reactive_admin/param_normalizer.rb +89 -0
  120. data/lib/reactive_admin/paths.rb +63 -0
  121. data/lib/reactive_admin/permissions.rb +31 -0
  122. data/lib/reactive_admin/provenance.rb +57 -0
  123. data/lib/reactive_admin/query_guard.rb +108 -0
  124. data/lib/reactive_admin/ransack_guard.rb +107 -0
  125. data/lib/reactive_admin/rate_limit.rb +59 -0
  126. data/lib/reactive_admin/reactive_dsl.rb +99 -0
  127. data/lib/reactive_admin/readiness.rb +189 -0
  128. data/lib/reactive_admin/registry.rb +69 -0
  129. data/lib/reactive_admin/resource_meta.rb +120 -0
  130. data/lib/reactive_admin/resource_summary.rb +41 -0
  131. data/lib/reactive_admin/routes.rb +60 -0
  132. data/lib/reactive_admin/row_errors.rb +29 -0
  133. data/lib/reactive_admin/rspec.rb +116 -0
  134. data/lib/reactive_admin/scrubbed_error.rb +22 -0
  135. data/lib/reactive_admin/search.rb +79 -0
  136. data/lib/reactive_admin/server_timing.rb +31 -0
  137. data/lib/reactive_admin/show_payload.rb +88 -0
  138. data/lib/reactive_admin/sidebars.rb +34 -0
  139. data/lib/reactive_admin/site.rb +55 -0
  140. data/lib/reactive_admin/style_report.rb +129 -0
  141. data/lib/reactive_admin/style_sources.rb +83 -0
  142. data/lib/reactive_admin/template_actions.rb +126 -0
  143. data/lib/reactive_admin/template_content.rb +49 -0
  144. data/lib/reactive_admin/template_form.rb +442 -0
  145. data/lib/reactive_admin/test_support.rb +31 -0
  146. data/lib/reactive_admin/typeahead.rb +33 -0
  147. data/lib/reactive_admin/ui/assets.rb +91 -0
  148. data/lib/reactive_admin/ui/client_build.rb +47 -0
  149. data/lib/reactive_admin/ui/helper.rb +24 -0
  150. data/lib/reactive_admin/ui/packaged_client.rb +67 -0
  151. data/lib/reactive_admin/ui/shell.rb +81 -0
  152. data/lib/reactive_admin/ui/switch.rb +38 -0
  153. data/lib/reactive_admin/ui.rb +43 -0
  154. data/lib/reactive_admin/value_payload.rb +147 -0
  155. data/lib/reactive_admin/value_token.rb +36 -0
  156. data/lib/reactive_admin/values.rb +43 -0
  157. data/lib/reactive_admin/version.rb +3 -0
  158. data/lib/reactive_admin/write_audit.rb +60 -0
  159. data/lib/reactive_admin/write_guards.rb +142 -0
  160. data/lib/reactive_admin.rb +153 -0
  161. data/lib/reactiveadmin.rb +1 -0
  162. data/lib/tasks/reactiveadmin.rake +36 -0
  163. data/lib/tasks/reactiveadmin_client.rake +11 -0
  164. data/lib/tasks/reactiveadmin_legacy.rake +7 -0
  165. data/lib/tasks/reactiveadmin_styles.rake +6 -0
  166. data/openapi/core.yaml +1643 -0
  167. data/vendor/client/assets/ActionPage-XUYorI8E.js +1 -0
  168. data/vendor/client/assets/ActionView-BsZFcsgp.js +1 -0
  169. data/vendor/client/assets/CommandPalette-C59HT1ip.js +1 -0
  170. data/vendor/client/assets/DatePicker-DuaK0iMg.js +1 -0
  171. data/vendor/client/assets/DateRangeCalendar-B2BDsG-X.js +1 -0
  172. data/vendor/client/assets/DegradedNotice-DiH5n2DO.js +1 -0
  173. data/vendor/client/assets/FormDialog-pmYl8Eov.js +1 -0
  174. data/vendor/client/assets/FormSkeleton-DuSBZO3C.js +1 -0
  175. data/vendor/client/assets/FrameView-2X8cFvUt.css +1 -0
  176. data/vendor/client/assets/FrameView-zmUeDO8d.js +1 -0
  177. data/vendor/client/assets/GroupOverview-DI5T3k5K.js +1 -0
  178. data/vendor/client/assets/InlineForm-CMEIMgeh.js +1 -0
  179. data/vendor/client/assets/JsonDiff-o7JWr7CH.js +3 -0
  180. data/vendor/client/assets/JsonEditor-D4VXdlEx.js +1 -0
  181. data/vendor/client/assets/JsonView-BrJLDmSN.js +1 -0
  182. data/vendor/client/assets/MobileMenu-GAeFOeEb.js +1 -0
  183. data/vendor/client/assets/Node-SQl61V4K.js +2 -0
  184. data/vendor/client/assets/PageView-C-laNEPZ.js +1 -0
  185. data/vendor/client/assets/ResourceForm-BPjsoCY6.js +1 -0
  186. data/vendor/client/assets/ResourceIndex-COezAw5t.js +3 -0
  187. data/vendor/client/assets/ResourceOrPage-CRZGCY84.js +1 -0
  188. data/vendor/client/assets/ResourceShow-DweRXn18.js +1 -0
  189. data/vendor/client/assets/Segmented-BE9TCbph.js +1 -0
  190. data/vendor/client/assets/Sidebars-CsB9rFqX.js +1 -0
  191. data/vendor/client/assets/breadcrumb-DSA3Tlyd.js +1 -0
  192. data/vendor/client/assets/button-CvZ4_DFC.js +1 -0
  193. data/vendor/client/assets/calendar-BoyMpJIf.js +1 -0
  194. data/vendor/client/assets/check-C5A3J16N.js +1 -0
  195. data/vendor/client/assets/command-CMuk0oAt.js +1 -0
  196. data/vendor/client/assets/dist-CqEI82S_.js +1 -0
  197. data/vendor/client/assets/dist-IW4yX942.js +1 -0
  198. data/vendor/client/assets/editor-yqRLzgsJ.js +2 -0
  199. data/vendor/client/assets/external-link-C2aR4slL.js +1 -0
  200. data/vendor/client/assets/frames-C9gPCc3N.js +1 -0
  201. data/vendor/client/assets/humanize-DtU_Kpr4.js +1 -0
  202. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  203. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  204. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  205. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  206. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  207. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  208. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  209. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  210. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  211. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  212. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  213. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  214. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  215. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  216. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  217. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  218. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  219. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  220. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  221. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  222. data/vendor/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  223. data/vendor/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  224. data/vendor/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  225. data/vendor/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  226. data/vendor/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  227. data/vendor/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  228. data/vendor/client/assets/index-B51aUaAY.js +43 -0
  229. data/vendor/client/assets/index-Cs9rCoWM.css +2 -0
  230. data/vendor/client/assets/input-DByFmQPa.js +1 -0
  231. data/vendor/client/assets/json-De3PN-R6.css +1 -0
  232. data/vendor/client/assets/json-oTp7Q-d-.js +5 -0
  233. data/vendor/client/assets/media-D4a_En8R.js +1 -0
  234. data/vendor/client/assets/plus-CfJ9vo8X.js +1 -0
  235. data/vendor/client/assets/popover-CDtI9R8Q.js +1 -0
  236. data/vendor/client/assets/purify-G7QKJyJq.js +1 -0
  237. data/vendor/client/assets/query-CCsZN2fa.js +1 -0
  238. data/vendor/client/assets/recent-BrzLwL0D.js +1 -0
  239. data/vendor/client/assets/rich-BQc_q5T7.js +1 -0
  240. data/vendor/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  241. data/vendor/client/assets/select-C43qDA3k.js +1 -0
  242. data/vendor/client/assets/sheet-BPl2n-4n.js +1 -0
  243. data/vendor/client/assets/textarea-BnOphXry.js +1 -0
  244. data/vendor/client/assets/uiMode-z0ZbRV49.js +1 -0
  245. data/vendor/client/assets/uiToggle-DwnRQTH1.js +1 -0
  246. data/vendor/client/assets/useRecordForm-X_DExEP2.js +1 -0
  247. data/vendor/client/assets/useRecordVisit-BRtfMi-q.js +1 -0
  248. data/vendor/client/assets/utils-DwBGbDkG.js +1 -0
  249. data/vendor/client/assets/vendor-calendar-nTZiq9oY.js +1 -0
  250. data/vendor/client/assets/vendor-datefns-BoC6MCnl.js +1 -0
  251. data/vendor/client/assets/vendor-forms-D0h8hG_S.js +55 -0
  252. data/vendor/client/assets/vendor-purify-BXoPR7WT.js +3 -0
  253. data/vendor/client/assets/vendor-query-DZ6APRNI.js +1 -0
  254. data/vendor/client/assets/vendor-react-C1iE8mnY.js +9 -0
  255. data/vendor/client/assets/vendor-router-CI6Vh4k_.js +1 -0
  256. data/vendor/client/assets/vendor-table-DuQ835by.js +4 -0
  257. data/vendor/client/index.html +24 -0
  258. data/vendor/client/manifest.json +867 -0
  259. data/vendor/client/reactiveadmin-client.json +4 -0
  260. metadata +350 -0
@@ -0,0 +1,466 @@
1
+ require "action_controller/test_case"
2
+ require "yaml"
3
+ require "json"
4
+
5
+ module ReactiveAdmin
6
+ # Coverage report behind `rake reactiveadmin:doctor`: how much of the admin the typed API covers
7
+ # and where it degrades, per resource, action and page. Samples one page of rows and one record
8
+ # per resource, read-only. Output names resources, sources and counts, never record data.
9
+ class Doctor
10
+ MODES = %w[native frame iframe custom api].freeze
11
+ SECTIONS = %i[index show form].freeze
12
+ BASELINE_VERSION = 1
13
+ DEFAULT_THRESHOLD = 0.5
14
+
15
+ # Runs an API action of a controller for real, as the given user: callbacks, `controller do`
16
+ # overrides and authorization all apply. Marked internal, so hosts keep it out of
17
+ # their view audits; the run as a whole is wrapped in while_preventing_writes.
18
+ class Sample
19
+ HOST = "doctor.invalid".freeze
20
+
21
+ def initialize(config, user)
22
+ @config = config
23
+ @user = user
24
+ end
25
+
26
+ # [status, parsed json]; failures are the API's own JSON errors.
27
+ def call(action, path_params: {}, query: {})
28
+ controller = @config.controller.new
29
+ bind_user(controller)
30
+ response = ActionDispatch::TestResponse.new
31
+ controller.dispatch(action, request(action, path_params, query), response)
32
+ [response.status, JSON.parse(response.body)]
33
+ rescue JSON::ParserError
34
+ [response.status, {}]
35
+ ensure
36
+ ActiveSupport::CurrentAttributes.clear_all
37
+ end
38
+
39
+ # Only the parts a view needs, for payloads built outside a request (filters). It belongs to
40
+ # the controller, as the user does, so AA's procs reach the helpers they would in a request.
41
+ def view
42
+ @view ||= begin
43
+ controller = @config.controller.new
44
+ bind_user(controller)
45
+ controller.request = request("index", {}, {})
46
+ controller.response = ActionDispatch::TestResponse.new
47
+ controller.view_context
48
+ end
49
+ end
50
+
51
+ def controller = view.controller
52
+
53
+ private
54
+
55
+ def bind_user(controller)
56
+ method = AA.current_user_method(Registry.namespace)
57
+ user = @user
58
+ controller.define_singleton_method(method) { user } if method
59
+ end
60
+
61
+ def request(action, path_params, query)
62
+ env = {"HTTP_HOST" => HOST, "PATH_INFO" => "/", "QUERY_STRING" => query.to_query,
63
+ BackgroundRequests::INTERNAL_ENV => true, "rack.input" => StringIO.new}
64
+ ActionDispatch::TestRequest.create(env).tap do |request|
65
+ request.session = ActionController::TestSession.new
66
+ request.path_parameters = {controller: @config.controller.controller_path, action: action.to_s, format: "reactiveadmin", **path_params}
67
+ end
68
+ end
69
+ end
70
+
71
+ # Typed versus html leaves of a payload's nodes or fields.
72
+ module Tally
73
+ CONTAINERS = %w[group box panel attributes_table table tabs tab columns column].freeze
74
+
75
+ module_function
76
+
77
+ def nodes(value, tally = {typed: 0, html: 0})
78
+ case value
79
+ when Array then value.each { nodes(it, tally) }
80
+ when Hash
81
+ type = value["type"] || value[:type]
82
+ if type
83
+ leaf(type, tally) unless CONTAINERS.include?(type)
84
+ nodes(value.reject { |key, _| %w[type action ref].include?(key.to_s) }.values, tally)
85
+ else
86
+ nodes(value.values, tally)
87
+ end
88
+ end
89
+ tally
90
+ end
91
+
92
+ def fields(sections, tally = {typed: 0, html: 0})
93
+ sections.each do |section|
94
+ [*section["fields"], *section["template_fields"], *Array(section["records"]).flat_map { it["fields"] }].each do |field|
95
+ case field["control"]
96
+ when "html" then tally[:html] += 1
97
+ when "content" then nodes(field["layout"], tally)
98
+ else tally[:typed] += 1
99
+ end
100
+ end
101
+ end
102
+ tally
103
+ end
104
+
105
+ # An `error` node is a cell or value that raised while rendering, inside an otherwise successful response.
106
+ def leaf(type, tally)
107
+ return if %w[empty].include?(type)
108
+ return tally[:errors] = tally[:errors].to_i + 1 if type == "error"
109
+
110
+ # A frame or iframe embeds a classic page: that section falls back, not merely leaves an html leaf.
111
+ return tally[:frames] = tally[:frames].to_i + 1 if %w[frame iframe].include?(type)
112
+
113
+ (type == "html") ? tally[:html] += 1 : tally[:typed] += 1
114
+ end
115
+ end
116
+
117
+ SampleFailed = Class.new(StandardError)
118
+
119
+ def self.run(**) = new(**).run
120
+
121
+ # What `doctor_page_params` gives the page to render with; pages that read required params need it.
122
+ def self.page_query(config) = ReactiveAdmin.config.doctor_page_params&.call(config.underscored_resource_name) || {}
123
+
124
+ # Options: user: (who to sample as; without one only the static parts run), sample: false for static only.
125
+ def initialize(user: nil, sample: true)
126
+ @user = user || ReactiveAdmin.config.doctor_user&.call
127
+ @sample = sample && !@user.nil?
128
+ end
129
+
130
+ def run
131
+ Rails.application.reload_routes_unless_loaded
132
+ ReactiveAdmin.diagnostics.clear
133
+ report = ApiGuards.with_channel(:session) { ActiveRecord::Base.while_preventing_writes { silence { Degradation.synthetic { StyleSources.trace { build } } } } }
134
+ [*Exposure.audit(user: @user), *ApiGuards.audit, *Mcp::Access.audit, *self.class.config_warnings].each { ReactiveAdmin.diagnostics.record(it[:kind], **it.except(:kind)) }
135
+ report.merge(api_guards: ApiGuards.accepted, mcp: mcp_surface, menu_links: MenuOverlay.links, diagnostics: ReactiveAdmin.diagnostics.entries.map { it.transform_values(&:to_s) })
136
+ end
137
+
138
+ # Baseline: what a later run must not do worse than.
139
+ def self.baseline(report)
140
+ {
141
+ "version" => BASELINE_VERSION,
142
+ "summary" => report[:summary].slice(:ladder_fallback_pct, :html_node_pct, :failures).transform_keys(&:to_s),
143
+ "actions" => report[:resources].flat_map { |r| r[:actions].map { |a| ["#{r[:key]}##{a[:name]}", a[:mode]] } }.to_h,
144
+ "pages" => report[:pages].to_h { [it[:key], it[:mode]] },
145
+ "failures" => failures(report)
146
+ }
147
+ end
148
+
149
+ def self.failures(report)
150
+ [*report[:resources].flat_map { |r| r[:failures].map { |section| "#{r[:key]}: #{section}" } },
151
+ *report[:pages].filter_map { "page #{it[:key]}: render" if it[:failure] }].sort
152
+ end
153
+
154
+ # Regressions against a baseline: a mode downgrade, a new failure, or a fallback share that grew.
155
+ def self.compare(report, baseline, threshold: DEFAULT_THRESHOLD)
156
+ issues = []
157
+ current = baseline(report)
158
+ %w[actions pages].each do |kind|
159
+ baseline.fetch(kind, {}).each do |name, before|
160
+ now = current[kind][name] or next
161
+ issues << "#{kind.chomp("s")} #{name}: #{before} -> #{now}" if rank(now) > rank(before)
162
+ end
163
+ end
164
+ (current["failures"] - baseline.fetch("failures", [])).each { issues << "new failure #{it}" }
165
+ %w[ladder_fallback_pct html_node_pct].each do |key|
166
+ before = baseline.dig("summary", key)
167
+ now = current["summary"][key]
168
+ issues << "#{key} #{before} -> #{now}" if before && now && now - before > threshold
169
+ end
170
+ issues
171
+ end
172
+
173
+ def self.rank(mode) = Ladder::RANK.fetch(mode.to_s, 0)
174
+
175
+ CONFIG_KINDS = %w[expose_all null_cache_store mcp_full_sensitive].freeze
176
+
177
+ # Gem defaults that are permissive, or protections that silently do nothing in this environment.
178
+ def self.config_warnings
179
+ [
180
+ ({kind: :expose_all, reason: "expose = :all serves every resource and page the policy permits; set :listed and name what is served"} if ReactiveAdmin.config.expose == :all && !Rails.env.local?),
181
+ ({kind: :null_cache_store, reason: "Rails.cache is a null store: rate limits and the meta cache are disabled"} if Rails.cache.is_a?(ActiveSupport::Cache::NullStore))
182
+ ].compact
183
+ end
184
+
185
+ # Where an error came from in the host's own code; its message may carry record data.
186
+ def self.location(error)
187
+ trace = error.backtrace.to_a
188
+ (trace.find { it.start_with?(Rails.root.to_s) } || trace.first).to_s.delete_prefix("#{Rails.root}/")
189
+ end
190
+
191
+ private
192
+
193
+ # What agents reach of each resource and page, only where the MCP endpoint may be on.
194
+ def mcp_surface
195
+ return unless ReactiveAdmin.config.mcp.possibly_enabled?
196
+
197
+ {default: ReactiveAdmin.config.mcp.default.to_s, resources: Mcp::Access.surface}
198
+ end
199
+
200
+ def build
201
+ resources = Registry.resources.select { Exposure.allowed?(it) && !ApiGuards.fully_denied?(it) }.map { resource(it) }
202
+ pages = Registry.pages.select { Exposure.allowed?(it) && !ApiGuards.fully_denied?(it) }.map { page(it) }
203
+ {generated_at: Time.current.iso8601, sampled: @sample, summary: summary(resources, pages), resources:, pages:}
204
+ end
205
+
206
+ def silence
207
+ stdout = $stdout
208
+ $stdout = StringIO.new
209
+ yield
210
+ ensure
211
+ $stdout = stdout
212
+ end
213
+
214
+ def resource(config)
215
+ row = {key: Registry.route_key(config), actions: actions(config), failures: []}
216
+ meta = guard(row, "filters") { filters(config) }
217
+ row[:filters] = meta || {total: 0, built: 0, by_control: {}, skipped: []}
218
+ row[:sources] = sources(config)
219
+ row[:implicit_view] = implicit_view(config, row[:key])
220
+ SECTIONS.each { |section| row[section] = sample(config, section, row) } if @sample
221
+ row[:index_options] = IndexOptions.declared(config).merge(row.dig(:index, :options) || {})
222
+ row
223
+ end
224
+
225
+ # Sections that fall back to default columns, with what secure defaults leave out of them.
226
+ def implicit_view(config, key)
227
+ ImplicitDefaults.audit(config).tap do |sections|
228
+ sections.each { |view, hidden| ReactiveAdmin.diagnostics.record(:implicit_view, resource: key, view:, hidden: hidden.join(", ")) if hidden.any? }
229
+ end
230
+ end
231
+
232
+ def sources(config)
233
+ SECTIONS.to_h do |section|
234
+ block = AA.page_presenter(config, (section == :form) ? :form : section)&.block
235
+ [section, block&.source_location&.then { "#{it[0].delete_prefix("#{Rails.root}/")}:#{it[1]}" }]
236
+ end.compact
237
+ end
238
+
239
+ def filters(config)
240
+ return {total: 0, built: 0, by_control: {}, skipped: []} unless AA.filters_enabled?(config)
241
+
242
+ built = Filters.new(config, Sample.new(config, @user).view).call
243
+ {total: AA.filters(config).size, built: built.size, by_control: built.pluck(:control).tally,
244
+ skipped: AA.filters(config).keys.map(&:to_s) - built.pluck(:name)}
245
+ end
246
+
247
+ def actions(config)
248
+ declared = [*config.member_actions.map { [it, :member] }, *config.collection_actions.map { [it, :collection] }]
249
+ declared.reject { |declaration, _| ApiGuards.denies?(config, declaration.name, verb: Array.wrap(declaration.http_verb).first) }.map do |declaration, kind|
250
+ name = declaration.name.to_s
251
+ verb = Array.wrap(declaration.http_verb).first.to_s
252
+ decision = Ladder.action(config, name) if verb == "get"
253
+ {name:, kind: kind.to_s, verb:, mode: decision&.mode || "api", reason: decision&.reason || "runs through the API"}
254
+ end
255
+ end
256
+
257
+ def page(config)
258
+ decision = Ladder.page(config)
259
+ key = config.underscored_resource_name
260
+ row = {key:, mode: decision.mode, reason: decision.reason, actions: page_actions(config)}
261
+ return row unless @sample && !Paths.nested?(config)
262
+
263
+ rendered = render_page(config)
264
+ return row.merge(failure: rendered[:failure]) if rendered[:failure]
265
+
266
+ reason = (rendered[:mode] == decision.mode) ? decision.reason : "the rendered content is #{rendered[:mode]} (the source reads as #{decision.mode})"
267
+ row.merge(mode: rendered[:mode], reason:, nodes: rendered[:nodes])
268
+ end
269
+
270
+ def page_actions(config)
271
+ config.page_actions.reject { ApiGuards.denies?(config, it.name, verb: Array.wrap(it.http_verb).first) }.map do |declaration|
272
+ name = declaration.name.to_s
273
+ verb = Array.wrap(declaration.http_verb).first.to_s
274
+ decision = Ladder.action(config, name) if verb == "get"
275
+ {name:, verb:, mode: decision&.mode || "api", reason: decision&.reason || "runs through the API"}
276
+ end
277
+ end
278
+
279
+ def render_page(config)
280
+ status, payload = Sample.new(config, @user).call(:reactiveadmin_page, query: self.class.page_query(config))
281
+ return {failure: failure(status, payload)} unless status == 200
282
+
283
+ {mode: payload.dig("view", "mode"), nodes: Tally.nodes(payload["layout"])}
284
+ end
285
+
286
+ def failure(status, payload) = "#{status} #{payload["code"]}: #{payload["message"]}"
287
+
288
+ # One page of rows, one record's show page, the new form (and edit when there is a record).
289
+ def sample(config, section, row)
290
+ action = (section == :form) ? :new : section
291
+ return unless Registry.actions(config).include?(action)
292
+ return {skipped: "nested under a parent"} if Paths.nested?(config) || !Registry.top_level_actions(config).include?(action)
293
+ return {skipped: "api guard"} if ApiGuards.denies?(config, action)
294
+
295
+ guard(row, section.to_s) { send(:"sample_#{section}", config) }
296
+ end
297
+
298
+ def sample_index(config)
299
+ payload = fetch(config, :index, query: {per_page: 5})
300
+ Tally.nodes(payload["rows"].flat_map { [*it["cells"].values, *it["layout"]] })
301
+ .merge(rows: payload["rows"].size, columns: payload["columns"].size, options: IndexOptions.sampled(payload))
302
+ end
303
+
304
+ def sample_show(config)
305
+ record = config.resource_class.first or return {skipped: "no record to show"}
306
+ Tally.nodes(fetch(config, :show, path_params: {id: record.to_param})["layout"]).merge(rows: 1)
307
+ end
308
+
309
+ def sample_form(config)
310
+ payload = fetch(config, :new, path_params: Paths.parent_params(config, config.resource_class.first))
311
+ Tally.fields(payload["form"]["sections"]).merge((payload["submittable"] == false) ? {submittable: false} : {})
312
+ end
313
+
314
+ def fetch(config, action, path_params: {}, query: {})
315
+ status, payload = Sample.new(config, @user).call(action, path_params:, query:)
316
+ raise SampleFailed, failure(status, payload) unless status == 200
317
+
318
+ payload
319
+ end
320
+
321
+ # A section that raises is a finding, not the end of the run.
322
+ def guard(row, section)
323
+ yield
324
+ rescue => e
325
+ row[:failures] << (e.is_a?(SampleFailed) ? "#{section} #{e.message}" : "#{section} #{e.class} at #{self.class.location(e)}")
326
+ nil
327
+ end
328
+
329
+ def summary(resources, pages)
330
+ actions = resources.flat_map { it[:actions] }
331
+ views = [*actions.map { it[:mode] }.reject { it == "api" }, *pages.map { it[:mode] }]
332
+ counts = views.tally
333
+ typed = SECTIONS.to_h { |section| [section, aggregate(resources.filter_map { it[section] })] }
334
+ all = aggregate(typed.values)
335
+ filters = resources.map { it[:filters] }
336
+ {
337
+ resources: resources.size, pages: pages.size,
338
+ actions: MODES.to_h { |mode| [mode.to_sym, actions.count { |action| action[:mode] == mode }] },
339
+ views: MODES.first(4).to_h { |mode| [mode.to_sym, counts.fetch(mode, 0)] },
340
+ pages_by_mode: pages.map { it[:mode] }.tally,
341
+ ladder_fallback_pct: percent(counts.fetch("frame", 0) + counts.fetch("iframe", 0), views.size),
342
+ typed:, html_node_pct: percent(all[:html], all[:typed] + all[:html]),
343
+ filters: {total: filters.sum { it[:total] }, built: filters.sum { it[:built] }, skipped: filters.sum { it[:skipped].size },
344
+ by_control: filters.flat_map { it[:by_control].to_a }.each_with_object(Hash.new(0)) { |(k, v), h| h[k] += v }},
345
+ index_options: resources.flat_map { it[:index_options].to_a }.each_with_object(Hash.new(0)) { |(k, _), h| h[k] += 1 },
346
+ failures: self.class.failures({resources:, pages:}).size
347
+ }
348
+ end
349
+
350
+ def aggregate(tallies) = {typed: tallies.sum { it[:typed].to_i }, html: tallies.sum { it[:html].to_i }}
351
+
352
+ def percent(part, whole) = whole.zero? ? 0.0 : (part * 100.0 / whole).round(1)
353
+
354
+ # Text rendering of a report.
355
+ class Table
356
+ def initialize(report)
357
+ @report = report
358
+ end
359
+
360
+ def to_s
361
+ [summary, ladder, resources, api_guards, mcp, menu_links, failures, warnings].compact.join("\n\n")
362
+ end
363
+
364
+ private
365
+
366
+ attr_reader :report
367
+
368
+ def summary
369
+ s = report[:summary]
370
+ lines = ["reactiveadmin doctor#{" (static: no sample user)" unless report[:sampled]}",
371
+ " resources #{s[:resources]}, pages #{s[:pages]}, filters #{s[:filters][:built]}/#{s[:filters][:total]} built (#{s[:filters][:skipped]} skipped)",
372
+ " actions: #{s[:actions].map { |k, v| "#{k} #{v}" }.join(", ")}",
373
+ " views (actions with a view + pages): #{s[:views].map { |k, v| "#{k} #{v}" }.join(", ")}; fallback #{s[:ladder_fallback_pct]}%",
374
+ " typed vs html leaves: #{s[:typed].map { |k, v| "#{k} #{v[:typed]}/#{v[:typed] + v[:html]}" }.join(", ")}; html #{s[:html_node_pct]}%",
375
+ (" index options (resources using each): #{s[:index_options].map { |k, v| "#{k} #{v}" }.join(", ")}" if s[:index_options].any?),
376
+ " failures #{s[:failures]}, diagnostics #{report[:diagnostics].size}"].compact
377
+ lines.join("\n")
378
+ end
379
+
380
+ def ladder
381
+ rows = report[:resources].flat_map { |r| r[:actions].reject { it[:mode].in?(%w[api native]) }.map { |a| ["#{r[:key]}##{a[:name]}", a[:mode], a[:reason]] } }
382
+ rows += report[:pages].reject { it[:mode] == "native" }.map { |p| ["page #{p[:key]}", p[:mode], p[:reason]] }
383
+ return if rows.empty?
384
+
385
+ width = rows.map { it[0].size }.max
386
+ "Fallback views\n" + rows.sort.map { |name, mode, reason| " #{name.ljust(width)} #{mode.ljust(6)} #{reason}" }.join("\n")
387
+ end
388
+
389
+ def resources
390
+ rows = report[:resources].filter_map do |r|
391
+ html = SECTIONS.filter_map { |section| (r[section] || {}).then { |t| "#{section} #{t[:html]}" if t[:html].to_i.positive? } }
392
+ skipped = r[:filters][:skipped]
393
+ next if html.empty? && skipped.empty?
394
+
395
+ " #{r[:key]}: #{[*html.map { "#{it} html" }, ("filters skipped #{skipped.join(", ")}" if skipped.any?)].compact.join("; ")}"
396
+ end
397
+ ("Html leaves and skipped filters\n#{rows.join("\n")}" if rows.any?)
398
+ end
399
+
400
+ # Decisions, not findings: nothing here counts against coverage.
401
+ def api_guards
402
+ rows = report[:api_guards].to_a.map do |d|
403
+ scope = [("only #{d[:only].join(", ")}" if d[:only]), ("except #{d[:except].join(", ")}" if d[:except]), ("attributes #{d[:attributes].join(", ")}" if d[:attributes])].compact
404
+ " #{d[:kind]} #{d[:key]}: #{d[:guard]} #{scope.join("; ").presence || "all"}#{" (#{d[:reason]})" if d[:reason]}"
405
+ end
406
+ ("API guards (accepted)\n#{rows.join("\n")}" if rows.any?)
407
+ end
408
+
409
+ def mcp
410
+ surface = report[:mcp] or return
411
+ rows = surface[:resources].map do |r|
412
+ reach = [("tools #{r[:tools].join(", ")}" if r[:tools].any?), ("actions #{r[:actions].join(", ")}" if r[:actions].any?)].compact
413
+ " #{r[:kind]} #{r[:key]}: #{r[:mode]}#{"; #{reach.join("; ")}" if reach.any?}"
414
+ end
415
+ "MCP surface (default #{surface[:default]})\n#{rows.join("\n")}"
416
+ end
417
+
418
+ def menu_links
419
+ rows = report[:menu_links].to_a.map { " #{it[:path].join(" > ")}: #{it[:url] || "computed"}" }
420
+ ("Menu links (accepted)\n#{rows.join("\n")}" if rows.any?)
421
+ end
422
+
423
+ def warnings
424
+ list = report[:diagnostics].select { it[:kind].in?(CONFIG_KINDS) }
425
+ ("Configuration warnings\n#{list.map { " #{it[:reason]}" }.join("\n")}" if list.any?)
426
+ end
427
+
428
+ def failures
429
+ list = Doctor.failures(report)
430
+ ("Failures\n#{list.map { " #{it}" }.join("\n")}" if list.any?)
431
+ end
432
+ end
433
+
434
+ # The rake task's driver: options come from the environment so they pass through `rake`.
435
+ module CLI
436
+ module_function
437
+
438
+ def run(env = ENV, out: $stdout)
439
+ report = Doctor.run(sample: env["SAMPLE"] != "0")
440
+ out.puts((env["FORMAT"] == "json") ? JSON.pretty_generate(report) : Table.new(report))
441
+ write_baseline(report, env["WRITE_BASELINE"], out)
442
+ regressions(report, env, out)
443
+ end
444
+
445
+ def write_baseline(report, path, out)
446
+ return unless path.present?
447
+
448
+ File.write(path, Doctor.baseline(report).to_yaml)
449
+ out.puts("baseline written to #{path}")
450
+ end
451
+
452
+ # Number of problems: regressions against the baseline, plus a fallback share above MAX_FALLBACK.
453
+ def regressions(report, env, out)
454
+ issues = []
455
+ if env["BASELINE"].present?
456
+ baseline = YAML.safe_load_file(env["BASELINE"])
457
+ issues += Doctor.compare(report, baseline, threshold: Float(env.fetch("THRESHOLD", DEFAULT_THRESHOLD)))
458
+ end
459
+ max = env["MAX_FALLBACK"]
460
+ issues << "fallback #{report[:summary][:ladder_fallback_pct]}% exceeds #{max}%" if max.present? && report[:summary][:ladder_fallback_pct] > Float(max)
461
+ issues.each { out.puts("regression: #{it}") }
462
+ issues.size
463
+ end
464
+ end
465
+ end
466
+ end
@@ -0,0 +1,147 @@
1
+ module ReactiveAdmin
2
+ # What an update would change, worked out without saving. The submitted attributes are assigned and
3
+ # validated inside a transaction that is always rolled back. Only validation callbacks run. The host's
4
+ # `update` override, save callbacks and AA's update callbacks don't, so a failure only they would cause
5
+ # isn't predicted.
6
+ #
7
+ # Rolling back undoes rows, not what callbacks did elsewhere (mail, jobs, uploads), and some writers
8
+ # save at once on a persisted record: association and `*_ids` writers, attachments. So only database
9
+ # columns whose writer is the one Rails generated, and nested rows built in memory, are previewed.
10
+ # Anything else (virtual or stored attributes, a host-defined writer) is refused: a writer that isn't
11
+ # Rails's own can do anything.
12
+ #
13
+ # Only attributes the form offers a control for are previewed, so a dry run can't read back a stored
14
+ # value the form never exposes. A password or masked control withholds its value, and a JSON value is
15
+ # shown only where the form would inline it, so their changes are masked like a configured secret.
16
+ #
17
+ # The diff names only the attributes the request submitted, so a value a callback derives from them
18
+ # (and the form never offered) isn't shown.
19
+ class DryRun
20
+ MASKED = ValuePayload::MASK
21
+ TEXT_LIMIT = 200
22
+ LIST_LIMIT = 50
23
+ NESTED = /_attributes\z/
24
+ MULTIPARAMETER = /\(\d+[a-z]?\)\z/
25
+ TOP_LEVEL_PARAM = /\A[^\[\]]+\[([^\[\]]+?)(?:\(\d+[a-z]?\))?\](?:\[\])?\z/
26
+
27
+ Result = Data.define(:valid, :changes, :nested)
28
+
29
+ def initialize(controller, record, sections)
30
+ @config = AA.config_of(controller)
31
+ @record = record
32
+ fields = sections.flat_map { (it[:kind] == "has_many") ? [] : it[:fields].to_a }
33
+ @offered = fields.filter_map { it[:param].to_s[TOP_LEVEL_PARAM, 1] }.to_set
34
+ @withheld = fields.select { it[:control] == "password" || it[:masked] }.filter_map { it[:param].to_s[TOP_LEVEL_PARAM, 1] }.to_set
35
+ @params = AA.resource_params(controller)
36
+ end
37
+
38
+ def call
39
+ @params.each { refuse_unpreviewable(@record.class, it, @offered) }
40
+ keys = @params.flat_map { it.keys.map { |key| key.to_s.sub(MULTIPARAMETER, "") } }.uniq
41
+ nested, plain = keys.partition { nested?(@record.class, it) }
42
+ result = nil
43
+ @record.class.transaction(requires_new: true) do
44
+ before = plain.index_with { read(it) }
45
+ @record.assign_attributes(*@params)
46
+ valid = @record.valid?
47
+ result = Result.new(valid:, changes: diff(before, plain.index_with { read(it) }), nested: nested_changes(nested))
48
+ raise ActiveRecord::Rollback
49
+ end
50
+ result
51
+ end
52
+
53
+ private
54
+
55
+ def refuse_unpreviewable(klass, attributes, offered = nil)
56
+ attributes.to_h.each do |key, value|
57
+ key = key.to_s
58
+ next if key == "_destroy"
59
+ next refuse_unpreviewable_rows(klass, key, value) if nested?(klass, key)
60
+
61
+ attribute = key.sub(MULTIPARAMETER, "")
62
+ refuse(key) unless plain_column?(klass, attribute)
63
+ refuse_unoffered(key) unless offered.nil? || offered.include?(attribute)
64
+ end
65
+ end
66
+
67
+ # A column may itself end in `_attributes`; only a declared nested-attributes association is a section.
68
+ def nested?(klass, key) = NESTED.match?(key) && klass.nested_attributes_options.key?(key.sub(NESTED, "").to_sym)
69
+
70
+ def plain_column?(klass, key) = klass.columns_hash.key?(key) && generated_method?(klass, key) && generated_method?(klass, "#{key}=")
71
+
72
+ def generated_method?(klass, writer)
73
+ klass.define_attribute_methods
74
+ return false unless klass.method_defined?(writer)
75
+
76
+ owner = klass.instance_method(writer).owner
77
+ owner.is_a?(ActiveRecord::AttributeMethods::GeneratedAttributeMethods) || owner == ActiveRecord::AttributeMethods::PrimaryKey ||
78
+ klass.ancestors.any? { it.is_a?(Class) && it.respond_to?(:generated_association_methods) && it.generated_association_methods.equal?(owner) }
79
+ end
80
+
81
+ def refuse_unpreviewable_rows(klass, key, value)
82
+ name = key.delete_suffix("_attributes").to_sym
83
+ refuse(key) unless previewable_nested?(klass, name)
84
+
85
+ reflection = klass.reflect_on_association(name)
86
+ refuse(key) if sti?(reflection.klass)
87
+ rows = value.respond_to?(:permitted?) ? value.to_h : value
88
+ rows = (rows.key?("id") ? [rows] : rows.values) if reflection.collection? && rows.is_a?(Hash)
89
+ Array.wrap(rows).each { refuse_unpreviewable(reflection.klass, it) if it.is_a?(Hash) || it.respond_to?(:permitted?) }
90
+ end
91
+
92
+ # A row's real class can be a subclass with its own writers, which the association's class doesn't reveal.
93
+ def sti?(klass) = klass.columns_hash.key?(klass.inheritance_column.to_s)
94
+
95
+ # A has_many builds its rows in memory unless the host hooks adding one. A has_one or belongs_to
96
+ # replaces its current record at once, except where `update_only` assigns to it in place. A
97
+ # `reject_if` other than `:all_blank`, or a `limit` given as a proc or method name, is host code that
98
+ # runs on assignment.
99
+ def previewable_nested?(klass, name)
100
+ options = klass.nested_attributes_options[name] or return false
101
+ reflection = klass.reflect_on_association(name) or return false
102
+ return false unless generated_method?(klass, "#{name}_attributes=")
103
+ return false unless [nil, ActiveRecord::NestedAttributes::ClassMethods::REJECT_ALL_BLANK_PROC].include?(options[:reject_if])
104
+
105
+ return options[:update_only] unless reflection.collection?
106
+
107
+ [Proc, Symbol].none? { options[:limit].is_a?(it) } && reflection.options.values_at(:before_add, :after_add).none?
108
+ end
109
+
110
+ # Names the field, never a value.
111
+ def refuse(key) = raise(ApiErrors::BadRequest, "dry_run can't preview #{key}: setting it saves at once or runs code that can't be undone. Send the update without dry_run, or leave it out.")
112
+
113
+ def refuse_unoffered(key) = raise(ApiErrors::BadRequest, "dry_run can't preview #{key}: the form doesn't offer it. Send the update without dry_run, or leave it out.")
114
+
115
+ def read(key) = @record[key].as_json
116
+
117
+ def diff(before, after)
118
+ after.filter_map { |key, to| [key, {from: show(key, before[key]), to: show(key, to)}] if before[key] != to }.to_h
119
+ end
120
+
121
+ def show(key, value)
122
+ return (MASKED if value.present?) if @withheld.include?(key) || Masking.attribute?(key, @config)
123
+
124
+ case value
125
+ when String then (value.size > TEXT_LIMIT) ? "#{value.first(TEXT_LIMIT)}... (#{value.size} characters)" : value
126
+ when Hash, Array then structure(value)
127
+ else value
128
+ end
129
+ end
130
+
131
+ def structure(value)
132
+ ValuePayload.inline?(value, @config) ? value : "[#{value.class.name.downcase}, #{value.to_json.bytesize} bytes]"
133
+ end
134
+
135
+ # Rows of has_many sections: counted, not diffed.
136
+ def nested_changes(keys)
137
+ keys.filter_map do |key|
138
+ name = key.sub(NESTED, "")
139
+ rows = Array.wrap(@record.association(name.to_sym).target)
140
+ counts = {added: rows.count(&:new_record?), removed: rows.count(&:marked_for_destruction?), changed: rows.count { !it.new_record? && !it.marked_for_destruction? && it.changed_for_autosave? }}
141
+ [name, counts] if counts.values.any?(&:positive?)
142
+ rescue ActiveRecord::AssociationNotFoundError
143
+ nil
144
+ end.to_h
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,18 @@
1
+ module ReactiveAdmin
2
+ # The API's `dry_run` flag, taken out of params so AA never sees it. Only an update can honor it; on
3
+ # any other action (a GET custom action and a page action included) ignoring it would run the action
4
+ # for real, so it is refused.
5
+ module DryRunFlag
6
+ private
7
+
8
+ def reactiveadmin_dry_run? = @reactiveadmin_dry_run == true
9
+
10
+ def take_dry_run_param = (@reactiveadmin_dry_run = ActiveModel::Type::Boolean.new.cast(params.delete(:dry_run)) == true)
11
+
12
+ def dry_run_supported? = false
13
+
14
+ def refuse_unsupported_dry_run
15
+ raise ApiErrors::BadRequest, "dry_run is only supported for update" if reactiveadmin_request? && reactiveadmin_dry_run? && !dry_run_supported?
16
+ end
17
+ end
18
+ end