create-marcapony-app 0.1.0 → 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 (35) hide show
  1. package/README.md +29 -27
  2. package/dist/index.d.ts +37 -3
  3. package/dist/index.js +138 -23
  4. package/package.json +5 -4
  5. package/template/base/.dev.vars.example +7 -0
  6. package/template/{_package.json → base/_package.json} +14 -10
  7. package/template/{marcapony.json → base/marcapony.json} +1 -1
  8. package/template/{scripts → base/scripts}/dev.ts +19 -2
  9. package/template/base/src/server/marcapony.ts +85 -0
  10. package/template/base/src/ui/api.ts +34 -0
  11. package/template/base/src/ui/styles.css +115 -0
  12. package/template/blank/README.md +48 -0
  13. package/template/{src → blank/src}/server/index.ts +9 -7
  14. package/template/booking/README.md +58 -0
  15. package/template/booking/marcapony.json +26 -0
  16. package/template/booking/src/server/index.ts +113 -0
  17. package/template/booking/src/ui/App.tsx +188 -0
  18. package/template/shop/README.md +66 -0
  19. package/template/shop/marcapony.json +12 -0
  20. package/template/shop/src/server/index.ts +211 -0
  21. package/template/shop/src/ui/App.tsx +214 -0
  22. package/template/team-tool/README.md +59 -0
  23. package/template/team-tool/marcapony.json +25 -0
  24. package/template/team-tool/src/server/index.ts +116 -0
  25. package/template/team-tool/src/ui/App.tsx +179 -0
  26. package/template/.dev.vars.example +0 -5
  27. package/template/README.md +0 -59
  28. package/template/src/server/marcapony.ts +0 -28
  29. package/template/src/ui/styles.css +0 -45
  30. /package/template/{_gitignore → base/_gitignore} +0 -0
  31. /package/template/{index.html → base/index.html} +0 -0
  32. /package/template/{src → base/src}/ui/main.tsx +0 -0
  33. /package/template/{tsconfig.json → base/tsconfig.json} +0 -0
  34. /package/template/{vite.config.ts → base/vite.config.ts} +0 -0
  35. /package/template/{src → blank/src}/ui/App.tsx +0 -0
package/README.md CHANGED
@@ -1,52 +1,54 @@
1
1
  # create-marcapony-app
2
2
 
3
- Scaffolds a Marcapony app: a Cloudflare Worker that talks to the Marcapony API
4
- through the SDK, plus a React UI served as static assets.
3
+ Creates a new Marcapony app: a small web app with its own backend, connected to
4
+ your Marcapony account and hosted by Marcapony.
5
5
 
6
6
  ```sh
7
- bunx create-marcapony-app my-app
7
+ npx create-marcapony-app my-app --template booking
8
8
  cd my-app
9
9
  bun install
10
- bunx marcapony app link
10
+ bun run link
11
11
  bun run dev
12
12
  ```
13
13
 
14
14
  When it is ready:
15
15
 
16
16
  ```sh
17
- bunx marcapony app deploy
17
+ bun run deploy
18
18
  ```
19
19
 
20
- No wrangler, no Cloudflare account, no git. The platform builds nothing for you
21
- locally and hosts the result.
20
+ `bun run link` and `bun run deploy` run the Marcapony CLI that the new project
21
+ pins in its `devDependencies`. `bun run link` also writes an `AGENTS.md` listing
22
+ exactly what the app is allowed to do, so an AI assistant can pick the project
23
+ up and build on it.
22
24
 
23
- ## What you get
25
+ ## Templates
24
26
 
