@cogover/sdk 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +65 -21
  2. package/dist/crypto.js +89 -46
  3. package/dist/data.js +4 -1
  4. package/dist/email.d.ts +77 -0
  5. package/dist/email.js +192 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/internal/base64.js +76 -27
  8. package/dist/internal/bridge.js +41 -3
  9. package/dist/internal/job-config.js +7 -1
  10. package/dist/internal/job-runtime.js +4 -0
  11. package/dist/internal/messaging.js +75 -0
  12. package/dist/internal/trigger-runtime.js +5 -0
  13. package/dist/internal/utf8.js +18 -17
  14. package/dist/jobs.d.ts +4 -0
  15. package/dist/locks.js +13 -3
  16. package/dist/logger.js +47 -1
  17. package/dist/notifications.d.ts +56 -0
  18. package/dist/notifications.js +92 -0
  19. package/dist/org.js +14 -14
  20. package/dist/records.d.ts +13 -0
  21. package/dist/response.js +21 -1
  22. package/dist/router.js +2 -0
  23. package/dist/schema.d.ts +1 -0
  24. package/dist/script.d.ts +4 -0
  25. package/dist/script.js +11 -3
  26. package/dist/trigger.d.ts +6 -0
  27. package/docs/en/api-reference/background-jobs.md +288 -0
  28. package/docs/en/api-reference/cryptography.md +317 -0
  29. package/docs/en/api-reference/fetch-and-secrets.md +184 -0
  30. package/docs/en/api-reference/inbound-webhooks.md +65 -0
  31. package/docs/en/api-reference/notifications-and-email.md +317 -0
  32. package/docs/en/api-reference/organization-structure.md +304 -0
  33. package/docs/en/api-reference/overview.md +198 -0
  34. package/docs/en/api-reference/push-messages.md +115 -0
  35. package/docs/en/api-reference/record-triggers.md +469 -0
  36. package/docs/en/api-reference/records.md +447 -0
  37. package/docs/en/api-reference/scripts-and-routes.md +354 -0
  38. package/docs/en/api-reference/state-and-locks.md +162 -0
  39. package/docs/en/usage-guide.md +218 -19
  40. package/package.json +1 -1
  41. package/docs/en/api-reference.md +0 -2619
