@latticecms/core 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +1297 -2
  2. package/dist/access.d.ts +209 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +241 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +555 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +655 -0
  9. package/dist/build.js.map +1 -0
  10. package/dist/collection.d.ts +480 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +351 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +46 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +527 -0
  17. package/dist/crud.js.map +1 -0
  18. package/dist/describe.d.ts +89 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +119 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/errors.d.ts +183 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +150 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/family.d.ts +80 -0
  27. package/dist/family.d.ts.map +1 -0
  28. package/dist/family.js +227 -0
  29. package/dist/family.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +10 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/marker.d.ts +15 -0
  35. package/dist/marker.d.ts.map +1 -0
  36. package/dist/marker.js +28 -0
  37. package/dist/marker.js.map +1 -0
  38. package/dist/mask.d.ts +69 -0
  39. package/dist/mask.d.ts.map +1 -0
  40. package/dist/mask.js +277 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +39 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +72 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +144 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +144 -0
  49. package/dist/relations.js.map +1 -0
  50. package/dist/repo.d.ts +99 -0
  51. package/dist/repo.d.ts.map +1 -0
  52. package/dist/repo.js +92 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +86 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +187 -0
  57. package/dist/sort.js.map +1 -0
  58. package/dist/store/conformance.d.ts +15 -0
  59. package/dist/store/conformance.d.ts.map +1 -0
  60. package/dist/store/conformance.js +811 -0
  61. package/dist/store/conformance.js.map +1 -0
  62. package/dist/store/index.d.ts +9 -0
  63. package/dist/store/index.d.ts.map +1 -0
  64. package/dist/store/index.js +8 -0
  65. package/dist/store/index.js.map +1 -0
  66. package/dist/store.d.ts +119 -0
  67. package/dist/store.d.ts.map +1 -0
  68. package/dist/store.js +176 -0
  69. package/dist/store.js.map +1 -0
  70. package/dist/tenancy.d.ts +66 -0
  71. package/dist/tenancy.d.ts.map +1 -0
  72. package/dist/tenancy.js +69 -0
  73. package/dist/tenancy.js.map +1 -0
  74. package/dist/tracing.d.ts +12 -0
  75. package/dist/tracing.d.ts.map +1 -0
  76. package/dist/tracing.js +27 -0
  77. package/dist/tracing.js.map +1 -0
  78. package/dist/where.d.ts +95 -0
  79. package/dist/where.d.ts.map +1 -0
  80. package/dist/where.js +308 -0
  81. package/dist/where.js.map +1 -0
  82. package/package.json +80 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +90 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +94 -0
  87. package/skills/lattice/references/event-handler.md +88 -0
  88. package/skills/lattice/references/masking.md +72 -0
  89. package/skills/lattice/references/method.md +88 -0
  90. package/skills/lattice/references/override.md +160 -0
  91. package/skills/lattice/references/relations.md +91 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +449 -0
  95. package/src/build.ts +1888 -0
  96. package/src/collection.ts +1025 -0
  97. package/src/crud.ts +797 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +174 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +44 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +336 -0
  104. package/src/populate.ts +103 -0
  105. package/src/relations.ts +370 -0
  106. package/src/repo.ts +218 -0
  107. package/src/sort.ts +271 -0
  108. package/src/store/conformance.ts +1179 -0
  109. package/src/store/index.ts +22 -0
  110. package/src/store.ts +315 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