25
- | Path | What it is |
26
- | ------------------------- | ------------------------------------------------ |
27
- | `src/server/index.ts` | The Worker. Only `/api/*` reaches it |
28
- | `src/server/marcapony.ts` | The only place that builds the Marcapony client |
29
- | `src/ui/` | React app, built to `dist/client` |
30
- | `marcapony.json` | How the platform builds and uploads the project |
31
- | `.gitignore` | Already ignores `.dev.vars`, before a key exists |
27
+ | Template | What it is | Runs in |
28
+ | ----------- | ------------------------------------------------------------------ | --------------- |
29
+ | `blank` | A starting point that lists your products (the default) | Your site |
30
+ | `booking` | Signed-in customers see, book and cancel their appointments | Customer portal |
31
+ | `shop` | Products, a cart and a checkout that sends the buyer to pay | Your site |
32
+ | `team-tool` | Your team approves, rejects and completes the day's reservations | Dashboard |
32
33
 
33
- The generated project has no `wrangler` dependency and no wrangler config. Local
34
- dev runs the server under Bun; the deployed app runs on the Workers runtime. They
35
- are close but not identical, so the generated README says to prefer plain web
36
- APIs in `src/server` and to check the app after deploying a server change.
34
+ Each template's `README.md` says which placement, data access, scopes and
35
+ permissions to choose when you create the app under **My Apps** in the
36
+ dashboard, which routes it exposes and what to change first.
37
37
 
38
38
  ## Options
39
39
 
40
- | Flag | Meaning |
41
- | --------- | ----------------------------------------------------- |
42
- | `--force` | Write into the directory even if it already has files |
43
- | `-h` | Help |
40
+ | Flag | Meaning |
41
+ | ----------------------- | ---------------------------------------------------------- |
42
+ | `--template`, `-t` | Which template to use; asked in a terminal, else `blank` |
43
+ | `--force` | Write into a directory that already has files; never overwrites a file that is there |
44
+ | `-h`, `--help` | Help |
44
45
 
45
- Run without a directory argument and it asks for one.
46
+ Run without a directory name and it asks for one.
46
47
 
47
- Requires Node ≥ 20 (or Bun). Zero runtime dependencies.
48
+ The scaffolder runs on Node 20 or newer and has no runtime dependencies. The app
49
+ it creates needs [Bun](https://bun.sh).
48
50
 
49
51
  ## License
50
52
 
51
- Proprietary tool, unrestricted output — the project it generates is yours to
52
- license and ship however you like. See [LICENSE.md](./LICENSE.md).
53
+ Proprietary tool, unrestricted output: the app it creates is yours to license
54
+ and ship however you like. See [LICENSE.md](./LICENSE.md).
package/dist/index.d.ts CHANGED
@@ -1,4 +1,21 @@
1
1
  #!/usr/bin/env node
2
+ export declare const TEMPLATES: readonly [{
3
+ readonly name: "blank";
4
+ readonly summary: "A starting point that lists your products";
5
+ }, {
6
+ readonly name: "booking";
7
+ readonly summary: "Customers book and cancel appointments in the portal";
8
+ }, {
9
+ readonly name: "shop";
10
+ readonly summary: "Products, a cart and checkout with a payment link";
11
+ }, {
12
+ readonly name: "team-tool";
13
+ readonly summary: "Your team approves and updates today's reservations";
14
+ }];
15
+ export type TemplateName = (typeof TEMPLATES)[number]['name'];
16
+ export declare const DEFAULT_TEMPLATE: TemplateName;
17
+ export declare function isTemplateName(value: string): value is TemplateName;
18
+ export declare function unknownTemplateMessage(name: string): string;
2
19
  /**
3
20
  * npm refuses to load a package whose name breaks its rules, and the name here
4
21
  * comes from a directory the user typed. Keep the recognizable part, drop the
@@ -8,14 +25,31 @@ export declare function sanitizePackageName(input: string): string;
8
25
  export declare function templateTargetName(name: string): string;
9
26
  export interface ParsedArgs {
10
27
  dir?: string;
28
+ /** As typed; validated by `run`. An empty string means the flag had no value. */
29
+ template?: string;
11
30
  force: boolean;
12
31
  help: boolean;
13
32
  }
14
33
  export declare function parseArgs(argv: string[]): ParsedArgs;
