@cogover/sdk 0.7.0 → 0.9.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.
@@ -0,0 +1,143 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { deepFreeze } from "./json.js";
3
+ import { isRecord } from "./values.js";
4
+ export const JOB_KEY = /^[A-Za-z][A-Za-z0-9_]{0,99}$/;
5
+ const CONFIG_KEYS = new Set(["key", "name", "timeoutMs", "maxAttempts", "schedule"]);
6
+ const SCHEDULE_KEYS = new Set(["cron", "timezone"]);
7
+ const MAX_NAME_LENGTH = 250;
8
+ const MIN_TIMEOUT_MILLIS = 1000;
9
+ const MAX_TIMEOUT_MILLIS = 60_000;
10
+ const DEFAULT_TIMEOUT_MILLIS = 30_000;
11
+ const MIN_ATTEMPTS = 1;
12
+ const MAX_ATTEMPTS = 10;
13
+ const DEFAULT_ATTEMPTS = 5;
14
+ const MAX_TIMEZONE_LENGTH = 64;
15
+ const DEFAULT_TIMEZONE = "UTC";
16
+ // The shape of an IANA zone ID; Cogover checks that the zone exists when the version is published.
17
+ const TIMEZONE = /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)*$/;
18
+ const CRON_FIELDS = [
19
+ { name: "minute", minimum: 0, maximum: 59 },
20
+ { name: "hour", minimum: 0, maximum: 23 },
21
+ { name: "day-of-month", minimum: 1, maximum: 31 },
22
+ { name: "month", minimum: 1, maximum: 12 },
23
+ { name: "day-of-week", minimum: 0, maximum: 7 },
24
+ ];
25
+ /** Validates a defineJob() config and returns the frozen plain-JSON manifest with defaults applied. */
26
+ export function normalizeJobConfig(config) {
27
+ if (!isRecord(config)) {
28
+ throw new ValidationError("defineJob() requires a configuration object");
29
+ }
30
+ const key = config.key;
31
+ if (typeof key !== "string" || !JOB_KEY.test(key)) {
32
+ throw new ValidationError("Job key must start with a letter and contain at most 100 letters, digits or underscores");
33
+ }
34
+ const fail = (option, message) => new ValidationError(`Job '${key}': ${message}`, { jobKey: key, option });
35
+ for (const option of Object.keys(config)) {
36
+ if (!CONFIG_KEYS.has(option))
37
+ throw fail(option, `unknown config key '${option}'`);
38
+ }
39
+ let name;
40
+ if (config.name !== undefined) {
41
+ name = typeof config.name === "string" ? config.name.trim() : "";
42
+ if (name.length === 0 || name.length > MAX_NAME_LENGTH) {
43
+ throw fail("name", `name must be a non-empty string of at most ${MAX_NAME_LENGTH} characters`);
44
+ }
45
+ }
46
+ const timeoutMs = integerOption(config.timeoutMs, "timeoutMs", MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS, DEFAULT_TIMEOUT_MILLIS, fail);
47
+ const maxAttempts = integerOption(config.maxAttempts, "maxAttempts", MIN_ATTEMPTS, MAX_ATTEMPTS, DEFAULT_ATTEMPTS, fail);
48
+ let schedule;
49
+ if (config.schedule !== undefined) {
50
+ schedule = normalizeSchedule(config.schedule, fail);
51
+ }
52
+ // Key order follows the manifest contract; absent optional keys are omitted, never undefined.
53
+ const manifest = {
54
+ key,
55
+ ...(name === undefined ? {} : { name }),
56
+ timeoutMs,
57
+ maxAttempts,
58
+ ...(schedule === undefined ? {} : { schedule }),
59
+ };
60
+ return deepFreeze(manifest);
61
+ }
62
+ function normalizeSchedule(value, fail) {
63
+ if (!isRecord(value)) {
64
+ throw fail("schedule", "schedule must be an object such as { cron: \"0 2 * * *\", timezone: \"UTC\" }");
65
+ }
66
+ for (const option of Object.keys(value)) {
67
+ if (!SCHEDULE_KEYS.has(option))
68
+ throw fail("schedule", `schedule contains the unknown key '${option}'`);
69
+ }
70
+ const cron = normalizeCron(value.cron, fail);
71
+ let timezone = DEFAULT_TIMEZONE;
72
+ if (value.timezone !== undefined) {
73
+ if (typeof value.timezone !== "string" || value.timezone.length === 0
74
+ || value.timezone.length > MAX_TIMEZONE_LENGTH || !TIMEZONE.test(value.timezone)) {
75
+ throw fail("schedule", "schedule.timezone must be an IANA time zone ID of at most "
76
+ + `${MAX_TIMEZONE_LENGTH} characters, for example "Asia/Ho_Chi_Minh"`);
77
+ }
78
+ timezone = value.timezone;
79
+ }
80
+ return { cron, timezone };
81
+ }
82
+ /** Validates a five-field cron expression and returns it with single spaces between the fields. */
83
+ function normalizeCron(expression, fail) {
84
+ if (typeof expression !== "string" || expression.trim().length === 0) {
85
+ throw fail("schedule", "schedule.cron must be a string of five fields: "
86
+ + "minute hour day-of-month month day-of-week");
87
+ }
88
+ const trimmed = expression.trim();
89
+ if (trimmed.startsWith("@")) {
90
+ throw fail("schedule", `schedule.cron does not support the macro '${trimmed}'; use five fields`);
91
+ }
92
+ const fields = trimmed.split(/\s+/u);
93
+ if (fields.length !== 5) {
94
+ throw fail("schedule", `schedule.cron must contain exactly five fields, found ${fields.length}`);
95
+ }
96
+ fields.forEach((field, index) => validateCronField(field, CRON_FIELDS[index], fail));
97
+ return fields.join(" ");
98
+ }
99
+ function validateCronField(field, spec, fail) {
100
+ const unsupported = (item) => fail("schedule", `schedule.cron ${spec.name} field contains the unsupported value '${item}'; `
101
+ + `use *, a, a-b, */n or a-b/n with numbers from ${spec.minimum} to ${spec.maximum}`);
102
+ for (const item of field.split(",")) {
103
+ const parts = item.split("/");
104
+ const range = parts[0] ?? "";
105
+ const step = parts[1];
106
+ if (parts.length > 2 || range === "" || step === "")
107
+ throw unsupported(item);
108
+ if (step !== undefined) {
109
+ const stepValue = cronNumber(step);
110
+ if (stepValue === null || stepValue < 1 || stepValue > spec.maximum) {
111
+ throw fail("schedule", `schedule.cron ${spec.name} field has the invalid step '${item}'; `
112
+ + `the step must be a number from 1 to ${spec.maximum}`);
113
+ }
114
+ }
115
+ if (range === "*")
116
+ continue;
117
+ const bounds = range.split("-");
118
+ if (bounds.length > 2)
119
+ throw unsupported(item);
120
+ if (step !== undefined && bounds.length !== 2) {
121
+ throw fail("schedule", `schedule.cron ${spec.name} field has the invalid step '${item}'; `
122
+ + "a step applies to * or to a range a-b");
123
+ }
124
+ const values = bounds.map(cronNumber);
125
+ if (values.some(value => value === null || value < spec.minimum || value > spec.maximum)) {
126
+ throw unsupported(item);
127
+ }
128
+ if (values.length === 2 && values[0] > values[1]) {
129
+ throw fail("schedule", `schedule.cron ${spec.name} field has the range '${item}' whose start is after its end`);
130
+ }
131
+ }
132
+ }
133
+ function cronNumber(text) {
134
+ return /^\d{1,2}$/u.test(text) ? Number(text) : null;
135
+ }
136
+ function integerOption(value, option, minimum, maximum, fallback, fail) {
137
+ if (value === undefined)
138
+ return fallback;
139
+ if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > maximum) {
140
+ throw fail(option, `${option} must be an integer between ${minimum} and ${maximum}`);
141
+ }
142
+ return value;
143
+ }
@@ -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
+ }
@@ -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
- return Object.freeze({ method, path, params: Object.freeze({}), query, headers, body });
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,10 +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";
5
6
  import { createPushApi } from "../push.js";
