create-marcapony-app 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,6 +31,7 @@ up and build on it.
31
31
  | `shop` | Products, a cart and a checkout that sends the buyer to pay | Your site |
32
32
  | `team-tool` | Your team approves, rejects and completes the day's reservations | Dashboard |
33
33
  | `character` | A character from your business that chats with visitors | Your site |
34
+ | `game` | A game anyone can play; signing in keeps the best score | Its own address |
34
35
 
35
36
  Each template's `README.md` says which placement, data access, scopes and
36
37
  permissions to choose when you create the app under **My Apps** in the
package/dist/index.d.ts CHANGED
@@ -14,6 +14,9 @@ export declare const TEMPLATES: readonly [{
14
14
  }, {
15
15
  readonly name: "character";
16
16
  readonly summary: "A character from your business that chats with visitors";
17
+ }, {
18
+ readonly name: "game";
19
+ readonly summary: "A game anyone can play; signing in keeps the best score";
17
20
  }];
18
21
  export type TemplateName = (typeof TEMPLATES)[number]['name'];
19
22
  export declare const DEFAULT_TEMPLATE: TemplateName;
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ export const TEMPLATES = [
19
19
  { name: 'shop', summary: 'Products, a cart and checkout with a payment link' },
20
20
  { name: 'team-tool', summary: "Your team approves and updates today's reservations" },
21
21
  { name: 'character', summary: 'A character from your business that chats with visitors' },
22
+ { name: 'game', summary: 'A game anyone can play; signing in keeps the best score' },
22
23
  ];
23
24
  export const DEFAULT_TEMPLATE = 'blank';
24
25
  const BASE_DIR = 'base';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-marcapony-app",
3
- "version": "0.4.6",
3
+ "version": "0.5.0",
4
4
  "description": "Scaffold a Marcapony app \u2014 a Worker backed by the Marcapony API, ready for `marcapony app link` and `marcapony app deploy`",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "hono": "^4.13.0",
17
- "marcapony-sdk": "^0.13.0",
17
+ "marcapony-sdk": "^0.14.0",
18
18
  "react": "^19.3.0",
19
19
  "react-dom": "^19.3.0"
20
20
  },
@@ -24,7 +24,7 @@
24
24
  "@types/react-dom": "^19.3.0",
25
25
  "@vitejs/plugin-react": "^5.2.0",
26
26
  "esbuild": "^0.28.0",
27
- "marcapony": "^0.15.0",
27
+ "marcapony": "^0.16.0",
28
28
  "typescript": "^5.9.0",
29
29
  "vite": "^7.3.0"
30
30
  }
