create-nextblock 0.16.3 → 0.17.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 (201) hide show
  1. package/CLAUDE.md +22 -0
  2. package/docker-template/.env.docker.example +69 -69
  3. package/docker-template/docker/db/init/99-jwt.sql +6 -6
  4. package/docker-template/docker/db/init/99-roles.sql +25 -25
  5. package/docker-template/docker/kong/kong.yml +112 -112
  6. package/docker-template/scripts/docker-setup.mjs +310 -310
  7. package/package.json +1 -1
  8. package/templates/nextblock-template/.browserslistrc +11 -11
  9. package/templates/nextblock-template/.swcrc +30 -30
  10. package/templates/nextblock-template/CLAUDE.md +26 -0
  11. package/templates/nextblock-template/app/(auth-pages)/sign-up/page.tsx +46 -46
  12. package/templates/nextblock-template/app/(auth-pages)/two-factor/page.tsx +51 -51
  13. package/templates/nextblock-template/app/.well-known/ucp/route.ts +16 -16
  14. package/templates/nextblock-template/app/actions/consent.ts +57 -57
  15. package/templates/nextblock-template/app/actions/twoFactorEmail.ts +22 -22
  16. package/templates/nextblock-template/app/api/ai/cortex/build-widget/route.ts +153 -153
  17. package/templates/nextblock-template/app/api/ai/generate-blocks/route.ts +96 -96
  18. package/templates/nextblock-template/app/api/brand/email-logo/route.ts +48 -48
  19. package/templates/nextblock-template/app/api/checkout/freemius/sync/route.ts +29 -29
  20. package/templates/nextblock-template/app/api/cms/check-updates/route.ts +44 -44
  21. package/templates/nextblock-template/app/api/cms/full-backup/export/route.ts +33 -33
  22. package/templates/nextblock-template/app/api/cms/full-backup/restore/route.ts +63 -63
  23. package/templates/nextblock-template/app/api/cron/reset-sandbox/route.ts +270 -205
  24. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +10388 -9315
  25. package/templates/nextblock-template/app/api/cron/sync-currencies/route.ts +39 -39
  26. package/templates/nextblock-template/app/api/custom-blocks/db-relations/route.ts +92 -92
  27. package/templates/nextblock-template/app/api/custom-blocks/editor-definitions/route.ts +43 -43
  28. package/templates/nextblock-template/app/api/media/library/route.ts +69 -69
  29. package/templates/nextblock-template/app/api/media/r2-presigned/route.ts +53 -53
  30. package/templates/nextblock-template/app/api/visual-editing/block-draft/route.ts +47 -47
  31. package/templates/nextblock-template/app/api/visual-editing/product-draft/route.ts +47 -47
  32. package/templates/nextblock-template/app/article/[slug]/PostClientContent.tsx +442 -441
  33. package/templates/nextblock-template/app/article/[slug]/page.utils.ts +4 -1
  34. package/templates/nextblock-template/app/checkout/UcpCartHydrator.tsx +20 -20
  35. package/templates/nextblock-template/app/cms/blocks/components/BlockEditorModal.tsx +241 -241
  36. package/templates/nextblock-template/app/cms/blocks/components/CustomBlockEditorPreview.tsx +160 -160
  37. package/templates/nextblock-template/app/cms/blocks/editors/DynamicCustomBlockEditor.tsx +167 -167
  38. package/templates/nextblock-template/app/cms/components/ConnectGitHubButton.tsx +122 -122
  39. package/templates/nextblock-template/app/cms/components/CortexAiActiveContext.tsx +23 -23
  40. package/templates/nextblock-template/app/cms/components/SeoScoreBadge.tsx +3 -40
  41. package/templates/nextblock-template/app/cms/components/SystemAlertsBanner.tsx +112 -112
  42. package/templates/nextblock-template/app/cms/components/TablePagination.tsx +136 -136
  43. package/templates/nextblock-template/app/cms/components/TwoFactorReminderBanner.tsx +45 -45
  44. package/templates/nextblock-template/app/cms/components/github-connect-actions.ts +102 -102
  45. package/templates/nextblock-template/app/cms/components/system-alerts-actions.ts +31 -31
  46. package/templates/nextblock-template/app/cms/coupons/[id]/edit/page.tsx +16 -16
  47. package/templates/nextblock-template/app/cms/coupons/page.tsx +16 -16
  48. package/templates/nextblock-template/app/cms/custom-blocks/[id]/edit/page.tsx +66 -66
  49. package/templates/nextblock-template/app/cms/custom-blocks/actions.ts +519 -519
  50. package/templates/nextblock-template/app/cms/custom-blocks/components/BlocksLibraryTransferControls.tsx +256 -256
  51. package/templates/nextblock-template/app/cms/custom-blocks/components/DBRelationSelect.tsx +384 -384
  52. package/templates/nextblock-template/app/cms/custom-blocks/components/ImageR2Picker.tsx +221 -221
  53. package/templates/nextblock-template/app/cms/custom-blocks/new/page.tsx +12 -12
  54. package/templates/nextblock-template/app/cms/custom-blocks/page.tsx +438 -438
  55. package/templates/nextblock-template/app/cms/dashboard/components/DashboardComponents.tsx +200 -200
  56. package/templates/nextblock-template/app/cms/dashboard/components/DashboardOnboarding.tsx +130 -130
  57. package/templates/nextblock-template/app/cms/import-export/actions.ts +226 -226
  58. package/templates/nextblock-template/app/cms/pages/page.tsx +273 -273
  59. package/templates/nextblock-template/app/cms/posts/page.tsx +251 -251
  60. package/templates/nextblock-template/app/cms/products/ProductFormClientShell.tsx +19 -0
  61. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +14 -2
  62. package/templates/nextblock-template/app/cms/products/categories/page.tsx +12 -12
  63. package/templates/nextblock-template/app/cms/products/new/page.tsx +135 -135
  64. package/templates/nextblock-template/app/cms/promotions/PromotionsWorkspace.tsx +456 -456
  65. package/templates/nextblock-template/app/cms/promotions/actions.ts +115 -115
  66. package/templates/nextblock-template/app/cms/promotions/page.tsx +31 -31
  67. package/templates/nextblock-template/app/cms/settings/backup-restore/BackupRestoreWorkspace.tsx +1004 -1004
  68. package/templates/nextblock-template/app/cms/settings/backup-restore/page.tsx +29 -29
  69. package/templates/nextblock-template/app/cms/settings/bot-protection/page.tsx +24 -24
  70. package/templates/nextblock-template/app/cms/settings/email/page.tsx +28 -28
  71. package/templates/nextblock-template/app/cms/settings/extra-translations/actions.ts +276 -276
  72. package/templates/nextblock-template/app/cms/settings/google-analytics/page.tsx +26 -26
  73. package/templates/nextblock-template/app/cms/settings/logos/components/DeleteLogoButton.tsx +21 -21
  74. package/templates/nextblock-template/app/cms/settings/logos/components/SetActiveLogoButton.tsx +42 -42
  75. package/templates/nextblock-template/app/cms/settings/logos/components/SiteSeoSettingsForm.tsx +133 -133
  76. package/templates/nextblock-template/app/cms/settings/privacy/page.tsx +27 -27
  77. package/templates/nextblock-template/app/cms/settings/registration/page.tsx +27 -27
  78. package/templates/nextblock-template/app/cms/settings/security/page.tsx +33 -33
  79. package/templates/nextblock-template/app/lib/site-settings.ts +105 -105
  80. package/templates/nextblock-template/app/lib/ucp/protocol.ts +190 -190
  81. package/templates/nextblock-template/app/lib/ucp/server.test.ts +56 -56
  82. package/templates/nextblock-template/app/setup/SetupWizard.tsx +678 -678
  83. package/templates/nextblock-template/app/setup/layout.tsx +13 -13
  84. package/templates/nextblock-template/app/setup/page.tsx +111 -111
  85. package/templates/nextblock-template/app/ucp/v1/carts/[id]/cancel/route.ts +38 -38
  86. package/templates/nextblock-template/app/ucp/v1/carts/[id]/route.ts +68 -68
  87. package/templates/nextblock-template/app/ucp/v1/carts/route.ts +35 -35
  88. package/templates/nextblock-template/app/ucp/v1/catalog/lookup/route.ts +35 -35
  89. package/templates/nextblock-template/app/ucp/v1/catalog/product/route.ts +35 -35
  90. package/templates/nextblock-template/app/ucp/v1/catalog/search/route.ts +34 -34
  91. package/templates/nextblock-template/components/CartTranslator.tsx +210 -210
  92. package/templates/nextblock-template/components/DeferredCartTranslator.tsx +51 -51
  93. package/templates/nextblock-template/components/DeferredGlobalSearch.tsx +68 -68
  94. package/templates/nextblock-template/components/DeferredGoogleAnalytics.tsx +70 -70
  95. package/templates/nextblock-template/components/FeatureImageHero.tsx +47 -47
  96. package/templates/nextblock-template/components/GlobalSearch.tsx +557 -557
  97. package/templates/nextblock-template/components/Header.tsx +38 -38
  98. package/templates/nextblock-template/components/PublicEnvBootstrap.tsx +30 -30
  99. package/templates/nextblock-template/components/ResponsiveNav.tsx +14 -14
  100. package/templates/nextblock-template/components/auth/AuthBotProtection.tsx +182 -182
  101. package/templates/nextblock-template/components/blocks/PostsGridClient.tsx +48 -48
  102. package/templates/nextblock-template/components/blocks/TestimonialBlock.tsx +9 -9
  103. package/templates/nextblock-template/components/blocks/publicRendererLoaders.ts +25 -25
  104. package/templates/nextblock-template/components/blocks/renderers/ButtonBlockRenderer.tsx +92 -92
  105. package/templates/nextblock-template/components/blocks/renderers/ClientTextBlockRenderer.tsx +11 -0
  106. package/templates/nextblock-template/components/blocks/renderers/PostsGridBlockRenderer.tsx +24 -24
  107. package/templates/nextblock-template/components/blocks/renderers/TestimonialBlockRenderer.tsx +57 -57
  108. package/templates/nextblock-template/components/blocks/renderers/inline/AlertWidgetRenderer.tsx +2 -2
  109. package/templates/nextblock-template/components/blocks/renderers/inline/CtaWidgetRenderer.tsx +2 -2
  110. package/templates/nextblock-template/components/media/YouTubeFacade.tsx +105 -105
  111. package/templates/nextblock-template/components/media/youtube-embed-replace.tsx +32 -32
  112. package/templates/nextblock-template/components/privacy/ConsentBanner.tsx +170 -170
  113. package/templates/nextblock-template/components/privacy/ConsentGatedAnalytics.tsx +70 -70
  114. package/templates/nextblock-template/components/renderers/CachedDynamicLayoutEngine.tsx +28 -28
  115. package/templates/nextblock-template/components/renderers/DynamicLayoutEngine.test.tsx +166 -166
  116. package/templates/nextblock-template/components/renderers/DynamicLayoutEngine.tsx +471 -471
  117. package/templates/nextblock-template/components/visual-editing/DeferredVisualEditing.tsx +21 -21
  118. package/templates/nextblock-template/context/language-rest-client.ts +32 -32
  119. package/templates/nextblock-template/docker/db/init/99-jwt.sql +6 -6
  120. package/templates/nextblock-template/docker/db/init/99-roles.sql +25 -25
  121. package/templates/nextblock-template/docker/kong/kong.yml +112 -112
  122. package/templates/nextblock-template/docs/02-ECOMMERCE-CAPABILITIES.md +364 -364
  123. package/templates/nextblock-template/docs/04-DATABASE-AND-AUTH.md +11 -0
  124. package/templates/nextblock-template/docs/07-BLOCK-SDK-AND-EXTENSIBILITY.md +146 -146
  125. package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +19 -0
  126. package/templates/nextblock-template/docs/10-CUSTOM-BLOCKS.md +222 -222
  127. package/templates/nextblock-template/lib/app-secrets.ts +39 -39
  128. package/templates/nextblock-template/lib/auth/cookies.ts +47 -47
  129. package/templates/nextblock-template/lib/auth/crypto.ts +45 -45
  130. package/templates/nextblock-template/lib/auth/trustedDevices.ts +92 -92
  131. package/templates/nextblock-template/lib/blocks/README.md +13 -13
  132. package/templates/nextblock-template/lib/botProtection/verify.ts +134 -134
  133. package/templates/nextblock-template/lib/cms/payments-reminder.test.ts +135 -135
  134. package/templates/nextblock-template/lib/cms/payments-reminder.ts +105 -105
  135. package/templates/nextblock-template/lib/cms-transfer/types.ts +145 -145
  136. package/templates/nextblock-template/lib/custom-block-definitions.ts +87 -87
  137. package/templates/nextblock-template/lib/custom-block-r2-upload-shared.ts +178 -178
  138. package/templates/nextblock-template/lib/custom-block-r2-upload.test.ts +140 -140
  139. package/templates/nextblock-template/lib/custom-block-r2-upload.ts +88 -88
  140. package/templates/nextblock-template/lib/custom-block-relations.test.ts +227 -227
  141. package/templates/nextblock-template/lib/custom-block-relations.ts +279 -279
  142. package/templates/nextblock-template/lib/custom-block-safelist.ts +14 -14
  143. package/templates/nextblock-template/lib/editor/dynamic-extension-core.test.ts +172 -172
  144. package/templates/nextblock-template/lib/editor/dynamic-extension-core.ts +213 -213
  145. package/templates/nextblock-template/lib/editor/dynamic-extension-loader.ts +22 -22
  146. package/templates/nextblock-template/lib/editor/dynamic-extensions.tsx +193 -193
  147. package/templates/nextblock-template/lib/email/branding-format.test.ts +133 -133
  148. package/templates/nextblock-template/lib/email/branding-format.ts +123 -123
  149. package/templates/nextblock-template/lib/email/branding.ts +76 -76
  150. package/templates/nextblock-template/lib/full-backup/manifest.test.ts +121 -121
  151. package/templates/nextblock-template/lib/full-backup/manifest.ts +206 -206
  152. package/templates/nextblock-template/lib/logos/active-logo.ts +53 -53
  153. package/templates/nextblock-template/lib/media/resolveMediaUrl.ts +56 -54
  154. package/templates/nextblock-template/lib/media/youtube.ts +99 -99
  155. package/templates/nextblock-template/lib/onboarding/actions.ts +31 -31
  156. package/templates/nextblock-template/lib/privacy/consent-client.ts +57 -57
  157. package/templates/nextblock-template/lib/privacy/contact-emails.ts +64 -64
  158. package/templates/nextblock-template/lib/privacy/settings.ts +115 -115
  159. package/templates/nextblock-template/lib/privacy/types.ts +69 -69
  160. package/templates/nextblock-template/lib/promotions/server.test.ts +74 -74
  161. package/templates/nextblock-template/lib/promotions/server.ts +741 -741
  162. package/templates/nextblock-template/lib/resolve-block-relations.test.ts +142 -142
  163. package/templates/nextblock-template/lib/resolve-block-relations.ts +255 -255
  164. package/templates/nextblock-template/lib/seo/page-audit-context.tsx +3 -3
  165. package/templates/nextblock-template/lib/seo/page-document.test.ts +34 -0
  166. package/templates/nextblock-template/lib/seo/page-document.ts +3 -462
  167. package/templates/nextblock-template/lib/seo/robots-txt.ts +5 -4
  168. package/templates/nextblock-template/lib/setup/actions.ts +460 -460
  169. package/templates/nextblock-template/lib/setup/env-status.ts +125 -125
  170. package/templates/nextblock-template/lib/setup/env-write.ts +111 -111
  171. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +50 -10
  172. package/templates/nextblock-template/lib/setup/provisioning.ts +59 -59
  173. package/templates/nextblock-template/lib/setup/schema-apply.ts +408 -408
  174. package/templates/nextblock-template/lib/setup/system-config.ts +105 -105
  175. package/templates/nextblock-template/lib/setup/types.ts +18 -18
  176. package/templates/nextblock-template/lib/storage/provider.ts +66 -66
  177. package/templates/nextblock-template/lib/storage/supabase-storage.ts +103 -103
  178. package/templates/nextblock-template/lib/updates/github-device.ts +206 -206
  179. package/templates/nextblock-template/lib/updates/repo-identity.ts +56 -56
  180. package/templates/nextblock-template/lib/visual-editing/draft-content.test.ts +105 -105
  181. package/templates/nextblock-template/lib/visual-editing/draft-route.test.ts +42 -42
  182. package/templates/nextblock-template/lib/visual-editing/edit-info.test.ts +143 -143
  183. package/templates/nextblock-template/lib/visual-editing/edit-info.ts +94 -94
  184. package/templates/nextblock-template/lib/visual-editing/product-drafts.test.ts +81 -81
  185. package/templates/nextblock-template/lib/zod-config.ts +5 -5
  186. package/templates/nextblock-template/next-env.d.ts +1 -0
  187. package/templates/nextblock-template/package.json +1 -1
  188. package/templates/nextblock-template/public/images/cortex_post.webp +0 -0
  189. package/templates/nextblock-template/public/images/update_nextblock.webp +0 -0
  190. package/templates/nextblock-template/scripts/docker-setup.mjs +310 -310
  191. package/templates/nextblock-template/scripts/validate-editor-block-schema.ts +112 -112
  192. package/templates/nextblock-template/scripts/verify-cortex-ai-build-widget.tsx +98 -98
  193. package/templates/nextblock-template/scripts/verify-cortex-ai-generate-blocks.ts +62 -62
  194. package/templates/nextblock-template/scripts/verify-cortex-ai-global-tools.ts +537 -537
  195. package/templates/nextblock-template/scripts/verify-cortex-ai-routing.ts +58 -58
  196. package/templates/nextblock-template/scripts/verify-custom-block-definitions.ts +188 -188
  197. package/templates/nextblock-template/scripts/verify-dynamic-custom-block-extensions.ts +123 -123
  198. package/templates/nextblock-template/scripts/verify-dynamic-layout-engine.tsx +133 -133
  199. package/templates/nextblock-template/scripts/verify-milestone-2-custom-blocks.ts +65 -65
  200. package/templates/nextblock-template/tools/deploy-supabase.js +159 -159
  201. package/templates/nextblock-template/types/jsdom.d.ts +6 -6
