@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
package/docs/en/api-reference.md
CHANGED
|
@@ -8,8 +8,8 @@ configured for the project.
|
|
|
8
8
|
## `defineScript`
|
|
9
9
|
|
|
10
10
|
`defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
|
|
11
|
-
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`,
|
|
12
|
-
and serializes its result.
|
|
11
|
+
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
|
|
12
|
+
`push`, `jobs`, `secrets`, and `crypto`, awaits the handler, and serializes its result.
|
|
13
13
|
|
|
14
14
|
```typescript
|
|
15
15
|
function defineScript<
|
|
@@ -39,6 +39,10 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
|
|
|
39
39
|
readonly response: ResponseApi;
|
|
40
40
|
readonly state: ProjectState;
|
|
41
41
|
readonly locks: DistributedLocks;
|
|
42
|
+
readonly push: PushApi<Schema>;
|
|
43
|
+
readonly jobs: JobsApi;
|
|
44
|
+
readonly secrets: SecretsApi;
|
|
45
|
+
readonly crypto: CryptoApi;
|
|
42
46
|
}
|
|
43
47
|
```
|
|
44
48
|
|
|
@@ -49,9 +53,9 @@ Returning `null` produces a null handler result; returning `undefined` is invali
|
|
|
49
53
|
## HTTP routers and request context
|
|
50
54
|
|
|
51
55
|
`ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
|
|
52
|
-
`log`, `state`, and `
|
|
53
|
-
input. Prefer `request.body` for business data: it excludes invocation
|
|
54
|
-
transport/authentication fields removed by Cogover.
|
|
56
|
+
`log`, `state`, `locks`, `push`, `jobs`, `secrets`, and `crypto` to both script and route handlers. `input`
|
|
57
|
+
preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
|
|
58
|
+
metadata and transport/authentication fields removed by Cogover.
|
|
55
59
|
|
|
56
60
|
```typescript
|
|
57
61
|
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
@@ -66,6 +70,8 @@ interface ScriptRequest<TBody = unknown> {
|
|
|
66
70
|
readonly query: ScriptQuery;
|
|
67
71
|
readonly headers: ScriptHeaders;
|
|
68
72
|
readonly body: TBody;
|
|
73
|
+
readonly rawBody?: string; // Webhook calls only
|
|
74
|
+
readonly contentType?: string; // Webhook calls only
|
|
69
75
|
}
|
|
70
76
|
```
|
|
71
77
|
|
|
@@ -76,6 +82,11 @@ credentials such as `authorization` and `cookie` are never exposed. Dynamic path
|
|
|
76
82
|
parameters are percent-decoded after safe route matching. TypeScript types do not
|
|
77
83
|
validate runtime business input.
|
|
78
84
|
|
|
85
|
+
`rawBody` and `contentType` are present only for a call that reached the project
|
|
86
|
+
through an inbound webhook (see [Inbound webhooks](#inbound-webhooks)): `rawBody`
|
|
87
|
+
is the request body exactly as received, as a UTF-8 string, and `contentType` is
|
|
88
|
+
the request's `Content-Type` header. For every other call both fields are absent.
|
|
89
|
+
|
|
79
90
|
## Invocation identity and workspace
|
|
80
91
|
|
|
81
92
|
`context.invocation` is a synchronous, immutable snapshot built from metadata that
|
|
@@ -83,7 +94,7 @@ Cogover already authenticated and loaded for the current execution. Reading it
|
|
|
83
94
|
does not make a data API request.
|
|
84
95
|
|
|
85
96
|
```typescript
|
|
86
|
-
type InvocationContext = UserInvocationContext | SystemInvocationContext;
|
|
97
|
+
type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
|
|
87
98
|
|
|
88
99
|
interface CurrentWorkspace {
|
|
89
100
|
readonly id: string;
|
|
@@ -124,16 +135,36 @@ interface SystemInvocationContext {
|
|
|
124
135
|
readonly workspace: CurrentWorkspace;
|
|
125
136
|
readonly user: null;
|
|
126
137
|
}
|
|
138
|
+
|
|
139
|
+
interface InboundInvocationContext {
|
|
140
|
+
readonly identity: "inbound";
|
|
141
|
+
readonly workspace: CurrentWorkspace;
|
|
142
|
+
readonly user: null;
|
|
143
|
+
readonly inbound: {
|
|
144
|
+
readonly id: string; // Part of the webhook URL
|
|
145
|
+
readonly name: string;
|
|
146
|
+
readonly mode: "KEY" | "HMAC"; // How the call was authenticated
|
|
147
|
+
};
|
|
148
|
+
}
|
|
127
149
|
```
|
|
128
150
|
|
|
129
151
|
All fields are readonly. Optional profile and workspace fields may be absent, so
|
|
130
152
|
scripts must not assume that they contain a value.
|
|
131
153
|
|
|
154
|
+
`identity` is `"user"` for a call made by an authenticated Workspace user,
|
|
155
|
+
`"system"` for an execution without a user, such as a scheduled job, and
|
|
156
|
+
`"inbound"` for a webhook call authenticated by one of the project's inbound
|
|
157
|
+
accesses (see [Inbound webhooks](#inbound-webhooks)). An inbound invocation has no
|
|
158
|
+
user; `inbound` identifies the inbound access that authenticated the call.
|
|
159
|
+
|
|
132
160
|
```typescript
|
|
133
161
|
export default defineScript(({ invocation }) => {
|
|
134
162
|
if (invocation.identity === "system") {
|
|
135
163
|
return {workspaceId: invocation.workspace.id, user: null};
|
|
136
164
|
}
|
|
165
|
+
if (invocation.identity === "inbound") {
|
|
166
|
+
return {workspaceId: invocation.workspace.id, inbound: invocation.inbound.name};
|
|
167
|
+
}
|
|
137
168
|
return {
|
|
138
169
|
workspaceId: invocation.workspace.id,
|
|
139
170
|
accountId: invocation.user.accountId,
|
|
@@ -143,9 +174,9 @@ export default defineScript(({ invocation }) => {
|
|
|
143
174
|
```
|
|
144
175
|
|
|
145
176
|
Cogover ignores caller-supplied invocation metadata and creates this snapshot from
|
|
146
|
-
the authenticated request context. Raw authentication data, tokens,
|
|
147
|
-
are not included. A handler called outside Cogover has no
|
|
148
|
-
snapshot.
|
|
177
|
+
the authenticated request context. Raw authentication data, tokens, inbound keys,
|
|
178
|
+
and credentials are not included. A handler called outside Cogover has no
|
|
179
|
+
authenticated invocation snapshot.
|
|
149
180
|
|
|
150
181
|
### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
|
|
151
182
|
|
|
@@ -466,6 +497,10 @@ interface TriggerContext<
|
|
|
466
497
|
readonly data: DataApi<Schema>;
|
|
467
498
|
readonly schema: SchemaApi<Schema>;
|
|
468
499
|
readonly log: ScriptLogger;
|
|
500
|
+
readonly push: PushApi<Schema>;
|
|
501
|
+
readonly jobs: JobsApi;
|
|
502
|
+
readonly secrets: SecretsApi;
|
|
503
|
+
readonly crypto: CryptoApi;
|
|
469
504
|
}
|
|
470
505
|
|
|
471
506
|
interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
|
|
@@ -501,11 +536,11 @@ receives all records of the same change that run the trigger, up to 200 records
|
|
|
501
536
|
once per record. Keep `fields` short, and read related data for the whole list with
|
|
502
537
|
one `records.getMany` call rather than one read per record.
|
|
503
538
|
|
|
504
|
-
`data`, `schema`, `log`,
|
|
505
|
-
trigger context has no `input`, `request`, `response`,
|
|
506
|
-
`
|
|
507
|
-
|
|
508
|
-
the call.
|
|
539
|
+
`data`, `schema`, `log`, `invocation`, `push`, `jobs`, `secrets`, and `crypto` are the
|
|
540
|
+
same APIs that scripts receive. A trigger context has no `input`, `request`, `response`,
|
|
541
|
+
`state`, or `locks`; `push` is refused in a before-change trigger. `trigger.operation` is
|
|
542
|
+
the operation of the current call, `trigger.id` identifies the trigger registration, and
|
|
543
|
+
`trigger.changeId` identifies the record change that caused the call.
|
|
509
544
|
|
|
510
545
|
Each `TriggerRecord` describes one record:
|
|
511
546
|
|
|
@@ -582,9 +617,12 @@ merges, and cascading deletes — do not run before-change triggers, and neither
|
|
|
582
617
|
a request that only validates input without saving.
|
|
583
618
|
|
|
584
619
|
- **Read-only.** A before-change trigger may read records and schema, but every
|
|
585
|
-
record write, `fetch`, lock,
|
|
620
|
+
record write, `fetch`, lock, state write, push message, `jobs.enqueue`, `secrets.get`,
|
|
621
|
+
and `crypto.hmacSha256` with a `{ secret }` key is refused with
|
|
586
622
|
`PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
|
|
587
|
-
applies to every identity, including `data.asSystem()`.
|
|
623
|
+
applies to every identity, including `data.asSystem()`. `crypto.sha256`,
|
|
624
|
+
`crypto.hmacSha256` with an explicit key, `crypto.randomBytes`,
|
|
625
|
+
`crypto.randomUUID`, and `crypto.timingSafeEqual` remain available.
|
|
588
626
|
- **Identity.** `data.object()` acts as the user who made the change, with that
|
|
589
627
|
user's permissions, and `invocation` describes the same user. When a change has
|
|
590
628
|
no user, `invocation.identity` is `"system"` and `data.object()` works only if the
|
|
@@ -646,10 +684,13 @@ export const triggers = [
|
|
|
646
684
|
were saved, including the record ID and values assigned while saving, such as an
|
|
647
685
|
auto number. For a deleted record `record.new` is `null` and `record.old` holds the
|
|
648
686
|
last values.
|
|
649
|
-
- **May write and call out.** Record writes
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
context has no `state` or `locks
|
|
687
|
+
- **May write and call out.** Record writes, `fetch`, `push`, `jobs.enqueue`,
|
|
688
|
+
`secrets.get`, and `crypto` work as they do in a script, within the same runtime
|
|
689
|
+
limits. `data.object()` acts as the user who made the change, and the other identity
|
|
690
|
+
rules of before-change triggers apply. The trigger context has no `state` or `locks`;
|
|
691
|
+
`push` is the usual way to refresh the records the handler changed for everyone who
|
|
692
|
+
has them open, and longer work, or work that needs `state` or `locks`, belongs in a
|
|
693
|
+
[background job](#background-jobs).
|
|
653
694
|
- **Best-effort delivery.** Cogover does not guarantee that an after-change handler
|
|
654
695
|
runs exactly once. It may occasionally run more than once for the same change, or
|
|
655
696
|
not at all. Make every handler idempotent: `trigger.changeId` together with
|
|
@@ -675,6 +716,279 @@ export const triggers = [
|
|
|
675
716
|
order. A retried call may run after a later change of the same record has already
|
|
676
717
|
been processed, so read the current record when the latest values matter.
|
|
677
718
|
|
|
719
|
+
## Background jobs
|
|
720
|
+
|
|
721
|
+
A background job runs project code outside an HTTP request: enqueued by a script, a
|
|
722
|
+
trigger, another job, or an administrator, or started by a cron schedule. Declare
|
|
723
|
+
each job with `defineJob` and list the results in the project's named `jobs`
|
|
724
|
+
export. The default export is still the HTTP handler and is optional in a project
|
|
725
|
+
that only declares jobs and triggers.
|
|
726
|
+
|
|
727
|
+
This example assumes that `workspace.d.ts` declares the `order` Object and the
|
|
728
|
+
fields used below.
|
|
729
|
+
|
|
730
|
+
```typescript
|
|
731
|
+
import { defineJob } from "@cogover/sdk";
|
|
732
|
+
|
|
733
|
+
interface RecalcPayload {
|
|
734
|
+
cursor?: string;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export const jobs = [
|
|
738
|
+
// Enqueued by a route or a trigger; walks all orders one page per run.
|
|
739
|
+
defineJob<RecalcPayload>({
|
|
740
|
+
key: "recalc_totals",
|
|
741
|
+
name: "Recalculate order totals",
|
|
742
|
+
timeoutMs: 60_000,
|
|
743
|
+
}, async ({ payload, data, jobs, log }) => {
|
|
744
|
+
const orders = data.object("order");
|
|
745
|
+
const page = await orders.records.list({
|
|
746
|
+
fields: ["subtotal", "tax"],
|
|
747
|
+
limit: 200,
|
|
748
|
+
...(payload?.cursor ? { cursor: payload.cursor } : {}),
|
|
749
|
+
});
|
|
750
|
+
for (const order of page.items) {
|
|
751
|
+
await orders.records.update(order.id, {
|
|
752
|
+
total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
if (page.nextCursor) {
|
|
756
|
+
// Continue with the next page in a new run instead of one long run.
|
|
757
|
+
await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
log.info("Order totals recalculated");
|
|
761
|
+
}),
|
|
762
|
+
|
|
763
|
+
// Runs every day at 02:00 in the given time zone.
|
|
764
|
+
defineJob({
|
|
765
|
+
key: "cancel_stale_orders",
|
|
766
|
+
schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
|
|
767
|
+
}, async ({ data }) => {
|
|
768
|
+
const orders = data.object("order");
|
|
769
|
+
const stale = await orders.records.list({
|
|
770
|
+
where: orders.fields.status.eq("new"),
|
|
771
|
+
fields: ["status"],
|
|
772
|
+
limit: 200,
|
|
773
|
+
});
|
|
774
|
+
for (const order of stale.items) {
|
|
775
|
+
await orders.records.update(order.id, { status: "cancelled" });
|
|
776
|
+
}
|
|
777
|
+
}),
|
|
778
|
+
];
|
|
779
|
+
```
|
|
780
|
+
|
|
781
|
+
Cogover reads the job configuration when a project version is published and applies
|
|
782
|
+
it while that version is active: `jobs.enqueue` accepts only the keys declared by the
|
|
783
|
+
active version, and schedules run only while their version is active. Deactivating
|
|
784
|
+
the project removes its schedules. A project can declare at most 50 jobs.
|
|
785
|
+
|
|
786
|
+
### `defineJob(config, handler): JobDefinition`
|
|
787
|
+
|
|
788
|
+
```typescript
|
|
789
|
+
function defineJob<
|
|
790
|
+
Payload = unknown,
|
|
791
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
792
|
+
>(config: JobConfig, handler: JobHandler<Payload, Schema>): JobDefinition;
|
|
793
|
+
```
|
|
794
|
+
|
|
795
|
+
`Payload` is the type of the value passed to `jobs.enqueue`; it is not validated at
|
|
796
|
+
run time, so treat the payload like request input. `defineJob` validates the
|
|
797
|
+
configuration immediately and throws `ValidationError` for any violation, for an
|
|
798
|
+
unknown configuration key, or for a handler that is not a function. It returns a
|
|
799
|
+
frozen `JobDefinition`.
|
|
800
|
+
|
|
801
|
+
```typescript
|
|
802
|
+
interface JobConfig {
|
|
803
|
+
readonly key: string;
|
|
804
|
+
readonly name?: string;
|
|
805
|
+
readonly timeoutMs?: number;
|
|
806
|
+
readonly maxAttempts?: number;
|
|
807
|
+
readonly schedule?: JobSchedule;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
interface JobSchedule {
|
|
811
|
+
readonly cron: string;
|
|
812
|
+
readonly timezone?: string;
|
|
813
|
+
}
|
|
814
|
+
```
|
|
815
|
+
|
|
816
|
+
| Option | Required | Rules and meaning |
|
|
817
|
+
|---|---|---|
|
|
818
|
+
| `key` | Yes | Identifies the job inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters; unique in the project regardless of case. Keep it stable between versions: a new key is a different job. |
|
|
819
|
+
| `name` | No | Display name of at most 250 characters. Defaults to `key`. |
|
|
820
|
+
| `timeoutMs` | No | Integer from 1000 through 60000; defaults to `30000`. Time budget of one attempt. |
|
|
821
|
+
| `maxAttempts` | No | Integer from 1 through 10; defaults to `5`. Total number of attempts of one run, including the first. |
|
|
822
|
+
| `schedule` | No | Runs the job automatically. `cron` has five fields — minute, hour, day-of-month, month, day-of-week — and `timezone` is an IANA time zone ID of at most 64 characters, defaulting to `"UTC"`. |
|
|
823
|
+
|
|
824
|
+
A cron field is `*`, a number, a range `a-b`, a list `a,b`, a step `*/n`, or a
|
|
825
|
+
stepped range `a-b/n`; the fields accept minutes 0–59, hours 0–23, days 1–31,
|
|
826
|
+
months 1–12, and weekdays 0–7 where both 0 and 7 are Sunday. Names such as `MON`,
|
|
827
|
+
the characters `L`, `W`, `#`, and `?`, and macros such as `@daily` are not supported.
|
|
828
|
+
The shortest period is one minute. Whitespace between the fields is normalized to
|
|
829
|
+
one space in the manifest.
|
|
830
|
+
|
|
831
|
+
### `JobDefinition` and `JobManifest`
|
|
832
|
+
|
|
833
|
+
```typescript
|
|
834
|
+
interface JobManifest {
|
|
835
|
+
readonly key: string;
|
|
836
|
+
readonly name?: string;
|
|
837
|
+
readonly timeoutMs: number;
|
|
838
|
+
readonly maxAttempts: number;
|
|
839
|
+
readonly schedule?: { readonly cron: string; readonly timezone: string };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
interface JobDefinition {
|
|
843
|
+
readonly key: string;
|
|
844
|
+
readonly config: JobManifest;
|
|
845
|
+
readonly __cogoverJobHandler: SandboxHandler;
|
|
846
|
+
}
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
`config` is the normalized configuration as deeply frozen plain JSON, with every
|
|
850
|
+
default applied: `timeoutMs: 30000`, `maxAttempts: 5`, and `schedule.timezone:
|
|
851
|
+
"UTC"`. Optional settings that were not provided are absent. It is detached from the
|
|
852
|
+
object passed to `defineJob`, so later edits of that object have no effect.
|
|
853
|
+
`__cogoverJobHandler` is reserved for Cogover; project code does not call it.
|
|
854
|
+
|
|
855
|
+
### Job handler context
|
|
856
|
+
|
|
857
|
+
```typescript
|
|
858
|
+
type JobHandler<
|
|
859
|
+
Payload = unknown,
|
|
860
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
861
|
+
> = (context: JobContext<Payload, Schema>) => void | Promise<void>;
|
|
862
|
+
|
|
863
|
+
interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspaceObjects> {
|
|
864
|
+
readonly job: JobInfo;
|
|
865
|
+
readonly payload: Payload | null;
|
|
866
|
+
readonly invocation: InvocationContext;
|
|
867
|
+
readonly data: DataApi<Schema>;
|
|
868
|
+
readonly schema: SchemaApi<Schema>;
|
|
869
|
+
readonly log: ScriptLogger;
|
|
870
|
+
readonly state: ProjectState;
|
|
871
|
+
readonly locks: DistributedLocks;
|
|
872
|
+
readonly jobs: JobsApi;
|
|
873
|
+
readonly secrets: SecretsApi;
|
|
874
|
+
readonly crypto: CryptoApi;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
interface JobInfo {
|
|
878
|
+
readonly id: string;
|
|
879
|
+
readonly key: string;
|
|
880
|
+
readonly attempt: number;
|
|
881
|
+
readonly maxAttempts: number;
|
|
882
|
+
readonly source: "enqueue" | "schedule";
|
|
883
|
+
readonly runAt: number;
|
|
884
|
+
readonly enqueuedAt?: number;
|
|
885
|
+
}
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
A handler may be synchronous or asynchronous; its return value is ignored. `data`,
|
|
889
|
+
`schema`, `log`, `invocation`, `state`, `locks`, `jobs`, `secrets`, and `crypto`
|
|
890
|
+
are the same APIs that scripts receive. A job context has no `input`, `request`, or
|
|
891
|
+
`response`.
|
|
892
|
+
|
|
893
|
+
- `job.id` identifies the run and stays the same across its attempts; use it as the
|
|
894
|
+
idempotency key of external calls. `job.attempt` starts at 1.
|
|
895
|
+
- `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
|
|
896
|
+
administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
|
|
897
|
+
is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
|
|
898
|
+
milliseconds, and `enqueuedAt` is absent for a scheduled run.
|
|
899
|
+
- `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
|
|
900
|
+
passed or the run is scheduled. It is plain, mutable data.
|
|
901
|
+
|
|
902
|
+
### `jobs.enqueue(jobKey, payload?, options?): Promise<EnqueueResult>`
|
|
903
|
+
|
|
904
|
+
```typescript
|
|
905
|
+
interface JobsApi {
|
|
906
|
+
enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
interface EnqueueOptions {
|
|
910
|
+
readonly delayMs?: number;
|
|
911
|
+
readonly runAt?: number;
|
|
912
|
+
readonly idempotencyKey?: string;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
interface EnqueueResult {
|
|
916
|
+
readonly runId: string;
|
|
917
|
+
readonly duplicate: boolean;
|
|
918
|
+
}
|
|
919
|
+
```
|
|
920
|
+
|
|
921
|
+
```typescript
|
|
922
|
+
const { runId, duplicate } = await jobs.enqueue("sync_order", { orderId: order.id }, {
|
|
923
|
+
delayMs: 60_000,
|
|
924
|
+
idempotencyKey: `sync_order:${order.id}:${order.system.updatedAt}`,
|
|
925
|
+
});
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
`jobKey` must be a job declared by the active version; otherwise Cogover throws
|
|
929
|
+
`ValidationError`. `payload` is any JSON value of at most 65,536 UTF-8 bytes after
|
|
930
|
+
serialization; `undefined` and `null` enqueue the run without a payload. Values that
|
|
931
|
+
JSON would silently change, such as `NaN` or class instances, are rejected with
|
|
932
|
+
`ValidationError`. `delayMs` is an integer from 0 through 2,592,000,000 (30 days)
|
|
933
|
+
and `runAt` a Unix millisecond time at most 30 days ahead; pass one or neither, not
|
|
934
|
+
both. `idempotencyKey` starts with a letter or digit, contains letters, digits, `.`,
|
|
935
|
+
`_`, `:`, or `-`, and is at most 128 characters: a second enqueue of the same job
|
|
936
|
+
with the same key while the earlier run is still kept returns that run with
|
|
937
|
+
`duplicate: true` instead of creating another. Run history is kept for 7 days.
|
|
938
|
+
|
|
939
|
+
`enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
|
|
940
|
+
webhook calls. A before-change trigger is refused with `PermissionDeniedError`
|
|
941
|
+
(`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
|
|
942
|
+
without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
|
|
943
|
+
enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
|
|
944
|
+
running; beyond that `RateLimitError` is thrown. When jobs are not enabled for the
|
|
945
|
+
Workspace, the error is `CogoverApiError` with `code: "JOBS_DISABLED"`.
|
|
946
|
+
|
|
947
|
+
### Job execution rules
|
|
948
|
+
|
|
949
|
+
- **Identity.** A run enqueued from a script, route, or trigger runs as the user of
|
|
950
|
+
that invocation: `invocation` describes that user and `data.object()` acts with
|
|
951
|
+
that user's permissions. A scheduled run, a run enqueued by an administrator, and
|
|
952
|
+
a run enqueued from an inbound webhook call have no user: `invocation.identity`
|
|
953
|
+
is `"system"`, and `data.object()` works only if the project's approved identity
|
|
954
|
+
policy sets `allowInternalSystem: true`; otherwise its calls throw
|
|
955
|
+
`PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
|
|
956
|
+
`data.asUser()` and `data.asSystem()` follow the identity policy as usual.
|
|
957
|
+
- **Capabilities.** A job may do everything a script can: read and write records,
|
|
958
|
+
call `fetch`, use `state` and `locks`, enqueue jobs, read secrets, and use
|
|
959
|
+
`crypto`, within the runtime limits of the job lane.
|
|
960
|
+
- **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
|
|
961
|
+
split: process one page, save the cursor, and enqueue the same job again with the
|
|
962
|
+
cursor in the payload, as in the example above.
|
|
963
|
+
- **At least once.** Cogover does not guarantee that a run executes exactly once: an
|
|
964
|
+
attempt that was interrupted, for example by a restart, is started again. Make
|
|
965
|
+
every handler idempotent. `job.id` identifies the run across attempts, and
|
|
966
|
+
`idempotencyKey` on `enqueue` prevents duplicate runs.
|
|
967
|
+
- **Retries.** Throw `RetryableError` when the handler fails for a temporary reason,
|
|
968
|
+
such as an external service that is unavailable. Cogover runs the attempt again
|
|
969
|
+
later, waiting longer before each attempt, from a few seconds to about half an
|
|
970
|
+
hour, until `maxAttempts` attempts have been made. An attempt that exceeds
|
|
971
|
+
`timeoutMs`, or that Cogover could not run for a temporary reason, is retried the
|
|
972
|
+
same way. Any other error ends the run as failed: the failure is logged and the
|
|
973
|
+
handler does not run again for that run.
|
|
974
|
+
- **Order and concurrency.** Runs execute in no guaranteed order, and two runs of the
|
|
975
|
+
same project, even of the same job, may execute at the same time. Use `locks` when
|
|
976
|
+
a section must not run concurrently, and delay through `delayMs` or `runAt` rather
|
|
977
|
+
than by waiting inside the handler.
|
|
978
|
+
- **Loops end.** Record writes made by a run carry the automation budget of the
|
|
979
|
+
invocation that enqueued it (a scheduled run and an administrator's enqueue start
|
|
980
|
+
with the full budget of 10 steps), so a chain of jobs and triggers started by
|
|
981
|
+
record writes ends the same way as a trigger chain. Enqueueing a job does not use
|
|
982
|
+
a step: a job that enqueues itself must stop on its own, for example when the
|
|
983
|
+
cursor is exhausted.
|
|
984
|
+
|
|
985
|
+
A scheduled job creates one run for each time the schedule matches, in the
|
|
986
|
+
schedule's time zone; the run may start a little later than the scheduled minute
|
|
987
|
+
under load. A slot that is missed while the project is inactive is not run later.
|
|
988
|
+
A run is still created when the previous scheduled run has not finished, so a
|
|
989
|
+
schedule whose work can take longer than its period should guard itself with a
|
|
990
|
+
lock.
|
|
991
|
+
|
|
678
992
|
## Outbound HTTP `fetch`
|
|
679
993
|
|
|
680
994
|
```typescript
|
|
@@ -685,6 +999,7 @@ interface CogoverFetchInit {
|
|
|
685
999
|
readonly headers?: Readonly<Record<string, string>>;
|
|
686
1000
|
readonly body?: string;
|
|
687
1001
|
readonly timeoutMs?: number;
|
|
1002
|
+
readonly credential?: string;
|
|
688
1003
|
}
|
|
689
1004
|
|
|
690
1005
|
interface CogoverFetchHeaders {
|
|
@@ -745,6 +1060,182 @@ Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
|
|
|
745
1060
|
times out or loses its response, the remote server may already have applied the
|
|
746
1061
|
request. Use the remote API's idempotency mechanism and never retry blindly.
|
|
747
1062
|
|
|
1063
|
+
### Authenticating with a credential
|
|
1064
|
+
|
|
1065
|
+
`credential` names a credential that an administrator stored for the project (see
|
|
1066
|
+
[Secrets and credentials](#secrets-and-credentials)). Cogover adds the credential's
|
|
1067
|
+
authentication header to the request, so project code never handles the value:
|
|
1068
|
+
|
|
1069
|
+
```typescript
|
|
1070
|
+
const response = await fetch("https://erp.example.com/v1/orders", {
|
|
1071
|
+
method: "POST",
|
|
1072
|
+
credential: "erp_api",
|
|
1073
|
+
headers: { "content-type": "application/json" },
|
|
1074
|
+
body: JSON.stringify({ id: "ORD-1" }),
|
|
1075
|
+
});
|
|
1076
|
+
```
|
|
1077
|
+
|
|
1078
|
+
Depending on how the credential was created, Cogover sends `Authorization: Bearer
|
|
1079
|
+
<value>`, `Authorization: Basic <base64 of value>`, or a header with the configured
|
|
1080
|
+
name. The name must start with a letter and contain at most 64 letters, digits, or
|
|
1081
|
+
underscores. A credential can only be sent to the hosts its administrator allowed;
|
|
1082
|
+
a request to another host, a request that sets the same header itself, or a name
|
|
1083
|
+
that is not an active credential fails with `FETCH_BLOCKED`. Redirects are never
|
|
1084
|
+
followed, so a credential never leaves an allowed host.
|
|
1085
|
+
|
|
1086
|
+
## Secrets and credentials
|
|
1087
|
+
|
|
1088
|
+
An administrator stores secrets for a project through the Cogover management API.
|
|
1089
|
+
Each one is either a **secret**, whose value code reads with `secrets.get`, or a
|
|
1090
|
+
**credential**, which only `fetch` uses (see
|
|
1091
|
+
[Authenticating with a credential](#authenticating-with-a-credential)); the value
|
|
1092
|
+
of a credential is never readable by code. Values are stored encrypted and are
|
|
1093
|
+
never returned by the management API, logged, or included in error messages.
|
|
1094
|
+
|
|
1095
|
+
```typescript
|
|
1096
|
+
interface SecretsApi {
|
|
1097
|
+
get(name: string): Promise<string>;
|
|
1098
|
+
}
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
```typescript
|
|
1102
|
+
const token = await secrets.get("erp_token");
|
|
1103
|
+
const response = await fetch("https://erp.example.com/v1/orders", {
|
|
1104
|
+
headers: { authorization: `Bearer ${token}` },
|
|
1105
|
+
});
|
|
1106
|
+
```
|
|
1107
|
+
|
|
1108
|
+
### `secrets.get(name): Promise<string>`
|
|
1109
|
+
|
|
1110
|
+
Returns the current value of the secret. `name` starts with a letter and contains
|
|
1111
|
+
at most 64 letters, digits, or underscores; other names throw `ValidationError`
|
|
1112
|
+
before the call. A secret that does not exist or is disabled throws
|
|
1113
|
+
`ValidationError` with the message `Secret '<name>' is not available`, and a
|
|
1114
|
+
credential throws `ValidationError` with `Secret '<name>' is a credential and
|
|
1115
|
+
cannot be read`.
|
|
1116
|
+
|
|
1117
|
+
`secrets.get` works in scripts and routes, after-change triggers, jobs, and inbound
|
|
1118
|
+
webhook calls. A before-change trigger is refused with `PermissionDeniedError`
|
|
1119
|
+
(`details.reason === "TRIGGER_READ_ONLY"`); a local development session reads
|
|
1120
|
+
secrets only when its administrator allowed it, otherwise the reason is
|
|
1121
|
+
`"SECRETS_NOT_ALLOWED"`. One invocation may read at most 20 secrets; reading the
|
|
1122
|
+
same name again in the same invocation returns the cached value. When secrets are
|
|
1123
|
+
not enabled for the Workspace, the error is `CogoverApiError` with
|
|
1124
|
+
`code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
|
|
1125
|
+
state, or to a response. To sign data with a secret without reading it, use
|
|
1126
|
+
`crypto.hmacSha256({ secret: name }, data)`.
|
|
1127
|
+
|
|
1128
|
+
## Cryptography
|
|
1129
|
+
|
|
1130
|
+
`crypto` provides hashing, message authentication, and randomness through
|
|
1131
|
+
Cogover's managed implementation. Import it from `@cogover/sdk` or read it from
|
|
1132
|
+
`context.crypto`; both are the same frozen object.
|
|
1133
|
+
|
|
1134
|
+
```typescript
|
|
1135
|
+
const crypto: CryptoApi;
|
|
1136
|
+
|
|
1137
|
+
interface CryptoApi {
|
|
1138
|
+
sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
|
|
1139
|
+
hmacSha256(
|
|
1140
|
+
key: string | Uint8Array | { readonly secret: string },
|
|
1141
|
+
data: string | Uint8Array,
|
|
1142
|
+
encoding?: "hex" | "base64",
|
|
1143
|
+
): Promise<string>;
|
|
1144
|
+
randomBytes(length: number): Promise<Uint8Array>;
|
|
1145
|
+
randomUUID(): Promise<string>;
|
|
1146
|
+
timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
|
|
1147
|
+
}
|
|
1148
|
+
```
|
|
1149
|
+
|
|
1150
|
+
```typescript
|
|
1151
|
+
import { crypto } from "@cogover/sdk";
|
|
1152
|
+
|
|
1153
|
+
const digest = await crypto.sha256(JSON.stringify(payload));
|
|
1154
|
+
const signature = await crypto.hmacSha256({ secret: "webhook_secret" }, request.rawBody ?? "");
|
|
1155
|
+
if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
|
|
1156
|
+
return response.empty({ status: 401 });
|
|
1157
|
+
}
|
|
1158
|
+
const token = await crypto.randomUUID();
|
|
1159
|
+
```
|
|
1160
|
+
|
|
1161
|
+
- `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
|
|
1162
|
+
hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
|
|
1163
|
+
or `"base64"`.
|
|
1164
|
+
- `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
|
|
1165
|
+
non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
|
|
1166
|
+
a project secret without reading its value; the named secret must be readable by
|
|
1167
|
+
`secrets.get` in the same context and counts as one secret read.
|
|
1168
|
+
- `randomBytes(length)` returns `length` cryptographically secure random bytes;
|
|
1169
|
+
`length` is an integer from 1 through 1024.
|
|
1170
|
+
- `randomUUID()` returns a random version 4 UUID such as
|
|
1171
|
+
`"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
|
|
1172
|
+
- `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
|
|
1173
|
+
returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
|
|
1174
|
+
it for every comparison of a signature, token, or key.
|
|
1175
|
+
|
|
1176
|
+
`data` and an explicit key are limited to 256 KiB; larger values and invalid
|
|
1177
|
+
arguments throw `ValidationError` before the call. Every operation except
|
|
1178
|
+
`timingSafeEqual` is a capability call and counts towards the invocation's limits.
|
|
1179
|
+
The operations work in every context, including before-change triggers, except that
|
|
1180
|
+
a `{ secret }` key follows the rules of `secrets.get`. This version supports
|
|
1181
|
+
SHA-256 only.
|
|
1182
|
+
|
|
1183
|
+
## Inbound webhooks
|
|
1184
|
+
|
|
1185
|
+
An administrator can create an **inbound access** for a project so that an external
|
|
1186
|
+
system calls a route without a Cogover user session. The external system receives
|
|
1187
|
+
a URL of the form
|
|
1188
|
+
|
|
1189
|
+
```text
|
|
1190
|
+
https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
|
|
1191
|
+
```
|
|
1192
|
+
|
|
1193
|
+
and authenticates each call with the inbound key or the HMAC signature that was
|
|
1194
|
+
configured for the inbound access. Cogover verifies the key or signature, applies
|
|
1195
|
+
the rate limit, and rejects the call before any project code runs. A route handler
|
|
1196
|
+
sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
|
|
1197
|
+
under `/hooks/` and the inbound ID is not part of the path.
|
|
1198
|
+
|
|
1199
|
+
```typescript
|
|
1200
|
+
import { createRouter } from "@cogover/sdk";
|
|
1201
|
+
|
|
1202
|
+
const router = createRouter();
|
|
1203
|
+
router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
|
|
1204
|
+
if (invocation.identity !== "inbound") return response.empty({ status: 403 });
|
|
1205
|
+
|
|
1206
|
+
// Optional: verify the external system's own signature over the raw body.
|
|
1207
|
+
const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
|
|
1208
|
+
if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
|
|
1209
|
+
return response.empty({ status: 401 });
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
const event = request.body as { id: string; orderId: string };
|
|
1213
|
+
await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
|
|
1214
|
+
return response.json({ received: true }, { status: 202 });
|
|
1215
|
+
});
|
|
1216
|
+
export default router.toHandler();
|
|
1217
|
+
```
|
|
1218
|
+
|
|
1219
|
+
- **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
|
|
1220
|
+
and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
|
|
1221
|
+
inbound access. `data.object()` acts as the system identity and works only if the
|
|
1222
|
+
project's approved identity policy sets `allowInternalSystem: true`; otherwise its
|
|
1223
|
+
calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
|
|
1224
|
+
`data.asUser()` and `data.asSystem()` follow the identity policy as usual.
|
|
1225
|
+
- **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
|
|
1226
|
+
`request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
|
|
1227
|
+
`request.rawBody` always holds the body exactly as received, as a UTF-8 string,
|
|
1228
|
+
and `request.contentType` the request's `Content-Type`, so a handler can verify a
|
|
1229
|
+
signature or parse another format itself.
|
|
1230
|
+
- **Response.** The handler's return value and the `response` helpers work as for
|
|
1231
|
+
any route. Keep the handler short: acknowledge the event and enqueue a job for
|
|
1232
|
+
the actual work, so that the external system gets a quick answer and retries
|
|
1233
|
+
cannot overlap with slow processing.
|
|
1234
|
+
- **Retries.** External systems usually retry a webhook that did not receive a
|
|
1235
|
+
2xx response, so a handler may see the same event more than once. Use the event's
|
|
1236
|
+
own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
|
|
1237
|
+
An `Idempotency-Key` request header works as for any route.
|
|
1238
|
+
|
|
748
1239
|
## Record API
|
|
749
1240
|
|
|
750
1241
|
```typescript
|
|
@@ -1210,6 +1701,115 @@ system supports it, store/check `fencingToken` and reject stale tokens. Locks do
|
|
|
1210
1701
|
replace idempotency, provide exactly-once execution, or combine Record API and state
|
|
1211
1702
|
operations into a transaction.
|
|
1212
1703
|
|
|
1704
|
+
## Push messages
|
|
1705
|
+
|
|
1706
|
+
`push` sends messages to the web clients of the workspace: a request to reload
|
|
1707
|
+
records, a toast, or a background message the client handles silently. It is the
|
|
1708
|
+
same mechanism as the Workflow "Push Message" action, so the standard record pages
|
|
1709
|
+
react without custom client code. Delivery is best-effort: a call resolves once the
|
|
1710
|
+
messages are handed to Cogover, never when a client receives them.
|
|
1711
|
+
|
|
1712
|
+
```typescript
|
|
1713
|
+
type PushRecipients = "viewers" | readonly string[];
|
|
1714
|
+
|
|
1715
|
+
interface PushOptions {
|
|
1716
|
+
readonly recipients?: PushRecipients;
|
|
1717
|
+
readonly exclude?: readonly string[];
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT"
|
|
1721
|
+
| "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
|
|
1722
|
+
type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
|
|
1723
|
+
|
|
1724
|
+
interface ToastLink {
|
|
1725
|
+
readonly label: string;
|
|
1726
|
+
readonly url: string;
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
interface ToastMessage<ObjectSlug extends string = string> {
|
|
1730
|
+
readonly title?: string;
|
|
1731
|
+
readonly content?: string;
|
|
1732
|
+
readonly links?: readonly ToastLink[];
|
|
1733
|
+
readonly position?: ToastPosition;
|
|
1734
|
+
readonly size?: ToastSize;
|
|
1735
|
+
readonly durationSeconds?: number;
|
|
1736
|
+
readonly object?: ObjectSlug;
|
|
1737
|
+
readonly recordIds?: readonly string[];
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
type BackgroundContentType = "text" | "template";
|
|
1741
|
+
|
|
1742
|
+
interface BackgroundMessage<ObjectSlug extends string = string> {
|
|
1743
|
+
readonly content: string;
|
|
1744
|
+
readonly contentType?: BackgroundContentType;
|
|
1745
|
+
readonly object?: ObjectSlug;
|
|
1746
|
+
readonly recordIds?: readonly string[];
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
interface PushApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
1750
|
+
refreshRecords(object: StringKeyOf<Schema>, recordIds: readonly string[],
|
|
1751
|
+
options?: PushOptions): Promise<void>;
|
|
1752
|
+
toast(message: ToastMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
|
|
1753
|
+
message(message: BackgroundMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
|
|
1754
|
+
}
|
|
1755
|
+
```
|
|
1756
|
+
|
|
1757
|
+
```typescript
|
|
1758
|
+
// After-change trigger: the handler changed the records, so everyone who has them
|
|
1759
|
+
// open must reload, including the user whose save started the trigger.
|
|
1760
|
+
await data.object("order").records.batchUpdate(items);
|
|
1761
|
+
await push.refreshRecords("order", items.map(item => item.id));
|
|
1762
|
+
```
|
|
1763
|
+
|
|
1764
|
+
### Recipients
|
|
1765
|
+
|
|
1766
|
+
Every method accepts the same `options`. `recipients` defaults to `"viewers"`:
|
|
1767
|
+
everyone who currently has one of the target records open receives the message, so
|
|
1768
|
+
`object` and `recordIds` are required. A list of personnel IDs delivers to those
|
|
1769
|
+
people wherever they are in the workspace; `object` and `recordIds` are then
|
|
1770
|
+
optional for `toast` and `message` and, when given, tell the client which records
|
|
1771
|
+
the message is about. `exclude` lists personnel IDs that never receive the message;
|
|
1772
|
+
the special value `"actor"` is the user whose action started the current execution
|
|
1773
|
+
(the caller of an HTTP script, the user whose save ran a trigger). A system
|
|
1774
|
+
execution has no actor, so `"actor"` excludes nobody. Personnel without a user
|
|
1775
|
+
account are skipped silently; an unknown personnel ID or object slug throws
|
|
1776
|
+
`NotFoundError` before anything is sent. A call accepts at most 200 record IDs and
|
|
1777
|
+
200 personnel IDs; duplicates are removed.
|
|
1778
|
+
|
|
1779
|
+
### `push.refreshRecords(object, recordIds, options?): Promise<void>`
|
|
1780
|
+
|
|
1781
|
+
Asks the clients that show these records to reload them. The record page of the
|
|
1782
|
+
web app handles the request itself. `recordIds` accepts 1 to 200 IDs.
|
|
1783
|
+
|
|
1784
|
+
### `push.toast(message, options?): Promise<void>`
|
|
1785
|
+
|
|
1786
|
+
Shows a short notification. At least one of `title` (up to 200 characters) and
|
|
1787
|
+
`content` (up to 4,000 characters) is required. `links` holds up to 5 entries whose
|
|
1788
|
+
`url` is an absolute `http` or `https` URL. `position` defaults to `"TOP_RIGHT"`,
|
|
1789
|
+
`size` to `"MEDIUM"` and `durationSeconds` to 5 (1 to 60). When `object` and
|
|
1790
|
+
`recordIds` are given, the client shows the toast only while one of those records
|
|
1791
|
+
is open.
|
|
1792
|
+
|
|
1793
|
+
### `push.message(message, options?): Promise<void>`
|
|
1794
|
+
|
|
1795
|
+
Sends a message the client handles without a visible notification, for example a
|
|
1796
|
+
custom component listening for it. `content` is required (up to 16,384 characters);
|
|
1797
|
+
`contentType` is `"text"` (default) or `"template"`.
|
|
1798
|
+
|
|
1799
|
+
### Rules
|
|
1800
|
+
|
|
1801
|
+
- Each call costs one capability call regardless of the number of records or
|
|
1802
|
+
recipients; when the recipients are `"viewers"`, one message is sent per record.
|
|
1803
|
+
- Inputs are validated by the SDK and again by Cogover; invalid input throws
|
|
1804
|
+
`ValidationError` before any message is sent.
|
|
1805
|
+
- `push` is available in scripts, routes, after-change triggers and Development
|
|
1806
|
+
Sessions. A before-change trigger is read-only and receives `PermissionDeniedError`
|
|
1807
|
+
with reason `TRIGGER_READ_ONLY`; a read-only Development Session refuses it too.
|
|
1808
|
+
- When push messages are switched off for the deployment, every call throws
|
|
1809
|
+
`CogoverApiError` with code `PUSH_DISABLED`.
|
|
1810
|
+
- A sent message cannot be recalled, and retrying a failed execution may send it
|
|
1811
|
+
again.
|
|
1812
|
+
|
|
1213
1813
|
## Schema API
|
|
1214
1814
|
|
|
1215
1815
|
`SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
|
|
@@ -1317,11 +1917,17 @@ there was no server response, such as local SDK validation. The original message
|
|
|
1317
1917
|
remains in `error.message`.
|
|
1318
1918
|
|
|
1319
1919
|
`RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
|
|
1320
|
-
An after-change trigger handler throws it to report a temporary
|
|
1321
|
-
runs the handler again later (see
|
|
1322
|
-
[After-change execution rules](#after-change-execution-rules)
|
|
1323
|
-
|
|
1324
|
-
|
|
1920
|
+
An after-change trigger handler or a job handler throws it to report a temporary
|
|
1921
|
+
failure, and Cogover runs the handler again later (see
|
|
1922
|
+
[After-change execution rules](#after-change-execution-rules) and
|
|
1923
|
+
[Job execution rules](#job-execution-rules)). Anywhere else it has no special
|
|
1924
|
+
meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
|
|
1925
|
+
that throws it rejects the write like any other failure.
|
|
1926
|
+
|
|
1927
|
+
`jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
|
|
1928
|
+
`PermissionDeniedError`, or `RateLimitError` as described in their sections, and
|
|
1929
|
+
with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
|
|
1930
|
+
the feature is not enabled for the Workspace.
|
|
1325
1931
|
|
|
1326
1932
|
Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
|
|
1327
1933
|
error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
|