@@ -0,0 +1,71 @@
1
+ # Marcapony app: game
2
+
3
+ A small game anyone can play. A visitor who signs in keeps their best score.
4
+ It shows the two ways to sign a visitor in from an app: an e-mail code on the
5
+ app's own screen, and the portal's full sign-in page.
6
+
7
+ ## Set up in the dashboard
8
+
9
+ Create the app under **My Apps** with:
10
+
11
+ - **Placement:** customer portal (`"placement": "portal"`)
12
+ - **Data access:** customer (`"dataAccess": "customer"`)
13
+ - **Scopes:** none
14
+ - **Permissions** (declared in `marcapony.json`; choose who gets them):
15
+ - `keep-score`, "Save my best score": `records.own.read`, `records.own.write`.
16
+ Give it to every customer, or the score is not saved.
17
+
18
+ `"signIn": "optional"` in `marcapony.json` is what lets a visitor open the app
19
+ without an account. It needs `"runtime": "2026-12"` or newer and the app's own
20
+ address (the one `bun run deploy` prints).
21
+
22
+ ## Routes
23
+
24
+ | Route | What it does |
25
+ | ---------------- | ---------------------------------------------------------------- |
26
+ | `GET /api/health` | Answers `{ "ok": true }` |
27
+ | `GET /api/score` | The signed-in customer's best score, or `{ "best": null }` |
28
+ | `PUT /api/score` | Saves `{ score }` when it beats the best; 401 if nobody is signed in |
29
+
30
+ Sign-in itself has no route here. The interface calls
31
+ `marcapony-sdk/browser`, which talks to routes Marcapony serves on the app's
32
+ address under `/_marcapony/`:
33
+
34
+ | Call | What it does |
35
+ | ------------------------------------- | ------------------------------------------------------ |
36
+ | `auth.me()` | Who is signed in, and whether they may use the app |
37
+ | `auth.options()` | Whether a code can be sent, and how new accounts start |
38
+ | `auth.sendCode(email)` | E-mails a six-digit code and a sign-in link |
39
+ | `auth.verifyCode(email, code)` | Signs the visitor in |
40
+ | `auth.signInUrl({ returnTo })` | The full sign-in page: password, Google, registration |
41
+ | `auth.signOut()` | Signs the visitor out of this app |
42
+
43
+ The server never sees a password, a code or the session. It asks
44
+ `identityOf(...)` who the request is from, and the platform limits
45
+ `me.records` to that customer.
46
+
47
+ ## What to change first
48
+
49
+ 1. The game in `src/ui/App.tsx`. The browser reports the score here, so a
50
+ player can cheat; a game that matters keeps the round on the server.
51
+ 2. `signInScreen` in `marcapony.json`: the title, text, logo and background of
52
+ the sign-in page for visitors who come from this app. Put the images in
53
+ `public/` and name them by path, such as `"/logo.svg"`.
54
+ 3. The menu title in `marcapony.json` (`portal.title`).
55
+ 4. Test sign-in on the deployed app: locally there are no sign-in routes and
56
+ nobody is signed in, so the game is played without an account.
57
+
58
+ ## Develop and publish
59
+
60
+ Requires [Bun](https://bun.sh).
61
+
62
+ ```sh
63
+ bun install
64
+ bun run link # paste the connection code from the app's page; writes .env.local and AGENTS.md
65
+ bun run dev # interface and /api routes on your machine
66
+ bun run deploy # build and publish; prints the address
67
+ ```
68
+
69
+ `.env.local` holds the app key. Never commit it, and never send it to the
70
+ browser: the interface calls this app's own `/api` routes, and only those talk
71
+ to Marcapony.
@@ -0,0 +1,40 @@
1
+ {
2
+ "$schema": "./node_modules/marcapony/manifest.schema.json",
3
+ "manifest": 2,
4
+ "build": "bun run build",
5
+ "server": "dist/server/index.js",
6
+ "public": {
7
+ "dir": "dist/client"
8
+ },
9
+ "routes": {
10
+ "server": ["/api/*"],
11
+ "notFound": "spa"
12
+ },
13
+ "runtime": "2026-12",
14
+ "ignore": ["coverage/", "*.log"],
15
+ "placement": "portal",
16
+ "dataAccess": "customer",
17
+ "signIn": "optional",
18
+ "signInScreen": {
19
+ "title": "Keep your best score",
20
+ "text": "Sign in and your best round is saved for next time."
21
+ },
22
+ "permissions": [
23
+ {
24
+ "id": "keep-score",
25
+ "label": "Save my best score",
26
+ "grants": ["records.own.read", "records.own.write"]
27
+ }
28
+ ],
29
+ "collections": [
30
+ {
31
+ "name": "scores",
32
+ "read": "own",
33
+ "write": "own",
34
+ "maxRows": 10
35
+ }
36
+ ],
37
+ "portal": {
38
+ "title": "Game"
39
+ }
40
+ }
@@ -0,0 +1,55 @@
1
+ import { Hono } from 'hono'
2
+ import { errorResponse, identityOf, marcaponyFromEnv, type MarcaponyBindings } from './marcapony'
3
+
4
+ /**
5
+ * A game anyone can play; a signed-in customer keeps their best score. Only
6
+ * `/api/*` reaches this worker; everything else is served from `dist/client`
7
+ * (see `run_worker_first` in marcapony.json).
8
+ *
9
+ * `"signIn": "optional"` in marcapony.json means a visitor reaches the app
10
+ * without signing in, so `identityOf` answers null for them. Signing in happens
11
+ * in the browser (see `src/ui/App.tsx`); this server only ever asks who the
12
+ * request is from, and never sees a password, a code or the session.
13
+ */
14
+ const app = new Hono<{ Bindings: MarcaponyBindings }>()
15
+
16
+ // A type alias, not an interface: a record's data must be assignable to plain JSON.
17
+ type Score = { score: number }
18
+
19
+ const BEST = 'best'
20
+ const MAX_SCORE = 500
21
+
22
+ app.get('/api/health', (c) => c.json({ ok: true }))
23
+
24
+ app.get('/api/score', async (c) => {
25
+ const mp = marcaponyFromEnv(c.env)
26
+ const who = await identityOf(mp, c.env, c.req.raw)
27
+ if (!who || who.kind !== 'customer') return c.json({ best: null })
28
+ const record = await mp.forRequest(c.req.raw).me.records<Score>('scores').get(BEST)
29
+ return c.json({ best: record?.data.score ?? null })
30
+ })
31
+
32
+ app.put('/api/score', async (c) => {
33
+ const mp = marcaponyFromEnv(c.env)
34
+ const who = await identityOf(mp, c.env, c.req.raw)
35
+ if (!who) return c.json({ error: 'Sign in to keep your score.' }, 401)
36
+ if (who.kind !== 'customer') return c.json({ error: 'Scores are kept for customers.' }, 403)
37
+
38
+ const body = (await c.req.json().catch(() => ({}))) as { score?: unknown }
39
+ const { score } = body
40
+ if (typeof score !== 'number' || !Number.isInteger(score) || score < 0 || score > MAX_SCORE) {
41
+ return c.json({ error: 'score is a whole number from 0 to 500.' }, 400)
42
+ }
43
+
44
+ // The browser reports the score, so a player can cheat. A game that matters
45
+ // keeps the round on the server and counts there.
46
+ const scores = mp.forRequest(c.req.raw).me.records<Score>('scores')
47
+ const current = await scores.get(BEST)
48
+ if (current && current.data.score >= score) return c.json({ best: current.data.score })
49
+ const saved = await scores.put(BEST, { score })
50
+ return c.json({ best: saved.data.score })
51
+ })
52
+
53
+ app.onError((err) => errorResponse(err))
54
+
55
+ export default app
@@ -0,0 +1,231 @@
1
+ import { useCallback, useEffect, useState } from 'react'
2
+ import { auth, type SignedInState, type SignInOptions } from 'marcapony-sdk/browser'
3
+ import { api, errorMessage } from './api'
4
+
5
+ const ROUND_SECONDS = 5
6
+
7
+ /**
8
+ * Sign-in inside the app. `auth` calls routes Marcapony serves on the app's
9
+ * own address, so there is no key here and the app never sees a password or
10
+ * the session. Those routes exist on the deployed app only: locally every call
11
+ * fails, and the game is played signed out.
12
+ */
13
+ function SignIn({ offer, onSignedIn }: { offer: SignInOptions; onSignedIn: () => void }) {
14
+ const [email, setEmail] = useState('')
15
+ const [code, setCode] = useState('')
16
+ const [sent, setSent] = useState(false)
17
+ const [busy, setBusy] = useState(false)
18
+ const [error, setError] = useState<string | null>(null)
19
+
20
+ async function send() {
21
+ setBusy(true)
22
+ setError(null)
23
+ try {
24
+ await auth.sendCode(email.trim())
25
+ setSent(true)
26
+ } catch (err) {
27
+ setError(errorMessage(err))
28
+ } finally {
29
+ setBusy(false)
30
+ }
31
+ }
32
+
33
+ async function verify() {
34
+ setBusy(true)
35
+ setError(null)
36
+ try {
37
+ const { signedIn } = await auth.verifyCode(email.trim(), code.trim())
38
+ if (signedIn) onSignedIn()
39
+ else setError('That code is wrong or has expired. Ask for a new one.')
40
+ } catch (err) {
41
+ setError(errorMessage(err))
42
+ } finally {
43
+ setBusy(false)
44
+ }
45
+ }
46
+
47
+ return (
48
+ <section>
49
+ <h2>Keep your best score</h2>
50
+ {offer.emailCode && !sent ? (
51
+ <form
52
+ onSubmit={(event) => {
53
+ event.preventDefault()
54
+ void send()
55
+ }}
56
+ >
57
+ <label>
58
+ E-mail
59
+ <input
60
+ type="email"
61
+ required
62
+ autoComplete="email"
63
+ value={email}
64
+ onChange={(event) => setEmail(event.target.value)}
65
+ />
66
+ </label>
67
+ <button type="submit" disabled={busy || !email.trim()}>
68
+ Send me a code
69
+ </button>
70
+ </form>
71
+ ) : null}
72
+ {offer.emailCode && sent ? (
73
+ <form
74
+ onSubmit={(event) => {
75
+ event.preventDefault()
76
+ void verify()
77
+ }}
78
+ >
79
+ <p className="muted">
80
+ If {email.trim()} can sign in, a code is on its way. The e-mail also has a link that
81
+ signs you in.
82
+ {offer.signUp === 'app' ? ' New here? The code creates your account.' : null}
83
+ </p>
84
+ <label>
85
+ Code
86
+ <input
87
+ inputMode="numeric"
88
+ autoComplete="one-time-code"
89
+ maxLength={6}
90
+ required
91
+ value={code}
92
+ onChange={(event) => setCode(event.target.value)}
93
+ />
94
+ </label>
95
+ <p className="actions">
96
+ <button type="submit" disabled={busy || code.trim().length !== 6}>
97
+ Sign in
98
+ </button>
99
+ <button type="button" disabled={busy} onClick={() => setSent(false)}>
100
+ Use another address
101
+ </button>
102
+ </p>
103
+ </form>
104
+ ) : null}
105
+ {error ? <p className="error">{error}</p> : null}
106
+ <p>
107
+ {/* Password, Google and registration live on the full sign-in page. */}
108
+ <a href={auth.signInUrl({ returnTo: '/' })}>
109
+ {offer.emailCode ? 'Other ways to sign in' : 'Sign in'}
110
+ </a>
111
+ {offer.signUp === 'hosted' ? (
112
+ <span className="muted"> (new accounts start there)</span>
113
+ ) : null}
114
+ </p>
115
+ </section>
116
+ )
117
+ }
118
+
119
+ export function App() {
120
+ // undefined while loading; null when sign-in is not available (local dev).
121
+ const [who, setWho] = useState<SignedInState | null | undefined>(undefined)
122
+ const [offer, setOffer] = useState<SignInOptions | null>(null)
123
+ const [best, setBest] = useState<number | null>(null)
124
+ const [score, setScore] = useState(0)
125
+ const [left, setLeft] = useState<number | null>(null)
126
+ const [error, setError] = useState<string | null>(null)
127
+
128
+ const refresh = useCallback(async () => {
129
+ try {
130
+ const state = await auth.me()
131
+ setWho(state)
132
+ if (!state.signedIn) setOffer(await auth.options())
133
+ } catch {
134
+ setWho(null)
135
+ }
136
+ try {
137
+ setBest((await api<{ best: number | null }>('/api/score')).best)
138
+ } catch (err) {
139
+ setError(errorMessage(err))
140
+ }
141
+ }, [])
142
+
143
+ // Also covers a visitor who comes back from the sign-in page or the e-mail link.
144
+ useEffect(() => {
145
+ void refresh()
146
+ }, [refresh])
147
+
148
+ useEffect(() => {
149
+ if (left === null || left <= 0) return
150
+ const timer = setTimeout(() => setLeft(left - 1), 1000)
151
+ return () => clearTimeout(timer)
152
+ }, [left])
153
+
154
+ const playing = left !== null && left > 0
155
+ const finished = left === 0
156
+
157
+ useEffect(() => {
158
+ if (!finished || !who?.signedIn || !who.access) return
159
+ api<{ best: number }>('/api/score', { method: 'PUT', body: { score } })
160
+ .then((saved) => setBest(saved.best))
161
+ .catch((err: unknown) => setError(errorMessage(err)))
162
+ }, [finished, who, score])
163
+
164
+ function start() {
165
+ setError(null)
166
+ setScore(0)
167
+ setLeft(ROUND_SECONDS)
168
+ }
169
+
170
+ async function signOut() {
171
+ try {
172
+ await auth.signOut()
173
+ } catch (err) {
174
+ setError(errorMessage(err))
175
+ }
176
+ setBest(null)
177
+ await refresh()
178
+ }
179
+
180
+ return (
181
+ <main>
182
+ <h1>Tap as fast as you can</h1>
183
+ <p className="muted">
184
+ {ROUND_SECONDS} seconds a round. Anyone can play; sign in to keep your best score.
185
+ </p>
186
+
187
+ <p className="actions">
188
+ {playing ? (
189
+ <button type="submit" onClick={() => setScore((value) => value + 1)}>
190
+ Tap ({left}s)
191
+ </button>
192
+ ) : (
193
+ <button type="submit" onClick={start}>
194
+ {finished ? 'Play again' : 'Start'}
195
+ </button>
196
+ )}
197
+ </p>
198
+ <p>
199
+ Score: <strong>{score}</strong>
200
+ {best !== null ? <span className="muted"> · Best: {best}</span> : null}
201
+ </p>
202
+ {error ? <p className="error">{error}</p> : null}
203
+
204
+ {who?.signedIn && !who.access ? (
205
+ <p className="actions">
206
+ <span className="muted">This account cannot use this app here.</span>
207
+ <button type="button" onClick={() => void signOut()}>
208
+ Sign out
209
+ </button>
210
+ </p>
211
+ ) : null}
212
+ {who?.signedIn && who.access ? (
213
+ <p className="actions">
214
+ <span className="muted">Signed in as {who.name ?? who.email}</span>
215
+ <button type="button" onClick={() => void signOut()}>
216
+ Sign out
217
+ </button>
218
+ </p>
219
+ ) : null}
220
+ {who && !who.signedIn && offer ? (
221
+ <SignIn offer={offer} onSignedIn={() => void refresh()} />
222
+ ) : null}
223
+ {who === null ? (
224
+ <p className="notice">
225
+ Sign-in works on the deployed app. Run <code>bun run deploy</code> and open the address it
226
+ prints.
227
+ </p>
228
+ ) : null}
229
+ </main>
230
+ )
231
+ }