@cogover/sdk 0.12.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.
@@ -0,0 +1,198 @@
1
+ # API reference: `@cogover/sdk`
2
+
3
+ `@cogover/sdk` is the public TypeScript contract for developing Custom Backend
4
+ Modules on Cogover. Cogover authentication credentials are never exposed to
5
+ module code; capability calls are restricted by the permissions and limits
6
+ configured for the project.
7
+
8
+ ## Contents
9
+
10
+ The reference is split into the following pages. Each page covers one area of the SDK.
11
+
12
+ | Page | Covers |
13
+ |---|---|
14
+ | [Scripts and HTTP routes](scripts-and-routes.md) | `defineScript`; HTTP routers and request context; Invocation identity and workspace; HTTP response API; Logging |
15
+ | [Records and schema](records.md) | Record API; Filters and sorting; Record execution identities; Schema API; Workspace declarations |
16
+ | [Record triggers](record-triggers.md) | Record triggers |
17
+ | [Background jobs](background-jobs.md) | Background jobs |
18
+ | [Outbound HTTP and secrets](fetch-and-secrets.md) | Outbound HTTP `fetch`; Secrets and credentials |
19
+ | [Cryptography](cryptography.md) | Cryptography |
20
+ | [Inbound webhooks](inbound-webhooks.md) | Inbound webhooks |
21
+ | [Project state and locks](state-and-locks.md) | Project state; Distributed locks |
22
+ | [Push messages](push-messages.md) | Push messages |
23
+ | [Notifications and email](notifications-and-email.md) | Notifications; Email |
24
+ | [Organization structure](organization-structure.md) | Organization structure |
25
+
26
+ The sections below apply to every area: the errors every API can throw, the limits of one execution, and the compatibility helper.
27
+
28
+ ## Errors
29
+
30
+ API failures become `NotFoundError`, `ValidationError`,
31
+ `PermissionDeniedError`, `RateLimitError`, `RetryableError`, `StateConflictError`,
32
+ `LockUnavailableError`, `LockLostError`, or `CogoverApiError`.
33
+
34
+ ```typescript
35
+ class CogoverApiError extends Error {
36
+ readonly code: string;
37
+ readonly r: number | undefined;
38
+ readonly details?: unknown;
39
+ constructor(code: string, message: string, details?: unknown);
40
+ }
41
+
42
+ class NotFoundError extends CogoverApiError {
43
+ readonly resource: string;
44
+ readonly resourceId: string;
45
+ constructor(resource: string, resourceId: string, message?: string, details?: unknown);
46
+ }
47
+
48
+ class ValidationError extends CogoverApiError {
49
+ constructor(message: string, details?: unknown);
50
+ }
51
+
52
+ class PermissionDeniedError extends CogoverApiError {
53
+ constructor(message: string, details?: unknown);
54
+ }
55
+
56
+ class RateLimitError extends CogoverApiError {
57
+ constructor(message: string, details?: unknown);
58
+ }
59
+
60
+ class RetryableError extends CogoverApiError {
61
+ constructor(message: string, details?: unknown);
62
+ }
63
+
64
+ class StateConflictError extends CogoverApiError {
65
+ constructor(message: string, details?: unknown);
66
+ }
67
+
68
+ class LockUnavailableError extends CogoverApiError {
69
+ constructor(key: string, message?: string, details?: unknown);
70
+ }
71
+
72
+ class LockLostError extends CogoverApiError {
73
+ constructor(message: string, details?: unknown);
74
+ }
75
+ ```
76
+
77
+ Errors expose the SDK category in `error.code` and the original numeric server
78
+ result in `error.r` (also retained in `error.details.r`). `r` is `undefined` when
79
+ there was no server response, such as local SDK validation. The original message
80
+ remains in `error.message`.
81
+
82
+ `RetryableError` (`code: "RETRYABLE"`) reports a temporary failure. The SDK throws it
83
+ for a record write that a before-change trigger could not check (`details.reason`
84
+ `"TRIGGER_FAILED"`, see [Record triggers](record-triggers.md#validating-and-changing-records)),
85
+ and project code throws it itself. An after-change trigger handler or a job handler
86
+ throws it to report a temporary failure, and Cogover runs the handler again later (see
87
+ [After-change execution rules](record-triggers.md#after-change-execution-rules) and
88
+ [Job execution rules](background-jobs.md#job-execution-rules)). Anywhere else it has no special
89
+ meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
90
+ that throws it rejects the write like any other failure.
91
+
92
+ `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
93
+ `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
94
+ with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
95
+ the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
96
+ `crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
97
+ the ciphertext cannot be decrypted.
98
+
99
+ `notifications.send` and `email.send` fail with `ValidationError`, `NotFoundError`,
100
+ `PermissionDeniedError`, or `RateLimitError` as described in their sections, with
101
+ `CogoverApiError` whose `code` is `NOTIFICATIONS_DISABLED` or `EMAIL_DISABLED` when
102
+ the feature is switched off, and with `CogoverApiError` whose `code` is
103
+ `DUPLICATE_IN_PROGRESS` while an earlier call with the same `idempotencyKey` is
104
+ still sending. A sender mailbox that the Project policy does not allow is reported
105
+ as `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`.
106
+
107
+ Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
108
+ error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
109
+ the original code or message. A script's returned JSON remains its own response
110
+ with HTTP 200. All client-facing text in `msg`, `message`, and equivalent response
111
+ fields must be written in English, including responses created by customer scripts.
112
+
113
+ ```typescript
114
+ try {
115
+ await orders.records.update(id, fields);
116
+ } catch (error) {
117
+ if (error instanceof CogoverApiError && error.r === 37) {
118
+ return { r: 1001, msg: "You do not have permission to update this order." };
119
+ }
120
+ throw error;
121
+ }
122
+ ```
123
+
124
+ Import `CogoverApiError` from `@cogover/sdk`.
125
+
126
+ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
127
+ `r` equal to the HTTP status, `code`, and a safe `msg`:
128
+
129
+ | SDK code | HTTP / `r` |
130
+ |---|---|
131
+ | `PERMISSION_DENIED` | 403 |
132
+ | `NOT_FOUND` | 404 |
133
+ | `METHOD_NOT_ALLOWED` | 405 |
134
+ | `VALIDATION_ERROR` | 400 |
135
+ | `RATE_LIMITED` | 429 |
136
+ | `STATE_CONFLICT` | 409 |
137
+ | `LOCK_NOT_ACQUIRED` | 409 |
138
+ | `LOCK_LOST` | 409 |
139
+ | `STATE_SERVICE_UNAVAILABLE` | 503 |
140
+ | `LOCK_SERVICE_UNAVAILABLE` | 503 |
141
+ | `ORGANIZATION_UNAVAILABLE` | 503 |
142
+ | `FETCH_DISABLED` | 503 |
143
+ | `FETCH_BLOCKED` | 400 |
144
+ | `FETCH_REQUEST_TOO_LARGE` | 413 |
145
+ | `FETCH_RESPONSE_TOO_LARGE` | 502 |
146
+ | `FETCH_TIMEOUT` | 504 |
147
+ | `FETCH_FAILED` | 502 |
148
+ | `COGOVER_API_ERROR` | 422 |
149
+ | `RETRYABLE` | 422 |
150
+
151
+ Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
152
+ it does not mean the selected user was denied access to a particular record.
153
+ Raw error messages, stack traces and arbitrary details are not returned.
154
+ `writesMayHaveCompleted` is true if the execution sent any call that can change
155
+ something outside it, even if a later operation failed: a record write, `state.set` or
156
+ `state.delete`, any `locks` call (including an `acquire` that returned `null`), a push
157
+ message, `notifications.send`, `email.send`, or a `fetch` whose method is not `GET` or
158
+ `HEAD`. A `LockUnavailableError` that escapes a script therefore always reports `true`.
159
+ It is a conservative warning, not confirmation of a successful write.
160
+ Unknown errors and resource-limit failures retain the generic HTTP 422 response.
161
+ These responses do not roll back earlier writes; do not retry writes automatically.
162
+
163
+ ## Execution limits
164
+
165
+ Every execution runs within platform limits. These are the default values; they are
166
+ set by the platform and may differ between environments.
167
+
168
+ - An HTTP route and a record trigger may make at most 20 capability calls. Every call
169
+ to `data`, `schema`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`,
170
+ `secrets`, `crypto`, `org`, or `fetch` counts once. A background job may make 200.
171
+ The call over the budget, and every call after it, throws `RateLimitError`
172
+ (`details.limit` is the budget) without being sent, so a script can catch it.
173
+ - An HTTP route has 8 seconds of wall-clock time, counted from when its handler
174
+ starts, including the time spent waiting for capability calls, a lock, or a remote
175
+ server. A record trigger has its own `timeoutMs`, and a background job its
176
+ `timeoutMs`. Exceeding the time ends the whole execution: the script cannot catch it,
177
+ and an HTTP route returns the generic HTTP 422 response.
178
+ - A single capability request, JSON-encoded with its arguments, must not exceed
179
+ 262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
180
+ or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
181
+ is the limit. A capability result larger than 1,048,576 bytes is withheld the same
182
+ way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records or fields. The
183
+ operation itself did run, so a write may have completed.
184
+ - When the Workspace already has too many executions waiting, a new HTTP call is
185
+ refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
186
+
187
+ When an API has its own per-execution quota that is not below the call budget, such
188
+ as 20 `fetch` calls or 20 secret reads, the call budget is reached first in a route
189
+ or a trigger; both are reported as `RateLimitError`.
190
+
191
+ ## Compatibility helper
192
+
193
+ ```typescript
194
+ function createGreeting(name: string): string;
195
+ ```
196
+
197
+ `createGreeting("Cogover")` returns `"Hello Cogover"`. It remains available for
198
+ SDK 0.1.x compatibility and is not part of the data APIs.
@@ -0,0 +1,115 @@
1
+ # `@cogover/sdk` API reference: Push messages
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Push messages
6
+
7
+ `push` sends messages to the web clients of the workspace: a request to reload
8
+ records, a toast, or a background message the client handles silently. It is the
9
+ same mechanism as the Workflow "Push Message" action, so the standard record pages
10
+ react without custom client code. Delivery is best-effort: a call resolves once the
11
+ messages are handed to Cogover, never when a client receives them.
12
+
13
+ ```typescript
14
+ type PushRecipients = "viewers" | readonly string[];
15
+
16
+ interface PushOptions {
17
+ readonly recipients?: PushRecipients;
18
+ readonly exclude?: readonly string[];
19
+ }
20
+
21
+ type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT"
22
+ | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
23
+ type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
24
+
25
+ interface ToastLink {
26
+ readonly label: string;
27
+ readonly url: string;
28
+ }
29
+
30
+ interface ToastMessage<ObjectSlug extends string = string> {
31
+ readonly title?: string;
32
+ readonly content?: string;
33
+ readonly links?: readonly ToastLink[];
34
+ readonly position?: ToastPosition;
35
+ readonly size?: ToastSize;
36
+ readonly durationSeconds?: number;
37
+ readonly object?: ObjectSlug;
38
+ readonly recordIds?: readonly string[];
39
+ }
40
+
41
+ type BackgroundContentType = "text" | "template";
42
+
43
+ interface BackgroundMessage<ObjectSlug extends string = string> {
44
+ readonly content: string;
45
+ readonly contentType?: BackgroundContentType;
46
+ readonly object?: ObjectSlug;
47
+ readonly recordIds?: readonly string[];
48
+ }
49
+
50
+ interface PushApi<Schema extends object = EffectiveWorkspaceObjects> {
51
+ refreshRecords(object: StringKeyOf<Schema>, recordIds: readonly string[],
52
+ options?: PushOptions): Promise<void>;
53
+ toast(message: ToastMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
54
+ message(message: BackgroundMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
55
+ }
56
+ ```
57
+
58
+ ```typescript
59
+ // After-change trigger: the handler changed the records, so everyone who has them
60
+ // open must reload, including the user whose save started the trigger.
61
+ await data.object("order").records.batchUpdate(items);
62
+ await push.refreshRecords("order", items.map(item => item.id));
63
+ ```
64
+
65
+ ### Recipients
66
+
67
+ Every method accepts the same `options`. `recipients` defaults to `"viewers"`:
68
+ everyone who currently has one of the target records open receives the message, so
69
+ `object` and `recordIds` are required. A list of personnel IDs delivers to those
70
+ people wherever they are in the workspace; `object` and `recordIds` are then
71
+ optional for `toast` and `message` and, when given, tell the client which records
72
+ the message is about. `exclude` lists personnel IDs that never receive the message;
73
+ the special value `"actor"` is the user whose action started the current execution
74
+ (the caller of an HTTP script, the user whose save ran a trigger). A system
75
+ execution has no actor, so `"actor"` excludes nobody. Personnel without a user
76
+ account are skipped silently; an unknown personnel ID or object slug throws
77
+ `NotFoundError` before anything is sent. `recordIds` accepts at most 200 distinct
78
+ record IDs, and `recipients` and `exclude` each at most 200 entries, counted before
79
+ duplicates are removed; duplicates are then removed. Cogover does not check that the
80
+ record IDs exist: a message about a record that does not exist reaches no viewer.
81
+
82
+ ### `push.refreshRecords(object, recordIds, options?): Promise<void>`
83
+
84
+ Asks the clients that show these records to reload them. The record page of the
85
+ web app handles the request itself. `recordIds` accepts 1 to 200 IDs.
86
+
87
+ ### `push.toast(message, options?): Promise<void>`
88
+
89
+ Shows a short notification. At least one of `title` (up to 200 characters) and
90
+ `content` (up to 4,000 characters) is required. `links` holds up to 5 entries whose
91
+ `url` is an absolute `http` or `https` URL. `position` defaults to `"TOP_RIGHT"`,
92
+ `size` to `"MEDIUM"` and `durationSeconds` to 5 (1 to 60). When `object` and
93
+ `recordIds` are given, the client shows the toast only while one of those records
94
+ is open.
95
+
96
+ ### `push.message(message, options?): Promise<void>`
97
+
98
+ Sends a message the client handles without a visible notification, for example a
99
+ custom component listening for it. `content` is required (up to 16,384 characters);
100
+ `contentType` is `"text"` (default) or `"template"`.
101
+
102
+ ### Rules
103
+
104
+ - Each call costs one capability call regardless of the number of records or
105
+ recipients; when the recipients are `"viewers"`, one message is sent per record.
106
+ - Inputs are validated by the SDK and again by Cogover; invalid input throws
107
+ `ValidationError` before any message is sent.
108
+ - `push` is available in scripts, routes, after-change triggers and Development
109
+ Sessions. A before-change trigger is read-only and receives `PermissionDeniedError`
110
+ with reason `TRIGGER_READ_ONLY`; a read-only Development Session refuses it too.
111
+ - When push messages are switched off for the deployment, every call throws
112
+ `CogoverApiError` with code `PUSH_DISABLED`; an HTTP route that does not catch it
113
+ returns the generic HTTP 422 response.
114
+ - A sent message cannot be recalled, and retrying a failed execution may send it
115
+ again.