@cogover/sdk 0.7.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 +100 -4
- 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 +6 -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 +7 -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/request.d.ts +4 -0
- package/dist/response.js +1 -15
- package/dist/router.js +3 -0
- package/dist/script.d.ts +6 -0
- package/dist/script.js +6 -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 +8 -0
- package/docs/en/api-reference.md +520 -27
- package/docs/en/usage-guide.md +201 -4
- package/package.json +1 -1
|
@@ -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,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`);
|
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/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
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
|
+
}
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { CogoverApiError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { requireSecretName } from "./internal/validation.js";
|
|
4
|
+
import { isRecord } from "./internal/values.js";
|
|
5
|
+
/** @internal */
|
|
6
|
+
export function createSecretsApi() {
|
|
7
|
+
return Object.freeze({
|
|
8
|
+
async get(name) {
|
|
9
|
+
const secretName = requireSecretName(name, "secrets.get() name");
|
|
10
|
+
const secret = await callBridge("secrets.get", { name: secretName });
|
|
11
|
+
if (!isRecord(secret) || typeof secret.value !== "string") {
|
|
12
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", `Secret '${secretName}' has no value`);
|
|
13
|
+
}
|
|
14
|
+
return secret.value;
|
|
15
|
+
},
|
|
16
|
+
});
|
|
17
|
+
}
|
package/dist/state.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { callBridge } from "./internal/bridge.js";
|
|
2
|
+
import { utf8ByteLength } from "./internal/utf8.js";
|
|
2
3
|
import { ValidationError } from "./errors.js";
|
|
3
4
|
const NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
|
|
4
5
|
const MAX_NAMESPACE_LENGTH = 128;
|
|
@@ -51,7 +52,7 @@ function validateValue(value) {
|
|
|
51
52
|
}
|
|
52
53
|
if (serialized === undefined)
|
|
53
54
|
throw new ValidationError("state value must be JSON serializable");
|
|
54
|
-
if (
|
|
55
|
+
if (utf8ByteLength(serialized) > MAX_VALUE_BYTES) {
|
|
55
56
|
throw new ValidationError(`state value must not exceed ${MAX_VALUE_BYTES} UTF-8 bytes`);
|
|
56
57
|
}
|
|
57
58
|
}
|
|
@@ -71,21 +72,3 @@ export function optionalInteger(value, label, minimum, maximum) {
|
|
|
71
72
|
}
|
|
72
73
|
return value;
|
|
73
74
|
}
|
|
74
|
-
function utf8Bytes(value) {
|
|
75
|
-
let bytes = 0;
|
|
76
|
-
for (let index = 0; index < value.length; index++) {
|
|
77
|
-
const code = value.charCodeAt(index);
|
|
78
|
-
if (code < 0x80)
|
|
79
|
-
bytes++;
|
|
80
|
-
else if (code < 0x800)
|
|
81
|
-
bytes += 2;
|
|
82
|
-
else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length
|
|
83
|
-
&& value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) {
|
|
84
|
-
bytes += 4;
|
|
85
|
-
index++;
|
|
86
|
-
}
|
|
87
|
-
else
|
|
88
|
-
bytes += 3;
|
|
89
|
-
}
|
|
90
|
-
return bytes;
|
|
91
|
-
}
|
package/dist/trigger.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import type { CryptoApi } from "./crypto.js";
|
|
1
2
|
import type { DataApi } from "./data.js";
|
|
3
|
+
import type { JobsApi } from "./jobs.js";
|
|
4
|
+
import type { SecretsApi } from "./secrets.js";
|
|
2
5
|
import type { InvocationContext } from "./invocation.js";
|
|
3
6
|
import type { ScriptLogger } from "./logger.js";
|
|
4
7
|
import type { PushApi } from "./push.js";
|
|
@@ -117,6 +120,11 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
|
|
|
117
120
|
readonly log: ScriptLogger;
|
|
118
121
|
/** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
|
|
119
122
|
readonly push: PushApi<TSchema>;
|
|
123
|
+
/** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
|
|
124
|
+
readonly jobs: JobsApi;
|
|
125
|
+
/** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
|
|
126
|
+
readonly secrets: SecretsApi;
|
|
127
|
+
readonly crypto: CryptoApi;
|
|
120
128
|
}
|
|
121
129
|
export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
|
|
122
130
|
/** Declares a record trigger. Add the result to the project's `triggers` export. */
|