@guard-rail/core 0.11.0 → 0.12.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.
package/README.md CHANGED
@@ -435,6 +435,43 @@ scratch. A visual page builder (Puck, say) is a better fit for that and can
435
435
  sit alongside `<GRepeater>` later — it would decide composition, while
436
436
  `<GRail>` still owns each block's leaf content.
437
437
 
438
+ ## Reverting a change
439
+
440
+ Every editor popup has a circular-arrow **revert** button next to save and close.
441
+ It steps one version back:
442
+
443
+ - If the field was edited more than once, it restores the **previous saved value**
444
+ — the button reads "Revert to the version from Oct 28".
445
+ - If there's nothing earlier, it removes the saved value so the field shows the
446
+ **default written in the page** — the button reads "Reset to default".
447
+ - If the field has nothing saved, the button isn't shown.
448
+
449
+ The field updates in place, and everyone else sees the change straight away. There's
450
+ no confirmation step; the label says what it will do.
451
+
452
+ Behind it, each save that changes a field's value moves the old value into a
453
+ separate `gr_content_history` table, which only editors of the site can read (the
454
+ public `gr_content` table still holds just the current value). Saving the same value
455
+ again records nothing. History is kept for the newest **20 versions of each field**
456
+ and for **90 days**, whichever is less, and is cleaned up as part of saving — no
457
+ scheduled job. Removing a field (a deleted repeater item, say) removes its history.
458
+
459
+ Things to know:
460
+
461
+ - **Images:** reverting restores the earlier reference. Uploaded files aren't
462
+ deleted, so they stay in the media picker for reuse.
463
+ - **Repeaters:** a field inside an item reverts like any other. Adding, removing and
464
+ reordering items isn't part of history.
465
+ - **Existing content has no history yet.** Revert becomes available after a field's
466
+ next edit.
467
+ - **It needs the `content_history` migration.** Without it, the button just doesn't
468
+ appear. `pnpm exec guardrail-init-db --push`, or `guardrail-doctor --fix --push`,
469
+ applies it.
470
+
471
+ Building your own editing UI? `getRevertInfo(id)` reports what a revert would do
472
+ (`{ kind: "previous" | "default" | "none", at }`) and `revertField(id)` does it. Both
473
+ check the caller is an editor or admin.
474
+
438
475
  ## Custom editing UI
439
476
 
440
477
  `<GRail>` edits what's on the page. Some fields have nothing to click — an SEO
@@ -447,6 +484,8 @@ authorization in Guardrail's hands:
447
484
  field; pass `{ type: "image", src, alt }` etc. for the others. It checks the
448
485
  caller is an editor or admin itself, and writes the same row a `<GRail>` with
449
486
  that id would, so the two stay interchangeable.
487
+ - **`getRevertInfo(id)` / `revertField(id)`** report and perform a one-step revert
488
+ (see "Reverting a change").
450
489
  - **`isEditor()` / `isAdmin()`** are the role checks for your *own* Server
451
490
  Actions. `isEditor()` is true for editors and admins; `isAdmin()` only for
452
491
  admins (team management).
@@ -624,6 +663,13 @@ work inside Client Components (see above): one round trip returning the site's r
624
663
  and whether the list was cut off at `limit`. An adapter without it still works
625
664
  fully for Server Components — client-rendered fields just show their JSX fallback.
626
665
 
666
+ `getRevertInfo(pathKey, siteId)` and `revertOverride(pathKey, siteId)` are optional and
667
+ go together: they back the revert button (see "Reverting a change"). `getRevertInfo`
668
+ returns `{ kind: "previous" | "default" | "none", at? }`; `revertOverride` restores the
669
+ previous saved value (returning it) or removes the saved value, and reports which.
670
+ An adapter without them simply never shows the button — keeping the history is up to
671
+ your backend.
672
+
627
673
  `getOverrides(pathKeys, siteId)` is batched by design — it receives every key a
628
674
  render pass needs, already deduplicated. Adapters map their own storage naming
