@bygghammar/cms-platform 0.90.0-m7.1 → 0.90.0-m7.11

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 (69) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +16 -2
  3. package/docs/EDIT-LOCKS.md +213 -0
  4. package/migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql +274 -0
  5. package/package.json +11 -3
  6. package/scripts/create-cms-site.mjs +5 -4
  7. package/scripts/sync-migrations.mjs +27 -6
  8. package/src/backoffice/ContactDetailsView.tsx +19 -5
  9. package/src/backoffice/DomainsView.tsx +152 -25
  10. package/src/backoffice/EditLock.tsx +513 -0
  11. package/src/backoffice/EmailSettingsView.tsx +99 -0
  12. package/src/backoffice/FormEditorView.tsx +531 -512
  13. package/src/backoffice/FormSettingsView.tsx +16 -4
  14. package/src/backoffice/GlobalSectionBuilderView.tsx +42 -11
  15. package/src/backoffice/NavigationView.tsx +35 -11
  16. package/src/backoffice/PageBuilderView.tsx +108 -38
  17. package/src/backoffice/RichTextEditor.tsx +50 -14
  18. package/src/backoffice/SectionEditorView.tsx +18 -6
  19. package/src/backoffice/SectionFormView.tsx +184 -31
  20. package/src/backoffice/TrackingView.tsx +247 -208
  21. package/src/backoffice/forms/VersionHistory.tsx +4 -2
  22. package/src/backoffice/inspectors/blocks.tsx +22 -1
  23. package/src/backoffice/inspectors/fields.tsx +21 -0
  24. package/src/backoffice/routes/host.ts +36 -0
  25. package/src/backoffice/routes/index.tsx +117 -15
  26. package/src/backoffice/routes/pages.tsx +10 -6
  27. package/src/backoffice/seo/PageSeoPanelView.tsx +215 -197
  28. package/src/backoffice/shell/domain-guard.ts +27 -14
  29. package/src/backoffice/shell/index.ts +5 -0
  30. package/src/backoffice/shell/use-resolved-config.tsx +67 -0
  31. package/src/backoffice/tracking-drafts.ts +150 -0
  32. package/src/blocks/components/CtaBannerBlock.tsx +18 -12
  33. package/src/blocks/components/HeroFullBlock.tsx +25 -12
  34. package/src/blocks/components/MediaSplitBlock.tsx +91 -41
  35. package/src/blocks/components/PriceTableBlock.tsx +123 -89
  36. package/src/blocks/components/RichTextBlock.tsx +26 -4
  37. package/src/blocks/index.ts +8 -0
  38. package/src/blocks/optional-content.ts +82 -0
  39. package/src/blocks/registry.tsx +1 -0
  40. package/src/blocks/types.ts +6 -0
  41. package/src/cms/edit-lock.ts +491 -0
  42. package/src/config/modules.ts +34 -10
  43. package/src/forms/FormRenderer.tsx +22 -0
  44. package/src/host/index.tsx +17 -0
  45. package/src/navigation/index.ts +29 -0
  46. package/src/popups/admin.tsx +55 -4
  47. package/src/popups/cms-bridges.ts +50 -10
  48. package/src/popups/destinations.tsx +7 -1
  49. package/src/popups/host.ts +9 -0
  50. package/src/popups/runtime.tsx +48 -14
  51. package/src/runtime/server-entry.ts +8 -2
  52. package/src/server/content-sections-core.ts +22 -5
  53. package/src/server/domains-core.ts +124 -107
  54. package/src/server/edit-lock-adapter.ts +91 -0
  55. package/src/server/edit-lock-supabase-adapter.ts +135 -0
  56. package/src/server/edit-locks-core.ts +286 -0
  57. package/src/server/forms-core.ts +37 -2
  58. package/src/server/injections-core.ts +230 -49
  59. package/src/server/page-seo-save-core.ts +27 -0
  60. package/src/server/pages-core.ts +108 -11
  61. package/src/server/provider-secrets.ts +100 -4
  62. package/src/server/schemas.ts +74 -9
  63. package/src/site/SiteHeader.tsx +11 -5
  64. package/src/site/host.ts +172 -0
  65. package/src/site/locale-domains.ts +500 -0
  66. package/src/site/routes.ts +206 -38
  67. package/src/site/site-url.ts +80 -17
  68. package/src/tracking/injections.ts +52 -9
  69. package/src/ui/Reveal.tsx +74 -9
