@20baht/runs 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +123 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/pg.d.ts +530 -0
- package/dist/pg.js +416 -0
- package/dist/types.d.ts +182 -0
- package/dist/types.js +11 -0
- package/package.json +69 -4
package/dist/pg.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
import { advanceRun, approvalCommentRequired, askedTargets, settleStep, updateWorkflow, } from '@20baht/engine';
|
|
2
|
+
import { parseSchema, validateWorkflowData } from '@20baht/validator';
|
|
3
|
+
import { and, asc, eq, inArray, or } from 'drizzle-orm';
|
|
4
|
+
import { index, jsonb, pgTable, text, timestamp, } from 'drizzle-orm/pg-core';
|
|
5
|
+
export * from './index.js';
|
|
6
|
+
export function runTables(options = {}) {
|
|
7
|
+
const prefix = options.prefix ?? 'baht_';
|
|
8
|
+
const at = () => timestamp({ withTimezone: true });
|
|
9
|
+
const definitions = pgTable(`${prefix}run_definitions`, {
|
|
10
|
+
hash: text().primaryKey(),
|
|
11
|
+
workflow_id: text().notNull(),
|
|
12
|
+
definition: jsonb().$type().notNull(),
|
|
13
|
+
created_at: at().notNull(),
|
|
14
|
+
});
|
|
15
|
+
const runs = pgTable(`${prefix}runs`, {
|
|
16
|
+
id: text().primaryKey(),
|
|
17
|
+
workflow_id: text().notNull(),
|
|
18
|
+
definition_hash: text()
|
|
19
|
+
.notNull()
|
|
20
|
+
.references(() => definitions.hash),
|
|
21
|
+
status: text().$type().notNull(),
|
|
22
|
+
form_name: text().notNull(),
|
|
23
|
+
data: jsonb().$type().notNull(),
|
|
24
|
+
requester: text().notNull(),
|
|
25
|
+
created_at: at().notNull(),
|
|
26
|
+
updated_at: at().notNull(),
|
|
27
|
+
}, (table) => [
|
|
28
|
+
index(`${prefix}runs_requester_idx`).on(table.requester, table.status),
|
|
29
|
+
]);
|
|
30
|
+
const tasks = pgTable(`${prefix}run_tasks`, {
|
|
31
|
+
id: text().primaryKey(),
|
|
32
|
+
run_id: text()
|
|
33
|
+
.notNull()
|
|
34
|
+
.references(() => runs.id),
|
|
35
|
+
form_name: text().notNull(),
|
|
36
|
+
label: text().notNull(),
|
|
37
|
+
assignee: text(),
|
|
38
|
+
position: text(),
|
|
39
|
+
target: jsonb().$type(),
|
|
40
|
+
state: text().$type().notNull(),
|
|
41
|
+
decision: text().$type(),
|
|
42
|
+
comment: text(),
|
|
43
|
+
claimed_by: text(),
|
|
44
|
+
decided_by: text(),
|
|
45
|
+
decided_at: at(),
|
|
46
|
+
evidence: text(),
|
|
47
|
+
created_at: at().notNull(),
|
|
48
|
+
}, (table) => [
|
|
49
|
+
index(`${prefix}run_tasks_assignee_idx`).on(table.assignee, table.state),
|
|
50
|
+
index(`${prefix}run_tasks_position_idx`).on(table.position, table.state),
|
|
51
|
+
index(`${prefix}run_tasks_step_idx`).on(table.run_id, table.form_name),
|
|
52
|
+
]);
|
|
53
|
+
return { definitions, runs, tasks };
|
|
54
|
+
}
|
|
55
|
+
class Refusal extends Error {
|
|
56
|
+
constructor(result) {
|
|
57
|
+
super(result.message);
|
|
58
|
+
this.result = result;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const refuse = (reason, message) => ({
|
|
62
|
+
ok: false,
|
|
63
|
+
reason,
|
|
64
|
+
message,
|
|
65
|
+
});
|
|
66
|
+
const WAITING = ['open', 'claimed'];
|
|
67
|
+
const COUNTED = ['open', 'claimed', 'done', 'unassigned'];
|
|
68
|
+
const BLOCKED = 'the run cannot move from this step: the only way on is hidden by the rules, or they never settle';
|
|
69
|
+
function canonical(value) {
|
|
70
|
+
if (Array.isArray(value))
|
|
71
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
72
|
+
if (typeof value !== 'object' || value === null)
|
|
73
|
+
return JSON.stringify(value);
|
|
74
|
+
const record = value;
|
|
75
|
+
const entries = Object.keys(record)
|
|
76
|
+
.sort()
|
|
77
|
+
.filter((key) => record[key] !== undefined)
|
|
78
|
+
.map((key) => `${JSON.stringify(key)}:${canonical(record[key])}`);
|
|
79
|
+
return `{${entries.join(',')}}`;
|
|
80
|
+
}
|
|
81
|
+
async function hashOf(definition) {
|
|
82
|
+
const bytes = new TextEncoder().encode(canonical(definition));
|
|
83
|
+
const digest = await crypto.subtle.digest('SHA-256', bytes);
|
|
84
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
85
|
+
}
|
|
86
|
+
const formOf = (definition, form_name) => definition.forms.find((form) => form.form_name === form_name);
|
|
87
|
+
function askedState(task) {
|
|
88
|
+
if (task.state === 'done' && task.decision !== null)
|
|
89
|
+
return task.decision;
|
|
90
|
+
return task.state === 'unassigned' ? 'unassigned' : 'waiting';
|
|
91
|
+
}
|
|
92
|
+
export function createRuns(options) {
|
|
93
|
+
const { db, tables, resolve, authorize } = options;
|
|
94
|
+
const { definitions, runs, tasks } = tables;
|
|
95
|
+
const now = options.now ?? (() => new Date());
|
|
96
|
+
const newId = options.newId ?? (() => crypto.randomUUID());
|
|
97
|
+
const lockRun = async (tx, run_id) => {
|
|
98
|
+
const [run] = await tx.select().from(runs).where(eq(runs.id, run_id)).for('update');
|
|
99
|
+
return run;
|
|
100
|
+
};
|
|
101
|
+
const definitionOf = async (tx, run) => {
|
|
102
|
+
const [row] = await tx
|
|
103
|
+
.select({ definition: definitions.definition })
|
|
104
|
+
.from(definitions)
|
|
105
|
+
.where(eq(definitions.hash, run.definition_hash));
|
|
106
|
+
if (!row)
|
|
107
|
+
throw new Error(`run ${run.id}: its definition ${run.definition_hash} is gone`);
|
|
108
|
+
return row.definition;
|
|
109
|
+
};
|
|
110
|
+
const supersede = (tx, run, form_name) => tx
|
|
111
|
+
.update(tasks)
|
|
112
|
+
.set({ state: 'superseded' })
|
|
113
|
+
.where(and(eq(tasks.run_id, run.id), eq(tasks.form_name, form_name), inArray(tasks.state, COUNTED)));
|
|
114
|
+
const tasksFor = async (run, form, target) => {
|
|
115
|
+
const base = {
|
|
116
|
+
run_id: run.id,
|
|
117
|
+
form_name: form.form_name,
|
|
118
|
+
target,
|
|
119
|
+
created_at: now(),
|
|
120
|
+
};
|
|
121
|
+
const label = form.assignment?.label ?? form.form_name;
|
|
122
|
+
const asked = await resolve(target, { run, form_name: form.form_name });
|
|
123
|
+
if (asked.length === 0) {
|
|
124
|
+
return [{ ...base, id: newId(), label, state: 'unassigned' }];
|
|
125
|
+
}
|
|
126
|
+
return asked.map((one) => ({
|
|
127
|
+
...base,
|
|
128
|
+
id: newId(),
|
|
129
|
+
label: one.label ?? label,
|
|
130
|
+
assignee: 'person' in one ? one.person : null,
|
|
131
|
+
position: 'position' in one ? one.position : null,
|
|
132
|
+
state: 'open',
|
|
133
|
+
}));
|
|
134
|
+
};
|
|
135
|
+
const openStep = async (tx, run, form) => {
|
|
136
|
+
await supersede(tx, run, form.form_name);
|
|
137
|
+
const rows = [];
|
|
138
|
+
if (form.assignment) {
|
|
139
|
+
for (const target of askedTargets(form.assignment, run.data)) {
|
|
140
|
+
rows.push(...(await tasksFor(run, form, target)));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
rows.push({
|
|
145
|
+
id: newId(),
|
|
146
|
+
run_id: run.id,
|
|
147
|
+
form_name: form.form_name,
|
|
148
|
+
label: form.form_name,
|
|
149
|
+
target: null,
|
|
150
|
+
state: 'open',
|
|
151
|
+
created_at: now(),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return rows.length === 0 ? [] : tx.insert(tasks).values(rows).returning();
|
|
155
|
+
};
|
|
156
|
+
const apply = async (tx, run, definition, advance) => {
|
|
157
|
+
const change = advance.kind === 'ended'
|
|
158
|
+
? { status: advance.status, data: advance.data }
|
|
159
|
+
: { form_name: advance.form_name, data: advance.data };
|
|
160
|
+
const [next] = await tx
|
|
161
|
+
.update(runs)
|
|
162
|
+
.set({ ...change, updated_at: now() })
|
|
163
|
+
.where(eq(runs.id, run.id))
|
|
164
|
+
.returning();
|
|
165
|
+
if (!next)
|
|
166
|
+
throw new Error(`run ${run.id} vanished while it was held`);
|
|
167
|
+
const form = next.status === 'active' ? formOf(definition, next.form_name) : undefined;
|
|
168
|
+
const opened = form?.kind === 'approval' ? await openStep(tx, next, form) : [];
|
|
169
|
+
return { ok: true, run: next, opened };
|
|
170
|
+
};
|
|
171
|
+
const submitIn = async (tx, run, definition, body) => {
|
|
172
|
+
const checked = validateWorkflowData(definition, body, options.registry, options.locale, {
|
|
173
|
+
form: run.form_name,
|
|
174
|
+
context: run.data,
|
|
175
|
+
});
|
|
176
|
+
if (!checked.valid) {
|
|
177
|
+
return {
|
|
178
|
+
ok: false,
|
|
179
|
+
reason: 'invalid',
|
|
180
|
+
message: `${run.form_name} has ${String(checked.issues.length)} issue(s)`,
|
|
181
|
+
issues: checked.issues,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const data = { ...run.data, [run.form_name]: checked.data };
|
|
185
|
+
const advance = advanceRun(definition, { form_name: run.form_name, data }, { type: 'next' });
|
|
186
|
+
if (advance.kind === 'stayed')
|
|
187
|
+
return refuse('blocked', BLOCKED);
|
|
188
|
+
return apply(tx, run, definition, advance);
|
|
189
|
+
};
|
|
190
|
+
const keep = async (tx, definition) => {
|
|
191
|
+
const hash = await hashOf(definition);
|
|
192
|
+
const [known] = await tx
|
|
193
|
+
.select({ hash: definitions.hash })
|
|
194
|
+
.from(definitions)
|
|
195
|
+
.where(eq(definitions.hash, hash));
|
|
196
|
+
if (!known) {
|
|
197
|
+
parseSchema(definition);
|
|
198
|
+
await tx
|
|
199
|
+
.insert(definitions)
|
|
200
|
+
.values({ hash, workflow_id: definition.workflow_id, definition, created_at: now() })
|
|
201
|
+
.onConflictDoNothing();
|
|
202
|
+
}
|
|
203
|
+
return hash;
|
|
204
|
+
};
|
|
205
|
+
const requirementOf = (run, task) => ({
|
|
206
|
+
target: task.target,
|
|
207
|
+
task,
|
|
208
|
+
run,
|
|
209
|
+
});
|
|
210
|
+
const held = async (tx, task_id) => {
|
|
211
|
+
const [seen] = await tx.select().from(tasks).where(eq(tasks.id, task_id));
|
|
212
|
+
const run = seen && (await lockRun(tx, seen.run_id));
|
|
213
|
+
if (!run)
|
|
214
|
+
return refuse('not-found', 'no such task');
|
|
215
|
+
const [task] = await tx.select().from(tasks).where(eq(tasks.id, task_id));
|
|
216
|
+
if (!task)
|
|
217
|
+
return refuse('not-found', 'no such task');
|
|
218
|
+
const waiting = WAITING.includes(task.state) && run.status === 'active';
|
|
219
|
+
if (!waiting || run.form_name !== task.form_name) {
|
|
220
|
+
return refuse('not-open', 'this task is no longer open');
|
|
221
|
+
}
|
|
222
|
+
return { run, task };
|
|
223
|
+
};
|
|
224
|
+
const allowed = async (run, task, by) => {
|
|
225
|
+
const verdict = await authorize(requirementOf(run, task), by);
|
|
226
|
+
if (verdict.verdict === 'denied')
|
|
227
|
+
throw new Refusal(refuse('denied', verdict.reason));
|
|
228
|
+
if (verdict.verdict === 'unavailable') {
|
|
229
|
+
throw new Refusal(refuse('unavailable', verdict.reason ?? 'who may decide could not be checked; try again'));
|
|
230
|
+
}
|
|
231
|
+
return verdict.evidence ?? null;
|
|
232
|
+
};
|
|
233
|
+
const transact = async (work) => {
|
|
234
|
+
try {
|
|
235
|
+
return await db.transaction(work);
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (error instanceof Refusal)
|
|
239
|
+
return error.result;
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const decideIn = async (tx, task_id, input) => {
|
|
244
|
+
const found = await held(tx, task_id);
|
|
245
|
+
if ('ok' in found)
|
|
246
|
+
return found;
|
|
247
|
+
const { run, task } = found;
|
|
248
|
+
if (task.state === 'claimed' && task.claimed_by !== input.by.id) {
|
|
249
|
+
return refuse('claimed', 'someone else has claimed this task');
|
|
250
|
+
}
|
|
251
|
+
const definition = await definitionOf(tx, run);
|
|
252
|
+
const form = formOf(definition, task.form_name);
|
|
253
|
+
const comment = input.comment?.trim() ?? '';
|
|
254
|
+
if (form && approvalCommentRequired(form, input.decision) && comment === '') {
|
|
255
|
+
return refuse('comment-required', 'this decision needs a comment');
|
|
256
|
+
}
|
|
257
|
+
const evidence = await allowed(run, task, input.by);
|
|
258
|
+
const [done] = await tx
|
|
259
|
+
.update(tasks)
|
|
260
|
+
.set({
|
|
261
|
+
state: 'done',
|
|
262
|
+
decision: input.decision,
|
|
263
|
+
comment: comment === '' ? null : comment,
|
|
264
|
+
decided_by: input.by.id,
|
|
265
|
+
decided_at: now(),
|
|
266
|
+
evidence,
|
|
267
|
+
})
|
|
268
|
+
.where(eq(tasks.id, task.id))
|
|
269
|
+
.returning();
|
|
270
|
+
if (!done)
|
|
271
|
+
throw new Error(`task ${task.id} vanished while its run was held`);
|
|
272
|
+
const step = await tx
|
|
273
|
+
.select()
|
|
274
|
+
.from(tasks)
|
|
275
|
+
.where(and(eq(tasks.run_id, run.id), eq(tasks.form_name, task.form_name), inArray(tasks.state, COUNTED)));
|
|
276
|
+
const outcome = settleStep(form?.assignment?.rule ?? 'any', step.map(askedState));
|
|
277
|
+
if (outcome === 'pending')
|
|
278
|
+
return { ok: true, outcome, task: done, run, opened: [] };
|
|
279
|
+
await tx
|
|
280
|
+
.update(tasks)
|
|
281
|
+
.set({ state: 'cancelled' })
|
|
282
|
+
.where(and(eq(tasks.run_id, run.id), eq(tasks.form_name, task.form_name), inArray(tasks.state, [...WAITING, 'unassigned'])));
|
|
283
|
+
const advance = advanceRun(definition, { form_name: run.form_name, data: run.data }, { type: 'decide', decision: outcome, ...(comment === '' ? {} : { comment }) });
|
|
284
|
+
if (advance.kind === 'stayed')
|
|
285
|
+
throw new Refusal(refuse('blocked', BLOCKED));
|
|
286
|
+
const moved = await apply(tx, run, definition, advance);
|
|
287
|
+
return { ...moved, outcome, task: done };
|
|
288
|
+
};
|
|
289
|
+
return {
|
|
290
|
+
start: (input) => transact(async (tx) => {
|
|
291
|
+
let hash;
|
|
292
|
+
try {
|
|
293
|
+
hash = await keep(tx, input.definition);
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
return refuse('invalid-definition', error instanceof Error ? error.message : String(error));
|
|
297
|
+
}
|
|
298
|
+
const snapshot = {
|
|
299
|
+
workflow_id: input.definition.workflow_id,
|
|
300
|
+
data: {},
|
|
301
|
+
current: null,
|
|
302
|
+
history: [],
|
|
303
|
+
ended: null,
|
|
304
|
+
};
|
|
305
|
+
const first = updateWorkflow(input.definition, null, { type: 'restore', snapshot }).state;
|
|
306
|
+
if (first.current === null)
|
|
307
|
+
return refuse('no-step', 'the workflow has no step to start on');
|
|
308
|
+
const at = now();
|
|
309
|
+
const [run] = await tx
|
|
310
|
+
.insert(runs)
|
|
311
|
+
.values({
|
|
312
|
+
id: newId(),
|
|
313
|
+
workflow_id: input.definition.workflow_id,
|
|
314
|
+
definition_hash: hash,
|
|
315
|
+
status: 'active',
|
|
316
|
+
form_name: first.current,
|
|
317
|
+
data: first.derived.data,
|
|
318
|
+
requester: input.requester,
|
|
319
|
+
created_at: at,
|
|
320
|
+
updated_at: at,
|
|
321
|
+
})
|
|
322
|
+
.returning();
|
|
323
|
+
if (!run)
|
|
324
|
+
throw new Error('the run was not stored');
|
|
325
|
+
const form = formOf(input.definition, run.form_name);
|
|
326
|
+
if (form?.kind === 'approval') {
|
|
327
|
+
return { ok: true, run, opened: await openStep(tx, run, form) };
|
|
328
|
+
}
|
|
329
|
+
if (input.data === undefined)
|
|
330
|
+
return { ok: true, run, opened: [] };
|
|
331
|
+
const submitted = await submitIn(tx, run, input.definition, input.data);
|
|
332
|
+
if (!submitted.ok)
|
|
333
|
+
throw new Refusal(submitted);
|
|
334
|
+
return submitted;
|
|
335
|
+
}),
|
|
336
|
+
submit: (run_id, input) => transact(async (tx) => {
|
|
337
|
+
const run = await lockRun(tx, run_id);
|
|
338
|
+
if (!run)
|
|
339
|
+
return refuse('not-found', 'no such run');
|
|
340
|
+
if (run.status !== 'active')
|
|
341
|
+
return refuse('not-active', `the run is ${run.status}`);
|
|
342
|
+
const definition = await definitionOf(tx, run);
|
|
343
|
+
if (formOf(definition, run.form_name)?.kind === 'approval') {
|
|
344
|
+
return refuse('not-a-form-step', `${run.form_name} waits for a decision, not a form`);
|
|
345
|
+
}
|
|
346
|
+
if (input.by !== run.requester) {
|
|
347
|
+
return refuse('denied', 'only whoever started the run submits its forms');
|
|
348
|
+
}
|
|
349
|
+
return submitIn(tx, run, definition, input.data);
|
|
350
|
+
}),
|
|
351
|
+
decide: (task_id, input) => transact((tx) => decideIn(tx, task_id, input)),
|
|
352
|
+
claim: (task_id, by) => transact(async (tx) => {
|
|
353
|
+
const found = await held(tx, task_id);
|
|
354
|
+
if ('ok' in found)
|
|
355
|
+
return found;
|
|
356
|
+
const { run, task } = found;
|
|
357
|
+
if (task.state === 'claimed') {
|
|
358
|
+
return task.claimed_by === by.id
|
|
359
|
+
? { ok: true, task }
|
|
360
|
+
: refuse('claimed', 'someone else has claimed this task');
|
|
361
|
+
}
|
|
362
|
+
if (task.assignee !== null) {
|
|
363
|
+
return refuse('not-claimable', 'this task is asked of a named person');
|
|
364
|
+
}
|
|
365
|
+
await allowed(run, task, by);
|
|
366
|
+
const [claimed] = await tx
|
|
367
|
+
.update(tasks)
|
|
368
|
+
.set({ state: 'claimed', claimed_by: by.id })
|
|
369
|
+
.where(eq(tasks.id, task.id))
|
|
370
|
+
.returning();
|
|
371
|
+
if (!claimed)
|
|
372
|
+
throw new Error(`task ${task.id} vanished while its run was held`);
|
|
373
|
+
return { ok: true, task: claimed };
|
|
374
|
+
}),
|
|
375
|
+
release: (task_id, by) => transact(async (tx) => {
|
|
376
|
+
const found = await held(tx, task_id);
|
|
377
|
+
if ('ok' in found)
|
|
378
|
+
return found;
|
|
379
|
+
const { task } = found;
|
|
380
|
+
if (task.state !== 'claimed')
|
|
381
|
+
return refuse('not-open', 'this task is not claimed');
|
|
382
|
+
if (task.claimed_by !== by.id) {
|
|
383
|
+
return refuse('claimed', 'someone else has claimed this task');
|
|
384
|
+
}
|
|
385
|
+
const [released] = await tx
|
|
386
|
+
.update(tasks)
|
|
387
|
+
.set({ state: 'open', claimed_by: null })
|
|
388
|
+
.where(eq(tasks.id, task.id))
|
|
389
|
+
.returning();
|
|
390
|
+
if (!released)
|
|
391
|
+
throw new Error(`task ${task.id} vanished while its run was held`);
|
|
392
|
+
return { ok: true, task: released };
|
|
393
|
+
}),
|
|
394
|
+
inbox: (caller) => {
|
|
395
|
+
const positions = [...(caller.positions ?? [])];
|
|
396
|
+
const mine = or(and(eq(tasks.assignee, caller.id), eq(tasks.state, 'open')), and(eq(tasks.claimed_by, caller.id), eq(tasks.state, 'claimed')), positions.length === 0
|
|
397
|
+
? undefined
|
|
398
|
+
: and(inArray(tasks.position, positions), eq(tasks.state, 'open')));
|
|
399
|
+
return db.select().from(tasks).where(mine).orderBy(asc(tasks.created_at), asc(tasks.id));
|
|
400
|
+
},
|
|
401
|
+
get: async (run_id) => {
|
|
402
|
+
const [run] = await db.select().from(runs).where(eq(runs.id, run_id));
|
|
403
|
+
if (!run)
|
|
404
|
+
return null;
|
|
405
|
+
return {
|
|
406
|
+
run,
|
|
407
|
+
definition: await definitionOf(db, run),
|
|
408
|
+
tasks: await db
|
|
409
|
+
.select()
|
|
410
|
+
.from(tasks)
|
|
411
|
+
.where(eq(tasks.run_id, run.id))
|
|
412
|
+
.orderBy(asc(tasks.created_at), asc(tasks.id)),
|
|
413
|
+
};
|
|
414
|
+
},
|
|
415
|
+
};
|
|
416
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import type { ApprovalDecision, AssignTarget, Locale, NestedData, Registry, WorkflowDefinition } from '@20baht/engine';
|
|
2
|
+
export type RunStatus = 'active' | 'completed' | 'rejected';
|
|
3
|
+
/** A run: the step it stands on, and everything collected so far. */
|
|
4
|
+
export interface Run {
|
|
5
|
+
id: string;
|
|
6
|
+
workflow_id: string;
|
|
7
|
+
/** The definition this run was started on, by content: a later edit never moves a run. */
|
|
8
|
+
definition_hash: string;
|
|
9
|
+
status: RunStatus;
|
|
10
|
+
/** The step the run stands on; the last one it stood on once it has ended. */
|
|
11
|
+
form_name: string;
|
|
12
|
+
/** Nested `{ Form_Name: { key } }`, as the engine reads it. */
|
|
13
|
+
data: NestedData;
|
|
14
|
+
/** Whoever started it: the only one who submits its form steps. */
|
|
15
|
+
requester: string;
|
|
16
|
+
created_at: Date;
|
|
17
|
+
updated_at: Date;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* `open` waits for its person, or for anyone entitled to the position; `claimed` is a position
|
|
21
|
+
* one person took; `done` carries a decision; `unassigned` was asked of somebody the host could
|
|
22
|
+
* not name, and nobody can decide it; `cancelled` was still open when its step settled;
|
|
23
|
+
* `superseded` belongs to an earlier visit of a step a rejection sent the run back to.
|
|
24
|
+
*/
|
|
25
|
+
export type TaskState = 'open' | 'claimed' | 'done' | 'unassigned' | 'cancelled' | 'superseded';
|
|
26
|
+
/** One person's (or one position's) share of an approval step. */
|
|
27
|
+
export interface RunTask {
|
|
28
|
+
id: string;
|
|
29
|
+
run_id: string;
|
|
30
|
+
form_name: string;
|
|
31
|
+
label: string;
|
|
32
|
+
/** A named person. Exactly one of `assignee` and `position` is set, or neither (see `target`). */
|
|
33
|
+
assignee: string | null;
|
|
34
|
+
/** A position anyone entitled may claim: the host's own key (`group:helpdesk`). */
|
|
35
|
+
position: string | null;
|
|
36
|
+
/** The target of the definition this task came from; null on a step with no `assignment`. */
|
|
37
|
+
target: AssignTarget | null;
|
|
38
|
+
state: TaskState;
|
|
39
|
+
decision: ApprovalDecision | null;
|
|
40
|
+
comment: string | null;
|
|
41
|
+
claimed_by: string | null;
|
|
42
|
+
decided_by: string | null;
|
|
43
|
+
decided_at: Date | null;
|
|
44
|
+
/** What `authorize` returned as proof, stored and never read. */
|
|
45
|
+
evidence: string | null;
|
|
46
|
+
created_at: Date;
|
|
47
|
+
}
|
|
48
|
+
/** Who is acting. `positions` are the ones the host says this person may claim (their groups, roles). */
|
|
49
|
+
export interface Caller {
|
|
50
|
+
id: string;
|
|
51
|
+
positions?: readonly string[];
|
|
52
|
+
}
|
|
53
|
+
/** Who a target points at: a named person, or a position anyone entitled may claim. */
|
|
54
|
+
export type Asked = {
|
|
55
|
+
person: string;
|
|
56
|
+
label?: string;
|
|
57
|
+
} | {
|
|
58
|
+
position: string;
|
|
59
|
+
label?: string;
|
|
60
|
+
};
|
|
61
|
+
export interface ResolveContext {
|
|
62
|
+
run: Pick<Run, 'id' | 'workflow_id' | 'requester' | 'data'>;
|
|
63
|
+
form_name: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Port 1, when a step opens: who this target is asked of. Several answers are several tasks
|
|
67
|
+
* (everyone holding a role, one per row of a repeater). An empty answer is "nobody the host can
|
|
68
|
+
* name": the task is kept as `unassigned`, an exception to surface, never a step to drop.
|
|
69
|
+
* It runs inside the transaction that moves the run, so keep it to lookups.
|
|
70
|
+
*/
|
|
71
|
+
export type Resolve = (target: AssignTarget, context: ResolveContext) => readonly Asked[] | Promise<readonly Asked[]>;
|
|
72
|
+
export interface Requirement {
|
|
73
|
+
/** Null on a step with no `assignment`: the host alone says who may decide it. */
|
|
74
|
+
target: AssignTarget | null;
|
|
75
|
+
task: Pick<RunTask, 'id' | 'form_name' | 'assignee' | 'position' | 'claimed_by'>;
|
|
76
|
+
run: Pick<Run, 'id' | 'workflow_id' | 'requester' | 'data'>;
|
|
77
|
+
}
|
|
78
|
+
/** `unavailable` is not a yes: the host could not find out, so nothing is decided. */
|
|
79
|
+
export type Verdict = {
|
|
80
|
+
verdict: 'allowed';
|
|
81
|
+
evidence?: string;
|
|
82
|
+
} | {
|
|
83
|
+
verdict: 'denied';
|
|
84
|
+
reason: string;
|
|
85
|
+
} | {
|
|
86
|
+
verdict: 'unavailable';
|
|
87
|
+
reason?: string;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Port 2, when a claim or a decision arrives: may this caller act on this task, as things stand
|
|
91
|
+
* now (not as they stood when the step opened)?
|
|
92
|
+
*/
|
|
93
|
+
export type Authorize = (requirement: Requirement, caller: Caller) => Verdict | Promise<Verdict>;
|
|
94
|
+
/**
|
|
95
|
+
* The plainest `authorize`: the named person, or anyone holding the position. A step with no
|
|
96
|
+
* `assignment` names nobody, so it is refused; such a workflow needs a host rule of its own.
|
|
97
|
+
*/
|
|
98
|
+
export declare const byAssignment: Authorize;
|
|
99
|
+
export interface RunsBehaviour {
|
|
100
|
+
resolve: Resolve;
|
|
101
|
+
authorize: Authorize;
|
|
102
|
+
/** For `custom` validators and formatters the definitions name. */
|
|
103
|
+
registry?: Registry;
|
|
104
|
+
/** The language of validation messages. */
|
|
105
|
+
locale?: Locale;
|
|
106
|
+
/** The clock and the id source, for tests. */
|
|
107
|
+
now?: () => Date;
|
|
108
|
+
newId?: () => string;
|
|
109
|
+
}
|
|
110
|
+
export interface Issue {
|
|
111
|
+
ref: string;
|
|
112
|
+
message: string;
|
|
113
|
+
}
|
|
114
|
+
/** A run after a call, with the tasks the call opened (to notify their people). */
|
|
115
|
+
export interface Moved {
|
|
116
|
+
ok: true;
|
|
117
|
+
run: Run;
|
|
118
|
+
opened: RunTask[];
|
|
119
|
+
}
|
|
120
|
+
export interface Refused<Reason extends string> {
|
|
121
|
+
ok: false;
|
|
122
|
+
reason: Reason;
|
|
123
|
+
message: string;
|
|
124
|
+
}
|
|
125
|
+
export type StartResult = Moved | Refused<'invalid-definition' | 'no-step' | 'blocked'> | {
|
|
126
|
+
ok: false;
|
|
127
|
+
reason: 'invalid';
|
|
128
|
+
message: string;
|
|
129
|
+
issues: Issue[];
|
|
130
|
+
};
|
|
131
|
+
export type SubmitResult = Moved | Refused<'not-found' | 'not-active' | 'not-a-form-step' | 'denied' | 'blocked'> | {
|
|
132
|
+
ok: false;
|
|
133
|
+
reason: 'invalid';
|
|
134
|
+
message: string;
|
|
135
|
+
issues: Issue[];
|
|
136
|
+
};
|
|
137
|
+
export type DecideResult =
|
|
138
|
+
/** `pending`: recorded, and the step still waits for others. */
|
|
139
|
+
(Moved & {
|
|
140
|
+
outcome: 'pending' | ApprovalDecision;
|
|
141
|
+
task: RunTask;
|
|
142
|
+
}) | Refused<'not-found' | 'not-open' | 'claimed' | 'comment-required' | 'denied' | 'unavailable' | 'blocked'>;
|
|
143
|
+
export type ClaimResult = {
|
|
144
|
+
ok: true;
|
|
145
|
+
task: RunTask;
|
|
146
|
+
} | Refused<'not-found' | 'not-open' | 'not-claimable' | 'claimed' | 'denied' | 'unavailable'>;
|
|
147
|
+
export interface RunDetail {
|
|
148
|
+
run: Run;
|
|
149
|
+
/** The definition the run is pinned to: render it with this one, not the latest. */
|
|
150
|
+
definition: WorkflowDefinition;
|
|
151
|
+
/** Every task of the run, oldest first, earlier visits included. */
|
|
152
|
+
tasks: RunTask[];
|
|
153
|
+
}
|
|
154
|
+
export interface Runs {
|
|
155
|
+
/**
|
|
156
|
+
* A new run of `definition` for `requester`. With `data` (the flat body of the first form) it
|
|
157
|
+
* is submitted at once, as `submit` would.
|
|
158
|
+
*/
|
|
159
|
+
start(input: {
|
|
160
|
+
definition: WorkflowDefinition;
|
|
161
|
+
requester: string;
|
|
162
|
+
data?: Record<string, unknown>;
|
|
163
|
+
}): Promise<StartResult>;
|
|
164
|
+
/** The requester sends the form step the run stands on: validated, stored, and the run moves. */
|
|
165
|
+
submit(run_id: string, input: {
|
|
166
|
+
by: string;
|
|
167
|
+
data: Record<string, unknown>;
|
|
168
|
+
}): Promise<SubmitResult>;
|
|
169
|
+
/** One person's decision on a task. The run moves only once the step's rule is settled. */
|
|
170
|
+
decide(task_id: string, input: {
|
|
171
|
+
by: Caller;
|
|
172
|
+
decision: ApprovalDecision;
|
|
173
|
+
comment?: string;
|
|
174
|
+
}): Promise<DecideResult>;
|
|
175
|
+
/** Take a position's task, so nobody else works on it. */
|
|
176
|
+
claim(task_id: string, by: Caller): Promise<ClaimResult>;
|
|
177
|
+
/** Give a claimed task back to its position. */
|
|
178
|
+
release(task_id: string, by: Caller): Promise<ClaimResult>;
|
|
179
|
+
/** What waits for this caller: their own tasks, the ones they claimed, and open ones of their positions. */
|
|
180
|
+
inbox(caller: Caller): Promise<RunTask[]>;
|
|
181
|
+
get(run_id: string): Promise<RunDetail | null>;
|
|
182
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const byAssignment = ({ task }, caller) => {
|
|
2
|
+
if (task.assignee !== null) {
|
|
3
|
+
return task.assignee === caller.id
|
|
4
|
+
? { verdict: 'allowed' }
|
|
5
|
+
: { verdict: 'denied', reason: 'this task is asked of someone else' };
|
|
6
|
+
}
|
|
7
|
+
if (task.position !== null && (caller.positions ?? []).includes(task.position)) {
|
|
8
|
+
return { verdict: 'allowed' };
|
|
9
|
+
}
|
|
10
|
+
return { verdict: 'denied', reason: 'this task is not asked of a position you hold' };
|
|
11
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/runs",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=20.19.0"
|
|
7
|
+
},
|
|
8
|
+
"description": "Workflow runs kept on a server: start a run, take the requester's form steps, open an approval step's tasks, record decisions and move the run with the same engine the browser uses. Persistence is drizzle-orm (Postgres); who is asked and who may decide are two functions the host supplies.",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"author": "Nattapong Promthong",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/bank20baht/20baht.git",
|
|
14
|
+
"directory": "packages/core/runs"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/runs#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/bank20baht/20baht/issues"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"workflow",
|
|
22
|
+
"approval",
|
|
23
|
+
"tasks",
|
|
24
|
+
"inbox",
|
|
25
|
+
"drizzle",
|
|
26
|
+
"postgres",
|
|
27
|
+
"bahtui"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"import": "./dist/index.js",
|
|
39
|
+
"default": "./dist/index.js"
|
|
40
|
+
},
|
|
41
|
+
"./pg": {
|
|
42
|
+
"types": "./dist/pg.d.ts",
|
|
43
|
+
"import": "./dist/pg.js",
|
|
44
|
+
"default": "./dist/pg.js"
|
|
45
|
+
},
|
|
46
|
+
"./package.json": "./package.json"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
50
|
+
"test": "vitest run",
|
|
51
|
+
"test:watch": "vitest",
|
|
52
|
+
"test:coverage": "vitest run --coverage"
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"@20baht/validator": ">=0.3.0 <0.4.0"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"@20baht/engine": ">=0.3.0 <0.4.0",
|
|
59
|
+
"drizzle-orm": ">=0.44.0 <1.0.0"
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@20baht/engine": "workspace:*",
|
|
63
|
+
"@electric-sql/pglite": "^0.3.0",
|
|
64
|
+
"drizzle-kit": "^0.31.11",
|
|
65
|
+
"drizzle-orm": "^0.44.0",
|
|
66
|
+
"typescript": "^5.9.3",
|
|
67
|
+
"vitest": "^3.2.4"
|
|
68
|
+
},
|
|
69
|
+
"main": "./dist/index.js",
|
|
70
|
+
"types": "./dist/index.d.ts"
|
|
71
|
+
}
|