@cogover/sdk 0.12.0 → 0.12.2
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 +12 -9
- package/dist/crypto.js +182 -69
- package/dist/data.js +4 -1
- package/dist/email.js +5 -3
- package/dist/internal/base64.js +92 -28
- package/dist/internal/bridge.js +41 -3
- package/dist/internal/job-config.js +7 -1
- package/dist/internal/utf8.js +18 -53
- package/dist/locks.js +13 -3
- package/dist/logger.js +47 -1
- package/dist/org.js +14 -14
- package/dist/records.d.ts +13 -0
- package/dist/response.js +21 -1
- package/dist/schema.d.ts +1 -0
- package/dist/script.js +7 -3
- package/docs/en/api-reference/background-jobs.md +288 -0
- package/docs/en/api-reference/cryptography.md +321 -0
- package/docs/en/api-reference/fetch-and-secrets.md +184 -0
- package/docs/en/api-reference/inbound-webhooks.md +65 -0
- package/docs/en/api-reference/notifications-and-email.md +317 -0
- package/docs/en/api-reference/organization-structure.md +304 -0
- package/docs/en/api-reference/overview.md +198 -0
- package/docs/en/api-reference/push-messages.md +115 -0
- package/docs/en/api-reference/record-triggers.md +469 -0
- package/docs/en/api-reference/records.md +447 -0
- package/docs/en/api-reference/scripts-and-routes.md +354 -0
- package/docs/en/api-reference/state-and-locks.md +162 -0
- package/docs/en/usage-guide.md +17 -14
- package/package.json +1 -1
- package/docs/en/api-reference.md +0 -2944
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Scripts and HTTP routes
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## `defineScript`
|
|
6
|
+
|
|
7
|
+
`defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
|
|
8
|
+
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
|
|
9
|
+
`push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
|
|
10
|
+
result.
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
function defineScript<
|
|
14
|
+
Input = unknown,
|
|
15
|
+
Output = unknown,
|
|
16
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
17
|
+
>(handler: ScriptHandler<Input, Output, Schema>): SandboxHandler;
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The related public types are:
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
type SandboxHandler = (inputJson: string) => Promise<string | null>;
|
|
24
|
+
|
|
25
|
+
type ScriptHandler<Input, Output, Schema extends object = EffectiveWorkspaceObjects> =
|
|
26
|
+
(context: ScriptContext<Input, Schema>) =>
|
|
27
|
+
Output | ScriptResponse<unknown> | null |
|
|
28
|
+
Promise<Output | ScriptResponse<unknown> | null>;
|
|
29
|
+
|
|
30
|
+
interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects> {
|
|
31
|
+
readonly input: Input;
|
|
32
|
+
readonly request: ScriptRequest<Input>;
|
|
33
|
+
readonly invocation: InvocationContext;
|
|
34
|
+
readonly data: DataApi<Schema>;
|
|
35
|
+
readonly schema: SchemaApi<Schema>;
|
|
36
|
+
readonly log: ScriptLogger;
|
|
37
|
+
readonly response: ResponseApi;
|
|
38
|
+
readonly state: ProjectState;
|
|
39
|
+
readonly locks: DistributedLocks;
|
|
40
|
+
readonly push: PushApi<Schema>;
|
|
41
|
+
readonly notifications: NotificationsApi;
|
|
42
|
+
readonly email: EmailApi<Schema>;
|
|
43
|
+
readonly jobs: JobsApi;
|
|
44
|
+
readonly secrets: SecretsApi;
|
|
45
|
+
readonly crypto: CryptoApi;
|
|
46
|
+
readonly org: OrgApi;
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`defineScript` rejects a non-function handler with `ValidationError`. The returned
|
|
51
|
+
handler rejects invalid input JSON and values that cannot be serialized to JSON.
|
|
52
|
+
Returning `null` produces a null handler result; returning `undefined` is invalid.
|
|
53
|
+
|
|
54
|
+
## HTTP routers and request context
|
|
55
|
+
|
|
56
|
+
`ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
|
|
57
|
+
`log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
|
|
58
|
+
and route handlers. `input`
|
|
59
|
+
preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
|
|
60
|
+
metadata and transport/authentication fields removed by Cogover.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
64
|
+
type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
|
|
65
|
+
type ScriptHeaders = Readonly<Record<string, string>>;
|
|
66
|
+
type ScriptPathParams = Readonly<Record<string, string>>;
|
|
67
|
+
|
|
68
|
+
interface ScriptRequest<TBody = unknown> {
|
|
69
|
+
readonly method: RequestMethod;
|
|
70
|
+
readonly path: string; // Relative to /api/v1/ts-projects/{projectSlug}
|
|
71
|
+
readonly params: ScriptPathParams;
|
|
72
|
+
readonly query: ScriptQuery;
|
|
73
|
+
readonly headers: ScriptHeaders;
|
|
74
|
+
readonly body: TBody;
|
|
75
|
+
readonly rawBody?: string; // Webhook calls only
|
|
76
|
+
readonly contentType?: string; // Webhook calls only
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The descriptor and metadata maps are frozen; its body is not deeply frozen. Method,
|
|
81
|
+
path, query, and allowlisted headers come from Cogover, not from business fields.
|
|
82
|
+
Repeated query names become readonly arrays. Header names are lower-case and
|
|
83
|
+
credentials such as `authorization` and `cookie` are never exposed. Dynamic path
|
|
84
|
+
parameters are percent-decoded after safe route matching. TypeScript types do not
|
|
85
|
+
validate runtime business input.
|
|
86
|
+
|
|
87
|
+
`rawBody` and `contentType` are present only for a call that reached the project
|
|
88
|
+
through an inbound webhook (see [Inbound webhooks](inbound-webhooks.md#inbound-webhooks)): `rawBody`
|
|
89
|
+
is the request body exactly as received, as a UTF-8 string, and `contentType` is
|
|
90
|
+
the request's `Content-Type` header. For every other call both fields are absent.
|
|
91
|
+
|
|
92
|
+
## Invocation identity and workspace
|
|
93
|
+
|
|
94
|
+
`context.invocation` is a synchronous, immutable snapshot built from metadata that
|
|
95
|
+
Cogover already authenticated and loaded for the current execution. Reading it
|
|
96
|
+
does not make a data API request.
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
|
|
100
|
+
|
|
101
|
+
interface CurrentWorkspace {
|
|
102
|
+
readonly id: string;
|
|
103
|
+
readonly name?: string;
|
|
104
|
+
readonly domain?: string;
|
|
105
|
+
readonly language?: string;
|
|
106
|
+
readonly timezone?: string;
|
|
107
|
+
readonly dateFormat?: string;
|
|
108
|
+
readonly timeFormat?: string;
|
|
109
|
+
readonly numberFormat?: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface CurrentWorkspaceRole {
|
|
113
|
+
readonly id: string;
|
|
114
|
+
readonly name: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface CurrentWorkspaceMembership {
|
|
118
|
+
readonly personnelId?: string;
|
|
119
|
+
readonly language?: string;
|
|
120
|
+
readonly timezone?: string;
|
|
121
|
+
readonly isSuperAdmin: boolean; // Holds the workspace's Super Admin role
|
|
122
|
+
readonly roles: readonly CurrentWorkspaceRole[]; // Sorted by name
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface CurrentUser {
|
|
126
|
+
readonly accountId: string;
|
|
127
|
+
readonly email?: string;
|
|
128
|
+
readonly firstName?: string;
|
|
129
|
+
readonly lastName?: string;
|
|
130
|
+
readonly avatar?: string;
|
|
131
|
+
readonly language?: string;
|
|
132
|
+
readonly timezone?: string;
|
|
133
|
+
readonly membership: CurrentWorkspaceMembership;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
interface UserInvocationContext {
|
|
137
|
+
readonly identity: "user";
|
|
138
|
+
readonly workspace: CurrentWorkspace;
|
|
139
|
+
readonly user: CurrentUser;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface SystemInvocationContext {
|
|
143
|
+
readonly identity: "system";
|
|
144
|
+
readonly workspace: CurrentWorkspace;
|
|
145
|
+
readonly user: null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface InboundInvocationContext {
|
|
149
|
+
readonly identity: "inbound";
|
|
150
|
+
readonly workspace: CurrentWorkspace;
|
|
151
|
+
readonly user: null;
|
|
152
|
+
readonly inbound: {
|
|
153
|
+
readonly id: string; // Part of the webhook URL
|
|
154
|
+
readonly name: string;
|
|
155
|
+
readonly mode: "KEY" | "HMAC"; // How the call was authenticated
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
All fields are readonly. Optional profile and workspace fields may be absent, so
|
|
161
|
+
scripts must not assume that they contain a value.
|
|
162
|
+
|
|
163
|
+
`identity` is `"user"` for a call made by an authenticated Workspace user,
|
|
164
|
+
`"system"` for an execution without a user, such as a scheduled job, and
|
|
165
|
+
`"inbound"` for a webhook call authenticated by one of the project's inbound
|
|
166
|
+
accesses (see [Inbound webhooks](inbound-webhooks.md#inbound-webhooks)). An inbound invocation has no
|
|
167
|
+
user; `inbound` identifies the inbound access that authenticated the call.
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
export default defineScript(({ invocation }) => {
|
|
171
|
+
if (invocation.identity === "system") {
|
|
172
|
+
return {workspaceId: invocation.workspace.id, user: null};
|
|
173
|
+
}
|
|
174
|
+
if (invocation.identity === "inbound") {
|
|
175
|
+
return {workspaceId: invocation.workspace.id, inbound: invocation.inbound.name};
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
workspaceId: invocation.workspace.id,
|
|
179
|
+
accountId: invocation.user.accountId,
|
|
180
|
+
personnelId: invocation.user.membership.personnelId,
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Cogover ignores caller-supplied invocation metadata and creates this snapshot from
|
|
186
|
+
the authenticated request context. Raw authentication data, tokens, inbound keys,
|
|
187
|
+
and credentials are not included. A handler called outside Cogover has no
|
|
188
|
+
authenticated invocation snapshot.
|
|
189
|
+
|
|
190
|
+
### Workspace roles of the current user
|
|
191
|
+
|
|
192
|
+
`user.membership` describes the caller's membership in the current workspace:
|
|
193
|
+
|
|
194
|
+
- `isSuperAdmin` is `true` when one of the user's roles is the workspace's
|
|
195
|
+
highest administrator (Super Admin) role, otherwise `false`.
|
|
196
|
+
- `roles` lists the roles assigned to the user in the current workspace, sorted
|
|
197
|
+
by name. Each `CurrentWorkspaceRole` has only an `id` and a `name`; the list is
|
|
198
|
+
empty when the user has no role. Role permissions are not exposed.
|
|
199
|
+
|
|
200
|
+
Compare roles by `id`: a role can be renamed, and the same role name has a
|
|
201
|
+
different `id` in each workspace. Record and field access is still enforced by
|
|
202
|
+
Cogover under the user's identity, so use these fields for business rules, such
|
|
203
|
+
as who may approve an order, not as a replacement for security rules.
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
|
|
207
|
+
|
|
208
|
+
export default defineScript(({ invocation }) => {
|
|
209
|
+
const user = invocation.user;
|
|
210
|
+
const canApprove = user !== null && (user.membership.isSuperAdmin
|
|
211
|
+
|| user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
|
|
212
|
+
return {canApprove};
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
HTTP invocations reflect the user's roles at the time of the request. Record
|
|
217
|
+
triggers and background jobs may see a role change up to about one minute late.
|
|
218
|
+
In local development with the Cogover Dev CLI, the values are captured when the
|
|
219
|
+
development session starts; restart `cogover-dev` to pick up role changes. A
|
|
220
|
+
`system` or `inbound` invocation has `user: null` and therefore no membership.
|
|
221
|
+
|
|
222
|
+
### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
|
|
223
|
+
|
|
224
|
+
Creates an independent router. `TSchema extends object` defaults to the effective
|
|
225
|
+
workspace schema, preserving `WorkspaceObjects` augmentation for data and schema
|
|
226
|
+
APIs. Routes match a method and case-sensitive static or dynamic path; static routes
|
|
227
|
+
take precedence over dynamic routes. When several dynamic routes of the same method
|
|
228
|
+
match a path, such as `/orders/:id` and `/:collection/new` for `/orders/new`, the one
|
|
229
|
+
registered first handles it. `/` addresses
|
|
230
|
+
the canonical project URL without a route suffix.
|
|
231
|
+
`/index` is a separate route, registered explicitly. `defineScript()` remains valid
|
|
232
|
+
for `/`; requesting a child path on it throws `NotFoundError` before its handler runs.
|
|
233
|
+
|
|
234
|
+
### `router.addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>`
|
|
235
|
+
|
|
236
|
+
Registers a handler and returns the same router for chaining. Supported methods are
|
|
237
|
+
`GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. A path is `/` or static/dynamic
|
|
238
|
+
components such as `/orders/:orderId`. Static components start with an ASCII letter
|
|
239
|
+
or digit, may contain letters, digits, `_`, or `-`, and are at most 100 characters.
|
|
240
|
+
Parameter names start with an ASCII letter, may contain letters, digits, or `_`, are
|
|
241
|
+
at most 64 characters, and must be unique in a route. The complete path is at most
|
|
242
|
+
1,024 characters.
|
|
243
|
+
Child trailing slashes, empty segments, `.`, `..`, percent escapes in the template,
|
|
244
|
+
`?`, `#`, and wildcards are rejected. Duplicate or structurally ambiguous routes for
|
|
245
|
+
one method, invalid handlers, or more than 256 routes throw `ValidationError`.
|
|
246
|
+
|
|
247
|
+
Handlers are ordinary `ScriptHandler` functions, not functions already wrapped in
|
|
248
|
+
`defineScript()`. They receive the same data/schema/log APIs, input and request context.
|
|
249
|
+
The same handler may be registered at more than one path.
|
|
250
|
+
|
|
251
|
+
### `router.get/post/put/patch/delete(path, handler): ScriptRouter<TSchema>`
|
|
252
|
+
|
|
253
|
+
Method-specific shorthand for `addRoute()`, with identical validation, return value,
|
|
254
|
+
and errors.
|
|
255
|
+
|
|
256
|
+
### `router.toHandler(): SandboxHandler`
|
|
257
|
+
|
|
258
|
+
Returns a default-exportable handler that captures a snapshot of the current routes.
|
|
259
|
+
Later registrations do not affect an existing handler. It parses input, dispatches
|
|
260
|
+
exactly one route, awaits it, and serializes the result just like `defineScript()`.
|
|
261
|
+
`null` remains null; an undefined result throws `ValidationError`. Missing routes
|
|
262
|
+
throw `NotFoundError` (HTTP 404), including a path that is registered only for other
|
|
263
|
+
methods: the router does not answer 405 for a method mismatch. Unsupported invocation methods use
|
|
264
|
+
`CogoverApiError` with `code: "METHOD_NOT_ALLOWED"` (HTTP 405). Invalid invocation
|
|
265
|
+
metadata throws `ValidationError`.
|
|
266
|
+
When invoked directly without Cogover request metadata, handlers default to POST `/`.
|
|
267
|
+
|
|
268
|
+
Routes inherit project authentication, permissions and runtime limits. Registering a
|
|
269
|
+
route grants no additional permission or separate security boundary. Idempotency
|
|
270
|
+
replay is scoped to method/path as well as project version and caller; use a new key
|
|
271
|
+
for each distinct business operation.
|
|
272
|
+
|
|
273
|
+
## HTTP response API
|
|
274
|
+
|
|
275
|
+
Returning a plain JSON-serializable value keeps the compatible `200
|
|
276
|
+
application/json` behavior. Use the context's `response` helpers to control status,
|
|
277
|
+
headers, content type, or body representation. Only a response made by these helpers
|
|
278
|
+
can do so: a returned value is always sent as JSON data with HTTP 200, even when it has
|
|
279
|
+
the shape of Cogover's internal response envelope, for example a request body that a
|
|
280
|
+
route returns unchanged.
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
router.post("/orders", ({ response }) => response.json({ id: "ORD-1" }, {
|
|
284
|
+
status: 201,
|
|
285
|
+
headers: { location: "/orders/ORD-1", "x-request-state": "created" },
|
|
286
|
+
}));
|
|
287
|
+
|
|
288
|
+
router.get("/files/:fileId", ({ response }) =>
|
|
289
|
+
response.bytes(new Uint8Array([0, 1, 255]), { contentType: "application/octet-stream" }));
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
type ResponseHeaderValue = string | readonly string[];
|
|
294
|
+
|
|
295
|
+
interface ResponseInit {
|
|
296
|
+
readonly status?: number;
|
|
297
|
+
readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
interface BinaryResponseInit extends ResponseInit {
|
|
301
|
+
readonly contentType?: string;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
interface ResponseApi {
|
|
305
|
+
json<T>(body: T, init?: ResponseInit): ScriptResponse<T>;
|
|
306
|
+
text(body: string, init?: ResponseInit): ScriptResponse<string>;
|
|
307
|
+
bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
|
|
308
|
+
empty(init?: ResponseInit): ScriptResponse<null>;
|
|
309
|
+
redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
response.json(body, init?)
|
|
313
|
+
response.text(body, init?)
|
|
314
|
+
response.bytes(body: Uint8Array, { status?, headers?, contentType? }?)
|
|
315
|
+
response.empty(init?) // status defaults to 204
|
|
316
|
+
response.redirect(location, status?) // status defaults to 302
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Status must be an integer from 200 through 599. Header values may be one string or
|
|
320
|
+
a readonly string array. Hop-by-hop, credential-setting, and reserved Cogover headers
|
|
321
|
+
are rejected. Header names and values cannot contain newlines;
|
|
322
|
+
at most 50 headers are accepted. A header name is at most 128 characters and each
|
|
323
|
+
value at most 8,192 characters. Default content types are
|
|
324
|
+
`application/json; charset=utf-8`, `text/plain; charset=utf-8`, and
|
|
325
|
+
`application/octet-stream`. Redirect status is restricted to 301, 302, 303, 307, or
|
|
326
|
+
308; any other value throws `ValidationError`. Helpers return an opaque `ScriptResponse`; application code must not construct
|
|
327
|
+
the transport envelope directly. A redirect location must be non-empty, at most
|
|
328
|
+
4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
|
|
329
|
+
`response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
|
|
330
|
+
|
|
331
|
+
## Logging
|
|
332
|
+
|
|
333
|
+
`context.log` implements `ScriptLogger`:
|
|
334
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
interface ScriptLogger {
|
|
337
|
+
debug(message: string, details?: unknown): void;
|
|
338
|
+
info(message: string, details?: unknown): void;
|
|
339
|
+
warn(message: string, details?: unknown): void;
|
|
340
|
+
error(message: string, details?: unknown): void;
|
|
341
|
+
}
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Each call writes one line to the execution's standard output, for every level:
|
|
345
|
+
`[LEVEL] message`, followed by a space and `details` as JSON when `details` is given,
|
|
346
|
+
for example `[WARN] Stock is low {"sku":"A-1","left":2}`. A string detail is written
|
|
347
|
+
quoted. The JSON text is cut at 8,192 characters and then ends with `…[truncated]`.
|
|
348
|
+
A value that JSON cannot represent is written in a readable form instead of failing:
|
|
349
|
+
a repeated reference to an enclosing object becomes `"[Circular]"`, a `bigint` its
|
|
350
|
+
decimal string, an `Error` `{"name":…,"message":…}` without the stack, a `Map` an
|
|
351
|
+
object, and a `Set` an array. When `details` cannot be serialized at all, for example
|
|
352
|
+
because its `toJSON()` throws, the line ends with `[unserializable]`; a log call never
|
|
353
|
+
throws. Do not include credentials, tokens, personal data, or other secrets in either
|
|
354
|
+
argument.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Project state and locks
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Project state
|
|
6
|
+
|
|
7
|
+
State is durable JSON scoped by workspace, project, namespace, and key. It is not
|
|
8
|
+
version-scoped, so it remains available after a new project version is published.
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
interface StateEntry<T> {
|
|
12
|
+
readonly value: T;
|
|
13
|
+
readonly version: number;
|
|
14
|
+
readonly expiresAt?: number;
|
|
15
|
+
readonly createdAt: number;
|
|
16
|
+
readonly updatedAt: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface StateWriteOptions {
|
|
20
|
+
readonly expectedVersion?: number;
|
|
21
|
+
readonly ttlSeconds?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface StateDeleteOptions {
|
|
25
|
+
readonly expectedVersion?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface StateNamespace {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
get<T>(key: string): Promise<StateEntry<T> | null>;
|
|
31
|
+
set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
|
|
32
|
+
delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface ProjectState {
|
|
36
|
+
namespace(name: string): StateNamespace;
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
const progress = state.namespace("inventory-sync");
|
|
42
|
+
const current = await progress.get<{ cursor: string }>("cursor");
|
|
43
|
+
|
|
44
|
+
const saved = await progress.set("cursor", { cursor: "next-page" }, {
|
|
45
|
+
expectedVersion: current?.version ?? 0,
|
|
46
|
+
ttlSeconds: 3600,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
await progress.delete("cursor", { expectedVersion: saved.version });
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### `state.namespace(name): StateNamespace`
|
|
53
|
+
|
|
54
|
+
Creates an immutable namespace client. Namespaces are at most 128 characters and
|
|
55
|
+
keys at most 255. Both start with an ASCII letter or digit and may contain letters,
|
|
56
|
+
digits, `.`, `_`, `:`, `/`, and `-`.
|
|
57
|
+
|
|
58
|
+
### `namespace.get<T>(key): Promise<StateEntry<T> | null>`
|
|
59
|
+
|
|
60
|
+
Returns `null` when the entry is missing or expired. An entry contains `value`,
|
|
61
|
+
`version`, `createdAt`, `updatedAt`, and optional `expiresAt`; timestamps are Unix
|
|
62
|
+
milliseconds.
|
|
63
|
+
|
|
64
|
+
### `namespace.set<T>(key, value, options?): Promise<StateEntry<T>>`
|
|
65
|
+
|
|
66
|
+
Stores a JSON value of at most 32 KiB: 32,768 UTF-8 bytes of its `JSON.stringify`
|
|
67
|
+
form, in which a quote, a backslash, or a control character counts as its escape
|
|
68
|
+
sequence.
|
|
69
|
+
`ttlSeconds` ranges from one second through 365 days; omit it for no automatic
|
|
70
|
+
expiry. Both option values must be safe integers. `expectedVersion` enables
|
|
71
|
+
compare-and-set: `0` means create only, a positive value must match the current
|
|
72
|
+
version, and omission is an unconditional upsert.
|
|
73
|
+
Conflicts throw `StateConflictError`; the returned entry has the new version.
|
|
74
|
+
|
|
75
|
+
A version counts the writes since the entry was created. After `delete` or expiry, the
|
|
76
|
+
next `set` creates a new entry whose version starts again at 1, so a version seen
|
|
77
|
+
before the deletion can match an unrelated new entry (the ABA problem). When that
|
|
78
|
+
matters, store your own unique token in the value and compare it as well.
|
|
79
|
+
|
|
80
|
+
### `namespace.delete(key, options?): Promise<boolean>`
|
|
81
|
+
|
|
82
|
+
Deletes an entry and returns whether it existed. `expectedVersion` has the same CAS
|
|
83
|
+
meaning as on `set`. Expired entries are treated as absent. State operations do not
|
|
84
|
+
form a transaction with Record API calls. Do not use state for secrets, files, or
|
|
85
|
+
large data.
|
|
86
|
+
|
|
87
|
+
## Distributed locks
|
|
88
|
+
|
|
89
|
+
Locks are distributed leases scoped by workspace, project, namespace, and key. They
|
|
90
|
+
prevent concurrent executions from entering the same protected section. Prefer
|
|
91
|
+
`withLock` for automatic release:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
interface LockOptions {
|
|
95
|
+
readonly namespace?: string;
|
|
96
|
+
readonly waitMs?: number;
|
|
97
|
+
readonly leaseMs?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface LockLease {
|
|
101
|
+
readonly id: string;
|
|
102
|
+
readonly key: string;
|
|
103
|
+
readonly namespace: string;
|
|
104
|
+
readonly fencingToken: number;
|
|
105
|
+
readonly expiresAt: number;
|
|
106
|
+
renew(leaseMs?: number): Promise<void>;
|
|
107
|
+
release(): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface DistributedLocks {
|
|
111
|
+
acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
|
|
112
|
+
withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
113
|
+
withLock<T>(key: string, options: LockOptions,
|
|
114
|
+
callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
await locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
|
|
120
|
+
await processInvoice("INV-1", lease.fencingToken);
|
|
121
|
+
// Renew only if work can approach expiresAt.
|
|
122
|
+
// await lease.renew(30_000);
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### `locks.acquire(key, options?): Promise<LockLease | null>`
|
|
127
|
+
|
|
128
|
+
Returns a lease, or `null` when it cannot acquire one within `waitMs`. The namespace
|
|
129
|
+
defaults to `default`; `waitMs` ranges from 0 through 10,000 ms; `leaseMs` ranges
|
|
130
|
+
from 5,000 through 60,000 ms and defaults to 30,000 ms. One invocation may hold at
|
|
131
|
+
most 16 locks; acquiring a 17th throws `ValidationError`. Keys are at most 255
|
|
132
|
+
characters and namespaces at most 128; both use the same character rules as state
|
|
133
|
+
names. Numeric options must be safe integers.
|
|
134
|
+
|
|
135
|
+
Waiting counts toward the execution's wall-clock time. In an HTTP route, which has 8
|
|
136
|
+
seconds in total by default (see [Execution limits](overview.md#execution-limits)), a
|
|
137
|
+
`waitMs` close to or above the time left ends the whole execution with the generic
|
|
138
|
+
HTTP 422 response instead of returning `null`; keep `waitMs` well below the time left.
|
|
139
|
+
|
|
140
|
+
A lease exposes `id`, `key`, `namespace`, `fencingToken`, `expiresAt`,
|
|
141
|
+
`renew(leaseMs?)`, and `release()`. Cogover renews and releases a lease by its `id`
|
|
142
|
+
within the project that acquired it: any execution of the same project that knows the
|
|
143
|
+
`id` can renew or release that lease, and another project cannot. Treat the `id` as
|
|
144
|
+
private and do not return it to callers. A lost or expired lease throws
|
|
145
|
+
`LockLostError`. Repeated `release()` on the same successfully released lease object is
|
|
146
|
+
a no-op.
|
|
147
|
+
|
|
148
|
+
### `locks.withLock(key, callback)` / `locks.withLock(key, options, callback)`
|
|
149
|
+
|
|
150
|
+
Acquires the lock, runs the callback, and then releases the lease. Failure to acquire
|
|
151
|
+
throws `LockUnavailableError`. When the callback throws, the lease is released and the
|
|
152
|
+
callback's error is rethrown; if that release also fails, its error is ignored and the
|
|
153
|
+
lease expires after `leaseMs`. When the callback succeeds but the release fails, for
|
|
154
|
+
example with `LockLostError` because the lease expired while the callback ran, that
|
|
155
|
+
error is thrown instead of the callback's result. It does not auto-renew; long
|
|
156
|
+
callbacks must call `lease.renew()` before `expiresAt`.
|
|
157
|
+
|
|
158
|
+
A lock only guarantees one valid lease at a time. Timeouts, pauses, or network
|
|
159
|
+
failures may let old work continue after its lease expires. When the downstream
|
|
160
|
+
system supports it, store/check `fencingToken` and reject stale tokens. Locks do not
|
|
161
|
+
replace idempotency, provide exactly-once execution, or combine Record API and state
|
|
162
|
+
operations into a transaction.
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -235,7 +235,9 @@ export default defineScript<Input>(async ({ input }) => {
|
|
|
235
235
|
```
|
|
236
236
|
|
|
237
237
|
This Fetch-compatible API uses Cogover's managed network layer; it does not provide
|
|
238
|
-
unrestricted Node.js network access. Only public HTTPS URLs on port 443
|
|
238
|
+
unrestricted Node.js network access. Only public HTTPS URLs are supported, on port 443
|
|
239
|
+
or on another port whose exact origin a Workspace administrator approved for the
|
|
240
|
+
project.
|
|
239
241
|
V1 does not follow redirects, maintain a cookie jar, stream, support WebSocket,
|
|
240
242
|
accept IP-literal/userinfo URLs, or expose proxy, dispatcher, agent, DNS, or TLS
|
|
241
243
|
configuration. Requests and responses are bounded. For remote mutations, use the
|
|
@@ -381,8 +383,8 @@ export default defineScript(async ({ locks }) =>
|
|
|
381
383
|
}));
|
|
382
384
|
```
|
|
383
385
|
|
|
384
|
-
`withLock`
|
|
385
|
-
`LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
|
|
386
|
+
`withLock` releases the lease after the callback; when both fail, the callback's own
|
|
387
|
+
error is thrown. Acquisition failure throws `LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
|
|
386
388
|
longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
|
|
387
389
|
token in downstream systems where possible to reject stale writers. Locks do not
|
|
388
390
|
replace idempotency or provide exactly-once execution.
|
|
@@ -499,7 +501,7 @@ router.post("/recalculate", async ({ jobs, response }) => {
|
|
|
499
501
|
`duplicate: true`; `delayMs` or `runAt` postpones a run by up to 30 days. A
|
|
500
502
|
payload is JSON of at most 64 KiB.
|
|
501
503
|
|
|
502
|
-
See the [background job reference](api-reference.md#background-jobs) for every
|
|
504
|
+
See the [background job reference](api-reference/background-jobs.md#background-jobs) for every
|
|
503
505
|
option and rule.
|
|
504
506
|
|
|
505
507
|
## Send notifications and email
|
|
@@ -693,8 +695,8 @@ identity policy for both `data.object()` and the mailbox grant, and it cannot us
|
|
|
693
695
|
`from: "actor"`. A call made while an earlier call with the same key is still
|
|
694
696
|
sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`; let the run
|
|
695
697
|
fail with `RetryableError` or try again later. See
|
|
696
|
-
[Notifications](api-reference.md#notifications) and
|
|
697
|
-
[Email](api-reference.md#email) in the API reference for every option and error.
|
|
698
|
+
[Notifications](api-reference/notifications-and-email.md#notifications) and
|
|
699
|
+
[Email](api-reference/notifications-and-email.md#email) in the API reference for every option and error.
|
|
698
700
|
|
|
699
701
|
## Choose the identity for record operations
|
|
700
702
|
|
|
@@ -733,7 +735,7 @@ reads apply the selected user's permissions; failures never retry as system.
|
|
|
733
735
|
An uncaught permission error returns HTTP 403 with `code: "PERMISSION_DENIED"`.
|
|
734
736
|
`reason: "IDENTITY_NOT_GRANTED"` means the project lacks approval to select that
|
|
735
737
|
identity. Check `writesMayHaveCompleted` before considering a retry: earlier writes
|
|
736
|
-
are not rolled back. See the [error response reference](api-reference.md#errors).
|
|
738
|
+
are not rolled back. See the [error response reference](api-reference/overview.md#errors).
|
|
737
739
|
|
|
738
740
|
Unapproved selections fail; there is no automatic fallback. A project with
|
|
739
741
|
privileged access must validate which records a caller may request it to process;
|
|
@@ -741,7 +743,7 @@ being able to see a record is not sufficient business authorization. Never let
|
|
|
741
743
|
request input grant system privileges. Never place a Cogover API key or
|
|
742
744
|
authentication object in module code, and never log or return credentials for an
|
|
743
745
|
external service. See
|
|
744
|
-
[API reference](api-reference.md#record-execution-identities).
|
|
746
|
+
[API reference](api-reference/records.md#record-execution-identities).
|
|
745
747
|
|
|
746
748
|
## Record triggers
|
|
747
749
|
|
|
@@ -861,7 +863,7 @@ in scripts.
|
|
|
861
863
|
before-change triggers of one write share 8 seconds. Before-change triggers fail
|
|
862
864
|
closed: when a handler throws, runs out of time, or cannot be run, the write is
|
|
863
865
|
rejected and nothing is saved. Keep handlers short and deterministic. See the
|
|
864
|
-
[record trigger reference](api-reference.md#record-triggers).
|
|
866
|
+
[record trigger reference](api-reference/record-triggers.md#record-triggers).
|
|
865
867
|
|
|
866
868
|
### After-change triggers
|
|
867
869
|
|
|
@@ -935,7 +937,7 @@ export const triggers = [
|
|
|
935
937
|
- **Order.** After-change triggers of one change run independently; do not rely on
|
|
936
938
|
their relative order, and read the current record when the latest values matter.
|
|
937
939
|
|
|
938
|
-
See [After-change execution rules](api-reference.md#after-change-execution-rules).
|
|
940
|
+
See [After-change execution rules](api-reference/record-triggers.md#after-change-execution-rules).
|
|
939
941
|
|
|
940
942
|
## Recommended TypeScript configuration
|
|
941
943
|
|
|
@@ -979,9 +981,10 @@ Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `p
|
|
|
979
981
|
decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
|
|
980
982
|
`body`. Authentication headers are never exposed. Plain return values are JSON with
|
|
981
983
|
HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
|
|
982
|
-
status, safe response headers, and text/binary bodies. Missing routes
|
|
983
|
-
|
|
984
|
-
|
|
984
|
+
status, safe response headers, and text/binary bodies. Missing routes, including a
|
|
985
|
+
path registered only for other methods, return 404; methods other than these five
|
|
986
|
+
return 405. Existing `defineScript()` projects continue at `/`.
|
|
987
|
+
Validate all business input. See the [router API reference](api-reference/scripts-and-routes.md#http-routers-and-request-context).
|
|
985
988
|
|
|
986
989
|
## Receive webhooks
|
|
987
990
|
|
|
@@ -1044,4 +1047,4 @@ export const jobs = [
|
|
|
1044
1047
|
- Providers retry webhooks that did not get a 2xx answer, so use the event's own
|
|
1045
1048
|
ID as the job's `idempotencyKey`.
|
|
1046
1049
|
|
|
1047
|
-
See [Inbound webhooks](api-reference.md#inbound-webhooks) for the complete rules.
|
|
1050
|
+
See [Inbound webhooks](api-reference/inbound-webhooks.md#inbound-webhooks) for the complete rules.
|