create-usebecky 0.0.0-stage → 0.2.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 (157) hide show
  1. package/README.md +80 -2
  2. package/dist/create.js +842 -0
  3. package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
  4. package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
  5. package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
  6. package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
  7. package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  8. package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
  9. package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  10. package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
  11. package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
  12. package/dist/index.js +10 -0
  13. package/dist/keys.js +72 -0
  14. package/dist/platform.js +104 -0
  15. package/dist/pm.js +69 -0
  16. package/dist/prompts.js +242 -0
  17. package/dist/scaffold.js +108 -0
  18. package/dist/setup.js +130 -0
  19. package/dist/shared/ai.js +203 -0
  20. package/dist/shared/extension-skill.js +107 -0
  21. package/dist/shared/framework.js +460 -0
  22. package/dist/shared/hosted.js +8 -0
  23. package/dist/shared/ui.js +141 -0
  24. package/dist/skill/usebecky/SKILL.md +339 -0
  25. package/dist/skill/usebecky/references/access-rules.md +307 -0
  26. package/dist/skill/usebecky/references/addons.md +68 -0
  27. package/dist/skill/usebecky/references/analytics.md +166 -0
  28. package/dist/skill/usebecky/references/android.md +434 -0
  29. package/dist/skill/usebecky/references/auth.md +379 -0
  30. package/dist/skill/usebecky/references/cache.md +51 -0
  31. package/dist/skill/usebecky/references/components.md +127 -0
  32. package/dist/skill/usebecky/references/emails.md +105 -0
  33. package/dist/skill/usebecky/references/expo.md +147 -0
  34. package/dist/skill/usebecky/references/functions.md +99 -0
  35. package/dist/skill/usebecky/references/hosting.md +119 -0
  36. package/dist/skill/usebecky/references/http-api.md +233 -0
  37. package/dist/skill/usebecky/references/ios.md +355 -0
  38. package/dist/skill/usebecky/references/payments.md +493 -0
  39. package/dist/skill/usebecky/references/realtime.md +143 -0
  40. package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
  41. package/dist/skill/usebecky/references/sdk.md +838 -0
  42. package/dist/skill/usebecky/references/storage.md +210 -0
  43. package/dist/skill/usebecky/references/templates.md +191 -0
  44. package/dist/skill/usebecky/references/wordpress.md +87 -0
  45. package/dist/templates.js +74 -0
  46. package/package.json +37 -4
  47. package/templates/expo/App.tsx +48 -0
  48. package/templates/expo/README.md +59 -0
  49. package/templates/expo/_env.example +4 -0
  50. package/templates/expo/_gitignore +12 -0
  51. package/templates/expo/app.json +25 -0
  52. package/templates/expo/assets/icon.png +0 -0
  53. package/templates/expo/brand.ts +7 -0
  54. package/templates/expo/components/Avatar.tsx +75 -0
  55. package/templates/expo/components/ui.tsx +57 -0
  56. package/templates/expo/index.ts +4 -0
  57. package/templates/expo/lib/theme.ts +43 -0
  58. package/templates/expo/lib/usebecky.ts +15 -0
  59. package/templates/expo/package.json +29 -0
  60. package/templates/expo/screens/Home.tsx +187 -0
  61. package/templates/expo/screens/SignIn.tsx +112 -0
  62. package/templates/expo/tsconfig.json +6 -0
  63. package/templates/expo/usebecky.template.json +36 -0
  64. package/templates/extension/README.md +128 -0
  65. package/templates/extension/_env.example +21 -0
  66. package/templates/extension/_gitignore +11 -0
  67. package/templates/extension/logo.svg +1 -0
  68. package/templates/extension/package.json +25 -0
  69. package/templates/extension/src/accounts.ts +90 -0
  70. package/templates/extension/src/app.ts +178 -0
  71. package/templates/extension/src/pages.ts +108 -0
  72. package/templates/extension/src/replay-guard.ts +17 -0
  73. package/templates/extension/src/server.ts +57 -0
  74. package/templates/extension/src/settings.ts +69 -0
  75. package/templates/extension/src/ui.ts +70 -0
  76. package/templates/extension/test/app.test.ts +222 -0
  77. package/templates/extension/tsconfig.json +16 -0
  78. package/templates/extension/usebecky-extension.json +36 -0
  79. package/templates/extension/usebecky.template.json +22 -0
  80. package/templates/landing/README.md +43 -0
  81. package/templates/landing/_env.example +4 -0
  82. package/templates/landing/_gitignore +9 -0
  83. package/templates/landing/index.html +16 -0
  84. package/templates/landing/package.json +28 -0
  85. package/templates/landing/public/icon.svg +1 -0
  86. package/templates/landing/src/App.tsx +97 -0
  87. package/templates/landing/src/components/Contact.tsx +43 -0
  88. package/templates/landing/src/components/Counter.tsx +34 -0
  89. package/templates/landing/src/components/Feedback.tsx +36 -0
  90. package/templates/landing/src/components/Logo.tsx +11 -0
  91. package/templates/landing/src/components/Receipt.tsx +128 -0
  92. package/templates/landing/src/components/Setup.tsx +20 -0
  93. package/templates/landing/src/components/fields.tsx +63 -0
  94. package/templates/landing/src/content.ts +22 -0
  95. package/templates/landing/src/index.css +119 -0
  96. package/templates/landing/src/lib/usebecky.ts +11 -0
  97. package/templates/landing/src/lib/waitlist.ts +46 -0
  98. package/templates/landing/src/main.tsx +12 -0
  99. package/templates/landing/src/vite-env.d.ts +6 -0
  100. package/templates/landing/tsconfig.json +19 -0
  101. package/templates/landing/usebecky.template.json +20 -0
  102. package/templates/landing/vite.config.ts +10 -0
  103. package/templates/notes/README.md +68 -0
  104. package/templates/notes/_env.example +4 -0
  105. package/templates/notes/_gitignore +9 -0
  106. package/templates/notes/index.html +15 -0
  107. package/templates/notes/package.json +28 -0
  108. package/templates/notes/public/icon.svg +1 -0
  109. package/templates/notes/src/App.tsx +35 -0
  110. package/templates/notes/src/brand.ts +7 -0
  111. package/templates/notes/src/components/Composer.tsx +113 -0
  112. package/templates/notes/src/components/NoteEntry.tsx +151 -0
  113. package/templates/notes/src/components/Notes.tsx +163 -0
  114. package/templates/notes/src/components/Setup.tsx +44 -0
  115. package/templates/notes/src/components/SignIn.tsx +112 -0
  116. package/templates/notes/src/components/icons.tsx +54 -0
  117. package/templates/notes/src/index.css +105 -0
  118. package/templates/notes/src/lib/notes.ts +68 -0
  119. package/templates/notes/src/lib/usebecky.ts +9 -0
  120. package/templates/notes/src/main.tsx +22 -0
  121. package/templates/notes/src/vite-env.d.ts +6 -0
  122. package/templates/notes/tsconfig.json +19 -0
  123. package/templates/notes/usebecky.template.json +34 -0
  124. package/templates/notes/vite.config.ts +10 -0
  125. package/templates/saas/README.md +69 -0
  126. package/templates/saas/_env.example +10 -0
  127. package/templates/saas/_gitignore +11 -0
  128. package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
  129. package/templates/saas/app/(app)/account/page.tsx +71 -0
  130. package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
  131. package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
  132. package/templates/saas/app/(app)/layout.tsx +29 -0
  133. package/templates/saas/app/(app)/premium/page.tsx +62 -0
  134. package/templates/saas/app/auth/callback/page.tsx +33 -0
  135. package/templates/saas/app/globals.css +143 -0
  136. package/templates/saas/app/icon.svg +1 -0
  137. package/templates/saas/app/layout.tsx +20 -0
  138. package/templates/saas/app/page.tsx +87 -0
  139. package/templates/saas/app/pricing/Plans.tsx +133 -0
  140. package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
  141. package/templates/saas/app/pricing/page.tsx +21 -0
  142. package/templates/saas/app/setup/page.tsx +34 -0
  143. package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
  144. package/templates/saas/app/sign-in/page.tsx +21 -0
  145. package/templates/saas/brand.ts +10 -0
  146. package/templates/saas/components/AppNav.tsx +45 -0
  147. package/templates/saas/components/Logo.tsx +22 -0
  148. package/templates/saas/components/SiteHeader.tsx +50 -0
  149. package/templates/saas/components/Status.tsx +15 -0
  150. package/templates/saas/lib/session.ts +26 -0
  151. package/templates/saas/lib/usebecky.ts +11 -0
  152. package/templates/saas/next-env.d.ts +5 -0
  153. package/templates/saas/next.config.ts +5 -0
  154. package/templates/saas/package.json +26 -0
  155. package/templates/saas/postcss.config.mjs +3 -0
  156. package/templates/saas/tsconfig.json +21 -0
  157. package/templates/saas/usebecky.template.json +31 -0