15
- export declare const HELP = "create-marcapony-app \u2014 scaffold a Marcapony app\n\nUsage\n bunx create-marcapony-app [directory] [--force]\n\nOptions\n --force Write into the directory even if it already has files\n -h Show this help\n\nNext, in the new directory:\n bunx marcapony app link get this app's key\n bun run dev run it locally\n bunx marcapony app deploy put it live\n";
16
- export declare function nextSteps(dir: string): string;
17
- /** Resolve `template/` relative to the compiled entry, not the cwd. */
34
+ export declare const HELP: string;
35
+ export declare function nextSteps(dir: string, template?: TemplateName): string;
36
+ /** Resolve `template/` (the directory holding `base/` and every overlay) relative to the compiled entry, not the cwd. */
18
37
  export declare function templateRoot(moduleUrl: string): string;
38
+ /**
39
+ * Copy the template, never overwriting a file that is already there.
40
+ *
41
+ * That matters most with `--force`, which is how someone lands here with a
42
+ * directory that already has content. Clobbering would destroy exactly the files
43
+ * you cannot get back: `.dev.vars` holds a key the platform will not show again,
44
+ * and `marcapony.json` holds the app slug `marcapony app link` wrote. Filling in
45
+ * only what is missing is both safer and the more useful meaning of --force.
46
+ */
19
47
  export declare function copyTemplate(from: string, to: string): void;
48
+ /**
49
+ * Scaffold one template: its overlay first, then the base. `copyTemplate` never
50
+ * overwrites, so an overlay file wins over the base file of the same name, and
51
+ * neither ever replaces a file that was already in the target.
52
+ */
53
+ export declare function scaffoldTemplate(root: string, template: TemplateName, to: string): void;
20
54
  export declare function applyPackageName(dir: string, name: string): void;
21
55
  export declare function run(argv: string[], moduleUrl: string): Promise<number>;
package/dist/index.js CHANGED
@@ -1,16 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync, } from 'node:fs';
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { createInterface } from 'node:readline/promises';
6
6
  /**
7
- * `create-marcapony-app` — copies the template in `template/` into a new
8
- * directory and points its package.json at the chosen name. Deliberately does
7
+ * `create-marcapony-app` — copies a template from `template/` into a new
8
+ * directory and points its package.json at the chosen name. Every template is
9
+ * the shared `template/base/` plus its own overlay (`template/<name>/`), whose
10
+ * files replace or add to the base. Deliberately does
9
11
  * no key handling and no deploy: `marcapony app link` mints the key and
10
12
  * `marcapony app deploy` ships the project, and both work on any project, not
11
13
  * just a scaffolded one.
12
14
  */
13
15
  const DEFAULT_DIR = 'marcapony-app';
