create-signet-app 0.4.8 → 0.6.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 (99) hide show
  1. package/README.md +133 -33
  2. package/{template-full → base/api}/api/app.ts +105 -13
  3. package/base/api/api/db/open.ts +121 -0
  4. package/{template-full → base/api}/api/db/schema.ts +34 -7
  5. package/{template-full → base/api}/api/env.ts +16 -0
  6. package/base/api/api/server.ts +163 -0
  7. package/{template-full → base/api}/api/services.ts +103 -10
  8. package/base/api/drizzle/0002_ai_paywalls_workflows.sql +77 -0
  9. package/base/api/drizzle/meta/0002_snapshot.json +1759 -0
  10. package/{template-full → base/api}/drizzle/meta/_journal.json +7 -0
  11. package/base/api/test/api.test.ts +51 -0
  12. package/base/api/test/helpers.ts +51 -0
  13. package/base/both/scripts/dev.ts +44 -0
  14. package/base/shared/README.md +385 -0
  15. package/{template-full → base/shared}/_github/workflows/ci.yml +1 -1
  16. package/{template-full → base/web}/src/lib/api.ts +28 -1
  17. package/{template-full → base/web}/src/main.tsx +4 -1
  18. package/{template-full → base/web}/src/routeTree.gen.ts +155 -90
  19. package/{template-full → base/web}/src/router.test.ts +13 -9
  20. package/base/web/src/routes/_app/index.tsx +55 -0
  21. package/{template-full → base/web}/src/routes/_app.tsx +40 -16
  22. package/{template-full → base/web}/vite.config.ts +3 -1
  23. package/package.json +9 -5
  24. package/parts/account/api/test/account.test.ts +30 -0
  25. package/parts/account/part.ts +6 -0
  26. package/parts/admin/api/test/admin.test.ts +35 -0
  27. package/parts/admin/part.ts +6 -0
  28. package/{template-full → parts/admin/web}/src/routes/_app/admin.tsx +2 -1
  29. package/parts/ai/api/api/routes/ai.ts +28 -0
  30. package/parts/ai/api/test/ai.test.ts +52 -0
  31. package/parts/ai/part.ts +16 -0
  32. package/{template-full → parts/auth/api}/api/routes/account.ts +32 -3
  33. package/{template-full → parts/auth/api}/api/routes/auth.ts +5 -3
  34. package/parts/auth/api/test/auth.test.ts +28 -0
  35. package/{template-full → parts/auth/both}/e2e/smoke.spec.ts +21 -7
  36. package/parts/auth/part.ts +22 -0
  37. package/parts/growth/part.ts +7 -0
  38. package/{template-full/_mcp → parts/mcp/api}/test/mcp.test.ts +25 -16
  39. package/parts/mcp/part.ts +8 -0
  40. package/parts/notifications/api/test/notifications.test.ts +18 -0
  41. package/parts/notifications/part.ts +6 -0
  42. package/{template-full → parts/notifications/web}/src/routes/_app/notifications.tsx +1 -1
  43. package/parts/orgs/api/test/orgs.test.ts +56 -0
  44. package/parts/orgs/part.ts +7 -0
  45. package/{template-full → parts/payments/api}/api/routes/billing.ts +3 -2
  46. package/parts/payments/api/test/payments.test.ts +31 -0
  47. package/parts/payments/part.ts +12 -0
  48. package/{template-full → parts/payments/web}/src/routes/_app/billing.tsx +6 -3
  49. package/parts/paywalls/api/api/routes/paywall.ts +126 -0
  50. package/parts/paywalls/api/test/paywalls.test.ts +71 -0
  51. package/parts/paywalls/part.ts +8 -0
  52. package/parts/privacy/api/test/privacy.test.ts +20 -0
  53. package/parts/privacy/part.ts +7 -0
  54. package/parts/workflows/api/api/workflows.ts +33 -0
  55. package/parts/workflows/api/test/workflows.test.ts +44 -0
  56. package/parts/workflows/part.ts +7 -0
  57. package/parts/workflows/web/src/routes/_app/approvals.tsx +34 -0
  58. package/src/compose.ts +426 -0
  59. package/src/desktop.ts +10 -10
  60. package/src/index.ts +407 -174
  61. package/template-api/_targets/deno/Dockerfile +12 -0
  62. package/template-api/_targets/deno/_dockerignore +10 -0
  63. package/template-api/_targets/deno/src/server.ts +43 -0
  64. package/template-full/README.md +0 -166
  65. package/template-full/api/db/open.ts +0 -33
  66. package/template-full/api/server.ts +0 -50
  67. package/template-full/scripts/dev.ts +0 -17
  68. package/template-full/src/routes/_app/index.tsx +0 -33
  69. package/template-full/test/api.test.ts +0 -238
  70. package/template-full/tsconfig.json +0 -9
  71. /package/{template-full → base/api}/api/db/index.ts +0 -0
  72. /package/{template-full → base/api}/api/db/kv.ts +0 -0
  73. /package/{template-full → base/api}/drizzle/0000_init.sql +0 -0
  74. /package/{template-full → base/api}/drizzle/0001_orgs.sql +0 -0
  75. /package/{template-full → base/api}/drizzle/meta/0000_snapshot.json +0 -0
  76. /package/{template-full → base/api}/drizzle/meta/0001_snapshot.json +0 -0
  77. /package/{template-full → base/api}/drizzle.config.ts +0 -0
  78. /package/{template-full → base/api}/tsconfig.api.json +0 -0
  79. /package/{template-full → base/shared}/_gitignore +0 -0
  80. /package/{template-full → base/shared}/biome.json +0 -0
  81. /package/{template-full → base/web}/index.html +0 -0
  82. /package/{template-full → base/web}/src/app.css +0 -0
  83. /package/{template-full → base/web}/src/components/toaster.tsx +0 -0
  84. /package/{template-full → base/web}/src/router.ts +0 -0
  85. /package/{template-full → base/web}/src/routes/__root.tsx +0 -0
  86. /package/{template-full → base/web}/tsconfig.app.json +0 -0
  87. /package/{template-full → base/web}/tsconfig.node.json +0 -0
  88. /package/{template-full → base/web}/tsconfig.test.json +0 -0
  89. /package/{template-full → parts/account/web}/src/routes/_app/account.tsx +0 -0
  90. /package/{template-full → parts/auth/both}/playwright.config.ts +0 -0
  91. /package/{template-full → parts/auth/web}/src/routes/login.tsx +0 -0
  92. /package/{template-full → parts/notifications/api}/api/routes/notifications.ts +0 -0
  93. /package/{template-full → parts/orgs/web}/src/routes/_app/org/index.tsx +0 -0
  94. /package/{template-full → parts/orgs/web}/src/routes/_app/org/members.tsx +0 -0
  95. /package/{template-full → parts/orgs/web}/src/routes/_app/org/new.tsx +0 -0
  96. /package/{template-full → parts/orgs/web}/src/routes/invite.$token.tsx +0 -0
  97. /package/{template-full → parts/payments/api}/api/plans.ts +0 -0
  98. /package/{template-full → parts/privacy/api}/api/routes/privacy.ts +0 -0
  99. /package/{template-full → parts/privacy/web}/src/routes/_app/privacy.tsx +0 -0