package/CHANGELOG.md CHANGED
@@ -8,6 +8,267 @@ matches `package.json` exactly. See
8
8
  Versions 0.1.0 through 0.78.0 predate this repository and were reconstructed
9
9
  from the published npm tarballs.
10
10
 
11
+ ## 0.90.0-m7.11
12
+
13
+ - The page builder no longer invents a public URL for a locale with no
14
+ configured public domain. An empty `publicHost(locale)` means no public URL
15
+ exists, and is no longer read as a relative one.
16
+ - For an unmapped locale the page path is shown as plain, non-clickable
17
+ information, saying that no domain is configured for that language. The
18
+ public-link anchor and the Copy URL action are omitted rather than pointed
19
+ somewhere else: no relative href, no backoffice or request hostname, no other
20
+ locale's domain.
21
+ - Draft Preview keeps working for an unmapped locale. Previewing is a
22
+ backoffice operation and has never needed a public hostname.
23
+ - The `publicHost`, `publicPath` and `usePageUrl` host contracts document this,
24
+ so a host knows what the empty string means before it implements one.
25
+ - No migration and no database change. Nothing in this release concerns a
26
+ host's own integration code.
27
+
28
+ ## 0.90.0-m7.10
29
+
30
+ - Code & tracking drafts survive a refetch. A background reload replaced the
31
+ table under the administrator's hands: a brand new profile, a duplicate made
32
+ from an existing one, and edits typed but not yet saved all disappeared
33
+ without a word. What the server sends is merged into what is on screen
34
+ instead of replacing it.
35
+ - Tracking profiles apply in global, then language, then domain order, so a
36
+ domain profile refines the language one rather than replacing it. Hostname
37
+ matching is consistent throughout: an apex and its single `www.` are the same
38
+ site everywhere the decision is made.
39
+ - GTM, GA4, Meta Pixel, TikTok Pixel, verification meta tags and raw
40
+ head / body-start / body-end code all reach the server-rendered HTML at the
41
+ position each one requires, rather than depending on a client-side step to
42
+ fire.
43
+ - Raw custom code is injected byte for byte. `$&`, `` $` ``, `$'` and `$$` in a
44
+ snippet were read as replacement patterns and rewrote the markup around them;
45
+ a profile now reaches the page exactly as it was typed.
46
+ - Tracking is excluded from the configured backoffice path, preview routes, API
47
+ routes and server-function routes, so pixels no longer fire on administrative
48
+ traffic or on responses that are not pages.
49
+ - A tracking read that fails leaves the public site standing. The page renders
50
+ without injection, the failure is reported through an injectable logger, and
51
+ it is not cached — the next request retries instead of serving a fabricated
52
+ empty configuration for the rest of the cache window. A backend that answers
53
+ with an error rather than throwing counts as a failure; treating it as "no
54
+ profiles" made a broken deployment indistinguishable from an unconfigured one.
55
+ - The tracking cache is bounded rather than growing one entry per hostname
56
+ seen, and a successful create, update or delete drops it, so a change goes
57
+ live within the TTL instead of sitting behind whatever was cached first.
58
+ - A failed audit entry or a failed log line cannot undo a write that already
59
+ happened. Both are best-effort in both directions: the mutation stands and is
60
+ reported as the success it was, rather than coming back as an error whose
61
+ obvious retry inserts a second profile. That now holds even when the
62
+ host-supplied logger is itself what throws.
63
+ - A newly created profile whose id the server cannot establish is held until the
64
+ page is reloaded. The insert may well have landed, so pressing Save again
65
+ would create a duplicate firing every pixel twice; the screen says to reload,
66
+ and saving existing profiles is unaffected.
67
+ - Languages & domains has moved out of the main sidebar into System
68
+ administration, alongside the other installation-level screens.
69
+ - Code & tracking and Languages & domains require the `admin` role, matching the
70
+ authorization their server functions already enforce. Staff without it get a
71
+ plain no-access screen instead of a form that fails on Save.
72
+ - Storing a hostname and matching a request against one are now separate
73
+ questions. Canonical output carries the exact hostname the deployment
74
+ configured; matching still folds an apex and one `www.` together. A page is no
75
+ longer canonical on two of its own addresses.
76
+ - Canonical URLs, `og:url`, hreflang, `og:locale:alternate` and both sitemaps
77
+ are built from the configured canonical hostnames.
78
+ - Rows written before the domain validator existed are ignored for matching and
79
+ for every generated URL, instead of being normalized into a plausible-looking
80
+ address. `ftp://example.com` no longer reduces to `example.com` and wins a
81
+ request for it — which had decided the locale, the tracking profiles that fire
82
+ and the backoffice hostname alike.
83
+ - In explicit domain-mapping mode a supported language with no configured domain
84
+ is left out of hreflang and sitemap alternates, instead of borrowing another
85
+ locale's origin — or the origin of the current request — and advertising a URL
86
+ this deployment may not serve.
87
+ - Single-origin multilingual sites are supported by the sitemap helpers.
88
+ `sitemapEntries` and `sitemapIndexEntries` take the public origin and emit
89
+ absolute URLs only. Previously a locale sitemap could come out carrying
90
+ relative URLs, while the sitemap index had no domain mappings from which to
91
+ build entries at all.
92
+ - Public locale-domain projections omit `isAdminDomain`. Which hostname serves
93
+ the backoffice is not something an anonymous reader needs to be told.
94
+ - `SITE_URL` is validated before it can become the authoritative admin hostname,
95
+ and as configured rather than after normalizing — normalizing strips the
96
+ scheme, so a value nobody can serve validated cleanly and was allowed to
97
+ override the database and switch off the check that stops an unreachable
98
+ admin domain being saved.
99
+ - Admin-host resolution fails open. An unusable flagged row falls through to the
100
+ next source instead of stranding the backoffice, the screen names which source
101
+ the hostname came from, and the banner refreshes when a domain is saved.
102
+ - **Host integration required after upgrading.** Nothing below is done by this
103
+ package on the host's behalf:
104
+ - expose the shared Languages & domains screen at the host's canonical
105
+ `/admin/domains` route;
106
+ - keep the old `/domains` route as a compatibility redirect where applicable;
107
+ - register `getEffectiveAdminHost` among the backoffice host functions, so
108
+ the screen can say where the backoffice actually is;
109
+ - use `siteCanonicalHost()` when passing `SITE_URL` authority, not the raw
110
+ environment value;
111
+ - pass the public origin to `sitemapEntries` and `sitemapIndexEntries` on
112
+ single-origin sites;
113
+ - pass the configured `backofficePath` into `createServerEntry`, or tracking
114
+ will be injected into the backoffice;
115
+ - split public-safe locale-domain reads from authenticated admin reads; and
116
+ - ensure the tracking-create server function returns the newly created
117
+ profile id, which the screen now requires before it will treat a create as
118
+ complete.
119
+ - No database migration is included in this release, and no database data is
120
+ changed by it.
121
+ - Not included and not yet verified: Voyara's own integration is not part of
122
+ this package release, and neither staging nor production has been verified
123
+ with `0.90.0-m7.10`.
124
+
125
+ ## 0.90.0-m7.9
126
+
127
+ - The email settings screen says where provider credentials actually go. An
128
+ administrator told only that "passwords are stored as server secrets" does the
129
+ one thing the sentence was meant to prevent and pastes the password into the
130
+ CMS field in front of them, so the screen names the configuration file, the
131
+ environment-variable names and the secret-name convention for that
132
+ installation instead. It stays value-free: no secret is read, returned or
133
+ rendered, and hosts supply their own deployment root through
134
+ `secretsLocation` — including `/`, which stays absolute.
135
+ - Optional block content whose localized value is empty is no longer rendered.
136
+ A heading or paragraph written in one locale and left blank in another used to
137
+ leave its empty markup behind in the locale that had nothing to say.
138
+ - Nested navigation items are editable. Only top-level entries could be changed,
139
+ so fixing a typo in a child link meant deleting it and building it again.
140
+ - Rich text holds up at length, and a block chooses how it appears. Each block
141
+ carries its own reveal mode; `Reveal` still defaults to `fade`, so every
142
+ already-published page looks exactly as it did.
143
+ - Cooperative editing locks stop two administrators overwriting each other. A
144
+ lock is taken when an editor opens a resource, renewed while it stays open and
145
+ released when it closes, and a second editor is told who holds it instead of
146
+ silently losing the earlier write. Pages, global sections, shared content,
147
+ navigation, contact details, forms, form defaults, form history and page SEO
148
+ are covered, and the refusal is enforced in the server cores — not only by
149
+ disabling controls in the interface.
150
+ - The lock's session token is private and the session match is exact.
151
+ `session_id` is never returned by any read: authenticated callers hold column
152
+ grants that omit it, the JSON shape drops it, and the administrator listing
153
+ returns a redacted row. A write against a live lock succeeds only for the
154
+ exact, non-empty session that holds it. Empty or malformed lock responses fail
155
+ closed rather than reading as "free", a stale asynchronous reply cannot revive
156
+ a lock that was already released, reopening an editor can no longer let its
157
+ own release overtake its next acquire, and a duplicated browser tab is given
158
+ its own session identity — Web Locks where the browser provides them, a
159
+ best-effort BroadcastChannel fallback where it does not.
160
+ - Lock storage is a host port, not a provider. `editLockActionCore` and
161
+ `assertEditable` reach the database only through `EditLockAdapter`
162
+ (`@bygghammar/cms-platform/server/edit-lock-adapter`) — five methods covering
163
+ acquire, status, release, list and the staff check — so an application on
164
+ ordinary PostgreSQL implements it with the SQL it already writes, with no
165
+ PostgREST client and no `supabase` object to imitate. Hosts that already build
166
+ `{ supabase: { rpc }, userId, claims }` for their other cores keep passing
167
+ exactly that: `createSupabaseEditLockAdapter` is applied for them
168
+ automatically and nothing on an existing host changes.
169
+ - Locks require a migration and host wiring, and change nothing until both are
170
+ done. `migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql`
171
+ creates the table and its functions; `docs/EDIT-LOCKS.md` is the host
172
+ contract: one authenticated server endpoint through `editLockActionCore`, one
173
+ `EditLockProvider` built with `createEditLockApi`, the non-empty
174
+ `editSessionId` forwarded to every protected write, `pageKey` passed to
175
+ `PageSeoPanelView`, and the `edit_locked:` message prefix preserved across the
176
+ host's own transport. Until then every screen behaves exactly as it did before
177
+ locks existed.
178
+ - The lock is a cooperative server preflight, not a transaction-atomic write
179
+ fence. The check and the mutation are separate statements, so a host needing
180
+ strict exclusion must put both in one transaction or RPC. Full-document exits
181
+ deliberately let the lock lapse by TTL — 120 seconds by default — rather than
182
+ race a reload against its own release.
183
+ - Verified on PostgreSQL 16 and 17: the migration applies in a single
184
+ transaction against a throwaway container carrying a host's real role,
185
+ authentication and user objects; the grants, the RLS policy and the
186
+ `SECURITY DEFINER` `search_path` come out as written; twenty simultaneous
187
+ acquires of one resource leave exactly one holder and no errors; and a
188
+ shadowing `pg_temp` object cannot reach inside a definer body.
189
+ - Not verified in this release: the migration has not been applied to any real
190
+ staging or production database, and the two-user real-browser lock behaviour
191
+ has not been exercised against a live host. Both remain required before
192
+ production use.
193
+
194
+ ## 0.90.0-m7.8
195
+
196
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.8`. `m7.6` and `m7.7` were
197
+ tagged and never published: two defects in the release workflow stopped them
198
+ after every gate had passed. The form-identity work they were meant to carry
199
+ is unchanged and ships here.
200
+ - The release workflow gets both corrections, proven in lightweight-popup:
201
+ the redundant post-checkout `git fetch` is gone (checkout already brings
202
+ every branch, and its credentials are removed on the way out), and
203
+ `npm pack`'s destination is created before it is packed into, with the same
204
+ directory carried to the tarball verification rather than spelled twice.
205
+ - `ops/verify-release-tag.mjs` checks `refs/remotes/origin/main` is present
206
+ before asking `merge-base` about it, so a checkout that fetched too little no
207
+ longer reports itself as a tag on an unmerged branch.
208
+
209
+ ## 0.90.0-m7.6
210
+
211
+ - A form submitted from inside a popup now says so. `FormRenderer` and
212
+ `ManagedForm` take an opaque `context` that is merged into the submission,
213
+ and the popup module fills it with `{ popupKey }` — the form system keeps
214
+ knowing nothing about the features that use it. Without this the request was
215
+ indistinguishable from the same form filled on an ordinary page, so the
216
+ server stored an ordinary entry and every delivery configured on the popup
217
+ silently did nothing.
218
+ - `HostSubmitFormInput` gains `popupKey?: string`, the only popup-shaped value
219
+ the browser sends. Destination, endpoint, signing secret and which fields may
220
+ leave are all read on the server from the popup's stored configuration.
221
+ - Drafts and the builder preview carry no context, so a part-filled form and an
222
+ editor checking a layout cannot fire a campaign's webhook.
223
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.6`, which is where the
224
+ identity comes from.
225
+
226
+ ## 0.90.0-m7.5
227
+
228
+ - `BackofficeHost.pages.fns.listPages` is declared. It was what
229
+ `cmsPageDirectory` had always looked for, read through an index cast because
230
+ the contract did not name it — so a site could not register it without a type
231
+ error, and every site that had not silently got a picker with nothing in it.
232
+ The top-level lookup stays for anyone who registered it there anyway.
233
+
234
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.5`. In `m7.4` an advanced
235
+ path rule could not be typed: the row was reclassified after the first
236
+ keystroke and disappeared. No change here beyond the floor — a site pairing
237
+ this with `m7.4` would get a picker whose rules field does not work.
238
+
239
+ ## 0.90.0-m7.4
240
+
241
+ - `cmsPageDirectory` takes the site's routing engine and asks it for each
242
+ page's public path, instead of assuming the page key is the path. The home
243
+ page is why: its key is `home` and its address is `/`, so the popup page
244
+ picker would have offered an address that matches nothing.
245
+ - The Popups screen supplies that resolver from the `usePageUrl` hook the
246
+ backoffice already registers — no new host field, no second pages query. The
247
+ hook is called from its own component so it stays unconditional while the
248
+ page group remains optional.
249
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.4`, which is where the
250
+ page picker itself lives.
251
+
252
+ ## 0.90.0-m7.3
253
+
254
+ - Popup exclusions are derived from the configured `backofficePath`, so a site
255
+ that mounts its office at `/admin` or `/cms/backoffice` is covered without
256
+ naming it twice. Both the tree and its landing page are excluded: `/admin/**`
257
+ does not match `/admin`.
258
+ - `registerPopupPublicHost` accepts `excludedPaths` for a site's own private
259
+ routes — a checkout, a members' area. The CMS adds to that list and never
260
+ replaces it, and drops duplicates rather than repeating a path.
261
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.3`, whose defaults no
262
+ longer name anyone's backoffice.
263
+
264
+ ## 0.90.0-m7.2
265
+
266
+ - `backofficePaths` gains `popups` and `popupDestinations`, and both popup
267
+ mount points supply them to the package's navigation. The destinations screen
268
+ was reachable only by typing its address.
269
+ - Requires `@bygghammar/lightweight-popup@>=0.2.0-m7.2`, which is where the
270
+ navigation itself lives.
271
+
11
272
  ## 0.90.0-m7.1
12
273
 
13
274
  First version published to npm rather than vendored as a tarball. Same code as
package/README.md CHANGED
@@ -25,6 +25,14 @@ apply the canonical schema with `bunx cms-platform-migrations`, import
25
25
  `theme.css`, register host components / platform data / translations, wrap the
26
26
  server cores and mount the shared backoffice views.
27
27
 
28
+ ## Editing locks
29
+
30
+ `docs/EDIT-LOCKS.md` is what a host wires so two administrators cannot
31
+ overwrite each other: run the migration, expose one server endpoint through
32
+ `editLockActionCore`, mount `EditLockProvider` with `createEditLockApi`, and
33
+ forward `editSessionId` to the saves. Until that is done every screen behaves
34
+ exactly as it did before locks existed.
35
+
28
36
  ## Compatibility policy
29
37
 
30
38
  - `CHANGELOG.md` records every release; read it before upgrading.
@@ -119,8 +127,14 @@ bun run check # typecheck + tests + package verification
119
127
 
120
128
  The package ships TypeScript sources; there is no build output. Every change
121
129
  goes through a pull request, and every release is triggered by pushing a
122
- `vX.Y.Z` tag that matches `package.json`, which publishes to npm from GitHub
123
- Actions using the repository secret `NPM_TOKEN`. Never publish manually.
130
+ `vX.Y.Z` tag that matches `package.json`. That tag runs
131
+ `.github/workflows/publish.yml`, which publishes to npm using **Trusted
132
+ Publishing**: GitHub mints a short-lived OIDC token scoped to that single
133
+ workflow run, and npm exchanges it for publish rights through the package's
134
+ Trusted Publisher configuration. No long-lived npm credential takes part — no
135
+ `NPM_TOKEN`, no `NODE_AUTH_TOKEN`, no OTP. [RELEASING.md](./RELEASING.md) is
136
+ what the workflow checks and the npm settings it has to match. Never publish
137
+ manually.
124
138
 
125
139
  See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full workflow and changelog
126
140
  conventions. Consumers install an explicit released version such as
@@ -0,0 +1,213 @@
1
+ # Editing locks: what a host has to wire
2
+
3
+ Two administrators opening the same page used to be a silent race — whoever
4
+ saved last won, and the other one's work disappeared without a message. The
5
+ lock makes that a refusal instead: the second person sees who has the page and
6
+ cannot type into it, and the server refuses the write even if they try.
7
+
8
+ The package supplies all of it except three connections only the host can make.
9
+ Until they are made every screen behaves exactly as it did before locks
10
+ existed, which is what lets an installation upgrade the package first and the
11
+ database afterwards.
12
+
13
+ ## 1. Run the migration
14
+
15
+ `migrations/20260902090000_dc072b25-8467-46ae-aef3-0ccdf40aa7eb.sql` creates
16
+ `public.cms_edit_locks` and five functions. It is safe to run more than once.
17
+ It is ordinary PostgreSQL — a table, an index, grants, one RLS policy and four
18
+ `SECURITY DEFINER` functions with a pinned `search_path`. A host that stores
19
+ locks some other way can skip it and supply its own adapter instead; see
20
+ [Storage](#storage).
21
+
22
+ Until it runs, `assertEditable` sees "no such function" and lets every write
23
+ through — an upgrade cannot break saving. After it runs, the server checks are
24
+ available; the provider and save-path forwarding below are still required for
25
+ per-tab UI locking.
26
+
27
+ ## 2. One server endpoint
28
+
29
+ Every lock call goes through `editLockActionCore`, so the host writes one
30
+ server function rather than five:
31
+
32
+ ```ts
33
+ import { editLockActionCore, isEditLockAction } from "@bygghammar/cms-platform/server/edit-locks-core";
34
+ import { editLockSchemas } from "@bygghammar/cms-platform/server/schemas";
35
+
36
+ export const editLock = serverFn(async ({ data }) => {
37
+ if (!isEditLockAction(data.action)) throw new Error("Unknown lock action");
38
+ const input = editLockSchemas.acquire.parse(data);
39
+ return editLockActionCore(await authContext(), data.action, input);
40
+ });
41
+ ```
42
+
43
+ `authContext()` returns the lock storage for the signed-in user — see
44
+ [Storage](#storage) for what that is. The lock functions run as that user, so
45
+ `is_staff` and RLS apply exactly as they do everywhere else.
46
+
47
+ ## 3. One provider in the browser
48
+
49
+ ```tsx
50
+ import { useMemo } from "react";
51
+ import { createEditLockApi, EditLockProvider } from "@bygghammar/cms-platform/backoffice/EditLock";
52
+
53
+ const lockApi = useMemo(
54
+ () => createEditLockApi(
55
+ (action, input) => editLock({ data: { action, ...input } }),
56
+ { canSteal: isSuperadmin },
57
+ ),
58
+ [editLock, isSuperadmin],
59
+ );
60
+
61
+ <EditLockProvider api={lockApi}>{backoffice}</EditLockProvider>
62
+ ```
63
+
64
+ Mount it once, around the backoffice. Every editing screen finds it by itself.
65
+ Keep the API object stable with `useMemo`: its identity controls the editors'
66
+ acquire/release effects, so rebuilding it during each render would repeatedly
67
+ release and reacquire their locks.
68
+
69
+ `canSteal` only decides whether the take-over button is *offered*; the database
70
+ function refuses anyone but a superadmin regardless, so offering it to an
71
+ ordinary editor produces a button that always fails.
72
+
73
+ Leave the api `null` — or mount no provider at all — and every screen reports
74
+ "not enforced" and behaves as before.
75
+
76
+ ## 4. Pass the session id on to the saves
77
+
78
+ The provider is what shows the banner. The session id is what makes the server
79
+ able to tell *this* editor's save from someone else's, and it travels with the
80
+ save, not with the lock.
81
+
82
+ Each screen already puts `lock.sessionId` into the deps it calls. The host's
83
+ job is to forward it to the matching core:
84
+
85
+ | Screen | Host dep | Core | Resource |
86
+ | --- | --- | --- | --- |
87
+ | `PageBuilderView` | `save`, `rename`, `schedule`, `cancelPublication`, `restoreVersion` | `savePageVersionCore`, `renamePageCore`, `schedulePageVersionCore`, `cancelPagePublicationCore`, `restorePageVersionCore` | `page` / page id |
88
+ | `GlobalSectionBuilderView` | `save`, `rename`, `setKind` | `saveGlobalSectionVersionCore`, `renameGlobalSectionCore`, `setGlobalSectionKindCore` | `global_section` / section id |
89
+ | `SectionEditorView`, `NavigationView`, `ContactDetailsView` | `save` | `saveContentSectionCore` | `content_section` / section key |
90
+ | `FormEditorView` | `saveForm`; pass `editSessionId` into its host `VersionHistory` too | `saveFormCore`, `restoreFormVersionCore` | `form` / form id |
91
+ | `FormSettingsView` | `saveDefaults`; forward the whole `data` object, or destructure its `editSessionId` into the core's third argument | `saveFormDefaultsCore` | `form_defaults` / `form_settings` |
92
+ | `PageSeoPanelView` | `onSave(form, editSessionId)`, `onReset(editSessionId)` | `savePageSeoCore`, `deletePageSeoOverrideCore` | `page_seo` / `pageKey` |
93
+
94
+ The cores and schemas accept `editSessionId` as an optional field so an
95
+ unwired/unmigrated host keeps its old behaviour while no lock exists. Once a
96
+ resource has a live lock, every protected write requires the matching session
97
+ id, including writes by another tab of the same user. Forward it on every path
98
+ in the table; omission is not a bypass.
99
+
100
+ `PageSeoPanelView` additionally needs `pageKey`. Without it the SEO panel has
101
+ no resource to lock and stays unlocked, even with everything else wired.
102
+
103
+ ## Storage
104
+
105
+ `editLockActionCore` and `assertEditable` never touch a database themselves.
106
+ Every read and write goes through `EditLockAdapter`
107
+ (`@bygghammar/cms-platform/server/edit-lock-adapter`), five methods over the
108
+ domain operations and nothing else:
109
+
110
+ ```ts
111
+ type EditLockAdapter = {
112
+ assertStaff(): Promise<void>;
113
+ acquire(input: EditLockRef & { sessionId: string; ttlSeconds: number; steal: boolean }): Promise<EditLockState>;
114
+ status(input: EditLockRef & { sessionId: string | null }): Promise<EditLockState>;
115
+ release(input: EditLockRef & { sessionId: string }): Promise<boolean>;
116
+ list(): Promise<EditLockRow[]>;
117
+ };
118
+ ```
119
+
120
+ The context a core takes is `{ editLocks: <adapter> }`. Nothing in the contract
121
+ names a driver, a client library or a wire format, so a self-hosted application
122
+ on ordinary PostgreSQL implements it with the SQL it already writes:
123
+
124
+ ```ts
125
+ import type { EditLockAdapter } from "@bygghammar/cms-platform/server/edit-lock-adapter";
126
+ import { EditLockNotInstalledError } from "@bygghammar/cms-platform/server/edit-lock-adapter";
127
+ import { asEditLockState } from "@bygghammar/cms-platform/cms/edit-lock";
128
+
129
+ const MISSING = new Set(["42883", "42P01"]); // no such function, no such table
130
+
131
+ export function editLockStorage(pool: Pool, userId: string): EditLockAdapter {
132
+ const query = async (text: string, values: unknown[]) => {
133
+ try {
134
+ return await pool.query(text, values);
135
+ } catch (error) {
136
+ if (MISSING.has(error.code)) throw new EditLockNotInstalledError();
137
+ throw error;
138
+ }
139
+ };
140
+ return {
141
+ async acquire(input) {
142
+ const { rows } = await query(
143
+ "SELECT public.cms_acquire_edit_lock($1, $2, $3, $4, $5) AS state",
144
+ [input.resourceType, input.resourceId, input.sessionId, input.ttlSeconds, input.steal],
145
+ );
146
+ return asEditLockState(rows[0]?.state);
147
+ },
148
+ // status, release, list and assertStaff in the same shape
149
+ };
150
+ }
151
+ ```
152
+
153
+ Two rules an adapter has to honour, whatever it is built on:
154
+
155
+ - **`acquire` must be one atomic statement.** Two editors opening the same page
156
+ at the same instant have to contend on a single unique index so exactly one
157
+ wins. Read-then-write leaves a window in which both do.
158
+ - **`sessionId` is a bearer token.** It goes in and is never returned. Knowing
159
+ another tab's session id is enough to save as its holder, so no read may
160
+ include it — not `status`, not `list`.
161
+
162
+ Whether the storage runs on a stored function, plain SQL in the adapter, or a
163
+ service of its own is the host's decision. A PostgREST-shaped host that already
164
+ builds `{ supabase: { rpc }, userId, claims }` for its other cores can keep
165
+ passing exactly that: `createSupabaseEditLockAdapter` is applied for it
166
+ automatically, and the migration's functions are the storage.
167
+
168
+ ## What the server does with it
169
+
170
+ `assertEditable` sits before each protected write. A write from another session
171
+ throws `EditLockedError`. On the server it has `error.code === "edit_locked"` and
172
+ `error.state`. TanStack Start serializes only an Error's message, so the message
173
+ also begins with `edit_locked:` and `isEditLockedError()` recognises either
174
+ form after transport. Do not replace that failure with a success response.
175
+
176
+ This is a cooperative preflight lock, not a transaction-wide database fence.
177
+ Expiry, a new acquisition, a superadmin steal, or an explicit release could
178
+ land between the status preflight and a later PostgREST mutation. Strict
179
+ transactional exclusion would require each mutation and its lock check in one
180
+ database RPC, or a fencing token checked by the write itself.
181
+
182
+ The per-tab session id is a bearer value and is never returned by a lock
183
+ status/acquire response. Authenticated staff have column-level read access to
184
+ the operational lock fields but not `session_id`; the administrative list RPC
185
+ omits that column. This prevents a blocked browser from reading the
186
+ holder's token and replaying it in a save.
187
+
188
+ Modern browsers also hold an exclusive Web Lock for that bearer value before
189
+ the first server acquire. This detects a duplicated tab even when the original
190
+ is frozen. Browsers without Web Locks fall back to a short BroadcastChannel
191
+ handshake. That fallback is best-effort because a frozen source tab can answer
192
+ too late; without either primitive there is no duplicate-tab signal at all.
193
+ Multi-user locking remains enforced in either case.
194
+
195
+ ## Choosing the lifetime
196
+
197
+ A lock lasts 120 seconds by default and is renewed every 40. A browser that
198
+ crashes therefore frees the page about two minutes later, with no cleanup job
199
+ anywhere. Pass `ttlSeconds` to `createEditLockApi` to change it; the database
200
+ clamps to 15–3600 whatever it is told.
201
+
202
+ Leaving an editor through client-side navigation releases immediately. Closing
203
+ or reloading the whole document relies on the TTL: firing a release from the
204
+ old document can arrive after the reload has already reacquired with the same
205
+ session and delete its new lock. A restored/backgrounded page stays fenced
206
+ until its catch-up renewal confirms it still holds the resource.
207
+
208
+ ## Recovering a stuck lock
209
+
210
+ `listEditLocksCore` returns every live lock, and `steal` takes one — superadmin
211
+ only, enforced in the database. Neither is needed for the feature to work; they
212
+ are for the afternoon somebody's laptop dies mid-edit and two minutes is too
213
+ long to wait.