16
+ export const TEMPLATES = [
17
+ { name: 'blank', summary: 'A starting point that lists your products' },
18
+ { name: 'booking', summary: 'Customers book and cancel appointments in the portal' },
19
+ { name: 'shop', summary: 'Products, a cart and checkout with a payment link' },
20
+ { name: 'team-tool', summary: "Your team approves and updates today's reservations" },
21
+ ];
22
+ export const DEFAULT_TEMPLATE = 'blank';
23
+ const BASE_DIR = 'base';
24
+ export function isTemplateName(value) {
25
+ return TEMPLATES.some((template) => template.name === value);
26
+ }
27
+ export function unknownTemplateMessage(name) {
28
+ return `Unknown template "${name}". Choose one of: ${TEMPLATES.map((t) => t.name).join(', ')}.\n`;
29
+ }
14
30
  /**
15
31
  * npm refuses to load a package whose name breaks its rules, and the name here
16
32
  * comes from a directory the user typed. Keep the recognizable part, drop the
@@ -41,11 +57,24 @@ export function templateTargetName(name) {
41
57
  }
42
58
  export function parseArgs(argv) {
43
59
  const out = { force: false, help: false };
44
- for (const arg of argv) {
60
+ for (let i = 0; i < argv.length; i++) {
61
+ const arg = argv[i];
45
62
  if (arg === '--force')
46
63
  out.force = true;
47
64
  else if (arg === '--help' || arg === '-h')
48
65
  out.help = true;
66
+ else if (arg === '--template' || arg === '-t') {
67
+ const value = argv[i + 1];
68
+ if (value !== undefined && !value.startsWith('-')) {
69
+ out.template = value;
70
+ i++;
71
+ }
72
+ else {
73
+ out.template = '';
74
+ }
75
+ }
76
+ else if (arg.startsWith('--template='))
77
+ out.template = arg.slice('--template='.length);
49
78
  else if (!arg.startsWith('-') && out.dir === undefined)
50
79
  out.dir = arg;
51
80
  }
@@ -54,46 +83,103 @@ export function parseArgs(argv) {
54
83
  export const HELP = `create-marcapony-app — scaffold a Marcapony app
55
84
 
56
85
  Usage
57
- bunx create-marcapony-app [directory] [--force]
86
+ npx create-marcapony-app [directory] [--template <name>] [--force]
87
+
88
+ Templates
89
+ ${TEMPLATES.map((t) => ` ${t.name.padEnd(10)} ${t.summary}`).join('\n')}
58
90
 
59
91
  Options
60
- --force Write into the directory even if it already has files
61
- -h Show this help
92
+ --template, -t <name> Which template to use (asked when omitted in a
93
+ terminal, otherwise ${DEFAULT_TEMPLATE})
94
+ --force Write into the directory even if it already has files
95
+ -h, --help Show this help
62
96
 
63
97
  Next, in the new directory:
64
- bunx marcapony app link get this app's key
65
- bun run dev run it locally
66
- bunx marcapony app deploy put it live
98
+ bun install install dependencies, including the Marcapony CLI
99
+ bun run link get this app's key
100
+ bun run dev run it locally
101
+ bun run deploy put it live
102
+
103
+ The scaffolder runs on Node 20 or newer. The app it creates needs Bun.
67
104
  `;
68
- export function nextSteps(dir) {
105
+ export function nextSteps(dir, template = DEFAULT_TEMPLATE) {
69
106
  return [
70
107
  '',
71
- `Created ${dir}.`,
108
+ `Created ${dir} from the ${template} template.`,
109
+ '',
110
+ 'Read its README.md first: it says what the app does and which scopes and',
111
+ 'permissions to enable when you create the app in the Marcapony dashboard.',
72
112
  '',
73
113
  'Next:',
74
114
  ` cd ${dir}`,
75
115
  ' bun install',
76
- ' bunx marcapony app link # writes your app key into .dev.vars',
116
+ ' bun run link # writes your app key into .dev.vars',
77
117
  ' bun run dev',
78
118
  '',
79
119
  'When it is ready:',
80
- ' bunx marcapony app deploy',
120
+ ' bun run deploy',
81
121
  '',
82
122
  ].join('\n');
83
123
  }
84
- /** Resolve `template/` relative to the compiled entry, not the cwd. */
124
+ /** Resolve `template/` (the directory holding `base/` and every overlay) relative to the compiled entry, not the cwd. */
85
125
  export function templateRoot(moduleUrl) {
86
126
  return resolve(dirname(fileURLToPath(moduleUrl)), '..', 'template');
87
127
  }