@@ -1,678 +1,678 @@
1
- 'use client';
2
-
3
- import { useEffect, useMemo, useState, useTransition } from 'react';
4
- import {
5
- Alert,
6
- AlertDescription,
7
- Badge,
8
- Button,
9
- Card,
10
- CardContent,
11
- CardDescription,
12
- CardHeader,
13
- CardTitle,
14
- Checkbox,
15
- Input,
16
- Label,
17
- Separator,
18
- Spinner,
19
- } from '@nextblock-cms/ui';
20
- import type { DeployChannel } from '../../lib/setup/env-status';
21
- import { completeSetup, saveSupabaseConnection } from '../../lib/setup/actions';
22
- import { signInAction } from '../actions';
23
-
24
- export type StorageKind = 'minio' | 'supabase' | 'r2';
25
-
26
- export interface StoragePrefill {
27
- kind: StorageKind;
28
- readOnly: boolean;
29
- accountId: string;
30
- bucket: string;
31
- endpoint: string;
32
- publicUrl: string;
33
- baseUrl: string;
34
- accessKeyId: string;
35
- secretAccessKey: string;
36
- }
37
-
38
- export interface SupabaseEnvDetected {
39
- NEXT_PUBLIC_SUPABASE_URL: boolean;
40
- SUPABASE_URL: boolean;
41
- NEXT_PUBLIC_SUPABASE_ANON_KEY: boolean;
42
- SUPABASE_ANON_KEY: boolean;
43
- SUPABASE_SERVICE_ROLE_KEY: boolean;
44
- POSTGRES_URL: boolean;
45
- }
46
-
47
- interface Props {
48
- channel: DeployChannel;
49
- configured: boolean;
50
- writable: boolean;
51
- siteUrl: string;
52
- storagePrefill: StoragePrefill;
53
- /** Which Supabase env vars the running deployment can actually see (read-only channels). */
54
- supabaseEnvDetected: SupabaseEnvDetected;
55
- }
56
-
57
- // Email (SMTP), bot protection, and sign-up policy are no longer collected here — they
58
- // moved to the CMS (Settings → Configuration) and are nudged from the dashboard onboarding
59
- // checklist. A fresh install only needs the database connection, media storage, and the
60
- // first administrator account.
61
- type StepId = 'connection' | 'storage' | 'admin';
62
-
63
- const STEP_TITLES: Record<StepId, string> = {
64
- connection: 'Database connection',
65
- storage: 'Media storage',
66
- admin: 'Administrator account',
67
- };
68
-
69
- const CHANNEL_LABEL: Record<DeployChannel, string> = {
70
- docker: 'Self-hosted Docker',
71
- vercel: 'Vercel',
72
- local: 'Local development',
73
- };
74
-
75
- type Msg = { ok: string } | { err: string } | null;
76
-
77
- export default function SetupWizard({
78
- channel,
79
- configured,
80
- writable,
81
- siteUrl,
82
- storagePrefill,
83
- supabaseEnvDetected,
84
- }: Props) {
85
- const [isPending, startTransition] = useTransition();
86
- const [message, setMessage] = useState<Msg>(null);
87
- const [phase, setPhase] = useState<'form' | 'working' | 'done'>('form');
88
-
89
- // Connection (Profile B / local only).
90
- const [conn, setConn] = useState({
91
- supabaseUrl: '',
92
- anonKey: '',
93
- serviceRoleKey: '',
94
- postgresUrl: '',
95
- accessToken: '',
96
- siteUrl,
97
- });
98
- const [connectionDone, setConnectionDone] = useState(configured);
99
- // "Start from a clean database" — only offered/honored on a local fresh install.
100
- const [resetFirst, setResetFirst] = useState(true);
101
-
102
- // Storage / admin.
103
- const [storage, setStorage] = useState(storagePrefill);
104
- const [admin, setAdmin] = useState({ email: '', password: '', fullName: '' });
105
-
106
- const steps = useMemo<StepId[]>(() => {
107
- const list: StepId[] = [];
108
- if (!configured) {
109
- list.push('connection');
110
- }
111
- // Skip the storage step when there's nothing for the user to configure: one-click Vercel
112
- // deploys use the connected Supabase project with zero keys (native Supabase Storage), and
113
- // the Docker stack ships MinIO already wired up by docker-setup (a read-only prefill).
114
- if (channel !== 'vercel' && !storagePrefill.readOnly) {
115
- list.push('storage');
116
- }
117
- list.push('admin');
118
- return list;
119
- }, [configured, channel, storagePrefill.readOnly]);
120
-
121
- const [stepIndex, setStepIndex] = useState(0);
122
- const current = steps[stepIndex];
123
- const isLast = stepIndex === steps.length - 1;
124
-
125
- const setOk = (ok: string) => setMessage({ ok });
126
- const setErr = (err: string) => setMessage({ err });
127
-
128
- const goNext = () => {
129
- setMessage(null);
130
- setStepIndex((i) => Math.min(i + 1, steps.length - 1));
131
- };
132
- const goBack = () => {
133
- setMessage(null);
134
- setStepIndex((i) => Math.max(i - 1, 0));
135
- };
136
-
137
- // --- Step actions ------------------------------------------------------------
138
-
139
- const handleSaveConnection = () => {
140
- setMessage(null);
141
- if (!conn.accessToken.trim() && !conn.postgresUrl.trim()) {
142
- setErr(
143
- 'Provide a Supabase access token (recommended) or a Postgres connection string so the schema can be applied.',
144
- );
145
- return;
146
- }
147
- startTransition(async () => {
148
- const result = await saveSupabaseConnection({
149
- supabaseUrl: conn.supabaseUrl,
150
- anonKey: conn.anonKey,
151
- serviceRoleKey: conn.serviceRoleKey,
152
- postgresUrl: conn.postgresUrl,
153
- accessToken: conn.accessToken,
154
- siteUrl: conn.siteUrl,
155
- });
156
- if (!result.ok) {
157
- setErr(result.error ?? 'Could not save the connection.');
158
- return;
159
- }
160
- setConnectionDone(true);
161
- setOk('Connection saved. The database schema is applied automatically when you finish.');
162
- goNext();
163
- });
164
- };
165
-
166
- const handleFinish = () => {
167
- if (!admin.email || !admin.password) {
168
- setErr('Enter an administrator email and password.');
169
- return;
170
- }
171
- if (admin.password.length < 8) {
172
- setErr('Use a password of at least 8 characters.');
173
- return;
174
- }
175
-
176
- const envValues: Record<string, string> = {};
177
- if (writable && channel === 'local') {
178
- const put = (k: string, v: string) => {
179
- if (v && v.trim()) envValues[k] = v.trim();
180
- };
181
- put('R2_ACCOUNT_ID', storage.accountId);
182
- put('R2_BUCKET_NAME', storage.bucket);
183
- put('R2_ACCESS_KEY_ID', storage.accessKeyId);
184
- put('R2_SECRET_ACCESS_KEY', storage.secretAccessKey);
185
- // Both must hold the bucket's public read URL: image src is built from
186
- // NEXT_PUBLIC_R2_BASE_URL, while next.config remotePatterns + CSP read
187
- // NEXT_PUBLIC_R2_PUBLIC_URL. The wizard collects one URL and writes it to both
188
- // (baseUrl only differs if a channel prefilled a separate custom domain).
189
- put('NEXT_PUBLIC_R2_PUBLIC_URL', storage.publicUrl);
190
- put('NEXT_PUBLIC_R2_BASE_URL', storage.baseUrl || storage.publicUrl);
191
- }
192
-
193
- setMessage(null);
194
- setPhase('working');
195
- startTransition(async () => {
196
- const result = await completeSetup({
197
- admin,
198
- envValues,
199
- resetFirst: resetFirst && writable,
200
- });
201
-
202
- if (!result.ok) {
203
- setErr(result.error ?? 'Setup failed.');
204
- setPhase('form');
205
- return;
206
- }
207
-
208
- // Establish the session via the canonical sign-in path (reliable cookie), which
209
- // redirects into the CMS. With the runtime public-env injection the client works
210
- // without a dev-server restart.
211
- const signInData = new FormData();
212
- signInData.append('email', admin.email.trim());
213
- signInData.append('password', admin.password);
214
- await signInAction(signInData);
215
-
216
- // signInAction redirects on success (and on failure, to /sign-in with a message),
217
- // so this only runs in the unlikely case it returned without navigating.
218
- setPhase('done');
219
- });
220
- };
221
-
222
- // --- Render ------------------------------------------------------------------
223
-
224
- if (phase === 'working') {
225
- return (
226
- <div className="space-y-6">
227
- <SetupProgress willReset={resetFirst && writable} />
228
- </div>
229
- );
230
- }
231
-
232
- if (phase === 'done') {
233
- return (
234
- <div className="space-y-6">
235
- <SetupDone />
236
- </div>
237
- );
238
- }
239
-
240
- const alert =
241
- message &&
242
- ('ok' in message ? (
243
- <Alert variant="success" className="py-2 px-4">
244
- <AlertDescription>{message.ok}</AlertDescription>
245
- </Alert>
246
- ) : (
247
- <Alert variant="destructive" className="py-2 px-4">
248
- <AlertDescription>{message.err}</AlertDescription>
249
- </Alert>
250
- ));
251
-
252
- return (
253
- <div className="space-y-6">
254
- <div className="space-y-2 text-center">
255
- <h1 className="text-2xl font-semibold">Welcome to NextBlock</h1>
256
- <div className="text-sm text-muted-foreground">
257
- Let&rsquo;s get your CMS running. Detected environment:{' '}
258
- <Badge variant="secondary">{CHANNEL_LABEL[channel]}</Badge>
259
- </div>
260
- </div>
261
-
262
- <Stepper steps={steps} stepIndex={stepIndex} />
263
-
264
- <Card>
265
- <CardHeader>
266
- <CardTitle>{STEP_TITLES[current]}</CardTitle>
267
- <CardDescription>{stepDescription(current, channel)}</CardDescription>
268
- </CardHeader>
269
- <CardContent className="space-y-5">
270
- {alert}
271
-
272
- {current === 'connection' && (
273
- <div className="space-y-4">
274
- <Field label="Supabase URL" htmlFor="supabaseUrl">
275
- <Input
276
- id="supabaseUrl"
277
- placeholder="https://YOUR-PROJECT.supabase.co"
278
- value={conn.supabaseUrl}
279
- onChange={(e) => setConn({ ...conn, supabaseUrl: e.target.value })}
280
- />
281
- </Field>
282
- <Field label="Anon (publishable) key" htmlFor="anonKey">
283
- <Input
284
- id="anonKey"
285
- value={conn.anonKey}
286
- onChange={(e) => setConn({ ...conn, anonKey: e.target.value })}
287
- />
288
- </Field>
289
- <Field label="Service-role (secret) key" htmlFor="serviceRoleKey">
290
- <Input
291
- id="serviceRoleKey"
292
- type="password"
293
- value={conn.serviceRoleKey}
294
- onChange={(e) => setConn({ ...conn, serviceRoleKey: e.target.value })}
295
- />
296
- </Field>
297
- <Field label="Supabase access token" htmlFor="accessToken">
298
- <Input
299
- id="accessToken"
300
- type="password"
301
- placeholder="sbp_… (Account → Access Tokens)"
302
- value={conn.accessToken}
303
- onChange={(e) => setConn({ ...conn, accessToken: e.target.value })}
304
- />
305
- <p className="text-xs text-muted-foreground">
306
- Recommended — lets the wizard apply the database schema over HTTPS (works on any
307
- network, no database host to reach).
308
- </p>
309
- </Field>
310
- <Field label="Postgres connection string (optional)" htmlFor="postgresUrl">
311
- <Input
312
- id="postgresUrl"
313
- placeholder="postgresql://postgres.<ref>:[password]@aws-0-<region>.pooler.supabase.com:5432/postgres"
314
- value={conn.postgresUrl}
315
- onChange={(e) => setConn({ ...conn, postgresUrl: e.target.value })}
316
- />
317
- <p className="text-xs text-muted-foreground">
318
- Fallback used only if no access token is given. Use the <strong>Session pooler</strong>{' '}
319
- string (Supabase → Connect → Session pooler); the &ldquo;direct&rdquo;{' '}
320
- <code>db.&lt;ref&gt;.supabase.co</code> host fails on IPv4-only networks.
321
- </p>
322
- </Field>
323
- <Field label="Public site URL (optional)" htmlFor="siteUrl">
324
- <Input
325
- id="siteUrl"
326
- placeholder="http://localhost:4200"
327
- value={conn.siteUrl}
328
- onChange={(e) => setConn({ ...conn, siteUrl: e.target.value })}
329
- />
330
- </Field>
331
- {!writable && (
332
- <div className="space-y-3 rounded-md border p-4">
333
- <p className="text-sm font-medium">
334
- On {CHANNEL_LABEL[channel]} you don&apos;t fill this in — the database is
335
- connected through your platform&apos;s environment variables (e.g. Vercel&apos;s
336
- Supabase integration).
337
- </p>
338
- <div className="text-xs">
339
- <p className="mb-1 text-muted-foreground">
340
- Supabase variables this deployment can currently see:
341
- </p>
342
- <ul className="space-y-0.5 font-mono">
343
- {(
344
- [
345
- 'NEXT_PUBLIC_SUPABASE_URL',
346
- 'SUPABASE_URL',
347
- 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
348
- 'SUPABASE_ANON_KEY',
349
- 'SUPABASE_SERVICE_ROLE_KEY',
350
- 'POSTGRES_URL',
351
- ] as const
352
- ).map((k) => (
353
- <li key={k}>
354
- {supabaseEnvDetected[k] ? '✅' : '❌'} {k}
355
- </li>
356
- ))}
357
- </ul>
358
- </div>
359
- <Alert className="py-2 px-4">
360
- <AlertDescription className="text-xs">
361
- {supabaseEnvDetected.NEXT_PUBLIC_SUPABASE_URL ||
362
- supabaseEnvDetected.SUPABASE_URL
363
- ? 'Keys detected — reload this page and the database step will be skipped.'
364
- : 'No Supabase keys are visible to this deployment yet. If you just created the database via the Vercel integration, the keys were added AFTER this build — open Vercel → Deployments → ⋯ → Redeploy once, then reload. Env vars only bind on a new deployment.'}
365
- </AlertDescription>
366
- </Alert>
367
- </div>
368
- )}
369
- </div>
370
- )}
371
-
372
- {current === 'storage' && (
373
- <StorageStep storage={storage} setStorage={setStorage} channel={channel} />
374
- )}
375
-
376
- {current === 'admin' && (
377
- <div className="space-y-4">
378
- <Field label="Full name" htmlFor="adminName">
379
- <Input
380
- id="adminName"
381
- value={admin.fullName}
382
- onChange={(e) => setAdmin({ ...admin, fullName: e.target.value })}
383
- />
384
- </Field>
385
- <Field label="Email" htmlFor="adminEmail">
386
- <Input
387
- id="adminEmail"
388
- type="email"
389
- value={admin.email}
390
- onChange={(e) => setAdmin({ ...admin, email: e.target.value })}
391
- />
392
- </Field>
393
- <Field label="Password" htmlFor="adminPassword">
394
- <Input
395
- id="adminPassword"
396
- type="password"
397
- value={admin.password}
398
- onChange={(e) => setAdmin({ ...admin, password: e.target.value })}
399
- />
400
- </Field>
401
- <p className="text-xs text-muted-foreground">
402
- This first account becomes the site administrator, created already-confirmed (no
403
- verification email needed). Finishing also applies the database schema and saved
404
- settings, so it can take up to a minute.
405
- </p>
406
- <Alert className="py-2 px-4">
407
- <AlertDescription className="text-xs">
408
- Next, your dashboard will guide you through finishing setup — branding, copyright,
409
- email (SMTP), payment providers, and bot protection are all configured there, no
410
- environment variables required.
411
- </AlertDescription>
412
- </Alert>
413
-
414
- {writable && (
415
- <label className="flex items-start gap-3 rounded-lg border p-3">
416
- <Checkbox
417
- checked={resetFirst}
418
- onCheckedChange={(c) => setResetFirst(c === true)}
419
- className="mt-1"
420
- />
421
- <span className="text-sm">
422
- <span className="font-medium">Start from a clean database</span>
423
- <span className="block text-xs text-muted-foreground">
424
- Recommended for a fresh install. Wipes any existing tables, migration history,
425
- and users in this Supabase project before installing. Uncheck if this database
426
- already has data you want to keep.
427
- </span>
428
- </span>
429
- </label>
430
- )}
431
- </div>
432
- )}
433
-
434
- <Separator />
435
-
436
- <div className="flex items-center justify-between">
437
- <Button variant="ghost" onClick={goBack} disabled={isPending || stepIndex === 0}>
438
- Back
439
- </Button>
440
-
441
- {current === 'connection' ? (
442
- <Button onClick={handleSaveConnection} disabled={isPending || !writable}>
443
- {isPending ? <Spinner className="mr-2 h-4 w-4 animate-spin" /> : null}
444
- Save &amp; verify
445
- </Button>
446
- ) : isLast ? (
447
- <Button onClick={handleFinish} disabled={isPending}>
448
- {isPending ? <Spinner className="mr-2 h-4 w-4 animate-spin" /> : null}
449
- Finish setup
450
- </Button>
451
- ) : (
452
- <Button onClick={goNext} disabled={!connectionDone && !configured}>
453
- Next
454
- </Button>
455
- )}
456
- </div>
457
- </CardContent>
458
- </Card>
459
- </div>
460
- );
461
- }
462
-
463
- function stepDescription(step: StepId, channel: DeployChannel): string {
464
- switch (step) {
465
- case 'connection':
466
- return 'Connect this instance to your Supabase project.';
467
- case 'storage':
468
- return channel === 'docker'
469
- ? 'Your Docker stack uses MinIO for media storage — already wired up.'
470
- : channel === 'vercel'
471
- ? 'Using Supabase Storage (S3-compatible) for media.'
472
- : 'Bring your own Cloudflare R2 bucket for media storage.';
473
- case 'admin':
474
- return 'Create the first administrator account — the last step. Email, payments, branding, and the rest are configured from your dashboard.';
475
- default:
476
- return '';
477
- }
478
- }
479
-
480
- const PROGRESS_MESSAGES = [
481
- 'Laying the foundation blocks…',
482
- 'Seeding the first blocks…',
483
- 'Stacking a few more blocks…',
484
- 'Teaching the blocks to speak (translations)…',
485
- 'Waiting on some stubborn blocks…',
486
- 'Polishing the blocks until they shine…',
487
- 'Almost there — slotting in the last blocks…',
488
- ];
489
-
490
- function SetupProgress({ willReset }: { willReset: boolean }) {
491
- const messages = willReset
492
- ? ['Wiping the old blocks away…', ...PROGRESS_MESSAGES]
493
- : PROGRESS_MESSAGES;
494
- const [pct, setPct] = useState(8);
495
- const [msgIndex, setMsgIndex] = useState(0);
496
-
497
- useEffect(() => {
498
- // Indeterminate work (one server action) shown as a friendly creeping bar that eases
499
- // toward ~92% and a rotating set of block-themed messages.
500
- const progress = setInterval(() => {
501
- setPct((value) => (value >= 92 ? 92 : value + Math.max(1, Math.round((96 - value) / 14))));
502
- }, 700);
503
- const cycle = setInterval(() => {
504
- setMsgIndex((index) => (index + 1) % messages.length);
505
- }, 2200);
506
- return () => {
507
- clearInterval(progress);
508
- clearInterval(cycle);
509
- };
510
- }, [messages.length]);
511
-
512
- return (
513
- <Card>
514
- <CardHeader>
515
- <CardTitle>Building your NextBlock…</CardTitle>
516
- <CardDescription>
517
- {willReset ? 'Resetting the database, then applying' : 'Applying'} the schema, seeding
518
- content, and creating your account. This can take a minute — hang tight.
519
- </CardDescription>
520
- </CardHeader>
521
- <CardContent className="space-y-4">
522
- <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
523
- <div
524
- className="h-full rounded-full bg-primary transition-all duration-700 ease-out"
525
- style={{ width: `${pct}%` }}
526
- />
527
- </div>
528
- <p className="text-sm text-muted-foreground">{messages[msgIndex]}</p>
529
- </CardContent>
530
- </Card>
531
- );
532
- }
533
-
534
- function SetupDone() {
535
- return (
536
- <Card>
537
- <CardHeader>
538
- <CardTitle>🎉 Setup complete!</CardTitle>
539
- <CardDescription>
540
- Your administrator account is ready and the database is seeded.
541
- </CardDescription>
542
- </CardHeader>
543
- <CardContent>
544
- <Button onClick={() => (window.location.href = '/cms/dashboard')}>Enter your CMS</Button>
545
- </CardContent>
546
- </Card>
547
- );
548
- }
549
-
550
- function Stepper({
551
- steps,
552
- stepIndex,
553
- }: {
554
- steps: StepId[];
555
- stepIndex: number;
556
- }) {
557
- return (
558
- <ol className="flex flex-wrap items-center justify-center gap-2 text-xs">
559
- {steps.map((s, i) => (
560
- <li
561
- key={s}
562
- className={`flex items-center gap-2 rounded-full border px-3 py-1 ${
563
- i === stepIndex
564
- ? 'border-primary text-primary'
565
- : i < stepIndex
566
- ? 'border-muted text-muted-foreground'
567
- : 'border-muted text-muted-foreground/60'
568
- }`}
569
- >
570
- <span className="font-medium">{i + 1}</span>
571
- <span>{STEP_TITLES[s]}</span>
572
- </li>
573
- ))}
574
- </ol>
575
- );
576
- }
577
-
578
- function StorageStep({
579
- storage,
580
- setStorage,
581
- channel,
582
- }: {
583
- storage: StoragePrefill;
584
- setStorage: (s: StoragePrefill) => void;
585
- channel: DeployChannel;
586
- }) {
587
- if (channel === 'docker') {
588
- return (
589
- <div className="space-y-3 text-sm">
590
- <Alert variant="success" className="py-2 px-4">
591
- <AlertDescription>
592
- MinIO is already configured by the Docker setup. Nothing to do here.
593
- </AlertDescription>
594
- </Alert>
595
- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs text-muted-foreground">
596
- <dt>Endpoint</dt>
597
- <dd className="font-mono">{storage.endpoint}</dd>
598
- <dt>Bucket</dt>
599
- <dd className="font-mono">{storage.bucket}</dd>
600
- <dt>Public URL</dt>
601
- <dd className="font-mono">{storage.publicUrl}</dd>
602
- </dl>
603
- </div>
604
- );
605
- }
606
-
607
- return (
608
- <div className="space-y-4">
609
- {channel === 'vercel' && (
610
- <p className="text-xs text-muted-foreground">
611
- Pre-filled for Supabase Storage. Create an S3 access key in your Supabase project
612
- (Storage → S3 connection) and set R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in your Vercel
613
- environment.
614
- </p>
615
- )}
616
- <div className="grid gap-4 sm:grid-cols-2">
617
- <Field label="Account / provider id" htmlFor="r2Account">
618
- <Input
619
- id="r2Account"
620
- value={storage.accountId}
621
- onChange={(e) => setStorage({ ...storage, accountId: e.target.value })}
622
- />
623
- </Field>
624
- <Field label="Bucket" htmlFor="r2Bucket">
625
- <Input
626
- id="r2Bucket"
627
- value={storage.bucket}
628
- onChange={(e) => setStorage({ ...storage, bucket: e.target.value })}
629
- />
630
- </Field>
631
- <Field label="Access key id" htmlFor="r2Access">
632
- <Input
633
- id="r2Access"
634
- value={storage.accessKeyId}
635
- onChange={(e) => setStorage({ ...storage, accessKeyId: e.target.value })}
636
- />
637
- </Field>
638
- <Field label="Secret access key" htmlFor="r2Secret">
639
- <Input
640
- id="r2Secret"
641
- type="password"
642
- value={storage.secretAccessKey}
643
- onChange={(e) => setStorage({ ...storage, secretAccessKey: e.target.value })}
644
- />
645
- </Field>
646
- </div>
647
- <Field label="Public bucket URL" htmlFor="r2Public">
648
- <Input
649
- id="r2Public"
650
- placeholder="https://pub-xxxx.r2.dev"
651
- value={storage.publicUrl}
652
- onChange={(e) => setStorage({ ...storage, publicUrl: e.target.value })}
653
- />
654
- <p className="mt-1 text-xs text-muted-foreground">
655
- Your bucket&apos;s public URL (Cloudflare R2 → your bucket → Public Development URL)
656
- or a custom domain. Used to serve all media on your site.
657
- </p>
658
- </Field>
659
- </div>
660
- );
661
- }
662
-
663
- function Field({
664
- label,
665
- htmlFor,
666
- children,
667
- }: {
668
- label: string;
669
- htmlFor: string;
670
- children: React.ReactNode;
671
- }) {
672
- return (
673
- <div className="space-y-1.5">
674
- <Label htmlFor={htmlFor}>{label}</Label>
675
- {children}
676
- </div>
677
- );
678
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useMemo, useState, useTransition } from 'react';
4
+ import {
5
+ Alert,
6
+ AlertDescription,
7
+ Badge,
8
+ Button,
9
+ Card,
10
+ CardContent,
11
+ CardDescription,
12
+ CardHeader,
13
+ CardTitle,
14
+ Checkbox,
15
+ Input,
16
+ Label,
17
+ Separator,
18
+ Spinner,
19
+ } from '@nextblock-cms/ui';
20
+ import type { DeployChannel } from '../../lib/setup/env-status';
21
+ import { completeSetup, saveSupabaseConnection } from '../../lib/setup/actions';
22
+ import { signInAction } from '../actions';
23
+
24
+ export type StorageKind = 'minio' | 'supabase' | 'r2';
25
+
26
+ export interface StoragePrefill {
27
+ kind: StorageKind;
28
+ readOnly: boolean;
29
+ accountId: string;
30
+ bucket: string;
31
+ endpoint: string;
32
+ publicUrl: string;
33
+ baseUrl: string;
34
+ accessKeyId: string;
35
+ secretAccessKey: string;
36
+ }
37
+
38
+ export interface SupabaseEnvDetected {
39
+ NEXT_PUBLIC_SUPABASE_URL: boolean;
40
+ SUPABASE_URL: boolean;
41
+ NEXT_PUBLIC_SUPABASE_ANON_KEY: boolean;
42
+ SUPABASE_ANON_KEY: boolean;
43
+ SUPABASE_SERVICE_ROLE_KEY: boolean;
44
+ POSTGRES_URL: boolean;
45
+ }
46
+
47
+ interface Props {
48
+ channel: DeployChannel;
49
+ configured: boolean;
50
+ writable: boolean;
51
+ siteUrl: string;
52
+ storagePrefill: StoragePrefill;
53
+ /** Which Supabase env vars the running deployment can actually see (read-only channels). */
54
+ supabaseEnvDetected: SupabaseEnvDetected;
55
+ }
56
+
57
+ // Email (SMTP), bot protection, and sign-up policy are no longer collected here — they
58
+ // moved to the CMS (Settings → Configuration) and are nudged from the dashboard onboarding
59
+ // checklist. A fresh install only needs the database connection, media storage, and the
60
+ // first administrator account.
61
+ type StepId = 'connection' | 'storage' | 'admin';
62
+
63
+ const STEP_TITLES: Record<StepId, string> = {
64
+ connection: 'Database connection',
65
+ storage: 'Media storage',
66
+ admin: 'Administrator account',
67
+ };
68
+
69
+ const CHANNEL_LABEL: Record<DeployChannel, string> = {
70
+ docker: 'Self-hosted Docker',
71
+ vercel: 'Vercel',
72
+ local: 'Local development',
73
+ };
74
+
75
+ type Msg = { ok: string } | { err: string } | null;
76
+
77
+ export default function SetupWizard({
78
+ channel,
79
+ configured,
80
+ writable,
81
+ siteUrl,
82
+ storagePrefill,
83
+ supabaseEnvDetected,
84
+ }: Props) {
85
+ const [isPending, startTransition] = useTransition();
86
+ const [message, setMessage] = useState<Msg>(null);
87
+ const [phase, setPhase] = useState<'form' | 'working' | 'done'>('form');
88
+
89
+ // Connection (Profile B / local only).
90
+ const [conn, setConn] = useState({
91
+ supabaseUrl: '',
92
+ anonKey: '',
93
+ serviceRoleKey: '',
94
+ postgresUrl: '',
95
+ accessToken: '',
96
+ siteUrl,
97
+ });
98
+ const [connectionDone, setConnectionDone] = useState(configured);
99
+ // "Start from a clean database" — only offered/honored on a local fresh install.
100
+ const [resetFirst, setResetFirst] = useState(true);
101
+
102
+ // Storage / admin.
103
+ const [storage, setStorage] = useState(storagePrefill);
104
+ const [admin, setAdmin] = useState({ email: '', password: '', fullName: '' });
105
+
106
+ const steps = useMemo<StepId[]>(() => {
107
+ const list: StepId[] = [];
108
+ if (!configured) {
109
+ list.push('connection');
110
+ }
111
+ // Skip the storage step when there's nothing for the user to configure: one-click Vercel
112
+ // deploys use the connected Supabase project with zero keys (native Supabase Storage), and
113
+ // the Docker stack ships MinIO already wired up by docker-setup (a read-only prefill).
114
+ if (channel !== 'vercel' && !storagePrefill.readOnly) {
115
+ list.push('storage');
116
+ }
117
+ list.push('admin');
118
+ return list;
119
+ }, [configured, channel, storagePrefill.readOnly]);
120
+
121
+ const [stepIndex, setStepIndex] = useState(0);
122
+ const current = steps[stepIndex];
123
+ const isLast = stepIndex === steps.length - 1;
124
+
125
+ const setOk = (ok: string) => setMessage({ ok });
126
+ const setErr = (err: string) => setMessage({ err });
127
+
128
+ const goNext = () => {
129
+ setMessage(null);
130
+ setStepIndex((i) => Math.min(i + 1, steps.length - 1));
131
+ };
132
+ const goBack = () => {
133
+ setMessage(null);
134
+ setStepIndex((i) => Math.max(i - 1, 0));
135
+ };
136
+
137
+ // --- Step actions ------------------------------------------------------------
138
+
139
+ const handleSaveConnection = () => {
140
+ setMessage(null);
141
+ if (!conn.accessToken.trim() && !conn.postgresUrl.trim()) {
142
+ setErr(
143
+ 'Provide a Supabase access token (recommended) or a Postgres connection string so the schema can be applied.',
144
+ );
145
+ return;
146
+ }
147
+ startTransition(async () => {
148
+ const result = await saveSupabaseConnection({
149
+ supabaseUrl: conn.supabaseUrl,
150
+ anonKey: conn.anonKey,
151
+ serviceRoleKey: conn.serviceRoleKey,
152
+ postgresUrl: conn.postgresUrl,
153
+ accessToken: conn.accessToken,
154
+ siteUrl: conn.siteUrl,
155
+ });
156
+ if (!result.ok) {
157
+ setErr(result.error ?? 'Could not save the connection.');
158
+ return;
159
+ }
160
+ setConnectionDone(true);
161
+ setOk('Connection saved. The database schema is applied automatically when you finish.');
162
+ goNext();
163
+ });
164
+ };
165
+
166
+ const handleFinish = () => {
167
+ if (!admin.email || !admin.password) {
168
+ setErr('Enter an administrator email and password.');
169
+ return;
170
+ }
171
+ if (admin.password.length < 8) {
172
+ setErr('Use a password of at least 8 characters.');
173
+ return;
174
+ }
175
+
176
+ const envValues: Record<string, string> = {};
177
+ if (writable && channel === 'local') {
178
+ const put = (k: string, v: string) => {
179
+ if (v && v.trim()) envValues[k] = v.trim();
180
+ };
181
+ put('R2_ACCOUNT_ID', storage.accountId);
182
+ put('R2_BUCKET_NAME', storage.bucket);
183
+ put('R2_ACCESS_KEY_ID', storage.accessKeyId);
184
+ put('R2_SECRET_ACCESS_KEY', storage.secretAccessKey);
185
+ // Both must hold the bucket's public read URL: image src is built from
186
+ // NEXT_PUBLIC_R2_BASE_URL, while next.config remotePatterns + CSP read
187
+ // NEXT_PUBLIC_R2_PUBLIC_URL. The wizard collects one URL and writes it to both
188
+ // (baseUrl only differs if a channel prefilled a separate custom domain).
189
+ put('NEXT_PUBLIC_R2_PUBLIC_URL', storage.publicUrl);
190
+ put('NEXT_PUBLIC_R2_BASE_URL', storage.baseUrl || storage.publicUrl);
191
+ }
192
+
193
+ setMessage(null);
194
+ setPhase('working');
195
+ startTransition(async () => {
196
+ const result = await completeSetup({
197
+ admin,
198
+ envValues,
199
+ resetFirst: resetFirst && writable,
200
+ });
201
+
202
+ if (!result.ok) {
203
+ setErr(result.error ?? 'Setup failed.');
204
+ setPhase('form');
205
+ return;
206
+ }
207
+
208
+ // Establish the session via the canonical sign-in path (reliable cookie), which
209
+ // redirects into the CMS. With the runtime public-env injection the client works
210
+ // without a dev-server restart.
211
+ const signInData = new FormData();
212
+ signInData.append('email', admin.email.trim());
213
+ signInData.append('password', admin.password);
214
+ await signInAction(signInData);
215
+
216
+ // signInAction redirects on success (and on failure, to /sign-in with a message),
217
+ // so this only runs in the unlikely case it returned without navigating.
218
+ setPhase('done');
219
+ });
220
+ };
221
+
222
+ // --- Render ------------------------------------------------------------------
223
+
224
+ if (phase === 'working') {
225
+ return (
226
+ <div className="space-y-6">
227
+ <SetupProgress willReset={resetFirst && writable} />
228
+ </div>
229
+ );
230
+ }
231
+
232
+ if (phase === 'done') {
233
+ return (
234
+ <div className="space-y-6">
235
+ <SetupDone />
236
+ </div>
237
+ );
238
+ }
239
+
240
+ const alert =
241
+ message &&
242
+ ('ok' in message ? (
243
+ <Alert variant="success" className="py-2 px-4">
244
+ <AlertDescription>{message.ok}</AlertDescription>
245
+ </Alert>
246
+ ) : (
247
+ <Alert variant="destructive" className="py-2 px-4">
248
+ <AlertDescription>{message.err}</AlertDescription>
249
+ </Alert>
250
+ ));
251
+
252
+ return (
253
+ <div className="space-y-6">
254
+ <div className="space-y-2 text-center">
255
+ <h1 className="text-2xl font-semibold">Welcome to NextBlock</h1>
256
+ <div className="text-sm text-muted-foreground">
257
+ Let&rsquo;s get your CMS running. Detected environment:{' '}
258
+ <Badge variant="secondary">{CHANNEL_LABEL[channel]}</Badge>
259
+ </div>
260
+ </div>
261
+
262
+ <Stepper steps={steps} stepIndex={stepIndex} />
263
+
264
+ <Card>
265
+ <CardHeader>
266
+ <CardTitle>{STEP_TITLES[current]}</CardTitle>
267
+ <CardDescription>{stepDescription(current, channel)}</CardDescription>
268
+ </CardHeader>
269
+ <CardContent className="space-y-5">
270
+ {alert}
271
+
272
+ {current === 'connection' && (
273
+ <div className="space-y-4">
274
+ <Field label="Supabase URL" htmlFor="supabaseUrl">
275
+ <Input
276
+ id="supabaseUrl"
277
+ placeholder="https://YOUR-PROJECT.supabase.co"
278
+ value={conn.supabaseUrl}
279
+ onChange={(e) => setConn({ ...conn, supabaseUrl: e.target.value })}
280
+ />
281
+ </Field>
282
+ <Field label="Anon (publishable) key" htmlFor="anonKey">
283
+ <Input
284
+ id="anonKey"
285
+ value={conn.anonKey}
286
+ onChange={(e) => setConn({ ...conn, anonKey: e.target.value })}
287
+ />
288
+ </Field>
289
+ <Field label="Service-role (secret) key" htmlFor="serviceRoleKey">
290
+ <Input
291
+ id="serviceRoleKey"
292
+ type="password"
293
+ value={conn.serviceRoleKey}
294
+ onChange={(e) => setConn({ ...conn, serviceRoleKey: e.target.value })}
295
+ />
296
+ </Field>
297
+ <Field label="Supabase access token" htmlFor="accessToken">
298
+ <Input
299
+ id="accessToken"
300
+ type="password"
301
+ placeholder="sbp_… (Account → Access Tokens)"
302
+ value={conn.accessToken}
303
+ onChange={(e) => setConn({ ...conn, accessToken: e.target.value })}
304
+ />
305
+ <p className="text-xs text-muted-foreground">
306
+ Recommended — lets the wizard apply the database schema over HTTPS (works on any
307
+ network, no database host to reach).
308
+ </p>
309
+ </Field>
310
+ <Field label="Postgres connection string (optional)" htmlFor="postgresUrl">
311
+ <Input
312
+ id="postgresUrl"
313
+ placeholder="postgresql://postgres.<ref>:[password]@aws-0-<region>.pooler.supabase.com:5432/postgres"
314
+ value={conn.postgresUrl}
315
+ onChange={(e) => setConn({ ...conn, postgresUrl: e.target.value })}
316
+ />
317
+ <p className="text-xs text-muted-foreground">
318
+ Fallback used only if no access token is given. Use the <strong>Session pooler</strong>{' '}
319
+ string (Supabase → Connect → Session pooler); the &ldquo;direct&rdquo;{' '}
320
+ <code>db.&lt;ref&gt;.supabase.co</code> host fails on IPv4-only networks.
321
+ </p>
322
+ </Field>
323
+ <Field label="Public site URL (optional)" htmlFor="siteUrl">
324
+ <Input
325
+ id="siteUrl"
326
+ placeholder="http://localhost:4200"
327
+ value={conn.siteUrl}
328
+ onChange={(e) => setConn({ ...conn, siteUrl: e.target.value })}
329
+ />
330
+ </Field>
331
+ {!writable && (
332
+ <div className="space-y-3 rounded-md border p-4">
333
+ <p className="text-sm font-medium">
334
+ On {CHANNEL_LABEL[channel]} you don&apos;t fill this in — the database is
335
+ connected through your platform&apos;s environment variables (e.g. Vercel&apos;s
336
+ Supabase integration).
337
+ </p>
338
+ <div className="text-xs">
339
+ <p className="mb-1 text-muted-foreground">
340
+ Supabase variables this deployment can currently see:
341
+ </p>
342
+ <ul className="space-y-0.5 font-mono">
343
+ {(
344
+ [
345
+ 'NEXT_PUBLIC_SUPABASE_URL',
346
+ 'SUPABASE_URL',
347
+ 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
348
+ 'SUPABASE_ANON_KEY',
349
+ 'SUPABASE_SERVICE_ROLE_KEY',
350
+ 'POSTGRES_URL',
351
+ ] as const
352
+ ).map((k) => (
353
+ <li key={k}>
354
+ {supabaseEnvDetected[k] ? '✅' : '❌'} {k}
355
+ </li>
356
+ ))}
357
+ </ul>
358
+ </div>
359
+ <Alert className="py-2 px-4">
360
+ <AlertDescription className="text-xs">
361
+ {supabaseEnvDetected.NEXT_PUBLIC_SUPABASE_URL ||
362
+ supabaseEnvDetected.SUPABASE_URL
363
+ ? 'Keys detected — reload this page and the database step will be skipped.'
364
+ : 'No Supabase keys are visible to this deployment yet. If you just created the database via the Vercel integration, the keys were added AFTER this build — open Vercel → Deployments → ⋯ → Redeploy once, then reload. Env vars only bind on a new deployment.'}
365
+ </AlertDescription>
366
+ </Alert>
367
+ </div>
368
+ )}
369
+ </div>
370
+ )}
371
+
372
+ {current === 'storage' && (
373
+ <StorageStep storage={storage} setStorage={setStorage} channel={channel} />
374
+ )}
375
+
376
+ {current === 'admin' && (
377
+ <div className="space-y-4">
378
+ <Field label="Full name" htmlFor="adminName">
379
+ <Input
380
+ id="adminName"
381
+ value={admin.fullName}
382
+ onChange={(e) => setAdmin({ ...admin, fullName: e.target.value })}
383
+ />
384
+ </Field>
385
+ <Field label="Email" htmlFor="adminEmail">
386
+ <Input
387
+ id="adminEmail"
388
+ type="email"
389
+ value={admin.email}
390
+ onChange={(e) => setAdmin({ ...admin, email: e.target.value })}
391
+ />
392
+ </Field>
393
+ <Field label="Password" htmlFor="adminPassword">
394
+ <Input
395
+ id="adminPassword"
396
+ type="password"
397
+ value={admin.password}
398
+ onChange={(e) => setAdmin({ ...admin, password: e.target.value })}
399
+ />
400
+ </Field>
401
+ <p className="text-xs text-muted-foreground">
402
+ This first account becomes the site administrator, created already-confirmed (no
403
+ verification email needed). Finishing also applies the database schema and saved
404
+ settings, so it can take up to a minute.
405
+ </p>
406
+ <Alert className="py-2 px-4">
407
+ <AlertDescription className="text-xs">
408
+ Next, your dashboard will guide you through finishing setup — branding, copyright,
409
+ email (SMTP), payment providers, and bot protection are all configured there, no
410
+ environment variables required.
411
+ </AlertDescription>
412
+ </Alert>
413
+
414
+ {writable && (
415
+ <label className="flex items-start gap-3 rounded-lg border p-3">
416
+ <Checkbox
417
+ checked={resetFirst}
418
+ onCheckedChange={(c) => setResetFirst(c === true)}
419
+ className="mt-1"
420
+ />
421
+ <span className="text-sm">
422
+ <span className="font-medium">Start from a clean database</span>
423
+ <span className="block text-xs text-muted-foreground">
424
+ Recommended for a fresh install. Wipes any existing tables, migration history,
425
+ and users in this Supabase project before installing. Uncheck if this database
426
+ already has data you want to keep.
427
+ </span>
428
+ </span>
429
+ </label>
430
+ )}
431
+ </div>
432
+ )}
433
+
434
+ <Separator />
435
+
436
+ <div className="flex items-center justify-between">
437
+ <Button variant="ghost" onClick={goBack} disabled={isPending || stepIndex === 0}>
438
+ Back
439
+ </Button>
440
+
441
+ {current === 'connection' ? (
442
+ <Button onClick={handleSaveConnection} disabled={isPending || !writable}>
443
+ {isPending ? <Spinner className="mr-2 h-4 w-4 animate-spin" /> : null}
444
+ Save &amp; verify
445
+ </Button>
446
+ ) : isLast ? (
447
+ <Button onClick={handleFinish} disabled={isPending}>
448
+ {isPending ? <Spinner className="mr-2 h-4 w-4 animate-spin" /> : null}
449
+ Finish setup
450
+ </Button>
451
+ ) : (
452
+ <Button onClick={goNext} disabled={!connectionDone && !configured}>
453
+ Next
454
+ </Button>
455
+ )}
456
+ </div>
457
+ </CardContent>
458
+ </Card>
459
+ </div>
460
+ );
461
+ }
462
+
463
+ function stepDescription(step: StepId, channel: DeployChannel): string {
464
+ switch (step) {
465
+ case 'connection':
466
+ return 'Connect this instance to your Supabase project.';
467
+ case 'storage':
468
+ return channel === 'docker'
469
+ ? 'Your Docker stack uses MinIO for media storage — already wired up.'
470
+ : channel === 'vercel'
471
+ ? 'Using Supabase Storage (S3-compatible) for media.'
472
+ : 'Bring your own Cloudflare R2 bucket for media storage.';
473
+ case 'admin':
474
+ return 'Create the first administrator account — the last step. Email, payments, branding, and the rest are configured from your dashboard.';
475
+ default:
476
+ return '';
477
+ }
478
+ }
479
+
480
+ const PROGRESS_MESSAGES = [
481
+ 'Laying the foundation blocks…',
482
+ 'Seeding the first blocks…',
483
+ 'Stacking a few more blocks…',
484
+ 'Teaching the blocks to speak (translations)…',
485
+ 'Waiting on some stubborn blocks…',
486
+ 'Polishing the blocks until they shine…',
487
+ 'Almost there — slotting in the last blocks…',
488
+ ];
489
+
490
+ function SetupProgress({ willReset }: { willReset: boolean }) {
491
+ const messages = willReset
492
+ ? ['Wiping the old blocks away…', ...PROGRESS_MESSAGES]
493
+ : PROGRESS_MESSAGES;
494
+ const [pct, setPct] = useState(8);
495
+ const [msgIndex, setMsgIndex] = useState(0);
496
+
497
+ useEffect(() => {
498
+ // Indeterminate work (one server action) shown as a friendly creeping bar that eases
499
+ // toward ~92% and a rotating set of block-themed messages.
500
+ const progress = setInterval(() => {
501
+ setPct((value) => (value >= 92 ? 92 : value + Math.max(1, Math.round((96 - value) / 14))));
502
+ }, 700);
503
+ const cycle = setInterval(() => {
504
+ setMsgIndex((index) => (index + 1) % messages.length);
505
+ }, 2200);
506
+ return () => {
507
+ clearInterval(progress);
508
+ clearInterval(cycle);
509
+ };
510
+ }, [messages.length]);
511
+
512
+ return (
513
+ <Card>
514
+ <CardHeader>
515
+ <CardTitle>Building your NextBlock…</CardTitle>
516
+ <CardDescription>
517
+ {willReset ? 'Resetting the database, then applying' : 'Applying'} the schema, seeding
518
+ content, and creating your account. This can take a minute — hang tight.
519
+ </CardDescription>
520
+ </CardHeader>
521
+ <CardContent className="space-y-4">
522
+ <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
523
+ <div
524
+ className="h-full rounded-full bg-primary transition-all duration-700 ease-out"
525
+ style={{ width: `${pct}%` }}
526
+ />
527
+ </div>
528
+ <p className="text-sm text-muted-foreground">{messages[msgIndex]}</p>
529
+ </CardContent>
530
+ </Card>
531
+ );
532
+ }
533
+
534
+ function SetupDone() {
535
+ return (
536
+ <Card>
537
+ <CardHeader>
538
+ <CardTitle>🎉 Setup complete!</CardTitle>
539
+ <CardDescription>
540
+ Your administrator account is ready and the database is seeded.
541
+ </CardDescription>
542
+ </CardHeader>
543
+ <CardContent>
544
+ <Button onClick={() => (window.location.href = '/cms/dashboard')}>Enter your CMS</Button>
545
+ </CardContent>
546
+ </Card>
547
+ );
548
+ }
549
+
550
+ function Stepper({
551
+ steps,
552
+ stepIndex,
553
+ }: {
554
+ steps: StepId[];
555
+ stepIndex: number;
556
+ }) {
557
+ return (
558
+ <ol className="flex flex-wrap items-center justify-center gap-2 text-xs">
559
+ {steps.map((s, i) => (
560
+ <li
561
+ key={s}
562
+ className={`flex items-center gap-2 rounded-full border px-3 py-1 ${
563
+ i === stepIndex
564
+ ? 'border-primary text-primary'
565
+ : i < stepIndex
566
+ ? 'border-muted text-muted-foreground'
567
+ : 'border-muted text-muted-foreground/60'
568
+ }`}
569
+ >
570
+ <span className="font-medium">{i + 1}</span>
571
+ <span>{STEP_TITLES[s]}</span>
572
+ </li>
573
+ ))}
574
+ </ol>
575
+ );
576
+ }
577
+
578
+ function StorageStep({
579
+ storage,
580
+ setStorage,
581
+ channel,
582
+ }: {
583
+ storage: StoragePrefill;
584
+ setStorage: (s: StoragePrefill) => void;
585
+ channel: DeployChannel;
586
+ }) {
587
+ if (channel === 'docker') {
588
+ return (
589
+ <div className="space-y-3 text-sm">
590
+ <Alert variant="success" className="py-2 px-4">
591
+ <AlertDescription>
592
+ MinIO is already configured by the Docker setup. Nothing to do here.
593
+ </AlertDescription>
594
+ </Alert>
595
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs text-muted-foreground">
596
+ <dt>Endpoint</dt>
597
+ <dd className="font-mono">{storage.endpoint}</dd>
598
+ <dt>Bucket</dt>
599
+ <dd className="font-mono">{storage.bucket}</dd>
600
+ <dt>Public URL</dt>
601
+ <dd className="font-mono">{storage.publicUrl}</dd>
602
+ </dl>
603
+ </div>
604
+ );
605
+ }
606
+
607
+ return (
608
+ <div className="space-y-4">
609
+ {channel === 'vercel' && (
610
+ <p className="text-xs text-muted-foreground">
611
+ Pre-filled for Supabase Storage. Create an S3 access key in your Supabase project
612
+ (Storage → S3 connection) and set R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in your Vercel
613
+ environment.
614
+ </p>
615
+ )}
616
+ <div className="grid gap-4 sm:grid-cols-2">
617
+ <Field label="Account / provider id" htmlFor="r2Account">
618
+ <Input
619
+ id="r2Account"
620
+ value={storage.accountId}
621
+ onChange={(e) => setStorage({ ...storage, accountId: e.target.value })}
622
+ />
623
+ </Field>
624
+ <Field label="Bucket" htmlFor="r2Bucket">
625
+ <Input
626
+ id="r2Bucket"
627
+ value={storage.bucket}
628
+ onChange={(e) => setStorage({ ...storage, bucket: e.target.value })}
629
+ />
630
+ </Field>
631
+ <Field label="Access key id" htmlFor="r2Access">
632
+ <Input
633
+ id="r2Access"
634
+ value={storage.accessKeyId}
635
+ onChange={(e) => setStorage({ ...storage, accessKeyId: e.target.value })}
636
+ />
637
+ </Field>
638
+ <Field label="Secret access key" htmlFor="r2Secret">
639
+ <Input
640
+ id="r2Secret"
641
+ type="password"
642
+ value={storage.secretAccessKey}
643
+ onChange={(e) => setStorage({ ...storage, secretAccessKey: e.target.value })}
644
+ />
645
+ </Field>
646
+ </div>
647
+ <Field label="Public bucket URL" htmlFor="r2Public">
648
+ <Input
649
+ id="r2Public"
650
+ placeholder="https://pub-xxxx.r2.dev"
651
+ value={storage.publicUrl}
652
+ onChange={(e) => setStorage({ ...storage, publicUrl: e.target.value })}
653
+ />
654
+ <p className="mt-1 text-xs text-muted-foreground">
655
+ Your bucket&apos;s public URL (Cloudflare R2 → your bucket → Public Development URL)
656
+ or a custom domain. Used to serve all media on your site.
657
+ </p>
658
+ </Field>
659
+ </div>
660
+ );
661
+ }
662
+
663
+ function Field({
664
+ label,
665
+ htmlFor,
666
+ children,
667
+ }: {
668
+ label: string;
669
+ htmlFor: string;
670
+ children: React.ReactNode;
671
+ }) {
672
+ return (
673
+ <div className="space-y-1.5">
674
+ <Label htmlFor={htmlFor}>{label}</Label>
675
+ {children}
676
+ </div>
677
+ );
678
+ }