@@ -0,0 +1,447 @@
1
+ # `@cogover/sdk` API reference: Records and schema
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Record API
6
+
7
+ ```typescript
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 });
12
+ await orders.records.create(fields);
13
+ await orders.records.update(id, fields);
14
+ await orders.records.batchInsert(records);
15
+ await orders.records.batchUpdate(records);
16
+ await orders.records.upsertByUniqueField(matchBy, fields);
17
+ await orders.records.deleteMany(ids);
18
+ ```
19
+
20
+ ### Record values and results
21
+
22
+ ```typescript
23
+ type CogoverRecordId = string & {
24
+ readonly __cogoverRecordIdBrand: unique symbol;
25
+ };
26
+
27
+ interface RecordReference<ObjectSlug extends string = string> {
28
+ readonly id: CogoverRecordId;
29
+ readonly name: string;
30
+ readonly objectSlug?: ObjectSlug;
31
+ }
32
+
33
+ interface UrlValue {
34
+ readonly url: string;
35
+ readonly alias?: string;
36
+ }
37
+
38
+ interface FileValue {
39
+ readonly id: string;
40
+ readonly name: string;
41
+ readonly size?: number;
42
+ readonly contentType?: string;
43
+ readonly url?: string;
44
+ }
45
+
46
+ interface CogoverRecord<Fields> {
47
+ readonly id: CogoverRecordId;
48
+ readonly fields: Readonly<Fields>;
49
+ readonly system: {
50
+ readonly createdAt: number;
51
+ readonly updatedAt: number;
52
+ readonly createdBy?: { readonly id: string; readonly name: string };
53
+ };
54
+ }
55
+
56
+ interface RecordPage<Fields> {
57
+ readonly items: CogoverRecord<Fields>[];
58
+ readonly total: number;
59
+ readonly nextCursor?: string;
60
+ }
61
+
62
+ interface GetManyResult<Fields> {
63
+ readonly records: CogoverRecord<Fields>[];
64
+ readonly missingIds: CogoverRecordId[];
65
+ }
66
+
67
+ interface DeleteResult {
68
+ readonly deleted: CogoverRecordId[];
69
+ readonly notDeleted: CogoverRecordId[];
70
+ readonly recordErrors?: Readonly<Record<CogoverRecordId, {
71
+ readonly reason: "TRIGGER_REJECTED";
72
+ readonly fieldErrors?: Readonly<Record<string, string>>;
73
+ readonly messages?: readonly string[];
74
+ }>>;
75
+ }
76
+
77
+ interface BatchWriteRowResult {
78
+ readonly referenceId: string;
79
+ readonly id?: CogoverRecordId;
80
+ readonly r: number;
81
+ readonly msg?: string;
82
+ readonly success: boolean;
83
+ readonly fieldErrors?: Readonly<Record<string, string>>;
84
+ readonly messages?: readonly string[];
85
+ }
86
+
87
+ interface BatchWriteResponse {
88
+ readonly r: number;
89
+ readonly msg?: string;
90
+ readonly results: readonly BatchWriteRowResult[];
91
+ readonly success: boolean;
92
+ }
93
+
94
+ interface BatchUpdateItem<Fields> {
95
+ readonly id: CogoverRecordId;
96
+ readonly fields: UpdateFields<Fields>;
97
+ }
98
+
99
+ interface UpsertResult {
100
+ readonly id: CogoverRecordId;
101
+ readonly created: boolean;
102
+ }
103
+ ```
104
+
105
+ `CreateFields<Fields>` and `UpdateFields<Fields>` are partial mapped types over the
106
+ workspace fields. Reference values accept a string, `CogoverRecordId`, or matching
107
+ `RecordReference`; array fields accept readonly arrays. `UpsertFields<Fields,
108
+ MatchBy>` is a create-field map that requires the selected match field to be present
109
+ and non-null.
110
+
111
+ ### Data clients and operations
112
+
113
+ ```typescript
114
+ interface GetRecordOptions<Fields> {
115
+ readonly fields?: readonly (keyof Fields & string)[];
116
+ }
117
+
118
+ interface GetManyOptions<Fields> {
119
+ readonly fields: readonly (keyof Fields & string)[];
120
+ }
121
+
122
+ interface ListOptions<Fields> {
123
+ readonly where?: FilterExpression;
124
+ readonly orderBy?: readonly SortExpression[];
125
+ readonly fields?: readonly (keyof Fields & string)[];
126
+ readonly limit?: number;
127
+ readonly cursor?: string;
128
+ }
129
+
130
+ interface RecordWritesApi<Fields> {
131
+ create(fields: CreateFields<Fields>): Promise<CogoverRecordId>;
132
+ update(id: CogoverRecordId, fields: UpdateFields<Fields>): Promise<void>;
133
+ batchInsert(records: readonly CreateFields<Fields>[]): Promise<BatchWriteResponse>;
134
+ batchUpdate(records: readonly BatchUpdateItem<Fields>[]): Promise<BatchWriteResponse>;
135
+ upsertByUniqueField<MatchBy extends keyof Fields & string>(
136
+ matchBy: MatchBy,
137
+ fields: UpsertFields<Fields, MatchBy>,
138
+ ): Promise<UpsertResult>;
139
+ deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
140
+ }
141
+
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>>;
146
+ }
147
+
148
+ interface WriteObjectClient<Fields> {
149
+ readonly slug: string;
150
+ readonly fields: FieldReferences<Fields>;
151
+ readonly records: RecordWritesApi<Fields>;
152
+ }
153
+
154
+ interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
155
+ readonly records: RecordsApi<Fields>;
156
+ }
157
+
158
+ interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
159
+ object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
160
+ }
161
+
162
+ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
163
+ object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
164
+ asUser(personnelId: string): AsUserDataApi<Schema>;
165
+ asSystem(): DataApi<Schema>;
166
+ }
167
+ ```
168
+
169
+ `list` returns `RecordPage<T>` with `items`, `total`, and an optional opaque
170
+ `nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
171
+ `system` object containing creation/update metadata.
172
+
173
+ `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
175
+ trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
176
+ ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
177
+ An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
178
+ The result contains the readable `records` and `missingIds`: every requested ID that
179
+ could not be read, because the record does not exist or the identity in use cannot
180
+ see it. IDs are never dropped silently. The order of `records` is not guaranteed to
181
+ follow `ids`, so index them by `id`:
182
+
183
+ ```typescript
184
+ const accounts = data.object("account");
185
+ const { records, missingIds } = await accounts.records.getMany(accountIds, { fields: ["credit_limit"] });
186
+ const accountById = new Map(records.map(record => [record.id, record]));
187
+ ```
188
+
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.
191
+
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.
195
+
196
+ A `file` field is read as `FileValue` objects: one `FileValue`, or `null`, for a
197
+ single file field and an array for a multiple one. `url` is present only when Cogover
198
+ has a complete absolute URL for the file.
199
+
200
+ A write accepts a `FileValue` read from a record, so a file can be copied to another
201
+ record. Every written file must be a file uploaded to a file field of this workspace;
202
+ otherwise the write throws `ValidationError` (`details.r` 626) and nothing is saved.
203
+
204
+ A `date` field is read as a `"yyyy-MM-dd"` string and a `date_time` field as epoch
205
+ milliseconds. Writes accept the same forms and also an ISO 8601 string, which is what a
206
+ `Date` becomes: in a `date_time` field it is stored as that instant, and in a `date`
207
+ field as its UTC day. Other text for these fields throws `ValidationError` with
208
+ `details.reason` `"INVALID_FIELD_VALUE"`.
209
+
210
+ ## Filters and sorting
211
+
212
+ ```typescript
213
+ type FilterOperator =
214
+ | "=" | "!=" | ">" | ">=" | "<" | "<="
215
+ | "like" | "not like" | "startsWith" | "endsWith"
216
+ | "in" | "not in" | "is null" | "not null" | "between";
217
+
218
+ interface FilterCondition {
219
+ readonly kind: "condition";
220
+ readonly field: string;
221
+ readonly operator: FilterOperator;
222
+ readonly value?: unknown;
223
+ }
224
+
225
+ interface FilterGroup {
226
+ readonly kind: "group";
227
+ readonly operator: "and" | "or";
228
+ readonly expressions: readonly FilterExpression[];
229
+ }
230
+
231
+ type FilterExpression = FilterCondition | FilterGroup;
232
+
233
+ interface SortExpression {
234
+ readonly field: string;
235
+ readonly direction: "asc" | "desc";
236
+ }
237
+
238
+ interface FieldReference<Value> {
239
+ readonly slug: string;
240
+ eq(value: NonNullable<Value>): FilterCondition;
241
+ neq(value: NonNullable<Value>): FilterCondition;
242
+ gt(value: NonNullable<Value>): FilterCondition;
243
+ gte(value: NonNullable<Value>): FilterCondition;
244
+ lt(value: NonNullable<Value>): FilterCondition;
245
+ lte(value: NonNullable<Value>): FilterCondition;
246
+ like(value: string): FilterCondition;
247
+ notLike(value: string): FilterCondition;
248
+ startsWith(value: string): FilterCondition;
249
+ endsWith(value: string): FilterCondition;
250
+ in(values: readonly (
251
+ NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
252
+ )[]): FilterCondition;
253
+ notIn(values: readonly (
254
+ NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
255
+ )[]): FilterCondition;
256
+ isNull(): FilterCondition;
257
+ notNull(): FilterCondition;
258
+ between(from: NonNullable<Value>, to: NonNullable<Value>): FilterCondition;
259
+ asc(): SortExpression;
260
+ desc(): SortExpression;
261
+ }
262
+ ```
263
+
264
+ Each `FieldReference<Value>` exposes `slug`, `eq`, `neq`, `gt`, `gte`, `lt`,
265
+ `lte`, `like`, `notLike`, `startsWith`, `endsWith`, `in`, `notIn`, `isNull`,
266
+ `notNull`, `between`, `asc`, and `desc`. `FieldReferences<Fields>` provides these
267
+ references for workspace fields and the system fields `id`, `created`, `updated`,
268
+ and `created_by`. `and(...expressions)` and `or(...expressions)` return a
269
+ `FilterGroup` and require at least one expression.
270
+ For array-valued fields, `in` and `notIn` accept the array's element type.
271
+
272
+ Transport-specific field metadata and response envelopes are handled by Cogover.
273
+
274
+ `create` and `update` require a non-empty field object. `batchInsert` accepts 1–200
275
+ field objects; `batchUpdate` accepts 1–200 `{ id, fields }` items. Both are
276
+ best-effort operations: their `BatchWriteResponse`
277
+ contains one result per input row, and callers must inspect the top-level `success`
278
+ flag or each row's `success`, `r`, and `msg`. A successful request is not an
279
+ all-or-none transaction and does not guarantee that every row was written.
280
+ `referenceId` identifies the zero-based input index as a string. A unique-key
281
+ conflict, including two rows of the same batch with the same unique value, rejects the
282
+ whole batch instead of one row: the call throws `ValidationError` with
283
+ `details.reason` `"UNIQUE_KEY_VIOLATION"` and returns no row results. A write that a
284
+ before-change record trigger refuses throws `ValidationError` with `details.reason`
285
+ `"TRIGGER_REJECTED"`, and one that a trigger could not check throws `RetryableError`
286
+ with `details.reason` `"TRIGGER_FAILED"` (see
287
+ [Record triggers](record-triggers.md#validating-and-changing-records)). In
288
+ `batchInsert` and `batchUpdate` a trigger rejects rows, not the call: a rejected row
289
+ has `r` `70` and `success` `false`, and, when Cogover receives them, `fieldErrors`
290
+ maps each field slug (`$record` for the whole record) to the trigger's error code and
291
+ `messages` lists the trigger's texts.
292
+
293
+ `deleteMany` requires 1–200 non-blank record IDs and returns separate `deleted` and
294
+ `notDeleted` arrays. When a before-change record trigger rejects some of the records,
295
+ the others are still deleted, the rejected IDs are in `notDeleted`, and
296
+ `recordErrors` maps each rejected ID to `{ reason: "TRIGGER_REJECTED", fieldErrors?,
297
+ 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.
301
+
302
+ A field value that Cogover refuses throws `ValidationError` whose `details` name the
303
+ field in `fieldSlug`: `details.reason` is `"REQUIRED_FIELD_MISSING"` for a required
304
+ field without a value and `"INVALID_FIELD_VALUE"` for a value that does not fit the
305
+ field's type. Formula, auto number, and rollup summary fields, and fields whose
306
+ metadata has `readOnly: true`, can never be written, whatever the identity: writing
307
+ one throws `ValidationError` with `details.reason` `"FIELD_NOT_WRITABLE"`.
308
+
309
+ `upsertByUniqueField(matchBy, fields)` updates the record whose configured unique
310
+ field equals `fields[matchBy]`, or creates it when no record matches. The match field
311
+ must be a single, non-multiple field with uniqueness enabled, and the business key
312
+ must be non-null and non-blank. The result is `{ id, created }`. Because the server
313
+ chooses the create/update branch, the operation requires both record-create and
314
+ record-update permission.
315
+
316
+ A unique-key conflict is exposed as `ValidationError` with
317
+ `details.reason === "UNIQUE_KEY_VIOLATION"`, `objectSlug`, and `fieldSlug`. The
318
+ public error does not echo the rejected business-key value.
319
+
320
+ ## Record execution identities
321
+
322
+ `data.object(slug)` inherits the invocation identity. For an authenticated public
323
+ invocation this is the caller; a system invocation keeps system access.
324
+
325
+ ### `data.asUser(personnelId: string): AsUserDataApi<TSchema>`
326
+
327
+ Returns a new immutable client for reads and writes as the specified personnel ID (not an
328
+ 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
338
+ throw errors instead of being treated as missing records or an empty page.
339
+
340
+ ```typescript
341
+ const delegatedOrders = data.asUser(personnelId).object("order");
342
+ const order = await delegatedOrders.records.get(recordId, { fields: ["description"] });
343
+ const page = await delegatedOrders.records.list({
344
+ fields: ["description"],
345
+ where: delegatedOrders.fields.description.eq("Pending review"),
346
+ limit: 20,
347
+ });
348
+ ```
349
+
350
+ ### `data.asSystem(): DataApi<TSchema>`
351
+
352
+ 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
355
+ apply the caller's record permissions; approved project restrictions, field
356
+ validation, workspace boundaries, and runtime limits still apply. It neither
357
+ changes the invocation's caller nor modifies existing clients.
358
+
359
+ ```typescript
360
+ const orders = data.object("order");
361
+ await orders.records.update(order.id, { description: "Caller update" });
362
+ await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
363
+ await data.asSystem().object("order").records.update(order.id, { description: "System update" });
364
+ ```
365
+
366
+ Identity selection needs administrator approval for the project version, permitted
367
+ callers, target personnel, objects, operations, and fields. Selection alone grants
368
+ no permission. Unauthorized operations throw `PermissionDeniedError`; invalid or
369
+ unresolvable identities never fall back to system or caller access. A personnel
370
+ without an active user account in the workspace throws `PermissionDeniedError` with
371
+ `details.reason` `"IDENTITY_NOT_RESOLVED"`. Server failures
372
+ retain their original `CogoverApiError.r`. No credentials or workspace override are
373
+ accepted by these methods. Schema access is unchanged. Each write is independent;
374
+ the three example calls above are not a transaction.
375
+
376
+ ## Schema API
377
+
378
+ `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
379
+
380
+ ```typescript
381
+ interface ObjectMetadata {
382
+ readonly id: string;
383
+ readonly name: string;
384
+ readonly slug: string;
385
+ readonly fields: readonly {
386
+ readonly id: string;
387
+ readonly name: string;
388
+ readonly slug: string;
389
+ readonly fieldType: string;
390
+ readonly required: boolean;
391
+ readonly multiple: boolean;
392
+ readonly readOnly: boolean;
393
+ readonly manualModifyAllow?: boolean;
394
+ readonly creatable?: boolean;
395
+ readonly metaData?: Readonly<Record<string, unknown>>;
396
+ readonly options?: readonly {
397
+ readonly id: string;
398
+ readonly slug: string;
399
+ readonly value: string;
400
+ readonly isDefault?: boolean;
401
+ }[];
402
+ }[];
403
+ }
404
+
405
+ interface SchemaApi<Schema extends object = EffectiveWorkspaceObjects> {
406
+ object<Slug extends keyof Schema & string>(slug: Slug): Promise<ObjectMetadata>;
407
+ }
408
+ ```
409
+
410
+ `manualModifyAllow` is `false` when users may not change the field when they edit a
411
+ record, and `creatable` is `false` when they may not set it when they create one. A
412
+ write that sets such a field as the caller or through `data.asUser()` throws
413
+ `ValidationError`; `data.asSystem()` may set it.
414
+
415
+ Object and field mutation are not part of this SDK. An invalid object slug throws
416
+ `ValidationError`; service failures use the error types described below.
417
+
418
+ ## Workspace declarations
419
+
420
+ `WorkspaceObjects` is an open interface. Without augmentation, object and field
421
+ slugs are strings with unknown field values. Generate and include a declaration to
422
+ make them workspace-specific:
423
+
424
+ ```bash
425
+ npx cogover-generate-workspace-types objects.json workspace.d.ts
426
+ ```
427
+
428
+ The generator reads Object metadata, sorts object and field slugs, and maps field
429
+ types as follows:
430
+
431
+ | Object field type | Generated TypeScript type |
432
+ |---|---|
433
+ | `short_text`, `long_text`, `phone`, `email`, `regex`, `auto_number`, `date` | `string` |
434
+ | `boolean` | `boolean` |
435
+ | `numeric`, `decimal`, `currency`, `percent`, `rating`, `time`, `date_time`, `time_duration` | `number` |
436
+ | `single_choice` | union of option slugs, or `string` |
437
+ | `multi_choices`, `label`, `cascading` | readonly array of option slugs, or strings |
438
+ | `url` | `UrlValue` |
439
+ | `file` | `FileValue` |
440
+ | `lookup_normal`, `reference` | `RecordReference<ObjectSlug>` when the target is known |
441
+ | `date_range` | `readonly [string, string]` |
442
+ | `date_time_range`, `time_range` | `readonly [number, number]` |
443
+ | unknown field type | `unknown` |
444
+
445
+ 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
447
+ the project's TypeScript compilation and do not edit it manually.