@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
package/dist/email.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
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 body is measured as it travels, JSON-encoded, so that with the rest of the message it fits one capability
|
|
12
|
+
// request (MAX_BRIDGE_REQUEST_BYTES).
|
|
13
|
+
const MAX_BODY_BYTES = 192 * 1024;
|
|
14
|
+
const MAX_ATTACHMENTS = 10;
|
|
15
|
+
const MAX_RECORD_EMAIL_FIELDS = 20;
|
|
16
|
+
const MAILBOX_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
17
|
+
// One "@", a dotted domain and none of the characters that could break a mail header. Cogover checks again.
|
|
18
|
+
const EMAIL = /^[^\s@<>()[\],;:"\\]+@[^\s@<>()[\],;:"\\]+\.[^\s@<>()[\],;:"\\.]{2,}$/u;
|
|
19
|
+
const MESSAGE_KEYS = new Set([
|
|
20
|
+
"from", "to", "cc", "bcc", "subject", "html", "text", "attachments", "record", "recordEmailFields",
|
|
21
|
+
"appendSignature", "idempotencyKey",
|
|
22
|
+
]);
|
|
23
|
+
const RECORD_KEYS = new Set(["object", "recordId"]);
|
|
24
|
+
const ATTACHMENT_KEYS = new Set(["object", "recordId", "field"]);
|
|
25
|
+
/** @internal */
|
|
26
|
+
export function createEmailApi() {
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
async send(message) {
|
|
29
|
+
const result = await callBridge("email.send", emailPayload(message));
|
|
30
|
+
if (!isRecord(result) || typeof result.requestId !== "string"
|
|
31
|
+
|| (result.delivery !== "activity" && result.delivery !== "direct")
|
|
32
|
+
|| typeof result.recipients !== "number" || typeof result.duplicate !== "boolean") {
|
|
33
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email result is invalid");
|
|
34
|
+
}
|
|
35
|
+
return Object.freeze({
|
|
36
|
+
requestId: result.requestId,
|
|
37
|
+
delivery: result.delivery,
|
|
38
|
+
recipients: result.recipients,
|
|
39
|
+
duplicate: result.duplicate,
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
async senders() {
|
|
43
|
+
const result = await callBridge("email.senders", {});
|
|
44
|
+
if (!isRecord(result) || !Array.isArray(result.senders)) {
|
|
45
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email sender list is invalid");
|
|
46
|
+
}
|
|
47
|
+
return Object.freeze(result.senders.map(sender => {
|
|
48
|
+
if (!isRecord(sender) || typeof sender.id !== "string" || typeof sender.email !== "string"
|
|
49
|
+
|| typeof sender.displayName !== "string"
|
|
50
|
+
|| (sender.kind !== "workspace" && sender.kind !== "actor")) {
|
|
51
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Email sender list is invalid");
|
|
52
|
+
}
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
id: sender.id, kind: sender.kind, email: sender.email, displayName: sender.displayName,
|
|
55
|
+
});
|
|
56
|
+
}));
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function emailPayload(message) {
|
|
61
|
+
const input = requireKnownKeys(message, MESSAGE_KEYS, "email.send() message");
|
|
62
|
+
const payload = { from: sender(input.from) };
|
|
63
|
+
let total = 0;
|
|
64
|
+
for (const field of ["to", "cc", "bcc"]) {
|
|
65
|
+
if (input[field] === undefined)
|
|
66
|
+
continue;
|
|
67
|
+
const recipients = recipientList(input[field], field);
|
|
68
|
+
total += recipients.length;
|
|
69
|
+
if (recipients.length > 0)
|
|
70
|
+
payload[field] = recipients;
|
|
71
|
+
}
|
|
72
|
+
if (total > MAX_RECIPIENTS) {
|
|
73
|
+
throw new ValidationError(`to, cc and bcc must not list more than ${MAX_RECIPIENTS} recipients in total`);
|
|
74
|
+
}
|
|
75
|
+
const subject = requiredText(input.subject, "subject", MAX_SUBJECT_CHARS);
|
|
76
|
+
if (/[\r\n]/u.test(subject))
|
|
77
|
+
throw new ValidationError("subject must be a single line");
|
|
78
|
+
payload.subject = subject;
|
|
79
|
+
const html = optionalText(input.html, "html", Number.MAX_SAFE_INTEGER);
|
|
80
|
+
const text = optionalText(input.text, "text", Number.MAX_SAFE_INTEGER);
|
|
81
|
+
if ((html === undefined) === (text === undefined))
|
|
82
|
+
throw new ValidationError("Provide exactly one of html and text");
|
|
83
|
+
const body = (html ?? text);
|
|
84
|
+
// JSON.stringify adds two quotes; each quote, backslash or control character inside counts as its escape.
|
|
85
|
+
if (utf8ByteLength(JSON.stringify(body)) - 2 > MAX_BODY_BYTES) {
|
|
86
|
+
throw new ValidationError(`The email body must not exceed ${MAX_BODY_BYTES} bytes once JSON-encoded`);
|
|
87
|
+
}
|
|
88
|
+
if (html !== undefined)
|
|
89
|
+
payload.html = html;
|
|
90
|
+
else
|
|
91
|
+
payload.text = text;
|
|
92
|
+
const hasRecord = input.record !== undefined;
|
|
93
|
+
if (hasRecord) {
|
|
94
|
+
const record = requireKnownKeys(input.record, RECORD_KEYS, "record");
|
|
95
|
+
payload.record = { objectSlug: objectSlug(record.object, "record.object"), recordId: recordId(record.recordId, "record.recordId") };
|
|
96
|
+
}
|
|
97
|
+
if (input.recordEmailFields !== undefined) {
|
|
98
|
+
if (!Array.isArray(input.recordEmailFields))
|
|
99
|
+
throw new ValidationError("recordEmailFields must be a list of field slugs");
|
|
100
|
+
if (input.recordEmailFields.length > MAX_RECORD_EMAIL_FIELDS) {
|
|
101
|
+
throw new ValidationError(`recordEmailFields must not list more than ${MAX_RECORD_EMAIL_FIELDS} fields`);
|
|
102
|
+
}
|
|
103
|
+
const fields = [...new Set(input.recordEmailFields
|
|
104
|
+
.map(field => requireFieldSlug(field, "recordEmailFields field slug")))];
|
|
105
|
+
if (fields.length > 0)
|
|
106
|
+
payload.recordEmailFields = fields;
|
|
107
|
+
}
|
|
108
|
+
if (input.attachments !== undefined) {
|
|
109
|
+
if (!Array.isArray(input.attachments))
|
|
110
|
+
throw new ValidationError("attachments must be a list of { object, recordId, field }");
|
|
111
|
+
if (input.attachments.length > MAX_ATTACHMENTS) {
|
|
112
|
+
throw new ValidationError(`An email may carry at most ${MAX_ATTACHMENTS} attachments`);
|
|
113
|
+
}
|
|
114
|
+
const attachments = input.attachments.map(entry => {
|
|
115
|
+
const attachment = requireKnownKeys(entry, ATTACHMENT_KEYS, "attachments entry");
|
|
116
|
+
return {
|
|
117
|
+
objectSlug: objectSlug(attachment.object, "attachments object"),
|
|
118
|
+
recordId: recordId(attachment.recordId, "attachments recordId"),
|
|
119
|
+
field: requireFieldSlug(attachment.field, "attachments field slug"),
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
if (attachments.length > 0)
|
|
123
|
+
payload.attachments = attachments;
|
|
124
|
+
}
|
|
125
|
+
const appendSignature = optionalBoolean(input.appendSignature, "appendSignature");
|
|
126
|
+
if (appendSignature !== undefined)
|
|
127
|
+
payload.appendSignature = appendSignature;
|
|
128
|
+
if (!hasRecord && (payload.recordEmailFields !== undefined || payload.attachments !== undefined
|
|
129
|
+
|| appendSignature === true)) {
|
|
130
|
+
throw new ValidationError("recordEmailFields, attachments and appendSignature require record");
|
|
131
|
+
}
|
|
132
|
+
if (payload.to === undefined && payload.recordEmailFields === undefined) {
|
|
133
|
+
throw new ValidationError("to must name at least one recipient");
|
|
134
|
+
}
|
|
135
|
+
const idempotencyKey = optionalIdempotencyKey(input.idempotencyKey, "email.send()");
|
|
136
|
+
if (idempotencyKey !== undefined)
|
|
137
|
+
payload.idempotencyKey = idempotencyKey;
|
|
138
|
+
return payload;
|
|
139
|
+
}
|
|
140
|
+
function sender(value) {
|
|
141
|
+
if (value === "actor")
|
|
142
|
+
return { kind: "actor" };
|
|
143
|
+
const from = requireKnownKeys(value, new Set(["mailbox"]), "from");
|
|
144
|
+
if (typeof from.mailbox !== "string" || !MAILBOX_ID.test(from.mailbox)) {
|
|
145
|
+
throw new ValidationError("from must be \"actor\" or { mailbox: <mailbox ID> }");
|
|
146
|
+
}
|
|
147
|
+
return { kind: "mailbox", mailboxId: from.mailbox };
|
|
148
|
+
}
|
|
149
|
+
function recipientList(value, label) {
|
|
150
|
+
if (!Array.isArray(value))
|
|
151
|
+
throw new ValidationError(`${label} must be a list of recipients`);
|
|
152
|
+
if (value.length > MAX_RECIPIENTS) {
|
|
153
|
+
throw new ValidationError(`${label} must not list more than ${MAX_RECIPIENTS} recipients`);
|
|
154
|
+
}
|
|
155
|
+
return value.map(entry => {
|
|
156
|
+
if (typeof entry === "string")
|
|
157
|
+
return { email: address(entry, label) };
|
|
158
|
+
if (isRecord(entry) && "personnelId" in entry) {
|
|
159
|
+
requireKnownKeys(entry, new Set(["personnelId"]), `${label} entry`);
|
|
160
|
+
if (typeof entry.personnelId !== "string" || !PERSONNEL_ID.test(entry.personnelId)) {
|
|
161
|
+
throw new ValidationError(`${label} personnelId must be a personnel ID`);
|
|
162
|
+
}
|
|
163
|
+
return { personnelId: entry.personnelId };
|
|
164
|
+
}
|
|
165
|
+
const recipient = requireKnownKeys(entry, new Set(["email", "name"]), `${label} entry`);
|
|
166
|
+
const result = { email: address(recipient.email, label) };
|
|
167
|
+
const name = optionalText(recipient.name, `${label} name`, MAX_NAME_CHARS);
|
|
168
|
+
if (name !== undefined) {
|
|
169
|
+
if (/[\r\n]/u.test(name))
|
|
170
|
+
throw new ValidationError(`${label} name must be a single line`);
|
|
171
|
+
result.name = name;
|
|
172
|
+
}
|
|
173
|
+
return result;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function address(value, label) {
|
|
177
|
+
const email = typeof value === "string" ? value.trim() : "";
|
|
178
|
+
if (email.length === 0 || email.length > MAX_EMAIL_CHARS || !EMAIL.test(email)) {
|
|
179
|
+
throw new ValidationError(`${label} contains an invalid email address`);
|
|
180
|
+
}
|
|
181
|
+
return email;
|
|
182
|
+
}
|
|
183
|
+
function objectSlug(value, label) {
|
|
184
|
+
if (typeof value !== "string")
|
|
185
|
+
throw new ValidationError(`${label} must be an object slug`);
|
|
186
|
+
return requireSlug(value);
|
|
187
|
+
}
|
|
188
|
+
function recordId(value, label) {
|
|
189
|
+
if (typeof value !== "string" || !RECORD_ID.test(value))
|
|
190
|
+
throw new ValidationError(`${label} must be a record ID`);
|
|
191
|
+
return value;
|
|
192
|
+
}
|
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";
|
package/dist/internal/base64.js
CHANGED
|
@@ -1,41 +1,90 @@
|
|
|
1
|
-
const
|
|
1
|
+
const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
2
2
|
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
3
3
|
// Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
|
|
4
|
+
// The sandbox caps the statements one execution may run and every loop turn costs about three of them, so each
|
|
5
|
+
// turn handles 24 bytes in a single expression: 256 KiB costs about 33,000 statements instead of several hundred
|
|
6
|
+
// thousand.
|
|
7
|
+
let digits;
|
|
8
|
+
/** 6-bit value of each base64 character code; "=" reads as 0 once the text has been validated. */
|
|
9
|
+
function digitTable() {
|
|
10
|
+
if (digits === undefined) {
|
|
11
|
+
const table = new Int32Array(128);
|
|
12
|
+
for (let index = 0; index < A.length; index++)
|
|
13
|
+
table[A.charCodeAt(index)] = index;
|
|
14
|
+
digits = table;
|
|
15
|
+
}
|
|
16
|
+
return digits;
|
|
17
|
+
}
|
|
4
18
|
/** Standard base64 with padding (RFC 4648 section 4). */
|
|
5
19
|
export function encodeBase64(bytes) {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
+
|
|
14
|
-
+ (index +
|
|
15
|
-
+ (index +
|
|
20
|
+
const length = bytes.length;
|
|
21
|
+
const whole = length - (length % 3);
|
|
22
|
+
const parts = [];
|
|
23
|
+
let index = 0;
|
|
24
|
+
for (; index + 24 <= whole; index += 24) {
|
|
25
|
+
parts[parts.length] = A.charAt(bytes[index] >>> 2) + A.charAt(((bytes[index] & 3) << 4) | (bytes[index + 1] >>> 4))
|
|
26
|
+
+ A.charAt(((bytes[index + 1] & 15) << 2) | (bytes[index + 2] >>> 6)) + A.charAt(bytes[index + 2] & 63)
|
|
27
|
+
+ A.charAt(bytes[index + 3] >>> 2) + A.charAt(((bytes[index + 3] & 3) << 4) | (bytes[index + 4] >>> 4))
|
|
28
|
+
+ A.charAt(((bytes[index + 4] & 15) << 2) | (bytes[index + 5] >>> 6)) + A.charAt(bytes[index + 5] & 63)
|
|
29
|
+
+ A.charAt(bytes[index + 6] >>> 2) + A.charAt(((bytes[index + 6] & 3) << 4) | (bytes[index + 7] >>> 4))
|
|
30
|
+
+ A.charAt(((bytes[index + 7] & 15) << 2) | (bytes[index + 8] >>> 6)) + A.charAt(bytes[index + 8] & 63)
|
|
31
|
+
+ A.charAt(bytes[index + 9] >>> 2) + A.charAt(((bytes[index + 9] & 3) << 4) | (bytes[index + 10] >>> 4))
|
|
32
|
+
+ A.charAt(((bytes[index + 10] & 15) << 2) | (bytes[index + 11] >>> 6)) + A.charAt(bytes[index + 11] & 63)
|
|
33
|
+
+ A.charAt(bytes[index + 12] >>> 2) + A.charAt(((bytes[index + 12] & 3) << 4) | (bytes[index + 13] >>> 4))
|
|
34
|
+
+ A.charAt(((bytes[index + 13] & 15) << 2) | (bytes[index + 14] >>> 6)) + A.charAt(bytes[index + 14] & 63)
|
|
35
|
+
+ A.charAt(bytes[index + 15] >>> 2) + A.charAt(((bytes[index + 15] & 3) << 4) | (bytes[index + 16] >>> 4))
|
|
36
|
+
+ A.charAt(((bytes[index + 16] & 15) << 2) | (bytes[index + 17] >>> 6)) + A.charAt(bytes[index + 17] & 63)
|
|
37
|
+
+ A.charAt(bytes[index + 18] >>> 2) + A.charAt(((bytes[index + 18] & 3) << 4) | (bytes[index + 19] >>> 4))
|
|
38
|
+
+ A.charAt(((bytes[index + 19] & 15) << 2) | (bytes[index + 20] >>> 6)) + A.charAt(bytes[index + 20] & 63)
|
|
39
|
+
+ A.charAt(bytes[index + 21] >>> 2) + A.charAt(((bytes[index + 21] & 3) << 4) | (bytes[index + 22] >>> 4))
|
|
40
|
+
+ A.charAt(((bytes[index + 22] & 15) << 2) | (bytes[index + 23] >>> 6)) + A.charAt(bytes[index + 23] & 63);
|
|
41
|
+
}
|
|
42
|
+
for (; index < whole; index += 3) {
|
|
43
|
+
parts[parts.length] = A.charAt(bytes[index] >>> 2) + A.charAt(((bytes[index] & 3) << 4) | (bytes[index + 1] >>> 4))
|
|
44
|
+
+ A.charAt(((bytes[index + 1] & 15) << 2) | (bytes[index + 2] >>> 6)) + A.charAt(bytes[index + 2] & 63);
|
|
45
|
+
}
|
|
46
|
+
if (length - whole === 1) {
|
|
47
|
+
parts[parts.length] = `${A.charAt(bytes[whole] >>> 2)}${A.charAt((bytes[whole] & 3) << 4)}==`;
|
|
16
48
|
}
|
|
17
|
-
|
|
49
|
+
else if (length - whole === 2) {
|
|
50
|
+
parts[parts.length] = `${A.charAt(bytes[whole] >>> 2)}${A.charAt(((bytes[whole] & 3) << 4) | (bytes[whole + 1] >>> 4))}`
|
|
51
|
+
+ `${A.charAt((bytes[whole + 1] & 15) << 2)}=`;
|
|
52
|
+
}
|
|
53
|
+
return parts.join("");
|
|
18
54
|
}
|
|
19
55
|
/** Decodes padded standard base64; returns null for text that is not canonical base64. */
|
|
20
56
|
export function decodeBase64(text) {
|
|
21
57
|
if (typeof text !== "string" || !BASE64.test(text))
|
|
22
58
|
return null;
|
|
59
|
+
const table = digitTable();
|
|
23
60
|
const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
|
|
24
|
-
const
|
|
61
|
+
const groups = text.length / 4;
|
|
62
|
+
// One spare byte: each group is written as a 32-bit word whose last byte the next group overwrites.
|
|
63
|
+
const buffer = new Uint8Array(groups * 3 + 1);
|
|
64
|
+
const view = new DataView(buffer.buffer);
|
|
65
|
+
let index = 0;
|
|
25
66
|
let position = 0;
|
|
26
|
-
for (
|
|
27
|
-
|
|
28
|
-
| (
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
67
|
+
for (; index + 32 <= text.length; index += 32, position += 24) {
|
|
68
|
+
view.setUint32(position, (table[text.charCodeAt(index)] << 26) | (table[text.charCodeAt(index + 1)] << 20)
|
|
69
|
+
| (table[text.charCodeAt(index + 2)] << 14) | (table[text.charCodeAt(index + 3)] << 8)),
|
|
70
|
+
view.setUint32(position + 3, (table[text.charCodeAt(index + 4)] << 26) | (table[text.charCodeAt(index + 5)] << 20)
|
|
71
|
+
| (table[text.charCodeAt(index + 6)] << 14) | (table[text.charCodeAt(index + 7)] << 8)),
|
|
72
|
+
view.setUint32(position + 6, (table[text.charCodeAt(index + 8)] << 26) | (table[text.charCodeAt(index + 9)] << 20)
|
|
73
|
+
| (table[text.charCodeAt(index + 10)] << 14) | (table[text.charCodeAt(index + 11)] << 8)),
|
|
74
|
+
view.setUint32(position + 9, (table[text.charCodeAt(index + 12)] << 26) | (table[text.charCodeAt(index + 13)] << 20)
|
|
75
|
+
| (table[text.charCodeAt(index + 14)] << 14) | (table[text.charCodeAt(index + 15)] << 8)),
|
|
76
|
+
view.setUint32(position + 12, (table[text.charCodeAt(index + 16)] << 26) | (table[text.charCodeAt(index + 17)] << 20)
|
|
77
|
+
| (table[text.charCodeAt(index + 18)] << 14) | (table[text.charCodeAt(index + 19)] << 8)),
|
|
78
|
+
view.setUint32(position + 15, (table[text.charCodeAt(index + 20)] << 26) | (table[text.charCodeAt(index + 21)] << 20)
|
|
79
|
+
| (table[text.charCodeAt(index + 22)] << 14) | (table[text.charCodeAt(index + 23)] << 8)),
|
|
80
|
+
view.setUint32(position + 18, (table[text.charCodeAt(index + 24)] << 26) | (table[text.charCodeAt(index + 25)] << 20)
|
|
81
|
+
| (table[text.charCodeAt(index + 26)] << 14) | (table[text.charCodeAt(index + 27)] << 8)),
|
|
82
|
+
view.setUint32(position + 21, (table[text.charCodeAt(index + 28)] << 26) | (table[text.charCodeAt(index + 29)] << 20)
|
|
83
|
+
| (table[text.charCodeAt(index + 30)] << 14) | (table[text.charCodeAt(index + 31)] << 8));
|
|
35
84
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return
|
|
85
|
+
for (; index < text.length; index += 4, position += 3) {
|
|
86
|
+
view.setUint32(position, (table[text.charCodeAt(index)] << 26) | (table[text.charCodeAt(index + 1)] << 20)
|
|
87
|
+
| (table[text.charCodeAt(index + 2)] << 14) | (table[text.charCodeAt(index + 3)] << 8));
|
|
88
|
+
}
|
|
89
|
+
return buffer.slice(0, groups * 3 - padding);
|
|
41
90
|
}
|
package/dist/internal/bridge.js
CHANGED
|
@@ -1,13 +1,40 @@
|
|
|
1
|
-
import { CogoverApiError, NotFoundError, PermissionDeniedError, RateLimitError, StateConflictError, LockLostError, ValidationError, } from "../errors.js";
|
|
1
|
+
import { CogoverApiError, NotFoundError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockLostError, ValidationError, } from "../errors.js";
|
|
2
|
+
import { utf8ByteLength } from "./utf8.js";
|
|
2
3
|
import { errorMessage, isRecord } from "./values.js";
|
|
3
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Largest capability request, envelope included, that Cogover accepts. A larger one would end the whole execution
|
|
6
|
+
* with a platform failure that a script cannot catch, so it is refused here as a ValidationError instead.
|
|
7
|
+
*/
|
|
8
|
+
export const MAX_BRIDGE_REQUEST_BYTES = 256 * 1024;
|
|
9
|
+
/** Bytes of the request envelope around an empty operation name and an empty payload. */
|
|
10
|
+
const ENVELOPE_BYTES = JSON.stringify({ version: 1, operation: "", payload: {} }).length;
|
|
11
|
+
/**
|
|
12
|
+
* Sends one capability request. `minimumPayloadBytes`, when given, must not exceed the UTF-8 size of the
|
|
13
|
+
* JSON-encoded payload: a request that cannot fit is then refused before it is serialized, so values that encode
|
|
14
|
+
* themselves while serializing (large bytes as base64) cost no CPU time or statements from the invocation's limits.
|
|
15
|
+
*/
|
|
16
|
+
export async function callBridge(operation, payload, minimumPayloadBytes = 0) {
|
|
4
17
|
const bridge = globalThis.__cogoverBridgeCall;
|
|
5
18
|
if (typeof bridge !== "function") {
|
|
6
19
|
throw new CogoverApiError("CAPABILITY_UNAVAILABLE", "Cogover data capabilities are only available inside the Cogover runtime");
|
|
7
20
|
}
|
|
21
|
+
if (ENVELOPE_BYTES + operation.length + minimumPayloadBytes > MAX_BRIDGE_REQUEST_BYTES) {
|
|
22
|
+
throw requestTooLarge(operation);
|
|
23
|
+
}
|
|
24
|
+
let requestJson;
|
|
25
|
+
try {
|
|
26
|
+
requestJson = JSON.stringify({ version: 1, operation, payload });
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw new CogoverApiError("BRIDGE_ERROR", errorMessage(error));
|
|
30
|
+
}
|
|
31
|
+
// A UTF-16 code unit never takes more than three UTF-8 bytes, so a short request needs no count.
|
|
32
|
+
if (requestJson.length * 3 > MAX_BRIDGE_REQUEST_BYTES && utf8ByteLength(requestJson) > MAX_BRIDGE_REQUEST_BYTES) {
|
|
33
|
+
throw requestTooLarge(operation);
|
|
34
|
+
}
|
|
8
35
|
let responseJson;
|
|
9
36
|
try {
|
|
10
|
-
responseJson = await bridge(
|
|
37
|
+
responseJson = await bridge(requestJson);
|
|
11
38
|
}
|
|
12
39
|
catch (error) {
|
|
13
40
|
throw new CogoverApiError("BRIDGE_ERROR", errorMessage(error));
|
|
@@ -24,6 +51,15 @@ export async function callBridge(operation, payload) {
|
|
|
24
51
|
}
|
|
25
52
|
throw publicError(response.error);
|
|
26
53
|
}
|
|
54
|
+
/** The same error Cogover reports for a request it refuses before dispatch. */
|
|
55
|
+
function requestTooLarge(operation) {
|
|
56
|
+
return publicError({
|
|
57
|
+
code: operation === "http.fetch" ? "FETCH_REQUEST_TOO_LARGE" : "VALIDATION_ERROR",
|
|
58
|
+
message: `The ${operation} request must not exceed ${MAX_BRIDGE_REQUEST_BYTES} bytes once JSON-encoded; `
|
|
59
|
+
+ "send less data in one call",
|
|
60
|
+
details: { limit: MAX_BRIDGE_REQUEST_BYTES },
|
|
61
|
+
});
|
|
62
|
+
}
|
|
27
63
|
function publicError(error) {
|
|
28
64
|
switch (error.code) {
|
|
29
65
|
case "NOT_FOUND": {
|
|
@@ -38,6 +74,8 @@ function publicError(error) {
|
|
|
38
74
|
return new PermissionDeniedError(error.message, error.details);
|
|
39
75
|
case "RATE_LIMITED":
|
|
40
76
|
return new RateLimitError(error.message, error.details);
|
|
77
|
+
case "RETRYABLE":
|
|
78
|
+
return new RetryableError(error.message, error.details);
|
|
41
79
|
case "STATE_CONFLICT":
|
|
42
80
|
return new StateConflictError(error.message, error.details);
|
|
43
81
|
case "LOCK_LOST":
|
|
@@ -12,6 +12,8 @@ const MIN_ATTEMPTS = 1;
|
|
|
12
12
|
const MAX_ATTEMPTS = 10;
|
|
13
13
|
const DEFAULT_ATTEMPTS = 5;
|
|
14
14
|
const MAX_TIMEZONE_LENGTH = 64;
|
|
15
|
+
// Cogover refuses a longer expression when the version is published.
|
|
16
|
+
const MAX_CRON_LENGTH = 128;
|
|
15
17
|
const DEFAULT_TIMEZONE = "UTC";
|
|
16
18
|
// The shape of an IANA zone ID; Cogover checks that the zone exists when the version is published.
|
|
17
19
|
const TIMEZONE = /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)*$/;
|
|
@@ -93,8 +95,12 @@ function normalizeCron(expression, fail) {
|
|
|
93
95
|
if (fields.length !== 5) {
|
|
94
96
|
throw fail("schedule", `schedule.cron must contain exactly five fields, found ${fields.length}`);
|
|
95
97
|
}
|
|
98
|
+
const normalized = fields.join(" ");
|
|
99
|
+
if (normalized.length > MAX_CRON_LENGTH) {
|
|
100
|
+
throw fail("schedule", `schedule.cron must be a non-empty string of at most ${MAX_CRON_LENGTH} characters`);
|
|
101
|
+
}
|
|
96
102
|
fields.forEach((field, index) => validateCronField(field, CRON_FIELDS[index], fail));
|
|
97
|
-
return
|
|
103
|
+
return normalized;
|
|
98
104
|
}
|
|
99
105
|
function validateCronField(field, spec, fail) {
|
|
100
106
|
const unsupported = (item) => fail("schedule", `schedule.cron ${spec.name} field contains the unsupported value '${item}'; `
|
|
@@ -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/internal/utf8.js
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
|
-
|
|
1
|
+
const NON_ASCII = /[^\u0000-\u007f]/;
|
|
2
|
+
const TWO_BYTE_UNITS = /[\u0080-\u07ff]/g;
|
|
3
|
+
const THREE_BYTE_UNITS = /[\u0800-\ud7ff\ue000-\uffff]/g;
|
|
4
|
+
const SURROGATE_UNITS = /[\ud800-\udfff]/g;
|
|
5
|
+
const SURROGATE_PAIRS = /[\ud800-\udbff][\udc00-\udfff]/g;
|
|
6
|
+
/**
|
|
7
|
+
* Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. Native regular
|
|
8
|
+
* expressions count the code units, so the cost in the sandbox statement budget does not grow with the length.
|
|
9
|
+
*/
|
|
2
10
|
export function utf8ByteLength(value) {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
bytes += 4;
|
|
13
|
-
index++;
|
|
14
|
-
}
|
|
15
|
-
else
|
|
16
|
-
bytes += 3;
|
|
17
|
-
}
|
|
18
|
-
return bytes;
|
|
11
|
+
if (!NON_ASCII.test(value))
|
|
12
|
+
return value.length;
|
|
13
|
+
const matchedUnits = (pattern) => value.length - value.replace(pattern, "").length;
|
|
14
|
+
const surrogateUnits = matchedUnits(SURROGATE_UNITS);
|
|
15
|
+
const pairedUnits = surrogateUnits === 0 ? 0 : matchedUnits(SURROGATE_PAIRS);
|
|
16
|
+
// Every unit counts one byte, plus one for U+0080-U+07FF, two for the rest of the BMP, one for each unit of
|
|
17
|
+
// a surrogate pair (four bytes a pair) and two for a lone surrogate (encoded as U+FFFD).
|
|
18
|
+
return value.length + matchedUnits(TWO_BYTE_UNITS) + 2 * matchedUnits(THREE_BYTE_UNITS)
|
|
19
|
+
+ pairedUnits + 2 * (surrogateUnits - pairedUnits);
|
|
19
20
|
}
|
|
20
21
|
/** UTF-8 encoding without TextEncoder, which the sandbox does not provide; a lone surrogate becomes U+FFFD. */
|
|
21
22
|
export function encodeUtf8(value) {
|
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;
|
package/dist/locks.js
CHANGED
|
@@ -30,12 +30,22 @@ export function createLocksApi() {
|
|
|
30
30
|
const acquired = await api.acquire(key, options);
|
|
31
31
|
if (acquired === null)
|
|
32
32
|
throw new LockUnavailableError(key);
|
|
33
|
+
let result;
|
|
33
34
|
try {
|
|
34
|
-
|
|
35
|
+
result = await callback(acquired);
|
|
35
36
|
}
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
catch (error) {
|
|
38
|
+
try {
|
|
39
|
+
await acquired.release();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// The callback's error is the one the caller must see; an unreleased lease expires on its own.
|
|
43
|
+
}
|
|
44
|
+
throw error;
|
|
38
45
|
}
|
|
46
|
+
// After a successful callback a failed release (for example LockLostError) is reported.
|
|
47
|
+
await acquired.release();
|
|
48
|
+
return result;
|
|
39
49
|
},
|
|
40
50
|
};
|
|
41
51
|
return Object.freeze(api);
|