@sanity/workflow-engine 0.14.0 → 0.16.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/dist/define.js CHANGED
@@ -1,965 +1,105 @@
1
- import * as v from "valibot";
2
- import { printGuardRead, andConditions, expandRequiredRoles, normalizeRoleAliases, RESERVED_CONDITION_VARS, GROQ_IDENTIFIER, CONDITION_VARS, formatValidationError, issuesFromValibot, AuthoringWorkflowSchema, WorkflowConfigSchema, AuthoringStageSchema, AuthoringActivitySchema, AuthoringActionSchema, AuthoringTransitionSchema, AuthoringFieldEntrySchema, AuthoringOpSchema, AuthoringGuardSchema, EffectSchema } from "./_chunks-es/schema.js";
3
- import { FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS } from "./_chunks-es/schema.js";
4
- function groq(strings, ...values) {
5
- return strings.reduce((out, part, i) => i === 0 ? part : `${out}${serializeGroqValue(values[i - 1])}${part}`, "");
6
- }
7
- function serializeGroqValue(value) {
8
- const serialized = JSON.stringify(value);
9
- if (serialized === void 0)
10
- throw new Error(
11
- `groq tag cannot serialize ${typeof value} \u2014 interpolate JSON-representable values only`
12
- );
13
- return serialized;
14
- }
15
- function desugarWorkflow(authoring) {
16
- const issues = [];
17
- checkReservedRoleAliasKeys(authoring.roleAliases, issues);
18
- const roleAliases = normalizeRoleAliases(authoring.roleAliases), ctx = {
19
- issues,
20
- claimFields: /* @__PURE__ */ new Map(),
21
- claimedFields: /* @__PURE__ */ new Set(),
22
- roleAliases
23
- }, workflowFields = desugarFieldEntries({ entries: authoring.fields, path: ["fields"], ctx }), workflowLayer = layerOf(workflowFields), stages = authoring.stages.map((stage, i) => {
24
- const path = ["stages", i], stageFields = desugarFieldEntries({ entries: stage.fields, path: [...path, "fields"], ctx }), stageEnv = {
25
- layers: [
26
- { scope: "stage", entries: layerOf(stageFields) },
27
- { scope: "workflow", entries: workflowLayer }
28
- ]
29
- }, activities = (stage.activities ?? []).map(
30
- (activity, j) => desugarActivity({ activity, path: [...path, "activities", j], stageEnv, ctx })
31
- ), transitions = (stage.transitions ?? []).map(
32
- (transition, k) => desugarTransition({ transition, path: [...path, "transitions", k], stageEnv, ctx })
33
- ), editable = desugarStageEditable({
34
- overrides: stage.editable,
35
- inScope: editableFieldNames({ workflowFields, stageFields, activities }),
36
- path: [...path, "editable"],
37
- ctx
38
- });
39
- return {
40
- ...stripUndefined({
41
- name: stage.name,
42
- title: stage.title,
43
- description: stage.description,
44
- guards: stage.guards?.map(desugarGuard)
45
- }),
46
- ...stageFields ? { fields: stageFields } : {},
47
- ...activities.length > 0 ? { activities } : {},
48
- ...transitions.length > 0 ? { transitions } : {},
49
- ...editable ? { editable } : {}
50
- };
51
- });
52
- return checkUnclaimedClaimFields(ctx), { definition: {
53
- ...stripUndefined({
54
- name: authoring.name,
55
- title: authoring.title,
56
- description: authoring.description,
57
- lifecycle: authoring.lifecycle,
58
- initialStage: authoring.initialStage,
59
- predicates: authoring.predicates,
60
- roleAliases
61
- }),
62
- ...workflowFields ? { fields: workflowFields } : {},
63
- stages
64
- }, issues: ctx.issues };
65
- }
66
- function checkReservedRoleAliasKeys(aliases, issues) {
67
- for (const key of Object.keys(aliases ?? {}))
68
- key.startsWith("$") && issues.push({
69
- path: ["roleAliases", key],
70
- message: `role alias key "${key}" uses the reserved "$" prefix \u2014 that namespace is the engine's stored spelling for the universal fulfiller. Use "*" to mean "fulfills any gate", or rename the role.`
71
- });
72
- }
73
- const TODOLIST_OF = [
74
- { type: "string", name: "label", title: "Label" },
75
- { type: "string", name: "status", title: "Status" },
76
- { type: "assignee", name: "assignee", title: "Assignee" },
77
- { type: "date", name: "dueDate", title: "Due date" }
78
- ], NOTES_OF = [
79
- { type: "text", name: "body", title: "Body" },
80
- { type: "actor", name: "actor", title: "Actor" },
81
- { type: "datetime", name: "at", title: "At" }
82
- ];
83
- function desugarFieldEntries({
84
- entries,
85
- path,
86
- ctx
87
- }) {
88
- return !entries || entries.length === 0 ? entries === void 0 ? void 0 : [] : entries.map((entry, i) => desugarFieldEntry({ entry, path: [...path, i], ctx }));
89
- }
90
- function desugarFieldEntry({
91
- entry,
92
- path,
93
- ctx
94
- }) {
95
- if (entry.type === "claim") return desugarClaimField({ entry, path, ctx });
96
- if (entry.type === "todoList" || entry.type === "notes")
97
- return desugarListField({ entry, path, ctx });
98
- const editable = normalizeEditable({ editable: entry.editable, path: [...path, "editable"], ctx });
99
- return {
100
- ...stripUndefined({
101
- type: entry.type,
102
- name: entry.name,
103
- title: entry.title,
104
- description: entry.description,
105
- required: entry.required,
106
- initialValue: entry.initialValue,
107
- editable,
108
- fields: entry.fields,
109
- of: entry.of
110
- })
111
- };
112
- }
113
- function desugarClaimField({
114
- entry,
115
- path,
116
- ctx
117
- }) {
118
- const desugared = {
119
- ...stripUndefined({ name: entry.name, title: entry.title, description: entry.description }),
120
- type: "actor"
121
- };
122
- return ctx.claimFields.set(desugared, { name: entry.name, path }), desugared;
123
- }
124
- function desugarListField({
125
- entry,
126
- path,
127
- ctx
128
- }) {
129
- const editable = normalizeEditable({ editable: entry.editable, path: [...path, "editable"], ctx });
130
- return {
131
- ...stripUndefined({
132
- name: entry.name,
133
- title: entry.title,
134
- description: entry.description,
135
- required: entry.required,
136
- initialValue: entry.initialValue,
137
- editable
138
- }),
139
- type: "array",
140
- of: entry.type === "todoList" ? TODOLIST_OF : NOTES_OF
141
- };
142
- }
143
- function normalizeEditable({
144
- editable,
145
- path,
146
- ctx
147
- }) {
148
- if (editable === void 0 || editable === !0) return editable;
149
- if (Array.isArray(editable)) {
150
- const condition = rolesCondition(editable, ctx.roleAliases);
151
- if (condition === void 0) {
152
- ctx.issues.push({
153
- path,
154
- message: "editable: [] names no roles \u2014 use `true` to open the field to anyone in its scope, or list at least one role"
155
- });
156
- return;
157
- }
158
- return condition;
159
- }
160
- return editable;
161
- }
162
- function editableFieldNames({
163
- workflowFields,
164
- stageFields,
165
- activities
166
- }) {
167
- const names = /* @__PURE__ */ new Set(), collect = (entries) => {
168
- for (const entry of entries ?? []) entry.editable !== void 0 && names.add(entry.name);
169
- };
170
- collect(workflowFields), collect(stageFields);
171
- for (const activity of activities) collect(activity.fields);
172
- return names;
173
- }
174
- function desugarStageEditable({
175
- overrides,
176
- inScope,
177
- path,
178
- ctx
179
- }) {
180
- if (overrides === void 0) return;
181
- const out = {};
182
- for (const [name, value] of Object.entries(overrides)) {
183
- if (!inScope.has(name)) {
184
- ctx.issues.push({
185
- path: [...path, name],
186
- message: `stage editable override "${name}" does not narrow an editable field in scope \u2014 name a workflow/stage/activity field of this stage that declares \`editable\``
187
- });
188
- continue;
189
- }
190
- const normalized = normalizeEditable({ editable: value, path: [...path, name], ctx });
191
- normalized !== void 0 && (out[name] = normalized);
192
- }
193
- return Object.keys(out).length > 0 ? out : void 0;
194
- }
195
- function layerOf(entries) {
196
- return new Map((entries ?? []).map((entry) => [entry.name, entry]));
197
- }
198
- function desugarActivity({
199
- activity,
200
- path,
201
- stageEnv,
202
- ctx
203
- }) {
204
- const activityFields = desugarFieldEntries({
205
- entries: activity.fields,
206
- path: [...path, "fields"],
207
- ctx
208
- }), env = {
209
- layers: [{ scope: "activity", entries: layerOf(activityFields) }, ...stageEnv.layers]
210
- }, ops = desugarOps({
211
- ops: activity.ops,
212
- path: [...path, "ops"],
213
- env,
214
- firingActivity: activity.name,
215
- ctx
216
- }), actions = (activity.actions ?? []).map(
217
- (action, a) => desugarAction({ action, path: [...path, "actions", a], env, activityName: activity.name, ctx })
218
- ), target = desugarTarget({ target: activity.target, env, path: [...path, "target"], ctx });
219
- return {
220
- ...stripUndefined({
221
- name: activity.name,
222
- title: activity.title,
223
- description: activity.description,
224
- kind: activity.kind,
225
- filter: activity.filter,
226
- requirements: activity.requirements,
227
- completeWhen: activity.completeWhen,
228
- failWhen: activity.failWhen,
229
- effects: activity.effects,
230
- subworkflows: activity.subworkflows
231
- }),
232
- activation: activity.activation ?? "manual",
233
- ...target ? { target } : {},
234
- ...activityFields ? { fields: activityFields } : {},
235
- ...ops ? { ops } : {},
236
- ...actions.length > 0 ? { actions } : {}
237
- };
238
- }
239
- const TARGET_DOC_KINDS = ["doc.ref", "doc.refs", "release.ref"];
240
- function desugarTarget({
241
- target,
242
- env,
243
- path,
244
- ctx
245
- }) {
246
- if (target === void 0 || target.type === "url") return target;
247
- const ref = typeof target.field == "string" ? { field: target.field } : target.field, field = resolveRef({ ref, env, path: [...path, "field"], ctx }) ?? fallbackRef(ref), entry = entryAt(env, field);
248
- return entry && !TARGET_DOC_KINDS.includes(entry.type) && ctx.issues.push({
249
- path: [...path, "field"],
250
- message: `manual activity target references "${field.field}" of kind "${entry.type}" \u2014 a deep-link target needs a document-valued entry (${TARGET_DOC_KINDS.join(", ")})`
251
- }), { type: "field", field };
252
- }
253
- function desugarAction({
254
- action,
255
- path,
256
- env,
257
- activityName,
258
- ctx
259
- }) {
260
- if ("type" in action)
261
- return desugarClaimAction({ action, path, env, ctx });
262
- const filter = andConditions([rolesCondition(action.roles, ctx.roleAliases), action.filter]), ops = desugarOps({ ops: action.ops, path: [...path, "ops"], env, firingActivity: activityName, ctx }) ?? [];
263
- return action.status !== void 0 && ops.push({ type: "status.set", activity: activityName, status: action.status }), {
264
- ...stripUndefined({
265
- name: action.name,
266
- title: action.title,
267
- description: action.description,
268
- params: action.params,
269
- effects: action.effects
270
- }),
271
- ...filter ? { filter } : {},
272
- ...ops.length > 0 ? { ops } : {}
273
- };
274
- }
275
- function desugarClaimAction({
276
- action,
277
- path,
278
- env,
279
- ctx
280
- }) {
281
- const ref = typeof action.field == "string" ? { field: action.field } : action.field, resolved = resolveRef({ ref, env, path: [...path, "field"], ctx });
282
- if (resolved) {
283
- const entry = entryAt(env, resolved);
284
- entry && entry.type !== "actor" && ctx.issues.push({
285
- path: [...path, "field"],
286
- message: `claim action "${action.name}" references "${resolved.field}" of kind "${entry.type}" \u2014 a claim pair needs an actor-valued entry (a "claim" or "actor" field declaration)`
287
- }), checkShadowedClaimTarget({
288
- actionName: action.name,
289
- field: ref.field,
290
- resolved,
291
- env,
292
- path: [...path, "field"],
293
- ctx
294
- }), entry && ctx.claimedFields.add(entry);
295
- }
296
- const noSteal = `!defined($fields.${ref.field})`, filter = andConditions([
297
- noSteal,
298
- rolesCondition(action.roles, ctx.roleAliases),
299
- action.filter
300
- ]), ops = resolved ? [{ type: "field.set", target: resolved, value: { type: "actor" } }] : [];
301
- return {
302
- ...stripUndefined({
303
- name: action.name,
304
- title: action.title,
305
- description: action.description,
306
- params: action.params,
307
- effects: action.effects
308
- }),
309
- filter,
310
- ...ops.length > 0 ? { ops } : {}
311
- };
312
- }
313
- function checkShadowedClaimTarget({
314
- actionName,
315
- field,
316
- resolved,
317
- env,
318
- path,
319
- ctx
320
- }) {
321
- const nearest = env.layers.find((l) => l.entries.has(field));
322
- nearest === void 0 || nearest.scope === resolved.scope || ctx.issues.push({
323
- path,
324
- message: `claim action "${actionName}" targets "${field}" at scope "${resolved.scope}", but a nearer ${nearest.scope}-scope entry of the same name shadows it in $fields \u2014 the no-steal filter would read the shadowing entry while the claim writes the "${resolved.scope}" one. Rename one of the entries or claim the nearer one`
325
- });
326
- }
327
- function checkUnclaimedClaimFields(ctx) {
328
- for (const [entry, { name, path }] of ctx.claimFields)
329
- ctx.claimedFields.has(entry) || ctx.issues.push({
330
- path,
331
- message: `claim field "${name}" is never referenced by a claim action \u2014 you announced the pattern and wrote half of it. Declare a defineAction({ type: "claim", field: "${name}" }) or use a raw actor entry`
332
- });
333
- }
334
- function desugarTransition({
335
- transition,
336
- path,
337
- stageEnv,
338
- ctx
339
- }) {
340
- const ops = desugarOps({
341
- ops: transition.ops,
342
- path: [...path, "ops"],
343
- env: stageEnv,
344
- firingActivity: void 0,
345
- ctx
346
- });
347
- return {
348
- ...stripUndefined({
349
- name: transition.name,
350
- title: transition.title,
351
- description: transition.description,
352
- to: transition.to,
353
- effects: transition.effects
354
- }),
355
- filter: transition.filter ?? "$allActivitiesDone",
356
- ...ops ? { ops } : {}
357
- };
358
- }
359
- function desugarGuard(guard) {
360
- const { match, metadata, ...rest } = guard, { idRefs, ...matchRest } = match;
361
- return {
362
- ...rest,
363
- match: {
364
- ...matchRest,
365
- ...idRefs !== void 0 ? { idRefs: idRefs.map(printGuardRead) } : {}
366
- },
367
- ...metadata !== void 0 ? {
368
- metadata: Object.fromEntries(
369
- Object.entries(metadata).map(([key, read]) => [key, printGuardRead(read)])
370
- )
371
- } : {}
372
- };
373
- }
374
- function desugarOps({
375
- ops,
376
- path,
377
- env,
378
- firingActivity,
379
- ctx
380
- }) {
381
- if (ops)
382
- return ops.map((op, i) => desugarOp({ op, path: [...path, i], env, firingActivity, ctx }));
383
- }
384
- function desugarOp({
385
- op,
386
- path,
387
- env,
388
- firingActivity,
389
- ctx
390
- }) {
391
- if (op.type === "status.set") {
392
- const activity = op.activity ?? firingActivity;
393
- return activity === void 0 && ctx.issues.push({
394
- path: [...path, "activity"],
395
- message: "status.set outside an action must name its target activity"
396
- }), { type: "status.set", activity: activity ?? "", status: op.status };
397
- }
398
- if (op.type === "audit") return desugarAuditOp({ op, path, env, ctx });
399
- const target = resolveRef({ ref: op.target, env, path: [...path, "target"], ctx }) ?? fallbackRef(op.target);
400
- return { ...op, target };
401
- }
402
- const AUDIT_STAMPS = { actor: { type: "actor" }, at: { type: "now" } };
403
- function desugarAuditOp({
404
- op,
405
- path,
406
- env,
407
- ctx
408
- }) {
409
- const target = resolveRef({ ref: op.target, env, path: [...path, "target"], ctx }) ?? fallbackRef(op.target);
410
- if (op.value.type !== "object")
411
- return ctx.issues.push({
412
- path: [...path, "value"],
413
- message: `audit value must be an object source carrying the domain fields (got "${op.value.type}")`
414
- }), { type: "field.append", target, value: op.value };
415
- const actorField = op.stampFields?.actor ?? "actor", atField = op.stampFields?.at ?? "at", fields = { ...op.value.fields };
416
- for (const [stamp, source] of [
417
- [actorField, AUDIT_STAMPS.actor],
418
- [atField, AUDIT_STAMPS.at]
419
- ]) {
420
- if (stamp in fields) {
421
- ctx.issues.push({
422
- path: [...path, "value", "fields", stamp],
423
- message: `audit stamp field "${stamp}" collides with an authored domain field \u2014 rename yours or remap the stamp via stampFields`
424
- });
425
- continue;
426
- }
427
- fields[stamp] = source;
428
- }
429
- return { type: "field.append", target, value: { type: "object", fields } };
430
- }
431
- function resolveRef({
432
- ref,
433
- env,
434
- path,
435
- ctx
436
- }) {
437
- const layers = ref.scope === void 0 ? env.layers : env.layers.filter((l) => l.scope === ref.scope);
438
- for (const layer of layers)
439
- if (layer.entries.has(ref.field)) return { scope: layer.scope, field: ref.field };
440
- const reachable = env.layers.flatMap((l) => [...l.entries.keys()].map((n) => `${l.scope}:${n}`));
441
- ctx.issues.push({
442
- path,
443
- message: `field reference "${ref.field}"${ref.scope ? ` (scope "${ref.scope}")` : ""} does not resolve to a declared entry. Reachable: ${reachable.join(", ") || "(none)"}`
444
- });
445
- }
446
- function entryAt(env, ref) {
447
- return env.layers.find((l) => l.scope === ref.scope)?.entries.get(ref.field);
448
- }
449
- function fallbackRef(ref) {
450
- return { scope: ref.scope ?? "workflow", field: ref.field };
451
- }
452
- function rolesCondition(roles, aliases) {
453
- if (!(!roles || roles.length === 0))
454
- return groq`count($actor.roles[@ in ${expandRequiredRoles(roles, aliases)}]) > 0`;
455
- }
456
- function stripUndefined(obj) {
457
- const out = {};
458
- for (const [k, value] of Object.entries(obj))
459
- value !== void 0 && (out[k] = value);
460
- return out;
461
- }
462
- const PREDICATE_CALLER_VARS = CONDITION_VARS.filter((v2) => v2.binding === "caller").map(
463
- (v2) => v2.name
464
- );
465
- function knownList(ids) {
466
- return [...ids].map((s) => `"${s}"`).join(", ");
467
- }
468
- function checkDuplicates({
469
- names,
470
- what,
471
- issues
472
- }) {
473
- const seen = /* @__PURE__ */ new Set();
474
- for (const { name, path } of names)
475
- seen.has(name) && issues.push({ path, message: `duplicate ${what} "${name}" (already declared earlier)` }), seen.add(name);
476
- return seen;
477
- }
478
- function checkStages(def, issues) {
479
- const stageNames = checkDuplicates({
480
- names: def.stages.map((stage, i) => ({ name: stage.name, path: ["stages", i, "name"] })),
481
- what: "stage name",
482
- issues
483
- });
484
- for (const [i, stage] of def.stages.entries()) {
485
- const activityNames = checkDuplicates({
486
- names: (stage.activities ?? []).map((activity, j) => ({
487
- name: activity.name,
488
- path: ["stages", i, "activities", j, "name"]
489
- })),
490
- what: `activity name in stage "${stage.name}"`,
491
- issues
492
- });
493
- checkDuplicates({
494
- names: (stage.transitions ?? []).map((t, k) => ({
495
- name: t.name,
496
- path: ["stages", i, "transitions", k, "name"]
497
- })),
498
- what: `transition name in stage "${stage.name}"`,
499
- issues
500
- }), checkActivities({ def, i, activityNames, issues });
501
- }
502
- return stageNames;
503
- }
504
- function checkActivities({
505
- def,
506
- i,
507
- activityNames,
508
- issues
509
- }) {
510
- const stage = def.stages[i];
511
- for (const [j, activity] of (stage.activities ?? []).entries()) {
512
- const path = ["stages", i, "activities", j];
513
- checkDuplicates({
514
- names: (activity.actions ?? []).map((action, a) => ({
515
- name: action.name,
516
- path: [...path, "actions", a, "name"]
517
- })),
518
- what: `action name in activity "${activity.name}"`,
519
- issues
520
- }), checkStatusSetTargets({ activity, activityNames, path, issues });
521
- }
522
- }
523
- function checkStatusSetTargets({
524
- activity,
525
- activityNames,
526
- path,
527
- issues
528
- }) {
529
- checkStatusSetOps({ ops: activity.ops, activityNames, path: [...path, "ops"], issues });
530
- for (const [a, action] of (activity.actions ?? []).entries())
531
- checkStatusSetOps({
532
- ops: action.ops,
533
- activityNames,
534
- path: [...path, "actions", a, "ops"],
535
- issues
536
- });
537
- }
538
- function checkStatusSetOps({
539
- ops,
540
- activityNames,
541
- path,
542
- issues
543
- }) {
544
- for (const [o, op] of (ops ?? []).entries())
545
- op.type !== "status.set" || activityNames.has(op.activity) || issues.push({
546
- path: [...path, o, "activity"],
547
- message: `status.set targets activity "${op.activity}" which is not declared in this stage. Known activities: ${knownList(activityNames)}`
548
- });
549
- }
550
- function checkInitialStage({
551
- def,
552
- stageNames,
553
- issues
554
- }) {
555
- stageNames.has(def.initialStage) || issues.push({
556
- path: ["initialStage"],
557
- message: `initialStage "${def.initialStage}" is not a declared stage. Known stages: ${knownList(stageNames)}`
558
- });
559
- }
560
- function checkTransitionTargets({
561
- def,
562
- stageNames,
563
- issues
564
- }) {
565
- for (const [i, stage] of def.stages.entries())
566
- for (const [k, t] of (stage.transitions ?? []).entries())
567
- stageNames.has(t.to) || issues.push({
568
- path: ["stages", i, "transitions", k, "to"],
569
- message: `transition target "${t.to}" is not a declared stage. Known stages: ${knownList(stageNames)}`
570
- });
571
- }
572
- function checkEffectNames(def, issues) {
573
- const sites = [];
574
- for (const [i, stage] of def.stages.entries()) {
575
- for (const [j, activity] of (stage.activities ?? []).entries()) {
576
- collectEffects({
577
- effects: activity.effects,
578
- path: ["stages", i, "activities", j, "effects"],
579
- sites
580
- });
581
- for (const [a, action] of (activity.actions ?? []).entries())
582
- collectEffects({
583
- effects: action.effects,
584
- path: ["stages", i, "activities", j, "actions", a, "effects"],
585
- sites
586
- });
587
- }
588
- for (const [k, t] of (stage.transitions ?? []).entries())
589
- collectEffects({ effects: t.effects, path: ["stages", i, "transitions", k, "effects"], sites });
590
- }
591
- checkDuplicates({
592
- names: sites,
593
- what: "effect name (registry key \u2014 unique per definition)",
594
- issues
595
- });
596
- }
597
- function collectEffects({
598
- effects,
599
- path,
600
- sites
601
- }) {
602
- for (const [e, effect] of (effects ?? []).entries())
603
- sites.push({ name: effect.name, path: [...path, e, "name"] });
604
- }
605
- function checkGuardNames(def, issues) {
606
- const sites = def.stages.flatMap(
607
- (stage, i) => (stage.guards ?? []).map((guard, g) => ({
608
- name: guard.name,
609
- path: ["stages", i, "guards", g, "name"]
610
- }))
611
- );
612
- checkDuplicates({
613
- names: sites,
614
- what: "guard name (the guard lake _id derives from it \u2014 unique per definition)",
615
- issues
616
- });
617
- }
618
- function fieldScopes(def) {
619
- const scopes = [
620
- { entries: def.fields, scope: "workflow", path: ["fields"], label: "workflow fields" }
621
- ];
622
- for (const [i, stage] of def.stages.entries()) {
623
- scopes.push({
624
- entries: stage.fields,
625
- scope: "stage",
626
- path: ["stages", i, "fields"],
627
- label: `stage "${stage.name}" fields`
1
+ import { parseOrThrow, desugarWorkflow, checkWorkflowInvariants, formatValidationError, AuthoringWorkflowSchema, labelFor, WorkflowConfigSchema, AuthoringStageSchema, AuthoringActivitySchema, AuthoringActionSchema, AuthoringTransitionSchema, AuthoringFieldEntrySchema, AuthoringOpSchema, GroupSchema, AuthoringGuardSchema, EffectSchema } from "./_chunks-es/invariants.js";
2
+
3
+ import { CONDITION_VARS, FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS, RESERVED_CONDITION_VARS, groq } from "./_chunks-es/invariants.js";
4
+
5
+ function defineWorkflow(definition) {
6
+ const label = labelFor("defineWorkflow", definition), parsed = parseOrThrow({
7
+ schema: AuthoringWorkflowSchema,
8
+ input: definition,
9
+ label: label
10
+ }), {definition: stored, issues: desugarIssues} = desugarWorkflow(parsed), issues = [ ...desugarIssues, ...checkWorkflowInvariants(stored) ];
11
+ if (issues.length > 0) throw new Error(formatValidationError(label, issues));
12
+ return stored;
13
+ }
14
+
15
+ function defineWorkflowConfig(config) {
16
+ return parseOrThrow({
17
+ schema: WorkflowConfigSchema,
18
+ input: config,
19
+ label: "defineWorkflowConfig"
628
20
  });
629
- for (const [j, activity] of (stage.activities ?? []).entries())
630
- scopes.push({
631
- entries: activity.fields,
632
- scope: "activity",
633
- path: ["stages", i, "activities", j, "fields"],
634
- label: `activity "${activity.name}" fields`
635
- });
636
- }
637
- return scopes;
638
21
  }
639
- function checkRequiredField(def, issues) {
640
- for (const { entries, scope, path, label } of fieldScopes(def))
641
- for (const [n, entry] of (entries ?? []).entries())
642
- if (entry.required === !0) {
643
- if (scope !== "workflow")
644
- issues.push({
645
- path: [...path, n, "required"],
646
- message: `${label} entry "${entry.name}" is \`required\`, but \`required\` applies only to workflow-scope \`input\` entries \u2014 only those are caller-supplied at start/spawn`
647
- });
648
- else if (entry.initialValue?.type !== "input") {
649
- const seed = entry.initialValue?.type ?? "working memory (no initialValue)";
650
- issues.push({
651
- path: [...path, n, "required"],
652
- message: `field entry "${entry.name}" has initialValue "${seed}" \u2014 \`required\` applies only to \`input\`-sourced entries (the caller fills them at start/spawn)`
653
- });
654
- }
655
- }
656
- }
657
- function checkFieldEntryNames(def, issues) {
658
- for (const { entries, path, label } of fieldScopes(def))
659
- checkDuplicates({
660
- names: (entries ?? []).map((entry, n) => ({ name: entry.name, path: [...path, n, "name"] })),
661
- what: `field entry name in ${label}`,
662
- issues
22
+
23
+ function defineStage(stage) {
24
+ return parseOrThrow({
25
+ schema: AuthoringStageSchema,
26
+ input: stage,
27
+ label: labelFor("defineStage", stage)
663
28
  });
664
29
  }
665
- function checkPredicates(def, issues) {
666
- const reserved = new Set(RESERVED_CONDITION_VARS), names = Object.keys(def.predicates ?? {});
667
- for (const name of names)
668
- reserved.has(name) && issues.push({
669
- path: ["predicates", name],
670
- message: `predicate "${name}" shadows the built-in $${name} \u2014 pick another name`
30
+
31
+ function defineActivity(activity) {
32
+ return parseOrThrow({
33
+ schema: AuthoringActivitySchema,
34
+ input: activity,
35
+ label: labelFor("defineActivity", activity)
671
36
  });
672
- for (const [name, groq2] of Object.entries(def.predicates ?? {}))
673
- checkPredicateBody({ name, groq: groq2, names, issues });
674
37
  }
675
- function checkPredicateBody({
676
- name,
677
- groq: groq2,
678
- names,
679
- issues
680
- }) {
681
- for (const caller of PREDICATE_CALLER_VARS)
682
- referencesVar(groq2, caller) && issues.push({
683
- path: ["predicates", name],
684
- message: `predicate "${name}" reads $${caller} \u2014 predicates are instance-level (pre-evaluated once, without a caller); compose caller gates at the condition site instead`
685
- });
686
- for (const other of names)
687
- other === name || !referencesVar(groq2, other) || issues.push({
688
- path: ["predicates", name],
689
- message: `predicate "${name}" references predicate $${other} \u2014 predicates may read built-in vars only (no cross-references; compose at the condition site instead)`
38
+
39
+ function defineAction(action) {
40
+ return parseOrThrow({
41
+ schema: AuthoringActionSchema,
42
+ input: action,
43
+ label: labelFor("defineAction", action)
690
44
  });
691
45
  }
692
- function referencesVar(groq2, name) {
693
- return GROQ_IDENTIFIER.test(name) ? new RegExp(`\\$${name}\\b`).test(groq2) : !1;
694
- }
695
- function checkCanOutsideActionFilters(def, issues) {
696
- for (const site of nonActionFilterConditionSites(def))
697
- referencesVar(site.groq, "can") && issues.push({
698
- path: site.path,
699
- message: `${site.label} reads $can \u2014 $can (the caller's grants) is bound only when an action fires, so it may appear in action filters only`
46
+
47
+ function defineTransition(transition) {
48
+ return parseOrThrow({
49
+ schema: AuthoringTransitionSchema,
50
+ input: transition,
51
+ label: transitionLabel(transition)
700
52
  });
701
53
  }
702
- function nonActionFilterConditionSites(def) {
703
- const sites = [];
704
- for (const [i, stage] of def.stages.entries()) {
705
- for (const [k, t] of (stage.transitions ?? []).entries())
706
- sites.push({
707
- groq: t.filter,
708
- path: ["stages", i, "transitions", k, "filter"],
709
- label: `transition "${t.name}" filter`
710
- }), collectBindingSites({
711
- effects: t.effects,
712
- path: ["stages", i, "transitions", k, "effects"],
713
- label: `transition "${t.name}"`,
714
- sites
715
- }), collectOpWhereSites({
716
- ops: t.ops,
717
- path: ["stages", i, "transitions", k, "ops"],
718
- label: `transition "${t.name}"`,
719
- sites
720
- });
721
- for (const [j, activity] of (stage.activities ?? []).entries())
722
- collectActivityConditionSites({ activity, path: ["stages", i, "activities", j], sites });
723
- }
724
- return sites;
725
- }
726
- function collectOpWhereSites({
727
- ops,
728
- path,
729
- label,
730
- sites
731
- }) {
732
- for (const [o, op] of (ops ?? []).entries())
733
- op.where !== void 0 && sites.push({
734
- groq: op.where,
735
- path: [...path, o, "where"],
736
- label: `${label} ${op.type} where`
54
+
55
+ function defineField(entry) {
56
+ return parseOrThrow({
57
+ schema: AuthoringFieldEntrySchema,
58
+ input: entry,
59
+ label: labelFor("defineField", entry)
737
60
  });
738
61
  }
739
- function collectActivityConditionSites({
740
- activity,
741
- path,
742
- sites
743
- }) {
744
- for (const field of ["filter", "completeWhen", "failWhen"]) {
745
- const groq2 = activity[field];
746
- groq2 !== void 0 && sites.push({ groq: groq2, path: [...path, field], label: `activity "${activity.name}".${field}` });
747
- }
748
- collectBindingSites({
749
- effects: activity.effects,
750
- path: [...path, "effects"],
751
- label: `activity "${activity.name}"`,
752
- sites
753
- }), collectOpWhereSites({
754
- ops: activity.ops,
755
- path: [...path, "ops"],
756
- label: `activity "${activity.name}"`,
757
- sites
758
- });
759
- for (const [a, action] of (activity.actions ?? []).entries())
760
- collectBindingSites({
761
- effects: action.effects,
762
- path: [...path, "actions", a, "effects"],
763
- label: `action "${action.name}"`,
764
- sites
765
- }), collectOpWhereSites({
766
- ops: action.ops,
767
- path: [...path, "actions", a, "ops"],
768
- label: `action "${action.name}"`,
769
- sites
62
+
63
+ function defineOp(op) {
64
+ return parseOrThrow({
65
+ schema: AuthoringOpSchema,
66
+ input: op,
67
+ label: "defineOp"
770
68
  });
771
- collectSubworkflowSites({ activity, path, sites });
772
69
  }
773
- function collectSubworkflowSites({
774
- activity,
775
- path,
776
- sites
777
- }) {
778
- const sub = activity.subworkflows;
779
- if (sub === void 0) return;
780
- const subPath = [...path, "subworkflows"];
781
- sites.push({
782
- groq: sub.forEach,
783
- path: [...subPath, "forEach"],
784
- label: `activity "${activity.name}".subworkflows.forEach`
785
- });
786
- for (const [group, record] of [
787
- ["with", sub.with],
788
- ["context", sub.context]
789
- ])
790
- for (const [key, groq2] of Object.entries(record ?? {}))
791
- sites.push({
792
- groq: groq2,
793
- path: [...subPath, group, key],
794
- label: `activity "${activity.name}".subworkflows.${group} "${key}"`
795
- });
796
- }
797
- function collectBindingSites({
798
- effects,
799
- path,
800
- label,
801
- sites
802
- }) {
803
- for (const [e, effect] of (effects ?? []).entries())
804
- for (const [key, groq2] of Object.entries(effect.bindings ?? {}))
805
- sites.push({
806
- groq: groq2,
807
- path: [...path, e, "bindings", key],
808
- label: `${label} effect "${effect.name}" binding "${key}"`
809
- });
810
- }
811
- function checkAssigneesEntries(def, issues) {
812
- for (const { entries, path } of fieldScopes(def))
813
- (entries ?? []).filter((e) => e.type === "assignees").length <= 1 || issues.push({
814
- path,
815
- message: "at most one assignees-kind field entry per scope \u2014 the inbox reads it by kind"
70
+
71
+ function defineGroup(group) {
72
+ return parseOrThrow({
73
+ schema: GroupSchema,
74
+ input: group,
75
+ label: labelFor("defineGroup", group)
816
76
  });
817
77
  }
818
- function activityShape(activity) {
819
- return {
820
- hasActions: (activity.actions ?? []).length > 0,
821
- hasEffects: (activity.effects ?? []).length > 0,
822
- hasCompleteWhen: activity.completeWhen !== void 0,
823
- hasSubworkflows: activity.subworkflows !== void 0
824
- };
825
- }
826
- const KIND_SHAPE_RULES = {
827
- user: (s) => s.hasActions ? [] : ["needs at least one action for a person to fire"],
828
- service: (s) => s.hasEffects ? [] : ["needs at least one effect \u2014 the automated work it performs"],
829
- manual: (s) => [
830
- s.hasActions || s.hasCompleteWhen ? void 0 : "needs a way to complete \u2014 an action to acknowledge it, or a `completeWhen` predicate to verify it (otherwise it auto-resolves on activation)",
831
- s.hasSubworkflows ? "is off-system work, not a fan-out \u2014 drop `subworkflows` or move it to its own activity" : void 0
832
- ].filter((m) => m !== void 0),
833
- receive: (s) => [
834
- s.hasCompleteWhen || s.hasSubworkflows ? void 0 : "needs a `completeWhen` (or `subworkflows`) condition to wait on",
835
- s.hasActions ? "has no actor, so it cannot carry actions" : void 0
836
- ].filter((m) => m !== void 0),
837
- script: (s) => [
838
- s.hasActions ? "runs inline with no actor, so it cannot carry actions" : void 0,
839
- s.hasCompleteWhen ? "resolves on activation, so it cannot carry a `completeWhen` (that is a `receive`/`service` wait)" : void 0,
840
- s.hasSubworkflows ? "resolves on activation, so it cannot fan out with `subworkflows`" : void 0
841
- ].filter((m) => m !== void 0)
842
- };
843
- function checkActivityKinds(def, issues) {
844
- for (const [i, stage] of def.stages.entries())
845
- for (const [j, activity] of (stage.activities ?? []).entries()) {
846
- const path = ["stages", i, "activities", j];
847
- if (activity.target !== void 0 && activity.kind !== "manual" && issues.push({
848
- path: [...path, "target"],
849
- message: `activity "${activity.name}" has a \`target\` but is not \`kind: "manual"\` \u2014 a target is the deep-link for off-system manual work`
850
- }), activity.kind !== void 0)
851
- for (const fault of KIND_SHAPE_RULES[activity.kind](activityShape(activity)))
852
- issues.push({
853
- path: [...path, "kind"],
854
- message: `activity "${activity.name}" declares kind "${activity.kind}" but ${fault}`
855
- });
856
- }
857
- }
858
- function checkWorkflowInvariants(def) {
859
- const issues = [], stageNames = checkStages(def, issues);
860
- return checkInitialStage({ def, stageNames, issues }), checkTransitionTargets({ def, stageNames, issues }), checkEffectNames(def, issues), checkGuardNames(def, issues), checkFieldEntryNames(def, issues), checkRequiredField(def, issues), checkPredicates(def, issues), checkCanOutsideActionFilters(def, issues), checkAssigneesEntries(def, issues), checkActivityKinds(def, issues), issues;
861
- }
862
- function defineWorkflow(definition) {
863
- const label = labelFor("defineWorkflow", definition), parsed = parseOrThrow({ schema: AuthoringWorkflowSchema, input: definition, label }), { definition: stored, issues: desugarIssues } = desugarWorkflow(parsed), issues = [...desugarIssues, ...checkWorkflowInvariants(stored)];
864
- if (issues.length > 0) throw new Error(formatValidationError(label, issues));
865
- return stored;
866
- }
867
- function defineWorkflowConfig(config) {
868
- return parseOrThrow({ schema: WorkflowConfigSchema, input: config, label: "defineWorkflowConfig" });
869
- }
870
- function defineStage(stage) {
871
- return parseOrThrow({
872
- schema: AuthoringStageSchema,
873
- input: stage,
874
- label: labelFor("defineStage", stage)
875
- });
876
- }
877
- function defineActivity(activity) {
878
- return parseOrThrow({
879
- schema: AuthoringActivitySchema,
880
- input: activity,
881
- label: labelFor("defineActivity", activity)
882
- });
883
- }
884
- function defineAction(action) {
885
- return parseOrThrow({
886
- schema: AuthoringActionSchema,
887
- input: action,
888
- label: labelFor("defineAction", action)
889
- });
890
- }
891
- function defineTransition(transition) {
892
- return parseOrThrow({
893
- schema: AuthoringTransitionSchema,
894
- input: transition,
895
- label: transitionLabel(transition)
896
- });
897
- }
898
- function defineField(entry) {
899
- return parseOrThrow({
900
- schema: AuthoringFieldEntrySchema,
901
- input: entry,
902
- label: labelFor("defineField", entry)
903
- });
904
- }
905
- function defineOp(op) {
906
- return parseOrThrow({ schema: AuthoringOpSchema, input: op, label: "defineOp" });
907
- }
78
+
908
79
  function defineGuard(guard) {
909
- return parseOrThrow({
910
- schema: AuthoringGuardSchema,
911
- input: guard,
912
- label: labelFor("defineGuard", guard)
913
- });
80
+ return parseOrThrow({
81
+ schema: AuthoringGuardSchema,
82
+ input: guard,
83
+ label: labelFor("defineGuard", guard)
84
+ });
914
85
  }
86
+
915
87
  function defineEffect(effect) {
916
- return parseOrThrow({
917
- schema: EffectSchema,
918
- input: effect,
919
- label: labelFor("defineEffect", effect)
920
- });
88
+ return parseOrThrow({
89
+ schema: EffectSchema,
90
+ input: effect,
91
+ label: labelFor("defineEffect", effect)
92
+ });
921
93
  }
94
+
922
95
  function transitionLabel(transition) {
923
- const { name, to } = transition;
924
- return typeof name == "string" ? `defineTransition("${name}")` : typeof to == "string" ? `defineTransition(\u2192 "${to}")` : "defineTransition";
96
+ const {name: name, to: to} = transition;
97
+ return typeof name == "string" ? `defineTransition("${name}")` : typeof to == "string" ? `defineTransition( "${to}")` : "defineTransition";
925
98
  }
99
+
926
100
  function defineEffectDescriptor(descriptor) {
927
- if (!descriptor.name) throw new Error("EffectDescriptor missing name");
928
- return descriptor;
929
- }
930
- function parseOrThrow({
931
- schema,
932
- input,
933
- label
934
- }) {
935
- const result = v.safeParse(schema, input);
936
- if (!result.success)
937
- throw new Error(formatValidationError(label, issuesFromValibot(result.issues)));
938
- return result.output;
939
- }
940
- function labelFor(fn, value) {
941
- if (value && typeof value == "object" && "name" in value) {
942
- const raw = value.name;
943
- if (typeof raw == "string") return `${fn}("${raw}")`;
944
- }
945
- return fn;
101
+ if (!descriptor.name) throw new Error("EffectDescriptor missing name");
102
+ return descriptor;
946
103
  }
947
- export {
948
- CONDITION_VARS,
949
- FILTER_SCOPE_VARS,
950
- GUARD_PREDICATE_VARS,
951
- RESERVED_CONDITION_VARS,
952
- defineAction,
953
- defineActivity,
954
- defineEffect,
955
- defineEffectDescriptor,
956
- defineField,
957
- defineGuard,
958
- defineOp,
959
- defineStage,
960
- defineTransition,
961
- defineWorkflow,
962
- defineWorkflowConfig,
963
- groq
964
- };
965
- //# sourceMappingURL=define.js.map
104
+
105
+ export { CONDITION_VARS, FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS, RESERVED_CONDITION_VARS, defineAction, defineActivity, defineEffect, defineEffectDescriptor, defineField, defineGroup, defineGuard, defineOp, defineStage, defineTransition, defineWorkflow, defineWorkflowConfig, groq };