@@ -0,0 +1,160 @@
1
+ # Override
2
+
3
+ An override is a hand-written use case that serves a generated procedure in place of Lattice's. The procedure keeps its path, input, output and meta. There are two kinds:
4
+
5
+ - **One that adds a rule** checks the input, then returns the generated operation. Use it when the operation is right except for a case it must refuse, such as an update that would close a deal.
6
+ - **One that changes what the operation does,** such as a delete that archives, writes through repos.
7
+
8
+ ## An override that adds a rule
9
+
10
+ ```ts
11
+ // examples/crm/src/app/use-cases/deals/update-deal.ts
12
+ import type { Doc, UpdateInput } from '@latticecms/core';
13
+ import { Deals } from '../../../domain/collections/deals.js';
14
+ import { type AppCtx, AppUseCase } from '../context.js';
15
+ import { refuseClosing } from './close-only.js';
16
+
17
+ /**
18
+ * Replaces deals.update: the generated update, except that it cannot close
19
+ * the deal. A closed deal is already out of its access scope.
20
+ */
21
+ export class UpdateDeal extends AppUseCase('deals.update', {
22
+ collection: Deals,
23
+ }) {
24
+ constructor(
25
+ private readonly deps: {
26
+ update: (
27
+ ctx: AppCtx,
28
+ input: UpdateInput<typeof Deals>,
29
+ ) => Promise<Doc<typeof Deals>>;
30
+ },
31
+ ) {
32
+ super();
33
+ }
34
+
35
+ async execute(
36
+ ctx: AppCtx,
37
+ input: UpdateInput<typeof Deals>,
38
+ ): Promise<Doc<typeof Deals>> {
39
+ refuseClosing(input);
40
+ return this.deps.update(ctx, input);
41
+ }
42
+ }
43
+ ```
44
+
45
+ The rule is one function, which create shares:
46
+
47
+ ```ts
48
+ // examples/crm/src/app/use-cases/deals/close-only.ts
49
+ import { LatticeError, type UpdateInput } from '@latticecms/core';
50
+ import type { Deals } from '../../../domain/collections/deals.js';
51
+
52
+ /**
53
+ * A deal closes only through deals.close, which closes it once and
54
+ * publishes DealClosed. So create and update refuse a won or lost stage,
55
+ * and any closedAt, before they write. Typed from the deal's update input,
56
+ * which create's input also fits, so a renamed field or stage breaks the
57
+ * build here.
58
+ */
59
+ export function refuseClosing(
60
+ input: Pick<UpdateInput<typeof Deals>, 'stage' | 'closedAt'>,
61
+ ): void {
62
+ const issues = [
63
+ ...(input.stage === 'won' || input.stage === 'lost'
64
+ ? [{ path: ['stage'], message: 'Close a deal with deals.close' }]
65
+ : []),
66
+ ...(input.closedAt === undefined
67
+ ? []
68
+ : [{ path: ['closedAt'], message: 'deals.close sets closedAt' }]),
69
+ ];
70
+ if (issues.length > 0) throw LatticeError.VALIDATION({ issues });
71
+ }
72
+ ```
73
+
74
+ - Declare the input as `UpdateInput<C>` for update, or `CreateInput<C>` for create, and pass it on as is.
75
+ - Take the generated operation on `deps` in the constructor, and build the instance with `generated.<slug>.<operation>` in `build()`. A relation's is `generated.<slug>.<relation>.<op>`. `generated` holds only the operations the app overrides.
76
+ - Refuse before the call, with `LatticeError.VALIDATION` at the field's path. Nothing is written.
77
+ - The generated operation keeps everything: the input parse, the access scope, hooks, `null` clears, the diff, the event and masking. The guards, the log line and the span run once, in the override's own use case.
78
+
79
+ ## An override that changes the operation
80
+
81
+ ```ts
82
+ // examples/crm/src/app/use-cases/deals/archive-deal.ts
83
+ import { type Doc, LatticeError, type Repo } from '@latticecms/core';
84
+ import { Deals } from '../../../domain/collections/deals.js';
85
+ import { type AppCtx, AppUseCase } from '../context.js';
86
+
87
+ /** Replaces deals.delete: the deal is archived, and the row stays. */
88
+ export class ArchiveDeal extends AppUseCase('deals.delete', {
89
+ collection: Deals,
90
+ }) {
91
+ constructor(private readonly deps: { deals: Repo<typeof Deals> }) {
92
+ super();
93
+ }
94
+
95
+ async execute(
96
+ ctx: AppCtx,
97
+ input: { id: string },
98
+ ): Promise<Doc<typeof Deals>> {
99
+ const deal = await this.deps.deals.update(
100
+ input.id,
101
+ { archived: true },
102
+ await ctx.access.scope(Deals, 'delete'),
103
+ );
104
+ // The same refusal the generated delete gives for a missing id.
105
+ if (deal === null) {
106
+ throw LatticeError.NOT_FOUND({ collection: Deals.slug, id: input.id });
107
+ }
108
+ return deal;
109
+ }
110
+ }
111
+ ```
112
+
113
+ ## How to write one
114
+
115
+ - Extend the app's family with the procedure's token, `<slug>.<action>`, and a `collection` static. Declare no `summary` or `effect`: an override keeps the generated ones.
116
+ - Take repos on `deps` in the constructor. Annotate `execute` with the procedure's input and output types.
117
+ - Get the scope with `ctx.access.scope(C, action)`. The family has already checked access for the action. The override uses that action's access function.
118
+ - Refuse as the generated operation does: `LatticeError.NOT_FOUND`, `CONFLICT` or `REFERENCED`. A domain refusal is a member of the app's own `Errors` catalog, declared in `framework({ errors })`.
119
+ - Publish your own events. Lattice publishes nothing for an override that writes through repos.
120
+
121
+ Register both at composition, and build them from `generated` and the repos:
122
+
123
+ ```ts
124
+ // examples/crm/src/servers/rpc/contract.ts
125
+ methods: { close: CloseDeal },
126
+ // A deal closes only through deals.close: create and update refuse to.
127
+ overrides: { create: CreateDeal, update: UpdateDeal, delete: ArchiveDeal },
128
+ ```
129
+
130
+ ```ts
131
+ // examples/crm/src/servers/app.ts
132
+ overrides: ({ repos, generated }) => ({
133
+ deals: {
134
+ create: new CreateDeal({ create: generated.deals.create }),
135
+ update: new UpdateDeal({ update: generated.deals.update }),
136
+ delete: new ArchiveDeal({ deals: repos.deals }),
137
+ },
138
+ }),
139
+ ```
140
+
141
+ A relation's operation is overridden under its name: `overrides: { contacts: { set: ReplaceContacts } }`.
142
+
143
+ A soft delete is this override plus a `read` filter that hides archived rows. Read [access.md](access.md).
144
+
145
+ ## Do not
146
+
147
+ - Do not write a second procedure for the same story, such as `deals.archive` beside `deals.delete`. Override the one that exists.
148
+ - Do not skip the scope. A repo call with `unscoped` in an override ignores access and tenancy.
149
+ - Do not give a collection that overrides `delete` a cascading ref. The cascade would hard-delete rows the override keeps.
150
+ - Do not return a different shape. The procedure's output is fixed.
151
+ - Do not copy the generated update into an override to add a rule. Check, then return `generated`.
152
+ - Do not call `useCases.<slug>.<operation>` from an override. Its guards, log line and span would run twice.
153
+ - An overridden read takes no `populate`: population runs in the generated read.
154
+
155
+ ## Errors you will see
156
+
157
+ - A class whose token or `execute` types do not match the procedure fails `.collection()` with a type error on `overrides`.
158
+ - An override with `summary` or `effect` fails with `'~error'`, and throws `override "deals.delete" keeps the generated summary and effect; remove its summary and effect statics`.
159
+ - `"archive" is not a generated operation or a relation`, for an override key that names nothing.
160
+ - A missing `overrides` factory at `build()` is a type error: it is required exactly when a collection declares one.
@@ -0,0 +1,91 @@
1
+ # Relations
2
+
3
+ Lattice has no joins. A relation is an id in one document, and population reads the other collection once per call.
4
+
5
+ - `ref(slug)` marks a string field as another document's id. `z.array(ref(slug))` is a list of ids. A ref refuses an empty id, "Choose the company", so a required ref needs no `.min(1)`.
6
+ - `many(target, { through, fields? })` links each document to many of another collection, through a join collection Lattice derives.
7
+
8
+ ```ts
9
+ // examples/crm/src/domain/collections/deals.ts
10
+ schema: z.object({
11
+ // The messages are what a form shows at the field.
12
+ title: z.string().min(1, 'Enter a title'),
13
+ // An archived deal still refers to its company, so it restricts too.
14
+ companyId: ref('companies'),
15
+ ```
16
+
17
+ ```ts
18
+ // examples/crm/src/domain/collections/deals.ts
19
+ // The people on a deal, and what each is to it. A contact on a deal
20
+ // cannot be deleted: restrict, the default.
21
+ relations: {
22
+ contacts: many('contacts', {
23
+ through: 'deal_contacts',
24
+ fields: z.object({ role: contactRole }),
25
+ }),
26
+ },
27
+ ```
28
+
29
+ ## Refs and onDelete
30
+
31
+ `ref(slug, { onDelete })` says what the generated delete of the referenced document does:
32
+
33
+ | `onDelete` | When the referenced document is deleted |
34
+ | --- | --- |
35
+ | `restrict` (default) | The delete is `REFERENCED` (409), naming the collection and field, while any document refers to it |
36
+ | `cascade` | The referring documents are deleted too. A list of ids cannot cascade |
37
+ | `nullify` | The ref is cleared. A required ref cannot nullify |
38
+
39
+ - These steps skip access, stay inside the parent's tenant, and run in one store transaction. Events publish after the commit.
40
+ - A write does not check that the referenced document exists. Deleting it is where refs are kept whole.
41
+ - Each ref gets an index, led by the tenant field.
42
+ - `onDelete` runs in the generated delete only. An override of `delete` keeps the row, so its collection cannot have a cascading ref.
43
+
44
+ ## many() relations
45
+
46
+ - The join collection is `Deals.relations.contacts.through`, with slug `deal_contacts`. Its documents are `{ dealsId, contactsId, ...fields }` with the parent's tenant. It has events, which the app lists in its catalog, and a repo, but no slice of its own.
47
+ - `deals.contacts.list({ id })` pages a deal's links, under the deal's `read` access.
48
+ - `deals.contacts.set({ id, links })` replaces them all, under the deal's `update` access. It diffs in one transaction, and each change publishes its join event.
49
+
50
+ ```ts
51
+ // examples/crm/src/domain/events/domain-events.ts
52
+ dealContactsCreated: Deals.relations.contacts.through.events.created,
53
+ dealContactsUpdated: Deals.relations.contacts.through.events.updated,
54
+ dealContactsDeleted: Deals.relations.contacts.through.events.deleted,
55
+ ```
56
+
57
+ ## Population
58
+
59
+ A read takes `populate`, and the output type follows it on every ts-pf client:
60
+
61
+ ```ts
62
+ // examples/crm/src/servers/app.test.ts
63
+ const got = await local.contacts.get({
64
+ id: ada.id,
65
+ populate: ['companyId'],
66
+ });
67
+
68
+ expectTypeOf(got.companyId).toEqualTypeOf<
69
+ Doc<typeof Companies> | Withheld
70
+ >();
71
+ ```
72
+
73
+ - `get` populates refs and relations. `find` populates refs only.
74
+ - A document the caller may not read, or one that is gone, is `Withheld`: `{ id }` only. Narrow with a field: `'name' in got.companyId`.
75
+ - Population runs under the caller's `read` access on the target, with its tenant. One level deep.
76
+ - An overridden read takes no `populate`.
77
+
78
+ ## Do not
79
+
80
+ - Do not load related documents in a loop in a use case. Use `populate`, or one `getMany`.
81
+ - Do not store a copy of the other document. Store its id.
82
+ - Do not relate a collection to itself with `many()`. It is not supported.
83
+ - Do not cast a populated field. Narrow `Doc | Withheld` with `in`.
84
+
85
+ ## Errors you will see
86
+
87
+ - A ref to a slug that is not in the framework fails `.contract` and `build()` with `'~error'`, and throws `deals.companyId refers to "companys", which is not a collection of this framework`.
88
+ - `"<field>" is a list of ids; it cannot cascade (use restrict or nullify)`, and `"<field>" is required; nullify needs it .optional() or .nullable()`.
89
+ - `deals overrides delete, so deals.<field> cannot cascade; use restrict or nullify`.
90
+ - `relation "<name>" has the name of a field, an action or an access key`.
91
+ - At runtime, deleting a referenced document is `REFERENCED` with `{ collection, id, by: { collection, field } }`. When a `many()` relation's links refer to it, `by` names the join collection, and `by.relation` names the relation: `{ collection: 'deals', name: 'contacts' }`. A relation on `find`'s `populate` is `VALIDATION`.
@@ -0,0 +1,82 @@
1
+ # Tenancy
2
+
3
+ A collection with `tenant: 'organizationId'` keeps each tenant's rows apart. Lattice adds the field to the output, stamps it on create, and filters every call by the caller's tenant. A collection without `tenant` is global.
4
+
5
+ The family says each call's tenant:
6
+
7
+ ```ts
8
+ // examples/crm/src/app/use-cases/context.ts
9
+ /** The app's one use case family. Generated and hand-written use cases share it. */
10
+ export const AppUseCase = family({
11
+ actor: actorSchema,
12
+ actorId: (actor) => actor.userId,
13
+ tenantOf: (actor) =>
14
+ 'support' in actor ? tenancy.bypass : actor.organizationId,
15
+ });
16
+ ```
17
+
18
+ ## How it works
19
+
20
+ - `tenantOf` returns the actor's tenant id, or `tenancy.bypass` for a platform actor such as support staff. A framework with a tenanted collection requires it.
21
+ - The tenant field is in `Doc` and `Where`, never in create or update input. Create stamps it after `beforeChange`. Update never writes it.
22
+ - Every scope is the tenant clause ANDed with the access `Where`. Another tenant's row is `NOT_FOUND`, and `find` never returns it, page after page.
23
+ - A bypassed call reads across tenants and writes nothing on a tenanted collection: generated create, update and delete are `FORBIDDEN`, and so is a repo write through its scope. Each bypassed scope writes one `tenancy.bypass` log line.
24
+ - The actor schema validates the bypass flag. The edge sets it from server config, never from the request.
25
+
26
+ The crm proves isolation over HTTP:
27
+
28
+ ```ts
29
+ // examples/crm/src/servers/http/tenancy.test.ts
30
+ // An id from another organization is not there at all.
31
+ expect(await code(a, 'companies/get', { id: bolt })).toBe('NOT_FOUND');
32
+ expect(await code(b, 'companies/get', { id: acme })).toBe('NOT_FOUND');
33
+ // A where on the tenant field cannot reach past the tenant filter.
34
+ expect(
35
+ await ok(a, 'companies/find', {
36
+ where: { organizationId: { eq: 'org-b' } },
37
+ }),
38
+ ).toMatchObject({ docs: [] });
39
+ ```
40
+
41
+ ## Server code names its tenant
42
+
43
+ Code that acts for no caller says which tenant it works in. An event handler reads with `tenancy.scope(C, tenantId)`: the tenant clause, and no access. An insert through it is stamped with that tenant.
44
+
45
+ ```ts
46
+ // examples/crm/src/app/event-handlers/deal-closed-integration.ts
47
+ const { dealId, outcome, tenantId } = event.payload;
48
+ const deal = await this.deps.deals.get(
49
+ dealId,
50
+ tenancy.scope(Deals, tenantId),
51
+ );
52
+ ```
53
+
54
+ `unscoped` reads and writes every tenant. A script that acts for no tenant passes it. It cannot insert into a tenanted collection, since the row would belong to no tenant.
55
+
56
+ A global collection, such as the crm's `organizations` and `memberships`, has no tenant field. Its `read` access does the narrowing:
57
+
58
+ ```ts
59
+ // examples/crm/src/servers/rpc/contract.ts
60
+ .collection(Organizations, {
61
+ // A member reads the organization it acts in, and support every one.
62
+ // No create, update or delete: only trusted code writes them.
63
+ access: {
64
+ read: ({ actor }) =>
65
+ 'support' in actor ? true : { id: { eq: actor.organizationId } },
66
+ },
67
+ });
68
+ ```
69
+
70
+ ## Do not
71
+
72
+ - Do not put the tenant field in the schema. Lattice adds it.
73
+ - Do not take the tenant from the request body. The edge checks membership and puts the tenant on the actor.
74
+ - Do not pass `unscoped` in an event handler. Use the event's `tenantId` with `tenancy.scope`.
75
+ - Do not write through a bypass. Support reads; a write is a separate, audited path.
76
+
77
+ ## Errors you will see
78
+
79
+ - A schema field with the tenant's name fails `collection()` with `'~error'`: `tenant "organizationId" is stamped by Lattice; it cannot be a schema field, a reserved name or an invalid field name`.
80
+ - A tenanted collection in a family without `tenantOf` fails `.collection()`: `"notes" is tenanted, but the family has no tenantOf`.
81
+ - `insert` with `unscoped` on a tenanted collection does not compile, and throws `"notes" is tenanted, so insert needs a scope with a tenant, such as tenancy.scope()`.
82
+ - At runtime, a bypass write is `FORBIDDEN`, and another tenant's row is `NOT_FOUND`.
@@ -0,0 +1,75 @@
1
+ # Testing
2
+
3
+ Test a story through the contract. Build the app over a store, and call it with ts-pf's `createLocalClient`, as a client would. The local client runs the same router as HTTP: access, tenancy, masking and validation.
4
+
5
+ The smallest app, from core's quick start:
6
+
7
+ ```ts
8
+ // examples/crm/src/quickstart/quickstart.ts
9
+ const client = createLocalClient(app, {
10
+ context: { actor: { userId: 'ann' }, logger: new NoopLogger() },
11
+ });
12
+ const note = await client.notes.create({ title: 'Write the docs' });
13
+ await client.notes.update({ id: note.id, done: true });
14
+ const { docs } = await client.notes.find({ where: { done: { eq: true } } });
15
+ ```
16
+
17
+ ## The app's tests
18
+
19
+ The crm builds its app the way the server does, and gives the client an actor:
20
+
21
+ ```ts
22
+ // examples/crm/src/servers/app.test.ts
23
+ function setup() {
24
+ const events = new MemoryDomainEventPublisher();
25
+ const crm = createApp({ store: store(), events });
26
+ const local = createLocalClient(crm.app, {
27
+ context: { actor, logger: new NoopLogger() },
28
+ });
29
+ return { ...crm, events, local };
30
+ }
31
+ ```
32
+
33
+ A client needs no annotations. A refusal is a typed error:
34
+
35
+ ```ts
36
+ // examples/crm/src/servers/app.test.ts
37
+ const again = await asResult(
38
+ local.deals.close({ id: deal.id, outcome: 'lost' }),
39
+ );
40
+ if (again.ok) throw new Error('expected AlreadyClosed');
41
+ if (again.error.code !== 'AlreadyClosed')
42
+ throw new Error(again.error.code);
43
+ expectTypeOf(again.error.data).toEqualTypeOf<{ id: string }>();
44
+ expect(again.error.data).toEqual({ id: deal.id });
45
+ expect(again.error.status).toBe(409);
46
+ ```
47
+
48
+ - `MemoryStore` needs no server. The crm runs the same tests on `MemoryStore` and `MongoStore`, through `describe.each(backends)` in `src/test/stores.ts`.
49
+ - `build().repos` seeds and reads data directly, with a scope. `build().context({ actor, logger })` makes a context for a direct `useCases.*.execute` call. Prefer the client.
50
+ - A collection's own test, as `lattice collection` writes it, builds nothing: it checks the contract has the slug and its operations, and that the schema parses a document. Test behavior through the app's setup, as above.
51
+ - A test of a handler builds it with repos and a fake port, and calls `handle` with an event instance.
52
+ - Masking and tenancy are tested over HTTP in the crm: `src/servers/http/masking.test.ts` and `tenancy.test.ts`.
53
+
54
+ ## A store adapter
55
+
56
+ A new store passes the conformance suite from `@latticecms/core/store/conformance`, with a fresh store per case:
57
+
58
+ ```ts
59
+ // packages/store-mongo/src/mongo-store.test.ts
60
+ it.each(storeCases)('$name', ({ run }) => run(store));
61
+ ```
62
+
63
+ A case that needs a capability names it in `needs`. A store without transactions filters out `needs: ['transactions']`.
64
+
65
+ ## Do not
66
+
67
+ - Do not test through a mock of the store or the router. `MemoryStore` is the in-memory adapter.
68
+ - Do not cast a client's result. Narrow it: `asResult`, `'field' in doc`.
69
+ - Do not call `useCases` to test what a client sees. Masking happens in the router, so `useCases` return whole documents.
70
+ - Do not share one access context across calls. Make one per call with `context()`.
71
+
72
+ ## Errors you will see
73
+
74
+ - A test that expects a masked field from `useCases` passes and proves nothing. Call through `createLocalClient`.
75
+ - A tenanted collection seeded through `unscoped` does not compile. Seed with `tenancy.scope(C, tenantId)`.