@cogover/sdk 0.11.0 → 0.12.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 +53 -12
- package/dist/email.d.ts +77 -0
- package/dist/email.js +190 -0
- package/dist/index.d.ts +2 -0
- 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/jobs.d.ts +4 -0
- package/dist/notifications.d.ts +56 -0
- package/dist/notifications.js +92 -0
- package/dist/router.js +2 -0
- package/dist/script.d.ts +4 -0
- package/dist/script.js +4 -0
- package/dist/trigger.d.ts +6 -0
- package/docs/en/api-reference.md +341 -16
- package/docs/en/usage-guide.md +203 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,10 +45,10 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
|
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
`defineScript` parses the input JSON, provides invocation metadata and scoped
|
|
48
|
-
data, schema, logging, state, lock, push, job, secret, and
|
|
49
|
-
the async handler, and serializes its result. Cogover
|
|
50
|
-
not exposed to project code, and Cogover enforces
|
|
51
|
-
limits on capability calls.
|
|
48
|
+
data, schema, logging, state, lock, push, notification, email, job, secret, and
|
|
49
|
+
crypto APIs, waits for the async handler, and serializes its result. Cogover
|
|
50
|
+
authentication credentials are not exposed to project code, and Cogover enforces
|
|
51
|
+
the configured permissions and limits on capability calls.
|
|
52
52
|
|
|
53
53
|
## Current identity and workspace
|
|
54
54
|
|
|
@@ -157,15 +157,15 @@ the trigger runs.
|
|
|
157
157
|
|
|
158
158
|
A handler receives up to 200 records per call, so read related data once with
|
|
159
159
|
`records.getMany` instead of once per record. Before-change triggers are read-only:
|
|
160
|
-
record writes, `fetch`, locks, state writes,
|
|
161
|
-
`PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`).
|
|
162
|
-
acts as the user who made the change. A handler that throws or exceeds its
|
|
160
|
+
record writes, `fetch`, locks, state writes, push messages, notifications, and email
|
|
161
|
+
are refused with `PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`).
|
|
162
|
+
`data.object()` acts as the user who made the change. A handler that throws or exceeds its
|
|
163
163
|
`timeoutMs` (default 2,000 ms) rejects the write.
|
|
164
164
|
|
|
165
165
|
An after-change trigger (`timing: "afterChange"`) is for follow-up work. It cannot
|
|
166
166
|
reject or modify the saved change (`addError` is only logged), but it may write
|
|
167
|
-
records
|
|
168
|
-
ID.
|
|
167
|
+
records, call `fetch`, and send notifications and email. `record.new` holds the
|
|
168
|
+
saved values, including the record ID.
|
|
169
169
|
|
|
170
170
|
```typescript
|
|
171
171
|
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
@@ -244,9 +244,10 @@ export const jobs = [
|
|
|
244
244
|
|
|
245
245
|
A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
|
|
246
246
|
to `enqueue` or `null`, and the same `data`, `schema`, `log`, `state`, `locks`,
|
|
247
|
-
`jobs`, `secrets`, `crypto`, and `org` APIs as a script.
|
|
248
|
-
and retried with growing delays when the handler
|
|
249
|
-
out, up to `maxAttempts` (default 5) attempts;
|
|
247
|
+
`notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
|
|
248
|
+
Runs are delivered at least once and retried with growing delays when the handler
|
|
249
|
+
throws `RetryableError` or times out, up to `maxAttempts` (default 5) attempts;
|
|
250
|
+
other errors fail the run. A run
|
|
250
251
|
enqueued from a route acts as that route's user, while a scheduled run uses the
|
|
251
252
|
system identity. `jobs.enqueue(key, payload?, { delayMs?, runAt?, idempotencyKey? })`
|
|
252
253
|
returns `{ runId, duplicate }`.
|
|
@@ -509,6 +510,46 @@ Delivery is best-effort, each call counts as one capability call, and before-cha
|
|
|
509
510
|
triggers cannot push. Invalid input throws `ValidationError`; an unknown object or
|
|
510
511
|
personnel throws `NotFoundError`.
|
|
511
512
|
|
|
513
|
+
## Notifications and email
|
|
514
|
+
|
|
515
|
+
`notifications` saves a notification in people's notification list and delivers it
|
|
516
|
+
in the web app, by web and mobile push, and as an email copy, as the chosen
|
|
517
|
+
notification channel of the workspace decides. `email` sends email from a shared
|
|
518
|
+
workspace mailbox or from the personal mailbox of the user who started the
|
|
519
|
+
execution, and can log it on a record's timeline.
|
|
520
|
+
|
|
521
|
+
```typescript
|
|
522
|
+
router.post("/quotes/:id/send", async ({ request, notifications, email }) => {
|
|
523
|
+
const quoteId = request.params.id;
|
|
524
|
+
const sent = await email.send({
|
|
525
|
+
from: { mailbox: "EMWXXXXXXXXXXXX" },
|
|
526
|
+
subject: "Your quote",
|
|
527
|
+
html: "<p>Please find our quote attached.</p>",
|
|
528
|
+
record: { object: "quote", recordId: quoteId },
|
|
529
|
+
recordEmailFields: ["contact_email"],
|
|
530
|
+
attachments: [{ object: "quote", recordId: quoteId, field: "quote_pdf" }],
|
|
531
|
+
idempotencyKey: `quote-email:${quoteId}`,
|
|
532
|
+
});
|
|
533
|
+
await notifications.send({
|
|
534
|
+
to: ["PERXXXXXXXXXXXX"],
|
|
535
|
+
title: "Quote sent to the customer",
|
|
536
|
+
content: "The quote was emailed and logged on its timeline.",
|
|
537
|
+
link: { url: `/app/quote/${quoteId}` },
|
|
538
|
+
idempotencyKey: `quote-sent:${quoteId}`,
|
|
539
|
+
});
|
|
540
|
+
return { requestId: sent.requestId };
|
|
541
|
+
});
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
Both are available in scripts, routes, after-change triggers, and jobs, and both are
|
|
545
|
+
asynchronous and best-effort: a successful call means Cogover accepted the message.
|
|
546
|
+
`idempotencyKey` makes a retry within 7 days return the first result with
|
|
547
|
+
`duplicate: true` instead of sending again. Notifications need no approval; email
|
|
548
|
+
may only be sent from the mailboxes allowed by the `email` section of the Project's
|
|
549
|
+
approved identity policy, otherwise `PermissionDeniedError` is thrown with
|
|
550
|
+
`details.reason === "EMAIL_SENDER_NOT_GRANTED"`. `email.senders()` lists the
|
|
551
|
+
mailboxes the current execution may use.
|
|
552
|
+
|
|
512
553
|
## Organization structure
|
|
513
554
|
|
|
514
555
|
`org` reads the departments, positions, and personnel of the workspace, and the
|
package/dist/email.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { EffectiveWorkspaceObjects, StringKeyOf } from "./workspace.js";
|
|
2
|
+
/**
|
|
3
|
+
* Mailbox an email is sent from: a shared workspace mailbox by ID, or `"actor"` for the default personal mailbox
|
|
4
|
+
* of the user whose action started this execution. The Project policy must allow the mailbox.
|
|
5
|
+
*/
|
|
6
|
+
export type EmailSender = {
|
|
7
|
+
readonly mailbox: string;
|
|
8
|
+
} | "actor";
|
|
9
|
+
/** An address, an address with a display name, or a personnel whose work email is used. */
|
|
10
|
+
export type EmailRecipient = string | {
|
|
11
|
+
readonly email: string;
|
|
12
|
+
readonly name?: string;
|
|
13
|
+
} | {
|
|
14
|
+
readonly personnelId: string;
|
|
15
|
+
};
|
|
16
|
+
/** Record on whose timeline the email is logged as an activity. */
|
|
17
|
+
export interface EmailRecordLink<TObject extends string = string> {
|
|
18
|
+
readonly object: TObject;
|
|
19
|
+
readonly recordId: string;
|
|
20
|
+
}
|
|
21
|
+
/** Every file stored in a file field of a record. */
|
|
22
|
+
export interface EmailAttachment<TObject extends string = string> {
|
|
23
|
+
readonly object: TObject;
|
|
24
|
+
readonly recordId: string;
|
|
25
|
+
readonly field: string;
|
|
26
|
+
}
|
|
27
|
+
interface EmailMessageFields<TObject extends string> {
|
|
28
|
+
readonly from: EmailSender;
|
|
29
|
+
readonly to?: readonly EmailRecipient[];
|
|
30
|
+
readonly cc?: readonly EmailRecipient[];
|
|
31
|
+
readonly bcc?: readonly EmailRecipient[];
|
|
32
|
+
/** A single line of at most 255 characters. */
|
|
33
|
+
readonly subject: string;
|
|
34
|
+
/** Logs the email on this record's timeline and enables the options below. */
|
|
35
|
+
readonly record?: EmailRecordLink<TObject>;
|
|
36
|
+
/** Email fields of `record` whose addresses are added to `to`. */
|
|
37
|
+
readonly recordEmailFields?: readonly string[];
|
|
38
|
+
/** Files to attach, at most 10 files and 20 MB in total; requires `record`. */
|
|
39
|
+
readonly attachments?: readonly EmailAttachment<TObject>[];
|
|
40
|
+
/** Appends the sender's default email signature; requires `record` and a personal mailbox. */
|
|
41
|
+
readonly appendSignature?: boolean;
|
|
42
|
+
/** A retry with the same key returns the first result instead of sending again. */
|
|
43
|
+
readonly idempotencyKey?: string;
|
|
44
|
+
}
|
|
45
|
+
/** An email with either an HTML or a plain-text body of at most 192 KB. */
|
|
46
|
+
export type EmailMessage<TObject extends string = string> = EmailMessageFields<TObject> & ({
|
|
47
|
+
readonly html: string;
|
|
48
|
+
readonly text?: never;
|
|
49
|
+
} | {
|
|
50
|
+
readonly text: string;
|
|
51
|
+
readonly html?: never;
|
|
52
|
+
});
|
|
53
|
+
/** `"activity"` when the email was logged on a record, `"direct"` otherwise. */
|
|
54
|
+
export type EmailDelivery = "activity" | "direct";
|
|
55
|
+
export interface EmailSendResult {
|
|
56
|
+
readonly requestId: string;
|
|
57
|
+
readonly delivery: EmailDelivery;
|
|
58
|
+
/** Addresses in to, cc and bcc after duplicates were removed; record email fields are resolved later. */
|
|
59
|
+
readonly recipients: number;
|
|
60
|
+
/** `true` when an earlier call with the same `idempotencyKey` already sent it. */
|
|
61
|
+
readonly duplicate: boolean;
|
|
62
|
+
}
|
|
63
|
+
/** `"workspace"` senders are used as `{ mailbox: id }`; the `"actor"` sender is the mailbox `from: "actor"` uses. */
|
|
64
|
+
export type EmailSenderKind = "workspace" | "actor";
|
|
65
|
+
export interface EmailSenderInfo {
|
|
66
|
+
readonly id: string;
|
|
67
|
+
readonly kind: EmailSenderKind;
|
|
68
|
+
readonly email: string;
|
|
69
|
+
readonly displayName: string;
|
|
70
|
+
}
|
|
71
|
+
/** Sends email from workspace mailboxes. Sending is asynchronous: success means the email was accepted. */
|
|
72
|
+
export interface EmailApi<TSchema extends object = EffectiveWorkspaceObjects> {
|
|
73
|
+
send(message: EmailMessage<StringKeyOf<TSchema>>): Promise<EmailSendResult>;
|
|
74
|
+
/** Active mailboxes this execution may send from. */
|
|
75
|
+
senders(): Promise<readonly EmailSenderInfo[]>;
|
|
76
|
+
}
|
|
77
|
+
export {};
|
package/dist/email.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { PERSONNEL_ID, RECORD_ID, optionalBoolean, optionalIdempotencyKey, optionalText, requireKnownKeys, requiredText, } from "./internal/messaging.js";
|
|
4
|
+
import { utf8ByteLength } from "./internal/utf8.js";
|
|
5
|
+
import { requireFieldSlug, requireSlug } from "./internal/validation.js";
|
|
6
|
+
import { isRecord } from "./internal/values.js";
|
|
7
|
+
const MAX_RECIPIENTS = 50;
|
|
8
|
+
const MAX_SUBJECT_CHARS = 255;
|
|
9
|
+
const MAX_NAME_CHARS = 200;
|
|
10
|
+
const MAX_EMAIL_CHARS = 254;
|
|
11
|
+
// The whole capability request must fit the sandbox bridge limit, so the body leaves room for the envelope.
|
|
12
|
+
const MAX_BODY_BYTES = 192 * 1024;
|
|
13
|
+
const MAX_ATTACHMENTS = 10;
|
|
14
|
+
const MAX_RECORD_EMAIL_FIELDS = 20;
|
|
15
|
+
const MAILBOX_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
16
|
+
// One "@", a dotted domain and none of the characters that could break a mail header. Cogover checks again.
|
|
17
|
+
const EMAIL = /^[^\s@<>()[\],;:"\\]+@[^\s@<>()[\],;:"\\]+\.[^\s@<>()[\],;:"\\.]{2,}$/u;
|
|
18
|
+
const MESSAGE_KEYS = new Set([
|
|
19
|
+
"from", "to", "cc", "bcc", "subject", "html", "text", "attachments", "record", "recordEmailFields",
|
|
20
|
+
"appendSignature", "idempotencyKey",
|
|
21
|
+
]);
|
|
22
|
+
const RECORD_KEYS = new Set(["object", "recordId"]);
|
|
23
|
+
const ATTACHMENT_KEYS = new Set(["object", "recordId", "field"]);
|
|
24
|
+
/** @internal */
|
|
25
|
+
export function createEmailApi() {
|
|
26
|
+
return Object.freeze({
|
|
27
|
+
async send(message) {
|
|
28
|
+
const result = await callBridge("email.send", emailPayload(message));
|
|
29
|
+
if (!isRecord(result) || typeof result.requestId !== "string"
|
|
30
|
+
|| (result.delivery !== "activity" && result.delivery !== "direct")
|
|
31
|
+
|| typeof result.recipients !== "number" || typeof result.duplicate !== "boolean") {
|
|
32
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email result is invalid");
|
|
33
|
+
}
|
|
34
|
+
return Object.freeze({
|
|
35
|
+
requestId: result.requestId,
|
|
36
|
+
delivery: result.delivery,
|
|
37
|
+
recipients: result.recipients,
|
|
38
|
+
duplicate: result.duplicate,
|
|
39
|
+
});
|
|
40
|
+
},
|
|
41
|
+
async senders() {
|
|
42
|
+
const result = await callBridge("email.senders", {});
|
|
43
|
+
if (!isRecord(result) || !Array.isArray(result.senders)) {
|
|
44
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email sender list is invalid");
|
|
45
|
+
}
|
|
46
|
+
return Object.freeze(result.senders.map(sender => {
|
|
47
|
+
if (!isRecord(sender) || typeof sender.id !== "string" || typeof sender.email !== "string"
|
|
48
|
+
|| typeof sender.displayName !== "string"
|
|
49
|
+
|| (sender.kind !== "workspace" && sender.kind !== "actor")) {
|
|
50
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email sender list is invalid");
|
|
51
|
+
}
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
id: sender.id, kind: sender.kind, email: sender.email, displayName: sender.displayName,
|
|
54
|
+
});
|
|
55
|
+
}));
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function emailPayload(message) {
|
|
60
|
+
const input = requireKnownKeys(message, MESSAGE_KEYS, "email.send() message");
|
|
61
|
+
const payload = { from: sender(input.from) };
|
|
62
|
+
let total = 0;
|
|
63
|
+
for (const field of ["to", "cc", "bcc"]) {
|
|
64
|
+
if (input[field] === undefined)
|
|
65
|
+
continue;
|
|
66
|
+
const recipients = recipientList(input[field], field);
|
|
67
|
+
total += recipients.length;
|
|
68
|
+
if (recipients.length > 0)
|
|
69
|
+
payload[field] = recipients;
|
|
70
|
+
}
|
|
71
|
+
if (total > MAX_RECIPIENTS) {
|
|
72
|
+
throw new ValidationError(`to, cc and bcc must not list more than ${MAX_RECIPIENTS} recipients in total`);
|
|
73
|
+
}
|
|
74
|
+
const subject = requiredText(input.subject, "subject", MAX_SUBJECT_CHARS);
|
|
75
|
+
if (/[\r\n]/u.test(subject))
|
|
76
|
+
throw new ValidationError("subject must be a single line");
|
|
77
|
+
payload.subject = subject;
|
|
78
|
+
const html = optionalText(input.html, "html", Number.MAX_SAFE_INTEGER);
|
|
79
|
+
const text = optionalText(input.text, "text", Number.MAX_SAFE_INTEGER);
|
|
80
|
+
if ((html === undefined) === (text === undefined))
|
|
81
|
+
throw new ValidationError("Provide exactly one of html and text");
|
|
82
|
+
const body = (html ?? text);
|
|
83
|
+
if (utf8ByteLength(body) > MAX_BODY_BYTES) {
|
|
84
|
+
throw new ValidationError(`The email body must not exceed ${MAX_BODY_BYTES} bytes`);
|
|
85
|
+
}
|
|
86
|
+
if (html !== undefined)
|
|
87
|
+
payload.html = html;
|
|
88
|
+
else
|
|
89
|
+
payload.text = text;
|
|
90
|
+
const hasRecord = input.record !== undefined;
|
|
91
|
+
if (hasRecord) {
|
|
92
|
+
const record = requireKnownKeys(input.record, RECORD_KEYS, "record");
|
|
93
|
+
payload.record = { objectSlug: objectSlug(record.object, "record.object"), recordId: recordId(record.recordId, "record.recordId") };
|
|
94
|
+
}
|
|
95
|
+
if (input.recordEmailFields !== undefined) {
|
|
96
|
+
if (!Array.isArray(input.recordEmailFields))
|
|
97
|
+
throw new ValidationError("recordEmailFields must be a list of field slugs");
|
|
98
|
+
if (input.recordEmailFields.length > MAX_RECORD_EMAIL_FIELDS) {
|
|
99
|
+
throw new ValidationError(`recordEmailFields must not list more than ${MAX_RECORD_EMAIL_FIELDS} fields`);
|
|
100
|
+
}
|
|
101
|
+
const fields = [...new Set(input.recordEmailFields
|
|
102
|
+
.map(field => requireFieldSlug(field, "recordEmailFields field slug")))];
|
|
103
|
+
if (fields.length > 0)
|
|
104
|
+
payload.recordEmailFields = fields;
|
|
105
|
+
}
|
|
106
|
+
if (input.attachments !== undefined) {
|
|
107
|
+
if (!Array.isArray(input.attachments))
|
|
108
|
+
throw new ValidationError("attachments must be a list of { object, recordId, field }");
|
|
109
|
+
if (input.attachments.length > MAX_ATTACHMENTS) {
|
|
110
|
+
throw new ValidationError(`An email may carry at most ${MAX_ATTACHMENTS} attachments`);
|
|
111
|
+
}
|
|
112
|
+
const attachments = input.attachments.map(entry => {
|
|
113
|
+
const attachment = requireKnownKeys(entry, ATTACHMENT_KEYS, "attachments entry");
|
|
114
|
+
return {
|
|
115
|
+
objectSlug: objectSlug(attachment.object, "attachments object"),
|
|
116
|
+
recordId: recordId(attachment.recordId, "attachments recordId"),
|
|
117
|
+
field: requireFieldSlug(attachment.field, "attachments field slug"),
|
|
118
|
+
};
|
|
119
|
+
});
|
|
120
|
+
if (attachments.length > 0)
|
|
121
|
+
payload.attachments = attachments;
|
|
122
|
+
}
|
|
123
|
+
const appendSignature = optionalBoolean(input.appendSignature, "appendSignature");
|
|
124
|
+
if (appendSignature !== undefined)
|
|
125
|
+
payload.appendSignature = appendSignature;
|
|
126
|
+
if (!hasRecord && (payload.recordEmailFields !== undefined || payload.attachments !== undefined
|
|
127
|
+
|| appendSignature === true)) {
|
|
128
|
+
throw new ValidationError("recordEmailFields, attachments and appendSignature require record");
|
|
129
|
+
}
|
|
130
|
+
if (payload.to === undefined && payload.recordEmailFields === undefined) {
|
|
131
|
+
throw new ValidationError("to must name at least one recipient");
|
|
132
|
+
}
|
|
133
|
+
const idempotencyKey = optionalIdempotencyKey(input.idempotencyKey, "email.send()");
|
|
134
|
+
if (idempotencyKey !== undefined)
|
|
135
|
+
payload.idempotencyKey = idempotencyKey;
|
|
136
|
+
return payload;
|
|
137
|
+
}
|
|
138
|
+
function sender(value) {
|
|
139
|
+
if (value === "actor")
|
|
140
|
+
return { kind: "actor" };
|
|
141
|
+
const from = requireKnownKeys(value, new Set(["mailbox"]), "from");
|
|
142
|
+
if (typeof from.mailbox !== "string" || !MAILBOX_ID.test(from.mailbox)) {
|
|
143
|
+
throw new ValidationError("from must be \"actor\" or { mailbox: <mailbox ID> }");
|
|
144
|
+
}
|
|
145
|
+
return { kind: "mailbox", mailboxId: from.mailbox };
|
|
146
|
+
}
|
|
147
|
+
function recipientList(value, label) {
|
|
148
|
+
if (!Array.isArray(value))
|
|
149
|
+
throw new ValidationError(`${label} must be a list of recipients`);
|
|
150
|
+
if (value.length > MAX_RECIPIENTS) {
|
|
151
|
+
throw new ValidationError(`${label} must not list more than ${MAX_RECIPIENTS} recipients`);
|
|
152
|
+
}
|
|
153
|
+
return value.map(entry => {
|
|
154
|
+
if (typeof entry === "string")
|
|
155
|
+
return { email: address(entry, label) };
|
|
156
|
+
if (isRecord(entry) && "personnelId" in entry) {
|
|
157
|
+
requireKnownKeys(entry, new Set(["personnelId"]), `${label} entry`);
|
|
158
|
+
if (typeof entry.personnelId !== "string" || !PERSONNEL_ID.test(entry.personnelId)) {
|
|
159
|
+
throw new ValidationError(`${label} personnelId must be a personnel ID`);
|
|
160
|
+
}
|
|
161
|
+
return { personnelId: entry.personnelId };
|
|
162
|
+
}
|
|
163
|
+
const recipient = requireKnownKeys(entry, new Set(["email", "name"]), `${label} entry`);
|
|
164
|
+
const result = { email: address(recipient.email, label) };
|
|
165
|
+
const name = optionalText(recipient.name, `${label} name`, MAX_NAME_CHARS);
|
|
166
|
+
if (name !== undefined) {
|
|
167
|
+
if (/[\r\n]/u.test(name))
|
|
168
|
+
throw new ValidationError(`${label} name must be a single line`);
|
|
169
|
+
result.name = name;
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
function address(value, label) {
|
|
175
|
+
const email = typeof value === "string" ? value.trim() : "";
|
|
176
|
+
if (email.length === 0 || email.length > MAX_EMAIL_CHARS || !EMAIL.test(email)) {
|
|
177
|
+
throw new ValidationError(`${label} contains an invalid email address`);
|
|
178
|
+
}
|
|
179
|
+
return email;
|
|
180
|
+
}
|
|
181
|
+
function objectSlug(value, label) {
|
|
182
|
+
if (typeof value !== "string")
|
|
183
|
+
throw new ValidationError(`${label} must be an object slug`);
|
|
184
|
+
return requireSlug(value);
|
|
185
|
+
}
|
|
186
|
+
function recordId(value, label) {
|
|
187
|
+
if (typeof value !== "string" || !RECORD_ID.test(value))
|
|
188
|
+
throw new ValidationError(`${label} must be a record ID`);
|
|
189
|
+
return value;
|
|
190
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export type { ResponseApi, ResponseInit, BinaryResponseInit, ResponseHeaderValue
|
|
|
24
24
|
export type { ProjectState, StateNamespace, StateEntry, StateWriteOptions, StateDeleteOptions, } from "./state.js";
|
|
25
25
|
export type { DistributedLocks, LockLease, LockOptions, } from "./locks.js";
|
|
26
26
|
export type { PushRecipients, PushOptions, ToastPosition, ToastSize, ToastLink, ToastMessage, BackgroundContentType, BackgroundMessage, PushApi, } from "./push.js";
|
|
27
|
+
export type { NotificationContentType, NotificationDisplay, NotificationSender, NotificationLinkTarget, NotificationLink, NotificationMessage, NotificationResult, NotificationsApi, } from "./notifications.js";
|
|
28
|
+
export type { EmailSender, EmailRecipient, EmailRecordLink, EmailAttachment, EmailMessage, EmailDelivery, EmailSendResult, EmailSenderKind, EmailSenderInfo, EmailApi, } from "./email.js";
|
|
27
29
|
export { fetch } from "./fetch.js";
|
|
28
30
|
export type { CogoverFetchInit, CogoverFetchHeaders, CogoverFetchResponse, } from "./fetch.js";
|
|
29
31
|
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
@@ -2,7 +2,9 @@ import { crypto } from "../crypto.js";
|
|
|
2
2
|
import { createDataApi } from "../data.js";
|
|
3
3
|
import { ValidationError } from "../errors.js";
|
|
4
4
|
import { installCogoverFetch } from "../fetch.js";
|
|
5
|
+
import { createEmailApi } from "../email.js";
|
|
5
6
|
import { createLocksApi } from "../locks.js";
|
|
7
|
+
import { createNotificationsApi } from "../notifications.js";
|
|
6
8
|
import { SCRIPT_LOGGER } from "../logger.js";
|
|
7
9
|
import { createOrgApi } from "../org.js";
|
|
8
10
|
import { createSchemaApi } from "../schema.js";
|
|
@@ -43,6 +45,8 @@ export function createJobSandboxHandler(manifest, handler) {
|
|
|
43
45
|
log: SCRIPT_LOGGER,
|
|
44
46
|
state: createStateApi(),
|
|
45
47
|
locks: createLocksApi(),
|
|
48
|
+
notifications: createNotificationsApi(),
|
|
49
|
+
email: createEmailApi(),
|
|
46
50
|
jobs: createJobsApi(),
|
|
47
51
|
secrets: createSecretsApi(),
|
|
48
52
|
crypto,
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { isRecord } from "./values.js";
|
|
3
|
+
export const PERSONNEL_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
4
|
+
export const RECORD_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
5
|
+
const IDEMPOTENCY_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
6
|
+
/** Rejects option names the method does not know, so a typo is not silently ignored. */
|
|
7
|
+
export function requireKnownKeys(value, allowed, label) {
|
|
8
|
+
if (!isRecord(value))
|
|
9
|
+
throw new ValidationError(`${label} must be an object`);
|
|
10
|
+
for (const key of Object.keys(value)) {
|
|
11
|
+
if (!allowed.has(key))
|
|
12
|
+
throw new ValidationError(`${label} has the unknown field '${key}'`);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
/** @returns `undefined` for a missing or blank value */
|
|
17
|
+
export function optionalText(value, label, maximumChars) {
|
|
18
|
+
if (value === undefined || value === null)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (typeof value !== "string")
|
|
21
|
+
throw new ValidationError(`${label} must be a string`);
|
|
22
|
+
if (value.trim().length === 0)
|
|
23
|
+
return undefined;
|
|
24
|
+
if (value.length > maximumChars) {
|
|
25
|
+
throw new ValidationError(`${label} must not exceed ${maximumChars} characters`);
|
|
26
|
+
}
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
export function requiredText(value, label, maximumChars) {
|
|
30
|
+
const text = optionalText(value, label, maximumChars);
|
|
31
|
+
if (text === undefined)
|
|
32
|
+
throw new ValidationError(`${label} is required`);
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
export function optionalChoice(value, label, allowed) {
|
|
36
|
+
if (value === undefined)
|
|
37
|
+
return undefined;
|
|
38
|
+
if (typeof value !== "string" || !allowed.has(value)) {
|
|
39
|
+
throw new ValidationError(`${label} must be one of ${[...allowed].sort().join(", ")}`);
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
export function optionalBoolean(value, label) {
|
|
44
|
+
if (value === undefined)
|
|
45
|
+
return undefined;
|
|
46
|
+
if (typeof value !== "boolean")
|
|
47
|
+
throw new ValidationError(`${label} must be a boolean`);
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
export function optionalIdempotencyKey(value, method) {
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
if (typeof value !== "string" || !IDEMPOTENCY_KEY.test(value)) {
|
|
54
|
+
throw new ValidationError(`${method} idempotencyKey must start with a letter or digit and contain at most `
|
|
55
|
+
+ "128 letters, digits, '.', '_', ':' or '-'");
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
/** Personnel IDs in order without duplicates; `"actor"` is accepted only where `allowActor` is set. */
|
|
60
|
+
export function personnelIds(value, label, maximum, allowActor) {
|
|
61
|
+
if (!Array.isArray(value))
|
|
62
|
+
throw new ValidationError(`${label} must be a list of personnel IDs`);
|
|
63
|
+
if (value.length > maximum)
|
|
64
|
+
throw new ValidationError(`${label} must not list more than ${maximum} personnel IDs`);
|
|
65
|
+
const ids = new Set();
|
|
66
|
+
for (const entry of value) {
|
|
67
|
+
// "actor" is a reserved word, never a personnel ID.
|
|
68
|
+
const accepted = typeof entry === "string" && (entry === "actor" ? allowActor : PERSONNEL_ID.test(entry));
|
|
69
|
+
if (!accepted) {
|
|
70
|
+
throw new ValidationError(`${label} must only contain personnel IDs${allowActor ? " or \"actor\"" : ""}`);
|
|
71
|
+
}
|
|
72
|
+
ids.add(entry);
|
|
73
|
+
}
|
|
74
|
+
return [...ids];
|
|
75
|
+
}
|
|
@@ -5,6 +5,8 @@ import { installCogoverFetch } from "../fetch.js";
|
|
|
5
5
|
import { createOrgApi } from "../org.js";
|
|
6
6
|
import { SCRIPT_LOGGER } from "../logger.js";
|
|
7
7
|
import { createPushApi } from "../push.js";
|
|
8
|
+
import { createNotificationsApi } from "../notifications.js";
|
|
9
|
+
import { createEmailApi } from "../email.js";
|
|
8
10
|
import { createSchemaApi } from "../schema.js";
|
|
9
11
|
import { createSecretsApi } from "../secrets.js";
|
|
10
12
|
import { invocationContext } from "./invocation.js";
|
|
@@ -55,6 +57,9 @@ export function createTriggerSandboxHandler(manifest, handler) {
|
|
|
55
57
|
schema: createSchemaApi(),
|
|
56
58
|
log: SCRIPT_LOGGER,
|
|
57
59
|
push: createPushApi(),
|
|
60
|
+
// The host refuses notifications and email in a before-change trigger, like push.
|
|
61
|
+
notifications: createNotificationsApi(),
|
|
62
|
+
email: createEmailApi(),
|
|
58
63
|
// The host refuses jobs and secrets in a before-change trigger; the SDK does not pre-empt it.
|
|
59
64
|
jobs: createJobsApi(),
|
|
60
65
|
secrets: createSecretsApi(),
|
package/dist/jobs.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { CryptoApi } from "./crypto.js";
|
|
|
2
2
|
import type { DataApi } from "./data.js";
|
|
3
3
|
import type { InvocationContext } from "./invocation.js";
|
|
4
4
|
import type { DistributedLocks } from "./locks.js";
|
|
5
|
+
import type { EmailApi } from "./email.js";
|
|
6
|
+
import type { NotificationsApi } from "./notifications.js";
|
|
5
7
|
import type { ScriptLogger } from "./logger.js";
|
|
6
8
|
import type { OrgApi } from "./org.js";
|
|
7
9
|
import type { SchemaApi } from "./schema.js";
|
|
@@ -87,6 +89,8 @@ export interface JobContext<TPayload = unknown, TSchema extends object = Effecti
|
|
|
87
89
|
readonly log: ScriptLogger;
|
|
88
90
|
readonly state: ProjectState;
|
|
89
91
|
readonly locks: DistributedLocks;
|
|
92
|
+
readonly notifications: NotificationsApi;
|
|
93
|
+
readonly email: EmailApi<TSchema>;
|
|
90
94
|
readonly jobs: JobsApi;
|
|
91
95
|
readonly secrets: SecretsApi;
|
|
92
96
|
readonly crypto: CryptoApi;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** `"html"` content is reduced to basic formatting (paragraphs, lists, tables, links) before it is stored. */
|
|
2
|
+
export type NotificationContentType = "text" | "html";
|
|
3
|
+
/** `"FULL"` shows the subtitle; `"SIMPLE"` shows only the title and content. */
|
|
4
|
+
export type NotificationDisplay = "SIMPLE" | "FULL";
|
|
5
|
+
/** `"workspace"` sends as the workspace; `"actor"` shows the user whose action started this execution. */
|
|
6
|
+
export type NotificationSender = "workspace" | "actor";
|
|
7
|
+
export type NotificationLinkTarget = "SAME_TAB" | "NEW_TAB";
|
|
8
|
+
/** Page opened when the recipient clicks the notification. */
|
|
9
|
+
export interface NotificationLink {
|
|
10
|
+
/** A path of the Cogover web app starting with `/`, or an absolute `http` or `https` URL. */
|
|
11
|
+
readonly url: string;
|
|
12
|
+
/** Defaults to `"SAME_TAB"` for a path and `"NEW_TAB"` for an absolute URL. */
|
|
13
|
+
readonly openIn?: NotificationLinkTarget;
|
|
14
|
+
}
|
|
15
|
+
/** A notification saved in the recipients' notification list. */
|
|
16
|
+
export interface NotificationMessage {
|
|
17
|
+
/** Personnel IDs, 1 to 200. Personnel without a user account are skipped and reported in the result. */
|
|
18
|
+
readonly to: readonly string[];
|
|
19
|
+
/** Personnel IDs that never receive the notification; `"actor"` is the user who started this execution. */
|
|
20
|
+
readonly exclude?: readonly string[];
|
|
21
|
+
/** At most 200 characters; also the subject of the email copy. */
|
|
22
|
+
readonly title: string;
|
|
23
|
+
/** At most 16,384 characters. */
|
|
24
|
+
readonly content: string;
|
|
25
|
+
/** Defaults to `"text"`. */
|
|
26
|
+
readonly contentType?: NotificationContentType;
|
|
27
|
+
/** At most 200 characters; requires `display: "FULL"`, which is the default when a subtitle is given. */
|
|
28
|
+
readonly subtitle?: string;
|
|
29
|
+
/** Defaults to `"FULL"` with a subtitle and `"SIMPLE"` without one. */
|
|
30
|
+
readonly display?: NotificationDisplay;
|
|
31
|
+
readonly link?: NotificationLink;
|
|
32
|
+
/** Defaults to `"workspace"`. */
|
|
33
|
+
readonly sender?: NotificationSender;
|
|
34
|
+
/**
|
|
35
|
+
* Record ID of a notification channel of the workspace. The channel decides which deliveries (in-app, web push,
|
|
36
|
+
* mobile push, email) are enabled; without one, all of them are.
|
|
37
|
+
*/
|
|
38
|
+
readonly channel?: string;
|
|
39
|
+
/** Whether to include an email copy for channels that enable email. Defaults to `true`. */
|
|
40
|
+
readonly email?: boolean;
|
|
41
|
+
/** A retry with the same key returns the first result instead of notifying again. */
|
|
42
|
+
readonly idempotencyKey?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface NotificationResult {
|
|
45
|
+
readonly requestId: string;
|
|
46
|
+
/** Accounts the notification was addressed to after exclusions. */
|
|
47
|
+
readonly notified: number;
|
|
48
|
+
/** Recipients skipped because they have no user account. */
|
|
49
|
+
readonly skippedPersonnelIds: readonly string[];
|
|
50
|
+
/** `true` when an earlier call with the same `idempotencyKey` already sent it. */
|
|
51
|
+
readonly duplicate: boolean;
|
|
52
|
+
}
|
|
53
|
+
/** Sends notifications to people of the workspace. Delivery is asynchronous and best-effort. */
|
|
54
|
+
export interface NotificationsApi {
|
|
55
|
+
send(message: NotificationMessage): Promise<NotificationResult>;
|
|
56
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { optionalBoolean, optionalChoice, optionalIdempotencyKey, optionalText, personnelIds, requireKnownKeys, requiredText, } from "./internal/messaging.js";
|
|
4
|
+
import { isRecord } from "./internal/values.js";
|
|
5
|
+
const MAX_RECIPIENTS = 200;
|
|
6
|
+
const MAX_TITLE_CHARS = 200;
|
|
7
|
+
const MAX_SUBTITLE_CHARS = 200;
|
|
8
|
+
const MAX_CONTENT_CHARS = 16_384;
|
|
9
|
+
const MAX_LINK_CHARS = 2_048;
|
|
10
|
+
const CHANNEL_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
11
|
+
// The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
|
|
12
|
+
const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
|
|
13
|
+
const APP_PATH = /^\/(?!\/)[^\s\\]*$/u;
|
|
14
|
+
const MESSAGE_KEYS = new Set([
|
|
15
|
+
"to", "exclude", "title", "content", "contentType", "subtitle", "display", "link", "sender", "channel",
|
|
16
|
+
"email", "idempotencyKey",
|
|
17
|
+
]);
|
|
18
|
+
const LINK_KEYS = new Set(["url", "openIn"]);
|
|
19
|
+
const CONTENT_TYPES = new Set(["text", "html"]);
|
|
20
|
+
const DISPLAYS = new Set(["SIMPLE", "FULL"]);
|
|
21
|
+
const SENDERS = new Set(["workspace", "actor"]);
|
|
22
|
+
const LINK_TARGETS = new Set(["SAME_TAB", "NEW_TAB"]);
|
|
23
|
+
/** @internal */
|
|
24
|
+
export function createNotificationsApi() {
|
|
25
|
+
return Object.freeze({
|
|
26
|
+
async send(message) {
|
|
27
|
+
const result = await callBridge("notifications.send", notificationPayload(message));
|
|
28
|
+
if (!isRecord(result) || typeof result.requestId !== "string" || typeof result.notified !== "number"
|
|
29
|
+
|| !Array.isArray(result.skippedPersonnelIds) || typeof result.duplicate !== "boolean") {
|
|
30
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Notification result is invalid");
|
|
31
|
+
}
|
|
32
|
+
return Object.freeze({
|
|
33
|
+
requestId: result.requestId,
|
|
34
|
+
notified: result.notified,
|
|
35
|
+
skippedPersonnelIds: Object.freeze(result.skippedPersonnelIds.filter((id) => typeof id === "string")),
|
|
36
|
+
duplicate: result.duplicate,
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function notificationPayload(message) {
|
|
42
|
+
const input = requireKnownKeys(message, MESSAGE_KEYS, "notifications.send() message");
|
|
43
|
+
const to = personnelIds(input.to, "to", MAX_RECIPIENTS, false);
|
|
44
|
+
if (to.length === 0)
|
|
45
|
+
throw new ValidationError("to must name at least one personnel ID");
|
|
46
|
+
const payload = {
|
|
47
|
+
to,
|
|
48
|
+
title: requiredText(input.title, "title", MAX_TITLE_CHARS),
|
|
49
|
+
content: requiredText(input.content, "content", MAX_CONTENT_CHARS),
|
|
50
|
+
};
|
|
51
|
+
if (input.exclude !== undefined)
|
|
52
|
+
payload.exclude = personnelIds(input.exclude, "exclude", MAX_RECIPIENTS, true);
|
|
53
|
+
const contentType = optionalChoice(input.contentType, "contentType", CONTENT_TYPES);
|
|
54
|
+
if (contentType !== undefined)
|
|
55
|
+
payload.contentType = contentType;
|
|
56
|
+
const subtitle = optionalText(input.subtitle, "subtitle", MAX_SUBTITLE_CHARS);
|
|
57
|
+
const display = optionalChoice(input.display, "display", DISPLAYS);
|
|
58
|
+
if (subtitle !== undefined) {
|
|
59
|
+
if (display === "SIMPLE")
|
|
60
|
+
throw new ValidationError("subtitle requires display \"FULL\"");
|
|
61
|
+
payload.subtitle = subtitle;
|
|
62
|
+
}
|
|
63
|
+
if (display !== undefined)
|
|
64
|
+
payload.display = display;
|
|
65
|
+
if (input.link !== undefined)
|
|
66
|
+
payload.link = notificationLink(input.link);
|
|
67
|
+
const sender = optionalChoice(input.sender, "sender", SENDERS);
|
|
68
|
+
if (sender !== undefined)
|
|
69
|
+
payload.sender = sender;
|
|
70
|
+
if (input.channel !== undefined) {
|
|
71
|
+
if (typeof input.channel !== "string" || !CHANNEL_ID.test(input.channel)) {
|
|
72
|
+
throw new ValidationError("channel must be a notification channel record ID");
|
|
73
|
+
}
|
|
74
|
+
payload.channel = input.channel;
|
|
75
|
+
}
|
|
76
|
+
const email = optionalBoolean(input.email, "email");
|
|
77
|
+
if (email !== undefined)
|
|
78
|
+
payload.email = email;
|
|
79
|
+
const idempotencyKey = optionalIdempotencyKey(input.idempotencyKey, "notifications.send()");
|
|
80
|
+
if (idempotencyKey !== undefined)
|
|
81
|
+
payload.idempotencyKey = idempotencyKey;
|
|
82
|
+
return payload;
|
|
83
|
+
}
|
|
84
|
+
function notificationLink(value) {
|
|
85
|
+
const link = requireKnownKeys(value, LINK_KEYS, "link");
|
|
86
|
+
const url = requiredText(link.url, "link.url", MAX_LINK_CHARS);
|
|
87
|
+
if (!APP_PATH.test(url) && !HTTP_URL.test(url)) {
|
|
88
|
+
throw new ValidationError("link.url must be a path starting with / or an absolute http or https URL");
|
|
89
|
+
}
|
|
90
|
+
const openIn = optionalChoice(link.openIn, "link.openIn", LINK_TARGETS);
|
|
91
|
+
return openIn === undefined ? { url } : { url, openIn };
|
|
92
|
+
}
|