@cogover/sdk 0.5.0 → 0.7.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 +127 -5
- package/dist/data.d.ts +6 -1
- package/dist/data.js +28 -1
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +2 -1
- package/dist/internal/json.js +81 -0
- package/dist/internal/trigger-config.js +212 -0
- package/dist/internal/trigger-runtime.js +213 -0
- package/dist/push.d.ts +48 -0
- package/dist/push.js +190 -0
- package/dist/records.d.ts +5 -0
- package/dist/router.js +1 -0
- package/dist/script.d.ts +2 -0
- package/dist/script.js +2 -0
- package/dist/trigger.d.ts +124 -0
- package/dist/trigger.js +15 -0
- package/docs/en/api-reference.md +584 -4
- package/docs/en/usage-guide.md +242 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,7 +45,7 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
|
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
`defineScript` parses the input JSON, provides invocation metadata and scoped
|
|
48
|
-
data, schema, logging, state, and
|
|
48
|
+
data, schema, logging, state, lock, and push APIs, waits for the async handler, and
|
|
49
49
|
serializes its result. Cogover authentication credentials are not exposed to
|
|
50
50
|
project code, and Cogover enforces the configured permissions and limits on
|
|
51
51
|
capability calls.
|
|
@@ -102,6 +102,93 @@ status, safe response headers, and text/binary bodies. Missing routes return 404
|
|
|
102
102
|
unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
|
|
103
103
|
The complete router contract is included in `docs/en/api-reference.md`.
|
|
104
104
|
|
|
105
|
+
## Record triggers
|
|
106
|
+
|
|
107
|
+
A record trigger runs project code when records of an Object are created, updated,
|
|
108
|
+
or deleted, for every source of a write. A before-change trigger runs before the
|
|
109
|
+
change is saved and can reject records or adjust the values that will be saved. An
|
|
110
|
+
after-change trigger runs asynchronously after the change has been saved.
|
|
111
|
+
Declare triggers with `defineTrigger` and list them in the named `triggers` export;
|
|
112
|
+
the default export stays reserved for HTTP and is optional in a trigger-only project.
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { defineTrigger } from "@cogover/sdk";
|
|
116
|
+
|
|
117
|
+
export const triggers = [
|
|
118
|
+
defineTrigger({
|
|
119
|
+
key: "order_credit_check",
|
|
120
|
+
object: "order",
|
|
121
|
+
timing: "beforeChange",
|
|
122
|
+
operations: ["create", "update"],
|
|
123
|
+
fields: ["status", "amount"],
|
|
124
|
+
changedFields: ["status", "amount"],
|
|
125
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
126
|
+
writableFields: ["approval_level"],
|
|
127
|
+
}, async ({ records }) => {
|
|
128
|
+
for (const record of records) {
|
|
129
|
+
if ((record.new.amount ?? 0) > 1_000_000_000) {
|
|
130
|
+
record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
record.new.approval_level = "high";
|
|
134
|
+
}
|
|
135
|
+
}),
|
|
136
|
+
];
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`record.new` and `record.old` contain only the listed `fields`. Assign fields of
|
|
140
|
+
`record.new` to change what is saved: only `writableFields` may change, and values
|
|
141
|
+
use the same format as `records.update` input. `record.addError(field, code,
|
|
142
|
+
message?)` rejects a record; the optional English message is shown to the end user
|
|
143
|
+
when the code has no translation. `changedFields`, `when`, and `runWhen` limit when
|
|
144
|
+
the trigger runs.
|
|
145
|
+
|
|
146
|
+
A handler receives up to 200 records per call, so read related data once with
|
|
147
|
+
`records.getMany` instead of once per record. Before-change triggers are read-only:
|
|
148
|
+
record writes, `fetch`, locks, state writes, and push messages are refused with
|
|
149
|
+
`PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`). `data.object()`
|
|
150
|
+
acts as the user who made the change. A handler that throws or exceeds its
|
|
151
|
+
`timeoutMs` (default 2,000 ms) rejects the write.
|
|
152
|
+
|
|
153
|
+
An after-change trigger (`timing: "afterChange"`) is for follow-up work. It cannot
|
|
154
|
+
reject or modify the saved change (`addError` is only logged), but it may write
|
|
155
|
+
records and call `fetch`. `record.new` holds the saved values, including the record
|
|
156
|
+
ID.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
160
|
+
|
|
161
|
+
export const triggers = [
|
|
162
|
+
defineTrigger({
|
|
163
|
+
key: "order_confirmed_notify",
|
|
164
|
+
object: "order",
|
|
165
|
+
timing: "afterChange",
|
|
166
|
+
operations: ["update"],
|
|
167
|
+
fields: ["status", "amount"],
|
|
168
|
+
changedFields: ["status"],
|
|
169
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
170
|
+
runWhen: "onEnter",
|
|
171
|
+
}, async ({ records, trigger }) => {
|
|
172
|
+
for (const record of records) {
|
|
173
|
+
const response = await fetch("https://erp.example.com/orders", {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers: { "idempotency-key": `${trigger.changeId}:${record.id}` },
|
|
176
|
+
body: JSON.stringify({ id: record.id, amount: record.new.amount }),
|
|
177
|
+
});
|
|
178
|
+
if (response.status >= 500) throw new RetryableError("The ERP is temporarily unavailable");
|
|
179
|
+
}
|
|
180
|
+
}),
|
|
181
|
+
];
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Delivery is best-effort: a handler may occasionally run more than once for the same
|
|
185
|
+
change, or not at all, so make it idempotent and keep critical rules in a
|
|
186
|
+
before-change trigger. Throw `RetryableError` for a temporary failure and Cogover
|
|
187
|
+
runs the handler again later, a limited number of times; other errors are logged and
|
|
188
|
+
not retried. Writes made by a trigger run triggers again, and Cogover ends such
|
|
189
|
+
chains after a bounded number of automated writes. The complete contract is included
|
|
190
|
+
in `docs/en/api-reference.md`.
|
|
191
|
+
|
|
105
192
|
## Outbound HTTP with `fetch`
|
|
106
193
|
|
|
107
194
|
Cogover provides a Fetch-compatible function for calling an external HTTPS API.
|
|
@@ -139,8 +226,8 @@ and do not retry blindly.
|
|
|
139
226
|
|
|
140
227
|
## Record API
|
|
141
228
|
|
|
142
|
-
An Object client exposes `records.get`, `records.
|
|
143
|
-
`records.update`, `records.batchInsert`, `records.batchUpdate`,
|
|
229
|
+
An Object client exposes `records.get`, `records.getMany`, `records.list`,
|
|
230
|
+
`records.create`, `records.update`, `records.batchInsert`, `records.batchUpdate`,
|
|
144
231
|
`records.upsertByUniqueField`, and `records.deleteMany`. List filters are built from typed
|
|
145
232
|
field references, so scripts do not provide transport-specific field metadata or
|
|
146
233
|
response envelopes.
|
|
@@ -168,6 +255,11 @@ export default defineScript(async ({ data }) => {
|
|
|
168
255
|
});
|
|
169
256
|
```
|
|
170
257
|
|
|
258
|
+
`records.getMany(ids, { fields })` reads up to 200 records by ID with one capability
|
|
259
|
+
call. `fields` is required. The result is `{ records, missingIds }`: IDs that do not
|
|
260
|
+
exist or are not visible to the identity in use are reported in `missingIds` instead
|
|
261
|
+
of being dropped. Prefer it to calling `records.get` in a loop.
|
|
262
|
+
|
|
171
263
|
Batch writes are best-effort per row. Check `result.success` or every entry in
|
|
172
264
|
`result.results`; a successful request envelope does not mean every row succeeded.
|
|
173
265
|
Business upsert accepts one `matchBy` field that must be configured as a single-field
|
|
@@ -205,7 +297,7 @@ outbound requests → 400; state conflicts and lock errors → 409; oversized ou
|
|
|
205
297
|
requests → 413; permission denied → 403; not found → 404; unsupported methods →
|
|
206
298
|
405; rate limits → 429; unavailable state, lock, or outbound HTTP services → 503;
|
|
207
299
|
oversized or failed remote responses → 502; outbound timeouts → 504; and other
|
|
208
|
-
data API failures → 422. The response includes `code`, `msg`, `r` (HTTP status),
|
|
300
|
+
data API failures, as well as an escaped `RetryableError`, → 422. The response includes `code`, `msg`, `r` (HTTP status),
|
|
209
301
|
and `writesMayHaveCompleted` when relevant. Earlier writes are not rolled back;
|
|
210
302
|
never retry writes automatically. Unknown script errors and resource-limit
|
|
211
303
|
failures use a generic 422 response.
|
|
@@ -228,7 +320,12 @@ accepts a personnel ID (not an account ID) and supports the full record API, inc
|
|
|
228
320
|
batch writes and business upsert. Reads apply that user's permissions and approved field restrictions;
|
|
229
321
|
read access must be approved separately from writes. `asSystem` supports the
|
|
230
322
|
full record API, including in authenticated public scripts, without changing the
|
|
231
|
-
original caller or existing clients.
|
|
323
|
+
original caller or existing clients. `asSystem` may also write fields whose manual
|
|
324
|
+
creation (`creatable: false`) or manual modification (`manualModifyAllow: false`) is
|
|
325
|
+
disabled, because those locks only stop manual entry by users; for the caller and
|
|
326
|
+
`asUser`, creates reject `creatable: false` fields (`details.reason === "FIELD_NOT_CREATABLE"`)
|
|
327
|
+
and updates reject `manualModifyAllow: false` fields (`"FIELD_NOT_WRITABLE"`). Read-only
|
|
328
|
+
fields such as formulas, auto numbers and rollups stay rejected for every identity.
|
|
232
329
|
|
|
233
330
|
Administrator approval is required for the project version, callers, target users,
|
|
234
331
|
objects, operations, and fields. Unauthorized operations fail without falling back
|
|
@@ -269,6 +366,31 @@ export default defineScript(async ({ locks }) =>
|
|
|
269
366
|
State conflicts throw `StateConflictError`; failed lock acquisition and lost leases
|
|
270
367
|
use `LockUnavailableError` and `LockLostError`.
|
|
271
368
|
|
|
369
|
+
## Push messages to web clients
|
|
370
|
+
|
|
371
|
+
`push` asks the web app to react to what a script did: reload the records that are
|
|
372
|
+
open on screen, show a toast, or deliver a silent message. Recipients are the people
|
|
373
|
+
viewing the given records (the default) or explicit personnel IDs, and
|
|
374
|
+
`exclude: ["actor"]` skips the user who caused the execution.
|
|
375
|
+
|
|
376
|
+
```typescript
|
|
377
|
+
export default defineTrigger({
|
|
378
|
+
key: "order_totals_changed",
|
|
379
|
+
object: "order",
|
|
380
|
+
timing: "afterChange",
|
|
381
|
+
operations: ["update"],
|
|
382
|
+
fields: ["total"],
|
|
383
|
+
}, async ({ records, push }) => {
|
|
384
|
+
const ids = records.flatMap(record => record.id === null ? [] : [record.id]);
|
|
385
|
+
await push.refreshRecords("order", ids);
|
|
386
|
+
await push.toast({ title: "Order totals updated", object: "order", recordIds: ids });
|
|
387
|
+
});
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Delivery is best-effort, each call counts as one capability call, and before-change
|
|
391
|
+
triggers cannot push. Invalid input throws `ValidationError`; an unknown object or
|
|
392
|
+
personnel throws `NotFoundError`.
|
|
393
|
+
|
|
272
394
|
## Workspace types
|
|
273
395
|
|
|
274
396
|
`WorkspaceObjects` is an open interface augmented by a generated declaration for
|
package/dist/data.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { FieldReferences, FilterExpression, SortExpression } from "./query.js";
|
|
2
|
-
import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, RecordPage, UpdateFields, UpsertFields, UpsertResult } from "./records.js";
|
|
2
|
+
import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, GetManyResult, RecordPage, UpdateFields, UpsertFields, UpsertResult } from "./records.js";
|
|
3
3
|
import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
|
|
4
4
|
export interface GetRecordOptions<TFields> {
|
|
5
5
|
readonly fields?: readonly StringKeyOf<TFields>[];
|
|
6
6
|
}
|
|
7
|
+
export interface GetManyOptions<TFields> {
|
|
8
|
+
readonly fields: readonly StringKeyOf<TFields>[];
|
|
9
|
+
}
|
|
7
10
|
export interface ListOptions<TFields> {
|
|
8
11
|
readonly where?: FilterExpression;
|
|
9
12
|
readonly orderBy?: readonly SortExpression[];
|
|
@@ -21,6 +24,8 @@ export interface RecordWritesApi<TFields> {
|
|
|
21
24
|
}
|
|
22
25
|
export interface RecordsApi<TFields> extends RecordWritesApi<TFields> {
|
|
23
26
|
get(id: string, options?: GetRecordOptions<TFields>): Promise<CogoverRecord<TFields> | null>;
|
|
27
|
+
/** Reads up to 200 records by ID in one call; unreadable IDs are reported in `missingIds`. */
|
|
28
|
+
getMany(ids: readonly string[], options: GetManyOptions<TFields>): Promise<GetManyResult<TFields>>;
|
|
24
29
|
list(options?: ListOptions<TFields>): Promise<RecordPage<TFields>>;
|
|
25
30
|
}
|
|
26
31
|
export interface WriteObjectClient<TFields> {
|
package/dist/data.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ValidationError } from "./errors.js";
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
2
|
import { callBridge } from "./internal/bridge.js";
|
|
3
3
|
import { requireFieldSlug, requireFields, requireSlug, requireText } from "./internal/validation.js";
|
|
4
4
|
import { isRecord } from "./internal/values.js";
|
|
@@ -34,6 +34,33 @@ function createObjectClient(slug, identity) {
|
|
|
34
34
|
fields: options?.fields,
|
|
35
35
|
});
|
|
36
36
|
},
|
|
37
|
+
async getMany(ids, options) {
|
|
38
|
+
if (!Array.isArray(ids)) {
|
|
39
|
+
throw new ValidationError("getMany() requires an array of record ids");
|
|
40
|
+
}
|
|
41
|
+
const uniqueIds = [...new Set(ids.map((id) => requireText(id, "record id")))];
|
|
42
|
+
if (uniqueIds.length > MAX_BATCH_RECORDS) {
|
|
43
|
+
throw new ValidationError(`getMany() supports at most ${MAX_BATCH_RECORDS} unique record ids`);
|
|
44
|
+
}
|
|
45
|
+
const requestedFields = options?.fields;
|
|
46
|
+
if (!Array.isArray(requestedFields) || requestedFields.length === 0) {
|
|
47
|
+
throw new ValidationError("getMany() requires a non-empty fields array");
|
|
48
|
+
}
|
|
49
|
+
const fieldSlugs = [...new Set(requestedFields.map((field) => requireFieldSlug(field)))];
|
|
50
|
+
if (uniqueIds.length === 0) {
|
|
51
|
+
return { records: [], missingIds: [] };
|
|
52
|
+
}
|
|
53
|
+
const result = await callBridge("records.getMany", {
|
|
54
|
+
identity,
|
|
55
|
+
objectSlug: slug,
|
|
56
|
+
ids: uniqueIds,
|
|
57
|
+
fields: fieldSlugs,
|
|
58
|
+
});
|
|
59
|
+
if (!isRecord(result) || !Array.isArray(result.records) || !Array.isArray(result.missingIds)) {
|
|
60
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.getMany returned an invalid result");
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
},
|
|
37
64
|
async list(options) {
|
|
38
65
|
return callBridge("records.list", {
|
|
39
66
|
identity,
|
package/dist/errors.d.ts
CHANGED
|
@@ -19,6 +19,13 @@ export declare class PermissionDeniedError extends CogoverApiError {
|
|
|
19
19
|
export declare class RateLimitError extends CogoverApiError {
|
|
20
20
|
constructor(message: string, details?: unknown);
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs the handler again
|
|
24
|
+
* later. Anywhere else it is an ordinary failure.
|
|
25
|
+
*/
|
|
26
|
+
export declare class RetryableError extends CogoverApiError {
|
|
27
|
+
constructor(message: string, details?: unknown);
|
|
28
|
+
}
|
|
22
29
|
export declare class StateConflictError extends CogoverApiError {
|
|
23
30
|
constructor(message: string, details?: unknown);
|
|
24
31
|
}
|
package/dist/errors.js
CHANGED
|
@@ -42,6 +42,16 @@ export class RateLimitError extends CogoverApiError {
|
|
|
42
42
|
this.name = "RateLimitError";
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Thrown by an after-change trigger handler to report a temporary failure. Cogover runs the handler again
|
|
47
|
+
* later. Anywhere else it is an ordinary failure.
|
|
48
|
+
*/
|
|
49
|
+
export class RetryableError extends CogoverApiError {
|
|
50
|
+
constructor(message, details) {
|
|
51
|
+
super("RETRYABLE", message, details);
|
|
52
|
+
this.name = "RetryableError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
45
55
|
export class StateConflictError extends CogoverApiError {
|
|
46
56
|
constructor(message, details) {
|
|
47
57
|
super("STATE_CONFLICT", message, details);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
/** Public TypeScript API for Cogover projects. */
|
|
2
2
|
export type { WorkspaceObjects } from "./workspace.js";
|
|
3
|
-
export type { CogoverRecordId, RecordReference, UrlValue, FileValue, CogoverRecord, RecordPage, DeleteResult, BatchWriteRowResult, BatchWriteResponse, BatchUpdateItem, UpsertFields, UpsertResult, CreateFields, UpdateFields, } from "./records.js";
|
|
3
|
+
export type { CogoverRecordId, RecordReference, UrlValue, FileValue, CogoverRecord, RecordPage, GetManyResult, DeleteResult, BatchWriteRowResult, BatchWriteResponse, BatchUpdateItem, UpsertFields, UpsertResult, CreateFields, UpdateFields, } from "./records.js";
|
|
4
4
|
export { and, or } from "./query.js";
|
|
5
5
|
export type { FilterOperator, FilterCondition, FilterGroup, FilterExpression, SortExpression, FieldReference, FieldReferences, } from "./query.js";
|
|
6
|
-
export type { GetRecordOptions, ListOptions, RecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, DataApi, } from "./data.js";
|
|
6
|
+
export type { GetRecordOptions, GetManyOptions, ListOptions, RecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, DataApi, } from "./data.js";
|
|
7
7
|
export type { ObjectMetadata, SchemaApi } from "./schema.js";
|
|
8
8
|
export type { ScriptLogger } from "./logger.js";
|
|
9
9
|
export { defineScript } from "./script.js";
|
|
10
10
|
export type { ScriptContext, ScriptHandler, SandboxHandler } from "./script.js";
|
|
11
|
+
export { defineTrigger } from "./trigger.js";
|
|
12
|
+
export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCondition, TriggerFilterGroup, TriggerFilter, TriggerConfig, TriggerManifest, TriggerSandboxHandler, TriggerDefinition, TriggerInfo, TriggerNewValues, TriggerOldValues, TriggerRecord, TriggerContext, TriggerHandler, } from "./trigger.js";
|
|
11
13
|
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InvocationContext, } from "./invocation.js";
|
|
12
14
|
export { createRouter } from "./router.js";
|
|
13
15
|
export type { ScriptRouter } from "./router.js";
|
|
@@ -15,7 +17,8 @@ export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPa
|
|
|
15
17
|
export type { ResponseApi, ResponseInit, BinaryResponseInit, ResponseHeaderValue, ScriptResponse, } from "./response.js";
|
|
16
18
|
export type { ProjectState, StateNamespace, StateEntry, StateWriteOptions, StateDeleteOptions, } from "./state.js";
|
|
17
19
|
export type { DistributedLocks, LockLease, LockOptions, } from "./locks.js";
|
|
20
|
+
export type { PushRecipients, PushOptions, ToastPosition, ToastSize, ToastLink, ToastMessage, BackgroundContentType, BackgroundMessage, PushApi, } from "./push.js";
|
|
18
21
|
export { fetch } from "./fetch.js";
|
|
19
22
|
export type { CogoverFetchInit, CogoverFetchHeaders, CogoverFetchResponse, } from "./fetch.js";
|
|
20
|
-
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
23
|
+
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
21
24
|
export { createGreeting } from "./legacy.js";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Public TypeScript API for Cogover projects. */
|
|
2
2
|
export { and, or } from "./query.js";
|
|
3
3
|
export { defineScript } from "./script.js";
|
|
4
|
+
export { defineTrigger } from "./trigger.js";
|
|
4
5
|
export { createRouter } from "./router.js";
|
|
5
6
|
export { fetch } from "./fetch.js";
|
|
6
|
-
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
7
|
+
export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
|
|
7
8
|
export { createGreeting } from "./legacy.js";
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { errorMessage } from "./values.js";
|
|
3
|
+
/**
|
|
4
|
+
* Converts a value to plain JSON data using JSON.stringify semantics, but rejects every value that
|
|
5
|
+
* JSON.stringify would silently change or drop (NaN, functions, Map/Set, undefined array items...).
|
|
6
|
+
* Silent coercion would turn a calculation bug into a cleared field.
|
|
7
|
+
*/
|
|
8
|
+
export function toJsonValue(value, label) {
|
|
9
|
+
let serialized;
|
|
10
|
+
try {
|
|
11
|
+
serialized = JSON.stringify(value, strictReplacer);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new ValidationError(`${label} must be JSON serializable: ${errorMessage(error)}`);
|
|
15
|
+
}
|
|
16
|
+
if (serialized === undefined) {
|
|
17
|
+
throw new ValidationError(`${label} must be JSON serializable`);
|
|
18
|
+
}
|
|
19
|
+
return JSON.parse(serialized);
|
|
20
|
+
}
|
|
21
|
+
/** Deep copy of data that is already plain JSON. */
|
|
22
|
+
export function cloneJson(value) {
|
|
23
|
+
return JSON.parse(JSON.stringify(value));
|
|
24
|
+
}
|
|
25
|
+
/** Structural equality of two plain JSON values; object key order is irrelevant. */
|
|
26
|
+
export function jsonEquals(left, right) {
|
|
27
|
+
if (left === right)
|
|
28
|
+
return true;
|
|
29
|
+
if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
33
|
+
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
|
|
34
|
+
return false;
|
|
35
|
+
return left.every((item, index) => jsonEquals(item, right[index]));
|
|
36
|
+
}
|
|
37
|
+
const leftObject = left;
|
|
38
|
+
const rightObject = right;
|
|
39
|
+
const leftKeys = Object.keys(leftObject);
|
|
40
|
+
if (leftKeys.length !== Object.keys(rightObject).length)
|
|
41
|
+
return false;
|
|
42
|
+
return leftKeys.every(key => Object.prototype.hasOwnProperty.call(rightObject, key)
|
|
43
|
+
&& jsonEquals(leftObject[key], rightObject[key]));
|
|
44
|
+
}
|
|
45
|
+
export function deepFreeze(value) {
|
|
46
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
47
|
+
Object.freeze(value);
|
|
48
|
+
for (const item of Object.values(value))
|
|
49
|
+
deepFreeze(item);
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
// JSON.stringify invokes the replacer after toJSON(), so a Date arrives here as its ISO string.
|
|
54
|
+
function strictReplacer(_key, value) {
|
|
55
|
+
if (value === undefined) {
|
|
56
|
+
if (Array.isArray(this))
|
|
57
|
+
throw new TypeError("undefined is not allowed inside an array");
|
|
58
|
+
return value; // An undefined object property is omitted, exactly like JSON.stringify.
|
|
59
|
+
}
|
|
60
|
+
switch (typeof value) {
|
|
61
|
+
case "number":
|
|
62
|
+
if (!Number.isFinite(value))
|
|
63
|
+
throw new TypeError("numbers must be finite");
|
|
64
|
+
return value;
|
|
65
|
+
case "bigint":
|
|
66
|
+
case "function":
|
|
67
|
+
case "symbol":
|
|
68
|
+
throw new TypeError(`${typeof value} values are not supported`);
|
|
69
|
+
case "object": {
|
|
70
|
+
if (value === null || Array.isArray(value))
|
|
71
|
+
return value;
|
|
72
|
+
const prototype = Object.getPrototypeOf(value);
|
|
73
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
74
|
+
throw new TypeError("only plain objects and arrays are supported");
|
|
75
|
+
}
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
default:
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { deepFreeze, toJsonValue } from "./json.js";
|
|
3
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
4
|
+
const TRIGGER_KEY = /^[A-Za-z][A-Za-z0-9_]{0,99}$/;
|
|
5
|
+
export const TRIGGER_SLUG = /^[A-Za-z_][A-Za-z0-9_]{0,354}$/;
|
|
6
|
+
const CONFIG_KEYS = new Set([
|
|
7
|
+
"key", "name", "object", "timing", "operations", "fields", "changedFields", "when",
|
|
8
|
+
"runWhen", "writableFields", "order", "timeoutMs",
|
|
9
|
+
]);
|
|
10
|
+
const TIMINGS = new Set(["beforeChange", "afterChange"]);
|
|
11
|
+
const OPERATIONS = new Set(["create", "update", "delete"]);
|
|
12
|
+
const RUN_WHEN = new Set(["always", "onEnter"]);
|
|
13
|
+
const GROUP_OPERATORS = new Set(["and", "or"]);
|
|
14
|
+
const CONDITION_OPERATORS = new Set([
|
|
15
|
+
"=", "!=", ">", ">=", "<", "<=", "like", "not like", "startsWith", "endsWith",
|
|
16
|
+
"in", "not in", "is null", "not null", "between",
|
|
17
|
+
]);
|
|
18
|
+
const MAX_NAME_LENGTH = 250;
|
|
19
|
+
const MAX_FIELDS = 200;
|
|
20
|
+
const MAX_WRITABLE_FIELDS = 100;
|
|
21
|
+
const MIN_ORDER = 1000;
|
|
22
|
+
const MAX_ORDER = 8999;
|
|
23
|
+
const DEFAULT_ORDER = 5000;
|
|
24
|
+
const MIN_TIMEOUT_MILLIS = 100;
|
|
25
|
+
const MAX_TIMEOUT_MILLIS = 3000;
|
|
26
|
+
const DEFAULT_TIMEOUT_MILLIS = 2000;
|
|
27
|
+
const MAX_FILTER_DEPTH = 8;
|
|
28
|
+
const MAX_FILTER_CONDITIONS = 50;
|
|
29
|
+
/** Validates a defineTrigger() config and returns the frozen plain-JSON manifest with defaults applied. */
|
|
30
|
+
export function normalizeTriggerConfig(config) {
|
|
31
|
+
if (!isRecord(config)) {
|
|
32
|
+
throw new ValidationError("defineTrigger() requires a configuration object");
|
|
33
|
+
}
|
|
34
|
+
const key = config.key;
|
|
35
|
+
if (typeof key !== "string" || !TRIGGER_KEY.test(key)) {
|
|
36
|
+
throw new ValidationError("Trigger key must start with a letter and contain at most 100 letters, digits or underscores");
|
|
37
|
+
}
|
|
38
|
+
const fail = (option, message) => new ValidationError(`Trigger '${key}': ${message}`, { triggerKey: key, option });
|
|
39
|
+
for (const option of Object.keys(config)) {
|
|
40
|
+
if (!CONFIG_KEYS.has(option))
|
|
41
|
+
throw fail(option, `unknown config key '${option}'`);
|
|
42
|
+
}
|
|
43
|
+
let name;
|
|
44
|
+
if (config.name !== undefined) {
|
|
45
|
+
name = typeof config.name === "string" ? config.name.trim() : "";
|
|
46
|
+
if (name.length === 0 || name.length > MAX_NAME_LENGTH) {
|
|
47
|
+
throw fail("name", `name must be a non-empty string of at most ${MAX_NAME_LENGTH} characters`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const object = config.object;
|
|
51
|
+
if (typeof object !== "string" || !TRIGGER_SLUG.test(object)) {
|
|
52
|
+
throw fail("object", "object must be a valid object slug");
|
|
53
|
+
}
|
|
54
|
+
const timing = config.timing;
|
|
55
|
+
if (typeof timing !== "string" || !TIMINGS.has(timing)) {
|
|
56
|
+
throw fail("timing", "timing must be \"beforeChange\" or \"afterChange\"");
|
|
57
|
+
}
|
|
58
|
+
const operations = config.operations;
|
|
59
|
+
if (!Array.isArray(operations) || operations.length === 0) {
|
|
60
|
+
throw fail("operations", "operations must be a non-empty array of \"create\", \"update\" or \"delete\"");
|
|
61
|
+
}
|
|
62
|
+
const seenOperations = new Set();
|
|
63
|
+
for (const operation of operations) {
|
|
64
|
+
if (typeof operation !== "string" || !OPERATIONS.has(operation)) {
|
|
65
|
+
throw fail("operations", "operations must only contain \"create\", \"update\" or \"delete\"");
|
|
66
|
+
}
|
|
67
|
+
if (seenOperations.has(operation)) {
|
|
68
|
+
throw fail("operations", `operations contains the duplicate value '${operation}'`);
|
|
69
|
+
}
|
|
70
|
+
seenOperations.add(operation);
|
|
71
|
+
}
|
|
72
|
+
const fields = slugList(config.fields, "fields", 1, MAX_FIELDS, fail);
|
|
73
|
+
let changedFields;
|
|
74
|
+
if (config.changedFields !== undefined) {
|
|
75
|
+
if (!seenOperations.has("update")) {
|
|
76
|
+
throw fail("changedFields", "changedFields requires the \"update\" operation");
|
|
77
|
+
}
|
|
78
|
+
changedFields = slugList(config.changedFields, "changedFields", 1, MAX_FIELDS, fail);
|
|
79
|
+
}
|
|
80
|
+
const runWhen = config.runWhen === undefined ? "always" : config.runWhen;
|
|
81
|
+
if (typeof runWhen !== "string" || !RUN_WHEN.has(runWhen)) {
|
|
82
|
+
throw fail("runWhen", "runWhen must be \"always\" or \"onEnter\"");
|
|
83
|
+
}
|
|
84
|
+
let when;
|
|
85
|
+
if (config.when !== undefined) {
|
|
86
|
+
when = normalizeFilter(config.when, 1, { conditions: 0 }, fail);
|
|
87
|
+
}
|
|
88
|
+
else if (runWhen === "onEnter") {
|
|
89
|
+
throw fail("runWhen", "runWhen \"onEnter\" requires a when filter");
|
|
90
|
+
}
|
|
91
|
+
const writableFields = config.writableFields === undefined
|
|
92
|
+
? []
|
|
93
|
+
: slugList(config.writableFields, "writableFields", 0, MAX_WRITABLE_FIELDS, fail);
|
|
94
|
+
if (writableFields.length > 0) {
|
|
95
|
+
if (timing !== "beforeChange") {
|
|
96
|
+
throw fail("writableFields", "writableFields is only supported by beforeChange triggers");
|
|
97
|
+
}
|
|
98
|
+
if (seenOperations.size === 1 && seenOperations.has("delete")) {
|
|
99
|
+
throw fail("writableFields", "writableFields must be empty when the only operation is \"delete\"");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const order = integerOption(config.order, "order", MIN_ORDER, MAX_ORDER, DEFAULT_ORDER, fail);
|
|
103
|
+
const timeoutMs = integerOption(config.timeoutMs, "timeoutMs", MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS, DEFAULT_TIMEOUT_MILLIS, fail);
|
|
104
|
+
// Key order follows the manifest contract; absent optional keys are omitted, never undefined.
|
|
105
|
+
const manifest = {
|
|
106
|
+
key,
|
|
107
|
+
...(name === undefined ? {} : { name }),
|
|
108
|
+
object,
|
|
109
|
+
timing: timing,
|
|
110
|
+
operations: [...operations],
|
|
111
|
+
fields,
|
|
112
|
+
...(changedFields === undefined ? {} : { changedFields }),
|
|
113
|
+
...(when === undefined ? {} : { when }),
|
|
114
|
+
runWhen: runWhen,
|
|
115
|
+
writableFields,
|
|
116
|
+
order,
|
|
117
|
+
timeoutMs,
|
|
118
|
+
};
|
|
119
|
+
return deepFreeze(manifest);
|
|
120
|
+
}
|
|
121
|
+
function slugList(value, option, minimum, maximum, fail) {
|
|
122
|
+
if (!Array.isArray(value) || value.length < minimum || value.length > maximum) {
|
|
123
|
+
throw fail(option, minimum === 0
|
|
124
|
+
? `${option} must be an array of at most ${maximum} field slugs`
|
|
125
|
+
: `${option} must be an array of ${minimum} to ${maximum} field slugs`);
|
|
126
|
+
}
|
|
127
|
+
const seen = new Set();
|
|
128
|
+
for (const slug of value) {
|
|
129
|
+
if (typeof slug !== "string" || !TRIGGER_SLUG.test(slug)) {
|
|
130
|
+
throw fail(option, `${option} contains the invalid field slug '${String(slug)}'`);
|
|
131
|
+
}
|
|
132
|
+
if (seen.has(slug))
|
|
133
|
+
throw fail(option, `${option} contains the duplicate field slug '${slug}'`);
|
|
134
|
+
seen.add(slug);
|
|
135
|
+
}
|
|
136
|
+
return [...seen];
|
|
137
|
+
}
|
|
138
|
+
function integerOption(value, option, minimum, maximum, fallback, fail) {
|
|
139
|
+
if (value === undefined)
|
|
140
|
+
return fallback;
|
|
141
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > maximum) {
|
|
142
|
+
throw fail(option, `${option} must be an integer between ${minimum} and ${maximum}`);
|
|
143
|
+
}
|
|
144
|
+
return value;
|
|
145
|
+
}
|
|
146
|
+
function normalizeFilter(value, depth, counter, fail) {
|
|
147
|
+
if (depth > MAX_FILTER_DEPTH) {
|
|
148
|
+
throw fail("when", `when must not be nested deeper than ${MAX_FILTER_DEPTH} levels`);
|
|
149
|
+
}
|
|
150
|
+
if (!isRecord(value)) {
|
|
151
|
+
throw fail("when", "when must be a filter object such as { op: \"=\", field: \"status\", params: \"new\" }");
|
|
152
|
+
}
|
|
153
|
+
if ("kind" in value) {
|
|
154
|
+
throw fail("when", "when uses the { op, field, params } filter format; "
|
|
155
|
+
+ "expressions built with and(), or() or field references are not supported here");
|
|
156
|
+
}
|
|
157
|
+
const op = value.op;
|
|
158
|
+
if (typeof op === "string" && GROUP_OPERATORS.has(op)) {
|
|
159
|
+
rejectUnknownKeys(value, ["op", "conditions"], fail);
|
|
160
|
+
const conditions = value.conditions;
|
|
161
|
+
if (!Array.isArray(conditions) || conditions.length === 0) {
|
|
162
|
+
throw fail("when", `a when "${op}" group requires a non-empty conditions array`);
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
op: op,
|
|
166
|
+
conditions: conditions
|
|
167
|
+
.map(condition => normalizeFilter(condition, depth + 1, counter, fail)),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
if (typeof op !== "string" || !CONDITION_OPERATORS.has(op)) {
|
|
171
|
+
throw fail("when", `when contains the unsupported operator '${String(op)}'`);
|
|
172
|
+
}
|
|
173
|
+
rejectUnknownKeys(value, ["op", "field", "params"], fail);
|
|
174
|
+
if (++counter.conditions > MAX_FILTER_CONDITIONS) {
|
|
175
|
+
throw fail("when", `when supports at most ${MAX_FILTER_CONDITIONS} conditions`);
|
|
176
|
+
}
|
|
177
|
+
const field = value.field;
|
|
178
|
+
if (typeof field !== "string" || !TRIGGER_SLUG.test(field)) {
|
|
179
|
+
throw fail("when", `when contains the invalid field slug '${String(field)}'`);
|
|
180
|
+
}
|
|
181
|
+
const operator = op;
|
|
182
|
+
const params = value.params;
|
|
183
|
+
if (operator === "is null" || operator === "not null") {
|
|
184
|
+
if (params !== undefined && params !== null) {
|
|
185
|
+
throw fail("when", `the when operator "${operator}" does not accept params`);
|
|
186
|
+
}
|
|
187
|
+
return { op: operator, field };
|
|
188
|
+
}
|
|
189
|
+
if (params === undefined || params === null) {
|
|
190
|
+
throw fail("when", `the when operator "${operator}" requires params`);
|
|
191
|
+
}
|
|
192
|
+
if (operator === "in" || operator === "not in" || operator === "between") {
|
|
193
|
+
if (!Array.isArray(params) || params.length === 0) {
|
|
194
|
+
throw fail("when", `the when operator "${operator}" requires a non-empty params array`);
|
|
195
|
+
}
|
|
196
|
+
if (operator === "between" && params.length !== 2) {
|
|
197
|
+
throw fail("when", "the when operator \"between\" requires exactly two params");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
return { op: operator, field, params: toJsonValue(params, "params") };
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
throw fail("when", `the when params of field '${field}' are invalid: ${errorMessage(error)}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function rejectUnknownKeys(value, allowed, fail) {
|
|
208
|
+
for (const key of Object.keys(value)) {
|
|
209
|
+
if (!allowed.includes(key))
|
|
210
|
+
throw fail("when", `when contains the unknown key '${key}'`);
|
|
211
|
+
}
|
|
212
|
+
}
|