@donotdev/cli 0.2.2 → 0.3.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 (64) hide show
  1. package/dependencies-matrix.json +44 -42
  2. package/dist/bin/commands/agent-setup.js +135 -67
  3. package/dist/bin/commands/build.js +352 -234
  4. package/dist/bin/commands/bump.js +385 -257
  5. package/dist/bin/commands/cacheout.js +59 -49
  6. package/dist/bin/commands/coach.js +80 -50
  7. package/dist/bin/commands/create-app.js +501 -228
  8. package/dist/bin/commands/create-project.js +377 -241
  9. package/dist/bin/commands/db-check.js +192804 -0
  10. package/dist/bin/commands/db.js +1889 -1805
  11. package/dist/bin/commands/deploy.js +476 -287
  12. package/dist/bin/commands/dev.js +139 -108
  13. package/dist/bin/commands/doctor.js +91 -57
  14. package/dist/bin/commands/emu.js +196 -154
  15. package/dist/bin/commands/format.js +83 -50
  16. package/dist/bin/commands/get-demo.js +422 -197
  17. package/dist/bin/commands/make-admin.js +835 -713
  18. package/dist/bin/commands/preview.js +139 -108
  19. package/dist/bin/commands/seed.js +2186 -2044
  20. package/dist/bin/commands/setup-cicd.js +258 -204
  21. package/dist/bin/commands/setup.js +890 -339
  22. package/dist/bin/commands/staging.js +476 -287
  23. package/dist/bin/commands/sync-secrets.js +472 -141
  24. package/dist/bin/commands/type-check.js +163 -119
  25. package/dist/bin/commands/wai.js +53 -46
  26. package/dist/bin/dndev.js +32 -7
  27. package/dist/bin/donotdev.js +18 -8
  28. package/dist/index.js +654 -375
  29. package/package.json +2 -2
  30. package/templates/app-demo/index.html.example +1 -1
  31. package/templates/app-dndev/index.html.example +1 -1
  32. package/templates/app-dndev/src/globals.css.example +1 -1
  33. package/templates/app-dndev/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  34. package/templates/app-dndev/src/pages/legal/PrivacyPage.tsx.example +1 -1
  35. package/templates/app-dndev/src/pages/legal/TermsPage.tsx.example +1 -1
  36. package/templates/app-next/src/app/AppDocument.tsx.example +58 -0
  37. package/templates/app-next/src/app/ClientLayout.tsx.example +6 -2
  38. package/templates/app-next/src/globals.css.example +1 -1
  39. package/templates/app-next/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  40. package/templates/app-next/src/pages/legal/PrivacyPage.tsx.example +1 -1
  41. package/templates/app-next/src/pages/legal/TermsPage.tsx.example +1 -1
  42. package/templates/app-vite/csp.example.json +1 -1
  43. package/templates/app-vite/index.html.example +1 -1
  44. package/templates/app-vite/src/globals.css.example +1 -1
  45. package/templates/app-vite/src/pages/FormPageExample.tsx.example +21 -16
  46. package/templates/app-vite/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  47. package/templates/app-vite/src/pages/legal/PrivacyPage.tsx.example +1 -1
  48. package/templates/app-vite/src/pages/legal/TermsPage.tsx.example +1 -1
  49. package/templates/deploy-config/vercel.json.example +2 -2
  50. package/templates/functions-supabase/supabase/migrations/20250101000006_crud_bulk_status_guard.sql +258 -0
  51. package/templates/functions-supabase/supabase/migrations/20250101000007_rate_limit_check.sql +76 -0
  52. package/templates/overlay-supabase/src/config/providers.nextjs.ts.example +37 -0
  53. package/templates/root-consumer/.claude/hooks/guard-bash.sh.example +3 -3
  54. package/templates/root-consumer/.claude/hooks/guard-write.sh.example +5 -1
  55. package/templates/root-consumer/.claude/hooks/typecheck-stop.sh.example +2 -2
  56. package/templates/root-consumer/.claude/rules/definition-of-done.md.example +2 -2
  57. package/templates/root-consumer/.claude/rules/framework.md.example +1 -1
  58. package/templates/root-consumer/.claude/skills/build/SKILL.md.example +1 -1
  59. package/templates/root-consumer/.claude/skills/polish/SKILL.md.example +1 -1
  60. package/templates/root-consumer/.gitignore.example +7 -1
  61. package/templates/root-consumer/AGENTS.md.example +25 -2
  62. package/templates/root-consumer/README.md.example +1 -1
  63. package/templates/app-next/src/app/layout.tsx.example +0 -80
  64. package/templates/app-next/src/app/not-found.tsx.example +0 -40
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/cli",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Command-line interface for DoNotDev Framework",
5
5
  "type": "module",
