@ultimat3/cli 31.37.0 → 31.38.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/package.json +29 -29
- package/src/cmd-planned.ts +5 -28
- package/src/generate-sign-in-runtime.ts +70 -0
- package/src/generate-sign-in.ts +19 -6
- package/src/generate-write.ts +12 -0
- package/src/island-plugin-path.ts +35 -0
- package/src/island-realtime.ts +11 -8
- package/src/island-runtime.ts +4 -1
- package/src/new-shapes.ts +10 -1
- package/src/templates/shapes/agent-actions.ts +224 -0
- package/src/templates/shapes/agent-job.ts +171 -0
- package/src/templates/shapes/agent-model.ts +271 -0
- package/src/templates/shapes/agent-prompt.ts +254 -0
- package/src/templates/shapes/agent-scripted.ts +56 -0
- package/src/templates/shapes/agent.ts +138 -0
- package/src/templates/shapes/content-admin-es.ts +95 -0
- package/src/templates/shapes/content-pages.ts +221 -0
- package/src/templates/shapes/content-site.ts +343 -0
- package/src/templates/shapes/content.ts +133 -0
- package/src/templates/shapes/index.ts +10 -0
- package/src/templates/shapes/offline-e2e.ts +123 -0
- package/src/templates/shapes/offline-form.ts +334 -0
- package/src/templates/shapes/offline.ts +118 -0
- package/src/templates/shapes/realtime-mutator.ts +136 -0
- package/src/templates/shapes/realtime-nodes.ts +203 -0
- package/src/templates/shapes/realtime-slice.ts +166 -0
- package/src/templates/shapes/realtime.ts +162 -0
- package/src/templates/shapes/saas-billing-tests.ts +135 -0
- package/src/templates/shapes/saas-billing.ts +137 -0
- package/src/templates/shapes/saas-receiver.ts +136 -0
- package/src/templates/shapes/saas.ts +112 -0
- package/src/templates/sign-in-oidc.ts +2 -4
- package/src/templates/sign-in-runtime.ts +172 -0
- package/src/templates/sign-in-shared.ts +5 -36
- package/wiki/Building-Your-Own-Base.md +339 -0
- package/wiki/CLI-Reference.md +1 -14
- package/wiki/Caching-And-Invalidation.md +1 -1
- package/wiki/Entities-And-Migrations.md +2 -2
- package/wiki/Known-Gaps.md +8 -2
- package/wiki/MCP-And-AI.md +3 -3
- package/wiki/Money.md +1 -1
- package/wiki/Shapes.md +18 -9
- package/wiki/Troubleshooting.md +1 -1
- package/wiki/Upgrading.md +1 -1
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// `x new <name> --shape realtime`: multi-user live state across nodes. The default app — the live
|
|
2
|
+
// `postList`, the dashboard, `/admin` — plus the org's live room (a channel every member joins on
|
|
3
|
+
// whichever `sync` node it reached), a notifier that tells the room a post landed over the bus, and
|
|
4
|
+
// a rename every tab shows before the server answers (a mutator).
|
|
5
|
+
//
|
|
6
|
+
// Proved for two clients on two nodes over a real NATS (`realtime-nodes.ts`).
|
|
7
|
+
|
|
8
|
+
import { loadVersion } from '../../version-loader';
|
|
9
|
+
import type { NameSet } from '../naming';
|
|
10
|
+
import type { ShapeEdit, ShapeOverlay } from './overlay';
|
|
11
|
+
import { realtimeMutatorFiles } from './realtime-mutator';
|
|
12
|
+
import { realtimeNodeFiles } from './realtime-nodes';
|
|
13
|
+
import { realtimeSliceFiles } from './realtime-slice';
|
|
14
|
+
import { shapeLines } from './shared-edits';
|
|
15
|
+
|
|
16
|
+
const API = 'apps/web/api/index.ts';
|
|
17
|
+
const POLICY = 'apps/web/app/post/policy.ts';
|
|
18
|
+
const REPO = 'apps/web/app/post/repo.ts';
|
|
19
|
+
const CREATE = 'apps/web/app/post/actions/create-post.ts';
|
|
20
|
+
const CREATE_TEST = 'apps/web/app/post/actions/create-post.test.ts';
|
|
21
|
+
const CREATE_CONTRACT = 'apps/web/app/post/actions/create-post.contract.test.ts';
|
|
22
|
+
const QUEUE_ANCHOR =
|
|
23
|
+
"// One store per process: without this, one test's rows are the next test's fixtures.\n";
|
|
24
|
+
/** The queue `postCreated` lands in, for this file: a process-global port, put back at its end. */
|
|
25
|
+
const QUEUE_SWAP =
|
|
26
|
+
"// The queue createPost's enqueue lands in, swapped for this file and put back when it ends.\nbeforeAll(() => swapAdapter('jobs', memoryJobDriver()));\n\n";
|
|
27
|
+
const EXERCISE = 'apps/web/exercise.ts';
|
|
28
|
+
const ORG = "'00000000-0000-4000-8000-000000000002'";
|
|
29
|
+
|
|
30
|
+
const WRITE_RULE =
|
|
31
|
+
"/** Write compares the org the action's input names with the actor's — grant it apart from read. */\n";
|
|
32
|
+
|
|
33
|
+
const REPO_TAIL = ' return db.posts.insert(row);\n}\n';
|
|
34
|
+
|
|
35
|
+
const CREATE_IMPORT = "import { PostView, post } from '../entity';\n";
|
|
36
|
+
const CREATE_RETURN = ' return service.create({ ...input, orgId: orgOf(ctx.actor) });\n';
|
|
37
|
+
|
|
38
|
+
/** An exercise entry: an actor of the scaffold's org holding `permission`, and that org as input. */
|
|
39
|
+
const exerciseEntry = (name: string, permission: string): string => ` ${name}: {
|
|
40
|
+
actor: userActor({
|
|
41
|
+
id: 'member',
|
|
42
|
+
orgId: ${ORG},
|
|
43
|
+
permissions: ['${permission}'],
|
|
44
|
+
}),
|
|
45
|
+
input: (drawn) => ({ ...drawn, orgId: ${ORG} }),
|
|
46
|
+
},
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
const edits = (): readonly ShapeEdit[] => [
|
|
50
|
+
{
|
|
51
|
+
path: POLICY,
|
|
52
|
+
find: WRITE_RULE,
|
|
53
|
+
replace: `/**
|
|
54
|
+
* Joining the org's live room: the room is named by its \`orgId\` param, so the rule compares it with
|
|
55
|
+
* the actor's — a member of another org is refused the topic, never sent its events.
|
|
56
|
+
*/
|
|
57
|
+
export const canPostWatch = can<PostScope>(
|
|
58
|
+
'post:read',
|
|
59
|
+
({ actor, input }) => actor !== null && actor.orgId === input.orgId,
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
${WRITE_RULE}`,
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
path: REPO,
|
|
66
|
+
find: REPO_TAIL,
|
|
67
|
+
replace: `${REPO_TAIL}
|
|
68
|
+
/** One column of one row; the handle refuses a row outside the actor's org. */
|
|
69
|
+
export async function rename(id: string, title: string): Promise<Post> {
|
|
70
|
+
return db.posts.update(id, { title });
|
|
71
|
+
}
|
|
72
|
+
`,
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
path: CREATE,
|
|
76
|
+
find: CREATE_IMPORT,
|
|
77
|
+
replace: `${CREATE_IMPORT}import { postCreated } from '../jobs/post-created';\n`,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
path: CREATE,
|
|
81
|
+
find: CREATE_RETURN,
|
|
82
|
+
replace: ` const row = await service.create({ ...input, orgId: orgOf(ctx.actor) });
|
|
83
|
+
// Enqueued in this request's transaction: a rolled-back create tells the room nothing.
|
|
84
|
+
await postCreated.enqueue({ params: { id: row.id, orgId: row.orgId } });
|
|
85
|
+
return row;
|
|
86
|
+
`,
|
|
87
|
+
},
|
|
88
|
+
// createPost now enqueues, and a test process installs no queue: each suite that runs its
|
|
89
|
+
// handler swaps in the memory driver, as the job suite next door does.
|
|
90
|
+
{
|
|
91
|
+
path: CREATE_TEST,
|
|
92
|
+
find: "import { testActor } from '@ultimat3/policy';\nimport { afterEach, expect, unitTest } from '@ultimat3/testing';\n",
|
|
93
|
+
replace:
|
|
94
|
+
"import { memoryJobDriver } from '@ultimat3/jobs';\nimport { testActor } from '@ultimat3/policy';\nimport { afterEach, beforeAll, expect, swapAdapter, unitTest } from '@ultimat3/testing';\n",
|
|
95
|
+
},
|
|
96
|
+
{ path: CREATE_TEST, find: QUEUE_ANCHOR, replace: `${QUEUE_SWAP}${QUEUE_ANCHOR}` },
|
|
97
|
+
{
|
|
98
|
+
path: CREATE_CONTRACT,
|
|
99
|
+
find: "import { testActor } from '@ultimat3/policy';\nimport { contractTest, expect } from '@ultimat3/testing';\n",
|
|
100
|
+
replace:
|
|
101
|
+
"import { memoryJobDriver } from '@ultimat3/jobs';\nimport { testActor } from '@ultimat3/policy';\nimport { beforeAll, contractTest, expect, swapAdapter } from '@ultimat3/testing';\n",
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
path: CREATE_CONTRACT,
|
|
105
|
+
find: "const target = createPost.named('createPost');\n",
|
|
106
|
+
replace: `const target = createPost.named('createPost');\n\n${QUEUE_SWAP}`,
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
path: API,
|
|
110
|
+
find: "import * as createPost from '../app/post/actions/create-post';\n",
|
|
111
|
+
replace: `import * as createPost from '../app/post/actions/create-post';
|
|
112
|
+
import * as renamePost from '../app/post/actions/rename-post';
|
|
113
|
+
import * as postCreated from '../app/post/jobs/post-created';
|
|
114
|
+
`,
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
path: API,
|
|
118
|
+
find: "import * as postList from '../app/post/live/post-list';\n",
|
|
119
|
+
replace: `import * as postList from '../app/post/live/post-list';
|
|
120
|
+
import * as recentPosts from '../app/post/queries/recent-posts';
|
|
121
|
+
`,
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
path: API,
|
|
125
|
+
find: 'actions: [health, createPost, archivePost],',
|
|
126
|
+
replace: 'actions: [health, createPost, archivePost, renamePost],',
|
|
127
|
+
},
|
|
128
|
+
{ path: API, find: 'queries: [postList],', replace: 'queries: [postList, recentPosts],' },
|
|
129
|
+
{ path: API, find: 'jobs: [reindexPost],', replace: 'jobs: [reindexPost, postCreated],' },
|
|
130
|
+
{
|
|
131
|
+
path: EXERCISE,
|
|
132
|
+
find: ' },\n});\n',
|
|
133
|
+
replace: ` },\n${exerciseEntry('renamePost', 'post:write')}${exerciseEntry('recentPosts', 'post:read')}});\n`,
|
|
134
|
+
},
|
|
135
|
+
// The room and the notifier import both; an isolated install resolves only what the app declares.
|
|
136
|
+
{
|
|
137
|
+
path: 'package.json',
|
|
138
|
+
find: ' "@ultimat3/policy": ',
|
|
139
|
+
replace: ` "@ultimat3/notify": "^${loadVersion()}",\n "@ultimat3/policy": `,
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
path: 'package.json',
|
|
143
|
+
find: ' "@ultimat3/render": ',
|
|
144
|
+
replace: ` "@ultimat3/realtime": "^${loadVersion()}",\n "@ultimat3/render": `,
|
|
145
|
+
},
|
|
146
|
+
...shapeLines(
|
|
147
|
+
'realtime',
|
|
148
|
+
"multi-user live state across nodes — a notifier tells the org's room (`apps/web/app/post/channels.ts`) of each new post over the bus; two `sync` nodes in `apps/web/app/post/channels.live.test.ts`",
|
|
149
|
+
),
|
|
150
|
+
];
|
|
151
|
+
|
|
152
|
+
export const realtimeShape: ShapeOverlay = {
|
|
153
|
+
example: true,
|
|
154
|
+
drop: [],
|
|
155
|
+
dropKeys: [],
|
|
156
|
+
edits,
|
|
157
|
+
files: (app: NameSet) => [
|
|
158
|
+
...realtimeSliceFiles(app),
|
|
159
|
+
...realtimeMutatorFiles(app),
|
|
160
|
+
...realtimeNodeFiles(app),
|
|
161
|
+
],
|
|
162
|
+
};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// `--shape saas`'s billing tests: each billing file's unit suite, against the in-memory driver.
|
|
2
|
+
// Beside `saas-billing.ts`, which holds the sources they test.
|
|
3
|
+
|
|
4
|
+
import type { NameSet } from '../naming';
|
|
5
|
+
|
|
6
|
+
export const plansTest =
|
|
7
|
+
(): string => `// The plans as data: every price is Money, every allowance a whole count, and a feature answers
|
|
8
|
+
// by the plan it is asked about — never by who is asking.
|
|
9
|
+
import { isEnabled } from '@ultimat3/flags';
|
|
10
|
+
import { testActor } from '@ultimat3/policy';
|
|
11
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
12
|
+
import { DEFAULT_PLAN, PLAN_IDS, PLANS, postExport } from './plans';
|
|
13
|
+
|
|
14
|
+
const actor = testActor('member', { orgId: '00000000-0000-4000-8000-0000000000b1' }).actor;
|
|
15
|
+
|
|
16
|
+
unitTest('every plan has an integer price with its currency, and a whole allowance', () => {
|
|
17
|
+
for (const id of PLAN_IDS) {
|
|
18
|
+
expect(Number.isSafeInteger(PLANS[id].price.minor)).toBe(true);
|
|
19
|
+
expect(PLANS[id].price.currency).toMatch(/^[A-Z]{3}$/);
|
|
20
|
+
expect(Number.isSafeInteger(PLANS[id].postsPerDay)).toBe(true);
|
|
21
|
+
}
|
|
22
|
+
expect(PLAN_IDS).toContain(DEFAULT_PLAN);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
unitTest('a plan feature is on for the plans its flag names, and off for the rest', () => {
|
|
26
|
+
expect(isEnabled(postExport.key, actor, { plan: 'pro' })).toBe(true);
|
|
27
|
+
expect(isEnabled(postExport.key, actor, { plan: 'free' })).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
export const entityTest =
|
|
32
|
+
(): string => `// The subscription table's declaration: tenant-scoped, and one row per org.
|
|
33
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
34
|
+
import { subscription } from './entity';
|
|
35
|
+
|
|
36
|
+
unitTest('subscriptions is tenant-scoped by orgId', () => {
|
|
37
|
+
expect(subscription.$name).toBe('subscriptions');
|
|
38
|
+
expect(subscription.$tenantColumn).toBe('orgId');
|
|
39
|
+
expect(subscription.$describe().orgScoped).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
unitTest('a plan outside the declared ones does not parse', () => {
|
|
43
|
+
const row = {
|
|
44
|
+
id: '00000000-0000-4000-8000-000000000001',
|
|
45
|
+
orgId: '00000000-0000-4000-8000-0000000000b1',
|
|
46
|
+
plan: 'pro',
|
|
47
|
+
lastEventId: 'evt_1',
|
|
48
|
+
updatedAt: new Date(0),
|
|
49
|
+
};
|
|
50
|
+
expect(subscription.$parse(row).plan).toBe('pro');
|
|
51
|
+
expect(() => subscription.$parse({ ...row, plan: 'platinum' })).toThrow();
|
|
52
|
+
});
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
export const repoTest = (
|
|
56
|
+
app: NameSet,
|
|
57
|
+
): string => `// The subscriptions repo against the in-memory driver: one row per org, overwritten in place, and
|
|
58
|
+
// never read across orgs.
|
|
59
|
+
import { driver } from '@${app.kebab}/db';
|
|
60
|
+
import { ctxOf, runWithContext } from '@ultimat3/core';
|
|
61
|
+
import { testActor } from '@ultimat3/policy';
|
|
62
|
+
import { afterEach, expect, unitTest } from '@ultimat3/testing';
|
|
63
|
+
import * as repo from './repo';
|
|
64
|
+
|
|
65
|
+
const orgId = '00000000-0000-4000-8000-0000000000b1';
|
|
66
|
+
const otherOrg = '00000000-0000-4000-8000-0000000000b9';
|
|
67
|
+
|
|
68
|
+
const inOrg = <T>(org: string, run: () => Promise<T>): Promise<T> =>
|
|
69
|
+
runWithContext(ctxOf({ actor: testActor('billing', { orgId: org }).actor }), run);
|
|
70
|
+
|
|
71
|
+
afterEach(() => {
|
|
72
|
+
driver.reset?.();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
unitTest('no event yet is no subscription', async () => {
|
|
76
|
+
expect(await inOrg(orgId, repo.current)).toBeUndefined();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
unitTest('a second event overwrites the one row, never adds one', async () => {
|
|
80
|
+
await inOrg(orgId, () => repo.applyPlan({ orgId, plan: 'pro', lastEventId: 'evt_1' }));
|
|
81
|
+
await inOrg(orgId, () => repo.applyPlan({ orgId, plan: 'free', lastEventId: 'evt_2' }));
|
|
82
|
+
expect(await inOrg(orgId, repo.current)).toMatchObject({ plan: 'free', lastEventId: 'evt_2' });
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
unitTest("another org's subscription is never read", async () => {
|
|
86
|
+
await inOrg(orgId, () => repo.applyPlan({ orgId, plan: 'pro', lastEventId: 'evt_1' }));
|
|
87
|
+
expect(await inOrg(otherOrg, repo.current)).toBeUndefined();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
unitTest('a write for another org than the actor is refused', async () => {
|
|
91
|
+
const write = () => repo.applyPlan({ orgId: otherOrg, plan: 'pro', lastEventId: 'evt_1' });
|
|
92
|
+
const refused = await inOrg(orgId, write).catch((error: unknown) => error);
|
|
93
|
+
expect(refused).toBeUltimateError('X_TENANCY_ACTOR_MISMATCH');
|
|
94
|
+
});
|
|
95
|
+
`;
|
|
96
|
+
|
|
97
|
+
export const entitlementsTest = (
|
|
98
|
+
app: NameSet,
|
|
99
|
+
): string => `// Entitlements follow the plan row: no row is the default plan, and a row the payment webhook
|
|
100
|
+
// writes changes the features and the allowance the next call reads.
|
|
101
|
+
import { driver } from '@${app.kebab}/db';
|
|
102
|
+
import { ctxOf, runWithContext } from '@ultimat3/core';
|
|
103
|
+
import { testActor } from '@ultimat3/policy';
|
|
104
|
+
import { afterEach, expect, unitTest } from '@ultimat3/testing';
|
|
105
|
+
import { entitled, planOf, postMeter } from './entitlements';
|
|
106
|
+
import { PLANS, postExport } from './plans';
|
|
107
|
+
import * as repo from './repo';
|
|
108
|
+
|
|
109
|
+
const orgId = '00000000-0000-4000-8000-0000000000b1';
|
|
110
|
+
const member = testActor('member', { orgId }).actor;
|
|
111
|
+
const ctx = ctxOf({ actor: member });
|
|
112
|
+
const inOrg = <T>(run: () => Promise<T>): Promise<T> => runWithContext(ctx, run);
|
|
113
|
+
|
|
114
|
+
const allowance = (): Promise<number> => {
|
|
115
|
+
const { limit } = postMeter;
|
|
116
|
+
return inOrg(async () => (typeof limit === 'number' ? limit : limit({ ctx })));
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
afterEach(() => {
|
|
120
|
+
driver.reset?.();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
unitTest('an org no event has named is on the default plan, without its features', async () => {
|
|
124
|
+
expect(await inOrg(planOf)).toBe('free');
|
|
125
|
+
expect(await inOrg(() => entitled(postExport, member))).toBe(false);
|
|
126
|
+
expect(await allowance()).toBe(PLANS.free.postsPerDay);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
unitTest("an upgrade turns the plan's features on and raises the allowance", async () => {
|
|
130
|
+
await inOrg(() => repo.applyPlan({ orgId, plan: 'pro', lastEventId: 'evt_up' }));
|
|
131
|
+
expect(await inOrg(planOf)).toBe('pro');
|
|
132
|
+
expect(await inOrg(() => entitled(postExport, member))).toBe(true);
|
|
133
|
+
expect(await allowance()).toBe(PLANS.pro.postsPerDay);
|
|
134
|
+
});
|
|
135
|
+
`;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// `--shape saas`'s billing, as app code: the plans an org can be on (a price in Money and a daily
|
|
2
|
+
// allowance), each plan's features as permanent flags, the one subscription row per org, and the
|
|
3
|
+
// two reads the app asks — which plan, and is this feature in it. No provider, no package: wraps.
|
|
4
|
+
|
|
5
|
+
import type { GeneratedFile, NameSet } from '../naming';
|
|
6
|
+
import { entitlementsTest, entityTest, plansTest, repoTest } from './saas-billing-tests';
|
|
7
|
+
|
|
8
|
+
export const BILLING_DIR = 'apps/web/app/billing';
|
|
9
|
+
|
|
10
|
+
const plans =
|
|
11
|
+
(): string => `// The plans this app sells: a price and what each one includes. Example values — the app's to
|
|
12
|
+
// change. A price is Money (integer minor units and a currency), never a float. A plan's FEATURE is
|
|
13
|
+
// a permanent flag whose allow list is the plans that include it, so moving a feature between
|
|
14
|
+
// plans is one edit to its \`subjects\`, read by every check at once.
|
|
15
|
+
|
|
16
|
+
import { defineFlag } from '@ultimat3/flags';
|
|
17
|
+
import type { Money } from '@ultimat3/money';
|
|
18
|
+
|
|
19
|
+
export const PLAN_IDS = ['free', 'pro'] as const;
|
|
20
|
+
|
|
21
|
+
export type PlanId = (typeof PLAN_IDS)[number];
|
|
22
|
+
|
|
23
|
+
export interface Plan {
|
|
24
|
+
readonly price: Money;
|
|
25
|
+
/** Posts an org may create per UTC day: \`postMeter\` (\`entitlements.ts\`) draws on it. */
|
|
26
|
+
readonly postsPerDay: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const PLANS: { readonly [P in PlanId]: Plan } = {
|
|
30
|
+
free: { price: { minor: 0, currency: 'USD' }, postsPerDay: 100 },
|
|
31
|
+
pro: { price: { minor: 2900, currency: 'USD' }, postsPerDay: 10_000 },
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** An org no payment event has named yet is on this plan. */
|
|
35
|
+
export const DEFAULT_PLAN: PlanId = 'free';
|
|
36
|
+
|
|
37
|
+
/** A feature only a paying org has. Its \`subjects.plan\` IS the list of plans that include it. */
|
|
38
|
+
export const postExport = defineFlag({
|
|
39
|
+
kind: 'permanent',
|
|
40
|
+
key: 'plan.post-export',
|
|
41
|
+
description: 'export every post of the org — a pro plan feature',
|
|
42
|
+
targeting: { default: false, subjects: { plan: ['pro'] } },
|
|
43
|
+
});
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
const entity =
|
|
47
|
+
(): string => `// The subscription: which plan an org is on, and the payment event that put it there. One row per
|
|
48
|
+
// org — \`orgId\` is unique, which is also what a webhook's upsert lands on.
|
|
49
|
+
|
|
50
|
+
import { entity, enumerated, text, timestamp, uuid } from '@ultimat3/entity';
|
|
51
|
+
import { PLAN_IDS } from './plans';
|
|
52
|
+
|
|
53
|
+
export const subscription = entity('subscriptions', {
|
|
54
|
+
// Tenant-scoped like every app table: a read runs under the actor's org, and a write naming
|
|
55
|
+
// another org is refused (X_TENANCY_ACTOR_MISMATCH).
|
|
56
|
+
tenant: 'orgId',
|
|
57
|
+
columns: {
|
|
58
|
+
id: uuid().primaryKey(),
|
|
59
|
+
orgId: uuid().unique(),
|
|
60
|
+
plan: enumerated(PLAN_IDS),
|
|
61
|
+
/** The provider's event id that last wrote this row: what a support question starts from. */
|
|
62
|
+
lastEventId: text({ max: 256 }),
|
|
63
|
+
updatedAt: timestamp().defaultNow().onUpdateNow(),
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
export type Subscription = typeof subscription.$row;
|
|
68
|
+
`;
|
|
69
|
+
|
|
70
|
+
const repo = (
|
|
71
|
+
app: NameSet,
|
|
72
|
+
): string => `// The only module that touches the subscriptions table, through the typed handle: it scopes every
|
|
73
|
+
// read to the actor's org, so no function here takes one to read by.
|
|
74
|
+
|
|
75
|
+
import { db } from '@${app.kebab}/db';
|
|
76
|
+
import type { Insertable } from '@ultimat3/entity';
|
|
77
|
+
import type { Subscription, subscription } from './entity';
|
|
78
|
+
|
|
79
|
+
/** The actor's org's subscription; none until a payment event names the org. */
|
|
80
|
+
export async function current(): Promise<Subscription | undefined> {
|
|
81
|
+
return (await db.subscriptions.limit(1).one()) ?? undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The org's plan, as a verified payment event states it — insert or overwrite, one statement. A
|
|
86
|
+
* redelivered event writes the same row again, so at-least-once delivery needs no seen-set here.
|
|
87
|
+
*/
|
|
88
|
+
export async function applyPlan(row: Insertable<typeof subscription.$columns>): Promise<void> {
|
|
89
|
+
await db.subscriptions.upsertAll([row], { onConflict: ['orgId'] });
|
|
90
|
+
}
|
|
91
|
+
`;
|
|
92
|
+
|
|
93
|
+
const entitlements =
|
|
94
|
+
(): string => `// What an org may do, read off its plan: the plan itself, a feature check over the plan's flags,
|
|
95
|
+
// and the meter that holds an org to its plan's daily allowance. Every answer is the actor's org's.
|
|
96
|
+
|
|
97
|
+
import type { ActionMeter } from '@ultimat3/action';
|
|
98
|
+
import type { Actor } from '@ultimat3/core';
|
|
99
|
+
import { type Flag, isEnabled } from '@ultimat3/flags';
|
|
100
|
+
import { DEFAULT_PLAN, PLANS, type PlanId } from './plans';
|
|
101
|
+
import * as repo from './repo';
|
|
102
|
+
|
|
103
|
+
/** The actor's org's plan: the last payment event's, or the default before any. */
|
|
104
|
+
export async function planOf(): Promise<PlanId> {
|
|
105
|
+
return (await repo.current())?.plan ?? DEFAULT_PLAN;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Whether the actor's org's plan includes \`feature\`. Gate an action with it in \`handle\`:
|
|
110
|
+
* \`if (!(await entitled(postExport, ctx.actor))) throw …\` — a policy is synchronous, a plan is a row.
|
|
111
|
+
*/
|
|
112
|
+
export async function entitled(feature: Flag, actor: Actor): Promise<boolean> {
|
|
113
|
+
return isEnabled(feature.key, actor, { plan: await planOf() });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Posts per org per UTC day, as many as the org's plan allows: \`createPost\` declares it, and the
|
|
118
|
+
* call past the allowance is X_METER_EXCEEDED (429) on every surface.
|
|
119
|
+
*/
|
|
120
|
+
export const postMeter: ActionMeter = {
|
|
121
|
+
name: 'posts',
|
|
122
|
+
period: 'day',
|
|
123
|
+
limit: async () => PLANS[await planOf()].postsPerDay,
|
|
124
|
+
};
|
|
125
|
+
`;
|
|
126
|
+
|
|
127
|
+
/** `apps/web/app/billing/`: plans, the subscription table and its repo, entitlements, each tested. */
|
|
128
|
+
export const billingFiles = (app: NameSet): readonly GeneratedFile[] => [
|
|
129
|
+
{ path: `${BILLING_DIR}/plans.ts`, contents: plans() },
|
|
130
|
+
{ path: `${BILLING_DIR}/plans.test.ts`, contents: plansTest() },
|
|
131
|
+
{ path: `${BILLING_DIR}/entity.ts`, contents: entity() },
|
|
132
|
+
{ path: `${BILLING_DIR}/entity.test.ts`, contents: entityTest() },
|
|
133
|
+
{ path: `${BILLING_DIR}/repo.ts`, contents: repo(app) },
|
|
134
|
+
{ path: `${BILLING_DIR}/repo.test.ts`, contents: repoTest(app) },
|
|
135
|
+
{ path: `${BILLING_DIR}/entitlements.ts`, contents: entitlements() },
|
|
136
|
+
{ path: `${BILLING_DIR}/entitlements.test.ts`, contents: entitlementsTest(app) },
|
|
137
|
+
];
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// `--shape saas`'s payment webhook: `x g webhook-receiver billing-events --feature billing`'s own
|
|
2
|
+
// output — the hmac, the replay window, the event read out of the signed bytes — called here, never
|
|
3
|
+
// re-spelled, then edited at anchors that must each occur once: the event names an org and a plan,
|
|
4
|
+
// the run acts as that org, and its body writes the org's subscription. A moved anchor fails here.
|
|
5
|
+
|
|
6
|
+
import type { ExerciseEntry } from '../../exercise-entry-edit';
|
|
7
|
+
import { webhookReceiverFiles } from '../generate-webhook-receiver';
|
|
8
|
+
import type { GeneratedFile } from '../naming';
|
|
9
|
+
import { applyEdit, type ShapeEdit } from './overlay';
|
|
10
|
+
import { BILLING_DIR } from './saas-billing';
|
|
11
|
+
|
|
12
|
+
export const RECEIVER_NAME = 'billing-events';
|
|
13
|
+
export const RECEIVER_PATH = `${BILLING_DIR}/jobs/${RECEIVER_NAME}.ts`;
|
|
14
|
+
const TEST_PATH = RECEIVER_PATH.replace(/\.ts$/, '.test.ts');
|
|
15
|
+
|
|
16
|
+
const sourceEdits: readonly Omit<ShapeEdit, 'path'>[] = [
|
|
17
|
+
// The generator's comment names one vendor's canonical form; a shape names none (shapes.test.ts).
|
|
18
|
+
{ find: "(Stripe's `v1`\n * canonical form)", replace: '(a common\n * canonical form)' },
|
|
19
|
+
{
|
|
20
|
+
find: "import { t, webhookReceiver } from '@ultimat3/jobs';\n",
|
|
21
|
+
replace:
|
|
22
|
+
"import { t, webhookReceiver } from '@ultimat3/jobs';\nimport { PLAN_IDS } from '../plans';\nimport * as repo from '../repo';\n",
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
find: "/** The part of the vendor's payload this app reads. The app's schema, never the framework's. */\nconst BillingEventsEvent = t.object({ id: t.string, type: t.string });",
|
|
26
|
+
replace: [
|
|
27
|
+
'/**',
|
|
28
|
+
" * The part of the vendor's payload this app reads. The app's schema, never the framework's. It",
|
|
29
|
+
' * states the plan the org is now on — `free` once a subscription ends — never a delta, so an',
|
|
30
|
+
' * event delivered out of order still leaves a plan the provider sent.',
|
|
31
|
+
' */',
|
|
32
|
+
'const BillingEventsEvent = t.object({',
|
|
33
|
+
' id: t.string,',
|
|
34
|
+
' type: t.string,',
|
|
35
|
+
' orgId: t.uuid,',
|
|
36
|
+
' plan: t.enum(PLAN_IDS),',
|
|
37
|
+
'});',
|
|
38
|
+
].join('\n'),
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
find: "'does not carry a string id and type'",
|
|
42
|
+
replace: "'does not carry an id, a type, an org id and a known plan'",
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
find: " // The vendor's account is the app's, not an org's. A per-org receiver reads the org out of the\n // verified event instead: `tenant: (event) => event.orgId`.\n tenant: 'none',",
|
|
46
|
+
replace:
|
|
47
|
+
' // Per org: the run acts as the org the SIGNED event names, so its write is that org’s and no other.\n tenant: (event) => event.orgId,',
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
find: 'return { eventId: event.id, topic: event.type, payload: event };',
|
|
51
|
+
replace: 'return { eventId: event.id, orgId: event.orgId, topic: event.type, payload: event };',
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
find: ' // At least once per event id: a redelivery inside the window after this settles runs again, so a\n // write here is an upsert keyed by `eventId`, never an insert.\n handle: async ({ eventId, payload }) => ({ eventId, type: payload.type }),',
|
|
55
|
+
replace:
|
|
56
|
+
" // At least once per event id: the write is an upsert on the org's one row, so a redelivery\n // writes the same plan again. The entitlements read it on the org's next call.\n handle: async ({ eventId, orgId, payload, step }) => {\n // The run's tenant — `verify` read it out of the signed event, so it IS `payload.orgId`.\n const org = orgId ?? payload.orgId;\n // A step, so a run resumed after a crash does not write the row a second time.\n await step.run('apply-plan', () =>\n repo.applyPlan({ orgId: org, plan: payload.plan, lastEventId: eventId }),\n );\n return { eventId, plan: payload.plan };\n },",
|
|
57
|
+
},
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
const testEdits: readonly Omit<ShapeEdit, 'path'>[] = [
|
|
61
|
+
{
|
|
62
|
+
find: "import { ambientClock, hmac } from '@ultimat3/core';",
|
|
63
|
+
replace: "import { ambientClock, ctxOf, hmac, runWithContext } from '@ultimat3/core';",
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
find: "import { expect, unitTest } from '@ultimat3/testing';\n",
|
|
67
|
+
replace:
|
|
68
|
+
"import { testActor } from '@ultimat3/policy';\nimport { expect, unitTest } from '@ultimat3/testing';\nimport { planOf } from '../entitlements';\n",
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
find: "const SECRET_ENV = 'BILLING_EVENTS_WEBHOOK_SECRET';\n",
|
|
72
|
+
replace: `const SECRET_ENV = 'BILLING_EVENTS_WEBHOOK_SECRET';
|
|
73
|
+
const ORG = '00000000-0000-4000-8000-0000000000b1';
|
|
74
|
+
|
|
75
|
+
/** The org's plan, read as one of its members reads it. */
|
|
76
|
+
const planOfOrg = (): Promise<string> =>
|
|
77
|
+
runWithContext(ctxOf({ actor: testActor('member', { orgId: ORG }).actor }), planOf);
|
|
78
|
+
`,
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
find: `const body = '{"id":"evt_unit","type":"thing.happened"}';`,
|
|
82
|
+
replace: `const body = JSON.stringify({ id: 'evt_unit', type: 'plan.changed', orgId: ORG, plan: 'pro' });`,
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
find: " ['completed', { eventId: 'evt_unit', type: 'thing.happened' }],\n ]);\n",
|
|
86
|
+
replace:
|
|
87
|
+
" ['completed', { eventId: 'evt_unit', plan: 'pro' }],\n ]);\n // The entitlement moved: the org the signed event names is on the plan it names.\n expect(await planOfOrg()).toBe('pro');\n",
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
find: "unitTest('a signed event is queued, then handled from its verified payload', ({ runJobs }) =>\n withSecret(SECRET, async () => {\n",
|
|
91
|
+
replace:
|
|
92
|
+
"unitTest('a signed event is queued, then moves the org to its plan', ({ runJobs }) =>\n withSecret(SECRET, async () => {\n expect(await planOfOrg()).toBe('free');\n",
|
|
93
|
+
},
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
/** The org every scaffold's `apps/web/exercise.ts` acts in. */
|
|
97
|
+
const DEMO_ORG = '00000000-0000-4000-8000-000000000002';
|
|
98
|
+
|
|
99
|
+
/** What the verified route would queue: `x exercise` cannot sign an event. */
|
|
100
|
+
const exercise: ExerciseEntry = {
|
|
101
|
+
name: RECEIVER_NAME,
|
|
102
|
+
value: [
|
|
103
|
+
'{',
|
|
104
|
+
` actor: userActor({ id: 'billing', orgId: '${DEMO_ORG}' }),`,
|
|
105
|
+
" // What the verified route queues. The top-level orgId is the run's tenant, bound per draw.",
|
|
106
|
+
' input: () => ({',
|
|
107
|
+
" eventId: 'evt_exercise',",
|
|
108
|
+
` orgId: '${DEMO_ORG}',`,
|
|
109
|
+
" topic: 'plan.changed',",
|
|
110
|
+
' payload: {',
|
|
111
|
+
" id: 'evt_exercise',",
|
|
112
|
+
" type: 'plan.changed',",
|
|
113
|
+
` orgId: '${DEMO_ORG}',`,
|
|
114
|
+
" plan: 'pro',",
|
|
115
|
+
' },',
|
|
116
|
+
' }),',
|
|
117
|
+
'}',
|
|
118
|
+
].join('\n'),
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const edited = (file: GeneratedFile, edits: readonly Omit<ShapeEdit, 'path'>[]): string =>
|
|
122
|
+
edits.reduce(
|
|
123
|
+
(text, edit) => applyEdit(text, { ...edit, path: file.path }),
|
|
124
|
+
typeof file.contents === 'string' ? file.contents : '',
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
/** The generator's two files, edited into the payment receiver this shape needs. */
|
|
128
|
+
export function billingReceiverFiles(): readonly GeneratedFile[] {
|
|
129
|
+
const target = { surfaceDir: 'apps/web/app', feature: 'billing' };
|
|
130
|
+
return webhookReceiverFiles(RECEIVER_NAME, target).map((file): GeneratedFile => {
|
|
131
|
+
if (file.path === RECEIVER_PATH)
|
|
132
|
+
return { path: file.path, contents: edited(file, sourceEdits), exercise };
|
|
133
|
+
if (file.path === TEST_PATH) return { path: file.path, contents: edited(file, testEdits) };
|
|
134
|
+
return file;
|
|
135
|
+
});
|
|
136
|
+
}
|