package/README.md CHANGED
@@ -4,62 +4,149 @@ Scaffold a Vite + React 19 + TypeScript + Tailwind v4 app wired to
4
4
  `@dapplelight/signet-tokens`, `@dapplelight/signet-ui` and `@dapplelight/signet-lib`.
5
5
 
6
6
  ```bash
7
- npx create-signet-app@latest my-app --template full
7
+ npx create-signet-app@latest my-app --starter full
8
8
  cd my-app
9
9
  npm install
10
10
  npm run dev
11
11
  ```
12
12
 
13
- With pnpm: `pnpm create signet-app my-app --template full`. With bun:
14
- `bunx create-signet-app my-app --template full`. Then install and `run dev` with
15
- the same manager. Open `http://localhost:5173`. `full` needs
13
+ With pnpm: `pnpm create signet-app my-app --starter full`. With bun:
14
+ `bunx create-signet-app my-app --starter full`. Then install and `run dev` with
15
+ the same manager. Open `http://localhost:5173`. A composed app needs
16
16
  [Bun](https://bun.sh) 1.3+ installed: `run dev` is a Bun script, whichever
17
17
  package manager installs the app.
18
18
 
19
19
  `--theme` takes `editorial`, `cinematic` or `finance` (editorial plus the
20
20
  spend-category and money tokens; default `editorial`).
21
21
 
22
- `--pm bun|npm|pnpm` sets the commands printed after scaffolding, in the CI
23
- workflow (setup, frozen install, `<pm> run`) and in the full template's README.
24
- Default: the package manager that ran it (`npm create` / `pnpm create` say so
25
- in `npm_config_user_agent`), else bun. With pnpm a `pnpm-workspace.yaml`
26
- approves esbuild's and workerd's build scripts, which pnpm 10+ otherwise refuses
27
- to install without. Tests stay on `bun test`, so CI sets up Bun too.
28
-
29
- ## Which template
30
-
31
- `--template` defaults to `web`.
32
-
33
- | Template | Frontend | API | Database | Auth | MCP | Runs on |
22
+ `--pm bun|npm|pnpm|yarn|deno` sets the commands printed after scaffolding, in
23
+ the CI workflow (setup, frozen install, `<pm> run` or `deno task`) and in the
24
+ app's README. Default: the package manager that ran it (`npm create`, `pnpm
25
+ create`, `yarn create`, `bunx`, `deno run` say so in `npm_config_user_agent`),
26
+ else bun. With pnpm a `pnpm-workspace.yaml` approves esbuild's and workerd's
27
+ build scripts, which pnpm 10+ otherwise refuses to install without. With yarn
28
+ the app pins modern Yarn in `packageManager` (CI runs `corepack enable`), uses
29
+ a plain `node_modules` (`.yarnrc.yml`), and lists signet-ui's required peers,
30
+ which Yarn does not install on its own. Deno 2 installs and runs the
31
+ `package.json` scripts; `--platform cli` is refused with deno, as its build is
32
+ `bun build --compile`. Tests stay on `bun test`, so CI sets up Bun too.
33
+ `bun run test:pm` scaffolds the full starter and the web platform with each
34
+ manager installed on the machine, installs, typechecks and builds.
35
+
36
+ ## Which platform
37
+
38
+ `--platform` defaults to `web`. `--template` is its old name and still works;
39
+ `--template full` is `--starter full` (below).
40
+
41
+ | Platform | Frontend | API | Database | Auth | MCP | Runs on |
34
42
  |---|---|---|---|---|---|---|
35
43
  | `web` | Vite + React + Signet UI, TanStack Router | none (a configured `createApiClient` for yours) | none | placeholder `/login` | no | any static host |
36
44
  | `api` | none | Hono with the error envelope and request ids | none (add with `signet add db`) | none (add with `signet add auth`) | `/mcp`, default on | `--target` cloudflare, bun, node or vercel |
37
- | `full` | the `web` app plus account, inbox, privacy, billing, admin | Hono on Bun, served with the built app | SQLite with migrations | phone codes, stored sessions, orgs | `/mcp`, default on | Bun (one process) |
38
45
  | `cli` | none | none | none | device-code login | no | one compiled Bun binary |
39
46
  | `extension` | Chrome MV3: popup, options, service worker | none | none | PKCE via `chrome.identity` | no | Chrome |
40
47
  | `desktop` | Tauri v2 window and menu-bar app | none | none | browser sign-in (PKCE, loopback) | no | macOS, Windows, Linux |
41
48
 
49
+ ## Composed apps: parts, starters, `--ui` and `--api`
50
+
51
+ A web app and its API in one project, built from **parts**. Any of these flags
52
+ composes one (they do not mix with `--platform`):
53
+
54
+ ```bash
55
+ bunx create-signet-app my-app --starter full # every part, web + API
56
+ bunx create-signet-app my-app --with payments,notifications # those, plus what they need
57
+ bunx create-signet-app my-app --without admin,privacy # the full starter without them
58
+ bunx create-signet-app my-api --api --with orgs # the API half only
59
+ bunx create-signet-app my-ui --ui --with account # the web half only
60
+ bunx create-signet-app my-app --starter blank # no parts: shell, API, database
61
+ bunx create-signet-app my-app --starter saas --with ai # a starter, plus a part
62
+ ```
63
+
64
+ - **Surfaces.** Both halves by default. `--ui` writes the web half only: its
65
+ client calls an API elsewhere (`VITE_API_URL`, else the same origin), untyped
66
+ until you point `src/lib/api.ts` at that API's `AppType`. `--api` writes the
67
+ API half only: no web files, no Vite. `--ui --api` together is an error (it
68
+ is the default).
69
+ - **Starters** are named mixes of parts, by the shape of app. `--with` adds to
70
+ the starter, `--without` takes away; `--without` alone starts from `full`.
71
+ Run with no flags on a terminal to pick a platform or starter from a list.
72
+
73
+ | starter | parts (plus what they need) |
74
+ | --- | --- |
75
+ | `full` | every part (`--template full` is the same) |
76
+ | `blank` | none: the shell, the API, the database |
77
+ | `saas` | account, orgs, admin, notifications, privacy, payments |
78
+ | `launch` | account, privacy, growth (waitlist, invites, referrals, feedback) |
79
+ | `internal-tool` | account, orgs, admin, workflows |
80
+ | `api` | account, payments; the API half only |
81
+ | `ai-app` | account, privacy, payments, ai |
82
+ | `paywall` | account, payments, paywalls |
83
+ | `automation` | account, notifications, workflows |
84
+ - **Needs** come along on their own and the output says so (`--with payments`
85
+ prints `added auth for payments`). Leaving out a part another one needs is
86
+ an error.
87
+ - **Runtime.** `--target bun|deno|node` picks what runs the API (default
88
+ `bun`: Bun.serve and bun:sqlite, as before). `deno` (Deno 2) and `node`
89
+ (22.18+) get node:sqlite under Drizzle and a node:http server instead, and
90
+ their `dev`/`start` scripts run on that runtime with `.env` loaded. Tests stay
91
+ on `bun test` (Bun runs node:sqlite too). `bun run test:runtime` serves the
92
+ full starter on each runtime installed and checks `/api/health`, an MCP call
93
+ and the built page.
94
+ - **MCP** is the `mcp` part. As before it is asked for on a terminal (default
95
+ yes) unless `--mcp`, `--no-mcp`, `--with mcp` or `--without mcp` says.
96
+
97
+ | Part | What it adds | Needs |
98
+ |---|---|---|
99
+ | `auth` | phone one-time codes, stored sessions, `/login`, sign-out | |
100
+ | `account` | `/account`: profile, signed-in devices, API keys | auth |
101
+ | `orgs` | a personal org each, members, roles, invite links, `/org`, `/invite/$token`, tenant middleware | auth |
102
+ | `admin` | `/admin`: the operator's panel over every table, by platform role | auth, orgs |
103
+ | `notifications` | the in-app inbox and preferences, `/notifications` | auth |
104
+ | `privacy` | DPDP consent and data export / erasure requests, `/privacy` | auth |
105
+ | `payments` | plans (`api/plans.ts`), entitlements, `/billing`, gateway webhooks | auth |
106
+ | `paywalls` | remote paywalls: versioned offerings and placements with audience overrides (signet-db's `createOfferings`), `GET /api/paywall/:placement`; with `admin`, publishing under `/api/admin/paywalls` (API only) | payments |
107
+ | `growth` | waitlist, invites, referral codes, referrals, feedback and marks tables, with signet-db's `createGrowth` (API only) | |
108
+ | `ai` | AI spend caps per user and for the app (signet-db's `createAiSpend`, `requireAiSpend` on `/api/ai/*`), a sample `/api/ai/summary` on signet-ai's fake provider (no key needed); with `admin`, `/api/admin/ai-spend` (API only) | auth |
109
+ | `workflows` | durable workflows (signet-db's `createWorkflows`) at `/api/workflows`, a generic approval-request example, the runner in `api/server.ts`, `/approvals` | auth |
110
+ | `mcp` | the API's validated routes as tools at `/mcp` (API only) | |
111
+
112
+ ### How parts are put together
113
+
114
+ `base/` is the app with no parts; `parts/<name>/` holds what one part adds,
115
+ with a small typed manifest (`part.ts`: needs, dependencies, env lines, its
116
+ tables). Both are split into halves, each laid over the app root: `shared/`
117
+ (always), `web/`, `api/`, and `both/` (with both surfaces). Code several parts
118
+ share (`api/app.ts`, the schema, `services.ts`, the shell and nav, the route
119
+ tree, the tests' helpers) lives in `base/` once, with each part's lines marked
120
+ `// <part>:begin` / `// <part>:end` (or a single line ending in `// @<part>`;
121
+ `!<part>` means without it; `web` and `api` are the surfaces). The composer
122
+ keeps the chosen lines and drops every marker, so an app has no trace of the
123
+ parts it left out. The migrations in `base/api/drizzle/` cover every table; the
124
+ composer keeps the statements and snapshot entries for the chosen parts' tables
125
+ (a table two parts list, like `usage_counters` for `payments` and `ai`, stays
126
+ with either), drops a migration left empty and moves the later ones up a
127
+ number, so `db:check` passes and `db:generate` finds nothing to do.
128
+
42
129
  ## AI-assisted planning: `--describe`
43
130
 
44
131
  ```bash
45
132
  bunx create-signet-app my-app --describe "a team inbox with settings and pricing"
46
133
  ```
47
134
 
48
- One sentence picks the template (`web`, `api` or `full`) and theme, splits the
49
- sentence into pages, asks signet-mcp's `plan_page` about each, scaffolds the
50
- app, and writes `PLAN.md` (the pages, with blocks, components, data and files
51
- for each) and `AGENTS.md` (the instructions an agent working in the app
52
- should follow). It is deterministic and makes no LLM call: the same sentence
53
- always gives the same files. Keyword lists choose between Signet's own
54
- templates and themes; a sentence that names none gets `web` and `editorial`.
135
+ One sentence picks the platform (`web` or `api`) or the `full` starter and the
136
+ theme, splits the sentence into pages, asks signet-mcp's `plan_page` about each,
137
+ scaffolds the app, and writes `PLAN.md` (the pages, with blocks, components,
138
+ data and files for each) and `AGENTS.md` (the instructions an agent working in
139
+ the app should follow). It is deterministic and makes no LLM call: the same
140
+ sentence always gives the same files. Keyword lists choose between Signet's own
141
+ platforms and themes; a sentence that names none gets `web` and `editorial`.
55
142
 
56
- An explicit `--template` or `--theme` wins over what the sentence implies.
143
+ An explicit `--platform` or `--theme` wins over what the sentence implies.
57
144
  `--describe` applies to `web`, `api` and `full` only.
58
145
 
59
- ## `--template full`: web app + API in one project
146
+ ## `--starter full`: web app + API in one project
60
147
 
61
148
  ```bash
62
- npx create-signet-app@latest my-app --template full
149
+ npx create-signet-app@latest my-app --starter full
63
150
  cd my-app
64
151
  npm install
65
152
  npm run dev
@@ -107,9 +194,11 @@ same-origin. In dev, Vite proxies `/api` to it. What a fresh app has:
107
194
  across orgs.
108
195
  - **Env.** `api/env.ts` (`createEnv`), and a generated, gitignored env file
109
196
  with fresh `SESSION_SECRET` / `OTP_SECRET`.
110
- - **MCP** as in the api template (`--mcp` / `--no-mcp`).
111
- - **Tests.** `test/api.test.ts` drives sign-in, plans, inbox, admin roles,
112
- consent and sign-out against an in-memory database; `src/router.test.ts`
197
+ - **MCP** as in the api platform (`--mcp` / `--no-mcp`).
198
+ - **Tests.** One file per part under `test/` (`auth.test.ts`,
199
+ `payments.test.ts`, …, sharing `test/helpers.ts`) drives sign-in, plans,
200
+ inbox, admin roles, consent, API keys, orgs and sign-out against an in-memory
201
+ database; `src/router.test.ts`
113
202
  resolves every page; `e2e/smoke.spec.ts` (Playwright, `test:e2e`) starts the
114
203
  server with a throwaway database, reads the code from its console and goes
115
204
  sign-in → admin → billing → inbox → account → privacy in headless Chromium,
@@ -156,9 +245,9 @@ copied between repos as a block. Copy-paste is not configuration.
156
245
  paint — React mounts too late, and without it there is a visible flash
157
246
  - `src/lib/api.ts` with a configured `createApiClient`
158
247
 
159
- ## `--template api`: a Hono API on the runtime you pick
248
+ ## `--platform api`: a Hono API on the runtime you pick
160
249
 
161
- `bun create-signet-app my-api --template api [--target cloudflare|bun|node|vercel]`
250
+ `bun create-signet-app my-api --platform api [--target cloudflare|bun|node|vercel]`
162
251
  scaffolds a Hono API. Every target shares `src/app.ts`, `src/env.ts`, the tests
163
252
  and CI; `--target` decides the entry and its config, and only that target's
164
253
  files are written:
@@ -260,7 +349,18 @@ config into anything new produces a crash.
260
349
 
261
350
  ## Test
262
351
 
263
- `test/scaffold-full.ts` scaffolds the full template outside the monorepo with
352
+ `bun run test:parts` (`test/scaffold-parts.ts`; CI runs it on PRs that touch
353
+ this package and nightly) scaffolds each part alone (plus what it needs), no
354
+ parts and every part, on each surface (`--ui`, `--api`, both), and checks each
355
+ app: no markers or placeholders left, only its surfaces' files, every
356
+ dependency imported (or a peer of one that is) and every import declared, lint,
357
+ typecheck, its tests, and the build (web) or `db:check` plus a `drizzle-kit
358
+ generate` that finds nothing to do (api). Every app's dependencies are
359
+ installed once, into one shared directory each app links to; the apps run in
360
+ parallel, and a step over files identical to an earlier app's runs once.
361
+ `bun run test/scaffold-parts.ts api payments` runs one.
362
+
363
+ `test/scaffold-full.ts` scaffolds the full starter outside the monorepo with
264
364
  `--theme finance`, installs packs of every Signet package it uses, then lints,
265
365
  typechecks, runs the app's tests, builds, checks the finance tokens reached the
266
366
  CSS, and runs the app's Playwright smoke test headless. A `--no-mcp --pm pnpm`
@@ -1,9 +1,20 @@
1
+ // auth:begin
1
2
  import { sessionRoutes } from "@dapplelight/signet-server/auth/hono"
3
+ // auth:end
4
+ // orgs:begin
2
5
  import { maskPhone } from "@dapplelight/signet-server/auth/otp"
6
+ // orgs:end
3
7
  import { errorHandler } from "@dapplelight/signet-server/http"
4
- import { adminRoutes } from "@dapplelight/signet-server/http/admin"
5
- import { ApiException } from "@dapplelight/signet-server/http/errors"
8
+ import { adminRoutes } from "@dapplelight/signet-server/http/admin" // @admin
9
+ // ai:begin
10
+ import { aiSpendAdminRoutes, requireAiSpend } from "@dapplelight/signet-server/http/ai-spend" // @admin
11
+ import { requireAiSpend } from "@dapplelight/signet-server/http/ai-spend" // @!admin
12
+ // ai:end
13
+ import { ApiException } from "@dapplelight/signet-server/http/errors" // @admin
14
+ // orgs:begin
6
15
  import { orgRoutes, tenant } from "@dapplelight/signet-server/http/orgs"
16
+ // orgs:end
17
+ import { workflowRoutes } from "@dapplelight/signet-server/http/workflows" // @workflows
7
18
  // mcp:begin
8
19
  import { appTools } from "@dapplelight/signet-server/mcp"
9
20
  import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
@@ -15,40 +26,66 @@ import { healthRoutes } from "@dapplelight/signet-server/observability/health"
15
26
  import { createLogger } from "@dapplelight/signet-server/observability/logger"
16
27
  import { requestLog } from "@dapplelight/signet-server/observability/request-log"
17
28
  import { traceMiddleware } from "@dapplelight/signet-server/observability/trace"
29
+ // orgs:begin
18
30
  import { inArray } from "drizzle-orm"
31
+ // orgs:end
19
32
  import { Hono } from "hono"
20
- import { type User, users } from "./db/schema.ts"
33
+ // auth:begin
34
+ import { type User, users } from "./db/schema.ts" // @orgs
35
+ import type { User } from "./db/schema.ts" // @!orgs
36
+ // auth:end
21
37
  import { env } from "./env.ts"
22
- import { accountRoutes } from "./routes/account.ts"
23
- import { authRoutes, requireUser } from "./routes/auth.ts"
38
+ import { accountRoutes } from "./routes/account.ts" // @auth
39
+ import { aiRoutes } from "./routes/ai.ts" // @ai
40
+ import { authRoutes, requireUser } from "./routes/auth.ts" // @auth
41
+ // payments:begin
24
42
  import { billingRoutes, billingWebhooks } from "./routes/billing.ts"
43
+ // payments:end
44
+ // notifications:begin
25
45
  import { notificationRoutes } from "./routes/notifications.ts"
46
+ // notifications:end
47
+ // paywalls:begin
48
+ import { paywallAdminRoutes, paywallRoutes } from "./routes/paywall.ts" // @admin
49
+ import { paywallRoutes } from "./routes/paywall.ts" // @!admin
50
+ // paywalls:end
51
+ // privacy:begin
26
52
  import { privacyRoutes } from "./routes/privacy.ts"
27
- import { createServices, type Deps, TRUST } from "./services.ts"
53
+ // privacy:end
54
+ import { createServices, type Deps, TRUST } from "./services.ts" // @auth
55
+ import { approvalRequest } from "./workflows.ts" // @workflows
56
+ import { type Deps, TRUST } from "./services.ts" // @!auth
28
57
 
29
- export type AppEnv = { Variables: { reqId: string; user: User } }
58
+ export type AppEnv = { Variables: { reqId: string; user: User } } // @auth
59
+ export type AppEnv = { Variables: { reqId: string } } // @!auth
30
60
 
61
+ // auth:begin
31
62
  /** Paths that need a signed-in user. Everything else under /api is public. */
32
63
  const SIGNED_IN = [
33
- "/api/account",
34
- "/api/notifications",
35
- "/api/privacy",
36
- "/api/billing",
37
- "/api/admin",
64
+ "/api/account", // the user, profile and API keys
65
+ "/api/notifications", // the inbox // @notifications
66
+ "/api/privacy", // consent and data requests // @privacy
67
+ "/api/billing", // plan and checkout // @payments
68
+ "/api/admin", // the operator's admin API // @admin
69
+ "/api/ai", // AI calls, within the spend caps // @ai
70
+ "/api/paywall", // the paywall for a placement // @paywalls
71
+ "/api/workflows", // workflow runs and approvals // @workflows
38
72
  ]
73
+ // auth:end
39
74
 
40
75
  /** Probes stay out of spans and logs. */
41
76
  const HEALTH_PATHS = ["/health/live", "/health/ready"]
42
77
 
78
+ // orgs:begin
43
79
  /** An invite link can be looked at before signing in; everything else under /api/orgs needs a user. */
44
80
  const INVITE_PREVIEW = /^\/api\/orgs\/invites\/[^/]+$/
81
+ // orgs:end
45
82
 
46
83
  /**
47
84
  * The API. server.ts serves it (and the built web app) under Bun; tests call
48
85
  * `createApp(deps).request(...)` with an in-memory database.
49
86
  */
50
87
  export function createApp(deps: Deps) {
51
- const s = createServices(deps)
88
+ const s = createServices(deps) // @auth
52
89
  const base = new Hono<AppEnv>().use("*", requestId())
53
90
  // Off unless server.ts passes `observability` (OBSERVABILITY=on): then a span
54
91
  // and a JSON log line pair per request, both carrying the trace id, and
@@ -68,7 +105,21 @@ export function createApp(deps: Deps) {
68
105
  // served from this same origin, so nothing else needs trusting.
69
106
  base.use("/api/*", csrfMiddleware())
70
107
  base.use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
108
+ // auth:begin
71
109
  for (const path of SIGNED_IN) base.use(`${path}/*`, requireUser(s))
110
+ // auth:end
111
+ // ai:begin
112
+ // Over the caller's or the app's AI spend cap: 429 with Retry-After, before
113
+ // the route runs (caps in api/env.ts and the ai_spend_caps table).
114
+ base.use(
115
+ "/api/ai/*",
116
+ requireAiSpend({
117
+ spend: s.aiSpend,
118
+ subject: (c) => ({ userId: (c.get("user" as never) as User).id }),
119
+ }),
120
+ )
121
+ // ai:end
122
+ // orgs:begin
72
123
  const gate = requireUser(s)
73
124
  base.use("/api/orgs/*", (c, next) =>
74
125
  c.req.method === "GET" && INVITE_PREVIEW.test(c.req.path) ? next() : gate(c, next),
@@ -77,16 +128,41 @@ export function createApp(deps: Deps) {
77
128
  // ORG_ROOT_DOMAIN, the x-org header, or the cookie the switcher sets. It
78
129
  // grants nothing: /api/orgs checks membership on every call.
79
130
  base.use("/api/*", tenant({ orgs: s.orgs, rootDomain: env.ORG_ROOT_DOMAIN }))
131
+ // orgs:end
80
132
 
81
133
  const app = base
82
134
  .get("/api/health", (c) => c.json({ ok: true }))
135
+ // auth:begin
83
136
  .route("/api/auth", authRoutes(s))
84
137
  .route("/api/sessions", sessionRoutes(s.sessions))
85
138
  .route("/api/account", accountRoutes(s))
139
+ // auth:end
140
+ // notifications:begin
86
141
  .route("/api/notifications", notificationRoutes(s))
142
+ // notifications:end
143
+ // privacy:begin
87
144
  .route("/api/privacy", privacyRoutes(s))
145
+ // privacy:end
146
+ // payments:begin
88
147
  .route("/api/billing", billingRoutes(s))
89
148
  .route("/api/webhooks", billingWebhooks(s))
149
+ // payments:end
150
+ .route("/api/ai", aiRoutes(s)) // @ai
151
+ .route("/api/paywall", paywallRoutes(s)) // @paywalls
152
+ // workflows:begin
153
+ // Durable workflows (api/workflows.ts): anyone signed in may start an
154
+ // approval request and decide the ones waiting on them; admins see every run.
155
+ .route(
156
+ "/api/workflows",
157
+ workflowRoutes({
158
+ workflows: s.workflows,
159
+ subject: (c) => (c.get("user" as never) as User).id,
160
+ isAdmin: (c) => (c.get("user" as never) as User).role === "admin",
161
+ canStart: (_c, workflow) => workflow === approvalRequest.name,
162
+ }),
163
+ )
164
+ // workflows:end
165
+ // orgs:begin
90
166
  // Orgs: switch, settings, members, invites (signet-server orgRoutes).
91
167
  // Guard your own org routes the same way: orgGuards({ orgs: s.orgs, userId })
92
168
  // .requirePermission("projects:write"), then scoped(s.db, { orgId: currentTenant(c).id }).
@@ -108,6 +184,21 @@ export function createApp(deps: Deps) {
108
184
  ),
109
185
  }),
110
186
  )
187
+ // orgs:end
188
+ // admin:begin
189
+ // ai:begin
190
+ // AI spend for admins: usage, top spenders, and caps per user or for the app.
191
+ .route(
192
+ "/api/admin/ai-spend",
193
+ aiSpendAdminRoutes({
194
+ spend: s.aiSpend,
195
+ authorize: (c) => (c.get("user" as never) as User).role === "admin",
196
+ actor: (c) => ({ type: "user", id: (c.get("user" as never) as User).id }),
197
+ }),
198
+ )
199
+ // ai:end
200
+ // Publishing offerings and pointing placements at them. // @paywalls
201
+ .route("/api/admin/paywalls", paywallAdminRoutes(s)) // @paywalls
111
202
  // The operator's admin API over every org (signet-db defineAdmin, config
112
203
  // in services.ts): platform roles readonly, staff and admin (ADMIN_PHONES)
113
204
  // only; everyone else gets 403. Org owners manage their org under /org.
@@ -122,6 +213,7 @@ export function createApp(deps: Deps) {
122
213
  },
123
214
  }),
