@ultimat3/cli 31.37.0 → 31.38.1
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,118 @@
|
|
|
1
|
+
// `x new <name> --shape offline`: an installable app that keeps working with no network. The
|
|
2
|
+
// default app — its PWA, offline fallback and `post` slice — with the post form written through
|
|
3
|
+
// realtime's outbox, `createPost` safe to replay, both proven offline in a real browser, and the
|
|
4
|
+
// README's recipe for a phone on the LAN (`x dev --host <address> --tls`).
|
|
5
|
+
|
|
6
|
+
import { loadVersion } from '../../version-loader';
|
|
7
|
+
import { catalogJson } from '../catalog-json';
|
|
8
|
+
import { catalogPath } from '../locales';
|
|
9
|
+
import type { GeneratedFile, NameSet } from '../naming';
|
|
10
|
+
import { FALLBACK_E2E, offlineE2eFiles, WRITE_E2E } from './offline-e2e';
|
|
11
|
+
import { offlineFormFiles } from './offline-form';
|
|
12
|
+
import type { ShapeEdit, ShapeOverlay } from './overlay';
|
|
13
|
+
import { shapeLines } from './shared-edits';
|
|
14
|
+
|
|
15
|
+
const PAGE = 'apps/web/app/posts/page.tsx';
|
|
16
|
+
const CREATE = 'apps/web/app/post/actions/create-post.ts';
|
|
17
|
+
const README_LAYOUT = '## 🗺 Layout\n';
|
|
18
|
+
|
|
19
|
+
const BUDGET = ` // measured: 64,167 B (\`x build --target static\`, Bun 1.4.4) — the form island and the
|
|
20
|
+
// \`visible\` runtime. why: the form is Solid, @ultimat3/ui's Form/Input/Button and the transport.
|
|
21
|
+
// A raise states its own measured bytes and why here, in the same diff (\`X_BUDGET_EXCEEDED\`).
|
|
22
|
+
budget: { js: '66kb' },`;
|
|
23
|
+
|
|
24
|
+
const OFFLINE_BUDGET = ` // measured: 158,171 B (\`bunx x verify --only budgets\`, Bun 1.4.4, 2026-11-16) — the page boot
|
|
25
|
+
// 84,606 + the form island 72,293 + inline scripts 1,272. why: the form writes through
|
|
26
|
+
// \`@ultimat3/realtime\`'s outbox, so this page loads the page boot (the record store and the
|
|
27
|
+
// IndexedDB outbox that replays a write made offline) beside the form; the default form's
|
|
28
|
+
// transport-only island was 64,167 B. A raise states its own measured bytes and why here, in the
|
|
29
|
+
// same diff (\`X_BUDGET_EXCEEDED\`).
|
|
30
|
+
budget: { js: '155kb' },`;
|
|
31
|
+
|
|
32
|
+
const lan = (): string => `## 📶 Offline, and on your LAN
|
|
33
|
+
|
|
34
|
+
A service worker registers only on a secure origin — \`localhost\`, or https — so a phone on your
|
|
35
|
+
network needs TLS to install this app. Bind your machine's LAN address and serve it over https:
|
|
36
|
+
|
|
37
|
+
\`\`\`sh
|
|
38
|
+
LAN_IP=$(ipconfig getifaddr en0 2>/dev/null || hostname -I | cut -d' ' -f1)
|
|
39
|
+
bunx x dev --host "$LAN_IP" --tls
|
|
40
|
+
\`\`\`
|
|
41
|
+
|
|
42
|
+
\`--tls\` writes a self-signed certificate for \`localhost\` and that address to \`.x/tls/cert.pem\`.
|
|
43
|
+
Trust it once on the device (install it as a CA profile), open \`https://$LAN_IP:3000\`, and
|
|
44
|
+
install the app from the browser menu. Then cut the network:
|
|
45
|
+
|
|
46
|
+
| Offline | What answers |
|
|
47
|
+
|---|---|
|
|
48
|
+
| a page the worker cached, or \`/offline\` | the cache — \`offline:\` on each route decides (\`apps/web/site/offline/page.tsx\` is \`precache\`) |
|
|
49
|
+
| a personal page (\`/posts\`) | the offline document: a page rendered for someone is never cached |
|
|
50
|
+
| a new post | the outbox — \`apps/web/app/post/post-form.island.tsx\` writes through \`useMutation\`, and a write the network refuses waits in IndexedDB, then replays on reconnect under its idempotency key (\`createPost\` is \`idempotent: true\`) |
|
|
51
|
+
|
|
52
|
+
\`${FALLBACK_E2E}\` and \`${WRITE_E2E}\` prove both with the network cut, on every \`bun run verify\`.
|
|
53
|
+
The sync socket stays plaintext under \`--tls\`, so over a LAN origin live updates wait for a reload;
|
|
54
|
+
reads and writes are https.
|
|
55
|
+
|
|
56
|
+
`;
|
|
57
|
+
|
|
58
|
+
const edits = (): readonly ShapeEdit[] => [
|
|
59
|
+
// The form's path is \`useMutation\`'s to derive now: no endpoint prop, no \`derivePath\`.
|
|
60
|
+
{ path: PAGE, find: "import { derivePath } from '@ultimat3/action';\n", replace: '' },
|
|
61
|
+
{
|
|
62
|
+
path: PAGE,
|
|
63
|
+
find: " props: ['endpoint', 'locale', 'currency', 'labels'],",
|
|
64
|
+
replace: " props: ['locale', 'currency', 'labels'],",
|
|
65
|
+
},
|
|
66
|
+
{ path: PAGE, find: " endpoint={derivePath('createPost').path}\n", replace: '' },
|
|
67
|
+
{
|
|
68
|
+
path: PAGE,
|
|
69
|
+
find: " retry: t('app.post.retry'),\n",
|
|
70
|
+
replace:
|
|
71
|
+
" queued: t('app.post.queued'),\n retry: t('app.post.retry'),\n",
|
|
72
|
+
},
|
|
73
|
+
{ path: PAGE, find: BUDGET, replace: OFFLINE_BUDGET },
|
|
74
|
+
{
|
|
75
|
+
path: 'apps/web/app/posts/page.test.ts',
|
|
76
|
+
find: " expect(page.config.budget.js).toBe('66kb');",
|
|
77
|
+
replace: " expect(page.config.budget.js).toBe('155kb');",
|
|
78
|
+
},
|
|
79
|
+
// A write replayed from the outbox may already have landed: the key answers it, never twice.
|
|
80
|
+
{
|
|
81
|
+
path: CREATE,
|
|
82
|
+
find: ' cache: { invalidates: [postTag] },\n',
|
|
83
|
+
replace:
|
|
84
|
+
' cache: { invalidates: [postTag] },\n // The outbox replays a write whose answer was lost under the SAME Idempotency-Key: this is what\n // makes that replay answer the first result instead of inserting a second post.\n idempotent: true,\n',
|
|
85
|
+
},
|
|
86
|
+
// The form imports `@ultimat3/realtime`; an isolated install resolves only what the app declares.
|
|
87
|
+
{
|
|
88
|
+
path: 'package.json',
|
|
89
|
+
find: ' "@ultimat3/render": ',
|
|
90
|
+
replace: ` "@ultimat3/realtime": "^${loadVersion()}",\n "@ultimat3/render": `,
|
|
91
|
+
},
|
|
92
|
+
{ path: 'README.md', find: README_LAYOUT, replace: `${lan()}${README_LAYOUT}` },
|
|
93
|
+
...shapeLines(
|
|
94
|
+
'offline',
|
|
95
|
+
'an installable app that works with no network — the `post` form queues a write offline (`apps/web/app/post/post-form.island.tsx`) and replays it on reconnect; README.md says how to open it from a phone on your LAN',
|
|
96
|
+
),
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
/** The one key the queued state reads, merged into the catalog the base wrote. */
|
|
100
|
+
const catalog = (): GeneratedFile => ({
|
|
101
|
+
path: catalogPath('en'),
|
|
102
|
+
merge: 'json',
|
|
103
|
+
contents: catalogJson({
|
|
104
|
+
'app.post.queued': 'Saved on this device. It will send when you are back online.',
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
export const offlineShape: ShapeOverlay = {
|
|
109
|
+
example: true,
|
|
110
|
+
drop: [],
|
|
111
|
+
dropKeys: [],
|
|
112
|
+
edits,
|
|
113
|
+
files: (app: NameSet): readonly GeneratedFile[] => [
|
|
114
|
+
...offlineFormFiles(),
|
|
115
|
+
...offlineE2eFiles(app),
|
|
116
|
+
catalog(),
|
|
117
|
+
],
|
|
118
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// `--shape realtime`'s mutator: a rename this tab shows before the server answers, and the write
|
|
2
|
+
// every other tab's live list then patches in. Its unit and contract tests beside it.
|
|
3
|
+
|
|
4
|
+
import type { GeneratedFile, NameSet } from '../naming';
|
|
5
|
+
|
|
6
|
+
const ACTIONS = 'apps/web/app/post/actions';
|
|
7
|
+
|
|
8
|
+
const renamePost =
|
|
9
|
+
(): string => `// renamePost: a rename this tab shows before the server answers, and every other tab shows once it
|
|
10
|
+
// lands. \`local\` writes the twin into this tab's store at once; \`server\` is the write, and it is
|
|
11
|
+
// authoritative: the committed row reaches every \`postList\` subscriber as a patch, on every node.
|
|
12
|
+
|
|
13
|
+
import { mutator, t } from '@ultimat3/action';
|
|
14
|
+
import { PostNotFoundError } from '../errors';
|
|
15
|
+
import { canPostWrite, postTag } from '../policy';
|
|
16
|
+
import * as repo from '../repo';
|
|
17
|
+
|
|
18
|
+
/** The client store's row: the entity's own table, so the twin and the server row share a key. */
|
|
19
|
+
interface LocalPost {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly title: string;
|
|
22
|
+
readonly pending: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const renamePost = mutator({
|
|
26
|
+
// \`orgId\` because the policy decides on it; 200 is the entity's own bound on a title.
|
|
27
|
+
input: t.object({ id: t.uuid, orgId: t.uuid, title: t.string.min(1).max(200) }),
|
|
28
|
+
output: t.object({ id: t.uuid, title: t.string }),
|
|
29
|
+
policy: canPostWrite,
|
|
30
|
+
cache: { invalidates: [postTag] },
|
|
31
|
+
// Required on a mutator (X_MUTATOR_NOT_IDEMPOTENT): the client replays this write under one
|
|
32
|
+
// Idempotency-Key after a dropped response, and the replay answers the first result.
|
|
33
|
+
idempotent: true,
|
|
34
|
+
// The refusals a caller may branch on: add each code the handler comes to throw.
|
|
35
|
+
errors: [PostNotFoundError.code],
|
|
36
|
+
local(tx, input) {
|
|
37
|
+
tx.table<LocalPost>('posts').update(input.id, { title: input.title, pending: true });
|
|
38
|
+
},
|
|
39
|
+
async server(_ctx, input) {
|
|
40
|
+
// Another org's id reads nothing — the handle scopes the read — so it is "not found" too.
|
|
41
|
+
if ((await repo.byId(input.id)) === undefined) throw new PostNotFoundError({ id: input.id });
|
|
42
|
+
const row = await repo.rename(input.id, input.title);
|
|
43
|
+
return { id: row.id, title: row.title };
|
|
44
|
+
},
|
|
45
|
+
conflict: 'server-wins',
|
|
46
|
+
});
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
const renamePostTest = (
|
|
50
|
+
app: NameSet,
|
|
51
|
+
): string => `// renamePost: the twin this tab shows at once, and the write the server makes — in process, so
|
|
52
|
+
// both belong to the \`unit\` step. The contract projections are next door.
|
|
53
|
+
import { driver } from '@${app.kebab}/db';
|
|
54
|
+
import { ctxOf, runWithContext } from '@ultimat3/core';
|
|
55
|
+
import { testActor } from '@ultimat3/policy';
|
|
56
|
+
import { afterEach, expect, memoryLocalTx, unitTest } from '@ultimat3/testing';
|
|
57
|
+
import * as repo from '../repo';
|
|
58
|
+
import { renamePost } from './rename-post';
|
|
59
|
+
|
|
60
|
+
const id = '00000000-0000-4000-8000-000000000001';
|
|
61
|
+
const orgId = '00000000-0000-4000-8000-000000000002';
|
|
62
|
+
const otherOrg = '00000000-0000-4000-8000-000000000009';
|
|
63
|
+
const target = renamePost.named('renamePost');
|
|
64
|
+
const writer = testActor('writer', { orgId, permissions: ['post:write'] }).actor;
|
|
65
|
+
|
|
66
|
+
const store = (owner: string, title: string) => {
|
|
67
|
+
const draft = { orgId: owner, title, price: { minor: 0, currency: 'USD' } };
|
|
68
|
+
const actor = testActor('author', { orgId: owner }).actor;
|
|
69
|
+
return runWithContext(ctxOf({ actor }), () => repo.insert(draft));
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
afterEach(() => {
|
|
73
|
+
driver.reset?.();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
unitTest('the twin is marked pending at once, and a replay lands in the same place', () => {
|
|
77
|
+
const local = memoryLocalTx({ posts: { [id]: { id, title: 'before', pending: false } } });
|
|
78
|
+
target.local(local.tx, { id, orgId, title: 'after' });
|
|
79
|
+
const once = local.rows('posts');
|
|
80
|
+
expect(once).toEqual({ [id]: { id, title: 'after', pending: true } });
|
|
81
|
+
target.local(local.tx, { id, orgId, title: 'after' });
|
|
82
|
+
expect(local.rows('posts')).toEqual(once);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
unitTest('the server writes the new title, and a read sees it', async () => {
|
|
86
|
+
const row = await store(orgId, 'before');
|
|
87
|
+
const answer = await target.as(writer, { id: row.id, orgId, title: 'after' });
|
|
88
|
+
expect(answer).toEqual({ id: row.id, title: 'after' });
|
|
89
|
+
const read = await runWithContext(ctxOf({ actor: writer }), () => repo.byId(row.id));
|
|
90
|
+
expect(read?.title).toBe('after');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
unitTest('an id nothing holds, or another org’s, is not found and nothing is written', async () => {
|
|
94
|
+
const theirs = await store(otherOrg, 'theirs');
|
|
95
|
+
const refused = await target
|
|
96
|
+
.as(writer, { id: theirs.id, orgId, title: 'mine now' })
|
|
97
|
+
.catch((error: unknown) => error);
|
|
98
|
+
expect(refused).toBeUltimateError('X_POST_NOT_FOUND');
|
|
99
|
+
const outsider = testActor('outsider', { orgId: otherOrg }).actor;
|
|
100
|
+
const kept = await runWithContext(ctxOf({ actor: outsider }), () => repo.byId(theirs.id));
|
|
101
|
+
expect(kept?.title).toBe('theirs');
|
|
102
|
+
});
|
|
103
|
+
`;
|
|
104
|
+
|
|
105
|
+
const renamePostContract =
|
|
106
|
+
(): string => `// renamePost: the contract every action owes — a mutator's server half is one — and the
|
|
107
|
+
// caller in another org it refuses before the handler runs.
|
|
108
|
+
import { testActor } from '@ultimat3/policy';
|
|
109
|
+
import { contractTest, expect } from '@ultimat3/testing';
|
|
110
|
+
import { exercise } from '../../../exercise';
|
|
111
|
+
import { renamePost } from './rename-post';
|
|
112
|
+
|
|
113
|
+
const target = renamePost.named('renamePost');
|
|
114
|
+
const orgId = '00000000-0000-4000-8000-000000000002';
|
|
115
|
+
const input = { id: '00000000-0000-4000-8000-000000000001', orgId, title: 'renamed' };
|
|
116
|
+
|
|
117
|
+
contractTest('renamePost passes the action contract', async () => {
|
|
118
|
+
for (const contract of target.contract({ exercise })) await contract.run();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
contractTest('renamePost is refused to a writer of another org', async () => {
|
|
122
|
+
const outsider = testActor('outsider', {
|
|
123
|
+
orgId: '00000000-0000-4000-8000-000000000009',
|
|
124
|
+
permissions: ['post:write'],
|
|
125
|
+
}).actor;
|
|
126
|
+
const refused = await target.as(outsider, input).catch((error: unknown) => error);
|
|
127
|
+
expect(refused).toBeUltimateError('X_FORBIDDEN');
|
|
128
|
+
});
|
|
129
|
+
`;
|
|
130
|
+
|
|
131
|
+
/** The mutator and its two suites. */
|
|
132
|
+
export const realtimeMutatorFiles = (app: NameSet): readonly GeneratedFile[] => [
|
|
133
|
+
{ path: `${ACTIONS}/rename-post.ts`, contents: renamePost() },
|
|
134
|
+
{ path: `${ACTIONS}/rename-post.test.ts`, contents: renamePostTest(app) },
|
|
135
|
+
{ path: `${ACTIONS}/rename-post.contract.test.ts`, contents: renamePostContract() },
|
|
136
|
+
];
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// `--shape realtime`'s proof that one change reaches two clients: the org's room on one in-process
|
|
2
|
+
// node (the `unit` step: who may join, what a member is sent), and the same room on TWO `sync`
|
|
3
|
+
// nodes over a real NATS bus (the `live` step, `TEST_NATS_URL` from docker/test-services.env).
|
|
4
|
+
|
|
5
|
+
import type { GeneratedFile, NameSet } from '../naming';
|
|
6
|
+
|
|
7
|
+
const SLICE = 'apps/web/app/post';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A member's socket with no server behind it, recording every `events` frame: `WsLike` is
|
|
11
|
+
* structural, so the hub writes to this exactly as it writes to a browser's WebSocket. Shared by
|
|
12
|
+
* both suites, spelled once here and written into each — a `-fixture.ts` would count against the
|
|
13
|
+
* app's coverage floor from a live suite that can never earn it.
|
|
14
|
+
*/
|
|
15
|
+
const memberRig = `/** A member's socket, recording the \`events\` frames the hub writes to it. */
|
|
16
|
+
const member = (name: string, orgId: string) => {
|
|
17
|
+
const events: unknown[] = [];
|
|
18
|
+
const first = Promise.withResolvers<void>();
|
|
19
|
+
const ws: WsLike = {
|
|
20
|
+
send: (data: string) => {
|
|
21
|
+
const frame: unknown = JSON.parse(data);
|
|
22
|
+
if (typeof frame === 'object' && frame !== null && Reflect.get(frame, 'type') === 'events') {
|
|
23
|
+
events.push(Reflect.get(frame, 'event'));
|
|
24
|
+
first.resolve();
|
|
25
|
+
}
|
|
26
|
+
return data.length;
|
|
27
|
+
},
|
|
28
|
+
close: () => undefined,
|
|
29
|
+
subscribe: () => undefined,
|
|
30
|
+
unsubscribe: () => undefined,
|
|
31
|
+
getBufferedAmount: () => 0,
|
|
32
|
+
};
|
|
33
|
+
const actor = testActor(name, { orgId, permissions: ['post:read'] }).actor;
|
|
34
|
+
const socket = new SyncSocket({ ws, clientBuildId: 'test', serverBuildId: 'test', actor });
|
|
35
|
+
return { socket, events, received: first.promise };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** The subscribe target a page sends for the org's room. */
|
|
39
|
+
const room = (orgId: string) =>
|
|
40
|
+
({ kind: 'channel', channel: postActivity.name, params: { orgId } }) as const;
|
|
41
|
+
`;
|
|
42
|
+
|
|
43
|
+
const unitSuite = (
|
|
44
|
+
app: NameSet,
|
|
45
|
+
): string => `// postActivity on one node, in process: who may join the org's room, and what a member is sent
|
|
46
|
+
// when a post is created — through \`createPost\`, its enqueue and the notifier's run, never a
|
|
47
|
+
// publish by hand. The same room across two nodes and a real bus is ./channels.live.test.ts.
|
|
48
|
+
import { driver } from '@${app.kebab}/db';
|
|
49
|
+
import { testActor } from '@ultimat3/policy';
|
|
50
|
+
import type { WsLike } from '@ultimat3/realtime/server';
|
|
51
|
+
import {
|
|
52
|
+
ChannelHub,
|
|
53
|
+
InProcessTransport,
|
|
54
|
+
SocketRegistry,
|
|
55
|
+
SyncSocket,
|
|
56
|
+
} from '@ultimat3/realtime/server';
|
|
57
|
+
import { afterEach, expect, swapAdapter, unitTest } from '@ultimat3/testing';
|
|
58
|
+
import { createPost } from './actions/create-post';
|
|
59
|
+
import { postActivity } from './channels';
|
|
60
|
+
import { POST_CREATED } from './jobs/post-created';
|
|
61
|
+
import { recentPosts } from './queries/recent-posts';
|
|
62
|
+
|
|
63
|
+
const orgId = '00000000-0000-4000-8000-000000000002';
|
|
64
|
+
const otherOrg = '00000000-0000-4000-8000-000000000009';
|
|
65
|
+
const writer = testActor('writer', { orgId, permissions: ['post:write'] }).actor;
|
|
66
|
+
|
|
67
|
+
${memberRig}
|
|
68
|
+
/** One node: its bus is the one the notifier publishes on, as under \`x dev\`. */
|
|
69
|
+
const node = async () => {
|
|
70
|
+
const transport = await swapAdapter('transport', new InProcessTransport());
|
|
71
|
+
const sockets = new SocketRegistry();
|
|
72
|
+
const hub = new ChannelHub({ transport, sockets });
|
|
73
|
+
const join = async (joined: ReturnType<typeof member>, org: string) => {
|
|
74
|
+
sockets.add(joined.socket);
|
|
75
|
+
return hub.subscribeChannel(joined.socket, room(org));
|
|
76
|
+
};
|
|
77
|
+
return { hub, join };
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
afterEach(() => {
|
|
81
|
+
driver.reset?.();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
unitTest('the room re-reads through recentPosts, under the same rule', () => {
|
|
85
|
+
expect(postActivity.events).toBe(true);
|
|
86
|
+
expect(postActivity.params).toEqual(['orgId']);
|
|
87
|
+
expect(recentPosts.policy).toBe(postActivity.policy);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
unitTest('a member of another org is refused the room', async () => {
|
|
91
|
+
const { hub, join } = await node();
|
|
92
|
+
await expect(join(member('eve', otherOrg), orgId)).rejects.toThrow(/X_TOPIC_FORBIDDEN/);
|
|
93
|
+
await hub.close();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
unitTest('a created post reaches every member in the room, once', async ({ runJobs }) => {
|
|
97
|
+
const { hub, join } = await node();
|
|
98
|
+
const ada = member('ada', orgId);
|
|
99
|
+
const bo = member('bo', orgId);
|
|
100
|
+
await join(ada, orgId);
|
|
101
|
+
await join(bo, orgId);
|
|
102
|
+
const row = await createPost.named('createPost').as(writer, {
|
|
103
|
+
title: 'hello',
|
|
104
|
+
price: { minor: 0, currency: 'USD' },
|
|
105
|
+
});
|
|
106
|
+
await runJobs.drain();
|
|
107
|
+
await Promise.all([ada.received, bo.received]);
|
|
108
|
+
const sent = [{ type: POST_CREATED, id: row.id }];
|
|
109
|
+
expect(ada.events).toEqual(sent);
|
|
110
|
+
expect(bo.events).toEqual(sent);
|
|
111
|
+
await hub.close();
|
|
112
|
+
});
|
|
113
|
+
`;
|
|
114
|
+
|
|
115
|
+
const liveSuite = (
|
|
116
|
+
app: NameSet,
|
|
117
|
+
): string => `// postActivity across TWO \`sync\` nodes on one real NATS bus — the topology production runs once
|
|
118
|
+
// NATS_URL is set. Each node holds its own bus connection and its own sockets; a member joins the
|
|
119
|
+
// org's room on each; \`createPost\` runs, and its notifier publishes from a third connection, as a
|
|
120
|
+
// worker does. Both members are sent the one event: two clients, two nodes, one change.
|
|
121
|
+
//
|
|
122
|
+
// Skipped, naming the command that starts NATS, when TEST_NATS_URL is unset; \`bunx x verify\`
|
|
123
|
+
// starts docker/docker-compose.test.yml and sets it.
|
|
124
|
+
import { driver } from '@${app.kebab}/db';
|
|
125
|
+
import { testActor } from '@ultimat3/policy';
|
|
126
|
+
import type { WsLike } from '@ultimat3/realtime/server';
|
|
127
|
+
import { ChannelHub, NatsTransport, SocketRegistry, SyncSocket } from '@ultimat3/realtime/server';
|
|
128
|
+
import { afterEach, expect, liveTest, swapAdapter } from '@ultimat3/testing';
|
|
129
|
+
import { createPost } from './actions/create-post';
|
|
130
|
+
import { postActivity } from './channels';
|
|
131
|
+
import { POST_CREATED } from './jobs/post-created';
|
|
132
|
+
|
|
133
|
+
const orgId = '00000000-0000-4000-8000-000000000002';
|
|
134
|
+
const writer = testActor('writer', { orgId, permissions: ['post:write'] }).actor;
|
|
135
|
+
/** This suite's presence bucket on the shared test server, never the one an app runs on. */
|
|
136
|
+
const BUCKET = 'post_activity_test';
|
|
137
|
+
|
|
138
|
+
${memberRig}
|
|
139
|
+
/** One bus connection to the test server: a node's, or the worker's. */
|
|
140
|
+
const dial = async () => {
|
|
141
|
+
const transport = new NatsTransport({ url: Bun.env.TEST_NATS_URL ?? '', bucket: BUCKET });
|
|
142
|
+
await transport.connect();
|
|
143
|
+
return transport;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** A \`sync\` node of its own: bus connection, socket table, hub. */
|
|
147
|
+
const node = async () => {
|
|
148
|
+
const transport = await dial();
|
|
149
|
+
const sockets = new SocketRegistry();
|
|
150
|
+
const hub = new ChannelHub({ transport, sockets });
|
|
151
|
+
return {
|
|
152
|
+
join: async (joined: ReturnType<typeof member>) => {
|
|
153
|
+
sockets.add(joined.socket);
|
|
154
|
+
return hub.subscribeChannel(joined.socket, room(orgId));
|
|
155
|
+
},
|
|
156
|
+
stop: async () => {
|
|
157
|
+
await hub.close();
|
|
158
|
+
await transport.close();
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
afterEach(() => {
|
|
164
|
+
driver.reset?.();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
liveTest(
|
|
168
|
+
'a post created on one node reaches a member on each of two nodes',
|
|
169
|
+
async ({ runJobs }) => {
|
|
170
|
+
const a = await node();
|
|
171
|
+
const b = await node();
|
|
172
|
+
// The worker's bus: what the boot installs from NATS_URL in every role.
|
|
173
|
+
const worker = await swapAdapter('transport', await dial());
|
|
174
|
+
try {
|
|
175
|
+
const ada = member('ada', orgId);
|
|
176
|
+
const bo = member('bo', orgId);
|
|
177
|
+
// Each subscribe resolves once that node's bridge to the bus is open: nothing is lost after.
|
|
178
|
+
await a.join(ada);
|
|
179
|
+
await b.join(bo);
|
|
180
|
+
const row = await createPost.named('createPost').as(writer, {
|
|
181
|
+
title: 'hello',
|
|
182
|
+
price: { minor: 0, currency: 'USD' },
|
|
183
|
+
});
|
|
184
|
+
await runJobs.drain();
|
|
185
|
+
await Promise.all([ada.received, bo.received]);
|
|
186
|
+
const sent = [{ type: POST_CREATED, id: row.id }];
|
|
187
|
+
expect(ada.events).toEqual(sent);
|
|
188
|
+
expect(bo.events).toEqual(sent);
|
|
189
|
+
} finally {
|
|
190
|
+
await a.stop();
|
|
191
|
+
await b.stop();
|
|
192
|
+
await worker.close();
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
{ needs: ['nats'] },
|
|
196
|
+
);
|
|
197
|
+
`;
|
|
198
|
+
|
|
199
|
+
/** Both suites, beside the channel they prove. */
|
|
200
|
+
export const realtimeNodeFiles = (app: NameSet): readonly GeneratedFile[] => [
|
|
201
|
+
{ path: `${SLICE}/channels.test.ts`, contents: unitSuite(app) },
|
|
202
|
+
{ path: `${SLICE}/channels.live.test.ts`, contents: liveSuite(app) },
|
|
203
|
+
];
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// `--shape realtime`'s server half: the org's live room (a channel), the read a client re-runs
|
|
2
|
+
// after a gap, and the notifier that tells the room a post landed. Each beside its unit test; the
|
|
3
|
+
// mutator is `realtime-mutator.ts`, the two-node proof `realtime-nodes.ts`.
|
|
4
|
+
|
|
5
|
+
import type { GeneratedFile, NameSet } from '../naming';
|
|
6
|
+
|
|
7
|
+
const SLICE = 'apps/web/app/post';
|
|
8
|
+
|
|
9
|
+
const channels =
|
|
10
|
+
(): string => `// postActivity: the org's live room. Every member's socket, on whichever \`sync\` node it landed,
|
|
11
|
+
// joins \`post-activity.<orgId>\`; an event published once — by \`postCreated\` on a worker — reaches
|
|
12
|
+
// all of them through the bus the boot installed (NATS_URL; in-process under \`x dev\`). It carries
|
|
13
|
+
// EVENTS only, "a post landed: re-read", never rows: the rows are \`postList\`'s, a live query.
|
|
14
|
+
//
|
|
15
|
+
// \`catchUp\` is the read a client re-runs after a \`replay-gap\`. Its policy is THIS channel's, the
|
|
16
|
+
// same object, or \`channel()\` refuses it (X_CHANNEL_CATCHUP_POLICY_MISMATCH).
|
|
17
|
+
|
|
18
|
+
import { channel } from '@ultimat3/realtime';
|
|
19
|
+
import { canPostWatch } from './policy';
|
|
20
|
+
import { recentPosts } from './queries/recent-posts';
|
|
21
|
+
|
|
22
|
+
export const postActivity = channel('post-activity', {
|
|
23
|
+
params: ['orgId'],
|
|
24
|
+
policy: canPostWatch,
|
|
25
|
+
catchUp: recentPosts,
|
|
26
|
+
events: true,
|
|
27
|
+
});
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
const recentPostsQuery =
|
|
31
|
+
(): string => `// recentPosts: the org's newest posts, for the org the room names — what \`postActivity\`'s client
|
|
32
|
+
// re-reads after a gap. Its input IS the channel's params, so its policy is the channel's own rule.
|
|
33
|
+
// \`t\` comes from @ultimat3/query, not @ultimat3/schema: a query file imports one package.
|
|
34
|
+
|
|
35
|
+
import { from, query, t } from '@ultimat3/query';
|
|
36
|
+
import type { Post } from '../entity';
|
|
37
|
+
import { canPostWatch } from '../policy';
|
|
38
|
+
import * as repo from '../repo';
|
|
39
|
+
|
|
40
|
+
/** A catch-up is a page, never the table: a constant, so no caller picks the read's cost. */
|
|
41
|
+
export const RECENT_POSTS = 20;
|
|
42
|
+
|
|
43
|
+
export const recentPosts = query({
|
|
44
|
+
input: t.object({ orgId: t.uuid }),
|
|
45
|
+
policy: canPostWatch,
|
|
46
|
+
// The refusals a caller may branch on, closed: add each code this read comes to throw.
|
|
47
|
+
errors: [],
|
|
48
|
+
sql: ({ orgId }) =>
|
|
49
|
+
// \`repo.list\`'s order, spelled as SQL: newest first, the id last so the order is total.
|
|
50
|
+
from<Post>('posts', () => repo.list(RECENT_POSTS))
|
|
51
|
+
.where({ orgId })
|
|
52
|
+
.orderBy('createdAt', 'desc')
|
|
53
|
+
.orderBy('id', 'desc')
|
|
54
|
+
.limit(RECENT_POSTS),
|
|
55
|
+
});
|
|
56
|
+
`;
|
|
57
|
+
|
|
58
|
+
const recentPostsTest = (
|
|
59
|
+
app: NameSet,
|
|
60
|
+
): string => `// recentPosts, READ: the org the input names is the caller's own, or the read is refused.
|
|
61
|
+
import { driver } from '@${app.kebab}/db';
|
|
62
|
+
import { ctxOf, frozenClock, runWithContext } from '@ultimat3/core';
|
|
63
|
+
import { testActor } from '@ultimat3/policy';
|
|
64
|
+
import { afterEach, expect, unitTest } from '@ultimat3/testing';
|
|
65
|
+
import * as repo from '../repo';
|
|
66
|
+
import { RECENT_POSTS, recentPosts } from './recent-posts';
|
|
67
|
+
|
|
68
|
+
const orgId = '00000000-0000-4000-8000-000000000002';
|
|
69
|
+
const otherOrg = '00000000-0000-4000-8000-000000000009';
|
|
70
|
+
const target = recentPosts.named('recentPosts');
|
|
71
|
+
const member = testActor('member', { orgId, permissions: ['post:read'] }).actor;
|
|
72
|
+
const clock = frozenClock('2026-01-01T00:00:00.000Z');
|
|
73
|
+
|
|
74
|
+
const store = (title: string) => {
|
|
75
|
+
const draft = { orgId, title, price: { minor: 0, currency: 'USD' } };
|
|
76
|
+
return runWithContext(ctxOf({ actor: member, clock }), () => repo.insert(draft));
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
afterEach(() => {
|
|
80
|
+
driver.reset?.();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
unitTest('another org’s room is refused, even to a member holding the grant', async () => {
|
|
84
|
+
const refused = await target.as(member, { orgId: otherOrg }).catch((error: unknown) => error);
|
|
85
|
+
expect(refused).toBeUltimateError('X_FORBIDDEN');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
unitTest('the org’s posts, newest first, and never more than one page', async () => {
|
|
89
|
+
for (let at = 0; at <= RECENT_POSTS; at += 1) {
|
|
90
|
+
await store(\`post \${String(at)}\`);
|
|
91
|
+
clock.advance(1000);
|
|
92
|
+
}
|
|
93
|
+
const page = await target.as(member, { orgId });
|
|
94
|
+
expect(page.length).toBe(RECENT_POSTS);
|
|
95
|
+
expect(page[0]?.title).toBe(\`post \${String(RECENT_POSTS)}\`);
|
|
96
|
+
});
|
|
97
|
+
`;
|
|
98
|
+
|
|
99
|
+
const postCreated =
|
|
100
|
+
(): string => `// postCreated: "a post landed — re-read", told to the org's live room on EVERY sync node. A
|
|
101
|
+
// notifier is a job: \`createPost\` enqueues it in its own transaction (a rolled-back create tells
|
|
102
|
+
// nobody), a bus that refuses the send is retried, and the delivery ledger makes a replayed run tell
|
|
103
|
+
// the room once.
|
|
104
|
+
//
|
|
105
|
+
// The audience is the ROOM, one bulk delivery: the org is the one recipient. A per-member channel
|
|
106
|
+
// — mail, push, the inbox — is one more \`deliver\` entry and a \`recipients\` that names the members.
|
|
107
|
+
|
|
108
|
+
import { bulkChannel, notifier, t } from '@ultimat3/notify';
|
|
109
|
+
import { publishChannelEvent } from '@ultimat3/realtime/server';
|
|
110
|
+
import { postActivity } from '../channels';
|
|
111
|
+
|
|
112
|
+
/** The event every member's tab receives: what happened and to which row — never the row itself. */
|
|
113
|
+
export const POST_CREATED = 'post.created';
|
|
114
|
+
|
|
115
|
+
interface PostCreated {
|
|
116
|
+
readonly id: string;
|
|
117
|
+
readonly orgId: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const postCreated = notifier({
|
|
121
|
+
name: POST_CREATED,
|
|
122
|
+
input: t.object({ id: t.uuid, orgId: t.uuid }),
|
|
123
|
+
tenant: (params) => params.orgId,
|
|
124
|
+
// One announcement per post: a retried create, or a replayed run, tells the room once.
|
|
125
|
+
key: (params) => \`post-created:\${params.id}\`,
|
|
126
|
+
recipients: ({ input }) => [{ id: input.orgId }],
|
|
127
|
+
deliver: [
|
|
128
|
+
{
|
|
129
|
+
channel: bulkChannel<PostCreated>('room', ({ event }) =>
|
|
130
|
+
publishChannelEvent(
|
|
131
|
+
postActivity,
|
|
132
|
+
{ orgId: event.params.orgId },
|
|
133
|
+
{ type: POST_CREATED, id: event.params.id },
|
|
134
|
+
),
|
|
135
|
+
),
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
});
|
|
139
|
+
`;
|
|
140
|
+
|
|
141
|
+
const postCreatedTest =
|
|
142
|
+
(): string => `// postCreated's declaration: one announcement per post, under the org it names. What it sends,
|
|
143
|
+
// and to whom, is the room's test (../channels.test.ts) and the two nodes' (../channels.live.test.ts).
|
|
144
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
145
|
+
import { POST_CREATED, postCreated } from './post-created';
|
|
146
|
+
|
|
147
|
+
const params = {
|
|
148
|
+
id: '00000000-0000-4000-8000-000000000001',
|
|
149
|
+
orgId: '00000000-0000-4000-8000-000000000002',
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
unitTest('one key per post, and the run acts as the org the post is in', () => {
|
|
153
|
+
expect(postCreated.name).toBe(POST_CREATED);
|
|
154
|
+
expect(postCreated.idempotencyKeyFor({ params })).toBe(\`post-created:\${params.id}\`);
|
|
155
|
+
expect(postCreated.tenantFor({ params })).toBe(params.orgId);
|
|
156
|
+
});
|
|
157
|
+
`;
|
|
158
|
+
|
|
159
|
+
/** The room, its catch-up read and the notifier — each with its unit test. */
|
|
160
|
+
export const realtimeSliceFiles = (app: NameSet): readonly GeneratedFile[] => [
|
|
161
|
+
{ path: `${SLICE}/channels.ts`, contents: channels() },
|
|
162
|
+
{ path: `${SLICE}/queries/recent-posts.ts`, contents: recentPostsQuery() },
|
|
163
|
+
{ path: `${SLICE}/queries/recent-posts.test.ts`, contents: recentPostsTest(app) },
|
|
164
|
+
{ path: `${SLICE}/jobs/post-created.ts`, contents: postCreated() },
|
|
165
|
+
{ path: `${SLICE}/jobs/post-created.test.ts`, contents: postCreatedTest() },
|
|
166
|
+
];
|