@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.
- package/README.md +65 -21
- package/dist/crypto.js +89 -46
- package/dist/data.js +4 -1
- package/dist/email.d.ts +77 -0
- package/dist/email.js +192 -0
- package/dist/index.d.ts +2 -0
- package/dist/internal/base64.js +76 -27
- package/dist/internal/bridge.js +41 -3
- package/dist/internal/job-config.js +7 -1
- package/dist/internal/job-runtime.js +4 -0
- package/dist/internal/messaging.js +75 -0
- package/dist/internal/trigger-runtime.js +5 -0
- package/dist/internal/utf8.js +18 -17
- package/dist/jobs.d.ts +4 -0
- package/dist/locks.js +13 -3
- package/dist/logger.js +47 -1
- package/dist/notifications.d.ts +56 -0
- package/dist/notifications.js +92 -0
- package/dist/org.js +14 -14
- package/dist/records.d.ts +13 -0
- package/dist/response.js +21 -1
- package/dist/router.js +2 -0
- package/dist/schema.d.ts +1 -0
- package/dist/script.d.ts +4 -0
- package/dist/script.js +11 -3
- package/dist/trigger.d.ts +6 -0
- package/docs/en/api-reference/background-jobs.md +288 -0
- package/docs/en/api-reference/cryptography.md +317 -0
- package/docs/en/api-reference/fetch-and-secrets.md +184 -0
- package/docs/en/api-reference/inbound-webhooks.md +65 -0
- package/docs/en/api-reference/notifications-and-email.md +317 -0
- package/docs/en/api-reference/organization-structure.md +304 -0
- package/docs/en/api-reference/overview.md +198 -0
- package/docs/en/api-reference/push-messages.md +115 -0
- package/docs/en/api-reference/record-triggers.md +469 -0
- package/docs/en/api-reference/records.md +447 -0
- package/docs/en/api-reference/scripts-and-routes.md +354 -0
- package/docs/en/api-reference/state-and-locks.md +162 -0
- package/docs/en/usage-guide.md +218 -19
- package/package.json +1 -1
- package/docs/en/api-reference.md +0 -2619
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Outbound HTTP and secrets
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Outbound HTTP `fetch`
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
|
|
9
|
+
|
|
10
|
+
interface CogoverFetchInit {
|
|
11
|
+
readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
12
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
13
|
+
readonly body?: string;
|
|
14
|
+
readonly timeoutMs?: number;
|
|
15
|
+
readonly credential?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface CogoverFetchHeaders {
|
|
19
|
+
get(name: string): string | null;
|
|
20
|
+
has(name: string): boolean;
|
|
21
|
+
entries(): IterableIterator<[string, string]>;
|
|
22
|
+
[Symbol.iterator](): IterableIterator<[string, string]>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface CogoverFetchResponse {
|
|
26
|
+
readonly ok: boolean;
|
|
27
|
+
readonly status: number;
|
|
28
|
+
readonly statusText: string;
|
|
29
|
+
readonly url: string;
|
|
30
|
+
readonly redirected: false;
|
|
31
|
+
readonly headers: CogoverFetchHeaders;
|
|
32
|
+
readonly bodyUsed: boolean;
|
|
33
|
+
text(): Promise<string>;
|
|
34
|
+
json<T = unknown>(): Promise<T>;
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Cogover installs the global `fetch()` function in the hosted runtime. Import
|
|
39
|
+
`{ fetch }` from `@cogover/sdk` when the dependency should be explicit; this also
|
|
40
|
+
prevents local Node.js from silently using its native, unrestricted `fetch` during
|
|
41
|
+
tests. The SDK function requires the Cogover runtime and always uses Cogover's
|
|
42
|
+
managed network layer. `input` must be an absolute public HTTPS URL without
|
|
43
|
+
userinfo, a fragment, or an IP-literal host, on port 443 or on an origin approved
|
|
44
|
+
for the project (see [Other ports](#other-ports)). `body` accepts only a string;
|
|
45
|
+
use `JSON.stringify()` for JSON. `timeoutMs` must be a positive integer and is
|
|
46
|
+
always clamped by the platform limit. It never extends the execution: an HTTP route
|
|
47
|
+
has 8 seconds in total by default, so there a slower server ends the whole execution
|
|
48
|
+
(see [Execution limits](overview.md#execution-limits)).
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import { fetch } from "@cogover/sdk";
|
|
52
|
+
|
|
53
|
+
const response = await fetch("https://api.example.com/v1/orders", {
|
|
54
|
+
method: "POST",
|
|
55
|
+
headers: { "content-type": "application/json" },
|
|
56
|
+
body: JSON.stringify({ id: "ORD-1" }),
|
|
57
|
+
timeoutMs: 5_000,
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`CogoverFetchResponse` exposes `ok`, `status`, `statusText`, `url`, `redirected`
|
|
62
|
+
(always `false`), `headers`, `bodyUsed`, `text()`, and `json<T>()`. The bounded,
|
|
63
|
+
buffered body can be consumed once. Header `get(name)`, `has(name)`, `entries()`,
|
|
64
|
+
and iteration are case-insensitive.
|
|
65
|
+
|
|
66
|
+
V1 does not follow redirects, persist or send cookies, stream requests/responses,
|
|
67
|
+
or support WebSocket. It does not accept `signal`, `credentials`, `redirect`, proxy,
|
|
68
|
+
dispatcher, agent, DNS resolver, or TLS configuration. HTTP URLs, ports other than
|
|
69
|
+
443 that the project has not been approved for, userinfo, and IP-literal hosts are
|
|
70
|
+
unsupported. Framing, hop-by-hop, proxy,
|
|
71
|
+
forwarding, and reserved Cogover request headers are rejected. Request/response sizes,
|
|
72
|
+
headers, time, calls, destinations, and concurrency are bounded by platform quotas.
|
|
73
|
+
|
|
74
|
+
- A `GET` or `HEAD` request with a `body` fails with `FETCH_BLOCKED`.
|
|
75
|
+
- A compressed response, one whose `Content-Encoding` is not `identity`, fails with
|
|
76
|
+
`FETCH_BLOCKED`.
|
|
77
|
+
- The response body is decoded as UTF-8: bytes that are not valid UTF-8 become
|
|
78
|
+
U+FFFD, so binary content cannot be read exactly.
|
|
79
|
+
- A host name that resolves to an address that is not public fails with
|
|
80
|
+
`FETCH_FAILED`.
|
|
81
|
+
- Calls started together, for example with `Promise.all`, are sent one after another.
|
|
82
|
+
- A before-change trigger cannot call `fetch`: it throws `PermissionDeniedError` with
|
|
83
|
+
`details.reason` `"TRIGGER_READ_ONLY"`. A read-only version preview allows only `GET`
|
|
84
|
+
and `HEAD` without `credential` and refuses other calls with `PermissionDeniedError`.
|
|
85
|
+
|
|
86
|
+
Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
|
|
87
|
+
`FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
|
|
88
|
+
`FETCH_FAILED`; quota failures use `RateLimitError`. One execution may make at most 20
|
|
89
|
+
`fetch` calls; an HTTP route or a trigger reaches its budget of 20 capability calls
|
|
90
|
+
first, which is also reported as `RateLimitError` (see
|
|
91
|
+
[Execution limits](overview.md#execution-limits)). When POST, PUT, PATCH, or DELETE
|
|
92
|
+
times out or loses its response, the remote server may already have applied the
|
|
93
|
+
request. Use the remote API's idempotency mechanism and never retry blindly.
|
|
94
|
+
|
|
95
|
+
### Other ports
|
|
96
|
+
|
|
97
|
+
A system that is only published on another port, such as
|
|
98
|
+
`https://erp.example.com:9899`, can be called once a Workspace administrator approves
|
|
99
|
+
that exact origin in the `fetch` section of the project's identity policy. The
|
|
100
|
+
approval covers only the listed `https://host:port` origins; other ports of the same
|
|
101
|
+
host stay blocked. Everything else in this section still applies to an approved
|
|
102
|
+
origin: HTTPS with a certificate that is valid for the host name, public addresses
|
|
103
|
+
only, no redirects, and the same limits. A URL on a port that is not approved fails
|
|
104
|
+
with `FETCH_BLOCKED`. Requests leave Cogover from outbound addresses shared with other
|
|
105
|
+
Workspaces, so a firewall allowlist of those addresses does not identify your
|
|
106
|
+
Workspace: have the target system authenticate the request, for example with a
|
|
107
|
+
credential.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// Allowed only after "https://erp.example.com:9899" is approved for this project.
|
|
111
|
+
const orders = await fetch("https://erp.example.com:9899/api/orders?status=new");
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Authenticating with a credential
|
|
115
|
+
|
|
116
|
+
`credential` names a credential that an administrator stored for the project (see
|
|
117
|
+
[Secrets and credentials](#secrets-and-credentials)). Cogover adds the credential's
|
|
118
|
+
authentication header to the request, so project code never handles the value:
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
const response = await fetch("https://erp.example.com/v1/orders", {
|
|
122
|
+
method: "POST",
|
|
123
|
+
credential: "erp_api",
|
|
124
|
+
headers: { "content-type": "application/json" },
|
|
125
|
+
body: JSON.stringify({ id: "ORD-1" }),
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Depending on how the credential was created, Cogover sends `Authorization: Bearer
|
|
130
|
+
<value>`, `Authorization: Basic <base64 of value>`, or a header with the configured
|
|
131
|
+
name. The name must start with a letter and contain at most 64 letters, digits, or
|
|
132
|
+
underscores. A credential can only be sent to the hosts its administrator allowed.
|
|
133
|
+
A host listed without a port allows port 443 only; to use the credential on an
|
|
134
|
+
approved origin on another port, the administrator lists `host:port`, for example
|
|
135
|
+
`erp.example.com:9899`. A request to another host or port, a request that sets the
|
|
136
|
+
same header itself, or a name
|
|
137
|
+
that is not an active credential fails with `FETCH_BLOCKED`. Redirects are never
|
|
138
|
+
followed, so a credential never leaves an allowed host.
|
|
139
|
+
|
|
140
|
+
## Secrets and credentials
|
|
141
|
+
|
|
142
|
+
An administrator stores secrets for a project through the Cogover management API.
|
|
143
|
+
Each one is either a **secret**, whose value code reads with `secrets.get`, or a
|
|
144
|
+
**credential**, which only `fetch` uses (see
|
|
145
|
+
[Authenticating with a credential](#authenticating-with-a-credential)); the value
|
|
146
|
+
of a credential is never readable by code. Values are stored encrypted and are
|
|
147
|
+
never returned by the management API, logged, or included in error messages.
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
interface SecretsApi {
|
|
151
|
+
get(name: string): Promise<string>;
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
const token = await secrets.get("erp_token");
|
|
157
|
+
const response = await fetch("https://erp.example.com/v1/orders", {
|
|
158
|
+
headers: { authorization: `Bearer ${token}` },
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### `secrets.get(name): Promise<string>`
|
|
163
|
+
|
|
164
|
+
Returns the current value of the secret. `name` starts with a letter and contains
|
|
165
|
+
at most 64 letters, digits, or underscores; other names throw `ValidationError`
|
|
166
|
+
before the call. A secret that does not exist or is disabled throws
|
|
167
|
+
`ValidationError` with the message `Secret '<name>' is not available`, and a
|
|
168
|
+
credential throws `ValidationError` with `Secret '<name>' is a credential and
|
|
169
|
+
cannot be read`.
|
|
170
|
+
|
|
171
|
+
`secrets.get` works in scripts and routes, after-change triggers, jobs, and inbound
|
|
172
|
+
webhook calls. A before-change trigger is refused with `PermissionDeniedError`
|
|
173
|
+
(`details.reason === "TRIGGER_READ_ONLY"`); a local development session reads
|
|
174
|
+
secrets only when its administrator allowed it, otherwise the reason is
|
|
175
|
+
`"SECRETS_NOT_ALLOWED"`. One invocation may read secrets at most 20 times; every
|
|
176
|
+
read counts, including a repeated read of the same name and a `crypto` operation keyed
|
|
177
|
+
by `{ secret: name }`, and the 21st throws `RateLimitError`. In an HTTP route or a
|
|
178
|
+
trigger the budget of 20 capability calls is reached first (see
|
|
179
|
+
[Execution limits](overview.md#execution-limits)). When secrets are
|
|
180
|
+
not enabled for the Workspace, the error is `CogoverApiError` with
|
|
181
|
+
`code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
|
|
182
|
+
state, or to a response. To sign, encrypt, or decrypt with a secret without
|
|
183
|
+
reading it, pass `{ secret: name }` as the key of a [`crypto`](cryptography.md#cryptography)
|
|
184
|
+
operation.
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Inbound webhooks
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Inbound webhooks
|
|
6
|
+
|
|
7
|
+
An administrator can create an **inbound access** for a project so that an external
|
|
8
|
+
system calls a route without a Cogover user session. The external system receives
|
|
9
|
+
a URL of the form
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
and authenticates each call with the inbound key or the HMAC signature that was
|
|
16
|
+
configured for the inbound access. Cogover verifies the key or signature, applies
|
|
17
|
+
the rate limit, and rejects the call before any project code runs. A route handler
|
|
18
|
+
sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
|
|
19
|
+
under `/hooks/` and the inbound ID is not part of the path.
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { createRouter } from "@cogover/sdk";
|
|
23
|
+
|
|
24
|
+
const router = createRouter();
|
|
25
|
+
router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
|
|
26
|
+
if (invocation.identity !== "inbound") return response.empty({ status: 403 });
|
|
27
|
+
|
|
28
|
+
// Optional: verify the external system's own signature over the raw body.
|
|
29
|
+
const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
|
|
30
|
+
if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
|
|
31
|
+
return response.empty({ status: 401 });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const event = request.body as { id: string; orderId: string };
|
|
35
|
+
await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
|
|
36
|
+
return response.json({ received: true }, { status: 202 });
|
|
37
|
+
});
|
|
38
|
+
export default router.toHandler();
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
|
|
42
|
+
and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
|
|
43
|
+
inbound access. `data.object()` acts as the system identity and works only if the
|
|
44
|
+
project's approved identity policy sets `allowInternalSystem: true`; it then has the
|
|
45
|
+
same access as in a scheduled job, which the objects granted to `data.asSystem()` do
|
|
46
|
+
not narrow. Otherwise its calls throw `PermissionDeniedError` with `details.reason`
|
|
47
|
+
`"IDENTITY_NOT_GRANTED"`. `data.asUser()` and `data.asSystem()` follow the grants of
|
|
48
|
+
the identity policy only when `allowInternalSystem` is `true`; otherwise they are
|
|
49
|
+
refused in the same way, even for granted objects.
|
|
50
|
+
- **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
|
|
51
|
+
`request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
|
|
52
|
+
`request.rawBody` always holds the body exactly as received, as a UTF-8 string,
|
|
53
|
+
and `request.contentType` the request's `Content-Type`, so a handler can verify a
|
|
54
|
+
signature or parse another format itself.
|
|
55
|
+
- **Response.** The handler's return value and the `response` helpers work as for
|
|
56
|
+
any route. Keep the handler short: acknowledge the event and enqueue a job for
|
|
57
|
+
the actual work, so that the external system gets a quick answer and retries
|
|
58
|
+
cannot overlap with slow processing.
|
|
59
|
+
- **Retries.** External systems usually retry a webhook that did not receive a
|
|
60
|
+
2xx response, so a handler may see the same event more than once. Use the event's
|
|
61
|
+
own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
|
|
62
|
+
An `Idempotency-Key` request header works as for any route. When the inbound access
|
|
63
|
+
checks an HMAC signature with a timestamp, each signature is accepted once, before
|
|
64
|
+
the handler runs: a retry that repeats the same signature is refused with HTTP 401,
|
|
65
|
+
even when the first attempt failed, so the sender must sign each retry again.
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Notifications and email
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Notifications
|
|
6
|
+
|
|
7
|
+
`notifications` saves a notification in the notification list (the bell) of each
|
|
8
|
+
recipient and delivers it in the web app, by web push, by mobile push, and as an
|
|
9
|
+
email copy, as the workspace's notification channels decide. Unlike a
|
|
10
|
+
[push message](push-messages.md#push-messages), a notification stays in the list after it was
|
|
11
|
+
delivered, so it suits something a person must act on later, such as an approval
|
|
12
|
+
request. Delivery is asynchronous and best-effort: a call resolves once Cogover has
|
|
13
|
+
accepted the notification, never when it reaches a device or an inbox.
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
type NotificationContentType = "text" | "html";
|
|
17
|
+
type NotificationDisplay = "SIMPLE" | "FULL";
|
|
18
|
+
type NotificationSender = "workspace" | "actor";
|
|
19
|
+
type NotificationLinkTarget = "SAME_TAB" | "NEW_TAB";
|
|
20
|
+
|
|
21
|
+
interface NotificationLink {
|
|
22
|
+
readonly url: string;
|
|
23
|
+
readonly openIn?: NotificationLinkTarget;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface NotificationMessage {
|
|
27
|
+
readonly to: readonly string[];
|
|
28
|
+
readonly exclude?: readonly string[];
|
|
29
|
+
readonly title: string;
|
|
30
|
+
readonly content: string;
|
|
31
|
+
readonly contentType?: NotificationContentType;
|
|
32
|
+
readonly subtitle?: string;
|
|
33
|
+
readonly display?: NotificationDisplay;
|
|
34
|
+
readonly link?: NotificationLink;
|
|
35
|
+
readonly sender?: NotificationSender;
|
|
36
|
+
readonly channel?: string;
|
|
37
|
+
readonly email?: boolean;
|
|
38
|
+
readonly idempotencyKey?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface NotificationResult {
|
|
42
|
+
readonly requestId: string;
|
|
43
|
+
readonly notified: number;
|
|
44
|
+
readonly skippedPersonnelIds: readonly string[];
|
|
45
|
+
readonly duplicate: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface NotificationsApi {
|
|
49
|
+
send(message: NotificationMessage): Promise<NotificationResult>;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
const result = await notifications.send({
|
|
55
|
+
to: approverIds,
|
|
56
|
+
exclude: ["actor"],
|
|
57
|
+
title: "Leave request waiting for your approval",
|
|
58
|
+
content: "A leave request of 3 days was submitted and needs your decision.",
|
|
59
|
+
link: { url: `/app/leave_request/${recordId}` },
|
|
60
|
+
channel: approvalChannelId,
|
|
61
|
+
idempotencyKey: `leave-approval:${recordId}`,
|
|
62
|
+
});
|
|
63
|
+
// result.notified: accounts addressed; result.skippedPersonnelIds: personnel without an account
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### `notifications.send(message): Promise<NotificationResult>`
|
|
67
|
+
|
|
68
|
+
**Recipients.** `to` lists 1 to 200 personnel IDs; duplicates are removed. The
|
|
69
|
+
notification goes to the user account of each personnel. Personnel without a user
|
|
70
|
+
account are skipped and returned in `skippedPersonnelIds`, and `notified` is the
|
|
71
|
+
number of accounts the notification was addressed to after exclusions. `exclude`
|
|
72
|
+
lists personnel IDs that never receive it; the special value `"actor"` is the user
|
|
73
|
+
whose action started the current execution (the caller of an HTTP route, the user
|
|
74
|
+
whose save ran a trigger, the user whose call enqueued a job run). An execution
|
|
75
|
+
without a user has no actor, so `"actor"` excludes nobody. A personnel ID in `to`
|
|
76
|
+
that does not exist throws `NotFoundError` with `resource` `"personnel"` before
|
|
77
|
+
anything is sent. When every recipient is excluded or skipped, nothing is sent and
|
|
78
|
+
`notified` is `0`.
|
|
79
|
+
|
|
80
|
+
**Content and appearance.**
|
|
81
|
+
|
|
82
|
+
- `title` (required, at most 200 characters) is the heading of the notification and
|
|
83
|
+
the subject of its email copy.
|
|
84
|
+
- `content` (required, at most 16,384 characters) is the body. With
|
|
85
|
+
`contentType: "text"`, the default, it is plain text. With `"html"` it is reduced
|
|
86
|
+
to basic formatting before it is stored — paragraphs, headings, lists, tables,
|
|
87
|
+
links, and emphasis; scripts, styles, and images are removed — and it must still
|
|
88
|
+
contain visible text, otherwise `ValidationError` is thrown.
|
|
89
|
+
- `subtitle` (at most 200 characters) is shown only in the `"FULL"` display.
|
|
90
|
+
`display` defaults to `"FULL"` when a subtitle is given and to `"SIMPLE"`
|
|
91
|
+
otherwise; a subtitle together with `display: "SIMPLE"` throws `ValidationError`.
|
|
92
|
+
- `link` is the page opened when the recipient clicks the notification. `url` is a
|
|
93
|
+
path of the Cogover web app starting with `/`, or an absolute `http` or `https`
|
|
94
|
+
URL, at most 2,048 characters. `openIn` is `"SAME_TAB"` or `"NEW_TAB"`; it defaults
|
|
95
|
+
to `"SAME_TAB"` for a path and to `"NEW_TAB"` for an absolute URL.
|
|
96
|
+
- `sender` is `"workspace"`, the default, or `"actor"`, which shows the name and
|
|
97
|
+
avatar of the user whose action started the execution. `"actor"` in an execution
|
|
98
|
+
without a user throws `ValidationError`.
|
|
99
|
+
|
|
100
|
+
**Channels and the email copy.** `channel` is the record ID of one of the
|
|
101
|
+
workspace's notification channels. The channel decides which deliveries are enabled
|
|
102
|
+
— in the web app, web push, mobile push, and email — and each user may override that
|
|
103
|
+
choice in their own notification settings. Without `channel`, every delivery is
|
|
104
|
+
enabled. An unknown channel throws `NotFoundError` with `resource`
|
|
105
|
+
`"notificationChannel"`; a workspace in which notifications are not set up throws
|
|
106
|
+
`NotFoundError` with `resource` `"object"` and `resourceId` `"notification_channel"`.
|
|
107
|
+
|
|
108
|
+
`email: false` leaves out the email copy even when the channel enables email. The
|
|
109
|
+
copy uses `title` as its subject and `content` as its body, is sent from a Cogover
|
|
110
|
+
notification address rather than from a workspace mailbox, and counts against the
|
|
111
|
+
daily notification-email limit of the workspace's plan. To send an email from a
|
|
112
|
+
workspace mailbox, use [`email.send`](#email).
|
|
113
|
+
|
|
114
|
+
**Idempotency.** `idempotencyKey` starts with a letter or digit and contains at most
|
|
115
|
+
128 letters, digits, `.`, `_`, `:`, or `-`. A call whose key the project already
|
|
116
|
+
used for a notification in the last 7 days sends nothing and returns the first
|
|
117
|
+
call's result with `duplicate: true`. A call made while the first call with the same
|
|
118
|
+
key is still sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`;
|
|
119
|
+
retry it a moment later. A call that failed does not keep its key, so it can be
|
|
120
|
+
retried. Keys belong to the project and are separate from the keys of `email.send`.
|
|
121
|
+
In an after-change trigger or a job, which may run more than once, derive the key
|
|
122
|
+
from `trigger.changeId` and `record.id`, or from `job.id` or a business key.
|
|
123
|
+
Cogover does not compare the content: a call that reuses a key with different
|
|
124
|
+
recipients or text still returns the first result and sends nothing.
|
|
125
|
+
|
|
126
|
+
### Rules
|
|
127
|
+
|
|
128
|
+
- `notifications` is available in scripts, routes, after-change triggers, background
|
|
129
|
+
jobs, inbound webhook calls, and Development Sessions with write permission. A
|
|
130
|
+
before-change trigger is read-only and receives `PermissionDeniedError` with
|
|
131
|
+
`details.reason` `"TRIGGER_READ_ONLY"`; a read-only preview and a read-only
|
|
132
|
+
Development Session refuse it too.
|
|
133
|
+
- Notifications need no grant in the identity policy: a project may notify any
|
|
134
|
+
personnel of the workspace.
|
|
135
|
+
- A project may address at most 5,000 recipients per hour by default. A call that
|
|
136
|
+
would exceed this throws `RateLimitError` and sends nothing.
|
|
137
|
+
- Inputs are validated by the SDK and again by Cogover; invalid input throws
|
|
138
|
+
`ValidationError` before anything is sent. Each call counts as one capability call.
|
|
139
|
+
- When notifications are switched off for the deployment, every call throws
|
|
140
|
+
`CogoverApiError` with code `NOTIFICATIONS_DISABLED`.
|
|
141
|
+
- A sent notification cannot be recalled. Retrying a failed execution may notify
|
|
142
|
+
again unless the call uses an `idempotencyKey`.
|
|
143
|
+
|
|
144
|
+
## Email
|
|
145
|
+
|
|
146
|
+
`email` sends email from the workspace's mailboxes: a shared workspace mailbox, or
|
|
147
|
+
the default personal mailbox of the user whose action started the execution. The
|
|
148
|
+
Project's approved identity policy decides which mailboxes a project may use. With
|
|
149
|
+
`record`, the email is also logged as an email activity on that record's timeline,
|
|
150
|
+
like an email sent from the record page. Sending is asynchronous: a call resolves
|
|
151
|
+
once Cogover has accepted the email for delivery, and a delivery failure after that
|
|
152
|
+
is not reported back to the script.
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
type EmailSender = { readonly mailbox: string } | "actor";
|
|
156
|
+
|
|
157
|
+
type EmailRecipient =
|
|
158
|
+
| string
|
|
159
|
+
| { readonly email: string; readonly name?: string }
|
|
160
|
+
| { readonly personnelId: string };
|
|
161
|
+
|
|
162
|
+
interface EmailRecordLink<ObjectSlug extends string = string> {
|
|
163
|
+
readonly object: ObjectSlug;
|
|
164
|
+
readonly recordId: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
interface EmailAttachment<ObjectSlug extends string = string> {
|
|
168
|
+
readonly object: ObjectSlug;
|
|
169
|
+
readonly recordId: string;
|
|
170
|
+
readonly field: string;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
type EmailMessage<ObjectSlug extends string = string> = {
|
|
174
|
+
readonly from: EmailSender;
|
|
175
|
+
readonly to?: readonly EmailRecipient[];
|
|
176
|
+
readonly cc?: readonly EmailRecipient[];
|
|
177
|
+
readonly bcc?: readonly EmailRecipient[];
|
|
178
|
+
readonly subject: string;
|
|
179
|
+
readonly record?: EmailRecordLink<ObjectSlug>;
|
|
180
|
+
readonly recordEmailFields?: readonly string[];
|
|
181
|
+
readonly attachments?: readonly EmailAttachment<ObjectSlug>[];
|
|
182
|
+
readonly appendSignature?: boolean;
|
|
183
|
+
readonly idempotencyKey?: string;
|
|
184
|
+
} & (
|
|
185
|
+
| { readonly html: string; readonly text?: never }
|
|
186
|
+
| { readonly text: string; readonly html?: never }
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
type EmailDelivery = "activity" | "direct";
|
|
190
|
+
|
|
191
|
+
interface EmailSendResult {
|
|
192
|
+
readonly requestId: string;
|
|
193
|
+
readonly delivery: EmailDelivery;
|
|
194
|
+
readonly recipients: number;
|
|
195
|
+
readonly duplicate: boolean;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type EmailSenderKind = "workspace" | "actor";
|
|
199
|
+
|
|
200
|
+
interface EmailSenderInfo {
|
|
201
|
+
readonly id: string;
|
|
202
|
+
readonly kind: EmailSenderKind;
|
|
203
|
+
readonly email: string;
|
|
204
|
+
readonly displayName: string;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
interface EmailApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
208
|
+
send(message: EmailMessage<StringKeyOf<Schema>>): Promise<EmailSendResult>;
|
|
209
|
+
senders(): Promise<readonly EmailSenderInfo[]>;
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
const result = await email.send({
|
|
215
|
+
from: { mailbox: "EMWXXXXXXXXXXXX" },
|
|
216
|
+
bcc: ["sales-archive@example.com"],
|
|
217
|
+
subject: `Quote ${quote.fields.code}`,
|
|
218
|
+
html: "<p>Dear customer,</p><p>Please find our quote attached.</p>",
|
|
219
|
+
record: { object: "quote", recordId: quote.id },
|
|
220
|
+
recordEmailFields: ["contact_email"],
|
|
221
|
+
attachments: [{ object: "quote", recordId: quote.id, field: "quote_pdf" }],
|
|
222
|
+
idempotencyKey: `quote-email:${quote.id}`,
|
|
223
|
+
});
|
|
224
|
+
// result.delivery === "activity": the email appears on the quote's timeline.
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### `email.send(message): Promise<EmailSendResult>`
|
|
228
|
+
|
|
229
|
+
**Sender.** `from: { mailbox: id }` sends from a shared workspace mailbox;
|
|
230
|
+
`from: "actor"` sends from the default personal mailbox of the user whose action
|
|
231
|
+
started the execution. The sender must be allowed by the `email` section of the
|
|
232
|
+
Project's approved identity policy: `workspaceMailboxIds` lists the shared mailboxes
|
|
233
|
+
and `allowActorMailbox` allows `"actor"`. Like the rest of the policy, the section
|
|
234
|
+
applies only to the callers selected by `callerPersonnelIds`, and to executions
|
|
235
|
+
without a user only when the policy sets `allowInternalSystem: true`. A project
|
|
236
|
+
whose policy has no `email` section cannot send email. A sender that is not allowed
|
|
237
|
+
throws `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`;
|
|
238
|
+
this check comes before anything else is looked up. A mailbox that does not exist or
|
|
239
|
+
is deactivated, and an actor without an active personal mailbox, throw
|
|
240
|
+
`NotFoundError` with `resource` `"mailbox"`. `"actor"` in an execution without a
|
|
241
|
+
user throws `ValidationError`.
|
|
242
|
+
|
|
243
|
+
**Recipients.**
|
|
244
|
+
|
|
245
|
+
- `to`, `cc`, and `bcc` accept an address string, `{ email, name? }`, or
|
|
246
|
+
`{ personnelId }`. A personnel is resolved to their work email, or to the email of
|
|
247
|
+
their user account when there is no work email; a personnel with neither throws
|
|
248
|
+
`ValidationError`, and an unknown personnel throws `NotFoundError` with `resource`
|
|
249
|
+
`"personnel"`.
|
|
250
|
+
- Duplicates are removed within each list, ignoring case. The three lists together
|
|
251
|
+
accept at most 50 recipients. A `name` is a single line of at most 200 characters.
|
|
252
|
+
- `to` must name at least one recipient unless `recordEmailFields` is given.
|
|
253
|
+
|
|
254
|
+
**Content.** `subject` is required: a single line of at most 255 characters. Provide
|
|
255
|
+
exactly one of `html` and `text`; the body is at most 192 KB (196,608 bytes) in
|
|
256
|
+
UTF-8, measured in its JSON-encoded form: each quote, backslash, or control character
|
|
257
|
+
such as a line break counts as its escape sequence (`\"` is 2 bytes, `\n` is 2 bytes,
|
|
258
|
+
`\u0001` is 6 bytes). A longer body throws `ValidationError` before the call.
|
|
259
|
+
|
|
260
|
+
**Record.** `record: { object, recordId }` logs the email as an email activity on
|
|
261
|
+
that record's timeline: Cogover tracks opens and link clicks and threads replies
|
|
262
|
+
with it, and `result.delivery` is `"activity"`. The record must be readable by the
|
|
263
|
+
default identity of the execution: a record that does not exist throws
|
|
264
|
+
`NotFoundError` with `resource` `"record"`, and a record that the identity may not
|
|
265
|
+
read throws `PermissionDeniedError`. Without `record`, the email is only sent from the mailbox and
|
|
266
|
+
`delivery` is `"direct"`. The following options require `record`; without it they
|
|
267
|
+
throw `ValidationError`:
|
|
268
|
+
|
|
269
|
+
- `recordEmailFields` lists up to 20 email fields of that record whose addresses are
|
|
270
|
+
added to `to`. A field that is not an email field throws `ValidationError`.
|
|
271
|
+
- `attachments` attaches every file stored in the file field `field` of each listed
|
|
272
|
+
record: at most 10 files and 20 MB in total. The records must be readable by the
|
|
273
|
+
default identity; a field that is not a file field throws `ValidationError`.
|
|
274
|
+
- `appendSignature: true` appends the sender's default email signature. It requires a
|
|
275
|
+
personal mailbox, that is `from: "actor"`; otherwise `ValidationError` is thrown.
|
|
276
|
+
|
|
277
|
+
**Result.** `requestId` identifies the send. `recipients` counts the addresses in
|
|
278
|
+
`to`, `cc`, and `bcc` after duplicates were removed; the addresses of
|
|
279
|
+
`recordEmailFields` are resolved later and are not counted. `duplicate` is `true`
|
|
280
|
+
when an earlier call with the same `idempotencyKey` already sent the email.
|
|
281
|
+
|
|
282
|
+
**Idempotency.** `idempotencyKey` follows the same rules as for
|
|
283
|
+
[notifications](#notifications): a retry with the same key within 7 days returns
|
|
284
|
+
the first result with `duplicate: true` instead of sending again, and a retry while
|
|
285
|
+
the first call is still sending throws `CogoverApiError` with
|
|
286
|
+
`code: "DUPLICATE_IN_PROGRESS"`. Email keys are separate from notification keys. As
|
|
287
|
+
for notifications, the content is not compared: reusing a key for a different email
|
|
288
|
+
returns the first result and sends nothing.
|
|
289
|
+
|
|
290
|
+
### `email.senders(): Promise<readonly EmailSenderInfo[]>`
|
|
291
|
+
|
|
292
|
+
Returns the active mailboxes this execution may send from: one `kind: "workspace"`
|
|
293
|
+
entry for each active shared mailbox that the applicable policy lists in
|
|
294
|
+
`workspaceMailboxIds`, to be used as `{ mailbox: id }`, and, when the policy sets
|
|
295
|
+
`allowActorMailbox` and the actor has an active personal mailbox, at most one
|
|
296
|
+
`kind: "actor"` entry describing the mailbox that `from: "actor"` uses. The list is
|
|
297
|
+
empty when the policy grants this execution no sender. Use it to show the available
|
|
298
|
+
senders or to pick one by `email` address instead of hard-coding an ID. It sends
|
|
299
|
+
nothing, so it also works in a read-only preview and a read-only Development
|
|
300
|
+
Session.
|
|
301
|
+
|
|
302
|
+
### Rules
|
|
303
|
+
|
|
304
|
+
- `email` is available in scripts, routes, after-change triggers, background jobs,
|
|
305
|
+
inbound webhook calls, and Development Sessions. A before-change trigger receives
|
|
306
|
+
`PermissionDeniedError` with `details.reason` `"TRIGGER_READ_ONLY"` for both
|
|
307
|
+
methods; a read-only preview and a read-only Development Session refuse
|
|
308
|
+
`email.send`.
|
|
309
|
+
- A project may send at most 500 emails per hour by default; beyond that,
|
|
310
|
+
`RateLimitError` is thrown and nothing is sent. One call is one email, however many
|
|
311
|
+
recipients it has.
|
|
312
|
+
- Inputs are validated by the SDK and again by Cogover; invalid input throws
|
|
313
|
+
`ValidationError` before anything is sent. Each call counts as one capability call.
|
|
314
|
+
- When email is switched off for the deployment, every call throws
|
|
315
|
+
`CogoverApiError` with code `EMAIL_DISABLED`.
|
|
316
|
+
- A sent email cannot be recalled. Retrying a failed execution may send it again
|
|
317
|
+
unless the call uses an `idempotencyKey`.
|