@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.
- package/README.md +65 -13
- package/dist/data.d.ts +160 -13
- package/dist/data.js +30 -14
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/internal/job-runtime.js +5 -2
- package/dist/internal/local-invocation.js +8 -0
- package/dist/internal/record-reads.js +183 -0
- package/dist/internal/trigger-runtime.js +5 -2
- package/dist/jobs.d.ts +3 -0
- package/dist/limits.d.ts +33 -0
- package/dist/limits.js +51 -0
- package/dist/records.d.ts +18 -0
- package/dist/router.js +1 -0
- package/dist/script.d.ts +3 -0
- package/dist/script.js +5 -2
- package/dist/trigger.d.ts +3 -0
- package/docs/en/api-reference/background-jobs.md +11 -7
- package/docs/en/api-reference/cryptography.md +3 -2
- package/docs/en/api-reference/fetch-and-secrets.md +5 -5
- package/docs/en/api-reference/organization-structure.md +4 -3
- package/docs/en/api-reference/overview.md +107 -12
- package/docs/en/api-reference/record-triggers.md +15 -1
- package/docs/en/api-reference/records.md +387 -35
- package/docs/en/api-reference/scripts-and-routes.md +6 -4
- package/docs/en/api-reference/state-and-locks.md +3 -0
- package/docs/en/usage-guide.md +80 -3
- package/package.json +1 -1
- package/scripts/generate-workspace-types.mjs +19 -7
package/docs/en/usage-guide.md
CHANGED
|
@@ -32,7 +32,7 @@ npx tsc --noEmit
|
|
|
32
32
|
```
|
|
33
33
|
|
|
34
34
|
Place the generated `workspace.d.ts` declaration alongside the module's source
|
|
35
|
-
and include it in the TypeScript project.
|
|
35
|
+
and include it in the TypeScript project. Type checking needs TypeScript 5.0 or later.
|
|
36
36
|
|
|
37
37
|
## Quick start
|
|
38
38
|
|
|
@@ -172,6 +172,24 @@ const approvers = chain?.tiers.flatMap(tier =>
|
|
|
172
172
|
- For other personnel fields, such as custom fields, use
|
|
173
173
|
`data.object("personnel")`, which applies record permissions.
|
|
174
174
|
|
|
175
|
+
## Choose the fields to read
|
|
176
|
+
|
|
177
|
+
Every read names its fields: the slugs the script uses, or `"*"` for every field that
|
|
178
|
+
the identity in use may read (with `data.asUser()` or `data.asSystem()`, only the fields
|
|
179
|
+
that the project's identity policy grants). A read without
|
|
180
|
+
`fields` throws `ValidationError` (`fields is required: pass field slugs or "*"
|
|
181
|
+
(@cogover/sdk 0.13.0+)`) before anything is sent.
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
const order = await orders.records.get(orderId, { fields: ["code", "amount"] });
|
|
185
|
+
const amount = order?.fields.amount; // number | null | undefined
|
|
186
|
+
// order?.fields.status does not compile: it was not requested.
|
|
187
|
+
const everything = await orders.records.get(orderId, { fields: "*" });
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Prefer a list of fields to `"*"`: the read returns less data, and a large `"*"`
|
|
191
|
+
result, especially from `getMany` or `list`, can exceed the 1 MiB limit of one call.
|
|
192
|
+
|
|
175
193
|
## Filter and sort records
|
|
176
194
|
|
|
177
195
|
```typescript
|
|
@@ -180,6 +198,7 @@ import { and, defineScript } from "@cogover/sdk";
|
|
|
180
198
|
export default defineScript(async ({ data }) => {
|
|
181
199
|
const orders = data.object("order");
|
|
182
200
|
return orders.records.list({
|
|
201
|
+
fields: ["code", "status", "total"],
|
|
183
202
|
where: and(
|
|
184
203
|
orders.fields.status.in(["new", "nurturing"]),
|
|
185
204
|
orders.fields.is_active.eq(true),
|
|
@@ -207,7 +226,52 @@ if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds }
|
|
|
207
226
|
|
|
208
227
|
Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
|
|
209
228
|
`ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
|
|
210
|
-
every capability call counts towards the
|
|
229
|
+
every capability call and every record read counts towards the budgets of the
|
|
230
|
+
execution.
|
|
231
|
+
|
|
232
|
+
## Read linked records
|
|
233
|
+
|
|
234
|
+
A lookup value is `{ id, name: "", objectSlug }` unless the read asks for the linked
|
|
235
|
+
record, and `system.createdBy.name` is `""` as well. Set `expandLookups` when the script
|
|
236
|
+
needs the names or fields of linked records:
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
const order = await orders.records.get(orderId, {
|
|
240
|
+
fields: ["code", "customer"],
|
|
241
|
+
expandLookups: { customer: ["credit_limit", "tier"] },
|
|
242
|
+
});
|
|
243
|
+
const customer = order?.fields.customer;
|
|
244
|
+
log.info("Customer", { name: customer?.name, creditLimit: customer?.fields?.credit_limit });
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
`expandLookups: true` expands every lookup among the returned fields. Linked records
|
|
248
|
+
are read one level deep, up to 1,000 per call, with the same identity and permissions
|
|
249
|
+
as the read itself; a linked record that cannot be read keeps `name: ""` and has no
|
|
250
|
+
`fields`. Expanding reads more data, so expand only the lookups the script uses. The
|
|
251
|
+
`new` and `old` values of a record trigger already carry lookup names.
|
|
252
|
+
|
|
253
|
+
## Count and sum records
|
|
254
|
+
|
|
255
|
+
`records.aggregate` returns counts, sums, averages, and smallest or largest values
|
|
256
|
+
without reading the records, optionally grouped by up to three fields:
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
const byStatus = await orders.records.aggregate({
|
|
260
|
+
where: orders.fields.total.gt(0),
|
|
261
|
+
groupBy: ["status"],
|
|
262
|
+
metrics: { orders: { count: "id" }, revenue: { sum: "total" } },
|
|
263
|
+
});
|
|
264
|
+
for (const group of byStatus.groups) {
|
|
265
|
+
log.info("Orders by status", { status: group.key.status, ...group.values });
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Without `groupBy` the result is `{ values }`. A client from `data.asUser()`, like
|
|
270
|
+
`data.object()` in a trigger or a job that runs as a user or in a local Development
|
|
271
|
+
Session started by `cogover-dev run`, cannot group and supports only counts and number
|
|
272
|
+
metrics; use `data.asSystem()` there, or try grouping on a published version. Aggregates follow record writes after about one second,
|
|
273
|
+
so a record saved just before may not be counted yet. See
|
|
274
|
+
[Aggregates](api-reference/records.md#aggregates) for every metric and limit.
|
|
211
275
|
|
|
212
276
|
## Call an external API with `fetch`
|
|
213
277
|
|
|
@@ -345,7 +409,16 @@ and the JWT algorithm names.
|
|
|
345
409
|
- Cogover authentication credentials are never exposed to module code. Access is
|
|
346
410
|
limited to the configured Objects, operations, and fields.
|
|
347
411
|
- TypeScript types do not replace runtime validation of business input.
|
|
348
|
-
- Cogover limits
|
|
412
|
+
- Cogover limits, for each execution, the capability calls, the local calls (`crypto`,
|
|
413
|
+
`org` without display data), the records read and written, request and response
|
|
414
|
+
sizes, and execution time. An HTTP route may make 100 capability calls and read
|
|
415
|
+
10,000 records; a background job 1,000 calls and 50,000 records. A call that would go
|
|
416
|
+
over a budget throws `RateLimitError` with `details.budget`; waiting does not help.
|
|
417
|
+
- `limits.usage()` (also `context.limits`) tells how much of each budget the execution
|
|
418
|
+
has used, without a capability call. Use it to hand the rest of a long task to a
|
|
419
|
+
background job before a budget runs out.
|
|
420
|
+
- Totals and counts do not need to read records: `records.aggregate` is one capability
|
|
421
|
+
call whatever the number of records.
|
|
349
422
|
- Do not automatically retry writes after a timeout because the commit outcome may
|
|
350
423
|
be unknown.
|
|
351
424
|
|
|
@@ -859,6 +932,10 @@ permissions, so a read can legitimately return nothing for a record the user can
|
|
|
859
932
|
see. `data.asUser()` and `data.asSystem()` need the same administrator approval as
|
|
860
933
|
in scripts.
|
|
861
934
|
|
|
935
|
+
**Lookup names.** Lookups in `record.new` and `record.old` carry the linked record's
|
|
936
|
+
name. Records read through `data` have `name: ""` in their lookups unless the read
|
|
937
|
+
uses `expandLookups`.
|
|
938
|
+
|
|
862
939
|
**Time budget and failures.** A call must finish within `timeoutMs`, and all
|
|
863
940
|
before-change triggers of one write share 8 seconds. Before-change triggers fail
|
|
864
941
|
closed: when a handler throws, runs out of time, or cannot be run, the write is
|
package/package.json
CHANGED
|
@@ -27,14 +27,23 @@ function extractObjects(documentValue) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
function renderDeclaration(objectsValue) {
|
|
30
|
+
// SDK types used by the generated field types. The augmentation cannot see the module's own exports, so the
|
|
31
|
+
// declaration imports them; an unresolved name would silently become `any` under skipLibCheck.
|
|
32
|
+
const sdkTypes = new Set();
|
|
30
33
|
const objectLines = objectsValue
|
|
31
34
|
.filter((object) => typeof object?.slug === "string" && object.slug.length > 0)
|
|
32
35
|
.sort((left, right) => left.slug.localeCompare(right.slug))
|
|
33
|
-
.map(renderObject)
|
|
36
|
+
.map((object) => renderObject(object, sdkTypes))
|
|
34
37
|
.join("\n");
|
|
35
38
|
|
|
39
|
+
// Only the names in use are imported, so the file also compiles with noUnusedLocals.
|
|
40
|
+
const usedTypes = [...sdkTypes].sort();
|
|
41
|
+
const importLine = usedTypes.length === 0
|
|
42
|
+
? `import "@cogover/sdk";\n\n`
|
|
43
|
+
: `import type { ${usedTypes.join(", ")} } from "@cogover/sdk";\n\n`;
|
|
44
|
+
|
|
36
45
|
return `// Generated by @cogover/sdk. Do not edit manually.\n`
|
|
37
|
-
+
|
|
46
|
+
+ importLine
|
|
38
47
|
+ `declare module "@cogover/sdk" {\n`
|
|
39
48
|
+ ` interface WorkspaceObjects {\n`
|
|
40
49
|
+ objectLines
|
|
@@ -42,25 +51,25 @@ function renderDeclaration(objectsValue) {
|
|
|
42
51
|
+ `}\n`;
|
|
43
52
|
}
|
|
44
53
|
|
|
45
|
-
function renderObject(object) {
|
|
54
|
+
function renderObject(object, sdkTypes) {
|
|
46
55
|
const fields = Array.isArray(object.fields) ? object.fields : [];
|
|
47
56
|
const fieldLines = fields
|
|
48
57
|
.filter((field) => typeof field?.slug === "string" && field.slug.length > 0)
|
|
49
58
|
.sort((left, right) => left.slug.localeCompare(right.slug))
|
|
50
|
-
.map((field) => ` ${property(field.slug)}: ${fieldType(field)};\n`)
|
|
59
|
+
.map((field) => ` ${property(field.slug)}: ${fieldType(field, sdkTypes)};\n`)
|
|
51
60
|
.join("");
|
|
52
61
|
return ` ${property(object.slug)}: {\n${fieldLines} };\n`;
|
|
53
62
|
}
|
|
54
63
|
|
|
55
|
-
function fieldType(field) {
|
|
56
|
-
const baseType = baseFieldType(field);
|
|
64
|
+
function fieldType(field, sdkTypes) {
|
|
65
|
+
const baseType = baseFieldType(field, sdkTypes);
|
|
57
66
|
const nullableType = field.required === true ? baseType : `${baseType} | null`;
|
|
58
67
|
return field.multiple === true && !baseType.endsWith("[]")
|
|
59
68
|
? `readonly ${parenthesize(baseType)}[]${field.required === true ? "" : " | null"}`
|
|
60
69
|
: nullableType;
|
|
61
70
|
}
|
|
62
71
|
|
|
63
|
-
function baseFieldType(field) {
|
|
72
|
+
function baseFieldType(field, sdkTypes) {
|
|
64
73
|
switch (field.fieldType) {
|
|
65
74
|
case "short_text":
|
|
66
75
|
case "long_text":
|
|
@@ -88,11 +97,14 @@ function baseFieldType(field) {
|
|
|
88
97
|
case "cascading":
|
|
89
98
|
return `readonly ${parenthesize(optionUnion(field.options))}[]`;
|
|
90
99
|
case "url":
|
|
100
|
+
sdkTypes.add("UrlValue");
|
|
91
101
|
return "UrlValue";
|
|
92
102
|
case "file":
|
|
103
|
+
sdkTypes.add("FileValue");
|
|
93
104
|
return "FileValue";
|
|
94
105
|
case "lookup_normal":
|
|
95
106
|
case "reference": {
|
|
107
|
+
sdkTypes.add("RecordReference");
|
|
96
108
|
const objectSlug = referenceObjectSlug(field);
|
|
97
109
|
return objectSlug === null
|
|
98
110
|
? "RecordReference"
|