@@ -0,0 +1,68 @@
1
+ // Everything the app does with notes and their images, in one place.
2
+ // Tutorial: docs/guide/tutorial/1-notes-app.md (notes) and 2-file-uploads.md (images).
3
+ import { baas } from './usebecky'
4
+
5
+ /** The private bucket for images. Each user can only use the folder named after their user id. */
6
+ export const BUCKET = 'attachments'
7
+ export const COLUMNS = 'id, user_id, title, body, image_path, created_at'
8
+
9
+ export type Note = {
10
+ id: string
11
+ user_id: string
12
+ title: string
13
+ body: string | null
14
+ image_path: string | null
15
+ created_at: string
16
+ }
17
+
18
+ /** The signed-in user's notes, newest first. Access rules make sure nobody sees anyone else's. */
19
+ export function listNotes() {
20
+ return baas.from('notes').select(COLUMNS).order('created_at', { ascending: false }).returns<Note[]>()
21
+ }
22
+
23
+ export function addNote(values: { title: string; body: string; image_path: string | null }) {
24
+ return baas.from('notes').insert(values).select(COLUMNS).returns<Note[]>().single()
25
+ }
26
+
27
+ export function updateNote(id: string, values: Partial<Pick<Note, 'title' | 'body' | 'image_path'>>) {
28
+ return baas.from('notes').update(values).eq('id', id).select(COLUMNS).returns<Note[]>().single()
29
+ }
30
+
31
+ export function deleteNote(id: string) {
32
+ return baas.from('notes').delete().eq('id', id)
33
+ }
34
+
35
+ /** Upload an image into the user's own folder: "<user id>/<random>-<file name>". */
36
+ export async function uploadImage(userId: string, file: File) {
37
+ const safeName = file.name.toLowerCase().replace(/[^a-z0-9.]+/g, '-').slice(-60)
38
+ const path = `${userId}/${crypto.randomUUID().slice(0, 8)}-${safeName}`
39
+ const { error } = await baas.storage.from(BUCKET).upload(path, file, { contentType: file.type })
40
+ return error ? { path: null, error } : { path, error: null }
41
+ }
42
+
43
+ export function removeImage(path: string) {
44
+ return baas.storage.from(BUCKET).remove([path])
45
+ }
46
+
47
+ /** A link to a private image that works for one hour. */
48
+ export function imageUrl(path: string) {
49
+ return baas.storage.from(BUCKET).createSignedUrl(path, 60 * 60)
50
+ }
51
+
52
+ /** Put a note into a list: replace it if it is there, otherwise add it at the top. */
53
+ export function upsert(list: Note[], note: Note): Note[] {
54
+ if (list.some((n) => n.id === note.id)) return list.map((n) => (n.id === note.id ? note : n))
55
+ return [note, ...list]
56
+ }
57
+
58
+ const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
59
+ /** "just now", "5 minutes ago", "yesterday", then a date. */
60
+ export function timeAgo(iso: string): string {
61
+ const seconds = (new Date(iso).getTime() - Date.now()) / 1000
62
+ const abs = Math.abs(seconds)
63
+ if (abs < 45) return 'just now'
64
+ if (abs < 3600) return rtf.format(Math.round(seconds / 60), 'minute')
65
+ if (abs < 86400) return rtf.format(Math.round(seconds / 3600), 'hour')
66
+ if (abs < 86400 * 6) return rtf.format(Math.round(seconds / 86400), 'day')
67
+ return new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: abs > 86400 * 300 ? 'numeric' : undefined })
68
+ }
@@ -0,0 +1,9 @@
1
+ // Your usebecky client. Every file that talks to the backend imports it from here.
2
+ // Vite reads the two values from .env.local (only names that start with VITE_ reach the browser).
3
+ // Without a URL, the client uses the hosted API.
4
+ import { createClient } from 'usebecky'
5
+
6
+ export const baas = createClient(
7
+ import.meta.env.VITE_USEBECKY_URL,
8
+ import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY,
9
+ )
@@ -0,0 +1,22 @@
1
+ import '@fontsource-variable/instrument-sans'
2
+ import '@fontsource-variable/newsreader'
3
+ import './index.css'
4
+ import { StrictMode } from 'react'
5
+ import { createRoot } from 'react-dom/client'
6
+ import { Setup } from './components/Setup'
7
+
8
+ const root = createRoot(document.getElementById('root')!)
9
+
10
+ // Not connected to a project yet? Show how to connect instead of a blank page.
11
+ // (The app is only loaded once the key is there, because the client needs it.)
12
+ if (!import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY) {
13
+ root.render(<Setup />)
14
+ } else {
15
+ import('./App').then(({ App }) =>
16
+ root.render(
17
+ <StrictMode>
18
+ <App />
19
+ </StrictMode>,
20
+ ),
21
+ )
22
+ }
@@ -0,0 +1,6 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ interface ImportMetaEnv {
4
+ readonly VITE_USEBECKY_URL?: string
5
+ readonly VITE_USEBECKY_PUBLISHABLE_KEY: string
6
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "skipLibCheck": true,
11
+ "isolatedModules": true,
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "noUnusedLocals": true,
15
+ "noUnusedParameters": true,
16
+ "types": ["vite/client"]
17
+ },
18
+ "include": ["src", "vite.config.ts"]
19
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "id": "notes",
3
+ "name": "Notes",
4
+ "description": "Private notes, live updates, image uploads",
5
+ "stack": "React + Vite",
6
+ "kind": "node",
7
+ "framework": "vite",
8
+ "serverTemplate": "blank",
9
+ "order": 1,
10
+ "brandName": "Margin",
11
+ "brandSlug": "margin",
12
+ "brandFiles": ["src/brand.ts", "index.html"],
13
+ "customize": { "name": "src/brand.ts", "colour": "src/index.css (--brand)" },
14
+ "setup": {
15
+ "tables": [
16
+ {
17
+ "name": "notes",
18
+ "preset": "owner",
19
+ "comment": "Notes from the Notes starter. Each user sees only their own.",
20
+ "columns": [
21
+ { "name": "title", "type": "text", "nullable": false },
22
+ { "name": "body", "type": "text" },
23
+ { "name": "image_path", "type": "text", "comment": "Path of the attached image in the attachments bucket." }
24
+ ],
25
+ "realtime": true
26
+ }
27
+ ],
28
+ "buckets": [
29
+ { "id": "attachments", "public": false, "file_size_limit": 5242880, "allowed_mime_types": ["image/*"], "policies": ["user_folder"] }
30
+ ]
31
+ },
32
+ "run": { "script": "dev", "url": "http://localhost:3001", "port": 3001 },
33
+ "docs": [{ "title": "The tutorial this starter follows", "path": "tutorial/1-notes-app" }]
34
+ }
@@ -0,0 +1,10 @@
1
+ import tailwindcss from '@tailwindcss/vite'
2
+ import react from '@vitejs/plugin-react'
3
+ import { defineConfig } from 'vite'
4
+
5
+ // Port 3001, so it doesn't clash with the usebecky dashboard (5173) or a Next.js app (3000).
6
+ export default defineConfig({
7
+ plugins: [react(), tailwindcss()],
8
+ server: { port: 3001 },
9
+ preview: { port: 3001 },
10
+ })
@@ -0,0 +1,69 @@
1
+ # Plotline: a SaaS starter
2
+
3
+ A complete software-as-a-service app built with Next.js and usebecky: a landing page, sign-in, a dashboard where people manage their projects, Stripe subscriptions with a free trial, and a page only paying customers can open.
4
+
5
+ ## What's inside
6
+
7
+ | Page | What it does |
8
+ |---|---|
9
+ | `/` | The landing page (`app/page.tsx`) |
10
+ | `/sign-in` | Google, email and password, or a 6-digit code by email (`app/sign-in/SignInForm.tsx`) |
11
+ | `/dashboard` | Each person's projects: add, rename, change status, delete (`app/(app)/dashboard`) |
12
+ | `/pricing` | Monthly or yearly Premium plan with a 14-day trial, paid with Stripe Checkout (`app/pricing/Plans.tsx`) |
13
+ | `/premium` | Only for Premium customers (`app/(app)/premium/page.tsx`) |
14
+ | `/account` | Plan, trial end date and the Stripe billing portal (`app/(app)/account`) |
15
+
16
+ How it fits together:
17
+
18
+ - **Signed-in pages check the user on the server** with `usebecky/server` (`lib/session.ts`). People who aren't signed in go to `/sign-in` and come back afterwards.
19
+ - **Each person sees only their own projects**: the server reads them *as that person*, and the `projects` table's access rules do the rest.
20
+ - **The Premium page checks twice**: `baas.payments.hasAccess(user, 'premium')` on the server, and the `premium_content` table can't be read without Premium anyway.
21
+ - Browser code uses `lib/usebecky.ts`. It also puts the sign-in token in a cookie, which is how the server knows who is signed in.
22
+
23
+ ## Run it
24
+
25
+ ```bash
26
+ npm run dev
27
+ ```
28
+
29
+ Open http://localhost:3000, click **Start free** and create an account.
30
+
31
+ Your keys are in `.env.local`. The two `NEXT_PUBLIC_` values are safe in the browser; `USEBECKY_SECRET_KEY` is for server code only. Never rename it with a `NEXT_PUBLIC_` prefix and never commit the file.
32
+
33
+ ## Turn on payments
34
+
35
+ The pricing page shows the real prices of the **Premium** product the SaaS setup created ($9 a month or $90 a year, 14-day trial).
36
+
37
+ 1. In the dashboard, open **Payments** and connect Stripe. Test mode is fine.
38
+ 2. Click **Start 14-day free trial** on `/pricing` and pay with the test card `4242 4242 4242 4242`, any future date and any CVC.
39
+ 3. You land on `/account` with **Premium** and the trial end date. `/premium` now opens.
40
+
41
+ For **Manage billing**, turn on the customer portal in your Stripe dashboard (**Settings → Billing → Customer portal**).
42
+
43
+ ## Turn on Google sign-in
44
+
45
+ In the dashboard, open **Auth**, then **Sign-in methods**, and set up Google. Until then, the Google button explains that it's off.
46
+
47
+ ## Make it yours
48
+
49
+ - **Name, tagline and plan features**: `brand.ts`.
50
+ - **Colour**: change `--brand` at the top of `app/globals.css`. Light and dark mode both follow it.
51
+ - **Font**: Bricolage Grotesque, set in `app/layout.tsx`.
52
+ - **Project statuses**: `components/Status.tsx`.
53
+
54
+ ## Connect it later
55
+
56
+ 1. In this folder, run `npx usebecky init` and pick a project with the **SaaS with subscriptions** ready-made setup.
57
+ 2. Check that `.env.local` has four lines: `NEXT_PUBLIC_USEBECKY_URL`, `NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY`, `USEBECKY_URL` and `USEBECKY_SECRET_KEY`.
58
+ 3. Restart `npm run dev`.
59
+
60
+ ## Learn more
61
+
62
+ The docs are in your dashboard under **Docs**.
63
+
64
+ - **Next.js guide**: server components, route handlers and sign-in redirects (`frameworks/nextjs`).
65
+ - **Payments guide**: products, checkout, trials and webhooks (`guides/payments`).
66
+ - **Tutorial part 3**: charging for a Pro plan, step by step (`tutorial/3-charge-for-it`).
67
+ - **Starter apps**: all starters and how to change them (`getting-started/starters`).
68
+
69
+ Your AI assistant knows usebecky too: see `.claude/skills/usebecky` and `AGENTS.md`.
@@ -0,0 +1,10 @@
1
+ # Copy this file to .env.local and paste your values from Dashboard → Settings → API keys.
2
+ # (create-usebecky and `npx usebecky init` write .env.local for you.)
3
+
4
+ # Browser code can read these:
5
+ NEXT_PUBLIC_USEBECKY_URL=https://api.usebecky.com
6
+ NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY=ub_pk_...
7
+
8
+ # Server code only. Never give these a NEXT_PUBLIC_ name:
9
+ USEBECKY_URL=https://api.usebecky.com
10
+ USEBECKY_SECRET_KEY=ub_sk_...
@@ -0,0 +1,11 @@
1
+ node_modules
2
+ .next
3
+ out
4
+ *.log
5
+ .DS_Store
6
+ *.tsbuildinfo
7
+
8
+ # Your keys. Never commit these.
9
+ .env
10
+ .env.local
11
+ .env.*.local
@@ -0,0 +1,26 @@
1
+ 'use client'
2
+ // Opens the Stripe customer portal: change plan, update the card, download invoices, cancel.
3
+ import { useState } from 'react'
4
+ import { baas } from '@/lib/usebecky'
5
+
6
+ export function ManageBilling() {
7
+ const [busy, setBusy] = useState(false)
8
+ const [error, setError] = useState('')
9
+ async function open() {
10
+ setBusy(true)
11
+ setError('')
12
+ const { error } = await baas.payments.portal({ returnUrl: window.location.href })
13
+ if (error) {
14
+ setBusy(false)
15
+ setError(error.code === 'portal_not_configured' ? 'The billing portal isn’t set up yet. The developer can turn it on in the Stripe dashboard (Settings → Billing → Customer portal).' : error.message)
16
+ }
17
+ }
18
+ return (
19
+ <div>
20
+ <button onClick={open} disabled={busy} className="btn btn-ghost">
21
+ {busy ? 'Opening Stripe…' : 'Manage billing'}
22
+ </button>
23
+ {error && <p className="mt-3 max-w-md text-sm text-danger">{error}</p>}
24
+ </div>
25
+ )
26
+ }
@@ -0,0 +1,71 @@
1
+ // Your account and plan. Billing details come from usebecky, which keeps them in sync with Stripe.
2
+ import Link from 'next/link'
3
+ import { requireUser } from '@/lib/session'
4
+ import { ManageBilling } from './ManageBilling'
5
+
6
+ export const metadata = { title: 'Account' }
7
+
8
+ export default async function AccountPage({ searchParams }: { searchParams: Promise<{ checkout?: string }> }) {
9
+ const { user, db } = await requireUser('/account')
10
+ const { checkout } = await searchParams
11
+ const { data: billing } = await db.payments.me()
12
+ const sub = billing?.subscriptions.find((s) => ['active', 'trialing', 'past_due'].includes(s.status))
13
+ const date = (iso: string | null) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric' }) : '')
14
+
15
+ return (
16
+ <>
17
+ <h1 className="headline text-[clamp(2.4rem,6vw,3rem)]">Account</h1>
18
+
19
+ {checkout === 'success' && (
20
+ <p role="status" className="mt-6 rounded-xl bg-accent-soft px-4 py-3">
21
+ Thanks for subscribing! Stripe is confirming your payment, so Premium may take a few seconds to show up here. Reload if it doesn’t.
22
+ </p>
23
+ )}
24
+
25
+ <dl className="mt-8 divide-y divide-line rounded-2xl border border-line bg-surface">
26
+ <Row label="Email">{user.email}</Row>
27
+ <Row label="Member since">{date(user.created_at)}</Row>
28
+ <Row label="Plan">
29
+ {sub ? (
30
+ <span className="flex flex-wrap items-center gap-2">
31
+ <span className="font-semibold">Premium</span>
32
+ <span className="text-muted">
33
+ {sub.source === 'gift'
34
+ ? sub.gift?.ends_at
35
+ ? `a gift, free until ${date(sub.gift.ends_at)}`
36
+ : 'a gift, free with no end date'
37
+ : sub.status === 'trialing'
38
+ ? `free trial until ${date(sub.trial_end)}`
39
+ : sub.cancel_at_period_end
40
+ ? `ends on ${date(sub.current_period_end)}`
41
+ : sub.status === 'past_due'
42
+ ? 'payment failed: update your card'
43
+ : `renews on ${date(sub.current_period_end)}`}
44
+ </span>
45
+ </span>
46
+ ) : (
47
+ <span className="font-semibold">Free</span>
48
+ )}
49
+ </Row>
50
+ </dl>
51
+
52
+ <div className="mt-6 flex flex-wrap items-center gap-3">
53
+ {billing?.customer_id ? <ManageBilling /> : null}
54
+ {!sub && (
55
+ <Link href="/pricing" className="btn btn-primary">
56
+ Upgrade to Premium
57
+ </Link>
58
+ )}
59
+ </div>
60
+ </>
61
+ )
62
+ }
63
+
64
+ function Row({ label, children }: { label: string; children: React.ReactNode }) {
65
+ return (
66
+ <div className="grid gap-1 px-5 py-4 sm:grid-cols-[10rem_1fr] sm:px-6">
67
+ <dt className="text-sm text-muted">{label}</dt>
68
+ <dd>{children}</dd>
69
+ </div>
70
+ )
71
+ }
@@ -0,0 +1,227 @@
1
+ 'use client'
2
+ // Add, rename, change the status of, and delete your projects. Runs in the browser with your session.
3
+ import { useState, type FormEvent } from 'react'
4
+ import { STATUSES, StatusDot, statusLabel } from '@/components/Status'
5
+ import { baas } from '@/lib/usebecky'
6
+
7
+ export type Project = { id: string; name: string; description: string | null; status: string; created_at: string }
8
+ const COLUMNS = 'id, name, description, status, created_at'
9
+
10
+ export function Projects({ initial, greeting }: { initial: Project[]; greeting: string }) {
11
+ const [projects, setProjects] = useState(initial)
12
+ const [adding, setAdding] = useState(initial.length === 0)
13
+ const [error, setError] = useState('')
14
+ const [filter, setFilter] = useState<string>('all')
15
+
16
+ const counts = Object.fromEntries(STATUSES.map((s) => [s.value, projects.filter((p) => p.status === s.value).length]))
17
+ const shown = filter === 'all' ? projects : projects.filter((p) => p.status === filter)
18
+
19
+ async function update(id: string, values: Partial<Project>) {
20
+ setError('')
21
+ const { data, error } = await baas.from('projects').update(values).eq('id', id).select(COLUMNS).single()
22
+ if (error) return setError(error.message)
23
+ setProjects((list) => list.map((p) => (p.id === id ? (data as Project) : p)))
24
+ }
25
+
26
+ async function remove(id: string) {
27
+ setError('')
28
+ const { error } = await baas.from('projects').delete().eq('id', id)
29
+ if (error) return setError(error.message)
30
+ setProjects((list) => list.filter((p) => p.id !== id))
31
+ }
32
+
33
+ return (
34
+ <section>
35
+ <div className="flex items-end justify-between gap-4">
36
+ <div>
37
+ <p className="text-muted">{greeting}</p>
38
+ <h1 className="headline mt-1 text-[clamp(2.4rem,6vw,3rem)]">Your projects</h1>
39
+ </div>
40
+ {!adding && (
41
+ <button onClick={() => setAdding(true)} className="btn btn-primary mb-1">
42
+ New project
43
+ </button>
44
+ )}
45
+ </div>
46
+
47
+ {projects.length > 0 && (
48
+ <div className="-mx-5 mt-7 overflow-x-auto px-5 sm:mx-0 sm:px-0" role="group" aria-label="Show">
49
+ <div className="flex w-max gap-1.5 text-sm">
50
+ <FilterChip active={filter === 'all'} onClick={() => setFilter('all')} label="All" count={projects.length} />
51
+ {STATUSES.map((s) => (
52
+ <FilterChip key={s.value} active={filter === s.value} onClick={() => setFilter(s.value)} label={s.label} count={counts[s.value]} />
53
+ ))}
54
+ </div>
55
+ </div>
56
+ )}
57
+
58
+ {adding && (
59
+ <NewProject
60
+ onCancel={projects.length ? () => setAdding(false) : undefined}
61
+ onCreated={(p) => {
62
+ setProjects((list) => [p, ...list])
63
+ setAdding(false)
64
+ }}
65
+ />
66
+ )}
67
+
68
+ {error && (
69
+ <p role="alert" className="mt-4 rounded-xl bg-danger/10 px-4 py-3 text-sm text-danger">
70
+ {error}
71
+ </p>
72
+ )}
73
+
74
+ {projects.length > 0 && (
75
+ <ul className="mt-5 overflow-hidden rounded-2xl border border-line bg-surface" aria-label="Projects">
76
+ {shown.map((p) => (
77
+ <ProjectRow key={p.id} project={p} onUpdate={(v) => update(p.id, v)} onDelete={() => remove(p.id)} />
78
+ ))}
79
+ {shown.length === 0 && <li className="px-6 py-10 text-center text-muted">No projects are {statusLabel(filter).toLowerCase()} right now.</li>}
80
+ </ul>
81
+ )}
82
+ </section>
83
+ )
84
+ }
85
+
86
+ function FilterChip({ active, onClick, label, count }: { active: boolean; onClick: () => void; label: string; count: number }) {
87
+ return (
88
+ <button onClick={onClick} aria-pressed={active} className={`h-9 shrink-0 rounded-full px-3.5 font-medium transition-colors ${active ? 'bg-ink text-page' : 'text-muted ring-1 ring-line hover:text-ink'}`}>
89
+ {label} <span className={`ml-0.5 tabular-nums ${active ? 'opacity-70' : 'opacity-60'}`}>{count}</span>
90
+ </button>
91
+ )
92
+ }
93
+
94
+ function NewProject({ onCreated, onCancel }: { onCreated: (p: Project) => void; onCancel?: () => void }) {
95
+ const [name, setName] = useState('')
96
+ const [description, setDescription] = useState('')
97
+ const [busy, setBusy] = useState(false)
98
+ const [error, setError] = useState('')
99
+
100
+ async function create(event: FormEvent<HTMLFormElement>) {
101
+ event.preventDefault()
102
+ setBusy(true)
103
+ setError('')
104
+ // user_id is filled in by the database: it's always the signed-in user.
105
+ const { data, error } = await baas.from('projects').insert({ name: name.trim(), description: description.trim() || null }).select(COLUMNS).single()
106
+ setBusy(false)
107
+ if (error) return setError(error.message)
108
+ onCreated(data as Project)
109
+ }
110
+
111
+ return (
112
+ <form onSubmit={create} className="mt-5 rounded-2xl border border-line bg-surface p-5 sm:p-6">
113
+ <h2 className="text-lg font-semibold">{onCancel ? 'New project' : 'Add your first project'}</h2>
114
+ <div className="mt-4 grid gap-4 sm:grid-cols-[1fr_1.4fr]">
115
+ <div>
116
+ <label htmlFor="project-name" className="mb-1.5 block text-sm font-semibold">
117
+ Name
118
+ </label>
119
+ <input id="project-name" className="input" required maxLength={120} value={name} onChange={(e) => setName(e.target.value)} placeholder="Spring launch site" autoFocus />
120
+ </div>
121
+ <div>
122
+ <label htmlFor="project-description" className="mb-1.5 block text-sm font-semibold">
123
+ Next step <span className="font-normal text-muted">(optional)</span>
124
+ </label>
125
+ <input id="project-description" className="input" maxLength={300} value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Copy review with Mia on Thursday" />
126
+ </div>
127
+ </div>
128
+ {error && <p className="mt-3 text-sm text-danger">{error}</p>}
129
+ <div className="mt-5 flex gap-2">
130
+ <button disabled={busy || !name.trim()} className="btn btn-primary">
131
+ {busy ? 'Adding…' : 'Add project'}
132
+ </button>
133
+ {onCancel && (
134
+ <button type="button" onClick={onCancel} className="btn text-muted hover:text-ink">
135
+ Cancel
136
+ </button>
137
+ )}
138
+ </div>
139
+ </form>
140
+ )
141
+ }
142
+
143
+ function ProjectRow({ project, onUpdate, onDelete }: { project: Project; onUpdate: (v: Partial<Project>) => Promise<void>; onDelete: () => Promise<void> }) {
144
+ const [editing, setEditing] = useState(false)
145
+ const [confirming, setConfirming] = useState(false)
146
+ const [name, setName] = useState(project.name)
147
+ const [description, setDescription] = useState(project.description ?? '')
148
+
149
+ if (editing) {
150
+ return (
151
+ <li className="border-b border-line p-4 last:border-0 sm:px-6">
152
+ <form
153
+ className="grid gap-3 sm:grid-cols-[1fr_1.4fr_auto]"
154
+ onSubmit={async (e) => {
155
+ e.preventDefault()
156
+ await onUpdate({ name: name.trim(), description: description.trim() || null })
157
+ setEditing(false)
158
+ }}
159
+ >
160
+ <input aria-label="Name" className="input" required value={name} onChange={(e) => setName(e.target.value)} autoFocus />
161
+ <input aria-label="Next step" className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Next step" />
162
+ <div className="flex gap-2">
163
+ <button className="btn btn-primary">Save</button>
164
+ <button type="button" className="btn text-muted hover:text-ink" onClick={() => setEditing(false)}>
165
+ Cancel
166
+ </button>
167
+ </div>
168
+ </form>
169
+ </li>
170
+ )
171
+ }
172
+
173
+ return (
174
+ <li className="group border-b border-line px-4 py-4 last:border-0 sm:px-6">
175
+ <div className="flex items-center gap-4">
176
+ <StatusDot status={project.status} />
177
+ <div className="min-w-0 flex-1">
178
+ <p className="truncate font-semibold">{project.name}</p>
179
+ {project.description && <p className="mt-0.5 truncate text-sm text-muted">{project.description}</p>}
180
+ </div>
181
+ <label className="sr-only" htmlFor={`status-${project.id}`}>
182
+ Status of {project.name}
183
+ </label>
184
+ <select
185
+ id={`status-${project.id}`}
186
+ value={project.status}
187
+ onChange={(e) => onUpdate({ status: e.target.value })}
188
+ className="h-9 shrink-0 cursor-pointer rounded-lg border border-line bg-page px-2.5 text-sm font-medium outline-none focus:border-accent"
189
+ >
190
+ {STATUSES.map((s) => (
191
+ <option key={s.value} value={s.value}>
192
+ {s.label}
193
+ </option>
194
+ ))}
195
+ {!STATUSES.some((s) => s.value === project.status) && <option value={project.status}>{project.status}</option>}
196
+ </select>
197
+ <div className="hidden shrink-0 gap-1 sm:flex">
198
+ <button onClick={() => setEditing(true)} className="rounded-lg px-2.5 py-1.5 text-sm font-medium text-muted hover:bg-page hover:text-ink">
199
+ Edit
200
+ </button>
201
+ <button onClick={() => setConfirming(true)} className="rounded-lg px-2.5 py-1.5 text-sm font-medium text-muted hover:bg-page hover:text-danger">
202
+ Delete
203
+ </button>
204
+ </div>
205
+ </div>
206
+ <div className="mt-3 flex gap-3 pl-6 text-sm sm:hidden">
207
+ <button onClick={() => setEditing(true)} className="font-medium text-muted">
208
+ Edit
209
+ </button>
210
+ <button onClick={() => setConfirming(true)} className="font-medium text-muted">
211
+ Delete
212
+ </button>
213
+ </div>
214
+ {confirming && (
215
+ <div role="alertdialog" aria-label={`Delete ${project.name}?`} className="mt-3 flex flex-wrap items-center gap-3 rounded-xl bg-danger/8 px-4 py-3 text-sm">
216
+ <span className="mr-auto">Delete “{project.name}”? This can’t be undone.</span>
217
+ <button autoFocus onClick={onDelete} className="btn h-8 bg-danger px-3 text-sm text-surface">
218
+ Delete
219
+ </button>
220
+ <button onClick={() => setConfirming(false)} className="btn h-8 px-3 text-sm">
221
+ Keep it
222
+ </button>
223
+ </div>
224
+ )}
225
+ </li>
226
+ )
227
+ }
@@ -0,0 +1,21 @@
1
+ // Your projects. The server checks who you are and loads your projects AS you, so the
2
+ // "users see only their own projects" access rule applies. Changes happen in the browser (Projects.tsx).
3
+ import { requireUser } from '@/lib/session'
4
+ import { Projects, type Project } from './Projects'
5
+
6
+ export const metadata = { title: 'Projects' }
7
+
8
+ export default async function DashboardPage() {
9
+ const { user, db } = await requireUser('/dashboard')
10
+ const { data, error } = await db.from('projects').select('id, name, description, status, created_at').order('created_at', { ascending: false })
11
+ const firstName = (user.user_metadata?.name as string | undefined)?.split(' ')[0] ?? user.email?.split('@')[0]
12
+
13
+ if (error) {
14
+ return (
15
+ <p role="alert" className="rounded-xl bg-danger/10 px-4 py-3 text-danger">
16
+ {error.code === 'table_not_found' ? 'This project has no "projects" table. Create the project from the SaaS template (see the README).' : error.message}
17
+ </p>
18
+ )
19
+ }
20
+ return <Projects initial={(data ?? []) as Project[]} greeting={`Hi ${firstName}`} />
21
+ }
@@ -0,0 +1,29 @@
1
+ // The frame around the signed-in pages: a sidebar on wide screens, a top bar on phones.
2
+ // Each page checks the user itself (requireUser), because Next.js doesn't re-run layouts on every navigation.
3
+ import { AppNav, SignOutButton } from '@/components/AppNav'
4
+ import { Logo } from '@/components/Logo'
5
+ import { getUser } from '@/lib/session'
6
+
7
+ export default async function AppLayout({ children }: { children: React.ReactNode }) {
8
+ const user = await getUser()
9
+ return (
10
+ <div className="min-h-dvh lg:grid lg:grid-cols-[15rem_1fr]">
11
+ <aside className="border-b border-line px-5 py-4 lg:sticky lg:top-0 lg:flex lg:h-dvh lg:flex-col lg:border-r lg:border-b-0 lg:px-4 lg:py-6">
12
+ <div className="flex items-center justify-between lg:mb-8 lg:px-2">
13
+ <Logo href="/dashboard" />
14
+ <SignOutButton className="lg:hidden" />
15
+ </div>
16
+ <div className="mt-4 lg:mt-0">
17
+ <AppNav />
18
+ </div>
19
+ <div className="mt-auto hidden px-2 lg:block">
20
+ <p className="truncate text-sm text-muted" title={user?.email ?? ''}>
21
+ {user?.email}
22
+ </p>
23
+ <SignOutButton className="mt-1" />
24
+ </div>
25
+ </aside>
26
+ <main className="w-full max-w-4xl px-5 py-8 sm:px-8 lg:px-14 lg:py-12">{children}</main>
27
+ </div>
28
+ )
29
+ }