6
7
  import { createSchemaApi } from "../schema.js";
8
+ import { createSecretsApi } from "../secrets.js";
7
9
  import { invocationContext } from "./invocation.js";
10
+ import { createJobsApi } from "./jobs-api.js";
8
11
  import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
9
12
  import { TRIGGER_SLUG } from "./trigger-config.js";
10
13
  import { errorMessage, isRecord } from "./values.js";
@@ -51,6 +54,10 @@ export function createTriggerSandboxHandler(manifest, handler) {
51
54
  schema: createSchemaApi(),
52
55
  log: SCRIPT_LOGGER,
53
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,
54
61
  }));
55
62
  const results = [];
56
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`);
@@ -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/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
  }
package/dist/response.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ValidationError } from "./errors.js";
2
+ import { encodeBase64 } from "./internal/base64.js";
2
3
  const RESPONSE_KEY = "__cogoverHttpResponse";
3
4
  const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
4
5
  const DENIED_HEADERS = new Set([
@@ -91,18 +92,3 @@ function normalizeHeaders(source, defaultContentType) {
91
92
  }
92
93
  return Object.freeze(normalized);
93
94
  }
94
- function encodeBase64(bytes) {
95
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
96
- let result = "";
97
- for (let index = 0; index < bytes.length; index += 3) {
98
- const first = bytes[index] ?? 0;
99
- const second = bytes[index + 1] ?? 0;
100
- const third = bytes[index + 2] ?? 0;
101
- const value = (first << 16) | (second << 8) | third;
102
- result += alphabet.charAt((value >>> 18) & 63)
103
- + alphabet.charAt((value >>> 12) & 63)
104
- + (index + 1 < bytes.length ? alphabet.charAt((value >>> 6) & 63) : "=")
105
- + (index + 2 < bytes.length ? alphabet.charAt(value & 63) : "=");
106
- }
107
- return result;
108
- }
package/dist/router.js CHANGED
@@ -60,6 +60,9 @@ export function createRouter() {
60
60
  state: context.state,
61
61
  locks: context.locks,
62
62
  push: context.push,
63
+ jobs: context.jobs,
64
+ secrets: context.secrets,
65
+ crypto: context.crypto,
63
66
  });
64
67
  });
65
68
  },
package/dist/script.d.ts CHANGED
@@ -8,6 +8,9 @@ import type { ProjectState } from "./state.js";
8
8
  import type { DistributedLocks } from "./locks.js";
9
9
  import type { PushApi } from "./push.js";
10
10
  import type { InvocationContext } from "./invocation.js";
11
+ import type { JobsApi } from "./jobs.js";
12
+ import type { SecretsApi } from "./secrets.js";
13
+ import type { CryptoApi } from "./crypto.js";
11
14
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
12
15
  readonly input: TInput;
13
16
  readonly request: ScriptRequest<TInput>;
@@ -19,6 +22,9 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
19
22
  readonly state: ProjectState;
20
23
  readonly locks: DistributedLocks;
21
24
  readonly push: PushApi<TSchema>;
25
+ readonly jobs: JobsApi;
26
+ readonly secrets: SecretsApi;
27
+ readonly crypto: CryptoApi;
22
28
  }
23
29
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
24
30
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -10,6 +10,9 @@ import { createLocksApi } from "./locks.js";
10
10
  import { createPushApi } from "./push.js";
11
11
  import { installCogoverFetch } from "./fetch.js";
12
12
  import { invocationContext } from "./internal/invocation.js";
13
+ import { createJobsApi } from "./internal/jobs-api.js";
14
+ import { createSecretsApi } from "./secrets.js";
15
+ import { crypto } from "./crypto.js";
13
16
  export function defineScript(handler) {
14
17
  if (typeof handler !== "function") {
15
18
  throw new ValidationError("defineScript() requires a handler function");
@@ -45,6 +48,9 @@ export function createSandboxHandler(handler) {
45
48
  state: createStateApi(),
46
49
  locks: createLocksApi(),
47
50
  push: createPushApi(),
51
+ jobs: createJobsApi(),
52
+ secrets: createSecretsApi(),
53
+ crypto,
48
54
  });
49
55
  if (output === null) {
50
56
  return null;
@@ -0,0 +1,8 @@
1
+ /** Reads the secrets that an administrator stored for the project. */
2
+ export interface SecretsApi {
3
+ /**
4
+ * Returns the current value of a secret. Credentials that `fetch` sends on the project's behalf
5
+ * cannot be read; reference them with `fetch(url, { credential })` instead.
6
+ */
7
+ get(name: string): Promise<string>;
8
+ }