128
+ /**
129
+ * Copy the template, never overwriting a file that is already there.
130
+ *
131
+ * That matters most with `--force`, which is how someone lands here with a
132
+ * directory that already has content. Clobbering would destroy exactly the files
133
+ * you cannot get back: `.dev.vars` holds a key the platform will not show again,
134
+ * and `marcapony.json` holds the app slug `marcapony app link` wrote. Filling in
135
+ * only what is missing is both safer and the more useful meaning of --force.
136
+ */
88
137
  export function copyTemplate(from, to) {
89
138
  mkdirSync(to, { recursive: true });
90
- cpSync(from, to, { recursive: true });
139
+ cpSync(from, to, {
140
+ recursive: true,
141
+ force: false,
142
+ errorOnExist: false,
143
+ // Skip a template file when its destination — under the name it will
144
+ // actually land as — already exists.
145
+ filter: (source) => {
146
+ const relative = source.slice(from.length).replace(/^[/\\]/, '');
147
+ if (relative.length === 0)
148
+ return true;
149
+ // Always descend: an existing directory (from an overlay, or already in a
150
+ // --force target) must not hide the files beneath it.
151
+ if (statSync(source).isDirectory())
152
+ return true;
153
+ const segments = relative.split(/[/\\]/);
154
+ const last = segments[segments.length - 1];
155
+ if (last === undefined)
156
+ return true;
157
+ segments[segments.length - 1] = templateTargetName(last);
158
+ return !existsSync(join(to, ...segments));
159
+ },
160
+ });
91
161
  for (const [source, target] of Object.entries(TEMPLATE_RENAMES)) {
92
162
  const sourcePath = join(to, source);
93
- if (existsSync(sourcePath))
94
- renameSync(sourcePath, join(to, target));
163
+ if (!existsSync(sourcePath))
164
+ continue;
165
+ const targetPath = join(to, target);
166
+ if (existsSync(targetPath)) {
167
+ // The real name was already present, so the underscore copy is redundant.
168
+ rmSync(sourcePath);
169
+ continue;
170
+ }
171
+ renameSync(sourcePath, targetPath);
95
172
  }
96
173
  }
174
+ /**
175
+ * Scaffold one template: its overlay first, then the base. `copyTemplate` never
176
+ * overwrites, so an overlay file wins over the base file of the same name, and
177
+ * neither ever replaces a file that was already in the target.
178
+ */
179
+ export function scaffoldTemplate(root, template, to) {
180
+ copyTemplate(join(root, template), to);
181
+ copyTemplate(join(root, BASE_DIR), to);
182
+ }
97
183
  export function applyPackageName(dir, name) {
98
184
  const path = join(dir, 'package.json');
99
185
  const manifest = JSON.parse(readFileSync(path, 'utf8'));
@@ -113,26 +199,55 @@ async function promptForDir() {
113
199
  rl.close();
114
200
  }
115
201
  }