6
6
  "private": false,
@@ -32,7 +32,7 @@
32
32
  "type-check": "bunx tsc --noEmit"
33
33
  },
34
34
  "dependencies": {
35
- "@clack/prompts": "^1.8.1",
35
+ "@clack/prompts": "^1.9.0",
36
36
  "commander": "^14.0.3",
37
37
  "fast-glob": "^3.3.3"
38
38
  },
@@ -9,7 +9,7 @@
9
9
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
10
10
  <title>DoNotDev Demo</title>
11
11
 
12
- <!-- Fonts: Inter, Space Grotesk, Playfair, Roboto from @donotdev/ui/dndev.css (bundled). -->
12
+ <!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
13
13
 
14
14
  <!-- ✅ CRITICAL CSS: ECG waveform loader -->
15
15
  <style>
@@ -13,7 +13,7 @@
13
13
  <!-- ✅ DnDev: Asset manifest injection point -->
14
14
  <!-- window.__DNDEV_ASSETS__ and __DNDEV_ASSET_MANIFEST__ injected here -->
15
15
 
16
- <!-- Fonts: Inter, Space Grotesk, Playfair, Roboto loaded via @donotdev/ui/dndev.css (bundled). -->
16
+ <!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
17
17
  <!-- DNDEV_FONT_PRELOADS -->
18
18
 
19
19
  <!-- ✅ PERFORMANCE: Preconnect to external domains (OAuth providers) -->
@@ -6,5 +6,5 @@
6
6
 
