@cogover/sdk 0.12.1 → 0.13.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 CHANGED
@@ -11,7 +11,8 @@ documentation, and type checking.
11
11
  ## Requirements
12
12
 
13
13
  - Node.js 18 or later.
14
- - A TypeScript project using ECMAScript Modules (ESM).
14
+ - A TypeScript project using ECMAScript Modules (ESM), type checked with TypeScript 5.0
15
+ or later.
15
16
 
16
17
  ## Installation
17
18
 
@@ -149,7 +150,8 @@ export const triggers = [
149
150
  ];
150
151
  ```
151
152
 
152
- `record.new` and `record.old` contain only the listed `fields`. Assign fields of
153
+ `record.new` and `record.old` contain only the listed `fields`, and their lookup
154
+ values carry the linked record's name. Assign fields of
153
155
  `record.new` to change what is saved: only `writableFields` may change, and values
154
156
  use the same format as `records.update` input. `record.addError(field, code,
155
157
  message?)` rejects a record; the optional English message is shown to the end user
@@ -348,16 +350,37 @@ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key"
348
350
  ## Record API
349
351
 
350
352
  An Object client exposes `records.get`, `records.getMany`, `records.list`,
351
- `records.create`, `records.update`, `records.batchInsert`, `records.batchUpdate`,
352
- `records.upsertByUniqueField`, and `records.deleteMany`. List filters are built from typed
353
- field references, so scripts do not provide transport-specific field metadata or
354
- response envelopes.
353
+ `records.aggregate`, `records.create`, `records.update`, `records.batchInsert`,
354
+ `records.batchUpdate`, `records.upsertByUniqueField`, and `records.deleteMany`. List
355
+ filters are built from typed field references, so scripts do not provide
356
+ transport-specific field metadata or response envelopes.
357
+
358
+ Every read names the fields it needs: `fields` is required by `get`, `getMany`, and
359
+ `list`, either as a list of field slugs or as `"*"` for every field that the identity
360
+ in use and the project's identity policy may read. A read without `fields` throws
361
+ `ValidationError` (`fields is required: pass field slugs or "*" (@cogover/sdk
362
+ 0.13.0+)`). With workspace types, the result is narrowed to the requested fields, so
363
+ reading a field that was not requested is a compile error. A single result is limited
364
+ to 1 MiB; prefer a list of fields to `"*"` for `getMany` and large pages.
355
365
 
356
366
  Cogover normalizes service values to the declared SDK types: booleans become
357
- `true`/`false`, and lookup/reference values are reduced to
358
- `{ id, name, objectSlug }` so nested record fields are not exposed. For writes,
359
- reference fields accept either a record ID or a `RecordReference`; only the ID is
360
- sent to the Record API.
367
+ `true`/`false`, and lookup/reference values are `RecordReference` objects
368
+ `{ id, name, objectSlug }`. A lookup's `name` is `""`, and so is
369
+ `system.createdBy.name`, unless the read sets `expandLookups`; a `reference` field
370
+ keeps the name it stores. `expandLookups: true`, or an object such as
371
+ `{ customer: ["credit_limit", "tier"], owner: "*" }`, adds the linked records' names
372
+ and selected `fields`, read one level deep with the same identity and permissions
373
+ as the read itself. Expand only the lookups the script uses, since each one reads
374
+ more data. For writes, reference fields accept either a record ID or a
375
+ `RecordReference`; only the ID is sent to the Record API.
376
+
377
+ ```typescript
378
+ const order = await orders.records.get(orderId, {
379
+ fields: ["code", "amount", "customer"],
380
+ expandLookups: { customer: ["credit_limit"] },
381
+ });
382
+ const creditLimit = order?.fields.customer?.fields?.credit_limit;
383
+ ```
361
384
 
362
385
  ```typescript
363
386
  import { and, defineScript } from "@cogover/sdk";