202
+ async function promptForTemplate() {
203
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
204
+ try {
205
+ process.stdout.write('Template:\n');
206
+ TEMPLATES.forEach((t, i) => {
207
+ process.stdout.write(` ${i + 1}. ${t.name.padEnd(10)} ${t.summary}\n`);
208
+ });
209
+ for (;;) {
210
+ const answer = (await rl.question(`Choose 1-${TEMPLATES.length} (1): `)).trim();
211
+ if (answer.length === 0)
212
+ return DEFAULT_TEMPLATE;
213
+ const byNumber = TEMPLATES[Number(answer) - 1];
214
+ if (/^\d+$/.test(answer) && byNumber)
215
+ return byNumber.name;
216
+ if (isTemplateName(answer))
217
+ return answer;
218
+ process.stdout.write(`Type a number from 1 to ${TEMPLATES.length}, or a template name.\n`);
219
+ }
220
+ }
221
+ finally {
222
+ rl.close();
223
+ }
224
+ }
116
225
  export async function run(argv, moduleUrl) {
117
226
  const args = parseArgs(argv);
118
227
  if (args.help) {
119
228
  process.stdout.write(HELP);
120
229
  return 0;
121
230
  }
231
+ if (args.template !== undefined && !isTemplateName(args.template)) {
232
+ process.stderr.write(unknownTemplateMessage(args.template));
233
+ return 1;
234
+ }
122
235
  const requested = args.dir ?? (process.stdin.isTTY ? await promptForDir() : DEFAULT_DIR);
123
236
  const target = resolve(process.cwd(), requested);
124
237
  if (isNonEmptyDir(target) && !args.force) {
125
238
  process.stderr.write(`${requested} already has files in it. Pick another name, or pass --force to write into it anyway.\n`);
126
239
  return 1;
127
240
  }
128
- const template = templateRoot(moduleUrl);
129
- if (!existsSync(template)) {
130
- process.stderr.write(`The template directory is missing from this install (looked in ${template}). Reinstall create-marcapony-app.\n`);
241
+ const root = templateRoot(moduleUrl);
242
+ if (!existsSync(join(root, BASE_DIR))) {
243
+ process.stderr.write(`The template directory is missing from this install (looked in ${root}). Reinstall create-marcapony-app.\n`);
131
244
  return 1;
132
245
  }
133
- copyTemplate(template, target);
246
+ const template = args.template ??
247
+ (process.stdin.isTTY ? await promptForTemplate() : DEFAULT_TEMPLATE);
248
+ scaffoldTemplate(root, template, target);
134
249
  applyPackageName(target, sanitizePackageName(basename(target)));
135
- process.stdout.write(nextSteps(requested));
250
+ process.stdout.write(nextSteps(requested, template));
136
251
  return 0;
137
252
  }
138
253
  /**
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "create-marcapony-app",
3
- "version": "0.1.0",
4
- "description": "Scaffold a Marcapony app — a Worker backed by the Marcapony API, ready for `marcapony app link` and `marcapony app deploy`",
3
+ "version": "0.2.0",
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",
7
7
  "homepage": "https://marcapony.com",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/creafolks/marcapony-api.git",
10
+ "url": "git+https://github.com/creafolks/marcapony-devkit.git",
11
11
  "directory": "create-app"
12
12
  },
13
13
  "publishConfig": {
@@ -27,7 +27,8 @@
27
27
  "build": "tsc -p tsconfig.build.json",
28
28
  "typecheck": "tsc --noEmit",
29
29
  "test": "bun test",
30
- "prepublishOnly": "bun run build"
30
+ "prepublishOnly": "bun run build",
31
+ "check:templates": "bun run scripts/check-templates.ts"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@types/bun": "^1.3.14",
@@ -0,0 +1,7 @@
1
+ # `bun run link` writes the real values into `.dev.vars` for you: the key is
2
+ # minted fresh and never passes through a clipboard. This file is only here to
3
+ # document what ends up there.
4
+ MARCAPONY_API_KEY=mpk_...
5
+ MARCAPONY_API_URL=https://api.marcapony.com/ext/v1
6
+ # MARCAPONY_APP_ID is not written locally. The platform sets it when the app is
7
+ # deployed, so locally there is no app id and identity() is always null.
@@ -5,23 +5,27 @@
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "bun run scripts/dev.ts",
8
+ "link": "marcapony app link",
9
+ "deploy": "marcapony app deploy",
8
10
  "build": "bun run build:client && bun run build:worker",
9
11
  "build:client": "vite build",
10
12
  "build:worker": "esbuild src/server/index.ts --bundle --format=esm --platform=neutral --conditions=worker,browser --target=es2022 --outfile=dist/worker/index.js",
11
13
  "typecheck": "tsc --noEmit"
12
14
  },
13
15
  "dependencies": {
14
- "hono": "^4.6.14",
15
- "marcapony-sdk": "^0.2.0",
16
- "react": "^19.0.0",
17
- "react-dom": "^19.0.0"
16
+ "hono": "^4.13.0",
17
+ "marcapony-sdk": "^0.6.0",
18
+ "react": "^19.3.0",
19
+ "react-dom": "^19.3.0"
18
20
  },
19
21
  "devDependencies": {
20
- "@types/react": "^19.0.0",
21
- "@types/react-dom": "^19.0.0",
22
- "@vitejs/plugin-react": "^5.0.0",
23
- "esbuild": "^0.25.0",
24
- "typescript": "^5.8.3",
25
- "vite": "^7.0.0"
22
+ "@types/bun": "^1.4.4",
23
+ "@types/react": "^19.3.0",
24
+ "@types/react-dom": "^19.3.0",
25
+ "@vitejs/plugin-react": "^5.2.0",
26
+ "esbuild": "^0.28.0",
27
+ "marcapony": "^0.4.0",
28
+ "typescript": "^5.9.0",
29
+ "vite": "^7.3.0"
26
30
  }
27
31
  }
@@ -6,6 +6,6 @@
6
6
  "not_found_handling": "single-page-application",
7
7
  "run_worker_first": ["/api/*"]
8
8
  },
9
- "compatibilityDate": "2025-05-10",
9
+ "compatibilityDate": "2026-10-01",
10
10
  "compatibilityFlags": ["nodejs_compat"]
11
11
  }
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Caveat worth knowing: this runs under Bun, not the Workers runtime. The two
6
6
  * are close but not identical, so a deployed app can still surface something
7
- * local dev did not. Verify after `bunx marcapony app deploy`, and prefer plain
7
+ * local dev did not. Verify after `bun run deploy`, and prefer plain
8
8
  * web APIs (fetch, Request, Response, crypto) over Node built-ins in
9
9
  * `src/server` — those are the ones that behave the same in both.
10
10
  */
@@ -27,10 +27,27 @@ function loadDevVars(): Record<string, string> {
27
27
  return out
28
28
  }
29
29
 
30
+ function readPlacement(): string | undefined {
31
+ try {
32
+ const config = JSON.parse(readFileSync('marcapony.json', 'utf8')) as { placement?: string }
33
+ return config.placement
34
+ } catch {
35
+ return undefined
36
+ }
37
+ }
38
+
30
39
  const env = loadDevVars()
31
40
  if (!env.MARCAPONY_API_KEY) {
32
41
  console.warn(
33
- `No MARCAPONY_API_KEY in ${ENV_FILE} — /api routes that call Marcapony will fail.\nRun \`bunx marcapony app link\` to get one.`,
42
+ `No MARCAPONY_API_KEY in ${ENV_FILE} — /api routes that call Marcapony will fail.\nRun \`bun run link\` to get one.`,
43
+ )
44
+ }
45
+
46
+ // A portal app only learns who is signed in from a header the platform adds,
47
+ // using the app id it sets at deploy. Neither exists here.
48
+ if (!env.MARCAPONY_APP_ID && readPlacement() === 'portal') {
49
+ console.info(
50
+ 'Local dev has no app id and no signed-in visitor, so identity is null and signed-in routes answer 401.\nTry those flows on the deployed app (`bun run deploy`), opened from the portal or the dashboard.',
34
51
  )
35
52
  }
36
53
 
@@ -0,0 +1,85 @@
1
+ import { createClient, MarcaponyError, type Identity } from 'marcapony-sdk'
2
+
3
+ /**
4
+ * The one place that owns the Marcapony env contract and builds the client.
5
+ * Keep it that way: a second `createClient` call somewhere else is how a key
6
+ * ends up read from the wrong place, or bundled into the browser.
7
+ */
8
+ export interface MarcaponyBindings {
9
+ /** Scoped app key (`mpk_...`). Written into `.dev.vars` by `bun run link`. */
10
+ MARCAPONY_API_KEY?: string
11
+ /** API root. Also written by `bun run link`; the SDK defaults to production. */
12
+ MARCAPONY_API_URL?: string
13
+ /**
14
+ * The app's id. The platform sets it when the app is deployed, and
15
+ * `identity()` needs it to check who is signed in. `bun run link` does not
16
+ * write it, so locally there is no app id (and no identity header either):
17
+ * identity is always null in local dev.
18
+ */
19
+ MARCAPONY_APP_ID?: string
20
+ }
21
+
22
+ export type Marcapony = ReturnType<typeof createClient>
23
+
24
+ /**
25
+ * Workers env is request-scoped, so build the client per request. The SDK is
26
+ * zero-dependency and holds no connections, so construction is effectively free.
27
+ */
28
+ export function marcaponyFromEnv(env: MarcaponyBindings): Marcapony {
29
+ if (!env.MARCAPONY_API_KEY) {
30
+ throw new Error(
31
+ 'MARCAPONY_API_KEY is missing. Run `bun run link` in this project. It writes the key into .dev.vars for you.',
32
+ )
33
+ }
34
+ return createClient({
35
+ apiKey: env.MARCAPONY_API_KEY,
36
+ baseUrl: env.MARCAPONY_API_URL,
37
+ appId: env.MARCAPONY_APP_ID,
38
+ })
39
+ }
40
+
41
+ /**
42
+ * Who is signed in on this request, or null. The SDK's `identity()` throws
43
+ * without an app id; locally there is none, so this answers null there instead
44
+ * of failing every request. Use it for display and for hiding buttons only:
45
+ * the platform enforces access itself on every call.
46
+ */
47
+ export async function identityOf(
48
+ mp: Marcapony,
49
+ env: MarcaponyBindings,
50
+ request: Request,
51
+ ): Promise<Identity | null> {
52
+ if (!env.MARCAPONY_APP_ID) return null
53
+ return mp.identity(request)
54
+ }
55
+
56
+ /**
57
+ * Whether Marcapony only simulated a write. New apps start in test mode, where
58
+ * writes answer with the record they would have created, marked
59
+ * `simulated: true`, and nothing is saved. The SDK types do not declare the
60
+ * marker yet, so read it defensively.
61
+ */
62
+ export function isSimulated(result: unknown): boolean {
63
+ return (
64
+ typeof result === 'object' &&
65
+ result !== null &&
66
+ (result as { simulated?: unknown }).simulated === true
67
+ )
68
+ }
69
+
70
+ /**
71
+ * Turns a failed call into a JSON answer for the browser. A Marcapony error
72
+ * keeps its status (401 not signed in, 403 not allowed, 404, 422 invalid
73
+ * input, 429) so the interface can tell the visitor what happened; anything
74
+ * else is a 500.
75
+ */
76
+ export function errorResponse(err: unknown): Response {
77
+ if (err instanceof MarcaponyError && err.status >= 400 && err.status < 500) {
78
+ return Response.json({ error: err.message, code: err.code }, { status: err.status })
79
+ }
80
+ console.error(err)
81
+ return Response.json(
82
+ { error: err instanceof Error ? err.message : 'Unexpected error' },
83
+ { status: 500 },
84
+ )
85
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Calls this app's own `/api` routes. The interface never talks to Marcapony
3
+ * directly: the app key lives on the server and must stay there.
4
+ */
5
+ export class ApiError extends Error {
6
+ readonly status: number
7
+
8
+ constructor(status: number, message: string) {
9
+ super(message)
10
+ this.status = status
11
+ }
12
+ }
13
+
14
+ export async function api<T>(path: string, init?: { method?: string; body?: unknown }): Promise<T> {
15
+ const response = await fetch(path, {
16
+ method: init?.method ?? (init?.body === undefined ? 'GET' : 'POST'),
17
+ headers: init?.body === undefined ? undefined : { 'Content-Type': 'application/json' },
18
+ body: init?.body === undefined ? undefined : JSON.stringify(init.body),
19
+ })
20
+ const body = (await response.json().catch(() => ({}))) as { error?: string }
21
+ if (!response.ok) {
22
+ throw new ApiError(response.status, body.error ?? `Request failed with status ${response.status}`)
23
+ }
24
+ return body as T
25
+ }
26
+
27
+ export function errorMessage(err: unknown): string {
28
+ return err instanceof Error ? err.message : 'Request failed'
29
+ }
30
+
31
+ /** One id per user action, reused when that action is retried. */
32
+ export function newRequestId(): string {
33
+ return crypto.randomUUID()
34
+ }