7
7
  /**
8
8
  * Font choices (--font-family, --font-sans, etc.) belong in themes.css.
9
- * Fonts (Inter, Space Grotesk, Playfair, Roboto) are bundled via @donotdev/ui; no external fetch, no public/fonts required.
9
+ * Self-hosted: the build keeps only the @donotdev/ui catalogue fonts (Inter, Playfair Display, Space Grotesk, Roboto, Press Start 2P) they name; no external fetch, no public/fonts required.
10
10
  */
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Building } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { LegalNoticeTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Shield } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { PrivacyPolicyTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { FileText } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { TermsOfServiceTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -0,0 +1,58 @@
1
+ import type { Metadata } from 'next';
2
+ import type { ReactNode } from 'react';
3
+
4
+ import { FontPreloadLinks } from '@donotdev/ui/next';
5
+
6
+ import '../globals.css';
7
+
8
+ /**
9
+ * Framework fonts: only the catalogue families themes.css renders text in, copied to
10
+ * public/ at build. FontPreloadLinks links their stylesheet (renders nothing when the
11
+ * theme uses only the app's own fonts).
12
+ */
13
+
14
+ /**
15
+ * Site-level metadata only. Page title, description, canonical, Open Graph and JSON-LD
16
+ * come from the framework's AutoMetaTags (PageMeta + i18n) and from <Seo> on pages
17
+ * that render a record. Do not set `title` or `description` here: they would ship as
18
+ * a second <title>/<meta name="description"> in every page's HTML.
19
+ */
20
+ const appUrl = process.env.NEXT_PUBLIC_APP_URL;
21
+ export const metadata: Metadata = {
22
+ ...(appUrl ? { metadataBase: new URL(appUrl) } : {}),
23
+ };
24
+
25
+ /**
26
+ * The app's HTML document: <html>, <head> links and <body>.
27
+ *
28
+ * The framework generates the root layout and renders this document with the page's
29
+ * language (`lang`): the URL's language with 2+ languages (src/app/[lang]/layout),
30
+ * the app's language with one. Every page's HTML, cached pages included, carries its
31
+ * own <html lang>. It also renders the providers (./ClientLayout) below: src/app/(site)
32
+ * renders every page without request data, so pages are static and served from the
33
+ * cache (revalidated hourly) to guests and crawlers; with a cookie session (Supabase),
34
+ * src/app/dndev-session renders the same pages per request with the visitor's cookies.
35
+ * Reading request headers or cookies here, or exporting `dynamic`, would make every
36
+ * page per request: the build refuses it.
37
+ */
38
+ export function AppDocument({
39
+ lang,
40
+ children,
41
+ }: {
42
+ lang: string;
43
+ children: ReactNode;
44
+ }) {
45
+ return (
46
+ <html
47
+ lang={lang}
48
+ className="dndev-design-tokens light"
49
+ suppressHydrationWarning
50
+ >
51
+ <head>
52
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
53
+ <FontPreloadLinks />
54
+ </head>
55
+ <body className="light">{children}</body>
56
+ </html>
57
+ );
58
+ }
@@ -18,9 +18,13 @@ import { appConfig } from '../config/app';
18
18
 
19
19
  interface ClientLayoutProps {
20
20
  children: React.ReactNode;
21
- /** Request Cookie header (language cookie, auth session), from the root layout */
21
+ /**
22
+ * Request Cookie header (auth session): `""` in the generated src/app/(site) layout
23
+ * (cached pages, no request data), the request's in src/app/dndev-session
24
+ * (per-request pages of visitors with an auth cookie)
25
+ */
22
26
  serverCookies: string;
23
- /** Request Accept-Language header, from the root layout */
27
+ /** Request Accept-Language header (`null` on cached pages) */
24
28
  acceptLanguage: string | null;
25
29
  }
26
30
 
@@ -5,6 +5,6 @@
5
5
 
6
6
  /**
7
7
  * Font choices (--font-family, --font-sans, etc.) belong in themes.css.
8
- * Fonts are served from public/fonts/ (auto-copied by framework discovery).
8
+ * The framework fonts they name are served from public/fonts/ (copied by discovery); own fonts ship none.
9
9
  * dndev-next.css = font-stripped variant — use this for Next.js, NOT dndev.css.
10
10
  */
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Building } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { LegalNoticeTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Shield } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { PrivacyPolicyTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { FileText } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { TermsOfServiceTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -5,7 +5,7 @@
5
5
  "script-src": "'self'",
6
6
  "style-src": "'self' 'unsafe-inline'",
7
7
  "img-src": "'self' data: blob: https:",
8
- "font-src": "'self' https://fonts.gstatic.com",
8
+ "font-src": "'self'",
9
9
  "object-src": "'none'",
10
10
  "base-uri": "'self'",
11
11
  "form-action": "'self'",
@@ -13,7 +13,7 @@
13
13
  <!-- ✅ DnDev: Asset manifest injection point -->
14
14
  <!-- window.__DNDEV_ASSETS__ and __DNDEV_ASSET_MANIFEST__ injected here -->
15
15
 
16
- <!-- Fonts: Inter, Space Grotesk, Playfair, Roboto loaded via @donotdev/ui/dndev.css (bundled). -->
16
+ <!-- Fonts: the theme's framework fonts, bundled from @donotdev/ui/dndev.css (others dropped at build). -->
17
17
  <!-- DNDEV_FONT_PRELOADS -->
18
18
 
19
19
  <!-- ✅ PERFORMANCE: Preconnect to external domains (OAuth providers) -->
@@ -5,5 +5,5 @@
5
5
 
6
6
  /**
7
7
  * Font choices (--font-family, --font-sans, etc.) belong in themes.css.
8
- * Fonts (Inter, Space Grotesk, Playfair, Roboto) are bundled via @donotdev/ui; no external fetch, no public/fonts required.
8
+ * Self-hosted: the build keeps only the @donotdev/ui catalogue fonts (Inter, Playfair Display, Space Grotesk, Roboto, Press Start 2P) they name; no external fetch, no public/fonts required.
9
9
  */
@@ -6,14 +6,13 @@
6
6
  * HOW IT WORKS:
7
7
  * 1. Route: /products/:id (edit) or /products/new (create)
8
8
  * 2. EntityFormRenderer generates form from entity fields
9
- * 3. useCrud provides get/add/update operations
9
+ * 3. useCrudDoc reads the record (cache-backed, server-rendered on SSR);
10
+ * useCrud provides add/update operations
10
11
  * 4. Optimistic updates - navigation is instant, sync happens in background
11
12
  */
12
13
 
13
- import { useEffect, useState } from 'react';
14
-
15
- import { Section, Button, Alert } from '@donotdev/components';
16
- import { useCrud } from '@donotdev/crud';
14
+ import { Section, Button, Alert, Spinner } from '@donotdev/components';
15
+ import { useCrud, useCrudDoc } from '@donotdev/crud';
17
16
  import { useTranslation } from '@donotdev/core';
18
17
  import type { PageMeta } from '@donotdev/core';
19
18
  import { PageContainer, Link, EntityFormRenderer } from '@donotdev/ui';
@@ -53,20 +52,18 @@ export default function ProductPage() {
53
52
  const id = useParam('id');
54
53
  const isNew = id === 'new';
55
54
 
56
- // useCrud provides CRUD operations with optimistic updates
57
- const { get, add, update, error } = useCrud(productEntity);
58
- const [formData, setFormData] = useState<any>(null);
55
+ // useCrud provides write operations with optimistic updates
56
+ const { add, update } = useCrud(productEntity);
59
57
 
60
58
  // ==========================================================================
61
- // FETCH EXISTING DATA (edit mode only)
59
+ // EXISTING DATA (edit mode only)
60
+ // Read through the CRUD cache: fetched during the server render on SSR apps.
61
+ // Never get(id) in a useEffect: effects don't run on the server.
62
62
  // ==========================================================================
63
- useEffect(() => {
64
- if (!isNew && id) {
65
- get(id).then((data) => {
66
- if (data) setFormData(data);
67
- });
68
- }
69
- }, [id, isNew, get]);
63
+ const { data: formData, loading, error } = useCrudDoc(
64
+ productEntity,
65
+ isNew ? null : id
66
+ );
70
67
 
71
68
  // ==========================================================================
72
69
  // FORM SUBMISSION - Optimistic Update Pattern
@@ -102,6 +99,14 @@ export default function ProductPage() {
102
99
  );
103
100
  }
104
101
 
102
+ if (loading) {
103
+ return (
104
+ <PageContainer>
105
+ <Spinner overlay />
106
+ </PageContainer>
107
+ );
108
+ }
109
+
105
110
  // ==========================================================================
106
111
  // RENDER FORM
107
112
  // ==========================================================================
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Building } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { LegalNoticeTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { Shield } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { PrivacyPolicyTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { FileText } from 'lucide-react';
11
11
 
12
- import { type PageMeta } from '@donotdev/core';
12
+ import type { PageMeta } from '@donotdev/core';
13
13
  import { TermsOfServiceTemplate } from '@donotdev/templates';
14
14
  import { PageContainer } from '@donotdev/ui';
15
15
 
@@ -18,7 +18,7 @@
18
18
  "headers": [
19
19
  {
20
20
  "key": "Content-Security-Policy",
21
- "value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'{{#needsBilling}} https://fonts.googleapis.com{{/needsBilling}}; img-src 'self' data: blob: https:; font-src 'self' data:{{#needsBilling}} https://fonts.gstatic.com{{/needsBilling}}; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
21
+ "value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
22
22
  },
23
23
  {
24
24
  "key": "X-Content-Type-Options",
@@ -242,7 +242,7 @@
242
242
  "headers": [
243
243
  {
244
244
  "key": "Content-Security-Policy",
245
- "value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'{{#needsBilling}} https://fonts.googleapis.com{{/needsBilling}}; img-src 'self' data: blob: https:; font-src 'self' data:{{#needsBilling}} https://fonts.gstatic.com{{/needsBilling}}; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
245
+ "value": "default-src 'self'; script-src 'self' 'unsafe-inline'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com https://apis.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com{{/needsBilling}}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'{{#isFirebase}}{{#needsAuth}} https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://*.googleapis.com https://{{firebaseProjectId}}.firebaseio.com{{/needsAuth}}{{/isFirebase}}{{#isSupabase}} https://*.supabase.co wss://*.supabase.co{{/isSupabase}}{{#needsBilling}} https://api.stripe.com{{/needsBilling}}; frame-src 'none'{{#isFirebase}}{{#needsAuth}} https://accounts.google.com{{/needsAuth}}{{/isFirebase}}{{#needsBilling}} https://js.stripe.com https://hooks.stripe.com{{/needsBilling}}; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"
246
246
  },
247
247
  {
248
248
  "key": "X-Content-Type-Options",
@@ -0,0 +1,258 @@
1
+ -- Migration: crud_bulk re-checks the stored status of updated rows under lock
2
+ -- Generated: 2026-11-17
3
+ -- Purpose: Backs packages/functions/src/supabase/crud/bulk.ts. The handler reads the
4
+ -- stored rows of the updated ids BEFORE the RPC (their status decides each
5
+ -- patch's schema: draft / update / whole-row check on publish). That read is
6
+ -- outside this transaction, so the RPC re-reads every updated row's status
7
+ -- with FOR UPDATE and rejects the whole bulk when it is not the status the
8
+ -- handler validated against (SQLSTATE PT409 (PostgREST: HTTP 409 Conflict, never retried; 40001 is a retryable serialization failure), nothing written).
9
+ --
10
+ -- Replaces the 4-argument crud_bulk of 20250101000004: the new signature takes
11
+ -- p_expected_statuses, so a handler calling with it against a database that never
12
+ -- ran this migration fails loud (function not found) instead of skipping the check.
13
+ -- Also compares ids as literals coerced to the column type (`id = '<id>'`), so
14
+ -- uuid and text id columns both work (the 4-argument version bound the id as
15
+ -- text: `uuid = text` does not exist, every update / delete on a uuid table failed).
16
+
17
+ -- Semantics:
18
+ -- 1. Validate p_collection (length + quote_ident safety).
19
+ -- 2. Reject empty batches (defense in depth — handler short-circuits too).
20
+ -- 3. Status guard: each distinct updated id must be a key of p_expected_statuses
21
+ -- (value: the status read by the handler, JSON null when it was null); the row
22
+ -- is locked (FOR UPDATE) and its status compared. Missing row → raise; status
23
+ -- changed → raise SQLSTATE PT409 (PostgREST: HTTP 409 Conflict, never retried; 40001 is a retryable serialization failure). Runs before any write.
24
+ -- 4. Inserts: use client-provided id if present, else gen_random_uuid().
25
+ -- 5. Updates: apply partial patch — only keys in patch are overwritten.
26
+ -- 6. Deletes: by id.
27
+ -- 7. Any failure raises — Postgres rolls the function back as a unit.
28
+ -- 8. Returns { inserted_ids, updated_ids, deleted_ids } in snake_case.
29
+
30
+ DROP FUNCTION IF EXISTS crud_bulk(TEXT, JSONB, JSONB, JSONB);
31
+
32
+ CREATE OR REPLACE FUNCTION crud_bulk(
33
+ p_collection TEXT,
34
+ p_inserts JSONB,
35
+ p_updates JSONB,
36
+ p_deletes JSONB,
37
+ p_expected_statuses JSONB
38
+ ) RETURNS JSONB
39
+ LANGUAGE plpgsql
40
+ SECURITY DEFINER
41
+ SET search_path = public
42
+ AS $$
43
+ DECLARE
44
+ _inserted_ids TEXT[] := ARRAY[]::TEXT[];
45
+ _updated_ids TEXT[] := ARRAY[]::TEXT[];
46
+ _deleted_ids TEXT[] := ARRAY[]::TEXT[];
47
+
48
+ _insert_count INTEGER;
49
+ _update_count INTEGER;
50
+ _delete_count INTEGER;
51
+
52
+ _row JSONB;
53
+ _row_with_id JSONB;
54
+ _update_entry JSONB;
55
+ _patch JSONB;
56
+ _update_id TEXT;
57
+ _delete_id TEXT;
58
+ _inserted_id TEXT;
59
+ _updated_id TEXT;
60
+ _deleted_id TEXT;
61
+
62
+ _guard_id TEXT;
63
+ _expected_status TEXT;
64
+ _found_status TEXT;
65
+ _found BOOLEAN;
66
+
67
+ _set_sql TEXT;
68
+ _patch_key TEXT;
69
+ _patch_value JSONB;
70
+ _first_key BOOLEAN;
71
+ BEGIN
72
+ -- 1. Collection name validation — length-bound and safe for quote_ident.
73
+ IF p_collection IS NULL OR length(p_collection) = 0 THEN
74
+ RAISE EXCEPTION 'crud_bulk: p_collection must be a non-empty text';
75
+ END IF;
76
+ IF length(p_collection) > 63 THEN
77
+ RAISE EXCEPTION 'crud_bulk: p_collection exceeds 63-char Postgres identifier limit';
78
+ END IF;
79
+
80
+ -- 2. Reject empty batches — handler already short-circuits, but we enforce
81
+ -- the same contract at the SQL boundary.
82
+ _insert_count := COALESCE(jsonb_array_length(p_inserts), 0);
83
+ _update_count := COALESCE(jsonb_array_length(p_updates), 0);
84
+ _delete_count := COALESCE(jsonb_array_length(p_deletes), 0);
85
+
86
+ IF _insert_count = 0 AND _update_count = 0 AND _delete_count = 0 THEN
87
+ RAISE EXCEPTION 'crud_bulk: at least one of p_inserts, p_updates, p_deletes must be non-empty';
88
+ END IF;
89
+
90
+ -- 3. Status guard — the handler validated each patch against the status it
91
+ -- read before this transaction. Lock every updated row and compare, before
92
+ -- any write: all patches of one id are checked against the pre-bulk status.
93
+ IF _update_count > 0 THEN
94
+ IF p_expected_statuses IS NULL OR jsonb_typeof(p_expected_statuses) <> 'object' THEN
95
+ RAISE EXCEPTION 'crud_bulk: p_expected_statuses must be an object (id -> status read by the handler)';
96
+ END IF;
97
+ FOR _guard_id IN
98
+ SELECT DISTINCT value ->> 'id' FROM jsonb_array_elements(p_updates)
99
+ LOOP
100
+ IF _guard_id IS NULL THEN
101
+ RAISE EXCEPTION 'crud_bulk: each update entry must carry a string "id"';
102
+ END IF;
103
+ IF NOT (p_expected_statuses ? _guard_id) THEN
104
+ RAISE EXCEPTION 'crud_bulk: no expected status for % id=%', p_collection, _guard_id;
105
+ END IF;
106
+ _expected_status := p_expected_statuses ->> _guard_id;
107
+
108
+ EXECUTE format(
109
+ 'SELECT true, status::text FROM %I WHERE id = %L FOR UPDATE',
110
+ p_collection,
111
+ _guard_id
112
+ )
113
+ INTO _found, _found_status;
114
+
115
+ IF _found IS NULL THEN
116
+ RAISE EXCEPTION 'crud_bulk: update on % with id=% matched no row', p_collection, _guard_id;
117
+ END IF;
118
+ IF _found_status IS DISTINCT FROM _expected_status THEN
119
+ RAISE EXCEPTION USING
120
+ ERRCODE = 'PT409',
121
+ MESSAGE = format(
122
+ 'crud_bulk: status of %s id=%s changed since it was read (expected %s, found %s)',
123
+ p_collection,
124
+ _guard_id,
125
+ COALESCE(_expected_status, 'null'),
126
+ COALESCE(_found_status, 'null')
127
+ );
128
+ END IF;
129
+ END LOOP;
130
+ END IF;
131
+
132
+ -- 4. Inserts — preserve input order. Client-generated ids win; otherwise
133
+ -- allocate a uuid. jsonb_populate_record handles type coercion against
134
+ -- the real table schema, so unknown keys are ignored and typed columns
135
+ -- are cast correctly.
136
+ IF _insert_count > 0 THEN
137
+ FOR _row IN SELECT value FROM jsonb_array_elements(p_inserts)
138
+ LOOP
139
+ IF _row ? 'id' AND jsonb_typeof(_row -> 'id') = 'string' THEN
140
+ _row_with_id := _row;
141
+ ELSE
142
+ _row_with_id := _row || jsonb_build_object('id', gen_random_uuid()::text);
143
+ END IF;
144
+
145
+ EXECUTE format(
146
+ 'INSERT INTO %1$I SELECT * FROM jsonb_populate_record(NULL::%1$I, $1) RETURNING id',
147
+ p_collection
148
+ )
149
+ USING _row_with_id
150
+ INTO _inserted_id;
151
+
152
+ IF _inserted_id IS NULL THEN
153
+ RAISE EXCEPTION 'crud_bulk: insert into % returned no id', p_collection;
154
+ END IF;
155
+
156
+ _inserted_ids := _inserted_ids || _inserted_id;
157
+ END LOOP;
158
+ END IF;
159
+
160
+ -- 5. Updates — partial patches. We build a dynamic SET clause from the
161
+ -- patch keys so unspecified columns are untouched (jsonb_populate_record
162
+ -- would overwrite them with NULLs). Each patch key is quoted via
163
+ -- quote_ident; values are applied as jsonb with -> lookups inside the
164
+ -- generated SQL, binding the whole patch as a single $1 parameter. The id
165
+ -- is a quoted literal (%L), coerced to the id column type.
166
+ IF _update_count > 0 THEN
167
+ FOR _update_entry IN SELECT value FROM jsonb_array_elements(p_updates)
168
+ LOOP
169
+ IF NOT (_update_entry ? 'id') OR jsonb_typeof(_update_entry -> 'id') <> 'string' THEN
170
+ RAISE EXCEPTION 'crud_bulk: each update entry must carry a string "id"';
171
+ END IF;
172
+ IF NOT (_update_entry ? 'patch') OR jsonb_typeof(_update_entry -> 'patch') <> 'object' THEN
173
+ RAISE EXCEPTION 'crud_bulk: each update entry must carry an object "patch"';
174
+ END IF;
175
+
176
+ _update_id := _update_entry ->> 'id';
177
+ _patch := _update_entry -> 'patch';
178
+
179
+ -- Empty patch is a no-op at the app layer; refuse it here too so a
180
+ -- caller mistake surfaces loudly instead of silently "succeeding".
181
+ IF (SELECT count(*) FROM jsonb_object_keys(_patch)) = 0 THEN
182
+ RAISE EXCEPTION 'crud_bulk: update patch for id=% is empty', _update_id;
183
+ END IF;
184
+
185
+ _set_sql := '';
186
+ _first_key := TRUE;
187
+ FOR _patch_key, _patch_value IN SELECT * FROM jsonb_each(_patch)
188
+ LOOP
189
+ IF NOT _first_key THEN
190
+ _set_sql := _set_sql || ', ';
191
+ END IF;
192
+ -- quote_ident keeps the column name safe; the value is bound via
193
+ -- $1 so no user data is ever concatenated into SQL.
194
+ _set_sql := _set_sql
195
+ || quote_ident(_patch_key)
196
+ || ' = (jsonb_populate_record(NULL::'
197
+ || quote_ident(p_collection)
198
+ || ', $1)).'
199
+ || quote_ident(_patch_key);
200
+ _first_key := FALSE;
201
+ END LOOP;
202
+
203
+ EXECUTE format(
204
+ 'UPDATE %I SET %s WHERE id = %L RETURNING id',
205
+ p_collection,
206
+ _set_sql,
207
+ _update_id
208
+ )
209
+ USING _patch
210
+ INTO _updated_id;
211
+
212
+ IF _updated_id IS NULL THEN
213
+ RAISE EXCEPTION 'crud_bulk: update on % with id=% matched no row', p_collection, _update_id;
214
+ END IF;
215
+
216
+ _updated_ids := _updated_ids || _updated_id;
217
+ END LOOP;
218
+ END IF;
219
+
220
+ -- 6. Deletes — by id, preserve input order.
221
+ IF _delete_count > 0 THEN
222
+ FOR _delete_id IN SELECT value #>> '{}' FROM jsonb_array_elements(p_deletes)
223
+ LOOP
224
+ IF _delete_id IS NULL OR length(_delete_id) = 0 THEN
225
+ RAISE EXCEPTION 'crud_bulk: delete id must be a non-empty string';
226
+ END IF;
227
+
228
+ EXECUTE format(
229
+ 'DELETE FROM %I WHERE id = %L RETURNING id',
230
+ p_collection,
231
+ _delete_id
232
+ )
233
+ INTO _deleted_id;
234
+
235
+ IF _deleted_id IS NULL THEN
236
+ RAISE EXCEPTION 'crud_bulk: delete on % with id=% matched no row', p_collection, _delete_id;
237
+ END IF;
238
+
239
+ _deleted_ids := _deleted_ids || _deleted_id;
240
+ END LOOP;
241
+ END IF;
242
+
243
+ -- 7. Snake_case response — handler normalises both cases but SQL-side
244
+ -- consumers see idiomatic keys.
245
+ RETURN jsonb_build_object(
246
+ 'inserted_ids', to_jsonb(_inserted_ids),
247
+ 'updated_ids', to_jsonb(_updated_ids),
248
+ 'deleted_ids', to_jsonb(_deleted_ids)
249
+ );
250
+ END;
251
+ $$;
252
+
253
+ -- Service-role only — edge handlers enforce auth + ACL before invoking.
254
+ REVOKE EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) FROM PUBLIC;
255
+ REVOKE EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) FROM anon, authenticated;
256
+ GRANT EXECUTE ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) TO service_role;
257
+
258
+ COMMENT ON FUNCTION crud_bulk(TEXT, JSONB, JSONB, JSONB, JSONB) IS 'Atomic bulk CRUD for one collection; re-checks the stored status of updated rows under lock. Service-role only — edge handlers enforce auth + ACL before invoking.';