@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.
- package/README.md +1297 -2
- package/dist/access.d.ts +209 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +241 -0
- package/dist/access.js.map +1 -0
- package/dist/build.d.ts +555 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/build.js +655 -0
- package/dist/build.js.map +1 -0
- package/dist/collection.d.ts +480 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/collection.js +351 -0
- package/dist/collection.js.map +1 -0
- package/dist/crud.d.ts +46 -0
- package/dist/crud.d.ts.map +1 -0
- package/dist/crud.js +527 -0
- package/dist/crud.js.map +1 -0
- package/dist/describe.d.ts +89 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +119 -0
- package/dist/describe.js.map +1 -0
- package/dist/errors.d.ts +183 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +150 -0
- package/dist/errors.js.map +1 -0
- package/dist/family.d.ts +80 -0
- package/dist/family.d.ts.map +1 -0
- package/dist/family.js +227 -0
- package/dist/family.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/marker.d.ts +15 -0
- package/dist/marker.d.ts.map +1 -0
- package/dist/marker.js +28 -0
- package/dist/marker.js.map +1 -0
- package/dist/mask.d.ts +69 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +277 -0
- package/dist/mask.js.map +1 -0
- package/dist/populate.d.ts +39 -0
- package/dist/populate.d.ts.map +1 -0
- package/dist/populate.js +72 -0
- package/dist/populate.js.map +1 -0
- package/dist/relations.d.ts +144 -0
- package/dist/relations.d.ts.map +1 -0
- package/dist/relations.js +144 -0
- package/dist/relations.js.map +1 -0
- package/dist/repo.d.ts +99 -0
- package/dist/repo.d.ts.map +1 -0
- package/dist/repo.js +92 -0
- package/dist/repo.js.map +1 -0
- package/dist/sort.d.ts +86 -0
- package/dist/sort.d.ts.map +1 -0
- package/dist/sort.js +187 -0
- package/dist/sort.js.map +1 -0
- package/dist/store/conformance.d.ts +15 -0
- package/dist/store/conformance.d.ts.map +1 -0
- package/dist/store/conformance.js +811 -0
- package/dist/store/conformance.js.map +1 -0
- package/dist/store/index.d.ts +9 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +8 -0
- package/dist/store/index.js.map +1 -0
- package/dist/store.d.ts +119 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +176 -0
- package/dist/store.js.map +1 -0
- package/dist/tenancy.d.ts +66 -0
- package/dist/tenancy.d.ts.map +1 -0
- package/dist/tenancy.js +69 -0
- package/dist/tenancy.js.map +1 -0
- package/dist/tracing.d.ts +12 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +27 -0
- package/dist/tracing.js.map +1 -0
- package/dist/where.d.ts +95 -0
- package/dist/where.d.ts.map +1 -0
- package/dist/where.js +308 -0
- package/dist/where.js.map +1 -0
- package/package.json +80 -2
- package/skills/lattice/SKILL.md +106 -0
- package/skills/lattice/references/access.md +90 -0
- package/skills/lattice/references/cli.md +87 -0
- package/skills/lattice/references/collection.md +94 -0
- package/skills/lattice/references/event-handler.md +88 -0
- package/skills/lattice/references/masking.md +72 -0
- package/skills/lattice/references/method.md +88 -0
- package/skills/lattice/references/override.md +160 -0
- package/skills/lattice/references/relations.md +91 -0
- package/skills/lattice/references/tenancy.md +82 -0
- package/skills/lattice/references/testing.md +75 -0
- package/src/access.ts +449 -0
- package/src/build.ts +1888 -0
- package/src/collection.ts +1025 -0
- package/src/crud.ts +797 -0
- package/src/describe.ts +232 -0
- package/src/errors.ts +174 -0
- package/src/family.ts +334 -0
- package/src/index.ts +44 -0
- package/src/marker.ts +54 -0
- package/src/mask.ts +336 -0
- package/src/populate.ts +103 -0
- package/src/relations.ts +370 -0
- package/src/repo.ts +218 -0
- package/src/sort.ts +271 -0
- package/src/store/conformance.ts +1179 -0
- package/src/store/index.ts +22 -0
- package/src/store.ts +315 -0
- package/src/tenancy.ts +124 -0
- package/src/tracing.ts +29 -0
- package/src/where.ts +463 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@latticecms/core/store`: what a `CollectionStore` adapter needs. A store
|
|
3
|
+
* receives values Lattice has already parsed, so the input schemas stay out.
|
|
4
|
+
* The conformance suite is `@latticecms/core/store/conformance`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
after,
|
|
9
|
+
cursorValues,
|
|
10
|
+
encodeCursor,
|
|
11
|
+
type Order,
|
|
12
|
+
orderOf,
|
|
13
|
+
} from '../sort.js';
|
|
14
|
+
export {
|
|
15
|
+
CollectionStore,
|
|
16
|
+
type FindQuery,
|
|
17
|
+
type Index,
|
|
18
|
+
type Page,
|
|
19
|
+
type Patch,
|
|
20
|
+
type StoredDoc,
|
|
21
|
+
} from '../store.js';
|
|
22
|
+
export type { AnyWhere, FieldOps } from '../where.js';
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { Adapter, Port } from 'hexok';
|
|
3
|
+
import { LatticeError } from './errors.js';
|
|
4
|
+
import { after, compareDocs, encodeCursor, orderOf } from './sort.js';
|
|
5
|
+
import { type AnyWhere, matches } from './where.js';
|
|
6
|
+
|
|
7
|
+
/** A stored document. Every collection's documents have an `id`. */
|
|
8
|
+
export type StoredDoc = {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly [field: string]: unknown;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** A shallow change to a document. A key set to undefined removes the field. */
|
|
14
|
+
export type Patch = { readonly id?: never; readonly [field: string]: unknown };
|
|
15
|
+
|
|
16
|
+
export type FindQuery = {
|
|
17
|
+
readonly collection: string;
|
|
18
|
+
readonly where?: AnyWhere;
|
|
19
|
+
/** Keys as `field` or `-field`. Stores add `id` as the last tiebreak. */
|
|
20
|
+
readonly sort: readonly string[];
|
|
21
|
+
/**
|
|
22
|
+
* The sort fields a document may have no value for. Such a document comes
|
|
23
|
+
* after every one with a value, in either direction (0037). `orderOf`
|
|
24
|
+
* takes it, so a store plans a plain sort when nothing here is ascending.
|
|
25
|
+
*/
|
|
26
|
+
readonly optional: readonly string[];
|
|
27
|
+
readonly limit: number;
|
|
28
|
+
/** The `next` cursor of the previous page. */
|
|
29
|
+
readonly after?: string;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** One page of a find. `next` is null on the last page. */
|
|
33
|
+
export type Page = { readonly docs: StoredDoc[]; readonly next: string | null };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An index on a collection. `fields` maps each field to its direction, in
|
|
37
|
+
* the index's key order. A unique index treats a missing field as null, as
|
|
38
|
+
* MongoDB does, so two documents missing it conflict.
|
|
39
|
+
*/
|
|
40
|
+
export type Index = {
|
|
41
|
+
readonly fields: Readonly<Record<string, 1 | -1>>;
|
|
42
|
+
readonly unique?: boolean;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Storage for every collection. `where` on a single-row call is the access
|
|
47
|
+
* and tenant filter: a row outside it acts as missing.
|
|
48
|
+
*/
|
|
49
|
+
export abstract class CollectionStore extends Port('CollectionStore') {
|
|
50
|
+
/**
|
|
51
|
+
* Creates the indexes `collection` lacks, and never drops one. Rejects
|
|
52
|
+
* when a new unique index meets documents that already break it.
|
|
53
|
+
*/
|
|
54
|
+
abstract ensure(collection: string, indexes: readonly Index[]): Promise<void>;
|
|
55
|
+
abstract find(query: FindQuery): Promise<Page>;
|
|
56
|
+
/** How many documents match `where`. */
|
|
57
|
+
abstract count(collection: string, where?: AnyWhere): Promise<number>;
|
|
58
|
+
abstract get(
|
|
59
|
+
collection: string,
|
|
60
|
+
id: string,
|
|
61
|
+
where?: AnyWhere,
|
|
62
|
+
): Promise<StoredDoc | null>;
|
|
63
|
+
/** The docs that exist and match, in the order of `ids`. */
|
|
64
|
+
abstract getMany(
|
|
65
|
+
collection: string,
|
|
66
|
+
ids: readonly string[],
|
|
67
|
+
where?: AnyWhere,
|
|
68
|
+
): Promise<StoredDoc[]>;
|
|
69
|
+
/** Throws `CONFLICT` when the id exists, or a unique index would break. */
|
|
70
|
+
abstract insert(collection: string, doc: StoredDoc): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* The updated doc, or null when no row matched. Throws `CONFLICT` when a
|
|
73
|
+
* unique index would break.
|
|
74
|
+
*/
|
|
75
|
+
abstract update(
|
|
76
|
+
collection: string,
|
|
77
|
+
id: string,
|
|
78
|
+
patch: Patch,
|
|
79
|
+
where?: AnyWhere,
|
|
80
|
+
): Promise<StoredDoc | null>;
|
|
81
|
+
/**
|
|
82
|
+
* Runs `work` as one unit with a store whose calls join it: a commit, or
|
|
83
|
+
* on a throw, nothing. Each store makes it as atomic as it can. A store
|
|
84
|
+
* without transactions runs `work` on itself, in order. A `transaction`
|
|
85
|
+
* inside `work` joins the outer one.
|
|
86
|
+
*/
|
|
87
|
+
abstract transaction<T>(
|
|
88
|
+
work: (store: CollectionStore) => Promise<T>,
|
|
89
|
+
): Promise<T>;
|
|
90
|
+
/** The removed doc, or null when no row matched. */
|
|
91
|
+
abstract remove(
|
|
92
|
+
collection: string,
|
|
93
|
+
id: string,
|
|
94
|
+
where?: AnyWhere,
|
|
95
|
+
): Promise<StoredDoc | null>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A `CollectionStore` in memory, for tests and examples. It stores copies, so
|
|
100
|
+
* a caller that mutates an argument or a returned doc does not change it.
|
|
101
|
+
*/
|
|
102
|
+
export class MemoryStore extends Adapter(CollectionStore) {
|
|
103
|
+
private collections = new Map<string, Map<string, StoredDoc>>();
|
|
104
|
+
private indexes = new Map<string, Index[]>();
|
|
105
|
+
/** Whether a transaction is running, so a nested one joins it. */
|
|
106
|
+
private transacting = false;
|
|
107
|
+
|
|
108
|
+
private rows(collection: string): Map<string, StoredDoc> {
|
|
109
|
+
const existing = this.collections.get(collection);
|
|
110
|
+
if (existing !== undefined) return existing;
|
|
111
|
+
const rows = new Map<string, StoredDoc>();
|
|
112
|
+
this.collections.set(collection, rows);
|
|
113
|
+
return rows;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The unique indexes of `collection`. */
|
|
117
|
+
private unique(collection: string): Index[] {
|
|
118
|
+
return (this.indexes.get(collection) ?? []).filter(
|
|
119
|
+
(index) => index.unique === true,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Throws CONFLICT when `doc` would share a unique index's key with another
|
|
125
|
+
* row. A missing field keys as null, as in MongoDB.
|
|
126
|
+
*/
|
|
127
|
+
private checkUnique(collection: string, doc: StoredDoc): void {
|
|
128
|
+
for (const index of this.unique(collection)) {
|
|
129
|
+
const key = keyOf(index, doc);
|
|
130
|
+
for (const row of this.rows(collection).values()) {
|
|
131
|
+
if (row.id !== doc.id && isDeepStrictEqual(keyOf(index, row), key)) {
|
|
132
|
+
throw LatticeError.CONFLICT({ collection, id: doc.id });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async ensure(collection: string, indexes: readonly Index[]): Promise<void> {
|
|
139
|
+
const known = this.indexes.get(collection) ?? [];
|
|
140
|
+
const added: Index[] = [];
|
|
141
|
+
for (const index of indexes) {
|
|
142
|
+
const fields = Object.keys(index.fields).join(', ');
|
|
143
|
+
const existing = [...known, ...added].find((other) =>
|
|
144
|
+
sameKeys(other, index),
|
|
145
|
+
);
|
|
146
|
+
// Changing an index is a migration, so the same keys with other
|
|
147
|
+
// options reject, as MongoDB's IndexOptionsConflict does.
|
|
148
|
+
if (existing !== undefined) {
|
|
149
|
+
if ((existing.unique === true) !== (index.unique === true)) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
`MemoryStore: "${collection}" has an index on ${fields} with other options`,
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (index.unique === true && this.hasDuplicates(collection, index)) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`MemoryStore: "${collection}" has duplicates for the unique index on ${fields}`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
added.push(index);
|
|
162
|
+
}
|
|
163
|
+
this.indexes.set(collection, [...known, ...added]);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Whether two rows of `collection` share `index`'s key. */
|
|
167
|
+
private hasDuplicates(collection: string, index: Index): boolean {
|
|
168
|
+
const keys = [...this.rows(collection).values()].map((row) =>
|
|
169
|
+
keyOf(index, row),
|
|
170
|
+
);
|
|
171
|
+
return keys.some((key, i) =>
|
|
172
|
+
keys.slice(i + 1).some((other) => isDeepStrictEqual(key, other)),
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Snapshots every collection, runs `work`, and restores the snapshot when
|
|
178
|
+
* it throws. It does not isolate: a call made outside `work` while it
|
|
179
|
+
* runs sees its writes, and is lost too when it rolls back.
|
|
180
|
+
*/
|
|
181
|
+
async transaction<T>(
|
|
182
|
+
work: (store: CollectionStore) => Promise<T>,
|
|
183
|
+
): Promise<T> {
|
|
184
|
+
if (this.transacting) return work(this);
|
|
185
|
+
// Stored docs are never mutated in place, so copying the maps is enough.
|
|
186
|
+
const collections = new Map(
|
|
187
|
+
[...this.collections].map(([name, rows]) => [name, new Map(rows)]),
|
|
188
|
+
);
|
|
189
|
+
const indexes = new Map(
|
|
190
|
+
[...this.indexes].map(([name, list]) => [name, [...list]]),
|
|
191
|
+
);
|
|
192
|
+
this.transacting = true;
|
|
193
|
+
try {
|
|
194
|
+
return await work(this);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
this.collections = collections;
|
|
197
|
+
this.indexes = indexes;
|
|
198
|
+
throw error;
|
|
199
|
+
} finally {
|
|
200
|
+
this.transacting = false;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async count(collection: string, where?: AnyWhere): Promise<number> {
|
|
205
|
+
let count = 0;
|
|
206
|
+
for (const doc of this.rows(collection).values()) {
|
|
207
|
+
if (where === undefined || matches(doc, where)) count += 1;
|
|
208
|
+
}
|
|
209
|
+
return count;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private visible(
|
|
213
|
+
collection: string,
|
|
214
|
+
id: string,
|
|
215
|
+
where: AnyWhere | undefined,
|
|
216
|
+
): StoredDoc | undefined {
|
|
217
|
+
const doc = this.rows(collection).get(id);
|
|
218
|
+
if (doc === undefined) return undefined;
|
|
219
|
+
return where === undefined || matches(doc, where) ? doc : undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async find(query: FindQuery): Promise<Page> {
|
|
223
|
+
const order = orderOf(query.sort, query.optional);
|
|
224
|
+
const start =
|
|
225
|
+
query.after === undefined ? undefined : after(order, query.after);
|
|
226
|
+
const matching = [...this.rows(query.collection).values()]
|
|
227
|
+
.filter(
|
|
228
|
+
(doc) =>
|
|
229
|
+
(query.where === undefined || matches(doc, query.where)) &&
|
|
230
|
+
(start === undefined || matches(doc, start)),
|
|
231
|
+
)
|
|
232
|
+
.sort(compareDocs(order));
|
|
233
|
+
// One more than the page tells whether another page follows.
|
|
234
|
+
const window = matching.slice(0, query.limit + 1);
|
|
235
|
+
const docs = window.slice(0, query.limit);
|
|
236
|
+
const last = docs.at(-1);
|
|
237
|
+
return {
|
|
238
|
+
docs: docs.map((doc) => structuredClone(doc)),
|
|
239
|
+
next:
|
|
240
|
+
window.length > query.limit && last !== undefined
|
|
241
|
+
? encodeCursor(order, last)
|
|
242
|
+
: null,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async get(
|
|
247
|
+
collection: string,
|
|
248
|
+
id: string,
|
|
249
|
+
where?: AnyWhere,
|
|
250
|
+
): Promise<StoredDoc | null> {
|
|
251
|
+
const doc = this.visible(collection, id, where);
|
|
252
|
+
return doc === undefined ? null : structuredClone(doc);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async getMany(
|
|
256
|
+
collection: string,
|
|
257
|
+
ids: readonly string[],
|
|
258
|
+
where?: AnyWhere,
|
|
259
|
+
): Promise<StoredDoc[]> {
|
|
260
|
+
return ids.flatMap((id) => {
|
|
261
|
+
const doc = this.visible(collection, id, where);
|
|
262
|
+
return doc === undefined ? [] : [structuredClone(doc)];
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async insert(collection: string, doc: StoredDoc): Promise<void> {
|
|
267
|
+
const rows = this.rows(collection);
|
|
268
|
+
if (rows.has(doc.id)) {
|
|
269
|
+
throw LatticeError.CONFLICT({ collection, id: doc.id });
|
|
270
|
+
}
|
|
271
|
+
this.checkUnique(collection, doc);
|
|
272
|
+
rows.set(doc.id, structuredClone(doc));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async update(
|
|
276
|
+
collection: string,
|
|
277
|
+
id: string,
|
|
278
|
+
patch: Patch,
|
|
279
|
+
where?: AnyWhere,
|
|
280
|
+
): Promise<StoredDoc | null> {
|
|
281
|
+
const existing = this.visible(collection, id, where);
|
|
282
|
+
if (existing === undefined) return null;
|
|
283
|
+
const fields = Object.entries({ ...existing, ...patch }).filter(
|
|
284
|
+
([, value]) => value !== undefined,
|
|
285
|
+
);
|
|
286
|
+
const doc: StoredDoc = structuredClone({
|
|
287
|
+
...Object.fromEntries(fields),
|
|
288
|
+
id,
|
|
289
|
+
});
|
|
290
|
+
this.checkUnique(collection, doc);
|
|
291
|
+
this.rows(collection).set(id, doc);
|
|
292
|
+
return structuredClone(doc);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async remove(
|
|
296
|
+
collection: string,
|
|
297
|
+
id: string,
|
|
298
|
+
where?: AnyWhere,
|
|
299
|
+
): Promise<StoredDoc | null> {
|
|
300
|
+
const doc = this.visible(collection, id, where);
|
|
301
|
+
if (doc === undefined) return null;
|
|
302
|
+
this.rows(collection).delete(id);
|
|
303
|
+
return doc;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** An index's key for `doc`: its fields' values, a missing one as null. */
|
|
308
|
+
function keyOf(index: Index, doc: StoredDoc): unknown[] {
|
|
309
|
+
return Object.keys(index.fields).map((field) => doc[field] ?? null);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Whether two indexes have the same keys, in the same order and directions. */
|
|
313
|
+
function sameKeys(a: Index, b: Index): boolean {
|
|
314
|
+
return isDeepStrictEqual(Object.entries(a.fields), Object.entries(b.fields));
|
|
315
|
+
}
|
package/src/tenancy.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AnyCollection } from './collection.js';
|
|
3
|
+
import type { AnyWhere } from './where.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What `tenantOf` returns for a platform actor, such as support staff: the
|
|
7
|
+
* call reads across tenants. A bypass is read-only on tenanted collections,
|
|
8
|
+
* and each bypassed scope is logged (0024).
|
|
9
|
+
*/
|
|
10
|
+
const bypass: unique symbol = Symbol('lattice.tenancy.bypass');
|
|
11
|
+
|
|
12
|
+
/** What a family's `tenantOf` returns: a tenant id, or `tenancy.bypass`. */
|
|
13
|
+
export type Tenant = string | typeof bypass;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A collection's filter for one call: what `Repo` calls run under. It is the
|
|
17
|
+
* tenant clause ANDed with the access `Where`. `tenantId` is the tenant a
|
|
18
|
+
* write is stamped with: undefined for a global collection, and for a
|
|
19
|
+
* bypass, which cannot write a tenanted collection.
|
|
20
|
+
*/
|
|
21
|
+
export class Scope<Slug extends string = string> {
|
|
22
|
+
// A private field makes the type nominal: a plain object with the same
|
|
23
|
+
// fields is not a Scope, so no app can hand a repo a filter it made up.
|
|
24
|
+
readonly #scope = true;
|
|
25
|
+
|
|
26
|
+
constructor(
|
|
27
|
+
readonly collection: Slug,
|
|
28
|
+
readonly where: AnyWhere | undefined,
|
|
29
|
+
readonly tenantId: string | undefined,
|
|
30
|
+
) {
|
|
31
|
+
// Read once so noUnusedLocals keeps the brand, as hexok's Port does.
|
|
32
|
+
void this.#scope;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The tenant field of a collection with one, or never. */
|
|
37
|
+
export type TenantField<C extends { readonly tenant: string | undefined }> =
|
|
38
|
+
Exclude<C['tenant'], undefined>;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The tenant field's pieces, from its name: the `tenant` value a collection
|
|
42
|
+
* carries, the output shape that adds the field, and the event shape that
|
|
43
|
+
* adds `tenantId`. Each is empty without a tenant. The overload states the
|
|
44
|
+
* key and the conditional types; a computed key types as an index
|
|
45
|
+
* signature.
|
|
46
|
+
*/
|
|
47
|
+
export function tenantShapes<T extends string>(
|
|
48
|
+
tenant: T | undefined,
|
|
49
|
+
): {
|
|
50
|
+
readonly tenant: [T] extends [never] ? undefined : T;
|
|
51
|
+
readonly field: Record<T, z.ZodString>;
|
|
52
|
+
readonly event: [T] extends [never]
|
|
53
|
+
? Record<never, never>
|
|
54
|
+
: { tenantId: z.ZodString };
|
|
55
|
+
};
|
|
56
|
+
export function tenantShapes(tenant: string | undefined): {
|
|
57
|
+
readonly tenant: string | undefined;
|
|
58
|
+
readonly field: Record<string, z.ZodString>;
|
|
59
|
+
readonly event: Record<string, z.ZodString>;
|
|
60
|
+
} {
|
|
61
|
+
return tenant === undefined
|
|
62
|
+
? { tenant, field: {}, event: {} }
|
|
63
|
+
: {
|
|
64
|
+
tenant,
|
|
65
|
+
// The meta says which field is the tenant's, so a client such as
|
|
66
|
+
// the admin shows it read-only without guessing.
|
|
67
|
+
field: { [tenant]: z.string().meta({ 'x-lattice-tenant': true }) },
|
|
68
|
+
event: { tenantId: z.string() },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The filter that keeps a call inside one tenant, or none. */
|
|
73
|
+
export function tenantClause(
|
|
74
|
+
collection: AnyCollection,
|
|
75
|
+
tenant: Tenant | undefined,
|
|
76
|
+
): AnyWhere | undefined {
|
|
77
|
+
const field = collection.tenant;
|
|
78
|
+
if (field === undefined || tenant === undefined || tenant === bypass) {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
return { [field]: { eq: tenant } };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* `record` without `collection`'s tenant field. Update writes only the
|
|
86
|
+
* schema's fields: the tenant is stamped once, on create.
|
|
87
|
+
*/
|
|
88
|
+
export function withoutTenant(
|
|
89
|
+
collection: AnyCollection,
|
|
90
|
+
record: Readonly<Record<string, unknown>>,
|
|
91
|
+
): Record<string, unknown> {
|
|
92
|
+
const { tenant } = collection;
|
|
93
|
+
return Object.fromEntries(
|
|
94
|
+
Object.entries(record).filter(([key]) => key !== tenant),
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A collection with a tenant field. */
|
|
99
|
+
type Tenanted = AnyCollection & { readonly tenant: string };
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The scope of server code that works inside one tenant, such as an event
|
|
103
|
+
* handler: the tenant clause and no access. Writes through it are stamped
|
|
104
|
+
* with `tenantId`.
|
|
105
|
+
*/
|
|
106
|
+
function scope<C extends Tenanted>(
|
|
107
|
+
collection: C,
|
|
108
|
+
tenantId: string,
|
|
109
|
+
): Scope<C['slug']> {
|
|
110
|
+
if (collection.tenant === undefined) {
|
|
111
|
+
throw new Error(`Lattice: "${collection.slug}" has no tenant field`);
|
|
112
|
+
}
|
|
113
|
+
return new Scope(
|
|
114
|
+
collection.slug,
|
|
115
|
+
tenantClause(collection, tenantId),
|
|
116
|
+
tenantId,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Tenancy for server code: the platform bypass, and a tenant's scope. */
|
|
121
|
+
export const tenancy: {
|
|
122
|
+
readonly bypass: typeof bypass;
|
|
123
|
+
readonly scope: typeof scope;
|
|
124
|
+
} = { bypass, scope };
|
package/src/tracing.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { type Span, SpanStatusCode, trace } from '@opentelemetry/api';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
// The package's own version, read from its package.json at runtime, so the
|
|
6
|
+
// tracer's version never drifts from the release. src/ and dist/ both sit
|
|
7
|
+
// one level below it.
|
|
8
|
+
const { version } = z
|
|
9
|
+
.object({ version: z.string() })
|
|
10
|
+
.parse(createRequire(import.meta.url)('../package.json'));
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The package's tracer. With no OpenTelemetry SDK registered it is the
|
|
14
|
+
* API's no-op, so tracing costs nothing until an app registers one.
|
|
15
|
+
*/
|
|
16
|
+
export const tracer = trace.getTracer('@latticecms/core', version);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Marks `span` as failed by `error`, an unexpected throw: status ERROR, the
|
|
20
|
+
* error's type, and an exception event. A refusal is never marked so.
|
|
21
|
+
*/
|
|
22
|
+
export function failed(span: Span, error: unknown): void {
|
|
23
|
+
span.setAttributes({
|
|
24
|
+
'lattice.outcome': 'failed',
|
|
25
|
+
'error.type': error instanceof Error ? error.name : typeof error,
|
|
26
|
+
});
|
|
27
|
+
span.recordException(error instanceof Error ? error : String(error));
|
|
28
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
29
|
+
}
|