@dapplelight/signet-db 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.
- package/LICENSE +21 -0
- package/README.md +1556 -2
- package/dist/admin.d.ts +266 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +671 -0
- package/dist/admin.js.map +1 -0
- package/dist/agent.d.ts +27 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +117 -0
- package/dist/agent.js.map +1 -0
- package/dist/ai-cache.d.ts +9 -0
- package/dist/ai-cache.d.ts.map +1 -0
- package/dist/ai-cache.js +42 -0
- package/dist/ai-cache.js.map +1 -0
- package/dist/ai-spend.d.ts +91 -0
- package/dist/ai-spend.d.ts.map +1 -0
- package/dist/ai-spend.js +207 -0
- package/dist/ai-spend.js.map +1 -0
- package/dist/analytics-tools.d.ts +7 -0
- package/dist/analytics-tools.d.ts.map +1 -0
- package/dist/analytics-tools.js +110 -0
- package/dist/analytics-tools.js.map +1 -0
- package/dist/analytics.d.ts +92 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +275 -0
- package/dist/analytics.js.map +1 -0
- package/dist/charts.d.ts +96 -0
- package/dist/charts.d.ts.map +1 -0
- package/dist/charts.js +457 -0
- package/dist/charts.js.map +1 -0
- package/dist/cipher.d.ts +24 -0
- package/dist/cipher.d.ts.map +1 -0
- package/dist/cipher.js +69 -0
- package/dist/cipher.js.map +1 -0
- package/dist/collab.d.ts +159 -0
- package/dist/collab.d.ts.map +1 -0
- package/dist/collab.js +492 -0
- package/dist/collab.js.map +1 -0
- package/dist/columns/pg.d.ts +6254 -0
- package/dist/columns/pg.d.ts.map +1 -0
- package/dist/columns/pg.js +507 -0
- package/dist/columns/pg.js.map +1 -0
- package/dist/columns/shared.d.ts +2 -0
- package/dist/columns/shared.d.ts.map +1 -0
- package/dist/columns/shared.js +2 -0
- package/dist/columns/shared.js.map +1 -0
- package/dist/columns/sqlite.d.ts +6680 -0
- package/dist/columns/sqlite.d.ts.map +1 -0
- package/dist/columns/sqlite.js +507 -0
- package/dist/columns/sqlite.js.map +1 -0
- package/dist/crypt.d.ts +5 -0
- package/dist/crypt.d.ts.map +1 -0
- package/dist/crypt.js +37 -0
- package/dist/crypt.js.map +1 -0
- package/dist/customers.d.ts +339 -0
- package/dist/customers.d.ts.map +1 -0
- package/dist/customers.js +714 -0
- package/dist/customers.js.map +1 -0
- package/dist/d1.d.ts +6 -0
- package/dist/d1.d.ts.map +1 -0
- package/dist/d1.js +11 -0
- package/dist/d1.js.map +1 -0
- package/dist/db.d.ts +33 -0
- package/dist/db.d.ts.map +1 -0
- package/dist/db.js +28 -0
- package/dist/db.js.map +1 -0
- package/dist/describe.d.ts +37 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +79 -0
- package/dist/describe.js.map +1 -0
- package/dist/entitlement-tools.d.ts +17 -0
- package/dist/entitlement-tools.d.ts.map +1 -0
- package/dist/entitlement-tools.js +226 -0
- package/dist/entitlement-tools.js.map +1 -0
- package/dist/entitlements.d.ts +166 -0
- package/dist/entitlements.d.ts.map +1 -0
- package/dist/entitlements.js +493 -0
- package/dist/entitlements.js.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +12 -0
- package/dist/errors.js.map +1 -0
- package/dist/experiments.d.ts +97 -0
- package/dist/experiments.d.ts.map +1 -0
- package/dist/experiments.js +253 -0
- package/dist/experiments.js.map +1 -0
- package/dist/flags.d.ts +74 -0
- package/dist/flags.d.ts.map +1 -0
- package/dist/flags.js +127 -0
- package/dist/flags.js.map +1 -0
- package/dist/funnels.d.ts +236 -0
- package/dist/funnels.d.ts.map +1 -0
- package/dist/funnels.js +478 -0
- package/dist/funnels.js.map +1 -0
- package/dist/growth-tools.d.ts +10 -0
- package/dist/growth-tools.d.ts.map +1 -0
- package/dist/growth-tools.js +132 -0
- package/dist/growth-tools.js.map +1 -0
- package/dist/growth.d.ts +168 -0
- package/dist/growth.d.ts.map +1 -0
- package/dist/growth.js +406 -0
- package/dist/growth.js.map +1 -0
- package/dist/id.d.ts +3 -0
- package/dist/id.d.ts.map +1 -0
- package/dist/id.js +32 -0
- package/dist/id.js.map +1 -0
- package/dist/idempotency.d.ts +8 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +66 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/import.d.ts +33 -0
- package/dist/import.d.ts.map +1 -0
- package/dist/import.js +75 -0
- package/dist/import.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/check.d.ts +11 -0
- package/dist/migrations/check.d.ts.map +1 -0
- package/dist/migrations/check.js +68 -0
- package/dist/migrations/check.js.map +1 -0
- package/dist/migrations/cli.d.ts +3 -0
- package/dist/migrations/cli.d.ts.map +1 -0
- package/dist/migrations/cli.js +30 -0
- package/dist/migrations/cli.js.map +1 -0
- package/dist/money.d.ts +16 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +50 -0
- package/dist/money.js.map +1 -0
- package/dist/offerings.d.ts +133 -0
- package/dist/offerings.d.ts.map +1 -0
- package/dist/offerings.js +337 -0
- package/dist/offerings.js.map +1 -0
- package/dist/orgs.d.ts +144 -0
- package/dist/orgs.d.ts.map +1 -0
- package/dist/orgs.js +536 -0
- package/dist/orgs.js.map +1 -0
- package/dist/outbox.d.ts +23 -0
- package/dist/outbox.d.ts.map +1 -0
- package/dist/outbox.js +60 -0
- package/dist/outbox.js.map +1 -0
- package/dist/postgres.d.ts +7 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +9 -0
- package/dist/postgres.js.map +1 -0
- package/dist/pricing.d.ts +79 -0
- package/dist/pricing.d.ts.map +1 -0
- package/dist/pricing.js +208 -0
- package/dist/pricing.js.map +1 -0
- package/dist/privacy-tools.d.ts +9 -0
- package/dist/privacy-tools.d.ts.map +1 -0
- package/dist/privacy-tools.js +51 -0
- package/dist/privacy-tools.js.map +1 -0
- package/dist/privacy.d.ts +71 -0
- package/dist/privacy.d.ts.map +1 -0
- package/dist/privacy.js +176 -0
- package/dist/privacy.js.map +1 -0
- package/dist/query.d.ts +6 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +4 -0
- package/dist/query.js.map +1 -0
- package/dist/scoped.d.ts +51 -0
- package/dist/scoped.d.ts.map +1 -0
- package/dist/scoped.js +148 -0
- package/dist/scoped.js.map +1 -0
- package/dist/seed.d.ts +5 -0
- package/dist/seed.d.ts.map +1 -0
- package/dist/seed.js +195 -0
- package/dist/seed.js.map +1 -0
- package/dist/sequence.d.ts +4 -0
- package/dist/sequence.d.ts.map +1 -0
- package/dist/sequence.js +14 -0
- package/dist/sequence.js.map +1 -0
- package/dist/sqlite.d.ts +7 -0
- package/dist/sqlite.d.ts.map +1 -0
- package/dist/sqlite.js +13 -0
- package/dist/sqlite.js.map +1 -0
- package/dist/status.d.ts +101 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/status.js +198 -0
- package/dist/status.js.map +1 -0
- package/dist/tool-kit.d.ts +44 -0
- package/dist/tool-kit.d.ts.map +1 -0
- package/dist/tool-kit.js +34 -0
- package/dist/tool-kit.js.map +1 -0
- package/dist/user-data.d.ts +9 -0
- package/dist/user-data.d.ts.map +1 -0
- package/dist/user-data.js +50 -0
- package/dist/user-data.js.map +1 -0
- package/dist/versions.d.ts +12 -0
- package/dist/versions.d.ts.map +1 -0
- package/dist/versions.js +44 -0
- package/dist/versions.js.map +1 -0
- package/dist/webhooks.d.ts +95 -0
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +342 -0
- package/dist/webhooks.js.map +1 -0
- package/dist/workflows.d.ts +186 -0
- package/dist/workflows.d.ts.map +1 -0
- package/dist/workflows.js +563 -0
- package/dist/workflows.js.map +1 -0
- package/dist/zod.d.ts +14 -0
- package/dist/zod.d.ts.map +1 -0
- package/dist/zod.js +48 -0
- package/dist/zod.js.map +1 -0
- package/package.json +205 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1557 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dapplelight/signet-db
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Drizzle helpers for the parts every app rewrites: sortable ids, timestamps,
|
|
4
|
+
soft delete, money, encrypted fields, per-user scoping, an audit trail,
|
|
5
|
+
per-user export and erasure, seed data and a migration safety check.
|
|
6
|
+
|
|
7
|
+
The core never imports a driver. Thin entry points connect it to one:
|
|
8
|
+
|
|
9
|
+
| Import | What |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `@dapplelight/signet-db` | Core: `scoped`, `audited`, `createCipher`, money, `newId`, `seed`, `exportUser`, `deleteUser`, `nextSequence`, `describeSchema`, `defineQuery`, `fromDrizzle`, `dbCache` |
|
|
12
|
+
| `@dapplelight/signet-db/columns/sqlite` | Column helpers for SQLite and D1 tables |
|
|
13
|
+
| `@dapplelight/signet-db/columns/pg` | The same helpers for Postgres tables |
|
|
14
|
+
| `@dapplelight/signet-db/d1` | `createDb(env.DB)`, Cloudflare D1 |
|
|
15
|
+
| `@dapplelight/signet-db/sqlite` | `createDb("app.db")`, bun:sqlite |
|
|
16
|
+
| `@dapplelight/signet-db/postgres` | `createDb(url \| postgres())`, postgres-js (optional peer) |
|
|
17
|
+
| `@dapplelight/signet-db/migrations` | `checkMigrationSql`; the `signet-db-check` CLI |
|
|
18
|
+
| `@dapplelight/signet-db/zod` | `toZod(table, { mode })` (zod is an optional peer) |
|
|
19
|
+
| `@dapplelight/signet-db/agent` | `agentTools(db, { tables, userId })`, tools for AI agents (needs zod) |
|
|
20
|
+
| `@dapplelight/signet-db/entitlements` | `definePlans`, `createEntitlements`, billing events, usage limits, `entitlementTools` |
|
|
21
|
+
| `@dapplelight/signet-db/flags` | `defineFlags`, `evaluateFlag`, `createFlags` |
|
|
22
|
+
| `@dapplelight/signet-db/admin` | `defineAdmin(schema, { authorize })`, an admin API and admin MCP tools (needs zod) |
|
|
23
|
+
| `@dapplelight/signet-db/webhooks` | `createWebhooks`: outbound webhooks per user or org, signed, retried through the outbox, with a delivery log |
|
|
24
|
+
| `@dapplelight/signet-db/privacy` | `createPrivacy`: DPDP consent records, withdrawal, export and erasure requests; `privacyTools` |
|
|
25
|
+
| `@dapplelight/signet-db/analytics` | `createAnalyticsStore`: events in your database, counts, uniques, series, breakdowns, funnels, retention, trends; `analyticsTools` |
|
|
26
|
+
| `@dapplelight/signet-db/orgs` | `createOrgs`: organisations, memberships, roles and permissions, custom roles, invites, per-org domain and theme |
|
|
27
|
+
| `@dapplelight/signet-db/growth` | `createGrowth`: waitlist, invites, referrals, onboarding, changelog, feedback; `growthTools` |
|
|
28
|
+
| `@dapplelight/signet-db/workflows` | `defineWorkflow`, `createWorkflows`: durable multi-step runs with sleeps, events, human approvals, retries, cancel |
|
|
29
|
+
| `@dapplelight/signet-db/offerings` | `createOfferings`: versioned offerings (store and web products mapped to plans) with a remote paywall, served per placement and audience; `plansFromProducts` |
|
|
30
|
+
| `@dapplelight/signet-db/customers` | `createCustomers`: the customer timeline across stores and web, anonymous-to-account identity merge, and the Customer Center (cancel, refund request, retention offer, support) |
|
|
31
|
+
|
|
32
|
+
Peers: `drizzle-orm` ^0.45, `@dapplelight/signet-lib` ^0.3, `postgres` only
|
|
33
|
+
for `./postgres` and `zod` only for `./zod`. Types flow from your table definitions: rows, inserts
|
|
34
|
+
and updates are `InferSelectModel`/`InferInsertModel` of the table you pass.
|
|
35
|
+
|
|
36
|
+
Not on npm yet (`private: true`).
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
### Cloudflare D1
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { createDb } from "@dapplelight/signet-db/d1"
|
|
44
|
+
import { scoped } from "@dapplelight/signet-db"
|
|
45
|
+
import * as schema from "./schema"
|
|
46
|
+
|
|
47
|
+
export default {
|
|
48
|
+
async fetch(req: Request, bindings: { DB: D1Database }) {
|
|
49
|
+
const db = createDb(bindings.DB, { schema }) // per request; no env at import time
|
|
50
|
+
const me = scoped(db, { userId: await userIdFrom(req) })
|
|
51
|
+
return Response.json(await me.select(schema.orders))
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Atomic groups (`deleteUser`) run as one D1 `batch`, since D1 has no `BEGIN`.
|
|
57
|
+
See `examples/d1/worker.ts`.
|
|
58
|
+
|
|
59
|
+
### SQLite on Bun (Docker, VPS)
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { createDb } from "@dapplelight/signet-db/sqlite"
|
|
63
|
+
const db = createDb("/data/app.db", { schema })
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Runs on Bun (`bun:sqlite`). For better-sqlite3 on Node:
|
|
67
|
+
`fromDrizzle(drizzle(client), { dialect: "sqlite", atomicity: "sync-transaction" })`.
|
|
68
|
+
See `examples/sqlite.ts`.
|
|
69
|
+
|
|
70
|
+
### Postgres (Supabase, Neon, RDS)
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import postgres from "postgres"
|
|
74
|
+
import { createDb } from "@dapplelight/signet-db/postgres"
|
|
75
|
+
const db = createDb(postgres(url, { prepare: false }), { schema }) // prepare:false for Supabase's pooler
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
See `examples/postgres.ts`.
|
|
79
|
+
|
|
80
|
+
### Any other Drizzle driver
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { fromDrizzle } from "@dapplelight/signet-db"
|
|
84
|
+
const db = fromDrizzle(drizzle(client), { dialect: "pg", atomicity: "transaction" })
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Columns
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { sqliteTable, text } from "drizzle-orm/sqlite-core"
|
|
91
|
+
import { id, timestamps, softDelete } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
92
|
+
|
|
93
|
+
export const orders = sqliteTable("orders", {
|
|
94
|
+
id: id(), // text primary key, newId() on insert
|
|
95
|
+
userId: text("user_id").notNull(),
|
|
96
|
+
item: text("item").notNull(),
|
|
97
|
+
...timestamps(), // createdAt, updatedAt (moves on every Drizzle update)
|
|
98
|
+
...softDelete(), // deletedAt
|
|
99
|
+
})
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`newId()` ids are 26 characters, sort by creation time as plain strings and
|
|
103
|
+
stay ordered within a millisecond. `idTime(id)` reads the time back.
|
|
104
|
+
Timestamps carry a SQL default, so migrations and raw inserts get them too.
|
|
105
|
+
|
|
106
|
+
## Money
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { money } from "@dapplelight/signet-db/columns/sqlite"
|
|
110
|
+
import { moneyOf, addMoney, formatMoney } from "@dapplelight/signet-db"
|
|
111
|
+
|
|
112
|
+
const items = sqliteTable("items", { id: id(), ...money("price", { currency: "INR" }) })
|
|
113
|
+
// → price (integer minor units: paise), priceCurrency (default 'INR')
|
|
114
|
+
|
|
115
|
+
formatMoney(addMoney(moneyOf(row, "price"), { amount: 99, currency: "INR" })) // "₹1,234.56"
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Amounts are integers; a float or a different currency throws. Formatting turns
|
|
119
|
+
minor units into an exact decimal string before `Intl` sees it, so 2^53 paise
|
|
120
|
+
format without rounding. `minorDigits("JPY")` is 0, `"BHD"` is 3. Also
|
|
121
|
+
`subtractMoney`, `sumMoney`, `compareMoney`. Postgres stores amounts as
|
|
122
|
+
`bigint`, read as numbers.
|
|
123
|
+
|
|
124
|
+
## Encrypted fields
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import { encrypted } from "@dapplelight/signet-db/columns/sqlite"
|
|
128
|
+
import { createCipher } from "@dapplelight/signet-db"
|
|
129
|
+
|
|
130
|
+
const profiles = sqliteTable("profiles", { id: id(), userId: text("user_id").notNull(), pan: encrypted("pan") })
|
|
131
|
+
const db = createDb(bindings.DB, { cipher: createCipher({ keys: { k1: bindings.FIELD_KEY }, current: "k1" }) })
|
|
132
|
+
await scoped(db, { userId }).insert(profiles, { pan: "ABCDE1234F" }) // stored as enc:v1:k1:…
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
AES-GCM through Web Crypto. Reads through `scoped`/`audited`/`exportUser`
|
|
136
|
+
decrypt; writes encrypt. A raw Drizzle write of plaintext to an `encrypted()`
|
|
137
|
+
column throws instead of storing it. Reads fail closed (via
|
|
138
|
+
`@dapplelight/signet-lib/crypto`): a value that does not decrypt comes back as
|
|
139
|
+
`null`, never as ciphertext, and `onUndecrypted` is called.
|
|
140
|
+
|
|
141
|
+
Rotation: the key id is stored with each value. Add a new key, make it
|
|
142
|
+
`current`, keep the old one in `keys`; `onStaleKey` fires when an old key was
|
|
143
|
+
used and `cipher.rotate(value)` re-encrypts. `generateKey()` makes a key.
|
|
144
|
+
Encrypted columns cannot be filtered on (random IVs). See `examples/encrypted.ts`.
|
|
145
|
+
|
|
146
|
+
## Per-user scope and soft delete
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
const me = scoped(db, { userId: session.userId })
|
|
150
|
+
await me.insert(orders, { item: "Dosa" }) // userId set for you; passing another throws
|
|
151
|
+
await me.select(orders, eq(orders.item, "Dosa"), { orderBy: desc(orders.createdAt), limit: 20 })
|
|
152
|
+
await me.update(orders, { item: "Idli" }, eq(orders.id, id))
|
|
153
|
+
await me.delete(orders, eq(orders.id, id)) // sets deletedAt
|
|
154
|
+
await me.select(orders, undefined, { withDeleted: true })
|
|
155
|
+
await me.delete(orders, eq(orders.id, id), { hard: true })
|
|
156
|
+
db.orm.select().from(orders).where(me.where(orders, extra)) // the same filter, hand-built query
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Tables with a `userId` column get `where user_id = ?` on every read, update
|
|
160
|
+
and delete; tables with `deletedAt` hide deleted rows unless a call passes
|
|
161
|
+
`withDeleted`. A scoped update cannot change `userId`.
|
|
162
|
+
|
|
163
|
+
## Audit trail
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { auditLog } from "@dapplelight/signet-db/columns/sqlite"
|
|
167
|
+
export const audit = auditLog() // audit_log table; add it to your migrations
|
|
168
|
+
|
|
169
|
+
const db = createDb(bindings.DB, { schema, audit })
|
|
170
|
+
const me = audited(scoped(db, { userId })) // actor: { type: "user", id: userId }
|
|
171
|
+
const bot = audited(db, { actor: { type: "system", id: "nightly-cleanup" } }) // unscoped; where required
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Each changed row gets an entry: `actorType` (`user`, `agent` or `system`),
|
|
175
|
+
`actorId`, `action`
|
|
176
|
+
(insert/update/delete/delete_user), `tableName`, `rowId`, `before`, `after`,
|
|
177
|
+
`at`. Encrypted fields are recorded as ciphertext. The change and its entry
|
|
178
|
+
are separate statements; on D1 they are not one transaction.
|
|
179
|
+
|
|
180
|
+
## Migration safety check
|
|
181
|
+
|
|
182
|
+
```sh
|
|
183
|
+
signet-db-check drizzle/ # exit 1 on findings
|
|
184
|
+
signet-db-check $(git diff --name-only --diff-filter=A origin/main -- 'drizzle/*.sql') # new files only, in CI
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Flags `DROP TABLE`, `DROP COLUMN`, renames, and `NOT NULL` added without a
|
|
188
|
+
`DEFAULT` (including `SET NOT NULL`). drizzle-kit's SQLite table rebuilds are
|
|
189
|
+
not flagged. Accept a finding with `-- signet-allow: drop-column` (or `all`)
|
|
190
|
+
in the statement. `checkMigrationSql(sql, file)` is the same check as a function.
|
|
191
|
+
|
|
192
|
+
## Seed data
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const rows = seed(users, 50, { city: "Pune" }, { seed: 7 }) // or (i) => ({ … })
|
|
196
|
+
await db.orm.insert(users).values(rows)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Values follow column types and names: Indian names, `+91` mobile numbers,
|
|
200
|
+
6-digit PIN codes, cities, states, emails at example.com, amounts in minor
|
|
201
|
+
units. Same seed, same rows. Columns with defaults are left out.
|
|
202
|
+
|
|
203
|
+
## Per-user export and delete
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const tables = [orders, profiles, [users, users.id]] as const // [table, ownerColumn] when it is not userId
|
|
207
|
+
const data = await exportUser(db, userId, tables) // { orders: [...], profiles: [...], users: [...] }, decrypted
|
|
208
|
+
const counts = await deleteUser(db, userId, tables) // { orders: 3, profiles: 1, users: 1 }
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
`deleteUser` hard-deletes in one atomic batch, in the order given (children
|
|
212
|
+
first if foreign keys do not cascade). With auditing on, the same batch writes
|
|
213
|
+
a `delete_user` entry holding the counts, not the deleted data.
|
|
214
|
+
|
|
215
|
+
## Describe the schema
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
describeSchema(schema) // text, below
|
|
219
|
+
describeSchema(schema, { format: "json" }) // { tables: [{ name, columns, primaryKey, scoped, softDelete, relations }] }
|
|
220
|
+
// table orders
|
|
221
|
+
// id text primary key has default
|
|
222
|
+
// user_id text not null -- js: userId; owner; rows are per user
|
|
223
|
+
// total integer not null
|
|
224
|
+
// total_currency text not null has default -- js: totalCurrency; currency of total, which is in minor units
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Text for an agent's or a reviewer's context; JSON for tools. Each column says
|
|
228
|
+
whether it is the owner, the soft-delete marker, money or encrypted.
|
|
229
|
+
|
|
230
|
+
## Tools for AI agents
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { agentTools } from "@dapplelight/signet-db/agent"
|
|
234
|
+
import { createMcpServer } from "@dapplelight/signet-server/mcp"
|
|
235
|
+
|
|
236
|
+
const tools = agentTools(db, { tables: [orders, notes], userId: session.userId, maxRows: 50 })
|
|
237
|
+
createMcpServer({ name: "app", version: "1.0.0", tools }) // or call tool.run(input) yourself
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Per table: `<table>_list`, `<table>_get`, `<table>_search` (equals or
|
|
241
|
+
contains), and with `allowWrites: true` also `<table>_insert` and
|
|
242
|
+
`<table>_update`, which take `dryRun: true` to return the would-be change.
|
|
243
|
+
Guards that hold for every tool:
|
|
244
|
+
|
|
245
|
+
- Scoped to `userId`; a table without a `userId` column is refused.
|
|
246
|
+
- Soft-deleted rows hidden; `userId` and encrypted fields never returned
|
|
247
|
+
(`includeEncrypted: true` opts encrypted fields in).
|
|
248
|
+
- At most `maxRows` (100) rows per call; inputs are strict Zod objects, so
|
|
249
|
+
unknown fields (such as `userId`) are rejected with `BAD_INPUT`.
|
|
250
|
+
- Writes audited as `{ type: "agent", id }` (`actor` to name the agent).
|
|
251
|
+
|
|
252
|
+
Each tool is `{ name, description, annotations, input, inputSchema, run,
|
|
253
|
+
handler }`: `input` and `handler` are what signet-server's MCP server
|
|
254
|
+
registers; `inputSchema` is JSON Schema for other runners. `AGENTS.md` is the
|
|
255
|
+
short guide for agents.
|
|
256
|
+
|
|
257
|
+
## Admin API from the schema
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import { adminTools, defineAdmin, roles } from "@dapplelight/signet-db/admin"
|
|
261
|
+
import * as schema from "./schema"
|
|
262
|
+
|
|
263
|
+
export const admin = defineAdmin(schema, {
|
|
264
|
+
authorize: roles(), // admin: all; staff: all but delete; readonly: list, get
|
|
265
|
+
tables: {
|
|
266
|
+
users: { search: ["name", "email"], readonly: ["email"], hidden: ["phone"] },
|
|
267
|
+
outbox: false, // leave a table out
|
|
268
|
+
},
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
const ctx = { actor: { type: "user", id: me.id }, role: me.role }
|
|
272
|
+
await admin.list(db, ctx, "users", { filter: { plan: { eq: "pro" } }, sort: "createdAt", limit: 20 })
|
|
273
|
+
await admin.update(db, ctx, "users", id, { name: "New name" })
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Every table in the schema is included unless set to `false`; config is by SQL
|
|
277
|
+
table name. Operations: `meta`, `list`, `get`, `create`, `update`, `delete`,
|
|
278
|
+
`bulkDelete`, `action`, and `handle(db, ctx, request)` for HTTP (mount it with
|
|
279
|
+
signet-server's `adminRoutes`). Defaults that hold without config:
|
|
280
|
+
|
|
281
|
+
- **Deny by default.** Each op calls `authorize(ctx, { table, op })`, then again
|
|
282
|
+
with the `row` (each listed row, the stored row, or the new one on create).
|
|
283
|
+
Anything but `true`, or a throw, is `403 FORBIDDEN`. `roles(map)` reads
|
|
284
|
+
`ctx.role`; write your own for anything finer.
|
|
285
|
+
- **Secrets hidden.** `encrypted()` columns and names matching password,
|
|
286
|
+
hash, token, secret, salt, api key or private key are never returned,
|
|
287
|
+
sorted, filtered or written. `hidden` adds more; `reveal` opts one back in.
|
|
288
|
+
Audit log snapshots are cut to the audited table's visible columns.
|
|
289
|
+
- **Soft delete.** Rows with `deletedAt` set are left out unless a list or get
|
|
290
|
+
passes `withDeleted`; delete sets `deletedAt` (`soft: true` in the result).
|
|
291
|
+
- **Allow-listed queries.** `sort`, `filter` and `search` columns are fixed at
|
|
292
|
+
`defineAdmin` time (defaults: visible NOT NULL scalars, visible scalars,
|
|
293
|
+
visible text). A request naming anything else is `400 VALIDATION_FAILED`,
|
|
294
|
+
and SQL is built from Drizzle columns only. Filter operators: `eq`, `ne`,
|
|
295
|
+
`in`, `isNull`, `lt`/`lte`/`gt`/`gte` (numbers, dates, text), `contains` and
|
|
296
|
+
`startsWith` (text, case-insensitive).
|
|
297
|
+
- **Stable cursors.** Pages sort by the column plus the primary key, and the
|
|
298
|
+
cursor compares against the anchor row in SQL, so ties and inserts never
|
|
299
|
+
repeat or skip a row. A cursor for another sort is rejected.
|
|
300
|
+
- **Audited writes.** Writes go through `audited(db, { actor: ctx.actor })`;
|
|
301
|
+
the db needs an audit table. The `auditLog()` table itself is list and get
|
|
302
|
+
only. Inputs are strict `toZod` schemas: unknown, hidden and read-only
|
|
303
|
+
fields are rejected with field-level `details`.
|
|
304
|
+
|
|
305
|
+
`meta(ctx)` returns, per table this caller may use, the columns (type, enum,
|
|
306
|
+
money currency, read-only, sortable, filterable, operators), relations, the
|
|
307
|
+
allowed ops and actions: what an admin UI or an agent renders from.
|
|
308
|
+
|
|
309
|
+
Actions add per-row operations: `actions: { refund: { description, input?,
|
|
310
|
+
destructive?, run: ({ row, input, ctx, db, ops }) => ... } }`, where `ops`
|
|
311
|
+
is the audited writer.
|
|
312
|
+
|
|
313
|
+
### Admin tools for agents
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
import { requireApproval } from "@dapplelight/signet-server/mcp"
|
|
317
|
+
|
|
318
|
+
tools: async ({ c }) =>
|
|
319
|
+
adminTools(admin, { db: dbFor(c), ctx: await adminCtx(c), approve: requireApproval })
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
`admin_schema`, and per table `admin_<table>_list`, `_search`, `_get`; with
|
|
323
|
+
`approve`, also `_create`, `_update`, `_delete` and one tool per action. Only
|
|
324
|
+
ops `authorize` allows the caller are listed, and each call is authorized
|
|
325
|
+
again. A write validates and authorizes first, then calls `approve` (which
|
|
326
|
+
asks the person), and writes only when it returns undefined. Writes are
|
|
327
|
+
audited as `{ type: "agent", id: ctx.actor.id }` unless `actor` is given.
|
|
328
|
+
|
|
329
|
+
## Zod schemas from tables
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { toZod } from "@dapplelight/signet-db/zod"
|
|
333
|
+
import { parseBody } from "@dapplelight/signet-server/http/validate"
|
|
334
|
+
|
|
335
|
+
const body = await parseBody(c, toZod(orders, { mode: "insert" }))
|
|
336
|
+
await scoped(db, { userId }).insert(orders, body)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
`insert` leaves out the defaulted primary key, `createdAt`, `updatedAt`,
|
|
340
|
+
`deletedAt` and `userId` (stripped if a client sends them; `keep: ["userId"]`
|
|
341
|
+
keeps one), and makes defaulted or nullable columns optional. `update` is the
|
|
342
|
+
same with every field optional; `select` is a full row. Dates accept ISO
|
|
343
|
+
strings, money amounts must be integer minor units, currency codes three
|
|
344
|
+
capital letters, encrypted columns plaintext strings. Generated from the
|
|
345
|
+
columns, no drizzle-zod.
|
|
346
|
+
|
|
347
|
+
## Transactional outbox
|
|
348
|
+
|
|
349
|
+
```ts
|
|
350
|
+
import { outbox } from "@dapplelight/signet-db/columns/sqlite"
|
|
351
|
+
const db = createDb(bindings.DB, { schema, outbox: schema.outbox })
|
|
352
|
+
|
|
353
|
+
await db.batch([
|
|
354
|
+
(tx) => tx.insert(orders).values(order),
|
|
355
|
+
enqueue(db, "order.created", { orderId: order.id }), // same atomic write
|
|
356
|
+
])
|
|
357
|
+
await drainOutbox(db, queue, { batch: 50 }) // cron or waitUntil
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
`queue` is anything with `send(message)`, such as signet-server's `Queue`
|
|
361
|
+
adapters; messages are `{ id, topic, payload }`. Each row is leased before it
|
|
362
|
+
is sent, so concurrent drainers do not double-send; a failed send retries with
|
|
363
|
+
backoff (`2^attempt` s, capped at 1 h, or your `backoff`) until `maxAttempts`
|
|
364
|
+
(10), then the row is `dead`. A crash between send and mark resends: at least
|
|
365
|
+
once, so dedupe on `id`. In an interactive transaction:
|
|
366
|
+
`await enqueue(db, topic, payload)(tx)`. `pruneOutbox(db)` deletes old sent rows.
|
|
367
|
+
|
|
368
|
+
## Outbound webhooks
|
|
369
|
+
|
|
370
|
+
`@dapplelight/signet-db/webhooks`: endpoints registered per user or org, each
|
|
371
|
+
with its own `whsec_` secret; Standard Webhooks signatures; retries with
|
|
372
|
+
backoff through the outbox; a delivery log; manual redelivery; endpoints
|
|
373
|
+
switched off after repeated failures.
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { webhookTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
377
|
+
import { createWebhooks, WEBHOOK_TOPIC } from "@dapplelight/signet-db/webhooks"
|
|
378
|
+
import { drainOutbox } from "@dapplelight/signet-db"
|
|
379
|
+
|
|
380
|
+
export const { webhookEndpoints, webhookDeliveries } = webhookTables()
|
|
381
|
+
|
|
382
|
+
const webhooks = createWebhooks(db, { endpoints: webhookEndpoints, deliveries: webhookDeliveries })
|
|
383
|
+
const { endpoint, secret } = await webhooks.register({ owner: orgId, url, events: ["order.created"] }) // secret shown once
|
|
384
|
+
|
|
385
|
+
// Queued in the same atomic write as the change that caused it:
|
|
386
|
+
await db.batch([
|
|
387
|
+
(tx) => tx.insert(orders).values(order),
|
|
388
|
+
...(await webhooks.statements({ owner: orgId, type: "order.created", data: order })),
|
|
389
|
+
])
|
|
390
|
+
|
|
391
|
+
// From a cron: webhook rows go to webhooks.send, the rest to the app's queue.
|
|
392
|
+
await drainOutbox(db, { send: (m) => (m.topic === WEBHOOK_TOPIC ? webhooks.send(m) : queue.send(m)) })
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
- **Signature:** `webhook-id` (the event id), `webhook-timestamp` and
|
|
396
|
+
`webhook-signature: v1,<base64 HMAC-SHA256 of id.timestamp.body>`, made by
|
|
397
|
+
`signWebhook` from `@dapplelight/signet-lib/webhooks`. Receivers call
|
|
398
|
+
`verifyWebhook(secret, headers, rawBody)` and dedupe on `webhook-id`, which
|
|
399
|
+
is the same on every retry and redelivery. The body is
|
|
400
|
+
`{ type, timestamp, data }`.
|
|
401
|
+
- **Retries:** each delivery is one outbox row, so `drainOutbox`'s backoff and
|
|
402
|
+
`maxAttempts` apply. Pass the same `maxAttempts` to `createWebhooks` so the
|
|
403
|
+
last attempt logs as `failed`. A delivered row is never posted again, even
|
|
404
|
+
when the at-least-once outbox hands it over twice.
|
|
405
|
+
- **Delivery log:** `deliveries(owner, { endpointId, status, limit, before })`,
|
|
406
|
+
newest first: status (`pending`, `retrying`, `delivered`, `failed`,
|
|
407
|
+
`skipped`), attempts, the response status, the first 2 KB of the response,
|
|
408
|
+
the error and the duration.
|
|
409
|
+
- **Redeliver:** `redeliver(owner, deliveryId)` queues a new delivery with the
|
|
410
|
+
same event id and body.
|
|
411
|
+
- **Disable:** after `disableAfter` (default 20) failed attempts in a row the
|
|
412
|
+
endpoint is switched off and its queued deliveries are `skipped`.
|
|
413
|
+
`update(owner, id, { enabled: true })` turns it back on.
|
|
414
|
+
- **Safety:** urls must be `https:` on a public host (no localhost, private
|
|
415
|
+
ranges, IP literals or credentials) unless `allowPrivateUrls`. Before every
|
|
416
|
+
attempt the host is resolved (`node:dns/promises` `lookup` with `all: true`
|
|
417
|
+
on Bun and Node) and the delivery is refused if any address is private,
|
|
418
|
+
loopback, link-local, CGNAT, unique-local IPv6 or IPv4-mapped; that logs as
|
|
419
|
+
a failed attempt (`Refused: <host> resolves to a private address`) and
|
|
420
|
+
counts toward `disableAfter` like any other failure. Redirects are never
|
|
421
|
+
followed: a 3xx is a failed attempt. Each attempt times out after
|
|
422
|
+
`timeoutMs` (10 s). With a db cipher, secrets are stored encrypted;
|
|
423
|
+
`rotateSecret` replaces one.
|
|
424
|
+
- **Runtimes without DNS:** on Cloudflare Workers without `nodejs_compat`
|
|
425
|
+
there is nothing to resolve with, so the check is skipped and the
|
|
426
|
+
platform's outbound protections apply. Pass `resolveHost: (host) =>
|
|
427
|
+
Promise<string[]>` (DNS over HTTPS, say) to enforce it there too.
|
|
428
|
+
|
|
429
|
+
Admin routes: `webhookRoutes` in `@dapplelight/signet-server/http/webhooks`.
|
|
430
|
+
Screen: `WebhookDeliveryLog` in `@dapplelight/signet-ui/screens/api-screens`.
|
|
431
|
+
|
|
432
|
+
## Idempotency keys
|
|
433
|
+
|
|
434
|
+
```ts
|
|
435
|
+
import { idempotencyKeys } from "@dapplelight/signet-db/columns/sqlite"
|
|
436
|
+
const db = createDb(bindings.DB, { schema, idempotency: schema.idempotency })
|
|
437
|
+
|
|
438
|
+
const order = await withIdempotency(db, c.req.header("idempotency-key") ?? "", userId, () =>
|
|
439
|
+
scoped(db, { userId }).insert(orders, body),
|
|
440
|
+
)
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
Runs the function once per (scope, key) and replays its stored JSON result on
|
|
444
|
+
retries for `ttlMs` (24 h). A duplicate that arrives while the first is still
|
|
445
|
+
running gets `IDEMPOTENCY_IN_FLIGHT` (answer 409); a claim left by a crash
|
|
446
|
+
expires after `leaseMs` (60 s). If the function throws, the key is released.
|
|
447
|
+
With a cipher on the db the stored result is encrypted, so `encrypted()` fields
|
|
448
|
+
the function returns are not left as plaintext in the table.
|
|
449
|
+
`pruneIdempotency(db)` deletes expired keys.
|
|
450
|
+
|
|
451
|
+
## AI answer cache
|
|
452
|
+
|
|
453
|
+
A persistent cache for signet-ai's `createExtractor`, on a table in either
|
|
454
|
+
dialect, so paid answers survive restarts and are shared by every process.
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
// schema.ts
|
|
458
|
+
import { aiCache } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
459
|
+
export const aiAnswers = aiCache() // table "ai_cache"
|
|
460
|
+
|
|
461
|
+
// where the extractor is made
|
|
462
|
+
import { dbCache } from "@dapplelight/signet-db"
|
|
463
|
+
const ai = createExtractor({ providers, cache: dbCache(db, schema.aiAnswers) })
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
Rows are keyed by signet-ai's hash of model, schema, instructions and input,
|
|
467
|
+
hold the entry as JSON and expire after the extractor's `cacheTtlSeconds`. An
|
|
468
|
+
expired or unreadable row is a miss (an expired one is deleted on read). With a
|
|
469
|
+
cipher on the db the entry is encrypted, since answers often repeat the
|
|
470
|
+
personal data they were given. `pruneAiCache(db, table)` deletes expired rows;
|
|
471
|
+
run it from a cron. Held in a variable before it reaches `createExtractor`,
|
|
472
|
+
type it: `dbCache<CacheEntry>(db, table)`.
|
|
473
|
+
|
|
474
|
+
## Named queries
|
|
475
|
+
|
|
476
|
+
```ts
|
|
477
|
+
const openOrders = (userId: string) =>
|
|
478
|
+
defineQuery({
|
|
479
|
+
key: ["orders", "open", userId],
|
|
480
|
+
run: (db: SignetDb) => scoped(db, { userId }).select(orders, isNull(orders.shippedAt)),
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
await openOrders(userId).run(db)
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
Plain `{ key, run(db) }` objects with inferred result and key types, usable
|
|
487
|
+
from handlers, jobs and tests; the key names the query for caching, logs or
|
|
488
|
+
devtools.
|
|
489
|
+
|
|
490
|
+
## Plans and entitlements
|
|
491
|
+
|
|
492
|
+
```ts
|
|
493
|
+
import { entitlementTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
494
|
+
import { createEntitlements, definePlans } from "@dapplelight/signet-db/entitlements"
|
|
495
|
+
|
|
496
|
+
export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables()
|
|
497
|
+
|
|
498
|
+
const plans = definePlans({
|
|
499
|
+
free: { features: ["export"], limits: { seats: 1, aiCredits: 20 } },
|
|
500
|
+
pro: { features: ["export", "sso"], limits: { seats: 10, aiCredits: 1000 } },
|
|
501
|
+
team: { features: ["export", "sso", "audit"], limits: { seats: Infinity, aiCredits: 5000 } },
|
|
502
|
+
})
|
|
503
|
+
|
|
504
|
+
const ent = createEntitlements(db, {
|
|
505
|
+
plans,
|
|
506
|
+
default: "free",
|
|
507
|
+
tables: { subjectPlans, entitlementOverrides, usageCounters },
|
|
508
|
+
periods: { seats: "total" }, // aiCredits: "month" by default
|
|
509
|
+
billing: { plans: { plan_Nx1: "pro", price_9f: "team" }, graceMs: 3 * 86_400_000 },
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
await ent.can(orgId, "sso") // an undeclared feature is a type error, and throws at runtime
|
|
513
|
+
await ent.limit(orgId, "seats") // a limit a plan leaves out is 0; Infinity is unlimited
|
|
514
|
+
await ent.get(orgId) // { plan, storedPlan, status, graceUntil, features, limits, overrides }
|
|
515
|
+
await ent.consume(orgId, "aiCredits", 5) // { ok, used, limit, remaining, period }
|
|
516
|
+
await ent.usage(orgId) // this period, every limit
|
|
517
|
+
|
|
518
|
+
const actor = { type: "user", id: adminId }
|
|
519
|
+
await ent.setPlan(orgId, "pro", { actor })
|
|
520
|
+
await ent.grant(orgId, "audit", { actor, expiresAt: trialEnd }) // also revoke, setLimit (null = unlimited)
|
|
521
|
+
await ent.removeOverride(orgId, overrideId, { actor })
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
A subject is any id: a user or an org. It has one stored row per source:
|
|
525
|
+
each subscription (App Store, Google Play, Stripe, Razorpay, ...) and
|
|
526
|
+
`manual` for `setPlan`. Sources roll up into one entitlement per plan, active
|
|
527
|
+
while any of its sources is. A source is active while it is `active` or
|
|
528
|
+
`trialing` (until `currentPeriodEnd`, plus `graceMs` if the period ends with
|
|
529
|
+
no event), `cancelled` with a future `currentPeriodEnd`, or `past_due` before
|
|
530
|
+
`graceUntil`. Declare plans lowest first: the plan in effect is the last
|
|
531
|
+
declared plan with an active entitlement, else `default`. So `setPlan` sets
|
|
532
|
+
the manual source, and a live subscription on a later plan still wins.
|
|
533
|
+
`ent.get(subject)` returns `plan`, `currentPeriodEnd` (the latest among that
|
|
534
|
+
plan's active sources), `source` (the one behind it) and `entitlements`
|
|
535
|
+
(every plan with its sources). Overrides apply on
|
|
536
|
+
top, newest unexpired per key. Every write goes through `audited`, so the db
|
|
537
|
+
needs an audit table; usage counters are not audited.
|
|
538
|
+
|
|
539
|
+
`consume` adds to the counter only if the result stays within the limit, in
|
|
540
|
+
one `UPDATE … WHERE used + n <= limit`, so concurrent requests cannot
|
|
541
|
+
overspend. Periods are UTC calendar months (`"2026-11"`), days, or `"total"`.
|
|
542
|
+
|
|
543
|
+
### Billing events
|
|
544
|
+
|
|
545
|
+
```ts
|
|
546
|
+
const payments = createPayments({
|
|
547
|
+
gateways,
|
|
548
|
+
db: store,
|
|
549
|
+
onEvent: (event) => ent.applyBillingEvent(event),
|
|
550
|
+
})
|
|
551
|
+
// At checkout, link the subscription to the subject on its first event:
|
|
552
|
+
await ent.applyBillingEvent(event, { subject: orgId }) // or billing.subjectOf(event), e.g. from notes
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Applies `subscription.created`, `activated`, `charged`, `updated`, `paused`,
|
|
556
|
+
`resumed`, `past_due`, `cancelled` and `expired` (and App Store refunds) to
|
|
557
|
+
the source row of the event's gateway and subscription id. The subject is
|
|
558
|
+
`opts.subject`, `billing.subjectOf(event)`, the subject already stored for
|
|
559
|
+
the subscription, or for Google Play the subject of the `linkedPurchaseToken`.
|
|
560
|
+
A subscription belongs to one subject: an event or restore that names another
|
|
561
|
+
returns `{ applied: false, reason: "other_subject" }`.
|
|
562
|
+
The gateway plan id is read by `billing.planIdOf` (default: Razorpay's
|
|
563
|
+
`payload.subscription.entity.plan_id`, Stripe's item price or plan id, then
|
|
564
|
+
the event's store `productId`) and mapped through `billing.plans`, trying
|
|
565
|
+
`"<gateway>:<id>"` before `<id>`. `currentPeriodEnd` comes from
|
|
566
|
+
`billing.periodEndOf` (default: Stripe `current_period_end`, Razorpay
|
|
567
|
+
`current_end`, Paddle `current_billing_period.ends_at`, Lemon Squeezy
|
|
568
|
+
`ends_at` else `renews_at`; a web gateway's `subscription.cancelled` ends
|
|
569
|
+
access now, except Lemon Squeezy's, which lasts until `ends_at`). For `created` and `updated`, whose type does
|
|
570
|
+
not say whether the subscription is live, the status comes from the payload
|
|
571
|
+
via `billing.statusOf` (default: Stripe's `data.object.status`, Paddle's
|
|
572
|
+
`data.status`, Razorpay's entity status), falling back to the stored one.
|
|
573
|
+
Each subscription is its own source, so the old one lapsing after a
|
|
574
|
+
cancel-and-recreate upgrade does not touch the new one. Each
|
|
575
|
+
event applies once (`withIdempotency`,
|
|
576
|
+
so the db needs an idempotency table), and an event older than the stored
|
|
577
|
+
state returns `{ applied: false, reason: "stale" }`: a late `cancelled` cannot
|
|
578
|
+
undo a newer upgrade. `no_subject` and `unknown_plan` are not stored as done,
|
|
579
|
+
so a retry after linking the subject or fixing the map applies.
|
|
580
|
+
|
|
581
|
+
### App Store, Google Play and restore
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
const ent = createEntitlements(db, {
|
|
585
|
+
plans, default: "free", tables,
|
|
586
|
+
billing: {
|
|
587
|
+
plans: {
|
|
588
|
+
price_9f: "pro", // Stripe
|
|
589
|
+
"appstore:pro.monthly": "pro", // App Store product id
|
|
590
|
+
"googleplay:pro": "pro", // Google Play subscription product id
|
|
591
|
+
},
|
|
592
|
+
// First event before the app claimed the purchase: look the owner up in signet-payments.
|
|
593
|
+
subjectOf: async (e) =>
|
|
594
|
+
(await store.findLinked(e.gateway, { orderId: (e as { orderId?: string }).orderId }))?.userId,
|
|
595
|
+
},
|
|
596
|
+
})
|
|
597
|
+
|
|
598
|
+
// Restore purchases: re-verify on the store, claim, re-attach.
|
|
599
|
+
const { restored, refused } = await payments.restorePurchases({ userId, purchases })
|
|
600
|
+
for (const r of restored)
|
|
601
|
+
if (r.subscription) await ent.applySubscription(r.subscription, { subject: userId })
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
App Store and Google Play events are read with `storeStateOf`, from the
|
|
605
|
+
store's own state, not the event type:
|
|
606
|
+
|
|
607
|
+
| Store state | Source | Access |
|
|
608
|
+
|---|---|---|
|
|
609
|
+
| App Store status 1 (auto-renew on or off) / Play `ACTIVE`, `CANCELED` | `active` | until `currentPeriodEnd` (expiresDate / expiryTime) |
|
|
610
|
+
| App Store status 4 (Billing Grace Period) / Play `IN_GRACE_PERIOD` | `past_due` | until `gracePeriodExpiresDate` / `expiryTime` |
|
|
611
|
+
| App Store status 3 (billing retry) / Play `ON_HOLD` | `past_due` | none |
|
|
612
|
+
| App Store status 2, 5 (expired, refunded or revoked) / Play `EXPIRED`, revoked | `expired` | none |
|
|
613
|
+
| Play `PAUSED` | `paused` | none |
|
|
614
|
+
|
|
615
|
+
`applySubscription(sub, { subject })` applies a subscription read live (a
|
|
616
|
+
signet-payments `Subscription`), so a restore also fixes a missed webhook. A
|
|
617
|
+
`cancelled` web subscription ends access now, except Lemon Squeezy's, which keeps
|
|
618
|
+
access until its `currentPeriodEnd` (`ends_at`).
|
|
619
|
+
|
|
620
|
+
## Offerings, customers and the Customer Center
|
|
621
|
+
|
|
622
|
+
RevenueCat-style monetisation on top of plans and entitlements, in your own
|
|
623
|
+
database. Tables: `monetisationTables()` from `/columns/sqlite` or `/columns/pg`
|
|
624
|
+
(`offerings`, `placements`, `customerIdentities`, `customerEvents`,
|
|
625
|
+
`customerRequests`, `chartAudiences`).
|
|
626
|
+
|
|
627
|
+
### Offerings and remote paywalls
|
|
628
|
+
|
|
629
|
+
```ts
|
|
630
|
+
import { monetisationTables } from "@dapplelight/signet-db/columns/sqlite"
|
|
631
|
+
import { createOfferings, plansFromProducts } from "@dapplelight/signet-db/offerings"
|
|
632
|
+
|
|
633
|
+
export const { offerings, placements, customerIdentities, customerEvents, customerRequests } =
|
|
634
|
+
monetisationTables()
|
|
635
|
+
|
|
636
|
+
const products = [
|
|
637
|
+
{ id: "pro.monthly", store: "appstore", plan: "pro", interval: "month" },
|
|
638
|
+
{ id: "pro_monthly", store: "googleplay", plan: "pro", interval: "month" },
|
|
639
|
+
{ id: "price_pro_m", store: "web", plan: "pro", interval: "month", price: { amount: 49900, currency: "INR" } },
|
|
640
|
+
] as const
|
|
641
|
+
const off = createOfferings(db, { tables: { offerings, placements }, plans })
|
|
642
|
+
const ent = createEntitlements(db, { plans, default: "free", tables, billing: { plans: plansFromProducts(products) } })
|
|
643
|
+
|
|
644
|
+
await off.publish("default", {
|
|
645
|
+
products,
|
|
646
|
+
paywall: { title: "Go pro", plans: ["pro"], highlight: "pro", badge: "Best value", trial: "7 days free", cta: "Start trial" },
|
|
647
|
+
}, { actor }) // version 1; the next publish is 2
|
|
648
|
+
await off.setPlacement("onboarding", {
|
|
649
|
+
offering: "default", // latest version; `version: 1` pins (rollback)
|
|
650
|
+
overrides: [{ when: { country: ["IN"], platform: ["web"] }, offering: "india" }],
|
|
651
|
+
}, { actor })
|
|
652
|
+
await off.current("onboarding", { country: "IN", platform: "web", attributes: { cohort: "beta" } })
|
|
653
|
+
// { key, version, products, paywall, placement, override: 0 }
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
- A product maps a store product id (App Store, Google Play) or a web
|
|
657
|
+
gateway's plan or price id to a plan. `plansFromProducts` turns them into
|
|
658
|
+
entitlements' `billing.plans` keys (`"appstore:<id>"`, `"googleplay:<id>"`,
|
|
659
|
+
bare ids for web), so what the paywall sells is what billing grants.
|
|
660
|
+
- `publish` validates (every plan declared, no product twice, integer
|
|
661
|
+
prices, a highlight the offering sells) and writes an immutable version;
|
|
662
|
+
the row id is `key@version`, so concurrent publishes never share a number.
|
|
663
|
+
- A placement serves its offering's latest version unless pinned. Overrides
|
|
664
|
+
match `country`, `platform` and `attributes` (a list matches any value),
|
|
665
|
+
first match wins, with the same matcher as feature flags. Changing either
|
|
666
|
+
needs no app release: the app asks for the placement each time.
|
|
667
|
+
- Admin-editable: `publish`, `setPlacement`, `versions`, `list` and
|
|
668
|
+
`placements`, or signet-server's `monetisationAdminRoutes`. In
|
|
669
|
+
`defineAdmin`, list `offerings` as read-only so versions stay immutable.
|
|
670
|
+
- The paywall config is copy, not logic: the purchase still goes through your
|
|
671
|
+
checkout (`payments.checkout` on the web; StoreKit or Play Billing, then
|
|
672
|
+
`verifyPurchase`, in the app). signet-ui's `RemotePaywall` renders it.
|
|
673
|
+
|
|
674
|
+
### Customer timeline
|
|
675
|
+
|
|
676
|
+
```ts
|
|
677
|
+
import { createCustomers } from "@dapplelight/signet-db/customers"
|
|
678
|
+
|
|
679
|
+
const customers = createCustomers(db, {
|
|
680
|
+
tables: { ...entitlementTables, customerIdentities, customerEvents, customerRequests },
|
|
681
|
+
entitlements: ent,
|
|
682
|
+
payments: store, // signet-payments store: payments, ledger, merge
|
|
683
|
+
})
|
|
684
|
+
createPayments({
|
|
685
|
+
...,
|
|
686
|
+
onEvent: async (e) => {
|
|
687
|
+
const subject = await customers.resolve(ownerOf(e)) // the app's user id or anonymous id
|
|
688
|
+
await ent.applyBillingEvent(e, { subject })
|
|
689
|
+
await customers.record(e, { subject })
|
|
690
|
+
},
|
|
691
|
+
})
|
|
692
|
+
await customers.timeline(userId) // { entries: [{ kind, gateway, amount, ... }], totals: [{ currency, paid, refunded, approximate }] }
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
`record` puts each event on its customer's timeline once (keyed by gateway
|
|
696
|
+
and event id), as `purchase`, `renewal`, `refund`, `cancellation`,
|
|
697
|
+
`uncancellation`, `billing_issue`, `grace_period` (App Store status 4, Play
|
|
698
|
+
`IN_GRACE_PERIOD`), `expiration`, `paused` or `dispute`. Without a subject it
|
|
699
|
+
uses the owner of the event's subscription or payment. `timeline` adds the
|
|
700
|
+
events of the customer's payments from the payments store and totals per
|
|
701
|
+
currency from the ledger (App Store prices are marked `approximate`).
|
|
702
|
+
|
|
703
|
+
### Identity merge
|
|
704
|
+
|
|
705
|
+
```ts
|
|
706
|
+
const anon = await customers.anonymousId({ orgId }) // "anon_<uuid>", before sign-in
|
|
707
|
+
// Buy as anon: App Store appAccountToken = anon.slice(5); verifyPurchase({ userId: anon })
|
|
708
|
+
const r = await customers.merge({ anonymousId: anon, userId, orgId })
|
|
709
|
+
// { merged: true, already: false, moved: { subscriptions, overrides, events, requests, payments } }
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
Moves the anonymous id's subscriptions (not a `manual` plan), grants,
|
|
713
|
+
timeline, requests and, with `payments`, its payments (`reassignUser`) to the
|
|
714
|
+
account. Rows move, never copy, so nothing is granted twice. The claim is one
|
|
715
|
+
conditional UPDATE: of concurrent merges into different accounts exactly one
|
|
716
|
+
wins (`already_merged` for the rest); repeating a merge into the same account
|
|
717
|
+
returns `already: true` and finishes anything a crash left half done.
|
|
718
|
+
Refused: an id `anonymousId` did not issue (`not_anonymous`, so two real
|
|
719
|
+
accounts never merge), the same id, a target that is itself anonymous, another
|
|
720
|
+
org (`other_org`), or, with `isMember`, a user outside the org. Anonymous ids
|
|
721
|
+
carry 122 random bits: whoever holds one can claim its purchases, so keep it
|
|
722
|
+
on the device. After a merge, `resolve(anon)` is the account, so pass events
|
|
723
|
+
tagged with the old id through it.
|
|
724
|
+
|
|
725
|
+
### Customer Center
|
|
726
|
+
|
|
727
|
+
```ts
|
|
728
|
+
const customers = createCustomers(db, {
|
|
729
|
+
...,
|
|
730
|
+
notify: (n) => notifier.notify(teamId, "customer.request", { kind: n.kind, text: n.text }),
|
|
731
|
+
cancel: (s) => payments.gateway(s.gateway).cancelSubscription(s.subscriptionId, { atPeriodEnd: true }),
|
|
732
|
+
retention: { offer: { kind: "discount", percent: 50, months: 3 }, apply: ({ source }) => applyCoupon(source) },
|
|
733
|
+
googlePlayPackage: "com.example.app",
|
|
734
|
+
})
|
|
735
|
+
await customers.overview(userId) // plan, status, currentPeriodEnd, renews, source, manageUrl, canCancel, retention
|
|
736
|
+
await customers.cancel(userId) // web: cancelled at the gateway; store: { cancelled: false, reason: "store", manageUrl }
|
|
737
|
+
await customers.acceptRetention(userId) // once per customer; applied through `retention.apply`
|
|
738
|
+
await customers.requestRefund(userId, { gateway, paymentId, reason }) // once per payment; the team is notified
|
|
739
|
+
await customers.contactSupport(userId, { message, email, topic })
|
|
740
|
+
await customers.requests({ status: "open" }); await customers.setRequestStatus(id, "done", { actor })
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
- Stores cannot be cancelled by a server: `manageUrl` is the App Store's
|
|
744
|
+
subscriptions page, or Google Play's for the product and package. App Store
|
|
745
|
+
refund requests also return `storeUrl` (Apple decides those).
|
|
746
|
+
- A refund request is only for the customer's own payment (payments store,
|
|
747
|
+
else their timeline); anything else is `NOT_FOUND`. It is recorded before
|
|
748
|
+
`notify` runs, and a request whose notice failed is sent again on retry.
|
|
749
|
+
- The retention offer is shown to a live web subscription that never took
|
|
750
|
+
one; pass `eligible` to change that (store offers belong to the store).
|
|
751
|
+
- A web cancel is recorded, so `renews` and `canCancel` turn false while the
|
|
752
|
+
gateway still reports the subscription active until its period end.
|
|
753
|
+
- signet-ui's `CustomerCenter` renders it; signet-server's
|
|
754
|
+
`monetisationRoutes` serves it.
|
|
755
|
+
|
|
756
|
+
### Offers
|
|
757
|
+
|
|
758
|
+
Free trials, intro offers and win-back offers ride on offering products, so
|
|
759
|
+
they change with a `publish` like the rest of the paywall:
|
|
760
|
+
|
|
761
|
+
```ts
|
|
762
|
+
await off.publish("default", {
|
|
763
|
+
products: [{
|
|
764
|
+
id: "pro.monthly", store: "appstore", plan: "pro", interval: "month",
|
|
765
|
+
offers: [
|
|
766
|
+
{ id: "trial7", type: "free_trial", days: 7 }, // never subscribed, once
|
|
767
|
+
{ id: "winback50", type: "win_back", price: { amount: 249, currency: "USD" }, days: 30,
|
|
768
|
+
eligibility: { lapsedDays: 30 } }, // lapsed 30+ days, once
|
|
769
|
+
],
|
|
770
|
+
}],
|
|
771
|
+
}, { actor })
|
|
772
|
+
|
|
773
|
+
const offering = await customers.withOffers(userId, await off.current("onboarding", audience))
|
|
774
|
+
// each product's `offers` cut to what this customer may see now, best first
|
|
775
|
+
await customers.redeemOffer(userId, offering, "winback50")
|
|
776
|
+
// { redeemed: true, offer, product } | { redeemed: false, reason: "not_eligible" | "already_used" | "no_such_offer" }
|
|
777
|
+
```
|
|
778
|
+
|
|
779
|
+
- Eligibility (`offerEligible(offer, history)`, a pure function): never while
|
|
780
|
+
a subscription is live; `neverSubscribed` (the default for free trials and
|
|
781
|
+
intro offers) means no subscription or trial before on any plan;
|
|
782
|
+
`lapsedDays: n` (required for win-back) means the last subscription ended
|
|
783
|
+
at least `n` days ago; every offer is once per customer unless
|
|
784
|
+
`once: false`, and a free trial is also spent by any earlier trial on the
|
|
785
|
+
timeline.
|
|
786
|
+
- `redeemOffer` claims the offer before you apply it (a web coupon, a trial
|
|
787
|
+
at checkout): one row per customer and offer, so of concurrent claims one
|
|
788
|
+
wins. Store offers are still the store's to grant (App Store intro
|
|
789
|
+
eligibility, Play offer tags); the filter decides what the paywall shows.
|
|
790
|
+
- signet-server's `GET /offerings/:placement` returns the filtered offering;
|
|
791
|
+
signet-ui's `RemotePaywall` shows the first offer and passes it to
|
|
792
|
+
`onPurchase`.
|
|
793
|
+
|
|
794
|
+
### Promotional entitlements
|
|
795
|
+
|
|
796
|
+
```ts
|
|
797
|
+
await customers.grantPromotional(userId, { plan: "pro", days: 30, note: "Beta tester" }, { actor })
|
|
798
|
+
// or { expiresAt }; also ent.grantPromotional(subject, plan, { actor, expiresAt })
|
|
799
|
+
await customers.endPromotional(userId, grantId, { actor }) // early; once
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
A promotional grant is its own entitlement source (gateway `promotional`): it
|
|
803
|
+
rolls up with subscriptions, a paid plan declared later still wins, and it
|
|
804
|
+
lapses exactly at its expiry with no job to run and no grace period. The
|
|
805
|
+
timeline shows `promotional` when granted and `expiration` when it lapses or
|
|
806
|
+
is ended. It is not a paid source: the Customer Center does not offer to
|
|
807
|
+
cancel it, and charts leave it out.
|
|
808
|
+
|
|
809
|
+
### Apple refund requests (CONSUMPTION_REQUEST)
|
|
810
|
+
|
|
811
|
+
When a customer asks Apple for a refund, Apple sends `CONSUMPTION_REQUEST`
|
|
812
|
+
and wants your consumption information within 12 hours, only for a customer
|
|
813
|
+
who consented to share it.
|
|
814
|
+
|
|
815
|
+
```ts
|
|
816
|
+
const customers = createCustomers(db, {
|
|
817
|
+
...,
|
|
818
|
+
consumption: {
|
|
819
|
+
consented: (subject) => privacy.has(subject, "apple_refund_info"), // required; no consent = no answer
|
|
820
|
+
refundPreference: (ctx) => undefined, // optional: DECLINE | GRANT_FULL | GRANT_PRORATED
|
|
821
|
+
},
|
|
822
|
+
})
|
|
823
|
+
onEvent: async (e) => {
|
|
824
|
+
await customers.record(e) // on the timeline as refund_request
|
|
825
|
+
const r = await customers.consumptionInfo(e)
|
|
826
|
+
if (r.respond) await appstoreGateway.sendConsumptionInfo(r.transactionId, r.body)
|
|
827
|
+
}
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
The body is Apple's v2 ConsumptionRequest, built from the customer's data:
|
|
831
|
+
`customerConsented: true`, `deliveryStatus` `DELIVERED` when the purchase is
|
|
832
|
+
on their timeline (else `UNDELIVERED_OTHER`), `consumptionPercentage` as the
|
|
833
|
+
share of the paid period used (0 unless delivered, left out with
|
|
834
|
+
`GRANT_PRORATED`), and `sampleContentProvided` when they had a free trial.
|
|
835
|
+
Every field has a hook to override. `respond: false` says why
|
|
836
|
+
(`no_consent`, `no_subject`, `not_configured`, `not_consumption_request`).
|
|
837
|
+
|
|
838
|
+
### Subscription charts
|
|
839
|
+
|
|
840
|
+
```ts
|
|
841
|
+
import { chartsCsv, createCharts } from "@dapplelight/signet-db/charts"
|
|
842
|
+
|
|
843
|
+
const charts = createCharts(db, {
|
|
844
|
+
tables: { customerEvents, chartAudiences, offerings }, // products from every offering version
|
|
845
|
+
fx: { base: "USD", rates: { INR: 0.012, EUR: 1.08 } }, // optional: totals in one currency
|
|
846
|
+
})
|
|
847
|
+
const r = await charts.metrics({ from: "2026-10-01", to: "2026-10-31", store: "appstore", country: "IN" })
|
|
848
|
+
// r.days[i]: activeSubscribers, activeTrials, mrr, mrrTotal, newRevenue, renewalRevenue, refunds,
|
|
849
|
+
// refundCount, newSubscriptions, trialsStarted, trialConversions, churned, impressions, conversions
|
|
850
|
+
// r.summary: the same on the last day or summed, plus trialConversion, churnRate, paywallConversion
|
|
851
|
+
const a = await charts.saveAudience("India App Store", { store: "appstore", country: "IN" }, { actor })
|
|
852
|
+
await charts.metrics({ from, to, audience: a.id })
|
|
853
|
+
await charts.csv({ from, to }) // one row per day; or chartsCsv(r)
|
|
854
|
+
await customers.logImpression(userId, { offering: "default", version: 3, country: "IN" }) // paywall views
|
|
855
|
+
```
|
|
856
|
+
|
|
857
|
+
One GROUP BY on SQLite, D1 or Postgres buckets the timeline per subscription,
|
|
858
|
+
kind and UTC day; the rows are then replayed per subscription. Money stays per
|
|
859
|
+
currency in minor units; `mrrTotal` is set only when `fx` has a rate for
|
|
860
|
+
every currency in it. App Store amounts are list prices, so such results say
|
|
861
|
+
`approximate`. How the timeline reads: the first paid charge is new revenue
|
|
862
|
+
and later ones renewals; each charge covers one interval of its product
|
|
863
|
+
(unknown products a month) and MRR is that charge per month (a year / 12;
|
|
864
|
+
events without an amount use the product's display price); a refund or
|
|
865
|
+
expiration ends coverage that day, and coverage that ends without a renewal is
|
|
866
|
+
churn; a `trial` (a zero-amount or App Store FREE_TRIAL purchase) lasts the
|
|
867
|
+
product's free-trial `days` (else `trialDays`, 7) and converts when paid
|
|
868
|
+
within it; a start is a paywall conversion when the customer saw an offering
|
|
869
|
+
within `attributionDays` (7) before, and that offering is what the offering
|
|
870
|
+
filter matches. A customer's country is the latest one recorded
|
|
871
|
+
(`record(e, { country })` or the impression's). Ranges are at most 731 days.
|
|
872
|
+
signet-server's `monetisationAdminRoutes({ charts })` serves it and signet-ui's
|
|
873
|
+
`SubscriptionCharts` draws it.
|
|
874
|
+
|
|
875
|
+
## Web-to-app funnels
|
|
876
|
+
|
|
877
|
+
`@dapplelight/signet-db/funnels`: a hosted web checkout that sells an
|
|
878
|
+
offering's web products, then unlocks the purchase in the app. Tables:
|
|
879
|
+
`funnelTables()` (in `./columns/sqlite` and `./columns/pg`) plus
|
|
880
|
+
`customerEvents` from `monetisationTables()`.
|
|
881
|
+
|
|
882
|
+
### Funnels and checkout
|
|
883
|
+
|
|
884
|
+
```ts
|
|
885
|
+
import { createFunnels, funnelSteps } from "@dapplelight/signet-db/funnels"
|
|
886
|
+
|
|
887
|
+
const funnels = createFunnels(db, {
|
|
888
|
+
tables: { ...funnelTables(), customerEvents },
|
|
889
|
+
funnels: [{
|
|
890
|
+
key: "spring", placement: "web", title: "Sleep better",
|
|
891
|
+
questions: [{ id: "goal", title: "Your goal?", options: [{ value: "sleep", label: "Sleep" }] }],
|
|
892
|
+
}],
|
|
893
|
+
discounts: [{ code: "SPRING25", percentOff: 25, expiresAt: "2027-04-01", maxRedemptions: 500, plans: ["pro"] }],
|
|
894
|
+
offerings, customers, entitlements, // entitlements' billing.plans from plansFromProducts
|
|
895
|
+
checkout: (input) => payments.checkout(input), // signet-payments
|
|
896
|
+
track: (e) => sink.write([e]), // any signet-server AnalyticsSink
|
|
897
|
+
onPaid: async (s) => s.email && sendMail(s.email, (await redemptionLink(opts, s.id)).link),
|
|
898
|
+
})
|
|
899
|
+
createPayments({ ..., onEvent: async (e) => {
|
|
900
|
+
await entitlements.applyBillingEvent(e); await customers.record(e); await funnels.applyEvent(e)
|
|
901
|
+
} })
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
- `page(key, { code })` is what the hosted page shows: the funnel, the
|
|
905
|
+
placement's priced web products, and the URL's code priced per product.
|
|
906
|
+
- `start(key, { productId, answers, code, email, visitor })` checks the
|
|
907
|
+
product is a priced web product of the offering and the answers fit the
|
|
908
|
+
questions, prices the discount and takes one use, creates a new anonymous
|
|
909
|
+
customer (`customers.anonymousId`), and asks the gateway for exactly that
|
|
910
|
+
amount under the session id (`fs_<uuid>`) as idempotency key and reference.
|
|
911
|
+
The client never sends a price.
|
|
912
|
+
- `applyEvent(e)`: a verified `payment.captured` for a funnel checkout, for
|
|
913
|
+
the amount and currency priced, grants the plan to the anonymous customer
|
|
914
|
+
(one interval from the capture; lifetime for `once`) through
|
|
915
|
+
`entitlements.applySubscription`, puts the discount on the customer
|
|
916
|
+
timeline (kind `discount`) and marks the session `paid`, once. A different
|
|
917
|
+
amount is `amount_mismatch` and grants nothing. `refund.processed` ends the
|
|
918
|
+
access, on whichever account it was merged into. Pass `grant` to start a
|
|
919
|
+
renewing gateway subscription instead.
|
|
920
|
+
|
|
921
|
+
### URL discounts
|
|
922
|
+
|
|
923
|
+
A code arrives in the funnel URL (`/f/spring?code=SPRING25`) and is priced on
|
|
924
|
+
the server only: it must exist (case-insensitive), be unexpired, cover the
|
|
925
|
+
plan (`plans`) and the currency (`amountOff`), have uses left, and leave
|
|
926
|
+
something to charge. It is charged as a price override, so it works on every
|
|
927
|
+
gateway. `maxRedemptions` is held by one conditional UPDATE, so concurrent
|
|
928
|
+
checkouts never pass it; a checkout the gateway refused gives its use back.
|
|
929
|
+
An abandoned checkout holds its use for `discountHoldMs` (default 1 hour):
|
|
930
|
+
when a code looks used up, open sessions older than that are marked
|
|
931
|
+
`expired` and their uses freed. A payment captured after that still grants
|
|
932
|
+
the plan and takes a use again, so a limited code can go over by those late
|
|
933
|
+
payers only.
|
|
934
|
+
|
|
935
|
+
### Redemption
|
|
936
|
+
|
|
937
|
+
```ts
|
|
938
|
+
const r = await funnels.redeem(sessionId, userId, { orgId })
|
|
939
|
+
// { redeemed: true, already: false, session } | { redeemed: false, reason }
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
The session is claimed for one account with a conditional UPDATE, then
|
|
943
|
+
`customers.merge` moves the anonymous buyer's plan, payments and timeline to
|
|
944
|
+
it. Repeating it for the same account returns `already: true` and finishes a
|
|
945
|
+
merge a crash left half done; another account gets `already_redeemed`; of
|
|
946
|
+
two accounts racing, exactly one wins. A refused merge (`other_org`,
|
|
947
|
+
`not_member`) frees the claim. Before payment it is `not_paid`; after a
|
|
948
|
+
refund, `refunded`. The redemption token (signed, expiring) is
|
|
949
|
+
signet-server's: `funnelRoutes` checks it before calling this.
|
|
950
|
+
|
|
951
|
+
### Funnel analytics
|
|
952
|
+
|
|
953
|
+
Every step is an event named `funnel:<key>:<step>`: one per question, then
|
|
954
|
+
`plans`, `checkout`, `purchased`, `redeemed`, with the browser's analytics
|
|
955
|
+
id so the purchase joins the visit. Drop-off:
|
|
956
|
+
`analytics.funnel({ steps: funnelSteps(def) })`. Analytics never fails a
|
|
957
|
+
purchase.
|
|
958
|
+
|
|
959
|
+
## Feature flags
|
|
960
|
+
|
|
961
|
+
```ts
|
|
962
|
+
import { flagOverrides } from "@dapplelight/signet-db/columns/sqlite"
|
|
963
|
+
import { createFlags, defineFlags } from "@dapplelight/signet-db/flags"
|
|
964
|
+
|
|
965
|
+
const flags = defineFlags({
|
|
966
|
+
newEditor: {
|
|
967
|
+
default: false,
|
|
968
|
+
rules: [
|
|
969
|
+
{ when: { plan: ["team"] }, value: true },
|
|
970
|
+
{ when: { attributes: { country: ["IN", "LK"] } }, value: true },
|
|
971
|
+
],
|
|
972
|
+
rollout: { percent: 10, value: true },
|
|
973
|
+
},
|
|
974
|
+
})
|
|
975
|
+
const ff = createFlags(db, flags, { table: schema.flagOverrides, entitlements: ent })
|
|
976
|
+
|
|
977
|
+
await ff.get("newEditor", { id: userId, attributes: { country } }) // { value, reason: "rule", rule: 1 }
|
|
978
|
+
await ff.all({ id: userId })
|
|
979
|
+
await ff.set("newEditor", true, { subject: "*", actor }) // everyone; or one subject id
|
|
980
|
+
await ff.clear("newEditor", { subject: "*", actor })
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
First match wins: the subject's override, the everyone (`"*"`) override,
|
|
984
|
+
rules in order, the rollout, the default. The rollout bucket is FNV-1a of
|
|
985
|
+
`salt:subjectId` (salt defaults to the flag key) in 0–9999, so a subject keeps
|
|
986
|
+
its answer, raising the percent only adds subjects, and changing `salt`
|
|
987
|
+
reshuffles. `evaluateFlag(key, def, subject, override?)` is the same order as
|
|
988
|
+
a pure function. With `entitlements`, a subject without `plan` gets its plan
|
|
989
|
+
looked up. Overrides can expire and are audited. Every result says why.
|
|
990
|
+
|
|
991
|
+
### Tools for agents
|
|
992
|
+
|
|
993
|
+
```ts
|
|
994
|
+
import { entitlementTools } from "@dapplelight/signet-db/entitlements"
|
|
995
|
+
import { approvalGate } from "@dapplelight/signet-server/mcp"
|
|
996
|
+
|
|
997
|
+
const tools = entitlementTools({
|
|
998
|
+
entitlements: ent,
|
|
999
|
+
flags: ff,
|
|
1000
|
+
subject: orgId, // or allSubjects: true for an operator agent; tools then take `subject`
|
|
1001
|
+
allowWrites: true, // default false: read tools only
|
|
1002
|
+
actor: { type: "agent", id: "support-agent" },
|
|
1003
|
+
approve: approvalGate,
|
|
1004
|
+
})
|
|
1005
|
+
```
|
|
1006
|
+
|
|
1007
|
+
Read: `get_plan`, `check_entitlement`, `usage`, `list_flags`. Write (with
|
|
1008
|
+
`allowWrites`): `grant_feature`, `set_plan`, `set_flag`. Writes always call
|
|
1009
|
+
`approve`; without one they change nothing and return `APPROVAL_REQUIRED`.
|
|
1010
|
+
`approvalGate` is signet-server's one approval step: it asks in the client,
|
|
1011
|
+
or, with `createMcpServer({ approvals })`, opens a pending approval the
|
|
1012
|
+
person decides in the app (see signet-server's "Approvals").
|
|
1013
|
+
They are audited as `actor`. Give writes only to agents run by staff: on a
|
|
1014
|
+
per-user agent the person approving is the user who benefits.
|
|
1015
|
+
|
|
1016
|
+
## Experiments
|
|
1017
|
+
|
|
1018
|
+
A/B/n tests on top of feature flags. Tables: `experimentTables()` from
|
|
1019
|
+
`/columns/sqlite` or `/columns/pg` (`experiments`, `experimentExposures`);
|
|
1020
|
+
conversions are read from `analyticsEvents()`.
|
|
1021
|
+
|
|
1022
|
+
```ts
|
|
1023
|
+
import { analyticsEvents, experimentTables } from "@dapplelight/signet-db/columns/sqlite"
|
|
1024
|
+
import { createExperiments } from "@dapplelight/signet-db/experiments"
|
|
1025
|
+
|
|
1026
|
+
export const { experiments, experimentExposures } = experimentTables()
|
|
1027
|
+
const ex = createExperiments(db, { tables: { experiments, experimentExposures }, events: analyticsEvents() })
|
|
1028
|
+
|
|
1029
|
+
await ex.create("onboarding-copy", {
|
|
1030
|
+
variants: [{ key: "control", weight: 50 }, { key: "short", weight: 50, value: { steps: 3 } }],
|
|
1031
|
+
goal: "signup_completed", // an analytics event name
|
|
1032
|
+
audience: { plan: ["free"] }, // optional: a flag rule's `when`
|
|
1033
|
+
}, { actor })
|
|
1034
|
+
await ex.start("onboarding-copy", { actor })
|
|
1035
|
+
await ex.expose("onboarding-copy", { id: userId }) // { variant: "short", value: { steps: 3 }, reason: "assigned", first: true }
|
|
1036
|
+
await ex.results("onboarding-copy")
|
|
1037
|
+
// { control: "control", variants: [{ key, exposed, converted, rate, lift, pValue, significant }] }
|
|
1038
|
+
await ex.rollout("onboarding-copy", "short", { actor }) // everyone gets "short" from now on
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
- Assignment is sticky with no storage: the flags' `bucket` (FNV-1a of
|
|
1042
|
+
`salt:subjectId`) laid over the cumulative weights. Variants, weights and
|
|
1043
|
+
salt can change only while a draft, so a subject never switches variant.
|
|
1044
|
+
- `assign` reads the variant; `expose` also records the first exposure
|
|
1045
|
+
(once per subject, only while running). Call `expose` where the person
|
|
1046
|
+
actually sees the variant, so the readout counts only them.
|
|
1047
|
+
- A conversion is the subject's goal event (`userId` or `anonymousId` equal
|
|
1048
|
+
to the subject id) at or after their exposure. `results(key, { goal })`
|
|
1049
|
+
reads another event; `alpha` defaults to 0.05.
|
|
1050
|
+
- Each variant is compared with the control (the first variant) by a
|
|
1051
|
+
two-sided two-proportion z-test. With many variants, lower `alpha`.
|
|
1052
|
+
- Lifecycle: `draft` → `start` → `running` ⇄ `stop` → `rollout` →
|
|
1053
|
+
`rolled_out`. Draft and stopped give the control (`not_running`); outside
|
|
1054
|
+
the audience is the control (`not_eligible`); rolled out gives the winner.
|
|
1055
|
+
A wrong move is `CONFLICT`, as one conditional UPDATE.
|
|
1056
|
+
- A variant's `value` is JSON the app reads. Pricing experiments put an
|
|
1057
|
+
offering key there (`{ offering: "annual-first" }`) for a placement to
|
|
1058
|
+
serve; see [Pricing experiments](#pricing-experiments).
|
|
1059
|
+
- signet-server's `experimentRoutes` / `experimentAdminRoutes` serve it;
|
|
1060
|
+
signet-ui's `ExperimentResults` is the admin readout and `ExperimentForm`
|
|
1061
|
+
creates and edits one.
|
|
1062
|
+
|
|
1063
|
+
### Pricing experiments
|
|
1064
|
+
|
|
1065
|
+
A placement runs an experiment whose variants serve different offerings (or
|
|
1066
|
+
pinned versions). Pass `experiments` to `createOfferings`, link the
|
|
1067
|
+
experiment on the placement, and read it out with `createPricing` from
|
|
1068
|
+
`@dapplelight/signet-db/pricing`. Placements gain an `experiment` column:
|
|
1069
|
+
on an existing database, `ALTER TABLE placements ADD COLUMN experiment text`.
|
|
1070
|
+
|
|
1071
|
+
```ts
|
|
1072
|
+
import { createPricing } from "@dapplelight/signet-db/pricing"
|
|
1073
|
+
|
|
1074
|
+
const ex = createExperiments(db, { tables: { experiments, experimentExposures } })
|
|
1075
|
+
const offerings = createOfferings(db, { tables: { offerings: offeringsTable, placements }, plans, experiments: ex })
|
|
1076
|
+
const pricing = createPricing(db, {
|
|
1077
|
+
tables: { experimentExposures, customerEvents, customerIdentities },
|
|
1078
|
+
offerings,
|
|
1079
|
+
experiments: ex,
|
|
1080
|
+
})
|
|
1081
|
+
|
|
1082
|
+
await ex.create("annual-first", {
|
|
1083
|
+
variants: [
|
|
1084
|
+
{ key: "control", weight: 50 }, // no value: the placement's own offering
|
|
1085
|
+
{ key: "annual", weight: 50, value: { offering: "annual-first", version: 2 } },
|
|
1086
|
+
],
|
|
1087
|
+
goal: "subscribed",
|
|
1088
|
+
}, { actor })
|
|
1089
|
+
await offerings.setPlacement("onboarding", { offering: "default", experiment: "annual-first" }, { actor })
|
|
1090
|
+
await ex.start("annual-first", { actor })
|
|
1091
|
+
|
|
1092
|
+
await offerings.current("onboarding", audience, subjectId)
|
|
1093
|
+
// { key: "annual-first", version: 2, ..., experiment: { key: "annual-first", variant: "annual", reason: "assigned" } }
|
|
1094
|
+
await pricing.readout("annual-first")
|
|
1095
|
+
// { placements: ["onboarding"], variants: [{ key, offering, exposed, converted, rate, lift, pValue,
|
|
1096
|
+
// significant, trials, trialConverted, trialConversion, revenue, revenuePerExposed, ltv }] }
|
|
1097
|
+
await pricing.rollout("annual-first", "annual", { actor })
|
|
1098
|
+
// the placement now serves annual-first v2 directly; the experiment is rolled_out
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
- `current(placement, audience, subjectId)` assigns through the experiment
|
|
1102
|
+
(sticky, no storage) and records the exposure once, for everyone no
|
|
1103
|
+
audience override matched. With no subject id it serves the placement's
|
|
1104
|
+
own offering and records nothing. A variant whose offering is gone falls
|
|
1105
|
+
back to the placement's own.
|
|
1106
|
+
- `setPlacement` checks the experiment exists, is not rolled out, and that
|
|
1107
|
+
every variant's value is `{ offering, version? }` naming a published
|
|
1108
|
+
offering (or no value). It replaces the whole placement: leaving out
|
|
1109
|
+
`experiment` unlinks it.
|
|
1110
|
+
- Attribution needs no extra writes: a subject's purchases are their
|
|
1111
|
+
customer timeline events (`customers.record`) at or after the exposure,
|
|
1112
|
+
followed through identity merges when `customerIdentities` is passed.
|
|
1113
|
+
Conversion is a trial or purchase; trial conversion is a paid charge after
|
|
1114
|
+
the trial; revenue is charges minus refunds, per currency in minor units,
|
|
1115
|
+
divided by everyone exposed. Conversion gets the same z-test as `results`.
|
|
1116
|
+
- `ltv` is an estimate, labelled so: the average charge times the expected
|
|
1117
|
+
number of payments, `1 / churn` where churn is subscriptions ended
|
|
1118
|
+
(expired or refunded) per paid charge, capped at `maxPayments` (24).
|
|
1119
|
+
- `rollout` rolls the experiment out first, then points every placement
|
|
1120
|
+
running it at the winner's offering (the placement's own for a variant
|
|
1121
|
+
with none) and unlinks it; a retry after a partial failure is safe.
|
|
1122
|
+
- signet-server's `monetisationAdminRoutes({ pricing })` serves the readout
|
|
1123
|
+
and rollout; signet-ui's `PricingExperimentResults` shows them.
|
|
1124
|
+
|
|
1125
|
+
## Status page and maintenance
|
|
1126
|
+
|
|
1127
|
+
Tables: `statusTables()` (`statusComponents`, `statusIncidents`, `maintenance`).
|
|
1128
|
+
|
|
1129
|
+
```ts
|
|
1130
|
+
import { statusTables } from "@dapplelight/signet-db/columns/sqlite"
|
|
1131
|
+
import { createStatus } from "@dapplelight/signet-db/status"
|
|
1132
|
+
|
|
1133
|
+
export const { statusComponents, statusIncidents, maintenance } = statusTables()
|
|
1134
|
+
const status = createStatus(db, { tables: { statusComponents, statusIncidents, maintenance } })
|
|
1135
|
+
|
|
1136
|
+
await status.setComponent("api", { name: "API", position: 1 }, { actor })
|
|
1137
|
+
const inc = await status.openIncident(
|
|
1138
|
+
{ title: "Slow sign-in", impact: "minor", components: ["api"], message: "Looking into it" },
|
|
1139
|
+
{ actor },
|
|
1140
|
+
)
|
|
1141
|
+
await status.updateIncident(inc.id, { status: "resolved", message: "Fixed" }, { actor })
|
|
1142
|
+
await status.setMaintenance({ on: true, message: "Upgrading the database", until }, { actor })
|
|
1143
|
+
await status.summary() // { status, components, incidents, maintenance }
|
|
1144
|
+
```
|
|
1145
|
+
|
|
1146
|
+
- Component statuses (`operational`, `maintenance`, `degraded`,
|
|
1147
|
+
`partial_outage`, `major_outage`) are set by hand. The overall status is
|
|
1148
|
+
the worst of them and of open incidents' impact (`minor` degraded, `major`
|
|
1149
|
+
partial outage, `critical` major outage); maintenance mode shows unless
|
|
1150
|
+
something is worse.
|
|
1151
|
+
- Incident updates are appended, never edited; `resolved` closes the
|
|
1152
|
+
incident, after which it cannot change. `summary` lists open incidents and
|
|
1153
|
+
those resolved in the last 7 days (`days` changes it).
|
|
1154
|
+
- Every write is audited. `maintenance()` is what signet-server's
|
|
1155
|
+
`maintenanceMode` middleware reads.
|
|
1156
|
+
- signet-ui's `StatusPage` is the public page and `StatusAdmin` the admin
|
|
1157
|
+
screen (maintenance switch, component statuses, incidents and updates).
|
|
1158
|
+
|
|
1159
|
+
## Organisations and tenant scope
|
|
1160
|
+
|
|
1161
|
+
```ts
|
|
1162
|
+
import { orgTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
1163
|
+
export const { organizations, memberships, invitations, orgRoles } = orgTables()
|
|
1164
|
+
export const projects = sqliteTable("projects", { id: id(), orgId: text("org_id").notNull(), name: text("name").notNull() })
|
|
1165
|
+
|
|
1166
|
+
import { createOrgs } from "@dapplelight/signet-db/orgs"
|
|
1167
|
+
const orgs = createOrgs(db, { tables: { organizations, memberships, invitations, orgRoles } })
|
|
1168
|
+
const org = await orgs.create({ name: "Acme", ownerId: userId }) // creator is the owner
|
|
1169
|
+
await orgs.update(org.id, { domain: "app.acme.example", brandColor: "#12833c" }, { by: userId })
|
|
1170
|
+
const { token } = await orgs.invite({ orgId: org.id, role: "member", invitedBy: userId, email })
|
|
1171
|
+
await orgs.acceptInvite(token, { userId: other, email }) // { ok, membership, org } | { ok: false, reason }
|
|
1172
|
+
await orgs.can(org.id, other, "members:invite") // false
|
|
1173
|
+
await orgs.saveRole(org.id, "billing", ["billing:read"], { by: userId }) // a custom role in this org
|
|
1174
|
+
|
|
1175
|
+
const data = scoped(db, { orgId: org.id }) // org_id on every where and insert
|
|
1176
|
+
const mine = scoped(db, { userId, orgId: org.id }) // both
|
|
1177
|
+
```
|
|
1178
|
+
|
|
1179
|
+
- Roles map to permission sets (`DEFAULT_ORG_ROLES`: owner `*`, admin,
|
|
1180
|
+
member; `defineRoles` for your own). `members:*` matches every `members:`
|
|
1181
|
+
permission. Custom roles live per org in `orgRoles`.
|
|
1182
|
+
- With `{ by }`, a change is checked against the actor: they need the
|
|
1183
|
+
permission (`ORG_PERMISSIONS`) and cannot hand out a role with
|
|
1184
|
+
permissions they lack. An org always keeps one owner.
|
|
1185
|
+
- Invite tokens are 256 random bits shown once; only the SHA-256 is stored.
|
|
1186
|
+
They expire (`inviteTtlMs`, default 7 days), work once and can be revoked.
|
|
1187
|
+
- `byDomain(host)` and `bySlug(slug)` resolve a tenant; signet-server's
|
|
1188
|
+
`tenant()` middleware uses them.
|
|
1189
|
+
- An org scope is deny-by-default: a table without `orgId` (and without a
|
|
1190
|
+
`userId` the scope also fixes) throws `NOT_TENANT_TABLE`; writes that name
|
|
1191
|
+
another org throw `CROSS_ORG_WRITE`.
|
|
1192
|
+
- `defineAdmin` with `ctx.orgId` shows only tables with `orgId`, limits every
|
|
1193
|
+
op to that org and puts creates in it; `tenant: true` requires an org.
|
|
1194
|
+
- With an audit table, every write is logged: `org.create`, `org.update`,
|
|
1195
|
+
`member.add`, `member.role`, `member.remove`, `member.leave`,
|
|
1196
|
+
`role.create`, `role.update`, `role.delete`, `invite.create`,
|
|
1197
|
+
`invite.accept`, `invite.revoke`. Each entry has the actor (`by`, else the
|
|
1198
|
+
system), and before/after snapshots carrying `orgId`. Invite tokens and
|
|
1199
|
+
hashes are never logged. Without an audit table nothing is written.
|
|
1200
|
+
- Failures are `OrgError` (a `SignetDbError` with an HTTP `status`).
|
|
1201
|
+
|
|
1202
|
+
## Growth: waitlist, invites, referrals, onboarding, changelog, feedback
|
|
1203
|
+
|
|
1204
|
+
```ts
|
|
1205
|
+
import { growthTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
1206
|
+
import { createGrowth } from "@dapplelight/signet-db/growth"
|
|
1207
|
+
|
|
1208
|
+
export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables()
|
|
1209
|
+
|
|
1210
|
+
const growth = createGrowth(db, {
|
|
1211
|
+
tables: { waitlist, invites, referralCodes, referrals, marks, feedback },
|
|
1212
|
+
inviteTtlMs: 7 * 86_400_000, // the default
|
|
1213
|
+
})
|
|
1214
|
+
|
|
1215
|
+
// Waitlist: idempotent, position among people still waiting
|
|
1216
|
+
await growth.joinWaitlist(email, { source: "launch", referralCode }) // { email, position, joined }
|
|
1217
|
+
await growth.waitlistStats() // { total, pending, invited }
|
|
1218
|
+
await growth.markInvited([email]) // then send them an invite
|
|
1219
|
+
|
|
1220
|
+
// Invites: the token is returned once; only its SHA-256 is stored
|
|
1221
|
+
const { invite, token } = await growth.createInvite({ invitedBy: userId, scope: orgId, role: "member", email })
|
|
1222
|
+
await growth.acceptInvite(token, { userId, email }) // { ok: true, invite, already } | { ok: false, reason }
|
|
1223
|
+
await growth.revokeInvite(invite.id)
|
|
1224
|
+
|
|
1225
|
+
// Referrals: one referrer per person, no self-referral, reward once
|
|
1226
|
+
const code = await growth.referralCode(userId) // 8 Crockford base32 characters, stable
|
|
1227
|
+
await growth.refer(code, newUserId) // at sign-up
|
|
1228
|
+
const c = await growth.convertReferral(newUserId) // at first payment
|
|
1229
|
+
if (c?.first) { /* reward c.referral.referrer */ await growth.markRewarded(newUserId) }
|
|
1230
|
+
|
|
1231
|
+
// Onboarding and "what's new"
|
|
1232
|
+
await growth.completeStep(userId, "profile")
|
|
1233
|
+
await growth.onboarding(userId, ["profile", "invite", "first-project"]) // { done, next, complete, percent }
|
|
1234
|
+
await growth.unseenChangelog(userId, entries) // entries newer than the last markChangelogSeen
|
|
1235
|
+
await growth.markChangelogSeen(userId)
|
|
1236
|
+
|
|
1237
|
+
// Feedback
|
|
1238
|
+
await growth.sendFeedback({ subject: userId, kind: "bug", message, rating: 4, page: "/settings" })
|
|
1239
|
+
await growth.listFeedback({ status: "new" })
|
|
1240
|
+
```
|
|
1241
|
+
|
|
1242
|
+
`acceptInvite` fails with `not_found`, `expired`, `used` (by someone else),
|
|
1243
|
+
`revoked` or `email_mismatch` (the invite names an email and the caller's
|
|
1244
|
+
does not match). The claim is one conditional `UPDATE`, so two people
|
|
1245
|
+
cannot accept the same invite. What accepting grants (org membership, a role)
|
|
1246
|
+
is the app's: read `invite.scope` and `invite.role`. `marks` is one timestamp
|
|
1247
|
+
per subject and key; onboarding uses `onboarding:<step>` keys and the
|
|
1248
|
+
changelog `changelog:seen`, and `mark`/`marksOf` are there for your own
|
|
1249
|
+
(tours dismissed, tips seen). Feedback kinds default to
|
|
1250
|
+
`DEFAULT_FEEDBACK_KINDS` (bug, idea, praise, other); pass `feedbackKinds` to
|
|
1251
|
+
change them. These writes are the user's own actions and are not audited.
|
|
1252
|
+
|
|
1253
|
+
### Tools for agents
|
|
1254
|
+
|
|
1255
|
+
```ts
|
|
1256
|
+
import { growthTools } from "@dapplelight/signet-db/growth"
|
|
1257
|
+
|
|
1258
|
+
const tools = growthTools({ growth, allowWrites: true, invitedBy: staffId, approve })
|
|
1259
|
+
```
|
|
1260
|
+
|
|
1261
|
+
For an operator agent. Read: `waitlist_stats`, `list_waitlist`,
|
|
1262
|
+
`list_feedback`, `referral_stats`, `list_invites`. Write (with
|
|
1263
|
+
`allowWrites`): `create_invite`, `revoke_invite`, `set_feedback_status`, each
|
|
1264
|
+
gated on `approve` like the entitlement tools.
|
|
1265
|
+
|
|
1266
|
+
## DPDP: consent and data requests
|
|
1267
|
+
|
|
1268
|
+
```ts
|
|
1269
|
+
import { privacyTables } from "@dapplelight/signet-db/columns/sqlite" // or /columns/pg
|
|
1270
|
+
import { createPrivacy } from "@dapplelight/signet-db/privacy"
|
|
1271
|
+
|
|
1272
|
+
export const { consents, dataRequests } = privacyTables()
|
|
1273
|
+
|
|
1274
|
+
const privacy = createPrivacy(db, {
|
|
1275
|
+
tables: { consents, dataRequests },
|
|
1276
|
+
userTables: [notes, tags, [users, users.id]], // what export and erasure cover, children first
|
|
1277
|
+
respondWithinMs: 30 * 86_400_000, // optional: sets dueAt; no default
|
|
1278
|
+
})
|
|
1279
|
+
|
|
1280
|
+
await privacy.give(userId, "marketing-email", { noticeVersion: "2026-11-01", source: "signup" })
|
|
1281
|
+
await privacy.has(userId, "marketing-email", { noticeVersion: "2026-11-01" })
|
|
1282
|
+
await privacy.withdraw(userId, "marketing-email") // or withdraw(userId) for every purpose
|
|
1283
|
+
await privacy.history(userId) // every record, withdrawn ones included
|
|
1284
|
+
|
|
1285
|
+
const req = await privacy.requestErasure(userId) // or requestExport; one open request per kind
|
|
1286
|
+
await privacy.overdue() // pending past dueAt
|
|
1287
|
+
await privacy.fulfil(req.id, { actor: { type: "user", id: staffId } })
|
|
1288
|
+
await privacy.reject(req.id, { actor, reason: "Could not verify identity" })
|
|
1289
|
+
```
|
|
1290
|
+
|
|
1291
|
+
Consent records are append-only: each says which purpose, under which
|
|
1292
|
+
notice version, how, and when it was given and withdrawn. Giving again under
|
|
1293
|
+
the same notice returns the record in force; under a new notice it adds one.
|
|
1294
|
+
`fulfil` on an export returns the data from `exportUser` (send it to the
|
|
1295
|
+
person; it is not stored). On an erasure it runs `deleteUser` over
|
|
1296
|
+
`userTables` (audited when the db has an audit table), withdraws every
|
|
1297
|
+
consent, and stores the row counts. Consent and request records are kept as
|
|
1298
|
+
the proof of what happened; whether and when to purge them, the response
|
|
1299
|
+
deadline and the notice text are the app's decisions, not this module's.
|
|
1300
|
+
This is record-keeping for the DPDP Act, not legal advice.
|
|
1301
|
+
|
|
1302
|
+
### Tools for agents
|
|
1303
|
+
|
|
1304
|
+
```ts
|
|
1305
|
+
import { privacyTools } from "@dapplelight/signet-db/privacy"
|
|
1306
|
+
|
|
1307
|
+
const tools = privacyTools({ privacy, subject: userId, approve })
|
|
1308
|
+
```
|
|
1309
|
+
|
|
1310
|
+
For an agent acting for one person. Read: `list_consents`,
|
|
1311
|
+
`list_data_requests`. Write: `withdraw_consent`, `request_data_export`,
|
|
1312
|
+
`request_erasure`, always gated on `approve`. Agents only open requests;
|
|
1313
|
+
`fulfil` is a staff action in code.
|
|
1314
|
+
|
|
1315
|
+
## Analytics events
|
|
1316
|
+
|
|
1317
|
+
`createAnalyticsStore(db, { table: analyticsEvents(), retentionDays?, privacy? })`
|
|
1318
|
+
stores events (it is a signet-server `AnalyticsSink`), links anonymous events
|
|
1319
|
+
on `$identify`, keeps userIds only with consent when given `privacy`, and
|
|
1320
|
+
answers typed questions: `count`, `uniques`, `series`, `breakdown`, `funnel`,
|
|
1321
|
+
`retention`, `trend`, `events`. `prune()` applies the retention. Read-only
|
|
1322
|
+
agent tools: `analyticsTools({ store })`. The full guide is in
|
|
1323
|
+
[signet-lib's ANALYTICS.md](../lib/ANALYTICS.md#store-events-in-your-database).
|
|
1324
|
+
|
|
1325
|
+
## Workflows: durable runs with approval steps
|
|
1326
|
+
|
|
1327
|
+
**Jobs or workflows?** Use signet-server `jobs` for quick fire-and-forget
|
|
1328
|
+
background tasks; use signet-db workflows for long-running, multi-step,
|
|
1329
|
+
crash-safe work or work that needs a person's approval.
|
|
1330
|
+
|
|
1331
|
+
- Job: `await sendReceipt.enqueue({ orderId })`
|
|
1332
|
+
- Workflow: `await wf.start(refund, { orderId })`, where `refund` calls `step.approval({ approvers: [managerId] })`
|
|
1333
|
+
|
|
1334
|
+
```ts
|
|
1335
|
+
import { workflowTables } from "@dapplelight/signet-db/columns/sqlite" // or columns/pg
|
|
1336
|
+
import { createWorkflows, defineWorkflow } from "@dapplelight/signet-db/workflows"
|
|
1337
|
+
|
|
1338
|
+
export const { workflowRuns, workflowSteps, workflowEvents } = workflowTables()
|
|
1339
|
+
|
|
1340
|
+
const payout = defineWorkflow("payout", async (step, input: { requestId: string }) => {
|
|
1341
|
+
const req = await step.run("load", () => loadRequest(input.requestId))
|
|
1342
|
+
const ok = await step.approval({ approvers: req.approverIds, summary: `Pay ${req.amount}?`, timeout: 2 * DAY })
|
|
1343
|
+
if (!ok.approved) return { paid: false, by: ok.by, timedOut: ok.timedOut }
|
|
1344
|
+
await step.run("pay", () => psp.pay(req), { attempts: 5, backoff: (n) => n * 30_000 })
|
|
1345
|
+
await step.sleep("settle", HOUR) // or step.sleepUntil("x", date)
|
|
1346
|
+
const receipt = await step.waitForEvent(`settled:${req.id}`, { timeout: DAY })
|
|
1347
|
+
return { paid: true, receipt }
|
|
1348
|
+
})
|
|
1349
|
+
|
|
1350
|
+
const wf = createWorkflows(db, {
|
|
1351
|
+
tables: { workflowRuns, workflowSteps, workflowEvents },
|
|
1352
|
+
workflows: [payout],
|
|
1353
|
+
approvals, // optional: signet-server's kvApprovals
|
|
1354
|
+
notify: (to, r) => notifier.notify(to, "workflow.approval", r), // optional
|
|
1355
|
+
})
|
|
1356
|
+
const run = await wf.start(payout, { requestId }, { createdBy: userId })
|
|
1357
|
+
await wf.sendEvent(`settled:${id}`, receipt) // wakes the waiting run
|
|
1358
|
+
await wf.approve(run.id, "approval", userId) // or reject(...); null once decided
|
|
1359
|
+
await wf.cancel(run.id)
|
|
1360
|
+
await wf.get(run.id) // { run, steps } for a timeline
|
|
1361
|
+
await wf.list({ status: "waiting" }) // admin view
|
|
1362
|
+
await wf.pendingApprovals(userId) // an approval inbox
|
|
1363
|
+
```
|
|
1364
|
+
|
|
1365
|
+
Every tick calls the workflow function from the top. A finished step returns
|
|
1366
|
+
its stored JSON result and never runs again; the first unfinished one runs, or
|
|
1367
|
+
suspends the run until its sleep, event, approval or timeout. So step ids must
|
|
1368
|
+
be unique and stable, and anything non-deterministic goes inside `step.run`.
|
|
1369
|
+
A step whose process died half way runs again once the lease passes (it counts
|
|
1370
|
+
as an attempt), so make side effects idempotent. A changed step kind under the
|
|
1371
|
+
same id fails the run with `NONDETERMINISTIC`; a step out of attempts throws
|
|
1372
|
+
`STEP_FAILED` into the workflow, which can catch it and compensate.
|
|
1373
|
+
|
|
1374
|
+
Events go to every run waiting on that name, or one run with
|
|
1375
|
+
`{ runId }`. An event sent after the run started but before it reached the
|
|
1376
|
+
wait is still delivered; a second wait on the same name takes the next event.
|
|
1377
|
+
|
|
1378
|
+
Approval steps: only a listed approver can decide (`FORBIDDEN` otherwise).
|
|
1379
|
+
With `approvals`, each approver also gets a pending record in signet-server's
|
|
1380
|
+
approval inbox (`approvalRoutes`), and a decision made there is picked up
|
|
1381
|
+
within `approvalPollMs` (default 60 s). `notify` is called once per approver
|
|
1382
|
+
when the step opens. signet-server's `workflowRoutes` mounts start, status,
|
|
1383
|
+
events, approve/reject, cancel and the admin list over HTTP.
|
|
1384
|
+
|
|
1385
|
+
**Runners.** Nothing runs until something calls `tick()`. Each call claims up
|
|
1386
|
+
to `limit` due runs with a lease (a conditional UPDATE, so concurrent runners
|
|
1387
|
+
never hold the same run; `leaseMs`, default 5 min, must outlast your longest
|
|
1388
|
+
step) and returns `nextWakeAt`.
|
|
1389
|
+
|
|
1390
|
+
| Where | How |
|
|
1391
|
+
|---|---|
|
|
1392
|
+
| Bun / Node | `wf.poll({ intervalMs: 1000, signal })` in the server process, or `setInterval(() => wf.tick(), 1000)` |
|
|
1393
|
+
| Cloudflare Workers (the default path) | a cron trigger: `scheduled(_, env, ctx) { ctx.waitUntil(makeWf(env).tick({ limit: 25 })) }`. Cron fires once a minute, so sleeps and timeouts resolve to the minute; after `start` or `sendEvent` call `ctx.waitUntil(wf.tick())` to run right away |
|
|
1394
|
+
| Durable Object alarm (optional) | call `tick()` in `alarm()` and `setAlarm(nextWakeAt)` from its result. No extra dependency; worth it only for sub-minute timing on Workers |
|
|
1395
|
+
| Queue consumer (optional) | a message per start or event whose handler calls `tick()`. Same engine, no extra dependency |
|
|
1396
|
+
|
|
1397
|
+
Run as many runners as you like; they share the database and the lease.
|
|
1398
|
+
`prune(olderThanMs)` deletes finished runs and old events (default 30 days).
|
|
1399
|
+
|
|
1400
|
+
## Comments, mentions, activity and version history
|
|
1401
|
+
|
|
1402
|
+
Record collaboration for org apps: comment threads on any record, @mentions
|
|
1403
|
+
that notify, an activity timeline per record, and version history with diff,
|
|
1404
|
+
restore and undo.
|
|
1405
|
+
|
|
1406
|
+
```ts
|
|
1407
|
+
import { collabTables } from "@dapplelight/signet-db/columns/sqlite" // or columns/pg
|
|
1408
|
+
import { createCollab } from "@dapplelight/signet-db/collab"
|
|
1409
|
+
|
|
1410
|
+
export const { comments, recordVersions } = collabTables()
|
|
1411
|
+
// Version history is opt-in per table: writes through scoped()/audited() snapshot tracked rows.
|
|
1412
|
+
const db = createDb(env.DB, { audit, versions: { table: recordVersions, track: [tasks] } })
|
|
1413
|
+
|
|
1414
|
+
const collab = createCollab(db, {
|
|
1415
|
+
tables: { comments },
|
|
1416
|
+
records: { tasks }, // what can be commented on, by name; each needs orgId
|
|
1417
|
+
orgs, // createOrgs(...)
|
|
1418
|
+
people: (ids) => namesById(ids), // { [id]: { name, email?, image? } }
|
|
1419
|
+
notify: notifyMentions(notifier), // signet-server; or (to, m) => ...
|
|
1420
|
+
})
|
|
1421
|
+
const who = { orgId, userId }
|
|
1422
|
+
const ref = { table: "tasks", id: taskId }
|
|
1423
|
+
await collab.addComment(who, ref, { body: "Ready? @[Asha](user:u_1)" }) // mentions by id
|
|
1424
|
+
await collab.addComment(who, ref, { body: "Yes", parentId: commentId }) // a reply
|
|
1425
|
+
await collab.editComment(who, commentId, { body: "…" }) // author only; edited marker
|
|
1426
|
+
await collab.deleteComment(who, commentId) // soft: text cleared
|
|
1427
|
+
await collab.comments(who, ref) // threads with replies
|
|
1428
|
+
await collab.mentionable(who, "as") // the mention picker: org members only
|
|
1429
|
+
await collab.timeline(who, ref, { limit: 20 }) // { items: [{ summary: "Asha changed status to Done" }], nextCursor }
|
|
1430
|
+
await collab.versions(who, ref) // newest first, each with its field changes
|
|
1431
|
+
await collab.diff(who, ref, 2, 5) // { changes: [{ field, from, to }] }
|
|
1432
|
+
await collab.restore(who, ref, 2) // writes version N+1 and a "restore" audit entry
|
|
1433
|
+
await collab.undo(who, ref, { expected: 5 }) // 409 if the record moved on
|
|
1434
|
+
```
|
|
1435
|
+
|
|
1436
|
+
- **Deny by default.** Only tables in `records` exist. A record of another
|
|
1437
|
+
org, or any record for someone who is not a member, is 404 (`OrgError`).
|
|
1438
|
+
Reading and commenting need membership; `restore` and `undo` need
|
|
1439
|
+
`<record>:write` (`tasks:write`; owners hold `*`). `access` replaces that
|
|
1440
|
+
rule. Editing is the author's; deleting is the author's or needs
|
|
1441
|
+
`comments:moderate`. Someone who leaves the org loses access to their own
|
|
1442
|
+
comments too.
|
|
1443
|
+
- **Mentions** are written into the text as `@[Name](user:<id>)`
|
|
1444
|
+
(`mentionToken`, `parseMentions`), so a rename never breaks one. Only org
|
|
1445
|
+
members are kept and nobody is told about their own comment. `notify`
|
|
1446
|
+
gets `{ to, by, byName, table, rowId, commentId, excerpt, key }` once per
|
|
1447
|
+
person per comment: the comment remembers who was notified, so editing,
|
|
1448
|
+
or removing and re-adding a mention, never notifies twice.
|
|
1449
|
+
- **Timeline** merges the audit log's entries for the record with its
|
|
1450
|
+
comments, newest first. Each item has structured `changes` and a
|
|
1451
|
+
`summary` from `describeItem` (override with `describe`). Changes come
|
|
1452
|
+
from writes made with `audited(...)`; encrypted fields show as changed with
|
|
1453
|
+
no values.
|
|
1454
|
+
- **Versions** store the whole row after each write as stored (encrypted
|
|
1455
|
+
fields stay ciphertext) in `recordVersions`, numbered per record. Only
|
|
1456
|
+
writes through `scoped`/`audited` and `collab` itself are recorded.
|
|
1457
|
+
`undo` puts the version before the latest back, and refuses with 409 when
|
|
1458
|
+
`expected` is not the latest version or the record changed since its last
|
|
1459
|
+
version. Restoring a soft-deleted record's earlier version brings it back.
|
|
1460
|
+
- Comment writes, restores and undos are audited (`comment.create`,
|
|
1461
|
+
`comment.edit`, `comment.delete`, `restore`, `undo`) when the db has an
|
|
1462
|
+
audit table.
|
|
1463
|
+
- signet-server's `collabRoutes` mounts all of this over HTTP; signet-ui's
|
|
1464
|
+
`screens/collab-screens` renders it.
|
|
1465
|
+
|
|
1466
|
+
## AI spend caps
|
|
1467
|
+
|
|
1468
|
+
Per-user, per-org and global caps on AI spend, per UTC day and month, in
|
|
1469
|
+
cost units (1 unit = one millionth of a US dollar, so spend stays an
|
|
1470
|
+
integer). It plugs into signet-ai's extractor as its `ledger`.
|
|
1471
|
+
|
|
1472
|
+
```ts
|
|
1473
|
+
import { aiSpendCaps, entitlementTables } from "@dapplelight/signet-db/columns/sqlite"
|
|
1474
|
+
import { createAiSpend, spendKey } from "@dapplelight/signet-db/ai-spend"
|
|
1475
|
+
|
|
1476
|
+
export const { usageCounters } = entitlementTables()
|
|
1477
|
+
export const spendCaps = aiSpendCaps()
|
|
1478
|
+
|
|
1479
|
+
const spend = createAiSpend(db, {
|
|
1480
|
+
tables: { usageCounters, aiSpendCaps: spendCaps },
|
|
1481
|
+
caps: { user: { day: 200_000 }, org: { month: 20_000_000 }, global: { month: 100_000_000 } },
|
|
1482
|
+
})
|
|
1483
|
+
const extractor = createExtractor({ providers, ledger: spend.ledger })
|
|
1484
|
+
await extractor.extract({ ...args, budget: { key: spendKey({ userId, orgId }) } })
|
|
1485
|
+
```
|
|
1486
|
+
|
|
1487
|
+
- The ledger checks every cap that applies before a call (refused as
|
|
1488
|
+
signet-ai's `AI_BUDGET_EXCEEDED`) and records the call's cost after, on
|
|
1489
|
+
the user's, org's and global counters. A plain string `key` is a user id.
|
|
1490
|
+
- `streamChat`, `chat` and `ground` have no ledger: check first (signet-server's
|
|
1491
|
+
`requireAiSpend`, or `spend.check(subject)`) and pass `onUsage: spend.onUsage`.
|
|
1492
|
+
Do not give an extractor both, or spend counts twice.
|
|
1493
|
+
- Caps an admin sets (`setCap`, or signet-server's `aiSpendAdminRoutes`) win
|
|
1494
|
+
over `caps`: a user's or org's own row, then the `*` row for its scope, then
|
|
1495
|
+
the option. `units: null` stores unlimited; `removeCap` goes back.
|
|
1496
|
+
- `check(subject, estimateUnits?)` refuses once a cap is reached, and says
|
|
1497
|
+
which (`scope`, `period`, `capUnits`, `usedUnits`, `resetsAt`).
|
|
1498
|
+
`usage(scope, id)` and `top("user" | "org", period)` feed an admin screen.
|
|
1499
|
+
- Fails closed: a database error refuses the call. Calls in flight are not
|
|
1500
|
+
reserved, so concurrent calls can overshoot by their own cost.
|
|
1501
|
+
|
|
1502
|
+
## Sequences
|
|
1503
|
+
|
|
1504
|
+
```ts
|
|
1505
|
+
import { sequences } from "@dapplelight/signet-db/columns/sqlite"
|
|
1506
|
+
import { nextSequence } from "@dapplelight/signet-db"
|
|
1507
|
+
|
|
1508
|
+
await nextSequence(db, schema.sequences, "invoice:INV:2026-27") // 1, 2, 3, ...
|
|
1509
|
+
```
|
|
1510
|
+
|
|
1511
|
+
One upsert per call, so concurrent callers never get the same value. A value
|
|
1512
|
+
taken by a request that then fails is skipped, not reused.
|
|
1513
|
+
|
|
1514
|
+
## Bulk import
|
|
1515
|
+
|
|
1516
|
+
`bulkInsert(ops, table, rows, { key })` from `./import` puts many rows in at
|
|
1517
|
+
once (a CSV import, another system's export) and reports per row instead of
|
|
1518
|
+
failing the whole file.
|
|
1519
|
+
|
|
1520
|
+
```ts
|
|
1521
|
+
import { bulkInsert } from "@dapplelight/signet-db/import"
|
|
1522
|
+
|
|
1523
|
+
app.post("/customers/import", async (c) => {
|
|
1524
|
+
const { rows } = await c.req.json()
|
|
1525
|
+
const ops = audited(scoped(db, { orgId: c.get("orgId") }))
|
|
1526
|
+
return c.json(await bulkInsert(ops, customers, rows, { key: "externalId" }))
|
|
1527
|
+
// { inserted: 41, skipped: 7, errors: [{ row: 3, field: "email", message: "Invalid email" }] }
|
|
1528
|
+
})
|
|
1529
|
+
```
|
|
1530
|
+
|
|
1531
|
+
- Each row is validated first, by default with `toZod(table, { mode: "insert" })`
|
|
1532
|
+
(keeping `key` when it is a managed column like `id`), or with your own
|
|
1533
|
+
`schema`. Invalid rows are reported by index and field; the rest go in.
|
|
1534
|
+
- `key` is a unique column. A row whose key is already in the table (soft
|
|
1535
|
+
deleted ones included), or earlier in the same import, is skipped, so
|
|
1536
|
+
running the same file twice inserts nothing new. Without a unique index on
|
|
1537
|
+
it, two imports running at once can both insert a key.
|
|
1538
|
+
- Rows go through the `ops` you pass, so the scope's owner and org columns,
|
|
1539
|
+
encryption, the audit trail and version history apply.
|
|
1540
|
+
- Chunks fit D1's 100 bound parameters by default (500 rows on Postgres);
|
|
1541
|
+
`chunkSize` overrides. A chunk the database refuses is retried row by row,
|
|
1542
|
+
and each refused row is reported with the database's message.
|
|
1543
|
+
- `row` in the report is the index into `rows`, which is what signet-ui's
|
|
1544
|
+
`CsvImport` expects back from `onImport`.
|
|
1545
|
+
|
|
1546
|
+
## Errors
|
|
1547
|
+
|
|
1548
|
+
Everything thrown is a `SignetDbError` with a stable `code` (`NO_CIPHER`,
|
|
1549
|
+
`CROSS_USER_WRITE`, `UNSCOPED_WRITE`, `CURRENCY_MISMATCH`, …) and a message
|
|
1550
|
+
that says how to fix it. `isSignetDbError(e, "CROSS_USER_WRITE")` narrows.
|
|
1551
|
+
|
|
1552
|
+
## Test
|
|
1553
|
+
|
|
1554
|
+
```sh
|
|
1555
|
+
bun run test # bun:sqlite, D1 (stand-in), Postgres (PGlite) always
|
|
1556
|
+
SIGNET_TEST_PG_URL=postgres://… bun run test # also a real Postgres server
|
|
1557
|
+
```
|