124
215
  )
216
+ // admin:end
125
217
  .onError(errorHandler({ isProduction }))
126
218
 
127
219
  if (obs) {
@@ -0,0 +1,121 @@
1
+ import { Database } from "bun:sqlite" // @bun
2
+ import { mkdirSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+ import { DatabaseSync } from "node:sqlite" // @!bun
5
+ import { fromDrizzle } from "@dapplelight/signet-db" // @!bun
6
+ import { createDb } from "@dapplelight/signet-db/sqlite" // @bun
7
+ import { paymentsSchema } from "@dapplelight/signet-payments" // @payments
8
+ // !bun:begin
9
+ import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm"
10
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator"
11
+ import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session"
12
+ import { BaseSQLiteDatabase, SQLiteSyncDialect } from "drizzle-orm/sqlite-core"
13
+ // !bun:end
14
+ import { migrate } from "drizzle-orm/bun-sqlite/migrator" // @bun
15
+ import type { Db } from "./index.ts" // @bun
16
+ import type { Db, Orm } from "./index.ts" // @!bun
17
+ import * as schema from "./schema.ts"
18
+
19
+ const MIGRATIONS = join(import.meta.dirname, "../../drizzle")
20
+
21
+ /**
22
+ * Open (or create) the database and bring it up to date. `query` runs raw SQL
23
+ * with `?` placeholders, for signet-payments' store.
24
+ */
25
+ export function openDb(path: string): {
26
+ db: Db
27
+ query: (sql: string, params: unknown[]) => Record<string, unknown>[]
28
+ } {
29
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true })
30
+ // bun:begin
31
+ const sqlite = new Database(path)
32
+ if (path !== ":memory:") sqlite.run("pragma journal_mode = wal")
33
+ const db = createDb(sqlite, { schema, audit: schema.audit, idempotency: schema.idempotency })
34
+ // bun:end
35
+ // !bun:begin
36
+ // node:sqlite runs under Node 22.18+, Deno 2 and Bun alike (bun test uses it).
37
+ const sqlite = new DatabaseSync(path)
38
+ if (path !== ":memory:") sqlite.exec("pragma journal_mode = wal")
39
+ const db = fromDrizzle(orm(sqlite), {
40
+ dialect: "sqlite",
41
+ atomicity: "sync-transaction",
42
+ audit: schema.audit,
43
+ idempotency: schema.idempotency,
44
+ })
45
+ // !bun:end
46
+ // Your tables: the migrations drizzle-kit writes from api/db/schema.ts.
47
+ migrate(db.orm, { migrationsFolder: MIGRATIONS })
48
+ // payments:begin
49
+ // signet-payments' webhook inbox, payment records and ledger: its own
50
+ // CREATE TABLE IF NOT EXISTS statements, versioned with the package.
51
+ for (const statement of paymentsSchema("sqlite")) sqlite.run(statement) // @bun
52
+ for (const statement of paymentsSchema("sqlite")) sqlite.exec(statement) // @!bun
53
+ // payments:end
54
+ return {
55
+ db,
56
+ query: (s, p) => sqlite.query<Record<string, unknown>, never[]>(s).all(...(p as never[])), // @bun
57
+ query: (s, p) => sqlite.prepare(s).all(...(p as never[])) as Record<string, unknown>[], // @!bun
58
+ }
59
+ }
60
+ // !bun:begin
61
+
62
+ /**
63
+ * Drizzle over node:sqlite: the better-sqlite3 driver's session (its entry
64
+ * would load the better-sqlite3 package) on the client below.
65
+ */
66
+ function orm(sqlite: DatabaseSync): Orm {
67
+ const dialect = new SQLiteSyncDialect()
68
+ const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers)
69
+ const relational = {
70
+ fullSchema: schema,
71
+ schema: tables.tables,
72
+ tableNamesMap: tables.tableNamesMap,
73
+ }
74
+ const session = new BetterSQLiteSession(betterSqlite(sqlite), dialect, relational, {})
75
+ return new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Orm
76
+ }
77
+
78
+ type Params = never[]
79
+
80
+ /**
81
+ * node:sqlite in the shape that session calls: prepare (run, all, get, and
82
+ * raw for rows as arrays) and transaction.
83
+ */
84
+ function betterSqlite(sqlite: DatabaseSync) {
85
+ const begin = (mode: string) => (fn: (...args: unknown[]) => unknown) => (...args: unknown[]) => {
86
+ sqlite.exec(`begin ${mode}`)
87
+ try {
88
+ const result = fn(...args)
89
+ sqlite.exec("commit")
90
+ return result
91
+ } catch (err) {
92
+ sqlite.exec("rollback")
93
+ throw err
94
+ }
95
+ }
96
+ return {
97
+ prepare(sql: string) {
98
+ const stmt = sqlite.prepare(sql)
99
+ let arrays: ReturnType<DatabaseSync["prepare"]> | undefined
100
+ const raw = () => {
101
+ if (!arrays) {
102
+ arrays = sqlite.prepare(sql)
103
+ arrays.setReturnArrays(true)
104
+ }
105
+ return arrays
106
+ }
107
+ return {
108
+ run: (...p: Params) => stmt.run(...p),
109
+ all: (...p: Params) => stmt.all(...p),
110
+ get: (...p: Params) => stmt.get(...p),
111
+ raw: () => ({ all: (...p: Params) => raw().all(...p), get: (...p: Params) => raw().get(...p) }),
112
+ }
113
+ },
114
+ transaction: (fn: (...args: unknown[]) => unknown) => ({
115
+ deferred: begin("deferred")(fn),
116
+ immediate: begin("immediate")(fn),
117
+ exclusive: begin("exclusive")(fn),
118
+ }),
119
+ } as never
120
+ }
121
+ // !bun:end
@@ -1,18 +1,31 @@
1
+ // auth:begin
2
+ // payments|growth|orgs|privacy|ai|paywalls|workflows:begin
1
3
  import {
4
+ aiSpendCaps, // @ai
2
5
  auditLog,
3
- entitlementTables,
4
- growthTables,
6
+ entitlementTables, // @payments|ai
7
+ growthTables, // @growth
5
8
  id,
6
9
  idempotencyKeys,
7
- orgTables,
8
- privacyTables,
10
+ monetisationTables, // @paywalls
11
+ orgTables, // @orgs
12
+ privacyTables, // @privacy
9
13
  timestamps,
14
+ workflowTables, // @workflows
10
15
  } from "@dapplelight/signet-db/columns/sqlite"
