studio-engine 0.137.0 → 0.139.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -0
  3. data/README.md +86 -1
  4. data/app/assets/tailwind/studio_engine/engine.css +235 -0
  5. data/app/controllers/concerns/studio/connection_flow.rb +1 -1
  6. data/app/controllers/sessions_controller.rb +12 -3
  7. data/app/controllers/studio/integrations_controller.rb +43 -0
  8. data/app/controllers/studio/local_reviews_controller.rb +12 -0
  9. data/app/javascript/studio/carousel.js +109 -0
  10. data/app/javascript/studio/controllers/carousel_captions_controller.js +42 -0
  11. data/app/javascript/studio/controllers/carousel_controller.js +243 -1
  12. data/app/javascript/studio/stimulus.js +3 -1
  13. data/app/models/concerns/studio/account.rb +143 -0
  14. data/app/models/concerns/studio/omniauth_user.rb +9 -17
  15. data/app/models/error_log.rb +14 -5
  16. data/app/views/studio/_carousel.html.erb +74 -14
  17. data/app/views/studio/integrations/_card.html.erb +50 -0
  18. data/app/views/studio/integrations/index.html.erb +22 -0
  19. data/app/views/studio/integrations/show.html.erb +24 -0
  20. data/app/views/style/_tricks.html.erb +38 -0
  21. data/config/studio_tricks.yml +7 -0
  22. data/db/migrate/20261006120001_ensure_error_logs_table.rb +3 -1
  23. data/db/migrate/20261006120002_ensure_theme_settings_table.rb +3 -2
  24. data/db/migrate/20261108160000_require_slugs_on_engine_tables.rb +119 -0
  25. data/db/migrate/20261108160001_add_engine_state_checks.rb +94 -0
  26. data/db/migrate/20261108170000_add_users_role_known_check.rb +69 -0
  27. data/lib/generators/studio/connections/connections_generator.rb +10 -0
  28. data/lib/studio/connections.rb +53 -12
  29. data/lib/studio/integrations/egnyte.rb +69 -0
  30. data/lib/studio/integrations/microsoft_365.rb +63 -0
  31. data/lib/studio/integrations/quickbooks.rb +86 -0
  32. data/lib/studio/integrations.rb +265 -0
  33. data/lib/studio/node_tooling/README.md +9 -1
  34. data/lib/studio/node_tooling/e2e_helpers.js +93 -1
  35. data/lib/studio/node_tooling/playwright_base.js +51 -4
  36. data/lib/studio/roles.rb +17 -0
  37. data/lib/studio/version.rb +1 -1
  38. data/lib/studio.rb +59 -1
  39. metadata +16 -2
@@ -1,4 +1,4 @@
1
- <%# locals: (label:, items:, per_view: 3, id: nil, slide_label: nil, data: {}, class_name: nil, style: :standard, caption: nil, start: nil, autoplay: nil, loop: false) %>
1
+ <%# locals: (label:, items:, per_view: 3, id: nil, slide_label: nil, data: {}, class_name: nil, style: :standard, caption: nil, start: nil, autoplay: nil, loop: false, visible: nil, dots: true) %>
2
2
  <%# THE CAROUSEL: one sideways row of slides, the apps' standard for a set too
3
3
  long to grid. Render it as a layout, so each slide is your own block:
4
4
 
@@ -18,18 +18,25 @@
18
18
  slide is "2 of 6".
19
19
  data data attributes for the region, such as a test hook.
20
20
  class_name classes for the region, such as its width.
21
- style :standard (slides snap to the start) or :spotlight (the
21
+ style :standard (slides snap to the start), :spotlight (the
22
22
  centred slide is full size and colour, its neighbours smaller,
23
- faded and grey, and the arrows and keys move one slide).
23
+ faded and grey, and the arrows and keys move one slide), or
24
+ :cascade (a 3D stack: the open slide in front at full size,
25
+ the slides either side stepping back behind it, each step
26
+ smaller and dimmer; see THE CASCADE below).
27
+ visible a cascade's slides in view: 5 (the default: the open slide and
28
+ two each side) or 3. A region under 36rem wide shows 3 whatever
29
+ it asks. Only a cascade takes it.
24
30
  caption a callable that writes a line under a slide from its item. A
25
31
  standard row shows a small line under every slide; the
26
- spotlight shows it under the centred slide only.
32
+ spotlight and the cascade show it under the open slide only.
27
33
  start the slide the row opens on: an index from 0, or :middle (the
28
34
  slide at items.size / 2). Defaults to :middle for a spotlight
29
35
  that does not loop, so both halves of the row hold a slide at
30
36
  load, and to 0 for a standard row and for a looping spotlight