@@ -365,6 +388,7 @@ import { and, defineScript } from "@cogover/sdk";
365
388
  export default defineScript(async ({ data }) => {
366
389
  const orders = data.object("order");
367
390
  return orders.records.list({
391
+ fields: ["code", "status", "total"],
368
392
  where: and(
369
393
  orders.fields.status.in(["new", "nurturing"]),
370
394
  orders.fields.is_active.eq(true),
@@ -381,6 +405,28 @@ call. `fields` is required. The result is `{ records, missingIds }`: IDs that do
381
405
  exist or are not visible to the identity in use are reported in `missingIds` instead
382
406
  of being dropped. Prefer it to calling `records.get` in a loop.
383
407
 
408
+ `records.aggregate` counts, sums, averages, and finds the smallest and largest values
409
+ of the matching records in one call, without reading them. `groupBy` groups by up to
410
+ three fields and `limit` (1 to 5,000, default 1,000) caps the groups; `truncated`
411
+ reports that more groups exist. Aggregates follow record writes after about one
412
+ second. A client from `data.asUser()`, like `data.object()` in a trigger or job that runs
413
+ as a user, cannot group and supports only counts and number metrics; use
414
+ `data.asSystem()` there.
415
+
416
+ ```typescript
417
+ const totals = await orders.records.aggregate({
418
+ where: orders.fields.status.eq("paid"),
419
+ metrics: { orders: { count: "id" }, revenue: { sum: "total" } },
420
+ });
421
+ // totals.values: { orders: 120, revenue: 530000000 }
422
+
423
+ const byStatus = await orders.records.aggregate({
424
+ groupBy: ["status"],
425
+ metrics: { orders: { count: "id" }, average: { avg: "total" } },
426
+ });
427
+ // byStatus.groups: [{ key: { status: "paid" }, values: { orders: 120, average: 4416666 } }]
428
+ ```
429
+
384
430
  Batch writes are best-effort per row. Check `result.success` or every entry in
385
431
  `result.results`; a successful request envelope does not mean every row succeeded.
386
432
  Business upsert accepts one `matchBy` field that must be configured as a single-field
@@ -438,7 +484,7 @@ await data.asSystem().object("order").records.update(order.id, changes);
438
484
 
439
485
  Both methods return new immutable clients and preserve workspace typing. `asUser`
440
486
  accepts a personnel ID (not an account ID) and supports the full record API, including
441
- batch writes and business upsert. Reads apply that user's permissions and approved field restrictions;
487
+ batch writes and business upsert, except grouping in `records.aggregate`. Reads apply that user's permissions and approved field restrictions;
442
488
  read access must be approved separately from writes. `asSystem` supports the
443
489
  full record API, including in authenticated public scripts, without changing the
444
490
  original caller or existing clients. `asSystem` may also write fields whose manual
@@ -590,7 +636,10 @@ npx cogover-generate-workspace-types objects.json workspace.d.ts
590
636
  ```
591
637
 
592
638
  The declaration makes object slugs, field slugs, value types, and choice option
593
- slugs available to TypeScript. `schema.object(slug)` is read-only; Object and
639
+ slugs available to TypeScript, and types the `fields` of an expanded lookup from
640
+ its target Object. It imports the SDK types it uses (`RecordReference`, `FileValue`,
641
+ `UrlValue`); regenerate a declaration made by a version before 0.13.0, which left
642
+ them unresolved and typed those fields as `any` under `skipLibCheck`. `schema.object(slug)` is read-only; Object and
594
643
  field mutation are intentionally not part of this SDK.
595
644
 
596
645
  ## TypeScript
package/dist/crypto.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CogoverApiError, ValidationError } from "./errors.js";
2
- import { decodeBase64, encodeBase64 } from "./internal/base64.js";
2
+ import { decodeBase64, encodeBase64, encodeHex } from "./internal/base64.js";
3
3
  import { callBridge } from "./internal/bridge.js";
4
- import { encodeUtf8, utf8ByteLength } from "./internal/utf8.js";
4
+ import { utf8ByteLength } from "./internal/utf8.js";
5
5
  import { requireSecretName } from "./internal/validation.js";
6
6
  import { isRecord } from "./internal/values.js";
7
7
  const MAX_DATA_BYTES = 256 * 1024;
@@ -220,23 +220,19 @@ export const crypto = Object.freeze({
220
220
  return bytes;
221
221
  },
222
222
  async randomUUID() {
223
- const bytes = await crypto.randomBytes(16);
223
+ const bytes = await uuidBytes();
224
224
  bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; // version 4
225
225
  bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant
226
- const hex = toHex(bytes);
226
+ const hex = encodeHex(bytes);
227
227
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
228
228
  },
229
229
  timingSafeEqual(a, b) {
230
- const left = toBytes(a, "timingSafeEqual() first value");
231
- const right = toBytes(b, "timingSafeEqual() second value");
232
- // Every byte of the longer value is visited, so the time depends only on the lengths, never on
233
- // where the first difference is.
234
- let mismatch = left.length ^ right.length;
235
- const length = Math.max(left.length, right.length);
236
- for (let index = 0; index < length; index++) {
237
- mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);
238
- }
239
- return mismatch === 0;
230
+ const left = comparable(a, "timingSafeEqual() first value");
231
+ const right = comparable(b, "timingSafeEqual() second value");
232
+ // Well-formed strings are equal exactly when their UTF-8 encodings are, so two strings need no encoding.
233
+ return typeof left === "string" && typeof right === "string"
234
+ ? constantTimeEqual(wellFormed(left), wellFormed(right))
235
+ : constantTimeEqual(binaryString(left), binaryString(right));
240
236
  },
241
237
  aesEncrypt,
242
238
  aesDecrypt: aesDecrypt,
@@ -443,18 +439,92 @@ function digest(payload) {
443
439
  }
444
440
  return payload.digest;
445
441
  }
446
- function toBytes(value, label) {
447
- if (typeof value === "string")
448
- return encodeUtf8(value);
449
- if (value instanceof Uint8Array)
442
+ /** Random bytes for UUIDs, fetched MAX_RANDOM_BYTES at a time: one capability call covers 64 UUIDs. */
443
+ let uuidPool = new Uint8Array(0);
444
+ let uuidPoolOffset = 0;
445
+ let uuidPoolRefill;
446
+ async function uuidBytes() {
447
+ while (uuidPoolOffset + 16 > uuidPool.length) {
448
+ // Concurrent calls share one refill; a failed refill is retried by the next call.
449
+ uuidPoolRefill ??= crypto.randomBytes(MAX_RANDOM_BYTES)
450
+ .then(bytes => {
451
+ uuidPool = bytes;
452
+ uuidPoolOffset = 0;
453
+ })
454
+ .finally(() => {
455
+ uuidPoolRefill = undefined;
456
+ });
457
+ await uuidPoolRefill;
458
+ }
459
+ const bytes = uuidPool.slice(uuidPoolOffset, uuidPoolOffset + 16);
460
+ uuidPool.fill(0, uuidPoolOffset, uuidPoolOffset + 16);
461
+ uuidPoolOffset += 16;
462
+ return bytes;
463
+ }
464
+ /** A timingSafeEqual argument after its type and size checks. */
465
+ function comparable(value, label) {
466
+ if (typeof value === "string") {
467
+ if (utf8ByteLength(value) > MAX_DATA_BYTES)
468
+ throw tooLarge(label);
469
+ return value;
470
+ }
471
+ if (value instanceof Uint8Array) {
472
+ if (value.length > MAX_DATA_BYTES)
473
+ throw tooLarge(label);
450
474
  return value;
475
+ }
451
476
  throw new ValidationError(`${label} must be a string or a Uint8Array`);
452
477
  }
453
- function toHex(bytes) {
454
- let hex = "";
455
- for (const byte of bytes)
456
- hex += (byte < 16 ? "0" : "") + byte.toString(16);
457
- return hex;
478
+ const LONE_SURROGATES = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
479
+ const BINARY_CHUNK = 8192;
480
+ /** The string with each lone surrogate replaced by U+FFFD, as its UTF-8 encoding does. */
481
+ function wellFormed(value) {
482
+ const toWellFormed = String.prototype.toWellFormed;
483
+ return typeof toWellFormed === "function" ? toWellFormed.call(value) : value.replace(LONE_SURROGATES, "\ufffd");
484
+ }
485
+ /**
486
+ * One character per byte: the UTF-8 encoding of a string, or the bytes themselves. Both conversions run as engine
487
+ * code; encodeURIComponent leaves only ASCII characters unescaped, and unescape turns each %XX back into one byte.
488
+ */
489
+ function binaryString(value) {
490
+ if (typeof value === "string")
491
+ return unescape(encodeURIComponent(wellFormed(value)));
492
+ const parts = [];
493
+ for (let index = 0; index < value.length; index += BINARY_CHUNK) {
494
+ parts[parts.length] = String.fromCharCode.apply(null, value.subarray(index, index + BINARY_CHUNK));
495
+ }
496
+ return parts.join("");
497
+ }
498
+ /**
499
+ * Visits every code unit of the longer string, so the time depends only on the lengths, never on where the first
500
+ * difference is. Each loop turn compares 32 code units in one expression to stay within the statement budget; past
501
+ * the end of the shorter string charCodeAt returns NaN, which a bitwise operator reads as 0.
502
+ */
503
+ function constantTimeEqual(left, right) {
504
+ let mismatch = left.length ^ right.length;
505
+ const length = Math.max(left.length, right.length);
506
+ let index = 0;
507
+ for (; index + 32 <= length; index += 32) {
508
+ mismatch |= (left.charCodeAt(index) ^ right.charCodeAt(index)) | (left.charCodeAt(index + 1) ^ right.charCodeAt(index + 1))
509
+ | (left.charCodeAt(index + 2) ^ right.charCodeAt(index + 2)) | (left.charCodeAt(index + 3) ^ right.charCodeAt(index + 3))
510
+ | (left.charCodeAt(index + 4) ^ right.charCodeAt(index + 4)) | (left.charCodeAt(index + 5) ^ right.charCodeAt(index + 5))
511
+ | (left.charCodeAt(index + 6) ^ right.charCodeAt(index + 6)) | (left.charCodeAt(index + 7) ^ right.charCodeAt(index + 7))
512
+ | (left.charCodeAt(index + 8) ^ right.charCodeAt(index + 8)) | (left.charCodeAt(index + 9) ^ right.charCodeAt(index + 9))
513
+ | (left.charCodeAt(index + 10) ^ right.charCodeAt(index + 10)) | (left.charCodeAt(index + 11) ^ right.charCodeAt(index + 11))
514
+ | (left.charCodeAt(index + 12) ^ right.charCodeAt(index + 12)) | (left.charCodeAt(index + 13) ^ right.charCodeAt(index + 13))
515
+ | (left.charCodeAt(index + 14) ^ right.charCodeAt(index + 14)) | (left.charCodeAt(index + 15) ^ right.charCodeAt(index + 15))
516
+ | (left.charCodeAt(index + 16) ^ right.charCodeAt(index + 16)) | (left.charCodeAt(index + 17) ^ right.charCodeAt(index + 17))
517
+ | (left.charCodeAt(index + 18) ^ right.charCodeAt(index + 18)) | (left.charCodeAt(index + 19) ^ right.charCodeAt(index + 19))
518
+ | (left.charCodeAt(index + 20) ^ right.charCodeAt(index + 20)) | (left.charCodeAt(index + 21) ^ right.charCodeAt(index + 21))
519
+ | (left.charCodeAt(index + 22) ^ right.charCodeAt(index + 22)) | (left.charCodeAt(index + 23) ^ right.charCodeAt(index + 23))
520
+ | (left.charCodeAt(index + 24) ^ right.charCodeAt(index + 24)) | (left.charCodeAt(index + 25) ^ right.charCodeAt(index + 25))
521
+ | (left.charCodeAt(index + 26) ^ right.charCodeAt(index + 26)) | (left.charCodeAt(index + 27) ^ right.charCodeAt(index + 27))
522
+ | (left.charCodeAt(index + 28) ^ right.charCodeAt(index + 28)) | (left.charCodeAt(index + 29) ^ right.charCodeAt(index + 29))
523
+ | (left.charCodeAt(index + 30) ^ right.charCodeAt(index + 30)) | (left.charCodeAt(index + 31) ^ right.charCodeAt(index + 31));
524
+ }
525
+ for (; index < length; index++)
526
+ mismatch |= left.charCodeAt(index) ^ right.charCodeAt(index);
527
+ return mismatch === 0;
458
528
  }
459
529
  function tooLarge(label) {
460
530
  return new ValidationError(`${label} must not exceed ${MAX_DATA_BYTES} bytes`);
package/dist/data.d.ts CHANGED
@@ -1,18 +1,146 @@
1
1
  import type { FieldReferences, FilterExpression, SortExpression } from "./query.js";
2
- import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, GetManyResult, RecordPage, UpdateFields, UpsertFields, UpsertResult } from "./records.js";
3
- import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
4
- export interface GetRecordOptions<TFields> {
5
- readonly fields?: readonly StringKeyOf<TFields>[];
2
+ import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, FileValue, GetManyResult, RecordPage, UpdateFields, UpsertFields, UpsertResult, UrlValue } from "./records.js";
3
+ import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf, WorkspaceObjects } from "./workspace.js";
4
+ /**
5
+ * Fields a read returns: a non-empty list of field slugs, or `"*"` for every field that the identity in use and the
6
+ * project's identity policy may read.
7
+ */
8
+ export type FieldSelection<TFields> = "*" | readonly StringKeyOf<TFields>[];
9
+ /** Fields of the records that a read returns for `fields`: only the listed fields, or every field for `"*"`. */
10
+ export type SelectedFields<TFields, TSelection extends FieldSelection<TFields>> = TSelection extends "*" ? TFields : TSelection extends readonly (infer TSlug)[] ? StringKeyOf<TFields> extends TSlug ? TFields : Pick<TFields, Extract<TSlug, keyof TFields>> : TFields;
11
+ /** A lookup or reference value, told apart from a file value by its branded ID. */
12
+ interface LinkedRecordValue {
13
+ readonly id: CogoverRecordId;
14
+ readonly name: string;
6
15
  }
7
- export interface GetManyOptions<TFields> {
8
- readonly fields: readonly StringKeyOf<TFields>[];
16
+ /** Slugs of the lookup and reference fields; a field of unknown type may be one. */
17
+ type LookupFieldSlug<TFields> = string extends keyof TFields ? string : {
18
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends LinkedRecordValue | readonly LinkedRecordValue[] ? K : never;
19
+ }[StringKeyOf<TFields>];
20
+ type LinkedObjectSlug<TValue> = NonNullable<TValue> extends readonly (infer TItem)[] ? LinkedObjectSlug<TItem> : NonNullable<TValue> extends {
21
+ readonly objectSlug?: infer TSlug;
22
+ } ? Exclude<TSlug, undefined> : string;
23
+ type LinkedFieldSlug<TValue> = LinkedObjectSlug<TValue> extends infer TSlug ? TSlug extends keyof WorkspaceObjects ? StringKeyOf<WorkspaceObjects[TSlug]> : string : string;
24
+ /**
25
+ * Lookups to expand in a read: `true` expands every lookup and reference field in `fields`; an object expands only
26
+ * the named ones, each with the linked record's field slugs or `"*"`. `false` expands nothing, like leaving it out.
27
+ */
28
+ export type ExpandLookups<TFields> = boolean | ([LookupFieldSlug<TFields>] extends [never] ? never : {
29
+ readonly [K in LookupFieldSlug<TFields>]?: "*" | readonly LinkedFieldSlug<TFields[K]>[];
30
+ });
31
+ export interface GetRecordOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
32
+ readonly fields: TSelection;
33
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
9
34
  }
10
- export interface ListOptions<TFields> {
35
+ export interface GetManyOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
36
+ readonly fields: TSelection;
37
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
38
+ }
39
+ export interface ListOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
11
40
  readonly where?: FilterExpression;
12
41
  readonly orderBy?: readonly SortExpression[];
13
- readonly fields?: readonly StringKeyOf<TFields>[];
42
+ readonly fields: TSelection;
14
43
  readonly limit?: number;
15
44
  readonly cursor?: string;
45
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
46
+ }
47
+ /** Slugs of the fields whose values are `TValue`; a field of unknown type may be one. */
48
+ type FieldSlugOfType<TFields, TValue> = string extends keyof TFields ? string : {
49
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends TValue ? K : never;
50
+ }[StringKeyOf<TFields>];
51
+ /** Slugs of the fields that can be counted: every field except file and URL fields (and reference fields). */
52
+ type CountableFieldSlug<TFields> = string extends keyof TFields ? string : {
53
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends LinkedRecordValue | readonly LinkedRecordValue[] ? K : NonNullable<TFields[K]> extends UrlValue | FileValue | readonly (UrlValue | FileValue)[] ? never : K;
54
+ }[StringKeyOf<TFields>];
55
+ /**
56
+ * One metric of `records.aggregate`. `count` counts the matching records for `"id"` and the records with a value
57
+ * otherwise; `countDistinct` counts distinct values approximately on large sets; neither takes a reference, file or
58
+ * URL field. `sum` and `avg` take a number field; `min` and `max` take a number or date field.
59
+ */
60
+ export type AggregateMetric<TFields> = {
61
+ readonly count: "id" | CountableFieldSlug<TFields>;
62
+ } | {
63
+ readonly countDistinct: CountableFieldSlug<TFields>;
64
+ } | {
65
+ readonly sum: FieldSlugOfType<TFields, number>;
66
+ } | {
67
+ readonly avg: FieldSlugOfType<TFields, number>;
68
+ } | {
69
+ readonly min: FieldSlugOfType<TFields, number | string>;
70
+ } | {
71
+ readonly max: FieldSlugOfType<TFields, number | string>;
72
+ };
73
+ /**
74
+ * One metric of `records.aggregate` on a client from `asUser()`: `count` on `"id"` or a number field, or `sum`,
75
+ * `avg`, `min` or `max` on a number field.
76
+ */
77
+ export type AsUserAggregateMetric<TFields> = {
78
+ readonly count: "id" | FieldSlugOfType<TFields, number>;
79
+ } | {
80
+ readonly sum: FieldSlugOfType<TFields, number>;
81
+ } | {
82
+ readonly avg: FieldSlugOfType<TFields, number>;
83
+ } | {
84
+ readonly min: FieldSlugOfType<TFields, number>;
85
+ } | {
86
+ readonly max: FieldSlugOfType<TFields, number>;
87
+ };
88
+ type AggregateMetrics<TFields> = Readonly<Record<string, AggregateMetric<TFields>>>;
89
+ type AsUserAggregateMetrics<TFields> = Readonly<Record<string, AsUserAggregateMetric<TFields>>>;
90
+ /** Options of `records.aggregate` without groups: one set of metric values over every matching record. */
91
+ export interface AggregateOptions<TFields, TMetrics extends AggregateMetrics<TFields> | AsUserAggregateMetrics<TFields> = AggregateMetrics<TFields>> {
92
+ readonly where?: FilterExpression;
93
+ /** 1 to 20 metrics by name: a letter followed by up to 63 letters, digits or underscores. */
94
+ readonly metrics: TMetrics;
95
+ /** Grouping uses `GroupedAggregateOptions`; a client from `asUser()` cannot group. */
96
+ readonly groupBy?: never;
97
+ /** Only a grouped aggregate takes `limit`. */
98
+ readonly limit?: never;
99
+ }
100
+ /** Options of `records.aggregate` with groups: metric values for each combination of the `groupBy` values. */
101
+ export interface GroupedAggregateOptions<TFields, TMetrics extends AggregateMetrics<TFields> = AggregateMetrics<TFields>, TGroupBy extends readonly StringKeyOf<TFields>[] = readonly StringKeyOf<TFields>[]> {
102
+ readonly where?: FilterExpression;
103
+ /** 1 to 3 field slugs. */
104
+ readonly groupBy: TGroupBy;
105
+ /** 1 to 20 metrics by name: a letter followed by up to 63 letters, digits or underscores. */
106
+ readonly metrics: TMetrics;
107
+ /** Most groups to return, from 1 to 5000; Cogover returns up to 1000 when it is left out. */
108
+ readonly limit?: number;
109
+ }
110
+ /**
111
+ * Metric values by metric name. Counts and sums are numbers, `0` when no record matches; `avg`, `min` and `max` are
112
+ * `null` when no matching record has a value.
113
+ */
114
+ export type AggregateValues<TMetrics> = {
115
+ readonly [K in keyof TMetrics]: TMetrics[K] extends {
116
+ readonly count: string;
117
+ } | {
118
+ readonly countDistinct: string;
119
+ } | {
120
+ readonly sum: string;
121
+ } ? number : number | null;
122
+ };
123
+ type AggregateKeyValue<TValue> = TValue extends LinkedRecordValue ? CogoverRecordId : TValue extends readonly (infer TItem)[] ? AggregateKeyValue<NonNullable<TItem>> : TValue extends boolean ? boolean : TValue extends number ? number : TValue extends string ? string extends TValue ? number : TValue : string | number | boolean;
124
+ /**
125
+ * Values of one group by field slug: a record ID for a lookup, an option slug for a choice, `true`/`false`, a
126
+ * number, or epoch milliseconds for a date or date-time field. Text fields cannot be grouped, so a field typed
127
+ * `string` is a date here.
128
+ */
129
+ export type AggregateGroupKey<TFields, TSlug extends StringKeyOf<TFields>> = {
130
+ readonly [K in TSlug]: AggregateKeyValue<NonNullable<TFields[K]>>;
131
+ };
132
+ export interface AggregateResult<TValues = Readonly<Record<string, number | null>>> {
133
+ readonly values: TValues;
134
+ }
135
+ export interface AggregateGroup<TKey = Readonly<Record<string, string | number | boolean>>, TValues = Readonly<Record<string, number | null>>> {
136
+ readonly key: TKey;
137
+ readonly values: TValues;
138
+ }
139
+ export interface AggregateGroupResult<TKey = Readonly<Record<string, string | number | boolean>>, TValues = Readonly<Record<string, number | null>>> {
140
+ /** Groups with the most records first. A record without a value in a `groupBy` field is in no group. */
141
+ readonly groups: AggregateGroup<TKey, TValues>[];
142
+ /** `true` when there were more groups than `limit` and only the first `limit` are returned. */
143
+ readonly truncated: boolean;
16
144
  }
17
145
  export interface RecordWritesApi<TFields> {
18
146
  create(fields: CreateFields<TFields>): Promise<CogoverRecordId>;
@@ -22,11 +150,25 @@ export interface RecordWritesApi<TFields> {
22
150
  upsertByUniqueField<TMatchBy extends StringKeyOf<TFields>>(matchBy: TMatchBy, fields: UpsertFields<TFields, TMatchBy>): Promise<UpsertResult>;
23
151
  deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
24
152
  }
25
- export interface RecordsApi<TFields> extends RecordWritesApi<TFields> {
26
- get(id: string, options?: GetRecordOptions<TFields>): Promise<CogoverRecord<TFields> | null>;
153
+ /** Record API of a client from `asUser()`: the same as `RecordsApi` except that `aggregate` cannot group. */
154
+ export interface AsUserRecordsApi<TFields> extends RecordWritesApi<TFields> {
155
+ /** Reads one record; `null` when it does not exist or the identity in use cannot read it. */
156
+ get<const TSelection extends FieldSelection<TFields>>(id: string, options: GetRecordOptions<TFields, TSelection>): Promise<CogoverRecord<SelectedFields<TFields, TSelection>> | null>;
27
157
  /** Reads up to 200 records by ID in one call; unreadable IDs are reported in `missingIds`. */
28
- getMany(ids: readonly string[], options: GetManyOptions<TFields>): Promise<GetManyResult<TFields>>;
29
- list(options?: ListOptions<TFields>): Promise<RecordPage<TFields>>;
158
+ getMany<const TSelection extends FieldSelection<TFields>>(ids: readonly string[], options: GetManyOptions<TFields, TSelection>): Promise<GetManyResult<SelectedFields<TFields, TSelection>>>;
159
+ /** Reads one page of up to 200 matching records. */
160
+ list<const TSelection extends FieldSelection<TFields>>(options: ListOptions<TFields, TSelection>): Promise<RecordPage<SelectedFields<TFields, TSelection>>>;
161
+ /**
162
+ * Computes metrics over every matching record in one call; only the metrics of `AsUserAggregateMetric`. The
163
+ * same limits apply to `data.object()` where the execution reads as a user who is not the HTTP caller.
164
+ */
165
+ aggregate<const TMetrics extends AsUserAggregateMetrics<TFields>>(options: AggregateOptions<TFields, TMetrics>): Promise<AggregateResult<AggregateValues<TMetrics>>>;
166
+ }
167
+ export interface RecordsApi<TFields> extends AsUserRecordsApi<TFields> {
168
+ /** Computes metrics over every matching record in one call. */
169
+ aggregate<const TMetrics extends AggregateMetrics<TFields>>(options: AggregateOptions<TFields, TMetrics>): Promise<AggregateResult<AggregateValues<TMetrics>>>;
170
+ /** Computes metrics for each group of matching records in one call. */
171
+ aggregate<const TMetrics extends AggregateMetrics<TFields>, const TGroupBy extends readonly StringKeyOf<TFields>[]>(options: GroupedAggregateOptions<TFields, TMetrics, TGroupBy>): Promise<AggregateGroupResult<AggregateGroupKey<TFields, TGroupBy[number]>, AggregateValues<TMetrics>>>;
30
172
  }
31
173
  export interface WriteObjectClient<TFields> {
32
174
  readonly slug: string;
@@ -36,9 +178,13 @@ export interface WriteObjectClient<TFields> {
36
178
  export interface ObjectClient<TFields> extends WriteObjectClient<TFields> {
37
179
  readonly records: RecordsApi<TFields>;
38
180
  }
181
+ /** Object client of `asUser()`: its `records.aggregate` cannot group. */
182
+ export interface AsUserObjectClient<TFields> extends WriteObjectClient<TFields> {
183
+ readonly records: AsUserRecordsApi<TFields>;
184
+ }
39
185
  /** Reads and writes as an approved personnel ID. Authorization is enforced by Cogover. */
40
186
  export interface AsUserDataApi<TSchema extends object = EffectiveWorkspaceObjects> {
41
- object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
187
+ object<K extends StringKeyOf<TSchema>>(slug: K): AsUserObjectClient<FieldsFor<TSchema, K>>;
42
188
  }
43
189
  export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
44
190
  object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
@@ -47,3 +193,4 @@ export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
47
193
  /** New system client, including in public invocations. Requires approval; does not change this client. */
48
194
  asSystem(): DataApi<TSchema>;
49
195
  }
196
+ export {};
package/dist/data.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CogoverApiError, ValidationError } from "./errors.js";
2
2
  import { callBridge } from "./internal/bridge.js";
3
+ import { normalizeAggregateOptions, normalizeExpandLookups, normalizeFieldSelection, requireAggregateResult, } from "./internal/record-reads.js";
3
4
  import { requireFieldSlug, requireFields, requireSlug, requireText } from "./internal/validation.js";
4
5
  import { isRecord } from "./internal/values.js";
5
6
  import { createFieldReferences } from "./query.js";
@@ -27,11 +28,12 @@ function createObjectClient(slug, identity) {
27
28
  const fields = createFieldReferences();
28
29
  const records = Object.freeze({
29
30
  async get(id, options) {
31
+ const recordId = requireText(id, "record id");
30
32
  return callBridge("records.get", {
31
33
  identity,
32
34
  objectSlug: slug,
33
- id: requireText(id, "record id"),
34
- fields: options?.fields,
35
+ id: recordId,
36
+ ...readSelection(options),
35
37
  });
36
38
  },
37
39
  async getMany(ids, options) {
@@ -42,11 +44,8 @@ function createObjectClient(slug, identity) {
42
44
  if (uniqueIds.length > MAX_BATCH_RECORDS) {
43
45
  throw new ValidationError(`getMany() supports at most ${MAX_BATCH_RECORDS} unique record ids`);
44
46
  }
45
- const requestedFields = options?.fields;
46
- if (!Array.isArray(requestedFields) || requestedFields.length === 0) {
47
- throw new ValidationError("getMany() requires a non-empty fields array");
48
- }
49
- const fieldSlugs = [...new Set(requestedFields.map((field) => requireFieldSlug(field)))];
47
+ // `fields` is checked even when there is nothing to read, so the mistake is never hidden.
48
+ const selection = readSelection(options);
50
49
  if (uniqueIds.length === 0) {
51
50
  return { records: [], missingIds: [] };
52
51
  }
@@ -54,7 +53,7 @@ function createObjectClient(slug, identity) {
54
53
  identity,
55
54
  objectSlug: slug,
56
55
  ids: uniqueIds,
57
- fields: fieldSlugs,
56
+ ...selection,
58
57
  });
59
58
  if (!isRecord(result) || !Array.isArray(result.records) || !Array.isArray(result.missingIds)) {
60
59
  throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.getMany returned an invalid result");
@@ -62,16 +61,27 @@ function createObjectClient(slug, identity) {
62
61
  return result;
63
62
  },
64
63
  async list(options) {
64
+ const selection = readSelection(options);
65
65
  return callBridge("records.list", {
66
66
  identity,
67
67
  objectSlug: slug,
68
- where: options?.where,
69
- orderBy: options?.orderBy,
70
- fields: options?.fields,
71
- limit: options?.limit,
72
- cursor: options?.cursor,
68
+ where: options.where,
69
+ orderBy: options.orderBy,
70
+ fields: selection.fields,
71
+ limit: options.limit,
72
+ cursor: options.cursor,
73
+ expandLookups: selection.expandLookups,
73
74
  });
74
75
  },
76
+ async aggregate(options) {
77
+ const request = normalizeAggregateOptions(options, identity?.kind === "user");
78
+ const result = await callBridge("records.aggregate", {
79
+ identity,
80
+ objectSlug: slug,
81
+ ...request,
82
+ });
83
+ return requireAggregateResult(result, request);
84
+ },
75
85
  async create(fieldsToCreate) {
76
86
  return callBridge("records.create", {
77
87
  identity,
@@ -154,7 +164,13 @@ function createObjectClient(slug, identity) {
154
164
  });
155
165
  },
156
166
  });
157
- return Object.freeze({ slug, fields, records });
167
+ return Object.freeze({ slug, fields, records: records });
168
+ }
169
+ /** The validated `fields` and `expandLookups` of a read; `expandLookups` is left out when nothing is expanded. */
170
+ function readSelection(options) {
171
+ const fields = normalizeFieldSelection(isRecord(options) ? options.fields : undefined);
172
+ const expandLookups = normalizeExpandLookups(isRecord(options) ? options.expandLookups : undefined, fields);
173
+ return expandLookups === undefined ? { fields } : { fields, expandLookups };
158
174
  }
159
175
  function requireBatch(records, operation) {
160
176
  if (!Array.isArray(records) || records.length === 0) {
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { WorkspaceObjects } from "./workspace.js";
3
3
  export type { CogoverRecordId, RecordReference, UrlValue, FileValue, CogoverRecord, RecordPage, GetManyResult, DeleteResult, BatchWriteRowResult, BatchWriteResponse, BatchUpdateItem, UpsertFields, UpsertResult, CreateFields, UpdateFields, } from "./records.js";
4
4
  export { and, or } from "./query.js";
5
5
  export type { FilterOperator, FilterCondition, FilterGroup, FilterExpression, SortExpression, FieldReference, FieldReferences, } from "./query.js";
6
- export type { GetRecordOptions, GetManyOptions, ListOptions, RecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, DataApi, } from "./data.js";
6
+ export type { FieldSelection, SelectedFields, ExpandLookups, GetRecordOptions, GetManyOptions, ListOptions, AggregateMetric, AsUserAggregateMetric, AggregateOptions, GroupedAggregateOptions, AggregateValues, AggregateGroupKey, AggregateResult, AggregateGroup, AggregateGroupResult, RecordsApi, AsUserRecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, AsUserObjectClient, DataApi, } from "./data.js";
7
7
  export type { ObjectMetadata, SchemaApi } from "./schema.js";
8
8
  export type { ScriptLogger } from "./logger.js";
9
9
  export { defineScript } from "./script.js";
@@ -1,9 +1,5 @@
1
1
  const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2
2
  const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
3
- // Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
4
- // The sandbox caps the statements one execution may run and every loop turn costs about three of them, so each
5
- // turn handles 24 bytes in a single expression: 256 KiB costs about 33,000 statements instead of several hundred
6
- // thousand.
7
3
  let digits;
8
4
  /** 6-bit value of each base64 character code; "=" reads as 0 once the text has been validated. */
9
5
  function digitTable() {
@@ -17,6 +13,20 @@ function digitTable() {
17
13
  }
18
14
  /** Standard base64 with padding (RFC 4648 section 4). */
19
15
  export function encodeBase64(bytes) {
16
+ const toBase64 = Uint8Array.prototype.toBase64;
17
+ return typeof toBase64 === "function" ? toBase64.call(bytes) : encodeBase64InGuest(bytes);
18
+ }
19
+ /** Lowercase hexadecimal, two digits per byte. */
20
+ export function encodeHex(bytes) {
21
+ const toHex = Uint8Array.prototype.toHex;
22
+ if (typeof toHex === "function")
23
+ return toHex.call(bytes);
24
+ let hex = "";
25
+ for (const byte of bytes)
26
+ hex += (byte < 16 ? "0" : "") + byte.toString(16);
27
+ return hex;
28
+ }
29
+ function encodeBase64InGuest(bytes) {
20
30
  const length = bytes.length;
21
31
  const whole = length - (length % 3);
22
32
  const parts = [];
@@ -54,8 +64,13 @@ export function encodeBase64(bytes) {
54
64
  }
55
65
  /** Decodes padded standard base64; returns null for text that is not canonical base64. */
56
66
  export function decodeBase64(text) {
67
+ // The built-in also accepts whitespace and missing padding, so the text is validated first either way.
57
68
  if (typeof text !== "string" || !BASE64.test(text))
58
69
  return null;
70
+ const fromBase64 = Uint8Array.fromBase64;
71
+ return typeof fromBase64 === "function" ? fromBase64.call(Uint8Array, text) : decodeBase64InGuest(text);
72
+ }
73
+ function decodeBase64InGuest(text) {
59
74
  const table = digitTable();
60
75
  const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
61
76
  const groups = text.length / 4;