@cogover/sdk 0.6.0 → 0.8.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 +126 -5
- package/dist/crypto.d.ts +20 -0
- package/dist/crypto.js +123 -0
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/fetch.d.ts +2 -0
- package/dist/fetch.js +6 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.js +2 -0
- package/dist/internal/base64.js +41 -0
- package/dist/internal/invocation.js +15 -0
- package/dist/internal/job-config.js +143 -0
- package/dist/internal/job-runtime.js +90 -0
- package/dist/internal/jobs-api.js +58 -0
- package/dist/internal/request.js +14 -2
- package/dist/internal/trigger-runtime.js +9 -0
- package/dist/internal/utf8.js +55 -0
- package/dist/internal/validation.js +8 -0
- package/dist/invocation.d.ts +14 -1
- package/dist/jobs.d.ts +95 -0
- package/dist/jobs.js +15 -0
- package/dist/push.d.ts +48 -0
- package/dist/push.js +190 -0
- package/dist/request.d.ts +4 -0
- package/dist/response.js +1 -15
- package/dist/router.js +4 -0
- package/dist/script.d.ts +8 -0
- package/dist/script.js +8 -0
- package/dist/secrets.d.ts +8 -0
- package/dist/secrets.js +17 -0
- package/dist/state.js +2 -19
- package/dist/trigger.d.ts +11 -0
- package/docs/en/api-reference.md +631 -25
- package/docs/en/usage-guide.md +230 -6
- package/package.json +1 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { crypto } from "../crypto.js";
|
|
2
|
+
import { createDataApi } from "../data.js";
|
|
3
|
+
import { ValidationError } from "../errors.js";
|
|
4
|
+
import { installCogoverFetch } from "../fetch.js";
|
|
5
|
+
import { createLocksApi } from "../locks.js";
|
|
6
|
+
import { SCRIPT_LOGGER } from "../logger.js";
|
|
7
|
+
import { createSchemaApi } from "../schema.js";
|
|
8
|
+
import { createSecretsApi } from "../secrets.js";
|
|
9
|
+
import { createStateApi } from "../state.js";
|
|
10
|
+
import { invocationContext } from "./invocation.js";
|
|
11
|
+
import { createJobsApi } from "./jobs-api.js";
|
|
12
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
13
|
+
// Both spellings of a source are accepted; project code only ever sees the SDK literals.
|
|
14
|
+
const SOURCES = new Map([
|
|
15
|
+
["enqueue", "enqueue"],
|
|
16
|
+
["ENQUEUE", "enqueue"],
|
|
17
|
+
["schedule", "schedule"],
|
|
18
|
+
["SCHEDULE", "schedule"],
|
|
19
|
+
]);
|
|
20
|
+
export function createJobSandboxHandler(manifest, handler) {
|
|
21
|
+
return async (inputJson) => {
|
|
22
|
+
installCogoverFetch();
|
|
23
|
+
let input;
|
|
24
|
+
try {
|
|
25
|
+
input = JSON.parse(inputJson);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
throw new ValidationError("Job input must be valid JSON", errorMessage(error));
|
|
29
|
+
}
|
|
30
|
+
if (!isRecord(input))
|
|
31
|
+
throw new ValidationError("Job input must be a JSON object");
|
|
32
|
+
const job = jobInfo(input, manifest);
|
|
33
|
+
let invocation;
|
|
34
|
+
await handler(Object.freeze({
|
|
35
|
+
job,
|
|
36
|
+
payload: input.payload ?? null,
|
|
37
|
+
get invocation() {
|
|
38
|
+
return invocation ??= invocationContext(input);
|
|
39
|
+
},
|
|
40
|
+
data: createDataApi(),
|
|
41
|
+
schema: createSchemaApi(),
|
|
42
|
+
log: SCRIPT_LOGGER,
|
|
43
|
+
state: createStateApi(),
|
|
44
|
+
locks: createLocksApi(),
|
|
45
|
+
jobs: createJobsApi(),
|
|
46
|
+
secrets: createSecretsApi(),
|
|
47
|
+
crypto,
|
|
48
|
+
}));
|
|
49
|
+
// The result of a job is not delivered anywhere, so nothing is serialized.
|
|
50
|
+
return null;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function jobInfo(input, manifest) {
|
|
54
|
+
const context = isRecord(input.__context) ? input.__context : undefined;
|
|
55
|
+
const raw = context !== undefined && isRecord(context.job) ? context.job : undefined;
|
|
56
|
+
if (raw === undefined) {
|
|
57
|
+
throw new ValidationError("Job metadata is unavailable outside Cogover Runtime");
|
|
58
|
+
}
|
|
59
|
+
const source = SOURCES.get(raw.source);
|
|
60
|
+
if (source === undefined)
|
|
61
|
+
throw new ValidationError("Invalid job source metadata");
|
|
62
|
+
const info = Object.freeze({
|
|
63
|
+
id: requiredString(raw.id, "id"),
|
|
64
|
+
key: requiredString(raw.key, "key"),
|
|
65
|
+
attempt: requiredInteger(raw.attempt, "attempt", 1),
|
|
66
|
+
maxAttempts: requiredInteger(raw.maxAttempts, "maxAttempts", 1),
|
|
67
|
+
source,
|
|
68
|
+
runAt: requiredInteger(raw.runAt, "runAt", 0),
|
|
69
|
+
...(raw.enqueuedAt === undefined || raw.enqueuedAt === null
|
|
70
|
+
? {}
|
|
71
|
+
: { enqueuedAt: requiredInteger(raw.enqueuedAt, "enqueuedAt", 0) }),
|
|
72
|
+
});
|
|
73
|
+
// A mismatch means the call was routed to a definition it was not registered for.
|
|
74
|
+
if (info.key !== manifest.key) {
|
|
75
|
+
throw new ValidationError(`Job input for '${info.key}' does not match the definition of '${manifest.key}'`);
|
|
76
|
+
}
|
|
77
|
+
return info;
|
|
78
|
+
}
|
|
79
|
+
function requiredString(value, name) {
|
|
80
|
+
if (typeof value !== "string" || value === "") {
|
|
81
|
+
throw new ValidationError(`Invalid job ${name} metadata`);
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
function requiredInteger(value, name, minimum) {
|
|
86
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
|
|
87
|
+
throw new ValidationError(`Invalid job ${name} metadata`);
|
|
88
|
+
}
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "../errors.js";
|
|
2
|
+
import { optionalInteger } from "../state.js";
|
|
3
|
+
import { callBridge } from "./bridge.js";
|
|
4
|
+
import { JOB_KEY } from "./job-config.js";
|
|
5
|
+
import { toJsonValue } from "./json.js";
|
|
6
|
+
import { utf8ByteLength } from "./utf8.js";
|
|
7
|
+
import { isRecord } from "./values.js";
|
|
8
|
+
const OPTION_KEYS = new Set(["delayMs", "runAt", "idempotencyKey"]);
|
|
9
|
+
const MAX_PAYLOAD_BYTES = 65_536;
|
|
10
|
+
const MAX_DELAY_MILLIS = 30 * 24 * 60 * 60 * 1000;
|
|
11
|
+
const IDEMPOTENCY_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
12
|
+
/** @internal */
|
|
13
|
+
export function createJobsApi() {
|
|
14
|
+
return Object.freeze({
|
|
15
|
+
async enqueue(jobKey, payload, options) {
|
|
16
|
+
if (typeof jobKey !== "string" || !JOB_KEY.test(jobKey)) {
|
|
17
|
+
throw new ValidationError("jobs.enqueue() job key must start with a letter and contain "
|
|
18
|
+
+ "at most 100 letters, digits or underscores");
|
|
19
|
+
}
|
|
20
|
+
if (options !== undefined && !isRecord(options)) {
|
|
21
|
+
throw new ValidationError("jobs.enqueue() options must be an object");
|
|
22
|
+
}
|
|
23
|
+
for (const option of Object.keys(options ?? {})) {
|
|
24
|
+
if (!OPTION_KEYS.has(option))
|
|
25
|
+
throw new ValidationError(`jobs.enqueue() has the unknown option '${option}'`);
|
|
26
|
+
}
|
|
27
|
+
const request = { jobKey };
|
|
28
|
+
if (payload !== undefined && payload !== null) {
|
|
29
|
+
const json = toJsonValue(payload, "jobs.enqueue() payload");
|
|
30
|
+
if (utf8ByteLength(JSON.stringify(json)) > MAX_PAYLOAD_BYTES) {
|
|
31
|
+
throw new ValidationError(`jobs.enqueue() payload must not exceed ${MAX_PAYLOAD_BYTES} UTF-8 bytes`);
|
|
32
|
+
}
|
|
33
|
+
request.payload = json;
|
|
34
|
+
}
|
|
35
|
+
const delayMs = optionalInteger(options?.delayMs, "jobs.enqueue() delayMs", 0, MAX_DELAY_MILLIS);
|
|
36
|
+
const runAt = optionalInteger(options?.runAt, "jobs.enqueue() runAt", 0, Number.MAX_SAFE_INTEGER);
|
|
37
|
+
if (delayMs !== undefined && runAt !== undefined) {
|
|
38
|
+
throw new ValidationError("jobs.enqueue() accepts either delayMs or runAt, not both");
|
|
39
|
+
}
|
|
40
|
+
if (delayMs !== undefined)
|
|
41
|
+
request.delayMs = delayMs;
|
|
42
|
+
if (runAt !== undefined)
|
|
43
|
+
request.runAt = runAt;
|
|
44
|
+
if (options?.idempotencyKey !== undefined) {
|
|
45
|
+
if (typeof options.idempotencyKey !== "string" || !IDEMPOTENCY_KEY.test(options.idempotencyKey)) {
|
|
46
|
+
throw new ValidationError("jobs.enqueue() idempotencyKey must start with a letter or digit and "
|
|
47
|
+
+ "contain at most 128 letters, digits, '.', '_', ':' or '-'");
|
|
48
|
+
}
|
|
49
|
+
request.idempotencyKey = options.idempotencyKey;
|
|
50
|
+
}
|
|
51
|
+
const result = await callBridge("jobs.enqueue", request);
|
|
52
|
+
if (!isRecord(result) || typeof result.runId !== "string" || typeof result.duplicate !== "boolean") {
|
|
53
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Enqueue result is invalid");
|
|
54
|
+
}
|
|
55
|
+
return Object.freeze({ runId: result.runId, duplicate: result.duplicate });
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
package/dist/internal/request.js
CHANGED
|
@@ -30,7 +30,8 @@ export function scriptRequest(input) {
|
|
|
30
30
|
if (metadata !== undefined && (!isRecord(metadata)
|
|
31
31
|
|| typeof metadata.method !== "string" || typeof metadata.path !== "string"
|
|
32
32
|
|| (metadata.query !== undefined && !isRecord(metadata.query))
|
|
33
|
-
|| (metadata.headers !== undefined && !isRecord(metadata.headers))
|
|
33
|
+
|| (metadata.headers !== undefined && !isRecord(metadata.headers))
|
|
34
|
+
|| !isOptionalString(metadata.rawBody) || !isOptionalString(metadata.contentType))) {
|
|
34
35
|
throw new ValidationError("Invalid invocation request metadata");
|
|
35
36
|
}
|
|
36
37
|
// Direct SDK invocations without host metadata retain the original POST/root behavior.
|
|
@@ -47,7 +48,18 @@ export function scriptRequest(input) {
|
|
|
47
48
|
const { __context: _context, ...businessBody } = input;
|
|
48
49
|
body = businessBody;
|
|
49
50
|
}
|
|
50
|
-
|
|
51
|
+
// Absent optional keys are omitted, never undefined.
|
|
52
|
+
const rawBody = isRecord(metadata) && typeof metadata.rawBody === "string" ? metadata.rawBody : undefined;
|
|
53
|
+
const contentType = isRecord(metadata) && typeof metadata.contentType === "string" ? metadata.contentType : undefined;
|
|
54
|
+
return Object.freeze({
|
|
55
|
+
method, path, params: Object.freeze({}), query, headers, body,
|
|
56
|
+
...(rawBody === undefined ? {} : { rawBody }),
|
|
57
|
+
...(contentType === undefined ? {} : { contentType }),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
// A JSON writer may emit null for an absent field, so null counts as absent.
|
|
61
|
+
function isOptionalString(value) {
|
|
62
|
+
return value === undefined || value === null || typeof value === "string";
|
|
51
63
|
}
|
|
52
64
|
export function withRouteParams(request, params) {
|
|
53
65
|
return Object.freeze({ ...request, params: Object.freeze({ ...params }) });
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { crypto } from "../crypto.js";
|
|
1
2
|
import { createDataApi } from "../data.js";
|
|
2
3
|
import { ValidationError } from "../errors.js";
|
|
3
4
|
import { installCogoverFetch } from "../fetch.js";
|
|
4
5
|
import { SCRIPT_LOGGER } from "../logger.js";
|
|
6
|
+
import { createPushApi } from "../push.js";
|
|
5
7
|
import { createSchemaApi } from "../schema.js";
|
|
8
|
+
import { createSecretsApi } from "../secrets.js";
|
|
6
9
|
import { invocationContext } from "./invocation.js";
|
|
10
|
+
import { createJobsApi } from "./jobs-api.js";
|
|
7
11
|
import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
|
|
8
12
|
import { TRIGGER_SLUG } from "./trigger-config.js";
|
|
9
13
|
import { errorMessage, isRecord } from "./values.js";
|
|
@@ -49,6 +53,11 @@ export function createTriggerSandboxHandler(manifest, handler) {
|
|
|
49
53
|
data: createDataApi(),
|
|
50
54
|
schema: createSchemaApi(),
|
|
51
55
|
log: SCRIPT_LOGGER,
|
|
56
|
+
push: createPushApi(),
|
|
57
|
+
// The host refuses jobs and secrets in a before-change trigger; the SDK does not pre-empt it.
|
|
58
|
+
jobs: createJobsApi(),
|
|
59
|
+
secrets: createSecretsApi(),
|
|
60
|
+
crypto,
|
|
52
61
|
}));
|
|
53
62
|
const results = [];
|
|
54
63
|
for (const entry of entries) {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. */
|
|
2
|
+
export function utf8ByteLength(value) {
|
|
3
|
+
let bytes = 0;
|
|
4
|
+
for (let index = 0; index < value.length; index++) {
|
|
5
|
+
const code = value.charCodeAt(index);
|
|
6
|
+
if (code < 0x80)
|
|
7
|
+
bytes++;
|
|
8
|
+
else if (code < 0x800)
|
|
9
|
+
bytes += 2;
|
|
10
|
+
else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length
|
|
11
|
+
&& value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) {
|
|
12
|
+
bytes += 4;
|
|
13
|
+
index++;
|
|
14
|
+
}
|
|
15
|
+
else
|
|
16
|
+
bytes += 3;
|
|
17
|
+
}
|
|
18
|
+
return bytes;
|
|
19
|
+
}
|
|
20
|
+
/** UTF-8 encoding without TextEncoder, which the sandbox does not provide; a lone surrogate becomes U+FFFD. */
|
|
21
|
+
export function encodeUtf8(value) {
|
|
22
|
+
const bytes = new Uint8Array(utf8ByteLength(value));
|
|
23
|
+
let position = 0;
|
|
24
|
+
for (let index = 0; index < value.length; index++) {
|
|
25
|
+
let code = value.charCodeAt(index);
|
|
26
|
+
if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
|
|
27
|
+
const low = value.charCodeAt(index + 1);
|
|
28
|
+
if (low >= 0xdc00 && low <= 0xdfff) {
|
|
29
|
+
code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00);
|
|
30
|
+
index++;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (code >= 0xd800 && code <= 0xdfff)
|
|
34
|
+
code = 0xfffd;
|
|
35
|
+
if (code < 0x80) {
|
|
36
|
+
bytes[position++] = code;
|
|
37
|
+
}
|
|
38
|
+
else if (code < 0x800) {
|
|
39
|
+
bytes[position++] = 0xc0 | (code >> 6);
|
|
40
|
+
bytes[position++] = 0x80 | (code & 63);
|
|
41
|
+
}
|
|
42
|
+
else if (code < 0x10000) {
|
|
43
|
+
bytes[position++] = 0xe0 | (code >> 12);
|
|
44
|
+
bytes[position++] = 0x80 | ((code >> 6) & 63);
|
|
45
|
+
bytes[position++] = 0x80 | (code & 63);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
bytes[position++] = 0xf0 | (code >> 18);
|
|
49
|
+
bytes[position++] = 0x80 | ((code >> 12) & 63);
|
|
50
|
+
bytes[position++] = 0x80 | ((code >> 6) & 63);
|
|
51
|
+
bytes[position++] = 0x80 | (code & 63);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return bytes;
|
|
55
|
+
}
|
|
@@ -14,6 +14,14 @@ export function requireFieldSlug(value, name = "field slug") {
|
|
|
14
14
|
}
|
|
15
15
|
return slug;
|
|
16
16
|
}
|
|
17
|
+
/** Name of a project secret or credential: a letter followed by up to 63 letters, digits or underscores. */
|
|
18
|
+
export const SECRET_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
19
|
+
export function requireSecretName(value, label) {
|
|
20
|
+
if (typeof value !== "string" || !SECRET_NAME.test(value)) {
|
|
21
|
+
throw new ValidationError(`${label} must start with a letter and contain at most 64 letters, digits or underscores`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
17
25
|
export function requireText(value, name) {
|
|
18
26
|
if (typeof value !== "string" || value.trim().length === 0) {
|
|
19
27
|
throw new ValidationError(`${name} must be a non-empty string`);
|
package/dist/invocation.d.ts
CHANGED
|
@@ -36,5 +36,18 @@ export interface SystemInvocationContext {
|
|
|
36
36
|
readonly workspace: CurrentWorkspace;
|
|
37
37
|
readonly user: null;
|
|
38
38
|
}
|
|
39
|
+
/** A webhook call authenticated by one of the project's inbound accesses. */
|
|
40
|
+
export interface InboundInvocationContext {
|
|
41
|
+
readonly identity: "inbound";
|
|
42
|
+
readonly workspace: CurrentWorkspace;
|
|
43
|
+
readonly user: null;
|
|
44
|
+
readonly inbound: {
|
|
45
|
+
/** ID of the inbound access; it is part of the webhook URL. */
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
/** How the call was authenticated: an inbound key or an HMAC signature. */
|
|
49
|
+
readonly mode: "KEY" | "HMAC";
|
|
50
|
+
};
|
|
51
|
+
}
|
|
39
52
|
/** Immutable authenticated identity and workspace snapshot for one execution. */
|
|
40
|
-
export type InvocationContext = UserInvocationContext | SystemInvocationContext;
|
|
53
|
+
export type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
|
package/dist/jobs.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { CryptoApi } from "./crypto.js";
|
|
2
|
+
import type { DataApi } from "./data.js";
|
|
3
|
+
import type { InvocationContext } from "./invocation.js";
|
|
4
|
+
import type { DistributedLocks } from "./locks.js";
|
|
5
|
+
import type { ScriptLogger } from "./logger.js";
|
|
6
|
+
import type { SchemaApi } from "./schema.js";
|
|
7
|
+
import type { SandboxHandler } from "./script.js";
|
|
8
|
+
import type { SecretsApi } from "./secrets.js";
|
|
9
|
+
import type { ProjectState } from "./state.js";
|
|
10
|
+
import type { EffectiveWorkspaceObjects } from "./workspace.js";
|
|
11
|
+
/** Runs a job on a cron schedule. */
|
|
12
|
+
export interface JobSchedule {
|
|
13
|
+
/** Five fields: minute, hour, day-of-month, month, day-of-week. */
|
|
14
|
+
readonly cron: string;
|
|
15
|
+
/** IANA time zone the schedule is evaluated in; defaults to `"UTC"`. */
|
|
16
|
+
readonly timezone?: string;
|
|
17
|
+
}
|
|
18
|
+
/** Options accepted by `defineJob`. */
|
|
19
|
+
export interface JobConfig {
|
|
20
|
+
/** Stable identifier of the job inside the project. */
|
|
21
|
+
readonly key: string;
|
|
22
|
+
/** Display name; defaults to `key`. */
|
|
23
|
+
readonly name?: string;
|
|
24
|
+
/** Time budget of one run, in milliseconds. */
|
|
25
|
+
readonly timeoutMs?: number;
|
|
26
|
+
/** Number of attempts before a run that keeps failing for a temporary reason is given up. */
|
|
27
|
+
readonly maxAttempts?: number;
|
|
28
|
+
/** Runs the job automatically on a cron schedule. */
|
|
29
|
+
readonly schedule?: JobSchedule;
|
|
30
|
+
}
|
|
31
|
+
/** Normalized, immutable job configuration with every default applied. */
|
|
32
|
+
export interface JobManifest {
|
|
33
|
+
readonly key: string;
|
|
34
|
+
readonly name?: string;
|
|
35
|
+
readonly timeoutMs: number;
|
|
36
|
+
readonly maxAttempts: number;
|
|
37
|
+
readonly schedule?: Required<JobSchedule>;
|
|
38
|
+
}
|
|
39
|
+
/** Result of `defineJob`; list it in the project's `jobs` export. */
|
|
40
|
+
export interface JobDefinition {
|
|
41
|
+
readonly key: string;
|
|
42
|
+
readonly config: JobManifest;
|
|
43
|
+
/** Reserved for Cogover; project code does not call it. */
|
|
44
|
+
readonly __cogoverJobHandler: SandboxHandler;
|
|
45
|
+
}
|
|
46
|
+
/** Identifies the job run of the current call. */
|
|
47
|
+
export interface JobInfo {
|
|
48
|
+
/** Identifies this run across its attempts. */
|
|
49
|
+
readonly id: string;
|
|
50
|
+
readonly key: string;
|
|
51
|
+
/** 1 for the first attempt of a run. */
|
|
52
|
+
readonly attempt: number;
|
|
53
|
+
readonly maxAttempts: number;
|
|
54
|
+
/** Whether the run was enqueued by code or created by the schedule. */
|
|
55
|
+
readonly source: "enqueue" | "schedule";
|
|
56
|
+
/** When the run became due, in Unix milliseconds. */
|
|
57
|
+
readonly runAt: number;
|
|
58
|
+
/** When the run was enqueued, in Unix milliseconds; absent for a scheduled run. */
|
|
59
|
+
readonly enqueuedAt?: number;
|
|
60
|
+
}
|
|
61
|
+
/** Options of `jobs.enqueue`. */
|
|
62
|
+
export interface EnqueueOptions {
|
|
63
|
+
/** Runs the job after this delay in milliseconds instead of as soon as possible. */
|
|
64
|
+
readonly delayMs?: number;
|
|
65
|
+
/** Runs the job at this Unix millisecond time instead of as soon as possible. */
|
|
66
|
+
readonly runAt?: number;
|
|
67
|
+
/** A second enqueue of the same job with the same key within the retention period is ignored. */
|
|
68
|
+
readonly idempotencyKey?: string;
|
|
69
|
+
}
|
|
70
|
+
export interface EnqueueResult {
|
|
71
|
+
readonly runId: string;
|
|
72
|
+
/** `true` when an earlier enqueue with the same `idempotencyKey` was found; `runId` is that run. */
|
|
73
|
+
readonly duplicate: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** Enqueues background jobs of the project. */
|
|
76
|
+
export interface JobsApi {
|
|
77
|
+
enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
|
|
78
|
+
}
|
|
79
|
+
export interface JobContext<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> {
|
|
80
|
+
readonly job: JobInfo;
|
|
81
|
+
/** The JSON value passed to `jobs.enqueue`, or `null` when there was none or the run is scheduled. */
|
|
82
|
+
readonly payload: TPayload | null;
|
|
83
|
+
readonly invocation: InvocationContext;
|
|
84
|
+
readonly data: DataApi<TSchema>;
|
|
85
|
+
readonly schema: SchemaApi<TSchema>;
|
|
86
|
+
readonly log: ScriptLogger;
|
|
87
|
+
readonly state: ProjectState;
|
|
88
|
+
readonly locks: DistributedLocks;
|
|
89
|
+
readonly jobs: JobsApi;
|
|
90
|
+
readonly secrets: SecretsApi;
|
|
91
|
+
readonly crypto: CryptoApi;
|
|
92
|
+
}
|
|
93
|
+
export type JobHandler<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> = (context: JobContext<TPayload, TSchema>) => void | Promise<void>;
|
|
94
|
+
/** Declares a background job. Add the result to the project's `jobs` export. */
|
|
95
|
+
export declare function defineJob<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects>(config: JobConfig, handler: JobHandler<TPayload, TSchema>): JobDefinition;
|
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ValidationError } from "./errors.js";
|
|
2
|
+
import { normalizeJobConfig } from "./internal/job-config.js";
|
|
3
|
+
import { createJobSandboxHandler } from "./internal/job-runtime.js";
|
|
4
|
+
/** Declares a background job. Add the result to the project's `jobs` export. */
|
|
5
|
+
export function defineJob(config, handler) {
|
|
6
|
+
const manifest = normalizeJobConfig(config);
|
|
7
|
+
if (typeof handler !== "function") {
|
|
8
|
+
throw new ValidationError(`Job '${manifest.key}' requires a handler function`);
|
|
9
|
+
}
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
key: manifest.key,
|
|
12
|
+
config: manifest,
|
|
13
|
+
__cogoverJobHandler: createJobSandboxHandler(manifest, handler),
|
|
14
|
+
});
|
|
15
|
+
}
|
package/dist/push.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { EffectiveWorkspaceObjects, StringKeyOf } from "./workspace.js";
|
|
2
|
+
/** Who receives a push message: everyone who currently has a target record open, or explicit personnel. */
|
|
3
|
+
export type PushRecipients = "viewers" | readonly string[];
|
|
4
|
+
export interface PushOptions {
|
|
5
|
+
/** Defaults to `"viewers"`. Personnel IDs deliver to those people wherever they are in the workspace. */
|
|
6
|
+
readonly recipients?: PushRecipients;
|
|
7
|
+
/** Personnel IDs that never receive the message; `"actor"` is the user whose action started this execution. */
|
|
8
|
+
readonly exclude?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
export type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT" | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
|
|
11
|
+
export type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
|
|
12
|
+
export interface ToastLink {
|
|
13
|
+
readonly label: string;
|
|
14
|
+
/** Absolute `http` or `https` URL. */
|
|
15
|
+
readonly url: string;
|
|
16
|
+
}
|
|
17
|
+
/** A short notification shown by the web app. At least one of `title` and `content` is required. */
|
|
18
|
+
export interface ToastMessage<TObject extends string = string> {
|
|
19
|
+
readonly title?: string;
|
|
20
|
+
readonly content?: string;
|
|
21
|
+
readonly links?: readonly ToastLink[];
|
|
22
|
+
/** Defaults to `"TOP_RIGHT"`. */
|
|
23
|
+
readonly position?: ToastPosition;
|
|
24
|
+
/** Defaults to `"MEDIUM"`. */
|
|
25
|
+
readonly size?: ToastSize;
|
|
26
|
+
/** Seconds the toast stays visible, 1 to 60; defaults to 5. */
|
|
27
|
+
readonly durationSeconds?: number;
|
|
28
|
+
/** Records the toast is about; required when the recipients are `"viewers"`. */
|
|
29
|
+
readonly object?: TObject;
|
|
30
|
+
readonly recordIds?: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
export type BackgroundContentType = "text" | "template";
|
|
33
|
+
/** A message the web app handles without showing a notification. */
|
|
34
|
+
export interface BackgroundMessage<TObject extends string = string> {
|
|
35
|
+
readonly content: string;
|
|
36
|
+
/** Defaults to `"text"`. */
|
|
37
|
+
readonly contentType?: BackgroundContentType;
|
|
38
|
+
/** Records the message is about; required when the recipients are `"viewers"`. */
|
|
39
|
+
readonly object?: TObject;
|
|
40
|
+
readonly recordIds?: readonly string[];
|
|
41
|
+
}
|
|
42
|
+
/** Sends push messages to web clients of the workspace. Delivery is best-effort and never awaited. */
|
|
43
|
+
export interface PushApi<TSchema extends object = EffectiveWorkspaceObjects> {
|
|
44
|
+
/** Asks every client that shows one of these records to reload it. */
|
|
45
|
+
refreshRecords(object: StringKeyOf<TSchema>, recordIds: readonly string[], options?: PushOptions): Promise<void>;
|
|
46
|
+
toast(message: ToastMessage<StringKeyOf<TSchema>>, options?: PushOptions): Promise<void>;
|
|
47
|
+
message(message: BackgroundMessage<StringKeyOf<TSchema>>, options?: PushOptions): Promise<void>;
|
|
48
|
+
}
|
package/dist/push.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { requireSlug } from "./internal/validation.js";
|
|
4
|
+
import { isRecord } from "./internal/values.js";
|
|
5
|
+
import { optionalInteger } from "./state.js";
|
|
6
|
+
const MAX_RECORDS = 200;
|
|
7
|
+
const MAX_PERSONNEL = 200;
|
|
8
|
+
const MAX_TITLE_CHARS = 200;
|
|
9
|
+
const MAX_TOAST_CONTENT_CHARS = 4_000;
|
|
10
|
+
const MAX_MESSAGE_CONTENT_CHARS = 16_384;
|
|
11
|
+
const MAX_LINKS = 5;
|
|
12
|
+
const MAX_LINK_LABEL_CHARS = 100;
|
|
13
|
+
const MAX_LINK_URL_CHARS = 2_048;
|
|
14
|
+
const MIN_DURATION_SECONDS = 1;
|
|
15
|
+
const MAX_DURATION_SECONDS = 60;
|
|
16
|
+
const DEFAULT_DURATION_SECONDS = 5;
|
|
17
|
+
const RECORD_ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
18
|
+
const PERSONNEL_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
19
|
+
const ACTOR = "actor";
|
|
20
|
+
const VIEWERS = "viewers";
|
|
21
|
+
const POSITIONS = new Set([
|
|
22
|
+
"TOP_LEFT", "TOP_CENTER", "TOP_RIGHT", "BOTTOM_LEFT", "BOTTOM_CENTER", "BOTTOM_RIGHT",
|
|
23
|
+
]);
|
|
24
|
+
const SIZES = new Set(["SMALL", "MEDIUM", "LARGE"]);
|
|
25
|
+
const CONTENT_TYPES = new Set(["text", "template"]);
|
|
26
|
+
/** @internal */
|
|
27
|
+
export function createPushApi() {
|
|
28
|
+
return Object.freeze({
|
|
29
|
+
async refreshRecords(object, recordIds, options) {
|
|
30
|
+
const payload = { ...target(object, recordIds), ...audience(options) };
|
|
31
|
+
await callBridge("push.refreshRecords", payload);
|
|
32
|
+
},
|
|
33
|
+
async toast(message, options) {
|
|
34
|
+
requireMessageObject(message, "push.toast()");
|
|
35
|
+
const recipients = audience(options);
|
|
36
|
+
const title = optionalText(message.title, "title", MAX_TITLE_CHARS);
|
|
37
|
+
const content = optionalText(message.content, "content", MAX_TOAST_CONTENT_CHARS);
|
|
38
|
+
if (title === undefined && content === undefined) {
|
|
39
|
+
throw new ValidationError("A toast requires a title or content");
|
|
40
|
+
}
|
|
41
|
+
const payload = {
|
|
42
|
+
...optionalTarget(message.object, message.recordIds, recipients),
|
|
43
|
+
...recipients,
|
|
44
|
+
position: choice(message.position, "position", POSITIONS, "TOP_RIGHT"),
|
|
45
|
+
size: choice(message.size, "size", SIZES, "MEDIUM"),
|
|
46
|
+
duration: optionalInteger(message.durationSeconds, "durationSeconds", MIN_DURATION_SECONDS, MAX_DURATION_SECONDS) ?? DEFAULT_DURATION_SECONDS,
|
|
47
|
+
};
|
|
48
|
+
if (title !== undefined)
|
|
49
|
+
payload.title = title;
|
|
50
|
+
if (content !== undefined)
|
|
51
|
+
payload.content = content;
|
|
52
|
+
const links = toastLinks(message.links);
|
|
53
|
+
if (links !== undefined)
|
|
54
|
+
payload.links = links;
|
|
55
|
+
await callBridge("push.toast", payload);
|
|
56
|
+
},
|
|
57
|
+
async message(message, options) {
|
|
58
|
+
requireMessageObject(message, "push.message()");
|
|
59
|
+
const recipients = audience(options);
|
|
60
|
+
const content = optionalText(message.content, "content", MAX_MESSAGE_CONTENT_CHARS);
|
|
61
|
+
if (content === undefined)
|
|
62
|
+
throw new ValidationError("A background message requires content");
|
|
63
|
+
const payload = {
|
|
64
|
+
...optionalTarget(message.object, message.recordIds, recipients),
|
|
65
|
+
...recipients,
|
|
66
|
+
content,
|
|
67
|
+
contentType: choice(message.contentType, "contentType", CONTENT_TYPES, "text"),
|
|
68
|
+
};
|
|
69
|
+
await callBridge("push.message", payload);
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Checks the shape without narrowing the typed parameter, so property types stay those of the message. */
|
|
74
|
+
function requireMessageObject(value, method) {
|
|
75
|
+
if (!isRecord(value))
|
|
76
|
+
throw new ValidationError(`${method} requires a message object`);
|
|
77
|
+
}
|
|
78
|
+
function audience(options) {
|
|
79
|
+
if (options === undefined)
|
|
80
|
+
return { recipients: VIEWERS, exclude: [] };
|
|
81
|
+
if (!isRecord(options))
|
|
82
|
+
throw new ValidationError("push options must be an object");
|
|
83
|
+
const recipients = options.recipients;
|
|
84
|
+
let normalized;
|
|
85
|
+
if (recipients === undefined || recipients === VIEWERS) {
|
|
86
|
+
normalized = VIEWERS;
|
|
87
|
+
}
|
|
88
|
+
else if (Array.isArray(recipients)) {
|
|
89
|
+
normalized = personnelIds(recipients, "recipients", false);
|
|
90
|
+
if (normalized.length === 0)
|
|
91
|
+
throw new ValidationError("recipients must name at least one personnel ID");
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
throw new ValidationError("recipients must be \"viewers\" or a list of personnel IDs");
|
|
95
|
+
}
|
|
96
|
+
const exclude = options.exclude === undefined ? [] : personnelIds(options.exclude, "exclude", true);
|
|
97
|
+
return { recipients: normalized, exclude };
|
|
98
|
+
}
|
|
99
|
+
function personnelIds(value, label, allowActor) {
|
|
100
|
+
if (!Array.isArray(value))
|
|
101
|
+
throw new ValidationError(`${label} must be a list of personnel IDs`);
|
|
102
|
+
if (value.length > MAX_PERSONNEL) {
|
|
103
|
+
throw new ValidationError(`${label} must not list more than ${MAX_PERSONNEL} personnel IDs`);
|
|
104
|
+
}
|
|
105
|
+
const ids = new Set();
|
|
106
|
+
for (const entry of value) {
|
|
107
|
+
// "actor" is a reserved word of `exclude`, never a personnel ID.
|
|
108
|
+
const accepted = typeof entry === "string"
|
|
109
|
+
&& (entry === ACTOR ? allowActor : PERSONNEL_ID.test(entry));
|
|
110
|
+
if (!accepted) {
|
|
111
|
+
throw new ValidationError(`${label} must only contain personnel IDs${allowActor ? ` or "${ACTOR}"` : ""}`);
|
|
112
|
+
}
|
|
113
|
+
ids.add(entry);
|
|
114
|
+
}
|
|
115
|
+
return [...ids];
|
|
116
|
+
}
|
|
117
|
+
function target(object, recordIds) {
|
|
118
|
+
if (typeof object !== "string")
|
|
119
|
+
throw new ValidationError("object must be an object slug");
|
|
120
|
+
const objectSlug = requireSlug(object);
|
|
121
|
+
if (!Array.isArray(recordIds))
|
|
122
|
+
throw new ValidationError("recordIds must be a list of record IDs");
|
|
123
|
+
const ids = new Set();
|
|
124
|
+
for (const entry of recordIds) {
|
|
125
|
+
if (typeof entry !== "string" || !RECORD_ID.test(entry)) {
|
|
126
|
+
throw new ValidationError("recordIds must only contain record IDs");
|
|
127
|
+
}
|
|
128
|
+
ids.add(entry);
|
|
129
|
+
}
|
|
130
|
+
if (ids.size === 0 || ids.size > MAX_RECORDS) {
|
|
131
|
+
throw new ValidationError(`recordIds must contain 1 to ${MAX_RECORDS} record IDs`);
|
|
132
|
+
}
|
|
133
|
+
return { objectSlug, recordIds: [...ids] };
|
|
134
|
+
}
|
|
135
|
+
function optionalTarget(object, recordIds, recipients) {
|
|
136
|
+
if (object === undefined && recordIds === undefined) {
|
|
137
|
+
if (recipients.recipients === VIEWERS) {
|
|
138
|
+
throw new ValidationError("object and recordIds are required when the recipients are \"viewers\"");
|
|
139
|
+
}
|
|
140
|
+
return {};
|
|
141
|
+
}
|
|
142
|
+
return target(object, recordIds);
|
|
143
|
+
}
|
|
144
|
+
function optionalText(value, label, maximumChars) {
|
|
145
|
+
if (value === undefined || value === null)
|
|
146
|
+
return undefined;
|
|
147
|
+
if (typeof value !== "string")
|
|
148
|
+
throw new ValidationError(`${label} must be a string`);
|
|
149
|
+
if (value.trim().length === 0)
|
|
150
|
+
return undefined;
|
|
151
|
+
if (value.length > maximumChars) {
|
|
152
|
+
throw new ValidationError(`${label} must not exceed ${maximumChars} characters`);
|
|
153
|
+
}
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
function choice(value, label, allowed, fallback) {
|
|
157
|
+
if (value === undefined)
|
|
158
|
+
return fallback;
|
|
159
|
+
if (typeof value !== "string" || !allowed.has(value)) {
|
|
160
|
+
throw new ValidationError(`${label} must be one of ${[...allowed].sort().join(", ")}`);
|
|
161
|
+
}
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
function toastLinks(value) {
|
|
165
|
+
if (value === undefined)
|
|
166
|
+
return undefined;
|
|
167
|
+
if (!Array.isArray(value))
|
|
168
|
+
throw new ValidationError("links must be a list of { label, url }");
|
|
169
|
+
if (value.length === 0)
|
|
170
|
+
return undefined;
|
|
171
|
+
if (value.length > MAX_LINKS)
|
|
172
|
+
throw new ValidationError(`links must not contain more than ${MAX_LINKS} links`);
|
|
173
|
+
return value.map(entry => {
|
|
174
|
+
if (!isRecord(entry))
|
|
175
|
+
throw new ValidationError("links must be a list of { label, url }");
|
|
176
|
+
const { label, url } = entry;
|
|
177
|
+
if (typeof label !== "string" || label.trim().length === 0 || label.length > MAX_LINK_LABEL_CHARS) {
|
|
178
|
+
throw new ValidationError(`Each link label must be a string of 1 to ${MAX_LINK_LABEL_CHARS} characters`);
|
|
179
|
+
}
|
|
180
|
+
if (typeof url !== "string" || !isHttpUrl(url)) {
|
|
181
|
+
throw new ValidationError(`Each link url must be an absolute http or https URL of at most ${MAX_LINK_URL_CHARS} characters`);
|
|
182
|
+
}
|
|
183
|
+
return { label, url };
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
// The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
|
|
187
|
+
const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
|
|
188
|
+
function isHttpUrl(value) {
|
|
189
|
+
return value.length > 0 && value.length <= MAX_LINK_URL_CHARS && HTTP_URL.test(value);
|
|
190
|
+
}
|
package/dist/request.d.ts
CHANGED
|
@@ -15,4 +15,8 @@ export interface ScriptRequest<TBody = unknown> {
|
|
|
15
15
|
readonly headers: ScriptHeaders;
|
|
16
16
|
/** Business input only, without invocation metadata. */
|
|
17
17
|
readonly body: TBody;
|
|
18
|
+
/** The request body exactly as received; present for webhook calls so that signatures can be verified. */
|
|
19
|
+
readonly rawBody?: string;
|
|
20
|
+
/** The `Content-Type` of the request; present for webhook calls. */
|
|
21
|
+
readonly contentType?: string;
|
|
18
22
|
}
|