@cogover/sdk 0.1.2 → 0.6.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 +347 -24
- package/dist/data.d.ts +49 -0
- package/dist/data.js +170 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +72 -0
- package/dist/fetch.d.ts +28 -0
- package/dist/fetch.js +96 -0
- package/dist/index.d.ts +23 -3
- package/dist/index.js +8 -5
- package/dist/internal/bridge.js +48 -0
- package/dist/internal/invocation.js +57 -0
- package/dist/internal/json.js +81 -0
- package/dist/internal/request.js +87 -0
- package/dist/internal/trigger-config.js +212 -0
- package/dist/internal/trigger-runtime.js +211 -0
- package/dist/internal/validation.js +28 -0
- package/dist/internal/values.js +6 -0
- package/dist/invocation.d.ts +40 -0
- package/dist/invocation.js +1 -0
- package/dist/legacy.d.ts +2 -0
- package/dist/legacy.js +4 -0
- package/dist/locks.d.ts +19 -0
- package/dist/locks.js +68 -0
- package/dist/logger.d.ts +6 -0
- package/dist/logger.js +14 -0
- package/dist/query.d.ts +52 -0
- package/dist/query.js +59 -0
- package/dist/records.d.ts +79 -0
- package/dist/records.js +1 -0
- package/dist/request.d.ts +18 -0
- package/dist/request.js +1 -0
- package/dist/response.d.ts +21 -0
- package/dist/response.js +108 -0
- package/dist/router.d.ts +13 -0
- package/dist/router.js +104 -0
- package/dist/schema.d.ts +26 -0
- package/dist/schema.js +11 -0
- package/dist/script.d.ts +23 -0
- package/dist/script.js +56 -0
- package/dist/state.d.ts +24 -0
- package/dist/state.js +91 -0
- package/dist/trigger.d.ts +121 -0
- package/dist/trigger.js +15 -0
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +1 -0
- package/docs/en/api-reference.md +1415 -0
- package/docs/en/usage-guide.md +495 -0
- package/package.json +17 -5
- package/scripts/generate-workspace-types.mjs +135 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
# `@cogover/sdk`
|
|
2
2
|
|
|
3
|
-
The TypeScript SDK for
|
|
4
|
-
|
|
3
|
+
The TypeScript SDK for developing **Custom Backend Modules** on Cogover. These
|
|
4
|
+
modules run server-side business logic, work with workspace data, expose HTTP
|
|
5
|
+
routes, and connect to external services. They are separate from Custom Frontend
|
|
6
|
+
Modules, which implement user interfaces.
|
|
7
|
+
|
|
8
|
+
The package includes type declarations for IDE autocomplete, inline
|
|
9
|
+
documentation, and type checking.
|
|
5
10
|
|
|
6
11
|
## Requirements
|
|
7
12
|
|
|
@@ -16,56 +21,368 @@ npm install @cogover/sdk
|
|
|
16
21
|
|
|
17
22
|
## Quick start
|
|
18
23
|
|
|
24
|
+
This example assumes that the generated `workspace.d.ts` declares the `order`
|
|
25
|
+
Object and the fields used below. See [Workspace types](#workspace-types).
|
|
26
|
+
|
|
19
27
|
```typescript
|
|
20
|
-
import {
|
|
28
|
+
import { defineScript, NotFoundError } from "@cogover/sdk";
|
|
29
|
+
|
|
30
|
+
interface Input { recordId: string }
|
|
31
|
+
interface Output { recordId: string; total: number }
|
|
32
|
+
|
|
33
|
+
export default defineScript<Input, Output>(async ({ input, data, log }) => {
|
|
34
|
+
const orders = data.object("order");
|
|
35
|
+
const order = await orders.records.get(input.recordId, {
|
|
36
|
+
fields: ["subtotal", "tax", "status"],
|
|
37
|
+
});
|
|
38
|
+
if (!order) throw new NotFoundError("order", input.recordId);
|
|
21
39
|
|
|
22
|
-
const
|
|
23
|
-
|
|
40
|
+
const total = (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0);
|
|
41
|
+
await orders.records.update(order.id, { status: "processed", total });
|
|
42
|
+
log.info("Order processed", { recordId: order.id, total });
|
|
43
|
+
return { recordId: order.id, total };
|
|
44
|
+
});
|
|
24
45
|
```
|
|
25
46
|
|
|
26
|
-
|
|
47
|
+
`defineScript` parses the input JSON, provides invocation metadata and scoped
|
|
48
|
+
data, schema, logging, state, and lock APIs, waits for the async handler, and
|
|
49
|
+
serializes its result. Cogover authentication credentials are not exposed to
|
|
50
|
+
project code, and Cogover enforces the configured permissions and limits on
|
|
51
|
+
capability calls.
|
|
52
|
+
|
|
53
|
+
## Current identity and workspace
|
|
54
|
+
|
|
55
|
+
`context.invocation` is an immutable snapshot of the invocation identity and
|
|
56
|
+
current workspace that Cogover already resolved for this execution. The identity
|
|
57
|
+
may represent an authenticated user or a system invocation. Reading it is
|
|
58
|
+
synchronous and does not make a data API request:
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
export default defineScript(({ invocation }) => {
|
|
62
|
+
if (invocation.identity === "system") {
|
|
63
|
+
return { workspaceId: invocation.workspace.id, user: null };
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
workspaceId: invocation.workspace.id,
|
|
67
|
+
workspaceName: invocation.workspace.name,
|
|
68
|
+
accountId: invocation.user.accountId,
|
|
69
|
+
personnelId: invocation.user.membership.personnelId,
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The `identity` discriminant narrows `user` to a public `CurrentUser` for user
|
|
75
|
+
invocations and to `null` for system invocations. Only the documented profile,
|
|
76
|
+
membership, locale, and workspace fields are included. Raw authentication data
|
|
77
|
+
and Cogover credentials are never exposed.
|
|
78
|
+
|
|
79
|
+
## Full HTTP routes and responses
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { createRouter } from "@cogover/sdk";
|
|
83
|
+
|
|
84
|
+
const router = createRouter();
|
|
85
|
+
router.get("/orders/:orderId", ({ request, response }) => response.json({
|
|
86
|
+
orderId: request.params.orderId,
|
|
87
|
+
expand: request.query.expand,
|
|
88
|
+
}));
|
|
89
|
+
router.post<{ description: string }, object>("/orders", ({ request, response }) =>
|
|
90
|
+
response.json({ description: request.body.description }, { status: 201 }));
|
|
91
|
+
router.put("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
92
|
+
router.patch("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
93
|
+
router.delete("/orders/:orderId", ({ response }) => response.empty());
|
|
94
|
+
export default router.toHandler();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `path`,
|
|
98
|
+
decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
|
|
99
|
+
`body`. Authentication headers are never exposed. Plain return values are JSON with
|
|
100
|
+
HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
|
|
101
|
+
status, safe response headers, and text/binary bodies. Missing routes return 404;
|
|
102
|
+
unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
|
|
103
|
+
The complete router contract is included in `docs/en/api-reference.md`.
|
|
104
|
+
|
|
105
|
+
## Record triggers
|
|
106
|
+
|
|
107
|
+
A record trigger runs project code when records of an Object are created, updated,
|
|
108
|
+
or deleted, for every source of a write. A before-change trigger runs before the
|
|
109
|
+
change is saved and can reject records or adjust the values that will be saved. An
|
|
110
|
+
after-change trigger runs asynchronously after the change has been saved.
|
|
111
|
+
Declare triggers with `defineTrigger` and list them in the named `triggers` export;
|
|
112
|
+
the default export stays reserved for HTTP and is optional in a trigger-only project.
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { defineTrigger } from "@cogover/sdk";
|
|
116
|
+
|
|
117
|
+
export const triggers = [
|
|
118
|
+
defineTrigger({
|
|
119
|
+
key: "order_credit_check",
|
|
120
|
+
object: "order",
|
|
121
|
+
timing: "beforeChange",
|
|
122
|
+
operations: ["create", "update"],
|
|
123
|
+
fields: ["status", "amount"],
|
|
124
|
+
changedFields: ["status", "amount"],
|
|
125
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
126
|
+
writableFields: ["approval_level"],
|
|
127
|
+
}, async ({ records }) => {
|
|
128
|
+
for (const record of records) {
|
|
129
|
+
if ((record.new.amount ?? 0) > 1_000_000_000) {
|
|
130
|
+
record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
record.new.approval_level = "high";
|
|
134
|
+
}
|
|
135
|
+
}),
|
|
136
|
+
];
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`record.new` and `record.old` contain only the listed `fields`. Assign fields of
|
|
140
|
+
`record.new` to change what is saved: only `writableFields` may change, and values
|
|
141
|
+
use the same format as `records.update` input. `record.addError(field, code,
|
|
142
|
+
message?)` rejects a record; the optional English message is shown to the end user
|
|
143
|
+
when the code has no translation. `changedFields`, `when`, and `runWhen` limit when
|
|
144
|
+
the trigger runs.
|
|
145
|
+
|
|
146
|
+
A handler receives up to 200 records per call, so read related data once with
|
|
147
|
+
`records.getMany` instead of once per record. Before-change triggers are read-only:
|
|
148
|
+
record writes, `fetch`, locks, and state writes are refused with
|
|
149
|
+
`PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`). `data.object()`
|
|
150
|
+
acts as the user who made the change. A handler that throws or exceeds its
|
|
151
|
+
`timeoutMs` (default 2,000 ms) rejects the write.
|
|
152
|
+
|
|
153
|
+
An after-change trigger (`timing: "afterChange"`) is for follow-up work. It cannot
|
|
154
|
+
reject or modify the saved change (`addError` is only logged), but it may write
|
|
155
|
+
records and call `fetch`. `record.new` holds the saved values, including the record
|
|
156
|
+
ID.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
160
|
+
|
|
161
|
+
export const triggers = [
|
|
162
|
+
defineTrigger({
|
|
163
|
+
key: "order_confirmed_notify",
|
|
164
|
+
object: "order",
|
|
165
|
+
timing: "afterChange",
|
|
166
|
+
operations: ["update"],
|
|
167
|
+
fields: ["status", "amount"],
|
|
168
|
+
changedFields: ["status"],
|
|
169
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
170
|
+
runWhen: "onEnter",
|
|
171
|
+
}, async ({ records, trigger }) => {
|
|
172
|
+
for (const record of records) {
|
|
173
|
+
const response = await fetch("https://erp.example.com/orders", {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers: { "idempotency-key": `${trigger.changeId}:${record.id}` },
|
|
176
|
+
body: JSON.stringify({ id: record.id, amount: record.new.amount }),
|
|
177
|
+
});
|
|
178
|
+
if (response.status >= 500) throw new RetryableError("The ERP is temporarily unavailable");
|
|
179
|
+
}
|
|
180
|
+
}),
|
|
181
|
+
];
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Delivery is best-effort: a handler may occasionally run more than once for the same
|
|
185
|
+
change, or not at all, so make it idempotent and keep critical rules in a
|
|
186
|
+
before-change trigger. Throw `RetryableError` for a temporary failure and Cogover
|
|
187
|
+
runs the handler again later, a limited number of times; other errors are logged and
|
|
188
|
+
not retried. Writes made by a trigger run triggers again, and Cogover ends such
|
|
189
|
+
chains after a bounded number of automated writes. The complete contract is included
|
|
190
|
+
in `docs/en/api-reference.md`.
|
|
191
|
+
|
|
192
|
+
## Outbound HTTP with `fetch`
|
|
27
193
|
|
|
28
|
-
|
|
194
|
+
Cogover provides a Fetch-compatible function for calling an external HTTPS API.
|
|
195
|
+
The request always goes through Cogover's managed network layer; it does not grant
|
|
196
|
+
project code unrestricted network access.
|
|
29
197
|
|
|
30
198
|
```typescript
|
|
31
|
-
import {
|
|
199
|
+
import { defineScript, fetch } from "@cogover/sdk";
|
|
32
200
|
|
|
33
201
|
interface Input {
|
|
34
|
-
|
|
202
|
+
externalToken: string;
|
|
203
|
+
orderId: string;
|
|
35
204
|
}
|
|
36
205
|
|
|
37
|
-
export default
|
|
38
|
-
const
|
|
206
|
+
export default defineScript<Input>(async ({ input }) => {
|
|
207
|
+
const response = await fetch("https://api.example.com/v1/orders", {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: {
|
|
210
|
+
authorization: `Bearer ${input.externalToken}`,
|
|
211
|
+
"content-type": "application/json",
|
|
212
|
+
},
|
|
213
|
+
body: JSON.stringify({ id: input.orderId }),
|
|
214
|
+
timeoutMs: 5_000,
|
|
215
|
+
});
|
|
216
|
+
return response.json();
|
|
217
|
+
});
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
V1 supports public HTTPS URLs on port 443 and the methods GET, HEAD, POST, PUT,
|
|
221
|
+
PATCH, and DELETE. Requests and buffered responses have platform limits. Redirects,
|
|
222
|
+
cookie jars, streaming, WebSocket, URL credentials, IP-literal hosts, custom proxy,
|
|
223
|
+
dispatcher, agent, DNS, and TLS settings are not supported. A failed mutating request
|
|
224
|
+
may already have reached the remote API, so use the remote API's idempotency mechanism
|
|
225
|
+
and do not retry blindly.
|
|
226
|
+
|
|
227
|
+
## Record API
|
|
228
|
+
|
|
229
|
+
An Object client exposes `records.get`, `records.getMany`, `records.list`,
|
|
230
|
+
`records.create`, `records.update`, `records.batchInsert`, `records.batchUpdate`,
|
|
231
|
+
`records.upsertByUniqueField`, and `records.deleteMany`. List filters are built from typed
|
|
232
|
+
field references, so scripts do not provide transport-specific field metadata or
|
|
233
|
+
response envelopes.
|
|
234
|
+
|
|
235
|
+
Cogover normalizes service values to the declared SDK types: booleans become
|
|
236
|
+
`true`/`false`, and lookup/reference values are reduced to
|
|
237
|
+
`{ id, name, objectSlug }` so nested record fields are not exposed. For writes,
|
|
238
|
+
reference fields accept either a record ID or a `RecordReference`; only the ID is
|
|
239
|
+
sent to the Record API.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { and, defineScript } from "@cogover/sdk";
|
|
39
243
|
|
|
40
|
-
|
|
41
|
-
|
|
244
|
+
export default defineScript(async ({ data }) => {
|
|
245
|
+
const orders = data.object("order");
|
|
246
|
+
return orders.records.list({
|
|
247
|
+
where: and(
|
|
248
|
+
orders.fields.status.in(["new", "nurturing"]),
|
|
249
|
+
orders.fields.is_active.eq(true),
|
|
250
|
+
orders.fields.total.gte(1_000_000),
|
|
251
|
+
),
|
|
252
|
+
orderBy: [orders.fields.updated.desc()],
|
|
253
|
+
limit: 50,
|
|
42
254
|
});
|
|
255
|
+
});
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
`records.getMany(ids, { fields })` reads up to 200 records by ID with one capability
|
|
259
|
+
call. `fields` is required. The result is `{ records, missingIds }`: IDs that do not
|
|
260
|
+
exist or are not visible to the identity in use are reported in `missingIds` instead
|
|
261
|
+
of being dropped. Prefer it to calling `records.get` in a loop.
|
|
262
|
+
|
|
263
|
+
Batch writes are best-effort per row. Check `result.success` or every entry in
|
|
264
|
+
`result.results`; a successful request envelope does not mean every row succeeded.
|
|
265
|
+
Business upsert accepts one `matchBy` field that must be configured as a single-field
|
|
266
|
+
unique key. It returns `{ id, created }` and requires both create and update permission.
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
const inserted = await orders.records.batchInsert([
|
|
270
|
+
{ name: "Order A", external_id: "EXT-1" },
|
|
271
|
+
{ name: "Order B", external_id: "EXT-2" },
|
|
272
|
+
]);
|
|
273
|
+
const firstInserted = inserted.results[0];
|
|
274
|
+
if (!firstInserted?.success || !firstInserted.id) {
|
|
275
|
+
throw new Error(firstInserted?.msg ?? "Order A could not be created");
|
|
43
276
|
}
|
|
277
|
+
|
|
278
|
+
const updated = await orders.records.batchUpdate([
|
|
279
|
+
{ id: firstInserted.id, fields: { status: "processing" } },
|
|
280
|
+
]);
|
|
281
|
+
if (!updated.success) throw new Error("The order could not be updated");
|
|
282
|
+
|
|
283
|
+
const upserted = await orders.records.upsertByUniqueField("external_id", {
|
|
284
|
+
external_id: "EXT-1",
|
|
285
|
+
name: "Order A from ERP",
|
|
286
|
+
});
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
API failures are unwrapped into `NotFoundError`, `ValidationError`,
|
|
290
|
+
`PermissionDeniedError`, `RateLimitError`, or `CogoverApiError`.
|
|
291
|
+
Unique-key conflicts are returned as `ValidationError` with
|
|
292
|
+
`details.reason === "UNIQUE_KEY_VIOLATION"`, plus the safe `objectSlug` and
|
|
293
|
+
`fieldSlug`; the rejected field value is not echoed in the public error.
|
|
294
|
+
|
|
295
|
+
Uncaught SDK errors return a safe HTTP error response: invalid input and blocked
|
|
296
|
+
outbound requests → 400; state conflicts and lock errors → 409; oversized outbound
|
|
297
|
+
requests → 413; permission denied → 403; not found → 404; unsupported methods →
|
|
298
|
+
405; rate limits → 429; unavailable state, lock, or outbound HTTP services → 503;
|
|
299
|
+
oversized or failed remote responses → 502; outbound timeouts → 504; and other
|
|
300
|
+
data API failures, as well as an escaped `RetryableError`, → 422. The response includes `code`, `msg`, `r` (HTTP status),
|
|
301
|
+
and `writesMayHaveCompleted` when relevant. Earlier writes are not rolled back;
|
|
302
|
+
never retry writes automatically. Unknown script errors and resource-limit
|
|
303
|
+
failures use a generic 422 response.
|
|
304
|
+
|
|
305
|
+
## Record execution identities
|
|
306
|
+
|
|
307
|
+
By default, `data.object("order")` uses the invocation's identity. Approved scripts
|
|
308
|
+
can explicitly select a personnel identity or system access:
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
const delegatedOrders = data.asUser(personnelId).object("order");
|
|
312
|
+
const record = await delegatedOrders.records.get(recordId, { fields: ["description"] });
|
|
313
|
+
const page = await delegatedOrders.records.list({ fields: ["description"], limit: 20 });
|
|
314
|
+
await data.asUser(personnelId).object("order").records.update(order.id, changes);
|
|
315
|
+
await data.asSystem().object("order").records.update(order.id, changes);
|
|
44
316
|
```
|
|
45
317
|
|
|
46
|
-
|
|
47
|
-
|
|
318
|
+
Both methods return new immutable clients and preserve workspace typing. `asUser`
|
|
319
|
+
accepts a personnel ID (not an account ID) and supports the full record API, including
|
|
320
|
+
batch writes and business upsert. Reads apply that user's permissions and approved field restrictions;
|
|
321
|
+
read access must be approved separately from writes. `asSystem` supports the
|
|
322
|
+
full record API, including in authenticated public scripts, without changing the
|
|
323
|
+
original caller or existing clients. `asSystem` may also write fields whose manual
|
|
324
|
+
creation (`creatable: false`) or manual modification (`manualModifyAllow: false`) is
|
|
325
|
+
disabled, because those locks only stop manual entry by users; for the caller and
|
|
326
|
+
`asUser`, creates reject `creatable: false` fields (`details.reason === "FIELD_NOT_CREATABLE"`)
|
|
327
|
+
and updates reject `manualModifyAllow: false` fields (`"FIELD_NOT_WRITABLE"`). Read-only
|
|
328
|
+
fields such as formulas, auto numbers and rollups stay rejected for every identity.
|
|
48
329
|
|
|
49
|
-
|
|
330
|
+
Administrator approval is required for the project version, callers, target users,
|
|
331
|
+
objects, operations, and fields. Unauthorized operations fail without falling back
|
|
332
|
+
to another identity. System access bypasses the caller's record permissions, so
|
|
333
|
+
privileged scripts must validate their business inputs and record scope. These
|
|
334
|
+
methods never accept credentials or a workspace override.
|
|
50
335
|
|
|
51
|
-
|
|
336
|
+
## Project state and distributed locks
|
|
52
337
|
|
|
53
|
-
|
|
338
|
+
Use project state for small durable JSON checkpoints and coordination values. State
|
|
339
|
+
is scoped to the workspace and project, survives new project versions, supports TTL
|
|
340
|
+
and compare-and-set, and limits each serialized value to 32 KiB.
|
|
54
341
|
|
|
55
342
|
```typescript
|
|
56
|
-
|
|
343
|
+
export default defineScript(async ({ state }) => {
|
|
344
|
+
const sync = state.namespace("inventory-sync");
|
|
345
|
+
const current = await sync.get<{ cursor: string }>("cursor");
|
|
346
|
+
return sync.set("cursor", { cursor: "next-page" }, {
|
|
347
|
+
expectedVersion: current?.version ?? 0,
|
|
348
|
+
ttlSeconds: 3600,
|
|
349
|
+
});
|
|
350
|
+
});
|
|
57
351
|
```
|
|
58
352
|
|
|
59
|
-
|
|
353
|
+
Distributed locks provide project-scoped token leases for short critical sections.
|
|
354
|
+
`withLock` releases in `finally`; manual leases support renew/release and expose a
|
|
355
|
+
fencing token. A lease does not auto-renew and locks do not replace idempotency or
|
|
356
|
+
provide exactly-once execution.
|
|
60
357
|
|
|
61
358
|
```typescript
|
|
62
|
-
|
|
359
|
+
export default defineScript(async ({ locks }) =>
|
|
360
|
+
locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
|
|
361
|
+
await processInvoice("INV-1", lease.fencingToken);
|
|
362
|
+
return { processed: true };
|
|
363
|
+
}));
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
State conflicts throw `StateConflictError`; failed lock acquisition and lost leases
|
|
367
|
+
use `LockUnavailableError` and `LockLostError`.
|
|
368
|
+
|
|
369
|
+
## Workspace types
|
|
370
|
+
|
|
371
|
+
`WorkspaceObjects` is an open interface augmented by a generated declaration for
|
|
372
|
+
the current Workspace. Generate a declaration from an Object Info JSON response:
|
|
373
|
+
|
|
374
|
+
```bash
|
|
375
|
+
npx cogover-generate-workspace-types objects.json workspace.d.ts
|
|
63
376
|
```
|
|
64
377
|
|
|
378
|
+
The declaration makes object slugs, field slugs, value types, and choice option
|
|
379
|
+
slugs available to TypeScript. `schema.object(slug)` is read-only; Object and
|
|
380
|
+
field mutation are intentionally not part of this SDK.
|
|
381
|
+
|
|
65
382
|
## TypeScript
|
|
66
383
|
|
|
67
|
-
Type declarations are included in the package.
|
|
68
|
-
|
|
384
|
+
Type declarations are included in the package. Add the generated `workspace.d.ts`
|
|
385
|
+
to the TypeScript project.
|
|
69
386
|
|
|
70
387
|
Recommended `tsconfig.json` options:
|
|
71
388
|
|
|
@@ -82,6 +399,12 @@ Recommended `tsconfig.json` options:
|
|
|
82
399
|
}
|
|
83
400
|
```
|
|
84
401
|
|
|
402
|
+
## Additional documentation
|
|
403
|
+
|
|
404
|
+
The installed package includes an English usage guide at
|
|
405
|
+
`docs/en/usage-guide.md` and the complete API reference at
|
|
406
|
+
`docs/en/api-reference.md`.
|
|
407
|
+
|
|
85
408
|
## License
|
|
86
409
|
|
|
87
|
-
|
|
410
|
+
MIT
|
package/dist/data.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
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>[];
|
|
6
|
+
}
|
|
7
|
+
export interface GetManyOptions<TFields> {
|
|
8
|
+
readonly fields: readonly StringKeyOf<TFields>[];
|
|
9
|
+
}
|
|
10
|
+
export interface ListOptions<TFields> {
|
|
11
|
+
readonly where?: FilterExpression;
|
|
12
|
+
readonly orderBy?: readonly SortExpression[];
|
|
13
|
+
readonly fields?: readonly StringKeyOf<TFields>[];
|
|
14
|
+
readonly limit?: number;
|
|
15
|
+
readonly cursor?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface RecordWritesApi<TFields> {
|
|
18
|
+
create(fields: CreateFields<TFields>): Promise<CogoverRecordId>;
|
|
19
|
+
update(id: CogoverRecordId, fields: UpdateFields<TFields>): Promise<void>;
|
|
20
|
+
batchInsert(records: readonly CreateFields<TFields>[]): Promise<BatchWriteResponse>;
|
|
21
|
+
batchUpdate(records: readonly BatchUpdateItem<TFields>[]): Promise<BatchWriteResponse>;
|
|
22
|
+
upsertByUniqueField<TMatchBy extends StringKeyOf<TFields>>(matchBy: TMatchBy, fields: UpsertFields<TFields, TMatchBy>): Promise<UpsertResult>;
|
|
23
|
+
deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
|
|
24
|
+
}
|
|
25
|
+
export interface RecordsApi<TFields> extends RecordWritesApi<TFields> {
|
|
26
|
+
get(id: string, options?: GetRecordOptions<TFields>): Promise<CogoverRecord<TFields> | null>;
|
|
27
|
+
/** 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>>;
|
|
30
|
+
}
|
|
31
|
+
export interface WriteObjectClient<TFields> {
|
|
32
|
+
readonly slug: string;
|
|
33
|
+
readonly fields: FieldReferences<TFields>;
|
|
34
|
+
readonly records: RecordWritesApi<TFields>;
|
|
35
|
+
}
|
|
36
|
+
export interface ObjectClient<TFields> extends WriteObjectClient<TFields> {
|
|
37
|
+
readonly records: RecordsApi<TFields>;
|
|
38
|
+
}
|
|
39
|
+
/** Reads and writes as an approved personnel ID. Authorization is enforced by Cogover. */
|
|
40
|
+
export interface AsUserDataApi<TSchema extends object = EffectiveWorkspaceObjects> {
|
|
41
|
+
object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
|
|
42
|
+
}
|
|
43
|
+
export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
|
|
44
|
+
object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
|
|
45
|
+
/** New client for reads and writes as an approved personnel ID. */
|
|
46
|
+
asUser(personnelId: string): AsUserDataApi<TSchema>;
|
|
47
|
+
/** New system client, including in public invocations. Requires approval; does not change this client. */
|
|
48
|
+
asSystem(): DataApi<TSchema>;
|
|
49
|
+
}
|
package/dist/data.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { requireFieldSlug, requireFields, requireSlug, requireText } from "./internal/validation.js";
|
|
4
|
+
import { isRecord } from "./internal/values.js";
|
|
5
|
+
import { createFieldReferences } from "./query.js";
|
|
6
|
+
const MAX_BATCH_RECORDS = 200;
|
|
7
|
+
/** @internal */
|
|
8
|
+
export function createDataApi(identity) {
|
|
9
|
+
return Object.freeze({
|
|
10
|
+
object(slug) {
|
|
11
|
+
return createObjectClient(requireSlug(String(slug)), identity);
|
|
12
|
+
},
|
|
13
|
+
asUser(personnelId) {
|
|
14
|
+
const delegated = Object.freeze({ kind: "user", personnelId: requireText(personnelId, "personnelId") });
|
|
15
|
+
return Object.freeze({
|
|
16
|
+
object(slug) {
|
|
17
|
+
return createObjectClient(requireSlug(String(slug)), delegated);
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
},
|
|
21
|
+
asSystem() {
|
|
22
|
+
return createDataApi(Object.freeze({ kind: "system" }));
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function createObjectClient(slug, identity) {
|
|
27
|
+
const fields = createFieldReferences();
|
|
28
|
+
const records = Object.freeze({
|
|
29
|
+
async get(id, options) {
|
|
30
|
+
return callBridge("records.get", {
|
|
31
|
+
identity,
|
|
32
|
+
objectSlug: slug,
|
|
33
|
+
id: requireText(id, "record id"),
|
|
34
|
+
fields: options?.fields,
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
async getMany(ids, options) {
|
|
38
|
+
if (!Array.isArray(ids)) {
|
|
39
|
+
throw new ValidationError("getMany() requires an array of record ids");
|
|
40
|
+
}
|
|
41
|
+
const uniqueIds = [...new Set(ids.map((id) => requireText(id, "record id")))];
|
|
42
|
+
if (uniqueIds.length > MAX_BATCH_RECORDS) {
|
|
43
|
+
throw new ValidationError(`getMany() supports at most ${MAX_BATCH_RECORDS} unique record ids`);
|
|
44
|
+
}
|
|
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)))];
|
|
50
|
+
if (uniqueIds.length === 0) {
|
|
51
|
+
return { records: [], missingIds: [] };
|
|
52
|
+
}
|
|
53
|
+
const result = await callBridge("records.getMany", {
|
|
54
|
+
identity,
|
|
55
|
+
objectSlug: slug,
|
|
56
|
+
ids: uniqueIds,
|
|
57
|
+
fields: fieldSlugs,
|
|
58
|
+
});
|
|
59
|
+
if (!isRecord(result) || !Array.isArray(result.records) || !Array.isArray(result.missingIds)) {
|
|
60
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.getMany returned an invalid result");
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
},
|
|
64
|
+
async list(options) {
|
|
65
|
+
return callBridge("records.list", {
|
|
66
|
+
identity,
|
|
67
|
+
objectSlug: slug,
|
|
68
|
+
where: options?.where,
|
|
69
|
+
orderBy: options?.orderBy,
|
|
70
|
+
fields: options?.fields,
|
|
71
|
+
limit: options?.limit,
|
|
72
|
+
cursor: options?.cursor,
|
|
73
|
+
});
|
|
74
|
+
},
|
|
75
|
+
async create(fieldsToCreate) {
|
|
76
|
+
return callBridge("records.create", {
|
|
77
|
+
identity,
|
|
78
|
+
objectSlug: slug,
|
|
79
|
+
fields: requireFields(fieldsToCreate),
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
async update(id, fieldsToUpdate) {
|
|
83
|
+
await callBridge("records.update", {
|
|
84
|
+
identity,
|
|
85
|
+
objectSlug: slug,
|
|
86
|
+
id: requireText(id, "record id"),
|
|
87
|
+
fields: requireFields(fieldsToUpdate),
|
|
88
|
+
});
|
|
89
|
+
},
|
|
90
|
+
async batchInsert(recordsToCreate) {
|
|
91
|
+
const records = requireBatch(recordsToCreate, "batchInsert").map((fields, index) => {
|
|
92
|
+
try {
|
|
93
|
+
return requireFields(fields);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
throw indexedValidationError(error, "batchInsert", index);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
return callBridge("records.batchInsert", {
|
|
100
|
+
identity,
|
|
101
|
+
objectSlug: slug,
|
|
102
|
+
records,
|
|
103
|
+
});
|
|
104
|
+
},
|
|
105
|
+
async batchUpdate(recordsToUpdate) {
|
|
106
|
+
const records = requireBatch(recordsToUpdate, "batchUpdate").map((item, index) => {
|
|
107
|
+
if (!isRecord(item)) {
|
|
108
|
+
throw new ValidationError(`batchUpdate record at index ${index} must be an object`);
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return {
|
|
112
|
+
id: requireText(item.id, `batchUpdate record id at index ${index}`),
|
|
113
|
+
fields: requireFields(item.fields),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
throw indexedValidationError(error, "batchUpdate", index);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
return callBridge("records.batchUpdate", {
|
|
121
|
+
identity,
|
|
122
|
+
objectSlug: slug,
|
|
123
|
+
records,
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
async upsertByUniqueField(matchBy, fieldsToUpsert) {
|
|
127
|
+
const normalizedMatchBy = requireFieldSlug(matchBy, "matchBy");
|
|
128
|
+
const fields = requireFields(fieldsToUpsert);
|
|
129
|
+
const businessValue = fields[normalizedMatchBy];
|
|
130
|
+
if (!Object.prototype.hasOwnProperty.call(fields, normalizedMatchBy)
|
|
131
|
+
|| businessValue === null || businessValue === undefined
|
|
132
|
+
|| (typeof businessValue === "string" && businessValue.trim() === "")
|
|
133
|
+
|| (Array.isArray(businessValue) && businessValue.length === 0)) {
|
|
134
|
+
throw new ValidationError(`upsertByUniqueField() requires a non-empty '${normalizedMatchBy}' value`);
|
|
135
|
+
}
|
|
136
|
+
return callBridge("records.upsertByUniqueField", {
|
|
137
|
+
identity,
|
|
138
|
+
objectSlug: slug,
|
|
139
|
+
matchBy: normalizedMatchBy,
|
|
140
|
+
fields,
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
async deleteMany(ids) {
|
|
144
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
145
|
+
throw new ValidationError("deleteMany() requires at least one record id");
|
|
146
|
+
}
|
|
147
|
+
return callBridge("records.deleteMany", {
|
|
148
|
+
identity,
|
|
149
|
+
objectSlug: slug,
|
|
150
|
+
ids: ids.map((id) => requireText(id, "record id")),
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
return Object.freeze({ slug, fields, records });
|
|
155
|
+
}
|
|
156
|
+
function requireBatch(records, operation) {
|
|
157
|
+
if (!Array.isArray(records) || records.length === 0) {
|
|
158
|
+
throw new ValidationError(`${operation}() requires at least one record`);
|
|
159
|
+
}
|
|
160
|
+
if (records.length > MAX_BATCH_RECORDS) {
|
|
161
|
+
throw new ValidationError(`${operation}() supports at most ${MAX_BATCH_RECORDS} records`);
|
|
162
|
+
}
|
|
163
|
+
return records;
|
|
164
|
+
}
|
|
165
|
+
function indexedValidationError(error, operation, index) {
|
|
166
|
+
if (error instanceof ValidationError) {
|
|
167
|
+
return new ValidationError(`${operation} record at index ${index}: ${error.message}`, error.details);
|
|
168
|
+
}
|
|
169
|
+
return new ValidationError(`${operation} record at index ${index} is invalid`);
|
|
170
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export declare class CogoverApiError extends Error {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
/** Original server result code; undefined for errors without a server response. */
|
|
4
|
+
readonly r: number | undefined;
|
|
5
|
+
readonly details?: unknown;
|
|
6
|
+
constructor(code: string, message: string, details?: unknown);
|
|
7
|
+
}
|
|
8
|
+
export declare class NotFoundError extends CogoverApiError {
|
|
9
|
+
readonly resource: string;
|
|
10
|
+
readonly resourceId: string;
|
|
11
|
+
constructor(resource: string, resourceId: string, message?: string, details?: unknown);
|
|
12
|
+
}
|
|
13
|
+
export declare class ValidationError extends CogoverApiError {
|
|
14
|
+
constructor(message: string, details?: unknown);
|
|
15
|
+
}
|
|
16
|
+
export declare class PermissionDeniedError extends CogoverApiError {
|
|
17
|
+
constructor(message: string, details?: unknown);
|
|
18
|
+
}
|
|
19
|
+
export declare class RateLimitError extends CogoverApiError {
|
|
20
|
+
constructor(message: string, details?: unknown);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs the handler again
|
|
24
|
+
* later. Anywhere else it is an ordinary failure.
|
|
25
|
+
*/
|
|
26
|
+
export declare class RetryableError extends CogoverApiError {
|
|
27
|
+
constructor(message: string, details?: unknown);
|
|
28
|
+
}
|
|
29
|
+
export declare class StateConflictError extends CogoverApiError {
|
|
30
|
+
constructor(message: string, details?: unknown);
|
|
31
|
+
}
|
|
32
|
+
export declare class LockUnavailableError extends CogoverApiError {
|
|
33
|
+
constructor(key: string, message?: string, details?: unknown);
|
|
34
|
+
}
|
|
35
|
+
export declare class LockLostError extends CogoverApiError {
|
|
36
|
+
constructor(message: string, details?: unknown);
|
|
37
|
+
}
|