@cogover/sdk 0.1.2 → 0.6.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 +347 -24
- package/dist/data.d.ts +49 -0
- package/dist/data.js +170 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +72 -0
- package/dist/fetch.d.ts +28 -0
- package/dist/fetch.js +96 -0
- package/dist/index.d.ts +23 -3
- package/dist/index.js +8 -5
- package/dist/internal/bridge.js +48 -0
- package/dist/internal/invocation.js +57 -0
- package/dist/internal/json.js +81 -0
- package/dist/internal/request.js +87 -0
- package/dist/internal/trigger-config.js +212 -0
- package/dist/internal/trigger-runtime.js +211 -0
- package/dist/internal/validation.js +28 -0
- package/dist/internal/values.js +6 -0
- package/dist/invocation.d.ts +40 -0
- package/dist/invocation.js +1 -0
- package/dist/legacy.d.ts +2 -0
- package/dist/legacy.js +4 -0
- package/dist/locks.d.ts +19 -0
- package/dist/locks.js +68 -0
- package/dist/logger.d.ts +6 -0
- package/dist/logger.js +14 -0
- package/dist/query.d.ts +52 -0
- package/dist/query.js +59 -0
- package/dist/records.d.ts +79 -0
- package/dist/records.js +1 -0
- package/dist/request.d.ts +18 -0
- package/dist/request.js +1 -0
- package/dist/response.d.ts +21 -0
- package/dist/response.js +108 -0
- package/dist/router.d.ts +13 -0
- package/dist/router.js +104 -0
- package/dist/schema.d.ts +26 -0
- package/dist/schema.js +11 -0
- package/dist/script.d.ts +23 -0
- package/dist/script.js +56 -0
- package/dist/state.d.ts +24 -0
- package/dist/state.js +91 -0
- package/dist/trigger.d.ts +121 -0
- package/dist/trigger.js +15 -0
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +1 -0
- package/docs/en/api-reference.md +1415 -0
- package/docs/en/usage-guide.md +495 -0
- package/package.json +17 -5
- package/scripts/generate-workspace-types.mjs +135 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { createDataApi } from "../data.js";
|
|
2
|
+
import { ValidationError } from "../errors.js";
|
|
3
|
+
import { installCogoverFetch } from "../fetch.js";
|
|
4
|
+
import { SCRIPT_LOGGER } from "../logger.js";
|
|
5
|
+
import { createSchemaApi } from "../schema.js";
|
|
6
|
+
import { invocationContext } from "./invocation.js";
|
|
7
|
+
import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
|
|
8
|
+
import { TRIGGER_SLUG } from "./trigger-config.js";
|
|
9
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
10
|
+
const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
11
|
+
const MAX_ERROR_MESSAGE_LENGTH = 500;
|
|
12
|
+
// Both spellings of a timing and an operation are accepted; project code only ever sees the SDK literals.
|
|
13
|
+
const TIMINGS = new Map([
|
|
14
|
+
["beforeChange", "beforeChange"],
|
|
15
|
+
["BEFORE_CHANGE", "beforeChange"],
|
|
16
|
+
["afterChange", "afterChange"],
|
|
17
|
+
["AFTER_CHANGE", "afterChange"],
|
|
18
|
+
]);
|
|
19
|
+
const OPERATIONS = new Map([
|
|
20
|
+
["create", "create"],
|
|
21
|
+
["CREATE", "create"],
|
|
22
|
+
["update", "update"],
|
|
23
|
+
["UPDATE", "update"],
|
|
24
|
+
["delete", "delete"],
|
|
25
|
+
["DELETE", "delete"],
|
|
26
|
+
]);
|
|
27
|
+
export function createTriggerSandboxHandler(manifest, handler) {
|
|
28
|
+
const writableFields = new Set(manifest.writableFields);
|
|
29
|
+
return async (inputJson) => {
|
|
30
|
+
installCogoverFetch();
|
|
31
|
+
let input;
|
|
32
|
+
try {
|
|
33
|
+
input = JSON.parse(inputJson);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
throw new ValidationError("Trigger input must be valid JSON", errorMessage(error));
|
|
37
|
+
}
|
|
38
|
+
if (!isRecord(input))
|
|
39
|
+
throw new ValidationError("Trigger input must be a JSON object");
|
|
40
|
+
const trigger = triggerInfo(input, manifest);
|
|
41
|
+
const entries = recordEntries(input.records, trigger.operation);
|
|
42
|
+
let invocation;
|
|
43
|
+
await handler(Object.freeze({
|
|
44
|
+
records: Object.freeze(entries.map(entry => entry.record)),
|
|
45
|
+
trigger,
|
|
46
|
+
get invocation() {
|
|
47
|
+
return invocation ??= invocationContext(input);
|
|
48
|
+
},
|
|
49
|
+
data: createDataApi(),
|
|
50
|
+
schema: createSchemaApi(),
|
|
51
|
+
log: SCRIPT_LOGGER,
|
|
52
|
+
}));
|
|
53
|
+
const results = [];
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
// Always diff: changing a field outside writableFields is a bug even on a rejected record.
|
|
56
|
+
const changes = recordChanges(entry, manifest.key, writableFields);
|
|
57
|
+
if (entry.errors.length > 0) {
|
|
58
|
+
results.push({ key: entry.key, errors: entry.errors });
|
|
59
|
+
}
|
|
60
|
+
else if (changes !== null) {
|
|
61
|
+
results.push({ key: entry.key, changes });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return JSON.stringify({ results });
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function triggerInfo(input, manifest) {
|
|
68
|
+
const context = isRecord(input.__context) ? input.__context : undefined;
|
|
69
|
+
const raw = context !== undefined && isRecord(context.trigger) ? context.trigger : undefined;
|
|
70
|
+
if (raw === undefined) {
|
|
71
|
+
throw new ValidationError("Trigger metadata is unavailable outside Cogover Runtime");
|
|
72
|
+
}
|
|
73
|
+
const timing = TIMINGS.get(raw.timing);
|
|
74
|
+
const operation = OPERATIONS.get(raw.operation);
|
|
75
|
+
if (timing === undefined)
|
|
76
|
+
throw new ValidationError("Invalid trigger timing metadata");
|
|
77
|
+
if (operation === undefined)
|
|
78
|
+
throw new ValidationError("Invalid trigger operation metadata");
|
|
79
|
+
const info = Object.freeze({
|
|
80
|
+
id: requiredString(raw.id, "id"),
|
|
81
|
+
key: requiredString(raw.key, "key"),
|
|
82
|
+
timing,
|
|
83
|
+
operation,
|
|
84
|
+
objectSlug: requiredString(raw.objectSlug, "objectSlug"),
|
|
85
|
+
changeId: requiredString(raw.changeId, "changeId"),
|
|
86
|
+
});
|
|
87
|
+
// A mismatch means the call was routed to a definition it was not registered for.
|
|
88
|
+
if (info.key !== manifest.key || info.timing !== manifest.timing
|
|
89
|
+
|| info.objectSlug !== manifest.object || !manifest.operations.includes(info.operation)) {
|
|
90
|
+
throw new ValidationError(`Trigger input for '${info.key}' (${info.timing} ${info.operation} on '${info.objectSlug}') `
|
|
91
|
+
+ `does not match the definition of '${manifest.key}' `
|
|
92
|
+
+ `(${manifest.timing} ${manifest.operations.join("/")} on '${manifest.object}')`);
|
|
93
|
+
}
|
|
94
|
+
return info;
|
|
95
|
+
}
|
|
96
|
+
function requiredString(value, name) {
|
|
97
|
+
if (typeof value !== "string" || value === "") {
|
|
98
|
+
throw new ValidationError(`Invalid trigger ${name} metadata`);
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
function recordEntries(records, operation) {
|
|
103
|
+
if (!Array.isArray(records))
|
|
104
|
+
throw new ValidationError("Trigger input records must be an array");
|
|
105
|
+
const keys = new Set();
|
|
106
|
+
return records.map((raw, index) => {
|
|
107
|
+
const invalid = (reason) => new ValidationError(`Trigger input record at index ${index} is invalid: ${reason}`);
|
|
108
|
+
if (!isRecord(raw))
|
|
109
|
+
throw invalid("it must be an object");
|
|
110
|
+
const key = raw.key;
|
|
111
|
+
if (typeof key !== "string" || key === "")
|
|
112
|
+
throw invalid("key must be a non-empty string");
|
|
113
|
+
if (keys.has(key))
|
|
114
|
+
throw invalid(`duplicate key '${key}'`);
|
|
115
|
+
keys.add(key);
|
|
116
|
+
if (raw.id !== undefined && raw.id !== null && typeof raw.id !== "string") {
|
|
117
|
+
throw invalid("id must be a string or null");
|
|
118
|
+
}
|
|
119
|
+
// An omitted value means null: JSON writers commonly drop null properties.
|
|
120
|
+
const current = fieldValues(raw.new, "new", invalid);
|
|
121
|
+
const old = fieldValues(raw.old, "old", invalid);
|
|
122
|
+
if ((operation === "delete") !== (current === null)) {
|
|
123
|
+
throw invalid(operation === "delete"
|
|
124
|
+
? "new must be null when the operation is delete"
|
|
125
|
+
: `new is required when the operation is ${operation}`);
|
|
126
|
+
}
|
|
127
|
+
if ((operation === "create") !== (old === null)) {
|
|
128
|
+
throw invalid(operation === "create"
|
|
129
|
+
? "old must be null when the operation is create"
|
|
130
|
+
: `old is required when the operation is ${operation}`);
|
|
131
|
+
}
|
|
132
|
+
const changedFields = raw.changedFields ?? [];
|
|
133
|
+
if (!Array.isArray(changedFields) || changedFields.some(field => typeof field !== "string")) {
|
|
134
|
+
throw invalid("changedFields must be an array of field slugs");
|
|
135
|
+
}
|
|
136
|
+
const errors = [];
|
|
137
|
+
const record = {
|
|
138
|
+
key,
|
|
139
|
+
id: typeof raw.id === "string" ? raw.id : null,
|
|
140
|
+
get new() {
|
|
141
|
+
return current;
|
|
142
|
+
},
|
|
143
|
+
set new(_value) {
|
|
144
|
+
throw new ValidationError(current === null
|
|
145
|
+
? "A record that is being deleted has no new values and cannot be modified"
|
|
146
|
+
: "record.new cannot be replaced; assign its fields instead, for example record.new.status = \"approved\"");
|
|
147
|
+
},
|
|
148
|
+
old: deepFreeze(old),
|
|
149
|
+
changedFields: deepFreeze([...changedFields]),
|
|
150
|
+
addError(field, code, message) {
|
|
151
|
+
errors.push(recordError(field, code, message));
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
return {
|
|
155
|
+
key,
|
|
156
|
+
record: Object.freeze(record),
|
|
157
|
+
current,
|
|
158
|
+
snapshot: current === null ? null : cloneJson(current),
|
|
159
|
+
errors,
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
function fieldValues(value, name, invalid) {
|
|
164
|
+
if (value === undefined || value === null)
|
|
165
|
+
return null;
|
|
166
|
+
if (!isRecord(value))
|
|
167
|
+
throw invalid(`${name} must be an object or null`);
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
function recordError(field, code, message) {
|
|
171
|
+
if (field !== null && (typeof field !== "string" || !TRIGGER_SLUG.test(field))) {
|
|
172
|
+
throw new ValidationError("addError() field must be a valid field slug, or null for a record-level error");
|
|
173
|
+
}
|
|
174
|
+
if (typeof code !== "string" || !ERROR_CODE.test(code)) {
|
|
175
|
+
throw new ValidationError("addError() code must start with an upper-case letter and contain "
|
|
176
|
+
+ "at most 64 upper-case letters, digits or underscores, for example AMOUNT_TOO_LARGE");
|
|
177
|
+
}
|
|
178
|
+
if (message === undefined || message === null || message === "")
|
|
179
|
+
return { field, code };
|
|
180
|
+
if (typeof message !== "string" || message.length > MAX_ERROR_MESSAGE_LENGTH) {
|
|
181
|
+
throw new ValidationError(`addError() message must be a string of at most ${MAX_ERROR_MESSAGE_LENGTH} characters`);
|
|
182
|
+
}
|
|
183
|
+
return { field, code, message };
|
|
184
|
+
}
|
|
185
|
+
/** Top-level diff of record.new against its snapshot, or null when the handler changed nothing. */
|
|
186
|
+
function recordChanges(entry, triggerKey, writableFields) {
|
|
187
|
+
const { current, snapshot } = entry;
|
|
188
|
+
if (current === null || snapshot === null)
|
|
189
|
+
return null;
|
|
190
|
+
// A null prototype keeps every field slug, including "__proto__", an ordinary own property.
|
|
191
|
+
const changes = Object.create(null);
|
|
192
|
+
let changed = false;
|
|
193
|
+
for (const field of new Set([...Object.keys(snapshot), ...Object.keys(current)])) {
|
|
194
|
+
const existed = Object.prototype.hasOwnProperty.call(snapshot, field);
|
|
195
|
+
const assigned = Object.prototype.hasOwnProperty.call(current, field) ? current[field] : undefined;
|
|
196
|
+
if (assigned === undefined && !existed)
|
|
197
|
+
continue;
|
|
198
|
+
// Deleting a field or assigning undefined clears it.
|
|
199
|
+
const after = assigned === undefined
|
|
200
|
+
? null
|
|
201
|
+
: toJsonValue(assigned, `Trigger '${triggerKey}': the value assigned to field '${field}'`);
|
|
202
|
+
if (existed && jsonEquals(snapshot[field], after))
|
|
203
|
+
continue;
|
|
204
|
+
if (!writableFields.has(field)) {
|
|
205
|
+
throw new ValidationError(`Trigger '${triggerKey}' changed field '${field}', which is not listed in writableFields`, { triggerKey, field, recordKey: entry.key });
|
|
206
|
+
}
|
|
207
|
+
changes[field] = after;
|
|
208
|
+
changed = true;
|
|
209
|
+
}
|
|
210
|
+
return changed ? changes : null;
|
|
211
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { ValidationError } from "../errors.js";
|
|
2
|
+
import { isRecord } from "./values.js";
|
|
3
|
+
export function requireSlug(value) {
|
|
4
|
+
const slug = requireText(value, "object slug");
|
|
5
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(slug)) {
|
|
6
|
+
throw new ValidationError(`Invalid object slug '${slug}'`);
|
|
7
|
+
}
|
|
8
|
+
return slug;
|
|
9
|
+
}
|
|
10
|
+
export function requireFieldSlug(value, name = "field slug") {
|
|
11
|
+
const slug = requireText(value, name);
|
|
12
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(slug)) {
|
|
13
|
+
throw new ValidationError(`Invalid ${name} '${slug}'`);
|
|
14
|
+
}
|
|
15
|
+
return slug;
|
|
16
|
+
}
|
|
17
|
+
export function requireText(value, name) {
|
|
18
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
19
|
+
throw new ValidationError(`${name} must be a non-empty string`);
|
|
20
|
+
}
|
|
21
|
+
return value.trim();
|
|
22
|
+
}
|
|
23
|
+
export function requireFields(fields) {
|
|
24
|
+
if (!isRecord(fields) || Object.keys(fields).length === 0) {
|
|
25
|
+
throw new ValidationError("Record fields must be a non-empty object");
|
|
26
|
+
}
|
|
27
|
+
return fields;
|
|
28
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Public workspace metadata provided for the current invocation. */
|
|
2
|
+
export interface CurrentWorkspace {
|
|
3
|
+
readonly id: string;
|
|
4
|
+
readonly name?: string;
|
|
5
|
+
readonly domain?: string;
|
|
6
|
+
readonly language?: string;
|
|
7
|
+
readonly timezone?: string;
|
|
8
|
+
readonly dateFormat?: string;
|
|
9
|
+
readonly timeFormat?: string;
|
|
10
|
+
readonly numberFormat?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Public membership metadata for the current user in the current workspace. */
|
|
13
|
+
export interface CurrentWorkspaceMembership {
|
|
14
|
+
readonly personnelId?: string;
|
|
15
|
+
readonly language?: string;
|
|
16
|
+
readonly timezone?: string;
|
|
17
|
+
}
|
|
18
|
+
/** Public account metadata for the authenticated user who initiated the invocation. */
|
|
19
|
+
export interface CurrentUser {
|
|
20
|
+
readonly accountId: string;
|
|
21
|
+
readonly email?: string;
|
|
22
|
+
readonly firstName?: string;
|
|
23
|
+
readonly lastName?: string;
|
|
24
|
+
readonly avatar?: string;
|
|
25
|
+
readonly language?: string;
|
|
26
|
+
readonly timezone?: string;
|
|
27
|
+
readonly membership: CurrentWorkspaceMembership;
|
|
28
|
+
}
|
|
29
|
+
export interface UserInvocationContext {
|
|
30
|
+
readonly identity: "user";
|
|
31
|
+
readonly workspace: CurrentWorkspace;
|
|
32
|
+
readonly user: CurrentUser;
|
|
33
|
+
}
|
|
34
|
+
export interface SystemInvocationContext {
|
|
35
|
+
readonly identity: "system";
|
|
36
|
+
readonly workspace: CurrentWorkspace;
|
|
37
|
+
readonly user: null;
|
|
38
|
+
}
|
|
39
|
+
/** Immutable authenticated identity and workspace snapshot for one execution. */
|
|
40
|
+
export type InvocationContext = UserInvocationContext | SystemInvocationContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/legacy.d.ts
ADDED
package/dist/legacy.js
ADDED
package/dist/locks.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface LockOptions {
|
|
2
|
+
readonly namespace?: string;
|
|
3
|
+
readonly waitMs?: number;
|
|
4
|
+
readonly leaseMs?: number;
|
|
5
|
+
}
|
|
6
|
+
export interface LockLease {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly key: string;
|
|
9
|
+
readonly namespace: string;
|
|
10
|
+
readonly fencingToken: number;
|
|
11
|
+
readonly expiresAt: number;
|
|
12
|
+
renew(leaseMs?: number): Promise<void>;
|
|
13
|
+
release(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export interface DistributedLocks {
|
|
16
|
+
acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
|
|
17
|
+
withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
18
|
+
withLock<T>(key: string, options: LockOptions, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
19
|
+
}
|
package/dist/locks.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { LockUnavailableError, ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { optionalInteger, validateName } from "./state.js";
|
|
4
|
+
const DEFAULT_NAMESPACE = "default";
|
|
5
|
+
const DEFAULT_LEASE_MILLIS = 30_000;
|
|
6
|
+
const MIN_LEASE_MILLIS = 5_000;
|
|
7
|
+
const MAX_LEASE_MILLIS = 60_000;
|
|
8
|
+
const MAX_WAIT_MILLIS = 10_000;
|
|
9
|
+
/** @internal */
|
|
10
|
+
export function createLocksApi() {
|
|
11
|
+
const api = {
|
|
12
|
+
async acquire(key, options) {
|
|
13
|
+
const lockKey = validateName(key, "lock key", 255);
|
|
14
|
+
const namespace = options?.namespace === undefined
|
|
15
|
+
? DEFAULT_NAMESPACE
|
|
16
|
+
: validateName(options.namespace, "lock namespace", 128);
|
|
17
|
+
const waitMs = optionalInteger(options?.waitMs, "waitMs", 0, MAX_WAIT_MILLIS) ?? 0;
|
|
18
|
+
const leaseMs = optionalInteger(options?.leaseMs, "leaseMs", MIN_LEASE_MILLIS, MAX_LEASE_MILLIS) ?? DEFAULT_LEASE_MILLIS;
|
|
19
|
+
const payload = await callBridge("locks.acquire", {
|
|
20
|
+
namespace, key: lockKey, waitMs, leaseMs,
|
|
21
|
+
});
|
|
22
|
+
return payload === null ? null : lease(payload, lockKey, namespace);
|
|
23
|
+
},
|
|
24
|
+
async withLock(key, optionsOrCallback, maybeCallback) {
|
|
25
|
+
const options = typeof optionsOrCallback === "function" ? undefined : optionsOrCallback;
|
|
26
|
+
const callback = typeof optionsOrCallback === "function" ? optionsOrCallback : maybeCallback;
|
|
27
|
+
if (typeof callback !== "function") {
|
|
28
|
+
throw new ValidationError("locks.withLock() requires a callback function");
|
|
29
|
+
}
|
|
30
|
+
const acquired = await api.acquire(key, options);
|
|
31
|
+
if (acquired === null)
|
|
32
|
+
throw new LockUnavailableError(key);
|
|
33
|
+
try {
|
|
34
|
+
return await callback(acquired);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
await acquired.release();
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
return Object.freeze(api);
|
|
42
|
+
}
|
|
43
|
+
function lease(initial, key, namespace) {
|
|
44
|
+
let current = initial;
|
|
45
|
+
let released = false;
|
|
46
|
+
return Object.freeze({
|
|
47
|
+
get id() { return current.id; },
|
|
48
|
+
key,
|
|
49
|
+
namespace,
|
|
50
|
+
get fencingToken() { return current.fencingToken; },
|
|
51
|
+
get expiresAt() { return current.expiresAt; },
|
|
52
|
+
async renew(leaseMs) {
|
|
53
|
+
if (released)
|
|
54
|
+
throw new ValidationError("Cannot renew a released lock lease");
|
|
55
|
+
const duration = optionalInteger(leaseMs, "leaseMs", MIN_LEASE_MILLIS, MAX_LEASE_MILLIS) ?? DEFAULT_LEASE_MILLIS;
|
|
56
|
+
current = await callBridge("locks.renew", {
|
|
57
|
+
leaseId: current.id,
|
|
58
|
+
leaseMs: duration,
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
async release() {
|
|
62
|
+
if (released)
|
|
63
|
+
return;
|
|
64
|
+
await callBridge("locks.release", { leaseId: current.id });
|
|
65
|
+
released = true;
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
package/dist/logger.d.ts
ADDED
package/dist/logger.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
function writeLog(level, message, details) {
|
|
2
|
+
if (details === undefined) {
|
|
3
|
+
console.log(`[${level}] ${message}`);
|
|
4
|
+
return;
|
|
5
|
+
}
|
|
6
|
+
console.log(`[${level}] ${message}`, details);
|
|
7
|
+
}
|
|
8
|
+
/** @internal */
|
|
9
|
+
export const SCRIPT_LOGGER = Object.freeze({
|
|
10
|
+
debug: (message, details) => writeLog("DEBUG", message, details),
|
|
11
|
+
info: (message, details) => writeLog("INFO", message, details),
|
|
12
|
+
warn: (message, details) => writeLog("WARN", message, details),
|
|
13
|
+
error: (message, details) => writeLog("ERROR", message, details),
|
|
14
|
+
});
|