16
+ // payments|growth|orgs|privacy|ai|paywalls|workflows:end
17
+ import { auditLog, id, idempotencyKeys, timestamps } from "@dapplelight/signet-db/columns/sqlite" // @!payments|growth|orgs|privacy|ai|paywalls|workflows
18
+ // auth:end
19
+ // !auth:begin
20
+ import { auditLog, growthTables, idempotencyKeys } from "@dapplelight/signet-db/columns/sqlite" // @growth
21
+ import { auditLog, idempotencyKeys } from "@dapplelight/signet-db/columns/sqlite" // @!growth
22
+ // !auth:end
11
23
  import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
12
24
 
13
25
  // The whole database. Change a table here, then `db:generate` writes the
14
26
  // migration into drizzle/ and the API applies it on its next start.
15
27
 
28
+ // auth:begin
16
29
  export const ROLES = ["user", "readonly", "staff", "admin"] as const
17
30
 
18
31
  export const users = sqliteTable("users", {
@@ -25,6 +38,7 @@ export const users = sqliteTable("users", {
25
38
  ...timestamps(),
26
39
  })
27
40
 
41
+ // auth:end
28
42
  /**
29
43
  * Sessions, one-time codes, API keys, the notification inbox and prefs, and
30
44
  * rate-limit counters: signet-server keeps each in a key-value store, and this
@@ -43,9 +57,19 @@ export const audit = auditLog()
43
57
  /** Billing events apply once. */
44
58
  export const idempotency = idempotencyKeys()
45
59
 
46
- export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables()
47
- export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables()
48
- export const { consents, dataRequests } = privacyTables()
60
+ export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables() // @payments
61
+ // ai:begin
62
+ export const { usageCounters } = entitlementTables() // @!payments
63
+ /** AI spend caps set at runtime; usage_counters holds the spend. */
64
+ export const spendCaps = aiSpendCaps()
65
+ // ai:end
66
+ /** Versioned offerings and the placements that serve them: the remote paywalls. */ // @paywalls
67
+ export const { offerings, placements } = monetisationTables() // @paywalls
68
+ /** Durable workflow runs, their steps, and the events they wait on. */ // @workflows
69
+ export const { workflowRuns, workflowSteps, workflowEvents } = workflowTables() // @workflows
70
+ export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables() // @growth
71
+ export const { consents, dataRequests } = privacyTables() // @privacy
72
+ // orgs:begin
49
73
  /**
50
74
  * Organisations: every user gets a personal one at sign-up and can make more,
51
75
  * invite people and give them roles (api/services.ts, routes under /api/orgs).
@@ -53,5 +77,8 @@ export const { consents, dataRequests } = privacyTables()
53
77
  * them through `scoped(s.db, { orgId })`, so each org only sees its own rows.
54
78
  */
55
79
  export const { organizations, memberships, invitations, orgRoles } = orgTables()
80
+ // orgs:end
81
+ // auth:begin
56
82
 
57
83
  export type User = typeof users.$inferSelect
84
+ // auth:end