31
37
  (its wrap already shows the last slide left of the first, so it
32
- opens on the host's first item). An explicit start: wins. The browser sets it before the first paint where
38
+ opens on the host's first item). A cascade takes the spotlight's
39
+ defaults. An explicit start: wins. The browser sets it before the first paint where
33
40
  it has scroll-initial-target; elsewhere the controller sets it
34
41
  when it connects, with no glide and nothing announced. A link
35
42
  to an id inside the row (#fragment) wins over the start.
@@ -44,6 +51,9 @@
44
51
  so a screen reader and Tab meet each slide once, a #fragment
45
52
  finds the real slide, and the dots and "slide N of M" count the
46
53
  real slides. Every slide of a looping row is a stop.
54
+ dots true (the default) draws a dot per slide under the row; false
55
+ draws none, so the row has no dot group in the tab order or the
56
+ accessibility tree. The arrows, keys, swipe and status line stay.
47
57
  autoplay seconds between moves (a number above 0); nil, the default, is
48
58
  off. The row moves one slide each interval and holds still while
49
59
  the pointer is over the slides, while keyboard focus is in it,
@@ -60,6 +70,29 @@
60
70
  transitions it. Under reduced motion nothing scales: the neighbours are only
61
71
  dimmed.
62
72
 
73
+ THE CASCADE (engine.css, carousel-cascade) does not scroll. Its slides share
74
+ one grid cell, and each wears data-cascade-step, its place from the open slide:
75
+ -2 to 2 in view, "before" and "after" past the window. The partial writes the
76
+ steps of the first paint and the controller rewrites them on a move, so CSS
77
+ lays the stack out (perspective, translateZ, a slight turn toward the centre)
78
+ and transitions it. An arrow, a dot, a key, a swipe or drag, autoplay, a click
79
+ on a side slide and keyboard focus in one bring that slide to the front; a
80
+ click on a side slide opens nothing. Tab skips the slides past the window (they
81
+ are hidden): it lands on the first slide in view and moves one on each press.
82
+ A cascade that does not loop and opens mid-row has slides before the window
83
+ that forward Tab never reaches; Shift+Tab from the first slide in view, Home,
84
+ the arrow keys, Previous and the dots do. A looping cascade needs no clones: the
85
+ steps wrap round the set, so the window is never wider than the set. A narrow
86
+ region fades its side slides at the track's edge. Under reduced motion it lays
87
+ flat, as a spotlight does, and swaps with no glide. If its controller fails it
88
+ falls back to a plain scrolling row.
89
+
90
+ THE CHANGE EVENT. Every style dispatches "studio:carousel:change" from the
91
+ region, bubbling, once each time the open slide changes, after data-current
92
+ has moved: detail { index, previous, slide, total }. A host that follows the
93
+ open slide listens for it. One caption under the row needs no script: the
94
+ carousel-captions controller follows it (README, the image-only pattern).
95
+
63
96
  THE TRACK IS A NATIVE SCROLL-SNAP ROW (engine.css, carousel). A swipe, a
64
97
  trackpad, a wheel and a focused link move it with no script. The carousel
65
98
  controller (studio/controllers/carousel_controller) adds the edge fade, the
@@ -80,16 +113,25 @@
80
113
  per_view = per_view.to_i if per_view == per_view.floor
81
114
  items = items.to_a
82
115
  total = items.size
83
- spotlight = case style.to_s
84
- when "standard" then false
85
- when "spotlight" then true
86
- else raise ArgumentError, "studio/carousel style: #{style.inspect} is not :standard or :spotlight"
87
- end
116
+ style_name = style.to_s
117
+ unless %w[standard spotlight cascade].include?(style_name)
118
+ raise ArgumentError, "studio/carousel style: #{style.inspect} is not :standard, :spotlight or :cascade"
119
+ end
120
+ spotlight = style_name == "spotlight"
121
+ cascade = style_name == "cascade"
122
+ # The spotlight and the cascade both centre one slide: they share its defaults.
123
+ centred = spotlight || cascade
124
+ if cascade
125
+ visible = 5 if visible.nil?
126
+ raise ArgumentError, "studio/carousel visible: #{visible.inspect} is not 3 or 5" unless [3, 5].include?(visible)
127
+ elsif !visible.nil?
128
+ raise ArgumentError, "studio/carousel visible: only a style: :cascade row takes it"
129
+ end
88
130
  loop = loop ? true : false
89
131
  wraps = loop && total > 1
90
132
  # A looping spotlight has a left neighbour at its first slide (the clones), so it
91
133
  # opens there; one that does not loop opens mid-row so neither half is empty.
92
- start = spotlight && !wraps ? :middle : 0 if start.nil?
134
+ start = centred && !wraps ? :middle : 0 if start.nil?
93
135
  start_index = case start
94
136
  when :middle, "middle" then total / 2
95
137
  when Integer then start.clamp(0, [total - 1, 0].max)
@@ -100,26 +142,43 @@
100
142
  raise ArgumentError, "studio/carousel autoplay: #{autoplay.inspect} is not a number of seconds above 0 or nil"
101
143
  end
102
144
  autoplay = autoplay.to_i if autoplay && autoplay == autoplay.floor
103
- arrow_noun = spotlight ? "slide" : "slides"
145
+ arrow_noun = centred ? "slide" : "slides"
146
+ # A cascade slide's place from the open slide (studio/carousel's cascadeStep and
147
+ # cascadeSlot): signed, the short way round a looping set, the later side on a tie.
148
+ cascade_slot = lambda do |index|
149
+ step = index - start_index
150
+ if wraps
151
+ step %= total
152
+ step -= total if step > total / 2.0
153
+ end
154
+ step < -2 ? "before" : step > 2 ? "after" : step.to_s
155
+ end
104
156
  track_id = id.presence || "carousel-#{label.to_s.parameterize.presence || 'slides'}"
105
157
  %>
106
- <%= tag.section(class: ["carousel", ("carousel-spotlight" if spotlight), class_name].compact.join(" "),
158
+ <%= tag.section(class: ["carousel", ("carousel-spotlight" if spotlight), ("carousel-cascade" if cascade), class_name].compact.join(" "),
107
159
  role: "region",
108
160
  aria: { roledescription: "carousel", label: label },
109
161
  style: "--carousel-per-view: #{per_view}",
110
162
  data: { studio_controller: "carousel", studio_action: "keydown->carousel#key", carousel_start: (start_index.to_s if start_index.positive?),
111
- carousel_autoplay: (autoplay.to_s if autoplay), carousel_loop: ("" if loop) }.compact.merge(data)) do %>
163
+ carousel_autoplay: (autoplay.to_s if autoplay), carousel_loop: ("" if loop), carousel_visible: (visible.to_s if cascade) }.compact.merge(data)) do %>
112
164
  <%# The track takes focus for the keys, so it carries a name: a group, since a
113
165
  bare div may not be named. %>
114
166
  <div id="<%= track_id %>" class="carousel-track" tabindex="0" role="group"
115
167
  aria-label="<%= label %> slides" data-carousel-target="track">
116
168
  <% items.each_with_index do |item, index| %>
169
+ <% if cascade %>
170
+ <div class="carousel-slide" role="group" aria-roledescription="slide"
171
+ aria-label="<%= slide_label ? slide_label.call(item) : "#{index + 1} of #{total}" %>"
172
+ data-carousel-target="slide" data-cascade-step="<%= cascade_slot.call(index) %>"<%= ' data-current'.html_safe if index == start_index %>><div class="carousel-cascade-body"><%= yield(item) %></div><% if caption %><div class="carousel-caption"><%= caption.call(item) %></div><% end %></div>
173
+ <% next %>
174
+ <% end %>
117
175
  <div class="carousel-slide" role="group" aria-roledescription="slide"
118
176
  aria-label="<%= slide_label ? slide_label.call(item) : "#{index + 1} of #{total}" %>"
119
177
  data-carousel-target="slide"<%= ' data-carousel-start-slide'.html_safe if start_index.positive? && index == start_index %><%= ' data-current'.html_safe if spotlight && index == start_index %>><% if spotlight %><div class="carousel-spotlight-body"><%= yield(item) %></div><% else %><%= yield(item) %><% end %><% if caption %><div class="carousel-caption"><%= caption.call(item) %></div><% end %></div>
120
178
  <% end %>
121
179
  </div>
122
180
  <div class="carousel-controls">
181
+ <% if dots %>
123
182
  <div class="carousel-dots" role="group" aria-label="Choose a slide">
124
183
  <% total.times do |index| %>
125
184
  <button type="button" class="carousel-dot" aria-label="Go to slide <%= index + 1 %>"
@@ -128,6 +187,7 @@
128
187
  data-studio-action="click->carousel#goTo"></button>
129
188
  <% end %>
130
189
  </div>
190
+ <% end %>
131
191
  <div class="carousel-arrows">
132
192
  <% if autoplay %>
133
193
  <%# The pause button (WCAG 2.2.2). The controller renames it "Play slideshow"
@@ -0,0 +1,50 @@
1
+ <%# locals: (integration:, connections:, return_to:, linked:) %>
2
+ <%# One integration's card: status, what keeps it off, Connect (a POST, with
3
+ the account field when the admin names the account at Connect), and its
4
+ connections with Disconnect. No token, and no part of one, is shown. %>
5
+ <% provider = integration.provider %>
6
+ <% status = integration.status %>
7
+ <section class="card p-4" data-studio-integration-card="<%= integration.key %>" data-status="<%= status %>">
8
+ <div class="flex flex-wrap items-center justify-between gap-2">
9
+ <h2 class="text-heading font-semibold">
10
+ <% if linked %><a href="<%= integration_path_for(integration) %>" class="hover:underline"><%= integration.label %></a><% else %><%= integration.label %><% end %>
11
+ </h2>
12
+ <span class="badge" data-studio-integration-status><%= integration.status_label %></span>
13
+ </div>
14
+ <p class="text-sm text-secondary mt-1"><%= integration.summary %></p>
15
+
16
+ <% integration.missing.each do |reason| %>
17
+ <p class="text-sm text-muted mt-2" data-studio-integration-missing><%= reason %></p>
18
+ <% end %>
19
+
20
+ <% if connections.any? %>
21
+ <ul class="mt-3 divide-y divide-subtle" data-studio-integration-connections>
22
+ <% connections.each do |connection| %>
23
+ <li class="py-2 flex flex-wrap items-center justify-between gap-2" data-studio-integration-connection="<%= connection.id %>">
24
+ <div>
25
+ <p class="text-sm text-heading font-medium"><%= connection.label %></p>
26
+ <p class="text-xs text-muted">
27
+ Connected <%= connection.connected_at.utc.strftime("%Y-%m-%d %H:%M UTC") %><% if connection.connected_by.present? %> by <%= connection.connected_by %><% end %><% if connection.metadata.to_h["environment"].present? %> · <%= connection.metadata["environment"] %><% end %>
28
+ </p>
29
+ </div>
30
+ <%= button_to "Disconnect", integration_disconnect_path(integration, connection), method: :delete,
31
+ params: { return_to: }, class: "btn btn-outline btn-sm",
32
+ form: { data: { turbo_confirm: "Disconnect #{connection.label}?" } } %>
33
+ </li>
34
+ <% end %>
35
+ </ul>
36
+ <% end %>
37
+
38
+ <%= form_with url: integration_connect_path(integration), method: :post, local: true,
39
+ class: "mt-3 flex flex-wrap items-end gap-2", data: { studio_integration_connect: integration.key, turbo: false } do |form| %>
40
+ <%= hidden_field_tag :return_to, return_to %>
41
+ <% if provider.account_source == :connect %>
42
+ <label class="text-sm text-secondary">
43
+ <span class="block mb-1"><%= integration.definition.account_label %></span>
44
+ <%= text_field_tag provider.account_param, nil, class: "input-field py-2", required: true, autocomplete: "off",
45
+ placeholder: integration.definition.account_hint %>
46
+ </label>
47
+ <% end %>
48
+ <%= form.submit(connections.any? ? "Connect another" : "Connect", class: "btn btn-primary btn-sm") %>
49
+ <% end %>
50
+ </section>
@@ -0,0 +1,22 @@
1
+ <%# /admin/integrations: every integration the host enabled
2
+ (Studio.enable_integration), with its status and Connect
3
+ (Studio::IntegrationsController#index). %>
4
+ <% content_for(:title, "Integrations") %>
5
+ <div class="max-w-4xl mx-auto px-4 py-6" data-studio-integrations>
6
+ <%= render "studio/page_header", title: "Integrations" %>
7
+ <p class="text-sm text-secondary mt-1 mb-6">Connect an account once. Each integration's page shows its connections and what this app reads.</p>
8
+
9
+ <% if @integrations.empty? %>
10
+ <div class="empty-state">
11
+ <p class="text-heading font-semibold mb-1">No integrations enabled</p>
12
+ <p class="text-sm text-muted">Enable one with <code>Studio.enable_integration</code>; see the engine's docs/INTEGRATIONS.md.</p>
13
+ </div>
14
+ <% else %>
15
+ <div class="grid gap-4">
16
+ <% @integrations.each do |integration| %>
17
+ <%= render "studio/integrations/card", integration:, connections: integration.connections,
18
+ return_to: integrations_index_path, linked: true %>
19
+ <% end %>
20
+ </div>
21
+ <% end %>
22
+ </div>
@@ -0,0 +1,24 @@
1
+ <%# /admin/integrations/<key>: one enabled integration, its connections and
2
+ Disconnect, the redirect URI to register, and the host's own panel
3
+ (Studio.enable_integration panel:), rendered with locals integration: and
4
+ connections: (Studio::IntegrationsController#show). %>
5
+ <% content_for(:title, @integration.label) %>
6
+ <div class="max-w-4xl mx-auto px-4 py-6" data-studio-integration="<%= @integration.key %>">
7
+ <%= render "studio/page_header", title: @integration.label %>
8
+ <p class="text-sm mt-1 mb-6"><a href="<%= integrations_index_path %>" class="text-secondary hover:underline">All integrations</a></p>
9
+
10
+ <%= render "studio/integrations/card", integration: @integration, connections: @connections,
11
+ return_to: integration_path_for(@integration), linked: false %>
12
+
13
+ <div class="card p-4 mt-4" data-studio-integration-redirect>
14
+ <p class="label-upper mb-1">Redirect URI</p>
15
+ <p class="text-sm text-secondary mb-2">Register this exact URL on the <%= @integration.label %> app as its redirect (callback) URI.</p>
16
+ <code class="text-sm break-all"><%= integration_callback_url(@integration) %></code>
17
+ </div>
18
+
19
+ <% if @integration.panel %>
20
+ <div class="mt-6" data-studio-integration-panel>
21
+ <%= render partial: @integration.panel, locals: { integration: @integration, connections: @connections } %>
22
+ </div>
23
+ <% end %>
24
+ </div>
@@ -267,6 +267,44 @@
267
267
  <% end %>
268
268
  </div>
269
269
  <% end %>
270
+
271
+ <%# The cascade: a 3D stack, five in view (visible: 3 shows one each side, and so
272
+ does a region under 36rem). Click a side card, drag, or use the arrow keys. %>
273
+ <%= render layout: "style/specimen", locals: { trick: "cascade" } do %>
274
+ <div class="w-full min-w-0" data-carousel-cascade-specimen>
275
+ <%= render layout: "studio/carousel",
276
+ locals: { label: "Cascade specimen", items: (1..7).to_a, style: :cascade, loop: true,
277
+ id: "style-carousel-cascade-specimen", caption: ->(n) { "Slide #{n}" } } do |n| %>
278
+ <div class="card h-full p-5 space-y-1 aspect-[4/3]" style="background-image: linear-gradient(150deg, rgb(var(--color-primary-rgb) / 0.35), transparent)">
279
+ <p class="label-upper">Slide <%= n %></p>
280
+ <p class="text-sm text-body">Any block content.</p>
281
+ </div>
282
+ <% end %>
283
+ </div>
284
+
285
+ <%# The image-only pattern (README, The carousel): each card is only its picture,
286
+ the open card wears a ring, the row draws no dots, and one caption under the
287
+ stack follows the open card (the carousel-captions controller, on
288
+ studio:carousel:change). %>
289
+ <div class="w-full min-w-0" data-studio-controller="carousel-captions" data-carousel-image-only-specimen>
290
+ <%= render layout: "studio/carousel",
291
+ locals: { label: "Image-only specimen", items: (1..5).to_a, style: :cascade, loop: true, dots: false,
292
+ id: "style-carousel-image-only-specimen", slide_label: ->(n) { "Picture #{n}" } } do |n| %>
293
+ <div role="img" aria-label="Picture <%= n %>"
294
+ class="aspect-[4/3] overflow-hidden rounded-2xl transition-shadow duration-300 in-data-current:ring-2 in-data-current:ring-primary"
295
+ style="background-image: linear-gradient(<%= 120 + n * 30 %>deg, rgb(var(--color-primary-rgb) / <%= 0.25 + n * 0.12 %>), rgb(var(--color-primary-rgb) / 0.08))"></div>
296
+ <% end %>
297
+ <div class="grid pt-3 text-center">
298
+ <% (1..5).each do |n| %>
299
+ <div class="col-start-1 row-start-1 opacity-0 invisible transition-opacity duration-200 data-current:opacity-100 data-current:visible"
300
+ data-carousel-captions-target="caption"<%= " data-current".html_safe if n == 1 %><%= ' aria-hidden="true"'.html_safe unless n == 1 %>>
301
+ <p class="text-sm font-semibold text-heading">Picture <%= n %></p>
302
+ <p class="text-xs text-secondary">One caption under the stack.</p>
303
+ </div>
304
+ <% end %>
305
+ </div>
306
+ </div>
307
+ <% end %>
270
308
  </section>
271
309
 
272
310
  <!-- Surfaces, text and form -->
@@ -160,6 +160,13 @@ spotlight:
160
160
  note: "Centres one slide with its caption; its neighbours shrink and fade."
161
161
  resolve: [partial:studio/carousel, css:carousel-spotlight]
162
162
 
163
+ cascade:
164
+ name: Cascade Carousel
165
+ group: Carousel
166
+ token: "render layout: \"studio/carousel\", style: :cascade"
167
+ note: "A 3D stack: the open slide in front, the others stepping back either side."
168
+ resolve: [partial:studio/carousel, css:carousel-cascade]
169
+
163
170
  card:
164
171
  name: Card
165
172
  group: "Surfaces, text & form"
@@ -14,7 +14,9 @@
14
14
  # fail on existing rows or lock a large table.
15
15
  #
16
16
  # On every consumer that existed when this shipped, the second branch adds
17
- # nothing. Studio::HostSchema checks the same columns at boot.
17
+ # nothing. Studio::HostSchema checks the same columns at boot. The slug
18
+ # standard (NOT NULL, unique) is the later RequireSlugsOnEngineTables
19
+ # (20261108160000), which tightens the column on every host.
18
20
  class EnsureErrorLogsTable < ActiveRecord::Migration[7.2]
19
21
  def up
20
22
  unless table_exists?(:error_logs)
@@ -5,8 +5,9 @@
5
5
  # Sluggable, whose before_save writes `slug` on every save, and the setup doc's
6
6
  # hand-copied migration omitted it, so a theme save raises on any host built
7
7
  # from that doc (cyvasse, mcritchie-industries and moms-app when this shipped).
8
- # The slug is "theme-<app_name>", derived on save; existing rows keep a NULL
9
- # slug until their next save, and nothing looks a theme up by slug.
8
+ # The slug is "theme-<app_name>", derived on save. Rows this left with a NULL
9
+ # slug are filled, and the column made NOT NULL and unique, by the later
10
+ # RequireSlugsOnEngineTables (20261108160000).
10
11
  #
11
12
  # A baseline, not a rebuild:
12
13
  #
@@ -0,0 +1,119 @@
1
+ # The engine's own settings and log tables take the hub's slug standard:
2
+ # `slug` NOT NULL with a unique index, on error_logs, theme_settings,
3
+ # studio_geo_settings and studio_site_identities (database audit 2026-11-07,
4
+ # finding 6). Every host inherits the tables, so one migration reaches them all.
5
+ #
6
+ # Each table goes through three steps, and a table the host does not have is
7
+ # skipped (its own create migration runs first whenever it is installed, since
8
+ # install:migrations copies the engine's migrations in order):
9
+ #
10
+ # 1. Backfill. A NULL or blank slug gets the one its model would write
11
+ # (Sluggable's `name_slug`): `error-log-<id>`, `theme-<app_name>`,
12
+ # `geo-<app_name>`, `site-identity-<app_name>`, with the app name
13
+ # parameterized. A slug another row already holds takes `-<id>` after it.
14
+ # 2. Duplicates. A table without a unique slug index (turf-monster's
15
+ # error_logs) may hold a slug twice; every copy after the lowest id takes
16
+ # `-<id>` after it. No table here has slug children, so nothing else
17
+ # references the old value.
18
+ # 3. NOT NULL, then the unique index on `slug` unless one is there. A
19
+ # non-unique slug index is replaced by the unique one.
20
+ #
21
+ # Production on 2026-11-08 (every app with a database, read-only counts): no
22
+ # NULL or blank slug, no duplicate, so steps 1 and 2 change no row there. The
23
+ # largest table is the hub's error_logs at 606 rows, so the NOT NULL scan and
24
+ # the index build are short. On Postgres each ALTER waits at most LOCK_TIMEOUT
25
+ # for its lock; a migrate that cannot get it fails whole, changes nothing, and
26
+ # runs again on the next release.
27
+ class RequireSlugsOnEngineTables < ActiveRecord::Migration[7.2]
28
+ LOCK_TIMEOUT = "10s"
29
+
30
+ # table => the slug prefix its model's name_slug writes before the app name.
31
+ # error_logs has no app name: its slug is the id.
32
+ NAMED = {
33
+ "theme_settings" => "theme",
34
+ "studio_geo_settings" => "geo",
35
+ "studio_site_identities" => "site-identity"
36
+ }.freeze
37
+ TABLES = (["error_logs"] + NAMED.keys).freeze
38
+
39
+ def up
40
+ set_lock_timeout
41
+ TABLES.each do |table|
42
+ next unless table_exists?(table) && column_exists?(table, :slug)
43
+
44
+ backfill(table)
45
+ dedupe(table)
46
+ change_column_null table, :slug, false
47
+ unique_slug_index(table)
48
+ end
49
+ end
50
+
51
+ # Only the NOT NULL is undone. The unique index stays: most hosts had it before
52
+ # this migration, and a down cannot tell which index it added. Backfilled slugs
53
+ # stay too; a slug is a valid value either way.
54
+ def down
55
+ TABLES.each do |table|
56
+ next unless table_exists?(table) && column_exists?(table, :slug)
57
+
58
+ change_column_null table, :slug, true
59
+ end
60
+ end
61
+
62
+ private
63
+
64
+ def set_lock_timeout
65
+ return unless connection.adapter_name.downcase.include?("postgres")
66
+
67
+ execute "SET LOCAL lock_timeout = '#{LOCK_TIMEOUT}'"
68
+ end
69
+
70
+ def quoted(table) = connection.quote_table_name(table)
71
+
72
+ def backfill(table)
73
+ rows = connection.select_rows(<<~SQL.squish)
74
+ SELECT id#{', app_name' if NAMED.key?(table)} FROM #{quoted(table)}
75
+ WHERE slug IS NULL OR slug = '' ORDER BY id
76
+ SQL
77
+ rows.each do |id, app_name|
78
+ derived = derived_slug(table, id, app_name)
79
+ derived = "#{derived}-#{id}" if taken?(table, derived, id)
80
+ write_slug(table, id, derived)
81
+ end
82
+ end
83
+
84
+ def derived_slug(table, id, app_name)
85
+ return "error-log-#{id}" unless NAMED.key?(table)
86
+
87
+ name = ActiveSupport::Inflector.parameterize(app_name.to_s)
88
+ name.empty? ? "#{NAMED.fetch(table)}-#{id}" : "#{NAMED.fetch(table)}-#{name}"
89
+ end
90
+
91
+ def dedupe(table)
92
+ duplicates = connection.select_rows(<<~SQL.squish)
93
+ SELECT id, slug FROM #{quoted(table)} later
94
+ WHERE EXISTS (SELECT 1 FROM #{quoted(table)} earlier WHERE earlier.slug = later.slug AND earlier.id < later.id)
95
+ ORDER BY id
96
+ SQL
97
+ duplicates.each { |id, slug| write_slug(table, id, "#{slug}-#{id}") }
98
+ end
99
+
100
+ def taken?(table, slug, id)
101
+ connection.select_value(<<~SQL.squish).present?
102
+ SELECT 1 FROM #{quoted(table)} WHERE slug = #{connection.quote(slug)} AND id <> #{Integer(id)} LIMIT 1
103
+ SQL
104
+ end
105
+
106
+ def write_slug(table, id, slug)
107
+ connection.update(<<~SQL.squish, "#{self.class.name} backfill")
108
+ UPDATE #{quoted(table)} SET slug = #{connection.quote(slug)} WHERE id = #{Integer(id)}
109
+ SQL
110
+ end
111
+
112
+ def unique_slug_index(table)
113
+ slug_indexes = connection.indexes(table).select { |index| Array(index.columns) == ["slug"] }
114
+ return if slug_indexes.any?(&:unique)
115
+
116
+ slug_indexes.each { |index| remove_index table, name: index.name }
117
+ add_index table, :slug, unique: true
118
+ end
119
+ end
@@ -0,0 +1,94 @@
1
+ # The engine's two state columns take the hub's state standard: a CHECK named
2
+ # `<table>_<column>_known` holding the list the model validates against, so a
3
+ # write that skips validations (update_columns, update_all, insert_all, raw SQL)
4
+ # is refused by the database (database audit 2026-11-07, finding 6).
5
+ #
6
+ # studio_links.kind Studio::LinkToken::KINDS (Studio::Link validates it)
7
+ # studio_knowledge_docs.status Studio::KnowledgeDoc::STATUSES
8
+ #
9
+ # The lists below are this migration's own frozen copy. A new value needs a new
10
+ # migration: test/integration/engine_state_checks_test.rb fails while a model's
11
+ # list and this copy differ.
12
+ #
13
+ # A host without the table is skipped, and a constraint already there is left
14
+ # alone, so a second run changes nothing. Both columns are NOT NULL already.
15
+ #
16
+ # A row outside its list stops the migration before any change, with the table,
17
+ # the column and the stray values in the message: the constraint is validated,
18
+ # so it cannot go on over such a row. Production on 2026-11-08 held none (every
19
+ # app with a database, read-only counts): studio_links holds magic_link and
20
+ # referral, studio_knowledge_docs holds filed and superseded (industries alone).
21
+ # The validating scan is short (the largest table is 366 rows). On Postgres the
22
+ # ALTER waits at most LOCK_TIMEOUT for its lock; a migrate that cannot get it
23
+ # fails whole and runs again on the next release.
24
+ class AddEngineStateChecks < ActiveRecord::Migration[7.2]
25
+ LOCK_TIMEOUT = "10s"
26
+
27
+ CHECKS = {
28
+ "studio_links.kind" => %w[magic_link referral],
29
+ "studio_knowledge_docs.status" => %w[inbox filed superseded]
30
+ }.freeze
31
+
32
+ # The constraint's name: `<table>_<column>_known`, as the hub names its own.
33
+ def self.constraint_name(key) = key.tr(".", "_") + "_known"
34
+
35
+ def up
36
+ set_lock_timeout
37
+ CHECKS.each do |key, values|
38
+ table, column = key.split(".")
39
+ next unless table_exists?(table)
40
+ next if check_constraint_exists?(table, name: self.class.constraint_name(key))
41
+
42
+ refuse_strays!(table, column, values)
43
+ add_check_constraint table, expression(column, values), name: self.class.constraint_name(key)
44
+ end
45
+ end
46
+
47
+ def down
48
+ CHECKS.each_key do |key|
49
+ table, = key.split(".")
50
+ next unless table_exists?(table)
51
+
52
+ remove_check_constraint table, name: self.class.constraint_name(key), if_exists: true
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def set_lock_timeout
59
+ return unless postgres?
60
+
61
+ execute "SET LOCAL lock_timeout = '#{LOCK_TIMEOUT}'"
62
+ end
63
+
64
+ def list(values) = values.map { |value| connection.quote(value) }.join(", ")
65
+
66
+ # On Postgres, the spelling Postgres itself settles on once a schema.rb is
67
+ # loaded (`'x'::character varying::text`), so a host's schema dump after this
68
+ # migrate equals the dump after a load, byte for byte. An `IN (...)` list
69
+ # dumps as `ARRAY[...]::text[]` first and changes on the next load. Anywhere
70
+ # else (the engine's SQLite test host), the plain IN list.
71
+ def expression(column, values)
72
+ col = connection.quote_column_name(column)
73
+ return "#{col} IN (#{list(values)})" unless postgres?
74
+
75
+ array = values.map { |value| "#{connection.quote(value)}::character varying::text" }.join(", ")
76
+ "(#{col})::text = ANY (ARRAY[#{array}])"
77
+ end
78
+
79
+ def postgres? = connection.adapter_name.downcase.include?("postgres")
80
+
81
+ def refuse_strays!(table, column, values)
82
+ col = connection.quote_column_name(column)
83
+ strays = connection.select_rows(<<~SQL.squish)
84
+ SELECT #{col}, COUNT(*) FROM #{connection.quote_table_name(table)}
85
+ WHERE #{col} IS NOT NULL AND #{col} NOT IN (#{list(values)}) GROUP BY #{col} ORDER BY #{col}
86
+ SQL
87
+ return if strays.empty?
88
+
89
+ found = strays.map { |value, count| "#{value.inspect} (#{count})" }.join(", ")
90
+ raise ActiveRecord::MigrationError,
91
+ "#{table}.#{column} holds values outside #{values.inspect}: #{found}. " \
92
+ "Resolve those rows, then migrate again."
93
+ end
94
+ end
@@ -0,0 +1,69 @@
1
+ # CHECK users_role_known on the host's `users.role` (database audit 2026-11-07,
2
+ # section 3): the database half of Studio::Account's role validation, so a
3
+ # mistyped role is refused rather than saved as a quiet non-admin.
4
+ #
5
+ # THIS IS A MIGRATION AGAINST A HOST TABLE, shipped like the standard profile
6
+ # columns (20260813220000): install-copied with
7
+ # `bin/rails studio_engine:install:migrations`, never auto-run, and safe on an
8
+ # app that already disagrees.
9
+ #
10
+ # * No `users` table, no `role` column, or a role that is not a string (an
11
+ # integer enum): skipped.
12
+ # * A CHECK named users_role_known already there: skipped. The hub and Turf
13
+ # installed their own on 2026-11-08, narrowed to viewer + admin, and a host's
14
+ # narrower CHECK is the stronger guard; this one is the ceiling.
15
+ # * A row holding a role outside the list: REFUSED, naming the values, with
16
+ # nothing written. A stray role is a product call (Turf's "user" meant
17
+ # viewer); this migration does not guess it.
18
+ #
19
+ # Then it fills a NULL role with "viewer", sets NOT NULL, and adds the CHECK.
20
+ #
21
+ # The list is SPELLED OUT, not read from Studio::Roles: a migration is a record
22
+ # that must still run years from now, and a live constant may move. Widening the
23
+ # engine's list is a new migration that replaces this CHECK.
24
+ class AddUsersRoleKnownCheck < ActiveRecord::Migration[7.2]
25
+ ROLES = %w[viewer member admin].freeze
26
+ NAME = "users_role_known"
27
+
28
+ def up
29
+ return unless string_role?
30
+ return if check_constraint_exists?(:users, name: NAME)
31
+
32
+ allowed = ROLES.map { |role| connection.quote(role) }.join(", ")
33
+ unknown = select_values("SELECT DISTINCT role FROM users WHERE role IS NOT NULL AND role NOT IN (#{allowed})")
34
+ if unknown.any?
35
+ raise ActiveRecord::MigrationError, <<~MSG
36
+ AddUsersRoleKnownCheck refused: users.role holds #{unknown.sort.map(&:inspect).join(', ')},
37
+ outside Studio::Roles (#{ROLES.join(', ')}). Move those rows to a known role in a
38
+ migration of this app's own (Turf moved "user" to "viewer"), then run this again.
39
+ MSG
40
+ end
41
+
42
+ execute "UPDATE users SET role = 'viewer' WHERE role IS NULL"
43
+ change_column_null :users, :role, false
44
+ add_check_constraint :users, "role IN (#{allowed})", name: NAME
45
+ end
46
+
47
+ # Removes the CHECK only when it is this migration's: one that names every
48
+ # engine role. A host's own users_role_known, which `up` left in place, is
49
+ # narrower (the hub's and Turf's name viewer and admin only) and stays. NOT
50
+ # NULL stays too: `up` cannot record whether the host had it already, and a
51
+ # NULL role is the one value no host wants back.
52
+ def down
53
+ return unless string_role?
54
+
55
+ ours = check_constraints(:users).find { |check| check.name == NAME }
56
+ return unless ours && ROLES.all? { |role| ours.expression.include?("'#{role}'") }
57
+
58
+ remove_check_constraint :users, name: NAME
59
+ end
60
+
61
+ private
62
+
63
+ def string_role?
64
+ return false unless table_exists?(:users)
65
+
66
+ column = columns(:users).find { |c| c.name == "role" }
67
+ column && %i[string text].include?(column.type)
68
+ end
69
+ end