629
675
  at this boundary; core speaks `pathKey` / `siteId` only.
@@ -660,14 +706,14 @@ By default it only reads. It checks:
660
706
  `supabase/migrations/`, that `next.config` sets anti-framing headers, and that
661
707
  the root layout uses `withGuardrail()`.
662
708
  - **Database:** that the `guardrail` schema is exposed, the tables and functions
663
- exist, rate limiting works, and what your project's sign-up settings are
709
+ exist (including the revert history), rate limiting works, and what your project's sign-up settings are
664
710
  (whether **Confirm email** is on).
665
711
 
666
712
  | Flag | What it adds |
667
713
  |---|---|
668
714
  | `--fix` | Repairs what can be repaired in local files: copies missing migrations, adds a `GUARDRAIL_SITE_URL` note to `.env.example` / `.env.local`, adds baseline security headers to `next.config`. It never changes secrets or Supabase dashboard settings, and re-running it is safe. Add `--push` to also run `supabase db push`. |
669
715
  | `--app-url=http://localhost:3000` | Also checks the response headers of a running copy of your site, including that Guardrail's stylesheet reached the page and that its Content-Security-Policy lets Guardrail's uploads and images through. |
670
- | `--e2e` | Runs an end-to-end suite against the database. It creates a throwaway user, a few rows and a test image, then exercises sign-in, claiming an invitation, row-level security (an editor can write their own site and nobody else's; visitors can read but not write), the last-admin guard, rate limiting and image uploads, and deletes everything it made. It asks before touching a database that isn't local (`--yes` skips the question), and needs the service-role key. |
716
+ | `--e2e` | Runs an end-to-end suite against the database. It creates a throwaway user, a few rows and a test image, then exercises sign-in, claiming an invitation, row-level security (an editor can write their own site and nobody else's; visitors can read but not write), reverting and the history limits, the last-admin guard, rate limiting and image uploads, and deletes everything it made. It asks before touching a database that isn't local (`--yes` skips the question), and needs the service-role key. |
671
717
  | `--csp` | Prints a starter `Content-Security-Policy-Report-Only` header built from your `SUPABASE_URL` and exits. |
672
718
  | `--offline` | Skips the advisory lookup (the only network call besides your own Supabase project). Package names and versions are what's sent otherwise, as with `pnpm audit`; offline, Next.js is checked against a built-in list that may be out of date. |
673
719
  | `--production` | Treats production-only requirements as failures instead of warnings. |
@@ -833,4 +879,4 @@ one, is set by your site (Next.js does it from a proxy); Guardrail doesn't need
833
879
  - `withGuardrail` reads cookies in the root layout, which opts routes into
834
880
  dynamic rendering. See the repo README for the plan.
835
881
  - Saving revalidates the entire layout tree rather than the affected route.
836
- - No drafts, revisions, or scheduled publishing. Saves are live.
882
+ - No drafts or scheduled publishing. Saves are live; an editor can step back one version (see "Reverting a change"), but there is no full revision browser.
@@ -8,6 +8,9 @@ function toOverrideRow(row) {
8
8
  value: typeof row.value === "string" ? JSON.parse(row.value) : row.value
9
9
  };
10
10
  }
11
+ function isMissingFunction(error) {
12
+ return error.code === "PGRST202" || error.code === "42883" || /could not find the function/i.test(error.message ?? "");
13
+ }
11
14
  function supabaseDB(creds) {
12
15
  assertCredentials(creds);
13
16
  return {
@@ -45,6 +48,36 @@ function supabaseDB(creds) {
45
48
  );
46
49
  return error ? { success: false, error: error.message } : { success: true };
47
50
  },
51
+ // Reverting runs in the database (gr_revert_content / gr_revert_info) so a
52
+ // step back is one atomic move, and the editor's own access rules apply.
53
+ async getRevertInfo(pathKey, siteId) {
54
+ const client = await sessionClient(creds);
55
+ const { data, error } = await client.schema(GR_SCHEMA).rpc("gr_revert_info", { p_site: siteId, p_key: pathKey });
56
+ if (error) {
57
+ if (!isMissingFunction(error)) {
58
+ console.error("Guardrail (Supabase): gr_revert_info failed", error.message);
59
+ }
60
+ return { kind: "none" };
61
+ }
62
+ const info = data;
63
+ return info && ["previous", "default", "none"].includes(info.kind) ? info : { kind: "none" };
64
+ },
65
+ async revertOverride(pathKey, siteId) {
66
+ const client = await sessionClient(creds);
67
+ const { data, error } = await client.schema(GR_SCHEMA).rpc("gr_revert_content", { p_site: siteId, p_key: pathKey });
68
+ if (error) {
69
+ return {
70
+ success: false,
71
+ error: isMissingFunction(error) ? "Reverting needs the latest database migration \u2014 run `pnpm exec guardrail-init-db --push`." : error.code === "42501" ? "You don't have permission to revert this." : error.message
72
+ };
73
+ }
74
+ const result = data;
75
+ if (result?.action === "restored" && result.value) {
76
+ const value = typeof result.value === "string" ? JSON.parse(result.value) : result.value;
77
+ return { success: true, action: "restored", value };
78
+ }
79
+ return { success: true, action: result?.action === "reset" ? "reset" : "none" };
80
+ },
48
81
  async deleteOverrides(pathKeyPrefix, siteId) {
49
82
  const client = await sessionClient(creds);
50
83
  const { error } = await client.schema(GR_SCHEMA).from(GR_TABLE).delete().eq("site_id", siteId).like("path_key", `${pathKeyPrefix}%`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/adapters/supabase/db.ts"],"sourcesContent":["import { anonClient, assertCredentials, sessionClient } from \"./client\";\nimport type { SupabaseCredentials } from \"./client\";\nimport { GR_SCHEMA, GR_TABLE } from \"../../core/defs\";\nimport type { GRDBAdapter, GRStorageRow } from \"../../core/adapter-types\";\nimport type { OverrideRow, OverrideValue } from \"../../core/types\";\n\n/** Shape as stored in Postgres. Column naming stops at this boundary. */\ninterface ContentRow {\n id: string;\n path_key: string;\n value: OverrideValue | string;\n}\n\nfunction toOverrideRow(row: ContentRow): OverrideRow {\n return {\n id: row.id,\n pathKey: row.path_key,\n // Some drivers hand back jsonb columns as strings.\n value:\n typeof row.value === \"string\"\n ? (JSON.parse(row.value) as OverrideValue)\n : row.value,\n };\n}\n\nexport function supabaseDB(creds: SupabaseCredentials): GRDBAdapter {\n assertCredentials(creds);\n\n return {\n async getOverrides(pathKeys, siteId) {\n if (pathKeys.length === 0) return [];\n\n // Anon client keeps the read path cookie-free so routes stay static.\n const { data, error } = await anonClient(creds)\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .select(\"id, path_key, value\")\n .eq(\"site_id\", siteId)\n .in(\"path_key\", pathKeys);\n\n if (error) {\n console.error(\"Guardrail (Supabase): read failed\", error.message);\n return [];\n }\n return ((data ?? []) as ContentRow[]).map(toOverrideRow);\n },\n\n async listOverrides(siteId, { prefix, limit }) {\n let query = anonClient(creds)\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .select(\"id, path_key, value\")\n .eq(\"site_id\", siteId)\n // Ordered so that truncation, when it happens, is deterministic.\n .order(\"path_key\")\n // One past the ceiling, purely to learn whether anything was cut off.\n .limit(limit + 1);\n\n if (prefix?.length) {\n // Quoted so a prefix containing PostgREST's own separators (comma,\n // parens) can't be read as filter syntax.\n const quote = (p: string) => `\"${p.replace(/[\"\\\\]/g, \"\\\\$&\")}\"`;\n query = query.or(prefix.map((p) => `path_key.like.${quote(`${p}*`)}`).join(\",\"));\n }\n\n const { data, error } = await query;\n // Thrown, not swallowed to []: an empty list here would read as \"this\n // site has no content\" and short-circuit every field's own lookup.\n if (error) throw new Error(error.message);\n\n const rows = ((data ?? []) as ContentRow[]).map(toOverrideRow);\n return { rows: rows.slice(0, limit), truncated: rows.length > limit };\n },\n\n async setOverride(row: GRStorageRow) {\n const client = await sessionClient(creds);\n const { error } = await client\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .upsert(\n {\n path_key: row.pathKey,\n site_id: row.siteId,\n type: row.type,\n value: row.value,\n updated_at: new Date().toISOString(),\n },\n { onConflict: \"path_key,site_id\" },\n );\n return error\n ? { success: false, error: error.message }\n : { success: true };\n },\n\n async deleteOverrides(pathKeyPrefix: string, siteId: string) {\n const client = await sessionClient(creds);\n const { error } = await client\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .delete()\n .eq(\"site_id\", siteId)\n .like(\"path_key\", `${pathKeyPrefix}%`);\n if (error) {\n console.error(\"Guardrail (Supabase): deleteOverrides failed\", error.message);\n }\n },\n };\n}\n"],"mappings":"AAAA,SAAS,YAAY,mBAAmB,qBAAqB;AAE7D,SAAS,WAAW,gBAAgB;AAWpC,SAAS,cAAc,KAA8B;AACnD,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,SAAS,IAAI;AAAA;AAAA,IAEb,OACE,OAAO,IAAI,UAAU,WAChB,KAAK,MAAM,IAAI,KAAK,IACrB,IAAI;AAAA,EACZ;AACF;AAEO,SAAS,WAAW,OAAyC;AAClE,oBAAkB,KAAK;AAEvB,SAAO;AAAA,IACL,MAAM,aAAa,UAAU,QAAQ;AACnC,UAAI,SAAS,WAAW,EAAG,QAAO,CAAC;AAGnC,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,WAAW,KAAK,EAC3C,OAAO,SAAS,EAChB,KAAK,QAAQ,EACb,OAAO,qBAAqB,EAC5B,GAAG,WAAW,MAAM,EACpB,GAAG,YAAY,QAAQ;AAE1B,UAAI,OAAO;AACT,gBAAQ,MAAM,qCAAqC,MAAM,OAAO;AAChE,eAAO,CAAC;AAAA,MACV;AACA,cAAS,QAAQ,CAAC,GAAoB,IAAI,aAAa;AAAA,IACzD;AAAA,IAEA,MAAM,cAAc,QAAQ,EAAE,QAAQ,MAAM,GAAG;AAC7C,UAAI,QAAQ,WAAW,KAAK,EACzB,OAAO,SAAS,EAChB,KAAK,QAAQ,EACb,OAAO,qBAAqB,EAC5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AM,OAAO;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/adapters/supabase/db.ts"],"sourcesContent":["import { anonClient, assertCredentials, sessionClient } from \"./client\";\nimport type { SupabaseCredentials } from \"./client\";\nimport { GR_SCHEMA, GR_TABLE } from \"../../core/defs\";\nimport type { GRDBAdapter, GRRevertInfo, GRRevertResult, GRStorageRow } from \"../../core/adapter-types\";\nimport type { OverrideRow, OverrideValue } from \"../../core/types\";\n\n/** Shape as stored in Postgres. Column naming stops at this boundary. */\ninterface ContentRow {\n id: string;\n path_key: string;\n value: OverrideValue | string;\n}\n\nfunction toOverrideRow(row: ContentRow): OverrideRow {\n return {\n id: row.id,\n pathKey: row.path_key,\n // Some drivers hand back jsonb columns as strings.\n value:\n typeof row.value === \"string\"\n ? (JSON.parse(row.value) as OverrideValue)\n : row.value,\n };\n}\n\n/** PostgREST's \"no such function\" (PGRST202) or Postgres' own (42883): the migration isn't applied. */\nfunction isMissingFunction(error: { code?: string; message?: string }): boolean {\n return error.code === \"PGRST202\" || error.code === \"42883\" || /could not find the function/i.test(error.message ?? \"\");\n}\n\nexport function supabaseDB(creds: SupabaseCredentials): GRDBAdapter {\n assertCredentials(creds);\n\n return {\n async getOverrides(pathKeys, siteId) {\n if (pathKeys.length === 0) return [];\n\n // Anon client keeps the read path cookie-free so routes stay static.\n const { data, error } = await anonClient(creds)\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .select(\"id, path_key, value\")\n .eq(\"site_id\", siteId)\n .in(\"path_key\", pathKeys);\n\n if (error) {\n console.error(\"Guardrail (Supabase): read failed\", error.message);\n return [];\n }\n return ((data ?? []) as ContentRow[]).map(toOverrideRow);\n },\n\n async listOverrides(siteId, { prefix, limit }) {\n let query = anonClient(creds)\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .select(\"id, path_key, value\")\n .eq(\"site_id\", siteId)\n // Ordered so that truncation, when it happens, is deterministic.\n .order(\"path_key\")\n // One past the ceiling, purely to learn whether anything was cut off.\n .limit(limit + 1);\n\n if (prefix?.length) {\n // Quoted so a prefix containing PostgREST's own separators (comma,\n // parens) can't be read as filter syntax.\n const quote = (p: string) => `\"${p.replace(/[\"\\\\]/g, \"\\\\$&\")}\"`;\n query = query.or(prefix.map((p) => `path_key.like.${quote(`${p}*`)}`).join(\",\"));\n }\n\n const { data, error } = await query;\n // Thrown, not swallowed to []: an empty list here would read as \"this\n // site has no content\" and short-circuit every field's own lookup.\n if (error) throw new Error(error.message);\n\n const rows = ((data ?? []) as ContentRow[]).map(toOverrideRow);\n return { rows: rows.slice(0, limit), truncated: rows.length > limit };\n },\n\n async setOverride(row: GRStorageRow) {\n const client = await sessionClient(creds);\n const { error } = await client\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .upsert(\n {\n path_key: row.pathKey,\n site_id: row.siteId,\n type: row.type,\n value: row.value,\n updated_at: new Date().toISOString(),\n },\n { onConflict: \"path_key,site_id\" },\n );\n return error\n ? { success: false, error: error.message }\n : { success: true };\n },\n\n // Reverting runs in the database (gr_revert_content / gr_revert_info) so a\n // step back is one atomic move, and the editor's own access rules apply.\n async getRevertInfo(pathKey: string, siteId: string): Promise<GRRevertInfo> {\n const client = await sessionClient(creds);\n const { data, error } = await client\n .schema(GR_SCHEMA)\n .rpc(\"gr_revert_info\", { p_site: siteId, p_key: pathKey });\n if (error) {\n // Not migrated yet: no history to offer, so just don't offer one.\n if (!isMissingFunction(error)) {\n console.error(\"Guardrail (Supabase): gr_revert_info failed\", error.message);\n }\n return { kind: \"none\" };\n }\n const info = data as GRRevertInfo | null;\n return info && [\"previous\", \"default\", \"none\"].includes(info.kind) ? info : { kind: \"none\" };\n },\n\n async revertOverride(pathKey: string, siteId: string): Promise<GRRevertResult> {\n const client = await sessionClient(creds);\n const { data, error } = await client\n .schema(GR_SCHEMA)\n .rpc(\"gr_revert_content\", { p_site: siteId, p_key: pathKey });\n if (error) {\n return {\n success: false,\n error: isMissingFunction(error)\n ? \"Reverting needs the latest database migration — run `pnpm exec guardrail-init-db --push`.\"\n : error.code === \"42501\"\n ? \"You don't have permission to revert this.\"\n : error.message,\n };\n }\n const result = data as { action?: string; value?: OverrideValue | string } | null;\n if (result?.action === \"restored\" && result.value) {\n const value = typeof result.value === \"string\" ? (JSON.parse(result.value) as OverrideValue) : result.value;\n return { success: true, action: \"restored\", value };\n }\n return { success: true, action: result?.action === \"reset\" ? \"reset\" : \"none\" };\n },\n\n async deleteOverrides(pathKeyPrefix: string, siteId: string) {\n const client = await sessionClient(creds);\n const { error } = await client\n .schema(GR_SCHEMA)\n .from(GR_TABLE)\n .delete()\n .eq(\"site_id\", siteId)\n .like(\"path_key\", `${pathKeyPrefix}%`);\n if (error) {\n console.error(\"Guardrail (Supabase): deleteOverrides failed\", error.message);\n }\n },\n };\n}\n"],"mappings":"AAAA,SAAS,YAAY,mBAAmB,qBAAqB;AAE7D,SAAS,WAAW,gBAAgB;AAWpC,SAAS,cAAc,KAA8B;AACnD,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,SAAS,IAAI;AAAA;AAAA,IAEb,OACE,OAAO,IAAI,UAAU,WAChB,KAAK,MAAM,IAAI,KAAK,IACrB,IAAI;AAAA,EACZ;AACF;AAGA,SAAS,kBAAkB,OAAqD;AAC9E,SAAO,MAAM,SAAS,cAAc,MAAM,SAAS,WAAW,+BAA+B,KAAK,MAAM,WAAW,EAAE;AACvH;AAEO,SAAS,WAAW,OAAyC;AAClE,oBAAkB,KAAK;AAEvB,SAAO;AAAA,IACL,MAAM,aAAa,UAAU,QAAQ;AACnC,UAAI,SAAS,WAAW,EAAG,QAAO,CAAC;AAGnC,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,WAAW,KAAK,EAC3C,OAAO,SAAS,EAChB,KAAK,QAAQ,EACb,OAAO,qBAAqB,EAC5B,GAAG,WAAW,MAAM,EACpB,GAAG,YAAY,QAAQ;AAE1B,UAAI,OAAO;AACT,gBAAQ,MAAM,qCAAq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QAAQ,EACb,OAAO,EACP,GAAG,WAAW,MAAM,EACpB,KAAK,YAAY,GAAG,aAAa,GAAG;AACvC,UAAI,OAAO;AACT,gBAAQ,MAAM,gDAAgD,MAAM,OAAO;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -545,16 +545,19 @@ async function checkDatabase(ctx, sb) {
545
545
  }
546
546
  const admin = sb.createClient(ctx.url, ctx.serviceKey, { auth: { persistSession: false, autoRefreshToken: false } });
547
547
  const gr = () => admin.schema(GR_SCHEMA);
548
- for (const table of [GR_MEMBERS_TABLE, "gr_content", "gr_repeater_items", "gr_rate_limits"]) {
549
- const { error: error2 } = await gr().from(table).select("*", { head: true, count: "exact" }).limit(1);
548
+ for (const table of [GR_MEMBERS_TABLE, "gr_content", "gr_repeater_items", "gr_rate_limits", "gr_content_history"]) {
549
+ const { error: error2 } = await gr().from(table).select("*").limit(1);
550
550
  if (!error2) pass(`Table ${table}`);
551
551
  else if (table === "gr_rate_limits") warn("Table gr_rate_limits is missing", "Rate limits are counted in memory until the migration is applied.", "Run: pnpm exec guardrail-init-db --push");
552
+ else if (table === "gr_content_history") warn("Table gr_content_history is missing", "Editors won't be offered a revert button until the migration is applied.", "Run: pnpm exec guardrail-init-db --push");
552
553
  else fail(`Table ${table} isn't readable`, error2.message, "Run: pnpm exec guardrail-init-db --push");
553
554
  }
554
555
  const probes = [
555
556
  ["gr_confirmed_email", {}, "Confirmed-email identity check"],
556
557
  ["gr_claim_invite", { target_site: "doctor-probe" }, "Invite-claim function"],
557
- ["gr_ensure_bucket", { target_bucket: "gr-doctor-probe" }, "Media bucket function"]
558
+ ["gr_ensure_bucket", { target_bucket: "gr-doctor-probe" }, "Media bucket function"],
559
+ ["gr_revert_content", { p_site: "doctor-probe", p_key: "doctor.probe" }, "Revert function"],
560
+ ["gr_revert_info", { p_site: "doctor-probe", p_key: "doctor.probe" }, "Revert-info function"]
558
561
  ];
559
562
  for (const [fn, args, label] of probes) {
560
563
  const { error: error2 } = await gr().rpc(fn, args);
@@ -835,6 +838,37 @@ async function runE2E(ctx, sb) {
835
838
  value: { type: "text", text: "nope" }
836
839
  });
837
840
  expect(Boolean(anonWrite.error), "Visitors can't write content", anonWrite.error ? void 0 : "An unauthenticated write was allowed.");
841
+ const histCount = async () => {
842
+ const r = await gr(admin).from("gr_content_history").select("id", { count: "exact", head: true }).eq("site_id", siteId).eq("path_key", "doctor.check");
843
+ return r.error ? -1 : r.count ?? 0;
844
+ };
845
+ const setText = (text) => gr(user).from("gr_content").update({ value: { type: "text", text }, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("site_id", siteId).eq("path_key", "doctor.check");
846
+ const current = async () => {
847
+ const r = await gr(user).from("gr_content").select("value").eq("site_id", siteId).eq("path_key", "doctor.check").maybeSingle();
848
+ return r.data?.value?.text ?? null;
849
+ };
850
+ const revertRpc = async (site = siteId) => {
851
+ const r = await gr(user).rpc("gr_revert_content", { p_site: site, p_key: "doctor.check" });
852
+ return { error: r.error, data: r.data };
853
+ };
854
+ await setText("v1");
855
+ await setText("v1");
856
+ const afterTwo = await histCount();
857
+ expect(afterTwo === 1, "A save keeps the old value in history, and re-saving the same value doesn't", `Expected 1 history entry, found ${afterTwo}.`, "Apply the latest migrations: pnpm exec guardrail-init-db --push");
858
+ const info1 = await gr(user).rpc("gr_revert_info", { p_site: siteId, p_key: "doctor.check" });
859
+ expect(info1.data?.kind === "previous", "The editor is told a previous version exists", info1.error?.message);
860
+ const peek = await gr(anon).from("gr_content_history").select("id").eq("site_id", siteId);
861
+ expect(Boolean(peek.error) || (peek.data?.length ?? 0) === 0, "Visitors can't read content history", peek.error ? void 0 : "An unauthenticated read returned history rows.");
862
+ const foreign = await revertRpc(otherSite);
863
+ expect(Boolean(foreign.error), "An editor can't revert another site's content", foreign.error ? void 0 : "The revert was allowed.");
864
+ const r1 = await revertRpc();
865
+ expect(!r1.error && r1.data?.action === "restored" && await current() === "doctor" && await histCount() === 0, "Revert steps back one version", r1.error?.message ?? `Got ${JSON.stringify(r1.data)}.`, "Apply the latest migrations: pnpm exec guardrail-init-db --push");
866
+ const r2 = await revertRpc();
867
+ expect(!r2.error && r2.data?.action === "reset" && await current() === null, "Revert with nothing earlier returns the field to its default", r2.error?.message ?? `Got ${JSON.stringify(r2.data)}.`);
868
+ await gr(user).from("gr_content").insert({ site_id: siteId, path_key: "doctor.check", type: "text", value: { type: "text", text: "n0" } });
869
+ for (let i = 1; i <= 22; i++) await setText(`n${i}`);
870
+ const kept = await histCount();
871
+ expect(kept === 20, "History keeps the newest 20 versions of a field", `Expected 20, found ${kept}.`, "Apply the latest migrations: pnpm exec guardrail-init-db --push");
838
872
  const demote = await gr(user).from(GR_MEMBERS_TABLE).update({ role: "editor" }).eq("site_id", siteId).eq("email", email);
839
873
  expect(
840
874
  Boolean(demote.error),