@cogover/sdk 0.12.2 → 0.14.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.
@@ -6,9 +6,10 @@ This page is part of the [`@cogover/sdk` API reference](overview.md).
6
6
 
7
7
  ```typescript
8
8
  const orders = data.object("order");
9
- await orders.records.get(id, { fields });
10
- await orders.records.getMany(ids, { fields });
11
- await orders.records.list({ where, orderBy, fields, limit, cursor });
9
+ await orders.records.get(id, { fields, expandLookups });
10
+ await orders.records.getMany(ids, { fields, expandLookups });
11
+ await orders.records.list({ where, orderBy, fields, limit, cursor, expandLookups });
12
+ await orders.records.aggregate({ where, groupBy, metrics, limit });
12
13
  await orders.records.create(fields);
13
14
  await orders.records.update(id, fields);
14
15
  await orders.records.batchInsert(records);
@@ -17,6 +18,10 @@ await orders.records.upsertByUniqueField(matchBy, fields);
17
18
  await orders.records.deleteMany(ids);
18
19
  ```
19
20
 
21
+ Every read names the fields it returns: `fields` is required by `get`, `getMany`, and
22
+ `list` (see [Choosing fields](#choosing-fields)). Lookups are not expanded unless the
23
+ read asks for it with `expandLookups` (see [Linked records](#linked-records)).
24
+
20
25
  ### Record values and results
21
26
 
22
27
  ```typescript
@@ -26,8 +31,13 @@ type CogoverRecordId = string & {
26
31
 
27
32
  interface RecordReference<ObjectSlug extends string = string> {
28
33
  readonly id: CogoverRecordId;
34
+ // "" unless the read expanded this lookup; a `reference` field keeps its stored name.
29
35
  readonly name: string;
30
36
  readonly objectSlug?: ObjectSlug;
37
+ // Present only when the read expanded this lookup and the linked record could be read.
38
+ readonly fields?: ObjectSlug extends keyof WorkspaceObjects
39
+ ? Readonly<Partial<WorkspaceObjects[ObjectSlug]>>
40
+ : Readonly<Record<string, unknown>>;
31
41
  }
32
42
 
33
43
  interface UrlValue {
@@ -49,6 +59,7 @@ interface CogoverRecord<Fields> {
49
59
  readonly system: {
50
60
  readonly createdAt: number;
51
61
  readonly updatedAt: number;
62
+ // `name` is "" unless the read used `expandLookups`.
52
63
  readonly createdBy?: { readonly id: string; readonly name: string };
53
64
  };
54
65
  }
@@ -111,20 +122,116 @@ and non-null.
111
122
  ### Data clients and operations
112
123
 
113
124
  ```typescript
114
- interface GetRecordOptions<Fields> {
115
- readonly fields?: readonly (keyof Fields & string)[];
125
+ type FieldSelection<Fields> = "*" | readonly (keyof Fields & string)[];
126
+
127
+ type SelectedFields<Fields, Selection extends FieldSelection<Fields>> =
128
+ Selection extends "*" ? Fields
129
+ : Selection extends readonly (infer Slug)[] ? Pick<Fields, Slug & keyof Fields>
130
+ : Fields;
131
+
132
+ type ExpandLookups<Fields> =
133
+ | boolean
134
+ | {
135
+ // LookupFieldSlug: the lookup and reference fields of Fields. LinkedFieldSlug: the field
136
+ // slugs of the linked Object, or any string when that Object is not declared.
137
+ readonly [Slug in LookupFieldSlug<Fields>]?: "*" | readonly LinkedFieldSlug<Fields[Slug]>[];
138
+ };
139
+
140
+ interface GetRecordOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
141
+ readonly fields: Selection;
142
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
116
143
  }
117
144
 
118
- interface GetManyOptions<Fields> {
119
- readonly fields: readonly (keyof Fields & string)[];
145
+ interface GetManyOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
146
+ readonly fields: Selection;
147
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
120
148
  }
121
149
 
122
- interface ListOptions<Fields> {
150
+ interface ListOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
123
151
  readonly where?: FilterExpression;
124
152
  readonly orderBy?: readonly SortExpression[];
125
- readonly fields?: readonly (keyof Fields & string)[];
153
+ readonly fields: Selection;
126
154
  readonly limit?: number;
127
155
  readonly cursor?: string;
156
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
157
+ }
158
+
159
+ type AggregateMetric<Fields> =
160
+ | { readonly count: "id" | CountableFieldSlug<Fields> }
161
+ | { readonly countDistinct: CountableFieldSlug<Fields> }
162
+ | { readonly sum: NumberFieldSlug<Fields> }
163
+ | { readonly avg: NumberFieldSlug<Fields> }
164
+ | { readonly min: NumberOrTextFieldSlug<Fields> }
165
+ | { readonly max: NumberOrTextFieldSlug<Fields> };
166
+ // CountableFieldSlug: every field except file and URL fields. NumberFieldSlug: the fields
167
+ // typed `number`. NumberOrTextFieldSlug: the fields typed `number` or `string` (a `date` is
168
+ // a string). Each is any string when Fields is not declared.
169
+
170
+ type AsUserAggregateMetric<Fields> =
171
+ | { readonly count: "id" | NumberFieldSlug<Fields> }
172
+ | { readonly sum: NumberFieldSlug<Fields> }
173
+ | { readonly avg: NumberFieldSlug<Fields> }
174
+ | { readonly min: NumberFieldSlug<Fields> }
175
+ | { readonly max: NumberFieldSlug<Fields> };
176
+
177
+ type AggregateMetrics<Fields> = Readonly<Record<string, AggregateMetric<Fields>>>;
178
+ type AsUserAggregateMetrics<Fields> = Readonly<Record<string, AsUserAggregateMetric<Fields>>>;
179
+
180
+ interface AggregateOptions<
181
+ Fields,
182
+ Metrics extends AggregateMetrics<Fields> | AsUserAggregateMetrics<Fields> = AggregateMetrics<Fields>,
183
+ > {
184
+ readonly where?: FilterExpression;
185
+ readonly metrics: Metrics;
186
+ readonly groupBy?: never;
187
+ readonly limit?: never;
188
+ }
189
+
190
+ interface GroupedAggregateOptions<
191
+ Fields,
192
+ Metrics extends AggregateMetrics<Fields> = AggregateMetrics<Fields>,
193
+ GroupBy extends readonly (keyof Fields & string)[] = readonly (keyof Fields & string)[],
194
+ > {
195
+ readonly where?: FilterExpression;
196
+ readonly groupBy: GroupBy;
197
+ readonly metrics: Metrics;
198
+ readonly limit?: number;
199
+ }
200
+
201
+ type AggregateValues<Metrics> = {
202
+ readonly [Name in keyof Metrics]:
203
+ Metrics[Name] extends
204
+ | { readonly count: string }
205
+ | { readonly countDistinct: string }
206
+ | { readonly sum: string }
207
+ ? number
208
+ : number | null;
209
+ };
210
+
211
+ type AggregateGroupKey<Fields, Slug extends keyof Fields & string> = {
212
+ // CogoverRecordId for a lookup, the option slug for a choice, boolean, number, and
213
+ // epoch milliseconds (`number`) for a date: text cannot be grouped, so a `string` field is a date.
214
+ readonly [K in Slug]: GroupKeyValue<Fields[K]>;
215
+ };
216
+
217
+ interface AggregateResult<Values = Readonly<Record<string, number | null>>> {
218
+ readonly values: Values;
219
+ }
220
+
221
+ interface AggregateGroup<
222
+ Key = Readonly<Record<string, string | number | boolean>>,
223
+ Values = Readonly<Record<string, number | null>>,
224
+ > {
225
+ readonly key: Key;
226
+ readonly values: Values;
227
+ }
228
+
229
+ interface AggregateGroupResult<
230
+ Key = Readonly<Record<string, string | number | boolean>>,
231
+ Values = Readonly<Record<string, number | null>>,
232
+ > {
233
+ readonly groups: AggregateGroup<Key, Values>[];
234
+ readonly truncated: boolean;
128
235
  }
129
236
 
130
237
  interface RecordWritesApi<Fields> {
@@ -139,10 +246,33 @@ interface RecordWritesApi<Fields> {
139
246
  deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
140
247
  }
141
248
 
142
- interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
143
- get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
144
- getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
145
- list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
249
+ interface AsUserRecordsApi<Fields> extends RecordWritesApi<Fields> {
250
+ get<const Selection extends FieldSelection<Fields>>(
251
+ id: string,
252
+ options: GetRecordOptions<Fields, Selection>,
253
+ ): Promise<CogoverRecord<SelectedFields<Fields, Selection>> | null>;
254
+ getMany<const Selection extends FieldSelection<Fields>>(
255
+ ids: readonly string[],
256
+ options: GetManyOptions<Fields, Selection>,
257
+ ): Promise<GetManyResult<SelectedFields<Fields, Selection>>>;
258
+ list<const Selection extends FieldSelection<Fields>>(
259
+ options: ListOptions<Fields, Selection>,
260
+ ): Promise<RecordPage<SelectedFields<Fields, Selection>>>;
261
+ aggregate<const Metrics extends AsUserAggregateMetrics<Fields>>(
262
+ options: AggregateOptions<Fields, Metrics>,
263
+ ): Promise<AggregateResult<AggregateValues<Metrics>>>;
264
+ }
265
+
266
+ interface RecordsApi<Fields> extends AsUserRecordsApi<Fields> {
267
+ aggregate<const Metrics extends AggregateMetrics<Fields>>(
268
+ options: AggregateOptions<Fields, Metrics>,
269
+ ): Promise<AggregateResult<AggregateValues<Metrics>>>;
270
+ aggregate<
271
+ const Metrics extends AggregateMetrics<Fields>,
272
+ const GroupBy extends readonly (keyof Fields & string)[],
273
+ >(
274
+ options: GroupedAggregateOptions<Fields, Metrics, GroupBy>,
275
+ ): Promise<AggregateGroupResult<AggregateGroupKey<Fields, GroupBy[number]>, AggregateValues<Metrics>>>;
146
276
  }
147
277
 
148
278
  interface WriteObjectClient<Fields> {
@@ -155,8 +285,12 @@ interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
155
285
  readonly records: RecordsApi<Fields>;
156
286
  }
157
287
 
288
+ interface AsUserObjectClient<Fields> extends WriteObjectClient<Fields> {
289
+ readonly records: AsUserRecordsApi<Fields>;
290
+ }
291
+
158
292
  interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
159
- object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
293
+ object<Slug extends keyof Schema & string>(slug: Slug): AsUserObjectClient<Schema[Slug]>;
160
294
  }
161
295
 
162
296
  interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
@@ -171,7 +305,7 @@ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
171
305
  `system` object containing creation/update metadata.
172
306
 
173
307
  `getMany(ids, { fields })` reads up to 200 records by ID with a single capability
174
- call. `fields` is required and must be a non-empty list of field slugs. IDs are
308
+ call. `fields` is required, as for every read (see [Choosing fields](#choosing-fields)). IDs are
175
309
  trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
176
310
  ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
177
311
  An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
@@ -186,12 +320,18 @@ const { records, missingIds } = await accounts.records.getMany(accountIds, { fie
186
320
  const accountById = new Map(records.map(record => [record.id, record]));
187
321
  ```
188
322
 
189
- Use `getMany` instead of calling `get` in a loop. Every capability call counts
190
- towards the project's limits, and a record trigger can receive 200 records at once.
323
+ Use `getMany` instead of calling `get` in a loop. Every capability call and every record
324
+ read counts towards the budgets of the execution (see
325
+ [Execution limits](overview.md#execution-limits)), and a record trigger can receive 200
326
+ records at once.
191
327
 
192
- Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
193
- responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
194
- `RecordReference` and send only the ID to Cogover.
328
+ Service `0`/`1` booleans are normalized to JavaScript booleans. A lookup or reference
329
+ value is a `RecordReference` with `id`, `name`, and `objectSlug`. Its `name` is `""`
330
+ unless the read expanded the lookup, except in a `reference` field, which stores the
331
+ name with the record; an expanded value also has the linked record's `fields` (see
332
+ [Linked records](#linked-records)). The `new` and `old` values of a
333
+ [record trigger](record-triggers.md) always carry lookup names. Writes accept an ID or
334
+ a `RecordReference` and send only the ID to Cogover.
195
335
 
196
336
  A `file` field is read as `FileValue` objects: one `FileValue`, or `null`, for a
197
337
  single file field and an array for a multiple one. `url` is present only when Cogover
@@ -207,6 +347,208 @@ milliseconds. Writes accept the same forms and also an ISO 8601 string, which is
207
347
  field as its UTC day. Other text for these fields throws `ValidationError` with
208
348
  `details.reason` `"INVALID_FIELD_VALUE"`.
209
349
 
350
+ ### Choosing fields
351
+
352
+ `get`, `getMany`, and `list` return only the fields named in `fields`, so a read
353
+ costs no more than what the script uses. `fields` is required and is one of:
354
+
355
+ - a non-empty list of field slugs, trimmed and deduplicated in their original order;
356
+ - the string `"*"` on its own: every field that the identity in use may read. With
357
+ `data.asUser()` or `data.asSystem()` it is limited to the fields that the project's
358
+ identity policy grants: when the policy grants only some fields, `"*"` means those
359
+ fields, not every field of the Object.
360
+
361
+ Leaving `fields` out, or passing `null`, an empty list, `["*"]`, or a value that is not
362
+ a field slug, throws `ValidationError` before any request is sent, with this message:
363
+
364
+ ```text
365
+ fields is required: pass field slugs or "*" (@cogover/sdk 0.13.0+)
366
+ ```
367
+
368
+ Cogover refuses such a read with the same message, so a project version published with
369
+ an older SDK that reads without `fields` fails the same way: add `fields` to its reads
370
+ and publish it again.
371
+
372
+ The system slugs `id`, `created`, `updated`, and `created_by` may be listed; their
373
+ values are always returned in `id` and `system`, not in `fields`. `where` and `orderBy`
374
+ may use fields that are not in `fields`. With `data.asUser()` or `data.asSystem()`,
375
+ every field of `fields`, `where`, and `orderBy` must be granted by the project's identity
376
+ policy, otherwise the read throws `PermissionDeniedError`; reads through `data.object()`
377
+ need no policy and follow the permissions of the identity in use. A slug that the Object
378
+ does not have throws `ValidationError`.
379
+
380
+ The result type follows `fields`. With workspace declarations, `fields: ["code",
381
+ "amount"]` returns `CogoverRecord<Pick<Fields, "code" | "amount">>`, so reading a field
382
+ that was not requested is a compile error, and `"*"` returns every declared field:
383
+
384
+ ```typescript
385
+ const order = await orders.records.get(orderId, { fields: ["code", "amount"] });
386
+ const amount = order?.fields.amount; // number | null | undefined
387
+ // order?.fields.status would not compile: `status` was not requested.
388
+ const full = await orders.records.get(orderId, { fields: "*" });
389
+ ```
390
+
391
+ A capability result is limited to 1,048,576 bytes (see
392
+ [Execution limits](overview.md#execution-limits)). `"*"` on an Object with many or long
393
+ fields can exceed it, particularly with `getMany` or a `list` page of 200 records; the
394
+ call then throws `ValidationError` with `details.limit`. Name the fields the script
395
+ needs, or read fewer records per call.
396
+
397
+ ### Linked records
398
+
399
+ A read does not look up the records that its lookup fields point to unless it asks for
400
+ them:
401
+
402
+ - a `lookup_normal` value is `{ id, name: "", objectSlug }`, or an array of them for a
403
+ multiple lookup;
404
+ - a `reference` value keeps its `name`, which the record stores;
405
+ - `system.createdBy` is `{ id, name: "" }`.
406
+
407
+ Set `expandLookups` when the script needs the names or fields of the linked records:
408
+
409
+ ```typescript
410
+ const page = await orders.records.list({
411
+ fields: ["code", "customer", "owner"],
412
+ expandLookups: { customer: ["credit_limit", "tier"], owner: "*" },
413
+ limit: 50,
414
+ });
415
+ const customer = page.items[0]?.fields.customer;
416
+ // { id: "...", name: "ABC Company", objectSlug: "account",
417
+ // fields: { credit_limit: 5000000, tier: "gold" } }
418
+ ```
419
+
420
+ - `true` expands every lookup and reference field among the returned fields, each with
421
+ `"*"` of the linked Object.
422
+ - An object expands only the fields it names. Each key must be a lookup or reference
423
+ field that is also in `fields`; its value is `"*"` or a non-empty list of field slugs
424
+ of the linked Object.
425
+ - `false`, or leaving it out, expands nothing.
426
+
427
+ An expanded value is `{ id, name, objectSlug, fields }`, where `fields` holds the
428
+ selected fields of the linked record. With workspace declarations, the `fields` of a
429
+ `RecordReference<"account">` are typed as a partial of the `account` fields. When
430
+ `expandLookups` is present, `system.createdBy.name` is also filled in with the `name`
431
+ field of the creator's personnel record, which can be a generated code rather than the
432
+ person's full name; for display names, use
433
+ [`org.personnel.get`](organization-structure.md#orgpersonnelgetid-options-and-orgpersonnelgetmanyids-options)
434
+ with `withDisplay: true`.
435
+
436
+ Linked records are read with the same identity as the read itself: the caller,
437
+ `data.asUser()`, or `data.asSystem()`. With `data.object()` the linked records follow
438
+ the permissions of the identity in use. With `data.asUser()` or `data.asSystem()`, the
439
+ project's identity policy must also grant reading the linked Object:
440
+
441
+ - With `true` or `"*"`, only the linked fields that the policy grants are returned.
442
+ When the policy does not grant reading the linked Object, its values stay
443
+ unexpanded.
444
+ - With a list of fields, every listed field must be granted, otherwise the read throws
445
+ `PermissionDeniedError` whose `details.objectSlug` is the linked Object and, for a field
446
+ that is not granted, `details.fieldSlug` is that field; a slug that the linked Object
447
+ does not have throws `ValidationError`.
448
+ - A linked record that cannot be read, because the identity may not see it or it was
449
+ deleted, stays unexpanded, without `fields`.
450
+
451
+ An unexpanded value is `{ id, name: "", objectSlug }` in a lookup field; in a
452
+ `reference` field it keeps the name that the record stores.
453
+
454
+ Only one level is expanded: lookups inside a linked record's `fields` are
455
+ `{ id, name: "", objectSlug }`. One call expands at most 1,000 distinct linked records;
456
+ more throws `ValidationError` (`expandLookups can resolve at most 1000 linked records per
457
+ call`) and nothing is read. The read is still one capability call, but Cogover reads
458
+ every linked Object as well, which takes time: expand only the lookups whose names or
459
+ fields the script uses. The result, linked records included, must fit in the
460
+ 1,048,576-byte limit.
461
+
462
+ An `expandLookups` value of the wrong shape throws `ValidationError` before any request
463
+ is sent: an empty object, a key that is not a field slug or is not in `fields`, or a
464
+ value that is neither `"*"` nor a non-empty list of field slugs.
465
+
466
+ ### Aggregates
467
+
468
+ `records.aggregate(options)` counts, sums, averages, and finds the smallest and largest
469
+ values of the records that match `where`, in one capability call and without reading
470
+ the records:
471
+
472
+ ```typescript
473
+ const totals = await orders.records.aggregate({
474
+ where: orders.fields.status.eq("paid"),
475
+ metrics: { orders: { count: "id" }, revenue: { sum: "amount" } },
476
+ });
477
+ // { values: { orders: 120, revenue: 530000000 } }
478
+
479
+ const byStatus = await orders.records.aggregate({
480
+ groupBy: ["status"],
481
+ metrics: { orders: { count: "id" }, revenue: { sum: "amount" } },
482
+ limit: 100,
483
+ });
484
+ // { groups: [{ key: { status: "paid" }, values: { orders: 120, revenue: 530000000 } }],
485
+ // truncated: false }
486
+ ```
487
+
488
+ `metrics` names 1 to 20 metrics. A metric name is a letter followed by up to 63
489
+ letters, digits, or underscores, and each metric is exactly one of:
490
+
491
+ | Metric | Field | Value |
492
+ |---|---|---|
493
+ | `{ count: "id" }` | | number of matching records |
494
+ | `{ count: field }` | number, date, choice, `boolean`, `lookup_normal`, text, `email`, `phone`, and `auto_number` fields; not `reference`, `file`, `url`, `formula`, or `rollup_summary` | number of matching records with a value in the field |
495
+ | `{ countDistinct: field }` | the fields that `count` accepts | number of distinct values, approximate on large sets |
496
+ | `{ sum: field }` | `numeric`, `decimal`, `currency`, `percent` | sum |
497
+ | `{ avg: field }` | the number types above | average; `null` when no matching record has a value |
498
+ | `{ min: field }`, `{ max: field }` | the number types above, `date`, `date_time` | smallest or largest value; `null` when no matching record has a value; epoch milliseconds for a date |
499
+
500
+ Counts and sums are `0` when no record matches.
501
+
502
+ `where` works as in `list`. Without `groupBy`, the result is `{ values }` with one value
503
+ per metric name. With `groupBy`, a list of 1 to 3 field slugs, the result is
504
+ `{ groups, truncated }`: one `{ key, values }` entry for each combination of values,
505
+ the groups with the most records first. `groupBy` accepts fields of type
506
+ `single_choice`, `multi_choices`, `radio_button`, `checkbox`, `boolean`,
507
+ `lookup_normal`, `date`, `date_time`, `numeric`, `decimal`, `currency`, and `percent`;
508
+ another field, such as a text or `reference` field, throws `ValidationError`. `key` maps
509
+ each `groupBy` field to its value: the record ID for a lookup, the option slug for a
510
+ choice, `true` or `false`, a number, or epoch milliseconds for a `date` or `date_time`.
511
+ A key value is never `null`: a record without a value in a `groupBy` field is in no
512
+ group.
513
+
514
+ `limit`, accepted only with `groupBy`, is the most groups to return: 1 to 5,000, and
515
+ 1,000 when it is left out. `truncated` is `true` when there were more groups and only
516
+ the first `limit` are returned.
517
+
518
+ With `data.asUser()` or `data.asSystem()`, every field of `where`, `groupBy`, and
519
+ `metrics`, except `"id"`, must be granted by the project's identity policy, otherwise the
520
+ call throws `PermissionDeniedError`. Only the records that the identity in use can see are
521
+ counted.
522
+
523
+ A client from `data.asUser()` has narrower limits:
524
+
525
+ - It cannot group. Its type does not accept `groupBy`, and passing it anyway throws
526
+ `ValidationError` (`aggregate with groupBy is not supported for asUser(); use the
527
+ caller or asSystem()`).
528
+ - Its metrics are `count` on `"id"`, and `count`, `sum`, `avg`, `min`, and `max` on
529
+ number fields (`AsUserAggregateMetric`). Another metric throws `ValidationError`
530
+ (`metrics.<name>: asUser() without groupBy supports only count on id and count, sum,
531
+ avg, min and max on number fields; use the caller or asSystem()`).
532
+
533
+ The same limits apply to `data.object()` when the execution reads as a user who is not
534
+ an HTTP caller: in a record trigger for a change made by a user, in a job run that has
535
+ a user, or in a local Development Session started by `cogover-dev run`. Grouping
536
+ there throws `ValidationError` (`aggregate with groupBy is not supported for the default
537
+ identity of this invocation, which reads as a delegated user; use asSystem()`). Use
538
+ `data.asSystem()` there, or the caller in an HTTP route, for groups and the other
539
+ metrics.
540
+
541
+ Invalid options throw `ValidationError` before any request is sent: no metric or more
542
+ than 20, an invalid metric name, a metric that is not exactly one of the forms above,
543
+ an empty `groupBy` or one with more than 3 fields, `limit` without `groupBy`, or a
544
+ `limit` outside 1 to 5,000.
545
+
546
+ Aggregates are computed from a search index that follows record writes after a short
547
+ delay, usually about one second, so a record written just before may not be counted
548
+ yet. `aggregate` is allowed in a before-change record trigger, but the user's write
549
+ waits while it runs: keep such calls few, and do not rely on them to see the records
550
+ being written.
551
+
210
552
  ## Filters and sorting
211
553
 
212
554
  ```typescript
@@ -295,9 +637,9 @@ maps each field slug (`$record` for the whole record) to the trigger's error cod
295
637
  the others are still deleted, the rejected IDs are in `notDeleted`, and
296
638
  `recordErrors` maps each rejected ID to `{ reason: "TRIGGER_REJECTED", fieldErrors?,
297
639
  messages? }`. When the trigger rejects every record, nothing is deleted and the call
298
- throws `ValidationError` with `details.reason` `"TRIGGER_REJECTED"`. Record IDs, object slugs, the field slugs of `getMany`, and the
299
- `matchBy` of `upsertByUniqueField` are validated before a request is sent; Cogover
300
- checks the other field slugs.
640
+ throws `ValidationError` with `details.reason` `"TRIGGER_REJECTED"`. Record IDs, object slugs, the options of `get`,
641
+ `getMany`, `list`, and `aggregate`, and the `matchBy` of `upsertByUniqueField` are
642
+ validated before a request is sent; Cogover checks that the field slugs exist.
301
643
 
302
644
  A field value that Cogover refuses throws `ValidationError` whose `details` name the
303
645
  field in `fieldSlug`: `details.reason` is `"REQUIRED_FIELD_MISSING"` for a required
@@ -326,15 +668,16 @@ invocation this is the caller; a system invocation keeps system access.
326
668
 
327
669
  Returns a new immutable client for reads and writes as the specified personnel ID (not an
328
670
  account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
329
- value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
330
- whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
331
- `deleteMany` as well as batch insert, batch update, and business upsert, with the
332
- same argument and return types as the default record API.
333
-
334
- `get(id, options?)` returns `CogoverRecord<TFields> | null`; `list(options?)` returns
335
- `RecordPage<TFields>`. Field selection, filters, sorting and cursors work as on the
336
- default client. Reads apply the selected user's permissions and approved project
337
- field restrictions. An empty successful lookup returns `null`; server failures
671
+ value throws `ValidationError`. Its `object(slug)` returns `AsUserObjectClient<TFields>`,
672
+ whose `records: AsUserRecordsApi<TFields>` exposes `get`, `getMany`, `list`, `aggregate`,
673
+ `create`, `update`, and `deleteMany` as well as batch insert, batch update, and business
674
+ upsert, with the same argument and return types as the default record API, except that
675
+ its `aggregate` cannot group.
676
+
677
+ `get(id, options)` returns the record or `null`, and `list(options)` returns a
678
+ `RecordPage`, both narrowed to `fields`. Field selection, `expandLookups`, filters,
679
+ sorting and cursors work as on the default client. Reads, linked records included,
680
+ apply the selected user's permissions and approved project field restrictions. An empty successful lookup returns `null`; server failures
338
681
  throw errors instead of being treated as missing records or an empty page.
339
682
 
340
683
  ```typescript
@@ -350,8 +693,8 @@ const page = await delegatedOrders.records.list({
350
693
  ### `data.asSystem(): DataApi<TSchema>`
351
694
 
352
695
  Returns a new immutable client for system record access, including during an
353
- authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
354
- `deleteMany`, including batch writes and business upsert. System access does not
696
+ authenticated public invocation. It supports `get`, `getMany`, `list`, `aggregate` (with
697
+ groups), `create`, `update`, and `deleteMany`, including batch writes and business upsert. System access does not
355
698
  apply the caller's record permissions; approved project restrictions, field
356
699
  validation, workspace boundaries, and runtime limits still apply. It neither
357
700
  changes the invocation's caller nor modifies existing clients.
@@ -443,5 +786,14 @@ types as follows:
443
786
  | unknown field type | `unknown` |
444
787
 
445
788
  Fields that are not required include `null`; metadata marked `multiple` becomes a
446
- readonly array unless its base type is already an array. Add the generated file to
789
+ readonly array unless its base type is already an array. When a lookup's target Object
790
+ is declared too, the `fields` of its `RecordReference` are typed from that Object, and
791
+ `expandLookups` accepts only that Object's field slugs. Add the generated file to
447
792
  the project's TypeScript compilation and do not edit it manually.
793
+
794
+ The generated file imports the SDK types that its fields use (`RecordReference`,
795
+ `FileValue`, `UrlValue`) with `import type`. A file generated by `@cogover/sdk` before
796
+ 0.13.0 did not import them: with `skipLibCheck: false` it fails with `Cannot find name
797
+ 'RecordReference'`, and with `skipLibCheck: true` its lookup, file, and URL fields are
798
+ silently typed `any`, which also disables the checks on `fields`, `expandLookups`, and
799
+ `aggregate` for them. Generate such a file again.
@@ -6,8 +6,8 @@ This page is part of the [`@cogover/sdk` API reference](overview.md).
6
6
 
7
7
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
8
8
  the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
9
- `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
10
- result.
9
+ `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, and `limits`, awaits the handler, and
10
+ serializes its result.
11
11
 
12
12
  ```typescript
13
13
  function defineScript<
@@ -44,6 +44,7 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
44
44
  readonly secrets: SecretsApi;
45
45
  readonly crypto: CryptoApi;
46
46
  readonly org: OrgApi;
47
+ readonly limits: LimitsApi;
47
48
  }
48
49
  ```
49
50
 
@@ -54,8 +55,9 @@ Returning `null` produces a null handler result; returning `undefined` is invali
54
55
  ## HTTP routers and request context
55
56
 
56
57
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
57
- `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
58
- and route handlers. `input`
58
+ `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, and `limits` to
59
+ both script and route handlers. `limits` reads the budgets of the execution (see
60
+ [Reading limits in code](overview.md#reading-limits-in-code)). `input`
59
61
  preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
60
62
  metadata and transport/authentication fields removed by Cogover.
61
63
 
@@ -71,6 +71,9 @@ expiry. Both option values must be safe integers. `expectedVersion` enables
71
71
  compare-and-set: `0` means create only, a positive value must match the current
72
72
  version, and omission is an unconditional upsert.
73
73
  Conflicts throw `StateConflictError`; the returned entry has the new version.
74
+ A project keeps at most 100,000 unexpired entries: a `set` that would create another
75
+ throws `RateLimitError` and writes nothing, while updates of existing keys still work.
76
+ Expired entries are removed automatically and do not count.
74
77
 
75
78
  A version counts the writes since the entry was created. After `delete` or expiry, the
76
79
  next `set` creates a new entry whose version starts again at 1, so a version seen