@contractspec/example.workflow-system 3.8.8 → 3.8.10

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.
Files changed (95) hide show
  1. package/dist/approval/approval.enum.js +1 -22
  2. package/dist/approval/approval.event.js +1 -112
  3. package/dist/approval/approval.operations.js +1 -369
  4. package/dist/approval/approval.schema.js +1 -73
  5. package/dist/approval/index.js +1 -484
  6. package/dist/browser/approval/approval.enum.js +1 -22
  7. package/dist/browser/approval/approval.event.js +1 -112
  8. package/dist/browser/approval/approval.operations.js +1 -369
  9. package/dist/browser/approval/approval.schema.js +1 -73
  10. package/dist/browser/approval/index.js +1 -484
  11. package/dist/browser/docs/index.js +5 -49
  12. package/dist/browser/docs/workflow-system.docblock.js +5 -49
  13. package/dist/browser/entities/approval.js +1 -119
  14. package/dist/browser/entities/index.js +1 -508
  15. package/dist/browser/entities/instance.js +1 -161
  16. package/dist/browser/entities/step.js +1 -124
  17. package/dist/browser/entities/workflow.js +1 -82
  18. package/dist/browser/example.js +1 -42
  19. package/dist/browser/handlers/index.js +8 -253
  20. package/dist/browser/handlers/workflow.handlers.js +8 -253
  21. package/dist/browser/index.js +13 -3524
  22. package/dist/browser/instance/index.js +1 -677
  23. package/dist/browser/instance/instance.enum.js +1 -15
  24. package/dist/browser/instance/instance.event.js +1 -164
  25. package/dist/browser/instance/instance.handler.js +1 -356
  26. package/dist/browser/instance/instance.operations.js +1 -9
  27. package/dist/browser/instance/instance.schema.js +1 -101
  28. package/dist/browser/presentations/index.js +1 -109
  29. package/dist/browser/seeders/index.js +1 -3
  30. package/dist/browser/shared/demo-scenario.js +1 -213
  31. package/dist/browser/shared/index.js +1 -3
  32. package/dist/browser/shared/mock-data.js +1 -11
  33. package/dist/browser/state-machine/index.js +1 -6
  34. package/dist/browser/tests/operations.test-spec.js +1 -6
  35. package/dist/browser/ui/WorkflowDashboard.js +1 -3
  36. package/dist/browser/ui/WorkflowDashboard.visualizations.js +1 -239
  37. package/dist/browser/ui/hooks/index.js +1 -3
  38. package/dist/browser/ui/hooks/useWorkflowList.js +1 -52
  39. package/dist/browser/ui/index.js +1 -56
  40. package/dist/browser/ui/renderers/index.js +5 -562
  41. package/dist/browser/ui/renderers/workflow.markdown.js +5 -562
  42. package/dist/browser/visualizations/catalog.js +1 -132
  43. package/dist/browser/visualizations/index.js +1 -133
  44. package/dist/browser/visualizations/selectors.js +1 -195
  45. package/dist/browser/workflow/index.js +1 -21
  46. package/dist/browser/workflow/workflow.enum.js +1 -36
  47. package/dist/browser/workflow/workflow.event.js +1 -6
  48. package/dist/browser/workflow/workflow.handler.js +1 -5
  49. package/dist/browser/workflow/workflow.operations.js +1 -8
  50. package/dist/browser/workflow/workflow.schema.js +1 -151
  51. package/dist/browser/workflow-system.capability.js +1 -5
  52. package/dist/browser/workflow-system.feature.js +1 -3
  53. package/dist/docs/index.js +5 -49
  54. package/dist/docs/workflow-system.docblock.js +5 -49
  55. package/dist/entities/approval.js +1 -119
  56. package/dist/entities/index.js +1 -508
  57. package/dist/entities/instance.js +1 -161
  58. package/dist/entities/step.js +1 -124
  59. package/dist/entities/workflow.js +1 -82
  60. package/dist/example.js +1 -42
  61. package/dist/handlers/index.js +8 -253
  62. package/dist/handlers/workflow.handlers.js +8 -253
  63. package/dist/index.js +13 -3524
  64. package/dist/instance/index.js +1 -677
  65. package/dist/instance/instance.enum.js +1 -15
  66. package/dist/instance/instance.event.js +1 -164
  67. package/dist/instance/instance.handler.js +1 -356
  68. package/dist/instance/instance.operations.js +1 -9
  69. package/dist/instance/instance.schema.js +1 -101
  70. package/dist/presentations/index.js +1 -109
  71. package/dist/seeders/index.js +1 -3
  72. package/dist/shared/demo-scenario.js +1 -213
  73. package/dist/shared/index.js +1 -3
  74. package/dist/shared/mock-data.js +1 -11
  75. package/dist/state-machine/index.js +1 -6
  76. package/dist/tests/operations.test-spec.js +1 -6
  77. package/dist/ui/WorkflowDashboard.js +1 -3
  78. package/dist/ui/WorkflowDashboard.visualizations.js +1 -239
  79. package/dist/ui/hooks/index.js +1 -3
  80. package/dist/ui/hooks/useWorkflowList.js +1 -52
  81. package/dist/ui/index.js +1 -56
  82. package/dist/ui/renderers/index.js +5 -562
  83. package/dist/ui/renderers/workflow.markdown.js +5 -562
  84. package/dist/visualizations/catalog.js +1 -132
  85. package/dist/visualizations/index.js +1 -133
  86. package/dist/visualizations/selectors.js +1 -195
  87. package/dist/workflow/index.js +1 -21
  88. package/dist/workflow/workflow.enum.js +1 -36
  89. package/dist/workflow/workflow.event.js +1 -6
  90. package/dist/workflow/workflow.handler.js +1 -5
  91. package/dist/workflow/workflow.operations.js +1 -8
  92. package/dist/workflow/workflow.schema.js +1 -151
  93. package/dist/workflow-system.capability.js +1 -5
  94. package/dist/workflow-system.feature.js +1 -3
  95. package/package.json +11 -11
@@ -1,3524 +1,13 @@
1
- // src/approval/approval.enum.ts
2
- import { defineEnum } from "@contractspec/lib.schema";
3
- var ApprovalStatusEnum = defineEnum("ApprovalStatus", [
4
- "PENDING",
5
- "APPROVED",
6
- "REJECTED",
7
- "DELEGATED",
8
- "ESCALATED",
9
- "WITHDRAWN",
10
- "EXPIRED"
11
- ]);
12
- var ApprovalDecisionEnum = defineEnum("ApprovalDecision", [
13
- "APPROVE",
14
- "REJECT",
15
- "REQUEST_CHANGES",
16
- "DELEGATE",
17
- "ABSTAIN"
18
- ]);
19
-
20
- // src/approval/approval.event.ts
21
- import { defineEvent } from "@contractspec/lib.contracts-spec";
22
- import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
23
- var ApprovalRequestedPayload = defineSchemaModel({
24
- name: "ApprovalRequestedEventPayload",
25
- description: "Payload when approval is requested",
26
- fields: {
27
- requestId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
28
- instanceId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
29
- workflowKey: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
30
- approverId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
31
- approverRole: {
32
- type: ScalarTypeEnum.String_unsecure(),
33
- isOptional: true
34
- },
35
- title: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
36
- dueAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
37
- timestamp: { type: ScalarTypeEnum.DateTime(), isOptional: false }
38
- }
39
- });
40
- var ApprovalDecidedPayload = defineSchemaModel({
41
- name: "ApprovalDecidedEventPayload",
42
- description: "Payload when approval decision is made",
43
- fields: {
44
- requestId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
45
- instanceId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
46
- decision: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
47
- decidedBy: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
48
- comment: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
49
- timestamp: { type: ScalarTypeEnum.DateTime(), isOptional: false }
50
- }
51
- });
52
- var ApprovalDelegatedPayload = defineSchemaModel({
53
- name: "ApprovalDelegatedEventPayload",
54
- description: "Payload when approval is delegated",
55
- fields: {
56
- requestId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
57
- instanceId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
58
- fromUserId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
59
- toUserId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
60
- reason: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
61
- timestamp: { type: ScalarTypeEnum.DateTime(), isOptional: false }
62
- }
63
- });
64
- var ApprovalEscalatedPayload = defineSchemaModel({
65
- name: "ApprovalEscalatedEventPayload",
66
- description: "Payload when approval is escalated",
67
- fields: {
68
- requestId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
69
- instanceId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
70
- escalationLevel: {
71
- type: ScalarTypeEnum.Int_unsecure(),
72
- isOptional: false
73
- },
74
- escalatedTo: {
75
- type: ScalarTypeEnum.String_unsecure(),
76
- isOptional: false
77
- },
78
- reason: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
79
- timestamp: { type: ScalarTypeEnum.DateTime(), isOptional: false }
80
- }
81
- });
82
- var ApprovalRequestedEvent = defineEvent({
83
- meta: {
84
- key: "workflow.approval.requested",
85
- version: "1.0.0",
86
- description: "An approval has been requested.",
87
- stability: "stable",
88
- owners: ["@workflow-team"],
89
- tags: ["workflow", "approval", "requested"]
90
- },
91
- payload: ApprovalRequestedPayload
92
- });
93
- var ApprovalDecidedEvent = defineEvent({
94
- meta: {
95
- key: "workflow.approval.decided",
96
- version: "1.0.0",
97
- description: "An approval decision has been made.",
98
- stability: "stable",
99
- owners: ["@workflow-team"],
100
- tags: ["workflow", "approval", "decided"]
101
- },
102
- payload: ApprovalDecidedPayload
103
- });
104
- var ApprovalDelegatedEvent = defineEvent({
105
- meta: {
106
- key: "workflow.approval.delegated",
107
- version: "1.0.0",
108
- description: "An approval has been delegated.",
109
- stability: "stable",
110
- owners: ["@workflow-team"],
111
- tags: ["workflow", "approval", "delegated"]
112
- },
113
- payload: ApprovalDelegatedPayload
114
- });
115
- var ApprovalEscalatedEvent = defineEvent({
116
- meta: {
117
- key: "workflow.approval.escalated",
118
- version: "1.0.0",
119
- description: "An approval has been escalated.",
120
- stability: "stable",
121
- owners: ["@workflow-team"],
122
- tags: ["workflow", "approval", "escalated"]
123
- },
124
- payload: ApprovalEscalatedPayload
125
- });
126
-
127
- // src/shared/mock-data.ts
128
- var mockDataStore = {
129
- workflows: new Map,
130
- steps: new Map,
131
- instances: new Map,
132
- approvals: new Map,
133
- stepExecutions: new Map
134
- };
135
-
136
- // src/state-machine/index.ts
137
- class BasicStateMachineEngine {
138
- canTransition(definition, state, action, context) {
139
- if (state.status !== "RUNNING" && state.status !== "WAITING") {
140
- return {
141
- allowed: false,
142
- reason: `Workflow is ${state.status}, cannot transition`
143
- };
144
- }
145
- const currentStep = definition.steps[state.currentStepKey];
146
- if (!currentStep) {
147
- return {
148
- allowed: false,
149
- reason: `Step ${state.currentStepKey} not found`
150
- };
151
- }
152
- const transition = currentStep.transitions[action];
153
- if (!transition) {
154
- return {
155
- allowed: false,
156
- reason: `Action ${action} not available in step ${state.currentStepKey}`
157
- };
158
- }
159
- if (currentStep.allowedRoles && currentStep.allowedRoles.length > 0) {
160
- const hasRole = currentStep.allowedRoles.some((role) => context.userRoles.includes(role));
161
- if (!hasRole) {
162
- return {
163
- allowed: false,
164
- reason: `User lacks required role for this action`
165
- };
166
- }
167
- }
168
- if (typeof transition === "object" && transition.allowedRoles && transition.allowedRoles.length > 0) {
169
- const hasRole = transition.allowedRoles.some((role) => context.userRoles.includes(role));
170
- if (!hasRole) {
171
- return {
172
- allowed: false,
173
- reason: `User lacks required role for action ${action}`
174
- };
175
- }
176
- }
177
- return { allowed: true };
178
- }
179
- getAvailableActions(definition, state, context) {
180
- if (state.status !== "RUNNING" && state.status !== "WAITING") {
181
- return [];
182
- }
183
- const currentStep = definition.steps[state.currentStepKey];
184
- if (!currentStep) {
185
- return [];
186
- }
187
- return Object.keys(currentStep.transitions).filter((action) => {
188
- const result = this.canTransition(definition, state, action, context);
189
- return result.allowed;
190
- });
191
- }
192
- transition(definition, state, action, context) {
193
- const validation = this.canTransition(definition, state, action, context);
194
- if (!validation.allowed) {
195
- return {
196
- success: false,
197
- previousStepKey: state.currentStepKey,
198
- currentStepKey: state.currentStepKey,
199
- status: state.status,
200
- error: validation.reason
201
- };
202
- }
203
- const currentStep = definition.steps[state.currentStepKey];
204
- if (!currentStep) {
205
- return {
206
- success: false,
207
- previousStepKey: state.currentStepKey,
208
- currentStepKey: state.currentStepKey,
209
- status: state.status,
210
- error: `Current step ${state.currentStepKey} not found`
211
- };
212
- }
213
- const transition = currentStep.transitions[action];
214
- if (!transition) {
215
- return {
216
- success: false,
217
- previousStepKey: state.currentStepKey,
218
- currentStepKey: state.currentStepKey,
219
- status: state.status,
220
- error: `Transition for action ${action} not found`
221
- };
222
- }
223
- const targetStepKey = typeof transition === "string" ? transition : transition.targetStepKey;
224
- const targetStep = definition.steps[targetStepKey];
225
- if (!targetStep) {
226
- return {
227
- success: false,
228
- previousStepKey: state.currentStepKey,
229
- currentStepKey: state.currentStepKey,
230
- status: state.status,
231
- error: `Target step ${targetStepKey} not found`
232
- };
233
- }
234
- let newStatus = "RUNNING";
235
- if (targetStep.type === "END") {
236
- newStatus = "COMPLETED";
237
- } else if (targetStep.type === "APPROVAL" || targetStep.type === "WAIT") {
238
- newStatus = "WAITING";
239
- }
240
- return {
241
- success: true,
242
- previousStepKey: state.currentStepKey,
243
- currentStepKey: targetStepKey,
244
- status: newStatus
245
- };
246
- }
247
- evaluateCondition(expression, contextData) {
248
- try {
249
- const match = expression.match(/^(\w+)\s*(>=|<=|>|<|===|!==|==|!=)\s*(.+)$/);
250
- if (match) {
251
- const [, prop, operator, value] = match;
252
- if (!prop || !operator || value === undefined) {
253
- return false;
254
- }
255
- const propValue = contextData[prop];
256
- const compareValue = JSON.parse(value);
257
- switch (operator) {
258
- case ">":
259
- return Number(propValue) > Number(compareValue);
260
- case "<":
261
- return Number(propValue) < Number(compareValue);
262
- case ">=":
263
- return Number(propValue) >= Number(compareValue);
264
- case "<=":
265
- return Number(propValue) <= Number(compareValue);
266
- case "===":
267
- case "==":
268
- return propValue === compareValue;
269
- case "!==":
270
- case "!=":
271
- return propValue !== compareValue;
272
- }
273
- }
274
- if (expression in contextData) {
275
- return Boolean(contextData[expression]);
276
- }
277
- return false;
278
- } catch {
279
- return false;
280
- }
281
- }
282
- }
283
- function createStateMachineEngine() {
284
- return new BasicStateMachineEngine;
285
- }
286
- function buildStateMachineDefinition(workflow, steps) {
287
- const stepMap = {};
288
- for (const step of steps) {
289
- stepMap[step.key] = {
290
- key: step.key,
291
- name: step.name,
292
- type: step.type,
293
- transitions: step.transitions,
294
- approvalMode: step.approvalMode,
295
- allowedRoles: step.approverRoles,
296
- timeoutSeconds: step.timeoutSeconds,
297
- conditionExpression: step.conditionExpression
298
- };
299
- }
300
- const startStep = steps.find((s) => s.type === "START");
301
- const initialStepKey = startStep?.key ?? steps[0]?.key ?? "";
302
- return {
303
- key: workflow.key,
304
- name: workflow.name,
305
- version: workflow.version,
306
- initialStepKey,
307
- steps: stepMap
308
- };
309
- }
310
- function createInitialState(definition, contextData = {}) {
311
- return {
312
- currentStepKey: definition.initialStepKey,
313
- status: "RUNNING",
314
- contextData,
315
- history: []
316
- };
317
- }
318
-
319
- // src/approval/approval.schema.ts
320
- import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
321
- var ApprovalRequestModel = defineSchemaModel2({
322
- name: "ApprovalRequestModel",
323
- description: "An approval request",
324
- fields: {
325
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
326
- workflowInstanceId: {
327
- type: ScalarTypeEnum2.String_unsecure(),
328
- isOptional: false
329
- },
330
- stepExecutionId: {
331
- type: ScalarTypeEnum2.String_unsecure(),
332
- isOptional: false
333
- },
334
- approverId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
335
- approverRole: {
336
- type: ScalarTypeEnum2.String_unsecure(),
337
- isOptional: true
338
- },
339
- title: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
340
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
341
- status: { type: ApprovalStatusEnum, isOptional: false },
342
- decision: { type: ApprovalDecisionEnum, isOptional: true },
343
- decisionComment: {
344
- type: ScalarTypeEnum2.String_unsecure(),
345
- isOptional: true
346
- },
347
- decidedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: true },
348
- dueAt: { type: ScalarTypeEnum2.DateTime(), isOptional: true },
349
- contextSnapshot: { type: ScalarTypeEnum2.JSON(), isOptional: true },
350
- sequenceOrder: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
351
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
352
- }
353
- });
354
- var ApprovalCommentModel = defineSchemaModel2({
355
- name: "ApprovalCommentModel",
356
- description: "A comment on an approval",
357
- fields: {
358
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
359
- approvalRequestId: {
360
- type: ScalarTypeEnum2.String_unsecure(),
361
- isOptional: false
362
- },
363
- authorId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
364
- content: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
365
- isInternal: { type: ScalarTypeEnum2.Boolean(), isOptional: false },
366
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
367
- }
368
- });
369
-
370
- // src/approval/approval.operations.ts
371
- import {
372
- defineCommand,
373
- defineQuery
374
- } from "@contractspec/lib.contracts-spec/operations";
375
- import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
376
- var OWNERS = ["@example.workflow-system"];
377
- var SubmitDecisionContract = defineCommand({
378
- meta: {
379
- key: "workflow.approval.decide",
380
- version: "1.0.0",
381
- stability: "stable",
382
- owners: [...OWNERS],
383
- tags: ["workflow", "approval", "decision"],
384
- description: "Submit an approval decision (approve/reject).",
385
- goal: "Allow approvers to make decisions on requests.",
386
- context: "Approval inbox, workflow detail."
387
- },
388
- io: {
389
- input: defineSchemaModel3({
390
- name: "ApproveRejectInput",
391
- fields: {
392
- requestId: {
393
- type: ScalarTypeEnum3.String_unsecure(),
394
- isOptional: false
395
- },
396
- decision: { type: ApprovalDecisionEnum, isOptional: false },
397
- comment: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
398
- data: { type: ScalarTypeEnum3.JSON(), isOptional: true }
399
- }
400
- }),
401
- output: ApprovalRequestModel
402
- },
403
- policy: { auth: "user" },
404
- sideEffects: {
405
- emits: [
406
- {
407
- key: "workflow.approval.decided",
408
- version: "1.0.0",
409
- when: "Decision is made",
410
- payload: ApprovalRequestModel
411
- }
412
- ],
413
- audit: ["workflow.approval.decided"]
414
- },
415
- acceptance: {
416
- scenarios: [
417
- {
418
- key: "approve-request-happy-path",
419
- given: ["Approval request is pending", "User is assignee"],
420
- when: ["User approves request"],
421
- then: ["Request is approved", "ApprovalDecided event is emitted"]
422
- }
423
- ],
424
- examples: [
425
- {
426
- key: "approve-basic",
427
- input: {
428
- requestId: "req-123",
429
- decision: "approve",
430
- comment: "Looks good"
431
- },
432
- output: { id: "req-123", status: "approved" }
433
- }
434
- ]
435
- }
436
- });
437
- var DelegateApprovalContract = defineCommand({
438
- meta: {
439
- key: "workflow.approval.delegate",
440
- version: "1.0.0",
441
- stability: "stable",
442
- owners: [...OWNERS],
443
- tags: ["workflow", "approval", "delegate"],
444
- description: "Delegate an approval request to another user.",
445
- goal: "Allow approvers to pass approval to others.",
446
- context: "Approval inbox."
447
- },
448
- io: {
449
- input: defineSchemaModel3({
450
- name: "DelegateInput",
451
- fields: {
452
- requestId: {
453
- type: ScalarTypeEnum3.String_unsecure(),
454
- isOptional: false
455
- },
456
- delegateTo: {
457
- type: ScalarTypeEnum3.String_unsecure(),
458
- isOptional: false
459
- },
460
- reason: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true }
461
- }
462
- }),
463
- output: ApprovalRequestModel
464
- },
465
- policy: { auth: "user" },
466
- sideEffects: {
467
- emits: [
468
- {
469
- key: "workflow.approval.delegated",
470
- version: "1.0.0",
471
- when: "Approval is delegated",
472
- payload: ApprovalRequestModel
473
- }
474
- ],
475
- audit: ["workflow.approval.delegated"]
476
- },
477
- acceptance: {
478
- scenarios: [
479
- {
480
- key: "delegate-approval-happy-path",
481
- given: ["Approval request is pending", "User is assignee"],
482
- when: ["User delegates to another user"],
483
- then: ["Assignee is updated", "ApprovalDelegated event is emitted"]
484
- }
485
- ],
486
- examples: [
487
- {
488
- key: "delegate-to-manager",
489
- input: {
490
- requestId: "req-123",
491
- delegateTo: "user-456",
492
- reason: "Out of office"
493
- },
494
- output: { id: "req-123", assigneeId: "user-456" }
495
- }
496
- ]
497
- }
498
- });
499
- var AddApprovalCommentContract = defineCommand({
500
- meta: {
501
- key: "workflow.approval.comment.add",
502
- version: "1.0.0",
503
- stability: "stable",
504
- owners: [...OWNERS],
505
- tags: ["workflow", "approval", "comment"],
506
- description: "Add a comment to an approval request.",
507
- goal: "Allow discussion on approval requests.",
508
- context: "Approval detail view."
509
- },
510
- io: {
511
- input: defineSchemaModel3({
512
- name: "AddCommentInput",
513
- fields: {
514
- requestId: {
515
- type: ScalarTypeEnum3.String_unsecure(),
516
- isOptional: false
517
- },
518
- content: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
519
- isInternal: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
520
- }
521
- }),
522
- output: ApprovalCommentModel
523
- },
524
- policy: { auth: "user" },
525
- sideEffects: {
526
- emits: [
527
- {
528
- key: "workflow.approval.comment.added",
529
- version: "1.0.0",
530
- when: "Comment is added",
531
- payload: ApprovalCommentModel
532
- }
533
- ]
534
- },
535
- acceptance: {
536
- scenarios: [
537
- {
538
- key: "add-comment-happy-path",
539
- given: ["Approval request exists"],
540
- when: ["User adds a comment"],
541
- then: ["Comment is added", "CommentAdded event is emitted"]
542
- }
543
- ],
544
- examples: [
545
- {
546
- key: "add-question",
547
- input: {
548
- requestId: "req-123",
549
- content: "Can you clarify budget?",
550
- isInternal: false
551
- },
552
- output: { id: "com-789", content: "Can you clarify budget?" }
553
- }
554
- ]
555
- }
556
- });
557
- var ListMyApprovalsContract = defineQuery({
558
- meta: {
559
- key: "workflow.approval.list.mine",
560
- version: "1.0.0",
561
- stability: "stable",
562
- owners: [...OWNERS],
563
- tags: ["workflow", "approval", "list", "inbox"],
564
- description: "List approval requests assigned to current user.",
565
- goal: "Show pending approvals in user inbox.",
566
- context: "Approval inbox, dashboard widget."
567
- },
568
- io: {
569
- input: defineSchemaModel3({
570
- name: "ListMyApprovalsInput",
571
- fields: {
572
- status: { type: ApprovalStatusEnum, isOptional: true },
573
- limit: {
574
- type: ScalarTypeEnum3.Int_unsecure(),
575
- isOptional: true,
576
- defaultValue: 20
577
- },
578
- offset: {
579
- type: ScalarTypeEnum3.Int_unsecure(),
580
- isOptional: true,
581
- defaultValue: 0
582
- }
583
- }
584
- }),
585
- output: defineSchemaModel3({
586
- name: "ListMyApprovalsOutput",
587
- fields: {
588
- requests: {
589
- type: ApprovalRequestModel,
590
- isArray: true,
591
- isOptional: false
592
- },
593
- total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
594
- pendingCount: {
595
- type: ScalarTypeEnum3.Int_unsecure(),
596
- isOptional: false
597
- }
598
- }
599
- })
600
- },
601
- policy: { auth: "user" },
602
- acceptance: {
603
- scenarios: [
604
- {
605
- key: "list-approvals-happy-path",
606
- given: ["User has assigned approvals"],
607
- when: ["User lists approvals"],
608
- then: ["List of requests is returned"]
609
- }
610
- ],
611
- examples: [
612
- {
613
- key: "list-pending",
614
- input: { status: "pending", limit: 10 },
615
- output: { requests: [], total: 2, pendingCount: 2 }
616
- }
617
- ]
618
- }
619
- });
620
- var GetApprovalContract = defineQuery({
621
- meta: {
622
- key: "workflow.approval.get",
623
- version: "1.0.0",
624
- stability: "stable",
625
- owners: [...OWNERS],
626
- tags: ["workflow", "approval", "get"],
627
- description: "Get an approval request with details.",
628
- goal: "View approval request details.",
629
- context: "Approval detail view."
630
- },
631
- io: {
632
- input: defineSchemaModel3({
633
- name: "GetApprovalInput",
634
- fields: {
635
- requestId: {
636
- type: ScalarTypeEnum3.String_unsecure(),
637
- isOptional: false
638
- }
639
- }
640
- }),
641
- output: ApprovalRequestModel
642
- },
643
- policy: { auth: "user" },
644
- acceptance: {
645
- scenarios: [
646
- {
647
- key: "get-approval-happy-path",
648
- given: ["Approval request exists"],
649
- when: ["User requests approval details"],
650
- then: ["Approval details are returned"]
651
- }
652
- ],
653
- examples: [
654
- {
655
- key: "get-basic",
656
- input: { requestId: "req-123" },
657
- output: { id: "req-123", status: "pending" }
658
- }
659
- ]
660
- }
661
- });
662
- // src/handlers/workflow.handlers.ts
663
- import { web } from "@contractspec/lib.runtime-sandbox";
664
- var { generateId } = web;
665
- function rowToDefinition(row) {
666
- return {
667
- id: row.id,
668
- projectId: row.projectId,
669
- organizationId: row.organizationId,
670
- name: row.name,
671
- description: row.description ?? undefined,
672
- type: row.type,
673
- status: row.status,
674
- createdAt: new Date(row.createdAt),
675
- updatedAt: new Date(row.updatedAt)
676
- };
677
- }
678
- function rowToStep(row) {
679
- return {
680
- id: row.id,
681
- definitionId: row.definitionId,
682
- name: row.name,
683
- description: row.description ?? undefined,
684
- stepOrder: row.stepOrder,
685
- type: row.type,
686
- requiredRoles: row.requiredRoles ? JSON.parse(row.requiredRoles) : [],
687
- autoApproveCondition: row.autoApproveCondition ?? undefined,
688
- timeoutHours: row.timeoutHours ?? undefined,
689
- createdAt: new Date(row.createdAt)
690
- };
691
- }
692
- function rowToInstance(row) {
693
- return {
694
- id: row.id,
695
- projectId: row.projectId,
696
- definitionId: row.definitionId,
697
- status: row.status,
698
- currentStepId: row.currentStepId ?? undefined,
699
- data: row.data ? JSON.parse(row.data) : undefined,
700
- requestedBy: row.requestedBy,
701
- startedAt: new Date(row.startedAt),
702
- completedAt: row.completedAt ? new Date(row.completedAt) : undefined
703
- };
704
- }
705
- function rowToApproval(row) {
706
- return {
707
- id: row.id,
708
- instanceId: row.instanceId,
709
- stepId: row.stepId,
710
- status: row.status,
711
- actorId: row.actorId ?? undefined,
712
- comment: row.comment ?? undefined,
713
- decidedAt: row.decidedAt ? new Date(row.decidedAt) : undefined,
714
- createdAt: new Date(row.createdAt)
715
- };
716
- }
717
- function createWorkflowHandlers(db) {
718
- function normalizeSql(sql) {
719
- let placeholderIndex = 0;
720
- return sql.replace(/\?/g, () => `$${++placeholderIndex}`);
721
- }
722
- async function queryRows(sql, params = []) {
723
- return (await db.query(normalizeSql(sql), params)).rows;
724
- }
725
- async function execute(sql, params = []) {
726
- await db.execute(normalizeSql(sql), params);
727
- }
728
- async function listDefinitions(input) {
729
- const { projectId, status, search, limit = 20, offset = 0 } = input;
730
- let whereClause = 'WHERE "projectId" = ?';
731
- const params = [projectId];
732
- if (status && status !== "all") {
733
- whereClause += " AND status = ?";
734
- params.push(status);
735
- }
736
- if (search) {
737
- whereClause += " AND name LIKE ?";
738
- params.push(`%${search}%`);
739
- }
740
- const countResult = await queryRows(`SELECT COUNT(*) as count FROM workflow_definition ${whereClause}`, params);
741
- const total = countResult[0]?.count ?? 0;
742
- const rows = await queryRows(`SELECT * FROM workflow_definition ${whereClause} ORDER BY "updatedAt" DESC LIMIT ? OFFSET ?`, [...params, limit, offset]);
743
- return {
744
- definitions: rows.map(rowToDefinition),
745
- total
746
- };
747
- }
748
- async function createDefinition(input, context) {
749
- const id = generateId("wfdef");
750
- const now = new Date().toISOString();
751
- await execute(`INSERT INTO workflow_definition (id, "projectId", "organizationId", name, description, type, status, "createdAt", "updatedAt")
752
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
753
- id,
754
- context.projectId,
755
- context.organizationId,
756
- input.name,
757
- input.description ?? null,
758
- input.type ?? "APPROVAL",
759
- "DRAFT",
760
- now,
761
- now
762
- ]);
763
- const rows = await queryRows(`SELECT * FROM workflow_definition WHERE id = ?`, [id]);
764
- return rowToDefinition(rows[0]);
765
- }
766
- async function addStep(input) {
767
- const id = generateId("wfstep");
768
- const now = new Date().toISOString();
769
- const maxOrderResult = await queryRows(`SELECT MAX("stepOrder") as maxOrder FROM workflow_step WHERE "definitionId" = ?`, [input.definitionId]);
770
- const nextOrder = (maxOrderResult[0]?.maxOrder ?? 0) + 1;
771
- await execute(`INSERT INTO workflow_step (id, "definitionId", name, description, "stepOrder", type, "requiredRoles", "autoApproveCondition", "timeoutHours", "createdAt")
772
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
773
- id,
774
- input.definitionId,
775
- input.name,
776
- input.description ?? null,
777
- nextOrder,
778
- input.type ?? "APPROVAL",
779
- JSON.stringify(input.requiredRoles),
780
- input.autoApproveCondition ?? null,
781
- input.timeoutHours ?? null,
782
- now
783
- ]);
784
- const rows = await queryRows(`SELECT * FROM workflow_step WHERE id = ?`, [id]);
785
- return rowToStep(rows[0]);
786
- }
787
- async function getSteps(definitionId) {
788
- const rows = await queryRows(`SELECT * FROM workflow_step WHERE "definitionId" = ? ORDER BY "stepOrder"`, [definitionId]);
789
- return rows.map(rowToStep);
790
- }
791
- async function listInstances(input) {
792
- const {
793
- projectId,
794
- definitionId,
795
- status,
796
- requestedBy,
797
- limit = 20,
798
- offset = 0
799
- } = input;
800
- let whereClause = 'WHERE "projectId" = ?';
801
- const params = [projectId];
802
- if (definitionId) {
803
- whereClause += ' AND "definitionId" = ?';
804
- params.push(definitionId);
805
- }
806
- if (status && status !== "all") {
807
- whereClause += " AND status = ?";
808
- params.push(status);
809
- }
810
- if (requestedBy) {
811
- whereClause += ' AND "requestedBy" = ?';
812
- params.push(requestedBy);
813
- }
814
- const countResult = await queryRows(`SELECT COUNT(*) as count FROM workflow_instance ${whereClause}`, params);
815
- const total = countResult[0]?.count ?? 0;
816
- const rows = await queryRows(`SELECT * FROM workflow_instance ${whereClause} ORDER BY "startedAt" DESC LIMIT ? OFFSET ?`, [...params, limit, offset]);
817
- return {
818
- instances: rows.map(rowToInstance),
819
- total
820
- };
821
- }
822
- async function startInstance(input, context) {
823
- const id = generateId("wfinst");
824
- const now = new Date().toISOString();
825
- const steps = await queryRows(`SELECT * FROM workflow_step WHERE "definitionId" = ? ORDER BY "stepOrder" LIMIT 1`, [input.definitionId]);
826
- const firstStepId = steps[0]?.id ?? null;
827
- await execute(`INSERT INTO workflow_instance (id, "projectId", "definitionId", status, "currentStepId", data, "requestedBy", "startedAt")
828
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
829
- id,
830
- context.projectId,
831
- input.definitionId,
832
- firstStepId ? "IN_PROGRESS" : "PENDING",
833
- firstStepId,
834
- input.data ? JSON.stringify(input.data) : null,
835
- context.requestedBy,
836
- now
837
- ]);
838
- if (firstStepId) {
839
- await execute(`INSERT INTO workflow_approval (id, "instanceId", "stepId", status, "createdAt")
840
- VALUES (?, ?, ?, ?, ?)`, [generateId("wfappr"), id, firstStepId, "PENDING", now]);
841
- }
842
- const rows = await queryRows(`SELECT * FROM workflow_instance WHERE id = ?`, [id]);
843
- return rowToInstance(rows[0]);
844
- }
845
- async function approveStep(input, context) {
846
- const now = new Date().toISOString();
847
- const instances = await queryRows(`SELECT * FROM workflow_instance WHERE id = ?`, [input.instanceId]);
848
- if (!instances[0]) {
849
- throw new Error("NOT_FOUND");
850
- }
851
- const instance = instances[0];
852
- await execute(`UPDATE workflow_approval SET status = 'APPROVED', "actorId" = ?, comment = ?, "decidedAt" = ?
853
- WHERE "instanceId" = ? AND "stepId" = ? AND status = 'PENDING'`, [
854
- context.actorId,
855
- input.comment ?? null,
856
- now,
857
- input.instanceId,
858
- instance.currentStepId
859
- ]);
860
- const currentStep = await queryRows(`SELECT * FROM workflow_step WHERE id = ?`, [instance.currentStepId]);
861
- const nextSteps = await queryRows(`SELECT * FROM workflow_step WHERE "definitionId" = ? AND "stepOrder" > ? ORDER BY "stepOrder" LIMIT 1`, [instance.definitionId, currentStep[0]?.stepOrder ?? 0]);
862
- if (nextSteps[0]) {
863
- await execute(`UPDATE workflow_instance SET "currentStepId" = ? WHERE id = ?`, [nextSteps[0].id, input.instanceId]);
864
- await execute(`INSERT INTO workflow_approval (id, "instanceId", "stepId", status, "createdAt")
865
- VALUES (?, ?, ?, ?, ?)`, [
866
- generateId("wfappr"),
867
- input.instanceId,
868
- nextSteps[0].id,
869
- "PENDING",
870
- now
871
- ]);
872
- } else {
873
- await execute(`UPDATE workflow_instance SET status = 'COMPLETED', "currentStepId" = NULL, "completedAt" = ? WHERE id = ?`, [now, input.instanceId]);
874
- }
875
- const updated = await queryRows(`SELECT * FROM workflow_instance WHERE id = ?`, [input.instanceId]);
876
- return rowToInstance(updated[0]);
877
- }
878
- async function rejectStep(input, context) {
879
- const now = new Date().toISOString();
880
- const instances = await queryRows(`SELECT * FROM workflow_instance WHERE id = ?`, [input.instanceId]);
881
- if (!instances[0]) {
882
- throw new Error("NOT_FOUND");
883
- }
884
- await execute(`UPDATE workflow_approval SET status = 'REJECTED', "actorId" = ?, comment = ?, "decidedAt" = ?
885
- WHERE "instanceId" = ? AND "stepId" = ? AND status = 'PENDING'`, [
886
- context.actorId,
887
- input.reason,
888
- now,
889
- input.instanceId,
890
- instances[0].currentStepId
891
- ]);
892
- await execute(`UPDATE workflow_instance SET status = 'REJECTED', "completedAt" = ? WHERE id = ?`, [now, input.instanceId]);
893
- const updated = await queryRows(`SELECT * FROM workflow_instance WHERE id = ?`, [input.instanceId]);
894
- return rowToInstance(updated[0]);
895
- }
896
- async function getApprovals(instanceId) {
897
- const rows = await queryRows(`SELECT * FROM workflow_approval WHERE "instanceId" = ? ORDER BY "createdAt"`, [instanceId]);
898
- return rows.map(rowToApproval);
899
- }
900
- return {
901
- listDefinitions,
902
- createDefinition,
903
- addStep,
904
- getSteps,
905
- listInstances,
906
- startInstance,
907
- approveStep,
908
- rejectStep,
909
- getApprovals
910
- };
911
- }
912
-
913
- // src/instance/instance.enum.ts
914
- import { defineEnum as defineEnum2 } from "@contractspec/lib.schema";
915
- var InstanceStatusEnum = defineEnum2("InstanceStatus", [
916
- "PENDING",
917
- "RUNNING",
918
- "WAITING",
919
- "PAUSED",
920
- "COMPLETED",
921
- "CANCELLED",
922
- "FAILED",
923
- "TIMEOUT"
924
- ]);
925
-
926
- // src/instance/instance.event.ts
927
- import { defineEvent as defineEvent2 } from "@contractspec/lib.contracts-spec";
928
- import { defineSchemaModel as defineSchemaModel4, ScalarTypeEnum as ScalarTypeEnum4 } from "@contractspec/lib.schema";
929
- var InstanceEventPayload = defineSchemaModel4({
930
- name: "InstanceEventPayload",
931
- description: "Base payload for instance events",
932
- fields: {
933
- instanceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
934
- workflowId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
935
- workflowKey: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
936
- status: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
937
- referenceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
938
- referenceType: {
939
- type: ScalarTypeEnum4.String_unsecure(),
940
- isOptional: true
941
- },
942
- triggeredBy: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
943
- organizationId: {
944
- type: ScalarTypeEnum4.String_unsecure(),
945
- isOptional: false
946
- },
947
- timestamp: { type: ScalarTypeEnum4.DateTime(), isOptional: false }
948
- }
949
- });
950
- var StepTransitionPayload = defineSchemaModel4({
951
- name: "StepTransitionEventPayload",
952
- description: "Payload for step transition events",
953
- fields: {
954
- instanceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
955
- workflowId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
956
- fromStepKey: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
957
- toStepKey: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
958
- action: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
959
- executedBy: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
960
- timestamp: { type: ScalarTypeEnum4.DateTime(), isOptional: false }
961
- }
962
- });
963
- var InstanceCompletedPayload = defineSchemaModel4({
964
- name: "InstanceCompletedEventPayload",
965
- description: "Payload when instance completes",
966
- fields: {
967
- instanceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
968
- workflowId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
969
- workflowKey: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
970
- outcome: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
971
- referenceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
972
- referenceType: {
973
- type: ScalarTypeEnum4.String_unsecure(),
974
- isOptional: true
975
- },
976
- duration: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
977
- timestamp: { type: ScalarTypeEnum4.DateTime(), isOptional: false }
978
- }
979
- });
980
- var InstanceStartedEvent = defineEvent2({
981
- meta: {
982
- key: "workflow.instance.started",
983
- version: "1.0.0",
984
- description: "A new workflow instance has been started.",
985
- stability: "stable",
986
- owners: ["@workflow-team"],
987
- tags: ["workflow", "instance", "started"]
988
- },
989
- payload: InstanceEventPayload
990
- });
991
- var StepEnteredEvent = defineEvent2({
992
- meta: {
993
- key: "workflow.step.entered",
994
- version: "1.0.0",
995
- description: "A workflow instance has entered a new step.",
996
- stability: "stable",
997
- owners: ["@workflow-team"],
998
- tags: ["workflow", "step", "entered"]
999
- },
1000
- payload: StepTransitionPayload
1001
- });
1002
- var StepExitedEvent = defineEvent2({
1003
- meta: {
1004
- key: "workflow.step.exited",
1005
- version: "1.0.0",
1006
- description: "A workflow instance has exited a step.",
1007
- stability: "stable",
1008
- owners: ["@workflow-team"],
1009
- tags: ["workflow", "step", "exited"]
1010
- },
1011
- payload: StepTransitionPayload
1012
- });
1013
- var InstanceCompletedEvent = defineEvent2({
1014
- meta: {
1015
- key: "workflow.instance.completed",
1016
- version: "1.0.0",
1017
- description: "A workflow instance has completed.",
1018
- stability: "stable",
1019
- owners: ["@workflow-team"],
1020
- tags: ["workflow", "instance", "completed"]
1021
- },
1022
- payload: InstanceCompletedPayload
1023
- });
1024
- var InstanceCancelledEvent = defineEvent2({
1025
- meta: {
1026
- key: "workflow.instance.cancelled",
1027
- version: "1.0.0",
1028
- description: "A workflow instance has been cancelled.",
1029
- stability: "stable",
1030
- owners: ["@workflow-team"],
1031
- tags: ["workflow", "instance", "cancelled"]
1032
- },
1033
- payload: InstanceEventPayload
1034
- });
1035
- var InstancePausedEvent = defineEvent2({
1036
- meta: {
1037
- key: "workflow.instance.paused",
1038
- version: "1.0.0",
1039
- description: "A workflow instance has been paused.",
1040
- stability: "stable",
1041
- owners: ["@workflow-team"],
1042
- tags: ["workflow", "instance", "paused"]
1043
- },
1044
- payload: InstanceEventPayload
1045
- });
1046
- var InstanceResumedEvent = defineEvent2({
1047
- meta: {
1048
- key: "workflow.instance.resumed",
1049
- version: "1.0.0",
1050
- description: "A workflow instance has been resumed.",
1051
- stability: "stable",
1052
- owners: ["@workflow-team"],
1053
- tags: ["workflow", "instance", "resumed"]
1054
- },
1055
- payload: InstanceEventPayload
1056
- });
1057
- var InstanceFailedEvent = defineEvent2({
1058
- meta: {
1059
- key: "workflow.instance.failed",
1060
- version: "1.0.0",
1061
- description: "A workflow instance has failed.",
1062
- stability: "stable",
1063
- owners: ["@workflow-team"],
1064
- tags: ["workflow", "instance", "failed"]
1065
- },
1066
- payload: InstanceEventPayload
1067
- });
1068
- var InstanceTimedOutEvent = defineEvent2({
1069
- meta: {
1070
- key: "workflow.instance.timedOut",
1071
- version: "1.0.0",
1072
- description: "A workflow instance has timed out.",
1073
- stability: "stable",
1074
- owners: ["@workflow-team"],
1075
- tags: ["workflow", "instance", "timeout"]
1076
- },
1077
- payload: InstanceEventPayload
1078
- });
1079
-
1080
- // src/instance/instance.schema.ts
1081
- import { defineSchemaModel as defineSchemaModel5, ScalarTypeEnum as ScalarTypeEnum5 } from "@contractspec/lib.schema";
1082
- var WorkflowInstanceModel = defineSchemaModel5({
1083
- name: "WorkflowInstanceModel",
1084
- description: "A running workflow instance",
1085
- fields: {
1086
- id: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1087
- workflowDefinitionId: {
1088
- type: ScalarTypeEnum5.String_unsecure(),
1089
- isOptional: false
1090
- },
1091
- referenceId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1092
- referenceType: {
1093
- type: ScalarTypeEnum5.String_unsecure(),
1094
- isOptional: true
1095
- },
1096
- status: { type: InstanceStatusEnum, isOptional: false },
1097
- currentStepId: {
1098
- type: ScalarTypeEnum5.String_unsecure(),
1099
- isOptional: true
1100
- },
1101
- contextData: { type: ScalarTypeEnum5.JSON(), isOptional: true },
1102
- triggeredBy: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1103
- organizationId: {
1104
- type: ScalarTypeEnum5.String_unsecure(),
1105
- isOptional: false
1106
- },
1107
- priority: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1108
- dueAt: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1109
- outcome: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1110
- resultData: { type: ScalarTypeEnum5.JSON(), isOptional: true },
1111
- errorMessage: {
1112
- type: ScalarTypeEnum5.String_unsecure(),
1113
- isOptional: true
1114
- },
1115
- createdAt: { type: ScalarTypeEnum5.DateTime(), isOptional: false },
1116
- startedAt: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1117
- completedAt: { type: ScalarTypeEnum5.DateTime(), isOptional: true }
1118
- }
1119
- });
1120
- var StartWorkflowInputModel = defineSchemaModel5({
1121
- name: "StartWorkflowInput",
1122
- description: "Input for starting a workflow",
1123
- fields: {
1124
- workflowKey: { type: ScalarTypeEnum5.NonEmptyString(), isOptional: false },
1125
- contextData: { type: ScalarTypeEnum5.JSON(), isOptional: true },
1126
- referenceId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1127
- referenceType: {
1128
- type: ScalarTypeEnum5.String_unsecure(),
1129
- isOptional: true
1130
- },
1131
- priority: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: true },
1132
- dueAt: { type: ScalarTypeEnum5.DateTime(), isOptional: true }
1133
- }
1134
- });
1135
- var TransitionInputModel = defineSchemaModel5({
1136
- name: "TransitionInput",
1137
- description: "Input for transitioning a workflow",
1138
- fields: {
1139
- instanceId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1140
- action: { type: ScalarTypeEnum5.NonEmptyString(), isOptional: false },
1141
- data: { type: ScalarTypeEnum5.JSON(), isOptional: true },
1142
- comment: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true }
1143
- }
1144
- });
1145
- var TransitionResultModel = defineSchemaModel5({
1146
- name: "TransitionResult",
1147
- description: "Result of a workflow transition",
1148
- fields: {
1149
- success: { type: ScalarTypeEnum5.Boolean(), isOptional: false },
1150
- instance: { type: WorkflowInstanceModel, isOptional: false },
1151
- previousStepKey: {
1152
- type: ScalarTypeEnum5.String_unsecure(),
1153
- isOptional: true
1154
- },
1155
- currentStepKey: {
1156
- type: ScalarTypeEnum5.String_unsecure(),
1157
- isOptional: true
1158
- },
1159
- message: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true }
1160
- }
1161
- });
1162
-
1163
- // src/instance/instance.operations.ts
1164
- import {
1165
- defineCommand as defineCommand2,
1166
- defineQuery as defineQuery2
1167
- } from "@contractspec/lib.contracts-spec/operations";
1168
- import { defineSchemaModel as defineSchemaModel6, ScalarTypeEnum as ScalarTypeEnum6 } from "@contractspec/lib.schema";
1169
- var OWNERS2 = ["@example.workflow-system"];
1170
- var StartWorkflowContract = defineCommand2({
1171
- meta: {
1172
- key: "workflow.instance.start",
1173
- version: "1.0.0",
1174
- stability: "stable",
1175
- owners: [...OWNERS2],
1176
- tags: ["workflow", "instance", "start"],
1177
- description: "Start a new workflow instance.",
1178
- goal: "Initiate a workflow for a business process.",
1179
- context: "Order creation, request submission, etc."
1180
- },
1181
- io: {
1182
- input: StartWorkflowInputModel,
1183
- output: WorkflowInstanceModel
1184
- },
1185
- policy: { auth: "user" },
1186
- sideEffects: {
1187
- emits: [
1188
- {
1189
- key: "workflow.instance.started",
1190
- version: "1.0.0",
1191
- when: "Workflow starts",
1192
- payload: WorkflowInstanceModel
1193
- },
1194
- {
1195
- key: "workflow.step.entered",
1196
- version: "1.0.0",
1197
- when: "First step entered",
1198
- payload: WorkflowInstanceModel
1199
- }
1200
- ],
1201
- audit: ["workflow.instance.started"]
1202
- },
1203
- acceptance: {
1204
- scenarios: [
1205
- {
1206
- key: "start-workflow-happy-path",
1207
- given: ["Workflow definition exists"],
1208
- when: ["User starts workflow"],
1209
- then: ["Instance is created and started"]
1210
- }
1211
- ],
1212
- examples: [
1213
- {
1214
- key: "start-onboarding",
1215
- input: {
1216
- workflowKey: "onboarding-v1",
1217
- context: { employeeId: "emp-123" }
1218
- },
1219
- output: { id: "inst-456", status: "running" }
1220
- }
1221
- ]
1222
- }
1223
- });
1224
- var TransitionWorkflowContract = defineCommand2({
1225
- meta: {
1226
- key: "workflow.instance.transition",
1227
- version: "1.0.0",
1228
- stability: "stable",
1229
- owners: [...OWNERS2],
1230
- tags: ["workflow", "instance", "transition", "state-machine"],
1231
- description: "Transition a workflow instance to the next step.",
1232
- goal: "Move workflow forward based on action.",
1233
- context: "Task completion, approval decisions."
1234
- },
1235
- io: {
1236
- input: TransitionInputModel,
1237
- output: TransitionResultModel
1238
- },
1239
- policy: { auth: "user" },
1240
- sideEffects: {
1241
- emits: [
1242
- {
1243
- key: "workflow.step.exited",
1244
- version: "1.0.0",
1245
- when: "Step is exited",
1246
- payload: WorkflowInstanceModel
1247
- },
1248
- {
1249
- key: "workflow.step.entered",
1250
- version: "1.0.0",
1251
- when: "New step is entered",
1252
- payload: WorkflowInstanceModel
1253
- },
1254
- {
1255
- key: "workflow.instance.completed",
1256
- version: "1.0.0",
1257
- when: "Workflow reaches end",
1258
- payload: WorkflowInstanceModel
1259
- }
1260
- ],
1261
- audit: ["workflow.instance.transitioned"]
1262
- },
1263
- acceptance: {
1264
- scenarios: [
1265
- {
1266
- key: "transition-workflow-happy-path",
1267
- given: ["Workflow instance is waiting at step"],
1268
- when: ["User provides input"],
1269
- then: ["Instance moves to next step"]
1270
- }
1271
- ],
1272
- examples: [
1273
- {
1274
- key: "complete-task",
1275
- input: {
1276
- instanceId: "inst-456",
1277
- action: "complete",
1278
- data: { approved: true }
1279
- },
1280
- output: { success: true, nextStep: "notify-hr" }
1281
- }
1282
- ]
1283
- }
1284
- });
1285
- var PauseWorkflowContract = defineCommand2({
1286
- meta: {
1287
- key: "workflow.instance.pause",
1288
- version: "1.0.0",
1289
- stability: "stable",
1290
- owners: [...OWNERS2],
1291
- tags: ["workflow", "instance", "pause"],
1292
- description: "Pause a running workflow instance.",
1293
- goal: "Temporarily halt workflow execution.",
1294
- context: "Administrative action, emergency stop."
1295
- },
1296
- io: {
1297
- input: defineSchemaModel6({
1298
- name: "PauseResumeInput",
1299
- fields: {
1300
- instanceId: {
1301
- type: ScalarTypeEnum6.String_unsecure(),
1302
- isOptional: false
1303
- },
1304
- reason: { type: ScalarTypeEnum6.String_unsecure(), isOptional: true }
1305
- }
1306
- }),
1307
- output: WorkflowInstanceModel
1308
- },
1309
- policy: { auth: "user" },
1310
- sideEffects: {
1311
- emits: [
1312
- {
1313
- key: "workflow.instance.paused",
1314
- version: "1.0.0",
1315
- when: "Workflow is paused",
1316
- payload: WorkflowInstanceModel
1317
- }
1318
- ],
1319
- audit: ["workflow.instance.paused"]
1320
- },
1321
- acceptance: {
1322
- scenarios: [
1323
- {
1324
- key: "pause-workflow-happy-path",
1325
- given: ["Workflow is running"],
1326
- when: ["Admin pauses workflow"],
1327
- then: ["Instance status becomes PAUSED"]
1328
- }
1329
- ],
1330
- examples: [
1331
- {
1332
- key: "pause-maintenance",
1333
- input: { instanceId: "inst-456", reason: "System maintenance" },
1334
- output: { id: "inst-456", status: "paused" }
1335
- }
1336
- ]
1337
- }
1338
- });
1339
- var ResumeWorkflowContract = defineCommand2({
1340
- meta: {
1341
- key: "workflow.instance.resume",
1342
- version: "1.0.0",
1343
- stability: "stable",
1344
- owners: [...OWNERS2],
1345
- tags: ["workflow", "instance", "resume"],
1346
- description: "Resume a paused workflow instance.",
1347
- goal: "Continue workflow execution.",
1348
- context: "Administrative action."
1349
- },
1350
- io: {
1351
- input: defineSchemaModel6({
1352
- name: "PauseResumeInput",
1353
- fields: {
1354
- instanceId: {
1355
- type: ScalarTypeEnum6.String_unsecure(),
1356
- isOptional: false
1357
- },
1358
- reason: { type: ScalarTypeEnum6.String_unsecure(), isOptional: true }
1359
- }
1360
- }),
1361
- output: WorkflowInstanceModel
1362
- },
1363
- policy: { auth: "user" },
1364
- sideEffects: {
1365
- emits: [
1366
- {
1367
- key: "workflow.instance.resumed",
1368
- version: "1.0.0",
1369
- when: "Workflow is resumed",
1370
- payload: WorkflowInstanceModel
1371
- }
1372
- ],
1373
- audit: ["workflow.instance.resumed"]
1374
- },
1375
- acceptance: {
1376
- scenarios: [
1377
- {
1378
- key: "resume-workflow-happy-path",
1379
- given: ["Workflow is paused"],
1380
- when: ["Admin resumes workflow"],
1381
- then: ["Instance status becomes RUNNING"]
1382
- }
1383
- ],
1384
- examples: [
1385
- {
1386
- key: "resume-normal",
1387
- input: { instanceId: "inst-456", reason: "Issue resolved" },
1388
- output: { id: "inst-456", status: "running" }
1389
- }
1390
- ]
1391
- }
1392
- });
1393
- var CancelWorkflowContract = defineCommand2({
1394
- meta: {
1395
- key: "workflow.instance.cancel",
1396
- version: "1.0.0",
1397
- stability: "stable",
1398
- owners: [...OWNERS2],
1399
- tags: ["workflow", "instance", "cancel"],
1400
- description: "Cancel a workflow instance.",
1401
- goal: "Terminate workflow without completion.",
1402
- context: "User request, system cancellation."
1403
- },
1404
- io: {
1405
- input: defineSchemaModel6({
1406
- name: "CancelWorkflowInput",
1407
- fields: {
1408
- instanceId: {
1409
- type: ScalarTypeEnum6.String_unsecure(),
1410
- isOptional: false
1411
- },
1412
- reason: {
1413
- type: ScalarTypeEnum6.String_unsecure(),
1414
- isOptional: false
1415
- }
1416
- }
1417
- }),
1418
- output: WorkflowInstanceModel
1419
- },
1420
- policy: { auth: "user" },
1421
- sideEffects: {
1422
- emits: [
1423
- {
1424
- key: "workflow.instance.cancelled",
1425
- version: "1.0.0",
1426
- when: "Workflow is cancelled",
1427
- payload: WorkflowInstanceModel
1428
- }
1429
- ],
1430
- audit: ["workflow.instance.cancelled"]
1431
- },
1432
- acceptance: {
1433
- scenarios: [
1434
- {
1435
- key: "cancel-workflow-happy-path",
1436
- given: ["Workflow is running"],
1437
- when: ["User cancels workflow"],
1438
- then: ["Instance status becomes CANCELLED"]
1439
- }
1440
- ],
1441
- examples: [
1442
- {
1443
- key: "cancel-mistake",
1444
- input: { instanceId: "inst-456", reason: "Created by mistake" },
1445
- output: { id: "inst-456", status: "cancelled" }
1446
- }
1447
- ]
1448
- }
1449
- });
1450
- var ListInstancesContract = defineQuery2({
1451
- meta: {
1452
- key: "workflow.instance.list",
1453
- version: "1.0.0",
1454
- stability: "stable",
1455
- owners: [...OWNERS2],
1456
- tags: ["workflow", "instance", "list"],
1457
- description: "List workflow instances with filtering.",
1458
- goal: "Browse and search running workflows.",
1459
- context: "Dashboard, monitoring."
1460
- },
1461
- io: {
1462
- input: defineSchemaModel6({
1463
- name: "ListInstancesInput",
1464
- fields: {
1465
- workflowKey: {
1466
- type: ScalarTypeEnum6.String_unsecure(),
1467
- isOptional: true
1468
- },
1469
- status: { type: InstanceStatusEnum, isOptional: true },
1470
- referenceType: {
1471
- type: ScalarTypeEnum6.String_unsecure(),
1472
- isOptional: true
1473
- },
1474
- referenceId: {
1475
- type: ScalarTypeEnum6.String_unsecure(),
1476
- isOptional: true
1477
- },
1478
- triggeredBy: {
1479
- type: ScalarTypeEnum6.String_unsecure(),
1480
- isOptional: true
1481
- },
1482
- limit: {
1483
- type: ScalarTypeEnum6.Int_unsecure(),
1484
- isOptional: true,
1485
- defaultValue: 20
1486
- },
1487
- offset: {
1488
- type: ScalarTypeEnum6.Int_unsecure(),
1489
- isOptional: true,
1490
- defaultValue: 0
1491
- }
1492
- }
1493
- }),
1494
- output: defineSchemaModel6({
1495
- name: "ListInstancesOutput",
1496
- fields: {
1497
- instances: {
1498
- type: WorkflowInstanceModel,
1499
- isArray: true,
1500
- isOptional: false
1501
- },
1502
- total: { type: ScalarTypeEnum6.Int_unsecure(), isOptional: false }
1503
- }
1504
- })
1505
- },
1506
- policy: { auth: "user" },
1507
- acceptance: {
1508
- scenarios: [
1509
- {
1510
- key: "list-instances-happy-path",
1511
- given: ["Workflow instances exist"],
1512
- when: ["User lists instances"],
1513
- then: ["List of instances is returned"]
1514
- }
1515
- ],
1516
- examples: [
1517
- {
1518
- key: "list-running",
1519
- input: { status: "running", limit: 10 },
1520
- output: { instances: [], total: 5 }
1521
- }
1522
- ]
1523
- }
1524
- });
1525
- var GetInstanceContract = defineQuery2({
1526
- meta: {
1527
- key: "workflow.instance.get",
1528
- version: "1.0.0",
1529
- stability: "stable",
1530
- owners: [...OWNERS2],
1531
- tags: ["workflow", "instance", "get"],
1532
- description: "Get a workflow instance with details.",
1533
- goal: "View workflow instance details.",
1534
- context: "Instance detail view."
1535
- },
1536
- io: {
1537
- input: defineSchemaModel6({
1538
- name: "GetInstanceInput",
1539
- fields: {
1540
- instanceId: {
1541
- type: ScalarTypeEnum6.String_unsecure(),
1542
- isOptional: false
1543
- }
1544
- }
1545
- }),
1546
- output: WorkflowInstanceModel
1547
- },
1548
- policy: { auth: "user" },
1549
- acceptance: {
1550
- scenarios: [
1551
- {
1552
- key: "get-instance-happy-path",
1553
- given: ["Instance exists"],
1554
- when: ["User requests instance details"],
1555
- then: ["Instance details are returned"]
1556
- }
1557
- ],
1558
- examples: [
1559
- {
1560
- key: "get-details",
1561
- input: { instanceId: "inst-456" },
1562
- output: { id: "inst-456", workflowKey: "onboarding-v1" }
1563
- }
1564
- ]
1565
- }
1566
- });
1567
- // src/workflow/workflow.enum.ts
1568
- import { defineEnum as defineEnum3 } from "@contractspec/lib.schema";
1569
- var WorkflowStatusEnum = defineEnum3("WorkflowStatus", [
1570
- "DRAFT",
1571
- "ACTIVE",
1572
- "DEPRECATED",
1573
- "ARCHIVED"
1574
- ]);
1575
- var TriggerTypeEnum = defineEnum3("WorkflowTriggerType", [
1576
- "MANUAL",
1577
- "EVENT",
1578
- "SCHEDULED",
1579
- "API"
1580
- ]);
1581
- var StepTypeEnum = defineEnum3("StepType", [
1582
- "START",
1583
- "APPROVAL",
1584
- "TASK",
1585
- "CONDITION",
1586
- "PARALLEL",
1587
- "WAIT",
1588
- "ACTION",
1589
- "END"
1590
- ]);
1591
- var ApprovalModeEnum = defineEnum3("ApprovalMode", [
1592
- "ANY",
1593
- "ALL",
1594
- "MAJORITY",
1595
- "SEQUENTIAL"
1596
- ]);
1597
-
1598
- // src/workflow/workflow.schema.ts
1599
- import { defineSchemaModel as defineSchemaModel7, ScalarTypeEnum as ScalarTypeEnum7 } from "@contractspec/lib.schema";
1600
- var WorkflowStepModel = defineSchemaModel7({
1601
- name: "WorkflowStepModel",
1602
- description: "A step in a workflow definition",
1603
- fields: {
1604
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1605
- key: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1606
- name: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1607
- description: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1608
- type: { type: StepTypeEnum, isOptional: false },
1609
- position: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: false },
1610
- transitions: { type: ScalarTypeEnum7.JSON(), isOptional: false },
1611
- approvalMode: { type: ApprovalModeEnum, isOptional: true },
1612
- approverRoles: {
1613
- type: ScalarTypeEnum7.String_unsecure(),
1614
- isArray: true,
1615
- isOptional: true
1616
- }
1617
- }
1618
- });
1619
- var WorkflowDefinitionModel = defineSchemaModel7({
1620
- name: "WorkflowDefinitionModel",
1621
- description: "A workflow definition",
1622
- fields: {
1623
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1624
- name: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1625
- key: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1626
- description: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1627
- version: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1628
- status: { type: WorkflowStatusEnum, isOptional: false },
1629
- triggerType: { type: TriggerTypeEnum, isOptional: false },
1630
- initialStepId: {
1631
- type: ScalarTypeEnum7.String_unsecure(),
1632
- isOptional: true
1633
- },
1634
- featureFlagKey: {
1635
- type: ScalarTypeEnum7.String_unsecure(),
1636
- isOptional: true
1637
- },
1638
- organizationId: {
1639
- type: ScalarTypeEnum7.String_unsecure(),
1640
- isOptional: false
1641
- },
1642
- createdAt: { type: ScalarTypeEnum7.DateTime(), isOptional: false },
1643
- updatedAt: { type: ScalarTypeEnum7.DateTime(), isOptional: false },
1644
- steps: { type: WorkflowStepModel, isArray: true, isOptional: true }
1645
- }
1646
- });
1647
- var CreateWorkflowInputModel = defineSchemaModel7({
1648
- name: "CreateWorkflowInput",
1649
- description: "Input for creating a workflow definition",
1650
- fields: {
1651
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1652
- key: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1653
- description: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1654
- triggerType: { type: TriggerTypeEnum, isOptional: true },
1655
- triggerConfig: { type: ScalarTypeEnum7.JSON(), isOptional: true },
1656
- featureFlagKey: {
1657
- type: ScalarTypeEnum7.String_unsecure(),
1658
- isOptional: true
1659
- },
1660
- settings: { type: ScalarTypeEnum7.JSON(), isOptional: true }
1661
- }
1662
- });
1663
- var UpdateWorkflowInputModel = defineSchemaModel7({
1664
- name: "UpdateWorkflowInput",
1665
- description: "Input for updating a workflow definition",
1666
- fields: {
1667
- workflowId: {
1668
- type: ScalarTypeEnum7.String_unsecure(),
1669
- isOptional: false
1670
- },
1671
- name: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1672
- description: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1673
- triggerType: { type: TriggerTypeEnum, isOptional: true },
1674
- triggerConfig: { type: ScalarTypeEnum7.JSON(), isOptional: true },
1675
- featureFlagKey: {
1676
- type: ScalarTypeEnum7.String_unsecure(),
1677
- isOptional: true
1678
- },
1679
- settings: { type: ScalarTypeEnum7.JSON(), isOptional: true }
1680
- }
1681
- });
1682
- var AddStepInputModel = defineSchemaModel7({
1683
- name: "AddStepInput",
1684
- description: "Input for adding a step to a workflow",
1685
- fields: {
1686
- workflowId: {
1687
- type: ScalarTypeEnum7.String_unsecure(),
1688
- isOptional: false
1689
- },
1690
- key: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1691
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1692
- description: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1693
- type: { type: StepTypeEnum, isOptional: false },
1694
- position: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: true },
1695
- transitions: { type: ScalarTypeEnum7.JSON(), isOptional: false },
1696
- approvalMode: { type: ApprovalModeEnum, isOptional: true },
1697
- approverRoles: {
1698
- type: ScalarTypeEnum7.String_unsecure(),
1699
- isArray: true,
1700
- isOptional: true
1701
- },
1702
- approverUserIds: {
1703
- type: ScalarTypeEnum7.String_unsecure(),
1704
- isArray: true,
1705
- isOptional: true
1706
- },
1707
- timeoutSeconds: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: true },
1708
- slaSeconds: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: true }
1709
- }
1710
- });
1711
-
1712
- // src/presentations/index.ts
1713
- import {
1714
- definePresentation,
1715
- StabilityEnum
1716
- } from "@contractspec/lib.contracts-spec";
1717
- var WorkflowDesignerPresentation = definePresentation({
1718
- meta: {
1719
- key: "workflow.designer",
1720
- version: "1.0.0",
1721
- title: "Workflow Designer",
1722
- description: "Visual workflow designer with drag-and-drop steps",
1723
- domain: "workflow-system",
1724
- owners: ["@workflow-team"],
1725
- tags: ["workflow", "designer", "admin"],
1726
- stability: StabilityEnum.Experimental,
1727
- goal: "Building and modifying workflow definitions",
1728
- context: "Workflow administration and setup"
1729
- },
1730
- source: {
1731
- type: "component",
1732
- framework: "react",
1733
- componentKey: "WorkflowDesigner",
1734
- props: WorkflowDefinitionModel
1735
- },
1736
- targets: ["react"],
1737
- policy: {
1738
- flags: ["workflow.designer.enabled"]
1739
- }
1740
- });
1741
- var WorkflowListPresentation = definePresentation({
1742
- meta: {
1743
- key: "workflow.definition.viewList",
1744
- version: "1.0.0",
1745
- title: "Workflow List",
1746
- description: "List of workflow definitions with status and actions",
1747
- domain: "workflow-system",
1748
- owners: ["@workflow-team"],
1749
- tags: ["workflow", "list", "admin"],
1750
- stability: StabilityEnum.Experimental,
1751
- goal: "Overview of all defined workflows",
1752
- context: "Workflow management dashboard"
1753
- },
1754
- source: {
1755
- type: "component",
1756
- framework: "react",
1757
- componentKey: "WorkflowDefinitionList",
1758
- props: WorkflowDefinitionModel
1759
- },
1760
- targets: ["react", "markdown"],
1761
- policy: {
1762
- flags: ["workflow.enabled"]
1763
- }
1764
- });
1765
- var WorkflowDetailPresentation = definePresentation({
1766
- meta: {
1767
- key: "workflow.definition.detail",
1768
- version: "1.0.0",
1769
- title: "Workflow Details",
1770
- description: "Detailed view of a workflow definition with steps",
1771
- domain: "workflow-system",
1772
- owners: ["@workflow-team"],
1773
- tags: ["workflow", "detail"],
1774
- stability: StabilityEnum.Experimental,
1775
- goal: "Viewing technical details of a workflow definition",
1776
- context: "Workflow inspection and debugging"
1777
- },
1778
- source: {
1779
- type: "component",
1780
- framework: "react",
1781
- componentKey: "WorkflowDefinitionDetail",
1782
- props: WorkflowDefinitionModel
1783
- },
1784
- targets: ["react", "markdown"],
1785
- policy: {
1786
- flags: ["workflow.enabled"]
1787
- }
1788
- });
1789
- var InstanceListPresentation = definePresentation({
1790
- meta: {
1791
- key: "workflow.instance.viewList",
1792
- version: "1.0.0",
1793
- title: "Instance List",
1794
- description: "List of workflow instances with status and progress",
1795
- domain: "workflow-system",
1796
- owners: ["@workflow-team"],
1797
- tags: ["workflow", "instance", "list"],
1798
- stability: StabilityEnum.Experimental,
1799
- goal: "Monitoring active and past workflow executions",
1800
- context: "Operations monitoring"
1801
- },
1802
- source: {
1803
- type: "component",
1804
- framework: "react",
1805
- componentKey: "WorkflowInstanceList",
1806
- props: WorkflowInstanceModel
1807
- },
1808
- targets: ["react", "markdown"],
1809
- policy: {
1810
- flags: ["workflow.enabled"]
1811
- }
1812
- });
1813
- var InstanceDetailPresentation = definePresentation({
1814
- meta: {
1815
- key: "workflow.instance.detail",
1816
- version: "1.0.0",
1817
- title: "Instance Details",
1818
- description: "Detailed view of a workflow instance with step timeline",
1819
- domain: "workflow-system",
1820
- owners: ["@workflow-team"],
1821
- tags: ["workflow", "instance", "detail", "timeline"],
1822
- stability: StabilityEnum.Experimental,
1823
- goal: "Detailed inspection of a specific workflow instance",
1824
- context: "Case management and troubleshooting"
1825
- },
1826
- source: {
1827
- type: "component",
1828
- framework: "react",
1829
- componentKey: "WorkflowInstanceDetail",
1830
- props: WorkflowInstanceModel
1831
- },
1832
- targets: ["react", "markdown"],
1833
- policy: {
1834
- flags: ["workflow.enabled"]
1835
- }
1836
- });
1837
- var ProgressTrackerPresentation = definePresentation({
1838
- meta: {
1839
- key: "workflow.instance.progress",
1840
- version: "1.0.0",
1841
- title: "Progress Tracker",
1842
- description: "Visual progress tracker showing current step in workflow",
1843
- domain: "workflow-system",
1844
- owners: ["@workflow-team"],
1845
- tags: ["workflow", "progress", "widget"],
1846
- stability: StabilityEnum.Experimental,
1847
- goal: "Quick view of current progress for a workflow",
1848
- context: "Embedded progress indicator in entity views"
1849
- },
1850
- source: {
1851
- type: "component",
1852
- framework: "react",
1853
- componentKey: "WorkflowProgressTracker",
1854
- props: WorkflowInstanceModel
1855
- },
1856
- targets: ["react"],
1857
- policy: {
1858
- flags: ["workflow.enabled"]
1859
- }
1860
- });
1861
- var ApprovalInboxPresentation = definePresentation({
1862
- meta: {
1863
- key: "workflow.approval.inbox",
1864
- version: "1.0.0",
1865
- title: "Approval Inbox",
1866
- description: "Inbox showing pending approval requests for current user",
1867
- domain: "workflow-system",
1868
- owners: ["@workflow-team"],
1869
- tags: ["workflow", "approval", "inbox"],
1870
- stability: StabilityEnum.Experimental,
1871
- goal: "Managing personal workload of approval requests",
1872
- context: "Personal task management"
1873
- },
1874
- source: {
1875
- type: "component",
1876
- framework: "react",
1877
- componentKey: "ApprovalInbox",
1878
- props: ApprovalRequestModel
1879
- },
1880
- targets: ["react", "markdown"],
1881
- policy: {
1882
- flags: ["workflow.approvals.enabled"]
1883
- }
1884
- });
1885
- var ApprovalDetailPresentation = definePresentation({
1886
- meta: {
1887
- key: "workflow.approval.detail",
1888
- version: "1.0.0",
1889
- title: "Approval Details",
1890
- description: "Detailed approval request view with context and actions",
1891
- domain: "workflow-system",
1892
- owners: ["@workflow-team"],
1893
- tags: ["workflow", "approval", "detail"],
1894
- stability: StabilityEnum.Experimental,
1895
- goal: "Decision support for an approval request",
1896
- context: "Specific approval action"
1897
- },
1898
- source: {
1899
- type: "component",
1900
- framework: "react",
1901
- componentKey: "ApprovalRequestDetail",
1902
- props: ApprovalRequestModel
1903
- },
1904
- targets: ["react", "markdown"],
1905
- policy: {
1906
- flags: ["workflow.approvals.enabled"]
1907
- }
1908
- });
1909
- var ApprovalFormPresentation = definePresentation({
1910
- meta: {
1911
- key: "workflow.approval.form",
1912
- version: "1.0.0",
1913
- title: "Approval Form",
1914
- description: "Form for submitting approval decisions",
1915
- domain: "workflow-system",
1916
- owners: ["@workflow-team"],
1917
- tags: ["workflow", "approval", "form"],
1918
- stability: StabilityEnum.Experimental,
1919
- goal: "Submitting a decision on an approval request",
1920
- context: "Approval decision dialog"
1921
- },
1922
- source: {
1923
- type: "component",
1924
- framework: "react",
1925
- componentKey: "ApprovalDecisionForm"
1926
- },
1927
- targets: ["react"],
1928
- policy: {
1929
- flags: ["workflow.approvals.enabled"]
1930
- }
1931
- });
1932
- var PendingApprovalsBadgePresentation = definePresentation({
1933
- meta: {
1934
- key: "workflow.approval.badge",
1935
- version: "1.0.0",
1936
- title: "Pending Approvals Badge",
1937
- description: "Badge showing count of pending approvals",
1938
- domain: "workflow-system",
1939
- owners: ["@workflow-team"],
1940
- tags: ["workflow", "approval", "badge", "widget"],
1941
- stability: StabilityEnum.Experimental,
1942
- goal: "Visual notification of pending approvals",
1943
- context: "Global navigation or sidebar"
1944
- },
1945
- source: {
1946
- type: "component",
1947
- framework: "react",
1948
- componentKey: "PendingApprovalsBadge"
1949
- },
1950
- targets: ["react"],
1951
- policy: {
1952
- flags: ["workflow.approvals.enabled"]
1953
- }
1954
- });
1955
- var WorkflowMetricsPresentation = definePresentation({
1956
- meta: {
1957
- key: "workflow.metrics",
1958
- version: "1.0.0",
1959
- title: "Workflow Metrics",
1960
- description: "Dashboard widget showing workflow metrics and statistics",
1961
- domain: "workflow-system",
1962
- owners: ["@workflow-team"],
1963
- tags: ["workflow", "metrics", "dashboard"],
1964
- stability: StabilityEnum.Experimental,
1965
- goal: "Monitoring throughput and bottlenecks",
1966
- context: "System performance dashboard"
1967
- },
1968
- source: {
1969
- type: "component",
1970
- framework: "react",
1971
- componentKey: "WorkflowMetricsDashboard"
1972
- },
1973
- targets: ["react", "markdown"],
1974
- policy: {
1975
- flags: ["workflow.metrics.enabled"]
1976
- }
1977
- });
1978
- var WorkflowSystemPresentations = {
1979
- WorkflowDesignerPresentation,
1980
- WorkflowListPresentation,
1981
- WorkflowDetailPresentation,
1982
- InstanceListPresentation,
1983
- InstanceDetailPresentation,
1984
- ProgressTrackerPresentation,
1985
- ApprovalInboxPresentation,
1986
- ApprovalDetailPresentation,
1987
- ApprovalFormPresentation,
1988
- PendingApprovalsBadgePresentation,
1989
- WorkflowMetricsPresentation
1990
- };
1991
- // src/ui/hooks/useWorkflowList.ts
1992
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1993
- import { useCallback, useEffect, useState } from "react";
1994
- "use client";
1995
- function useWorkflowList(projectIdOverride) {
1996
- const { handlers, projectId: runtimeProjectId } = useTemplateRuntime();
1997
- const projectId = projectIdOverride ?? runtimeProjectId;
1998
- const workflow = handlers.workflow;
1999
- const [definitions, setDefinitions] = useState([]);
2000
- const [instances, setInstances] = useState([]);
2001
- const [loading, setLoading] = useState(true);
2002
- const [error, setError] = useState(null);
2003
- const fetchData = useCallback(async () => {
2004
- try {
2005
- setLoading(true);
2006
- setError(null);
2007
- const [defResult, instResult] = await Promise.all([
2008
- workflow.listDefinitions({ projectId, limit: 100 }),
2009
- workflow.listInstances({ projectId, limit: 100 })
2010
- ]);
2011
- setDefinitions(defResult.definitions);
2012
- setInstances(instResult.instances);
2013
- } catch (err) {
2014
- setError(err instanceof Error ? err : new Error("Failed to load workflows"));
2015
- } finally {
2016
- setLoading(false);
2017
- }
2018
- }, [projectId, workflow]);
2019
- useEffect(() => {
2020
- fetchData();
2021
- }, [fetchData]);
2022
- const stats = {
2023
- totalDefinitions: definitions.length,
2024
- activeDefinitions: definitions.filter((d) => d.status === "ACTIVE").length,
2025
- totalInstances: instances.length,
2026
- pendingInstances: instances.filter((i) => i.status === "PENDING").length,
2027
- inProgressInstances: instances.filter((i) => i.status === "IN_PROGRESS").length,
2028
- completedInstances: instances.filter((i) => i.status === "COMPLETED").length,
2029
- rejectedInstances: instances.filter((i) => i.status === "REJECTED").length
2030
- };
2031
- return {
2032
- definitions,
2033
- instances,
2034
- loading,
2035
- error,
2036
- stats,
2037
- refetch: fetchData
2038
- };
2039
- }
2040
-
2041
- // src/ui/hooks/index.ts
2042
- "use client";
2043
-
2044
- // src/shared/demo-scenario.ts
2045
- var WORKFLOW_SYSTEM_DEMO_PROJECT_ID = "workflow-system-demo";
2046
- var WORKFLOW_SYSTEM_DEMO_ORGANIZATION_ID = "org_demo";
2047
- var WORKFLOW_SYSTEM_DEMO_DEFINITIONS = [
2048
- {
2049
- id: "wf_expense",
2050
- name: "Expense Approval",
2051
- description: "Approve non-trivial spend before finance releases budget.",
2052
- type: "APPROVAL",
2053
- status: "ACTIVE",
2054
- createdAt: "2026-03-10T09:00:00.000Z",
2055
- updatedAt: "2026-03-20T08:15:00.000Z",
2056
- steps: [
2057
- {
2058
- id: "wfstep_expense_manager",
2059
- name: "Manager Review",
2060
- description: "Validate business value and team budget.",
2061
- stepOrder: 1,
2062
- type: "APPROVAL",
2063
- requiredRoles: ["manager"],
2064
- createdAt: "2026-03-10T09:00:00.000Z"
2065
- },
2066
- {
2067
- id: "wfstep_expense_finance",
2068
- name: "Finance Review",
2069
- description: "Confirm ledger coding and spending threshold.",
2070
- stepOrder: 2,
2071
- type: "APPROVAL",
2072
- requiredRoles: ["finance"],
2073
- createdAt: "2026-03-10T09:10:00.000Z"
2074
- }
2075
- ]
2076
- },
2077
- {
2078
- id: "wf_vendor",
2079
- name: "Vendor Onboarding",
2080
- description: "Sequence security, procurement, and legal before activation.",
2081
- type: "SEQUENTIAL",
2082
- status: "ACTIVE",
2083
- createdAt: "2026-03-08T11:00:00.000Z",
2084
- updatedAt: "2026-03-19T13:10:00.000Z",
2085
- steps: [
2086
- {
2087
- id: "wfstep_vendor_security",
2088
- name: "Security Check",
2089
- description: "Review data access and integration scope.",
2090
- stepOrder: 1,
2091
- type: "APPROVAL",
2092
- requiredRoles: ["security"],
2093
- createdAt: "2026-03-08T11:00:00.000Z"
2094
- },
2095
- {
2096
- id: "wfstep_vendor_procurement",
2097
- name: "Procurement Check",
2098
- description: "Validate pricing, procurement policy, and owner.",
2099
- stepOrder: 2,
2100
- type: "APPROVAL",
2101
- requiredRoles: ["procurement"],
2102
- createdAt: "2026-03-08T11:05:00.000Z"
2103
- },
2104
- {
2105
- id: "wfstep_vendor_legal",
2106
- name: "Legal Sign-off",
2107
- description: "Approve terms before the vendor goes live.",
2108
- stepOrder: 3,
2109
- type: "APPROVAL",
2110
- requiredRoles: ["legal"],
2111
- createdAt: "2026-03-08T11:10:00.000Z"
2112
- }
2113
- ]
2114
- },
2115
- {
2116
- id: "wf_policy_exception",
2117
- name: "Policy Exception",
2118
- description: "Escalate a temporary exception through team lead and compliance.",
2119
- type: "APPROVAL",
2120
- status: "DRAFT",
2121
- createdAt: "2026-03-15T07:30:00.000Z",
2122
- updatedAt: "2026-03-18T11:20:00.000Z",
2123
- steps: [
2124
- {
2125
- id: "wfstep_policy_lead",
2126
- name: "Team Lead Review",
2127
- description: "Check urgency and expected blast radius.",
2128
- stepOrder: 1,
2129
- type: "APPROVAL",
2130
- requiredRoles: ["team-lead"],
2131
- createdAt: "2026-03-15T07:30:00.000Z"
2132
- },
2133
- {
2134
- id: "wfstep_policy_compliance",
2135
- name: "Compliance Review",
2136
- description: "Accept or reject the exception request.",
2137
- stepOrder: 2,
2138
- type: "APPROVAL",
2139
- requiredRoles: ["compliance"],
2140
- createdAt: "2026-03-15T07:40:00.000Z"
2141
- }
2142
- ]
2143
- }
2144
- ];
2145
- var WORKFLOW_SYSTEM_DEMO_INSTANCES = [
2146
- {
2147
- id: "wfinst_expense_open",
2148
- definitionId: "wf_expense",
2149
- status: "IN_PROGRESS",
2150
- currentStepId: "wfstep_expense_finance",
2151
- data: {
2152
- amount: 4200,
2153
- currency: "EUR",
2154
- vendor: "Nimbus AI"
2155
- },
2156
- requestedBy: "sarah@contractspec.io",
2157
- startedAt: "2026-03-20T08:00:00.000Z",
2158
- approvals: [
2159
- {
2160
- id: "wfappr_expense_manager",
2161
- stepId: "wfstep_expense_manager",
2162
- status: "APPROVED",
2163
- actorId: "manager.demo",
2164
- comment: "Approved for the Q2 automation budget.",
2165
- decidedAt: "2026-03-20T08:15:00.000Z",
2166
- createdAt: "2026-03-20T08:05:00.000Z"
2167
- },
2168
- {
2169
- id: "wfappr_expense_finance",
2170
- stepId: "wfstep_expense_finance",
2171
- status: "PENDING",
2172
- createdAt: "2026-03-20T08:15:00.000Z"
2173
- }
2174
- ]
2175
- },
2176
- {
2177
- id: "wfinst_vendor_done",
2178
- definitionId: "wf_vendor",
2179
- status: "COMPLETED",
2180
- data: {
2181
- vendor: "Acme Cloud",
2182
- riskTier: "medium"
2183
- },
2184
- requestedBy: "leo@contractspec.io",
2185
- startedAt: "2026-03-19T09:30:00.000Z",
2186
- completedAt: "2026-03-19T13:10:00.000Z",
2187
- approvals: [
2188
- {
2189
- id: "wfappr_vendor_security",
2190
- stepId: "wfstep_vendor_security",
2191
- status: "APPROVED",
2192
- actorId: "security.demo",
2193
- comment: "SOC2 scope is acceptable.",
2194
- decidedAt: "2026-03-19T10:10:00.000Z",
2195
- createdAt: "2026-03-19T09:35:00.000Z"
2196
- },
2197
- {
2198
- id: "wfappr_vendor_procurement",
2199
- stepId: "wfstep_vendor_procurement",
2200
- status: "APPROVED",
2201
- actorId: "procurement.demo",
2202
- comment: "Commercial terms match the preferred vendor tier.",
2203
- decidedAt: "2026-03-19T11:25:00.000Z",
2204
- createdAt: "2026-03-19T10:15:00.000Z"
2205
- },
2206
- {
2207
- id: "wfappr_vendor_legal",
2208
- stepId: "wfstep_vendor_legal",
2209
- status: "APPROVED",
2210
- actorId: "legal.demo",
2211
- comment: "MSA redlines are complete.",
2212
- decidedAt: "2026-03-19T13:05:00.000Z",
2213
- createdAt: "2026-03-19T11:30:00.000Z"
2214
- }
2215
- ]
2216
- },
2217
- {
2218
- id: "wfinst_policy_rejected",
2219
- definitionId: "wf_policy_exception",
2220
- status: "REJECTED",
2221
- currentStepId: "wfstep_policy_compliance",
2222
- data: {
2223
- policy: "Model rollout freeze",
2224
- durationDays: 14
2225
- },
2226
- requestedBy: "maya@contractspec.io",
2227
- startedAt: "2026-03-18T10:00:00.000Z",
2228
- completedAt: "2026-03-18T11:20:00.000Z",
2229
- approvals: [
2230
- {
2231
- id: "wfappr_policy_lead",
2232
- stepId: "wfstep_policy_lead",
2233
- status: "APPROVED",
2234
- actorId: "lead.demo",
2235
- comment: "Escalation justified for the release train.",
2236
- decidedAt: "2026-03-18T10:30:00.000Z",
2237
- createdAt: "2026-03-18T10:05:00.000Z"
2238
- },
2239
- {
2240
- id: "wfappr_policy_compliance",
2241
- stepId: "wfstep_policy_compliance",
2242
- status: "REJECTED",
2243
- actorId: "compliance.demo",
2244
- comment: "Exception exceeds the allowed blast radius.",
2245
- decidedAt: "2026-03-18T11:15:00.000Z",
2246
- createdAt: "2026-03-18T10:35:00.000Z"
2247
- }
2248
- ]
2249
- }
2250
- ];
2251
-
2252
- // src/visualizations/catalog.ts
2253
- import {
2254
- defineVisualization,
2255
- VisualizationRegistry
2256
- } from "@contractspec/lib.contracts-spec/visualizations";
2257
- var INSTANCE_LIST_REF = {
2258
- key: "workflow.instance.list",
2259
- version: "1.0.0"
2260
- };
2261
- var META = {
2262
- version: "1.0.0",
2263
- domain: "workflow",
2264
- stability: "experimental",
2265
- owners: ["@example.workflow-system"],
2266
- tags: ["workflow", "visualization", "operations"]
2267
- };
2268
- var WorkflowInstanceStatusVisualization = defineVisualization({
2269
- meta: {
2270
- ...META,
2271
- key: "workflow-system.visualization.instance-status",
2272
- title: "Instance Status Breakdown",
2273
- description: "Distribution of workflow instance states.",
2274
- goal: "Surface the current workload mix.",
2275
- context: "Workflow operations overview."
2276
- },
2277
- source: { primary: INSTANCE_LIST_REF, resultPath: "data" },
2278
- visualization: {
2279
- kind: "pie",
2280
- nameDimension: "status",
2281
- valueMeasure: "instances",
2282
- dimensions: [
2283
- { key: "status", label: "Status", dataPath: "status", type: "category" }
2284
- ],
2285
- measures: [
2286
- {
2287
- key: "instances",
2288
- label: "Instances",
2289
- dataPath: "instances",
2290
- format: "number"
2291
- }
2292
- ],
2293
- table: { caption: "Workflow instance counts by status." }
2294
- }
2295
- });
2296
- var WorkflowThroughputVisualization = defineVisualization({
2297
- meta: {
2298
- ...META,
2299
- key: "workflow-system.visualization.throughput",
2300
- title: "Run Throughput",
2301
- description: "Daily workflow instance starts.",
2302
- goal: "Show operational throughput over time.",
2303
- context: "Workflow trend monitoring."
2304
- },
2305
- source: { primary: INSTANCE_LIST_REF, resultPath: "data" },
2306
- visualization: {
2307
- kind: "cartesian",
2308
- variant: "line",
2309
- xDimension: "day",
2310
- yMeasures: ["instances"],
2311
- dimensions: [{ key: "day", label: "Day", dataPath: "day", type: "time" }],
2312
- measures: [
2313
- {
2314
- key: "instances",
2315
- label: "Instances",
2316
- dataPath: "instances",
2317
- format: "number",
2318
- color: "#0f766e"
2319
- }
2320
- ],
2321
- table: { caption: "Daily workflow instance starts." }
2322
- }
2323
- });
2324
- var WorkflowActiveMetricVisualization = defineVisualization({
2325
- meta: {
2326
- ...META,
2327
- key: "workflow-system.visualization.active-work",
2328
- title: "Active Work",
2329
- description: "Current in-flight or pending workflow instances.",
2330
- goal: "Expose active operational workload.",
2331
- context: "Workflow workload comparison."
2332
- },
2333
- source: { primary: INSTANCE_LIST_REF, resultPath: "data" },
2334
- visualization: {
2335
- kind: "metric",
2336
- measure: "value",
2337
- measures: [
2338
- { key: "value", label: "Instances", dataPath: "value", format: "number" }
2339
- ],
2340
- table: { caption: "Active workflow count." }
2341
- }
2342
- });
2343
- var WorkflowCompletedMetricVisualization = defineVisualization({
2344
- meta: {
2345
- ...META,
2346
- key: "workflow-system.visualization.completed-work",
2347
- title: "Completed Work",
2348
- description: "Completed workflow instances in the current sample.",
2349
- goal: "Show output against active workload.",
2350
- context: "Workflow workload comparison."
2351
- },
2352
- source: { primary: INSTANCE_LIST_REF, resultPath: "data" },
2353
- visualization: {
2354
- kind: "metric",
2355
- measure: "value",
2356
- measures: [
2357
- { key: "value", label: "Instances", dataPath: "value", format: "number" }
2358
- ],
2359
- table: { caption: "Completed workflow count." }
2360
- }
2361
- });
2362
- var WorkflowVisualizationSpecs = [
2363
- WorkflowInstanceStatusVisualization,
2364
- WorkflowThroughputVisualization,
2365
- WorkflowActiveMetricVisualization,
2366
- WorkflowCompletedMetricVisualization
2367
- ];
2368
- var WorkflowVisualizationRegistry = new VisualizationRegistry([
2369
- ...WorkflowVisualizationSpecs
2370
- ]);
2371
- var WorkflowVisualizationRefs = WorkflowVisualizationSpecs.map((spec) => ({
2372
- key: spec.meta.key,
2373
- version: spec.meta.version
2374
- }));
2375
-
2376
- // src/visualizations/selectors.ts
2377
- function toDayKey(value) {
2378
- const date = value instanceof Date ? value : new Date(value);
2379
- return date.toISOString().slice(0, 10);
2380
- }
2381
- function createWorkflowVisualizationSections(instances) {
2382
- const statusCounts = new Map;
2383
- const throughput = new Map;
2384
- let activeCount = 0;
2385
- let completedCount = 0;
2386
- for (const instance of instances) {
2387
- statusCounts.set(instance.status, (statusCounts.get(instance.status) ?? 0) + 1);
2388
- const day = toDayKey(instance.startedAt);
2389
- throughput.set(day, (throughput.get(day) ?? 0) + 1);
2390
- if (instance.status === "PENDING" || instance.status === "IN_PROGRESS") {
2391
- activeCount += 1;
2392
- }
2393
- if (instance.status === "COMPLETED") {
2394
- completedCount += 1;
2395
- }
2396
- }
2397
- const primaryItems = [
2398
- {
2399
- key: "workflow-status",
2400
- spec: WorkflowInstanceStatusVisualization,
2401
- data: {
2402
- data: Array.from(statusCounts.entries()).map(([status, count]) => ({
2403
- status,
2404
- instances: count
2405
- }))
2406
- },
2407
- title: "Instance Status Breakdown",
2408
- description: "Status mix across workflow instances.",
2409
- height: 260
2410
- },
2411
- {
2412
- key: "workflow-throughput",
2413
- spec: WorkflowThroughputVisualization,
2414
- data: {
2415
- data: Array.from(throughput.entries()).sort(([left], [right]) => left.localeCompare(right)).map(([day, count]) => ({ day, instances: count }))
2416
- },
2417
- title: "Run Throughput",
2418
- description: "Daily workflow starts from current instances."
2419
- }
2420
- ];
2421
- const comparisonItems = [
2422
- {
2423
- key: "workflow-active",
2424
- spec: WorkflowActiveMetricVisualization,
2425
- data: { data: [{ value: activeCount }] },
2426
- title: "Active Work",
2427
- description: "Pending and in-progress workflows.",
2428
- height: 200
2429
- },
2430
- {
2431
- key: "workflow-completed",
2432
- spec: WorkflowCompletedMetricVisualization,
2433
- data: { data: [{ value: completedCount }] },
2434
- title: "Completed Work",
2435
- description: "Completed workflows in the current sample.",
2436
- height: 200
2437
- }
2438
- ];
2439
- return {
2440
- primaryItems,
2441
- comparisonItems
2442
- };
2443
- }
2444
- // src/ui/renderers/workflow.markdown.ts
2445
- var workflowDefinitions = WORKFLOW_SYSTEM_DEMO_DEFINITIONS;
2446
- var workflowInstances = WORKFLOW_SYSTEM_DEMO_INSTANCES;
2447
- var workflowDefinitionById = new Map(workflowDefinitions.map((definition) => [definition.id, definition]));
2448
- function formatDate(value) {
2449
- return new Date(value).toISOString().slice(0, 10);
2450
- }
2451
- var workflowDashboardMarkdownRenderer = {
2452
- target: "markdown",
2453
- render: async (desc) => {
2454
- if (desc.source.type !== "component" || desc.source.componentKey !== "WorkflowDashboard") {
2455
- throw new Error("workflowDashboardMarkdownRenderer: not WorkflowDashboard");
2456
- }
2457
- const definitions = workflowDefinitions;
2458
- const instances = workflowInstances;
2459
- const visualizations = createWorkflowVisualizationSections(instances);
2460
- const activeDefinitions = definitions.filter((d) => d.status === "ACTIVE");
2461
- const awaitingActionInstances = instances.filter((i) => i.status === "PENDING" || i.status === "IN_PROGRESS");
2462
- const lines = [
2463
- "# Workflow Dashboard",
2464
- "",
2465
- "> Seeded workflow and approval overview for the sandbox demo.",
2466
- "",
2467
- "## Summary",
2468
- "",
2469
- "| Metric | Value |",
2470
- "|--------|-------|",
2471
- `| Active Workflows | ${activeDefinitions.length} |`,
2472
- `| Awaiting Action | ${awaitingActionInstances.length} |`,
2473
- `| Completed | ${instances.filter((i) => i.status === "COMPLETED").length} |`,
2474
- `| Rejected | ${instances.filter((i) => i.status === "REJECTED").length} |`,
2475
- ""
2476
- ];
2477
- lines.push("## Visualization Overview");
2478
- lines.push("");
2479
- for (const item of [
2480
- ...visualizations.primaryItems,
2481
- ...visualizations.comparisonItems
2482
- ]) {
2483
- lines.push(`- **${item.title}** via \`${item.spec.meta.key}\``);
2484
- }
2485
- lines.push("");
2486
- lines.push("## Active Workflow Definitions");
2487
- lines.push("");
2488
- if (activeDefinitions.length === 0) {
2489
- lines.push("_No active workflow definitions._");
2490
- } else {
2491
- lines.push("| Name | Type | Steps | Status |");
2492
- lines.push("|------|------|-------|--------|");
2493
- for (const def of activeDefinitions) {
2494
- lines.push(`| ${def.name} | ${def.type} | ${def.steps.length} | ${def.status} |`);
2495
- }
2496
- }
2497
- lines.push("");
2498
- lines.push("## Recent Instances");
2499
- lines.push("");
2500
- if (instances.length === 0) {
2501
- lines.push("_No workflow instances._");
2502
- } else {
2503
- lines.push("| Workflow | Requested By | Status | Started |");
2504
- lines.push("|----------|--------------|--------|---------|");
2505
- for (const inst of instances.slice(0, 10)) {
2506
- const startedDate = formatDate(inst.startedAt);
2507
- const definitionName = workflowDefinitionById.get(inst.definitionId)?.name ?? inst.definitionId;
2508
- lines.push(`| ${definitionName} | ${inst.requestedBy} | ${inst.status} | ${startedDate} |`);
2509
- }
2510
- }
2511
- return {
2512
- mimeType: "text/markdown",
2513
- body: lines.join(`
2514
- `)
2515
- };
2516
- }
2517
- };
2518
- var workflowDefinitionListMarkdownRenderer = {
2519
- target: "markdown",
2520
- render: async (desc) => {
2521
- if (desc.source.type !== "component" || desc.source.componentKey !== "WorkflowDefinitionList") {
2522
- throw new Error("workflowDefinitionListMarkdownRenderer: not WorkflowDefinitionList");
2523
- }
2524
- const definitions = workflowDefinitions;
2525
- const lines = [
2526
- "# Workflow Definitions",
2527
- "",
2528
- "> Configure automated approval and process workflows",
2529
- ""
2530
- ];
2531
- for (const def of definitions) {
2532
- lines.push(`## ${def.name}`);
2533
- lines.push("");
2534
- lines.push(`**Type:** ${def.type} | **Status:** ${def.status}`);
2535
- lines.push("");
2536
- lines.push("### Steps");
2537
- lines.push("");
2538
- for (const step of def.steps) {
2539
- lines.push(`${step.stepOrder}. **${step.name}** - Roles: ${step.requiredRoles.join(", ")}`);
2540
- }
2541
- lines.push("");
2542
- }
2543
- return {
2544
- mimeType: "text/markdown",
2545
- body: lines.join(`
2546
- `)
2547
- };
2548
- }
2549
- };
2550
- var workflowInstanceDetailMarkdownRenderer = {
2551
- target: "markdown",
2552
- render: async (desc) => {
2553
- if (desc.source.type !== "component" || desc.source.componentKey !== "WorkflowInstanceDetail") {
2554
- throw new Error("workflowInstanceDetailMarkdownRenderer: not WorkflowInstanceDetail");
2555
- }
2556
- const instance = workflowInstances.find((workflowInstance) => workflowInstance.status === "IN_PROGRESS") ?? workflowInstances[0];
2557
- if (!instance) {
2558
- return {
2559
- mimeType: "text/markdown",
2560
- body: `# No Workflow Instances
2561
-
2562
- No workflow instances available.`
2563
- };
2564
- }
2565
- const definition = workflowDefinitions.find((d) => d.id === instance.definitionId);
2566
- const lines = [
2567
- `# Workflow: ${definition?.name ?? instance.definitionId}`,
2568
- "",
2569
- `**Instance ID:** ${instance.id}`,
2570
- `**Status:** ${instance.status}`,
2571
- `**Requested By:** ${instance.requestedBy}`,
2572
- `**Started:** ${formatDate(instance.startedAt)}`,
2573
- "",
2574
- "## Steps Progress",
2575
- ""
2576
- ];
2577
- if (definition) {
2578
- for (const step of definition.steps) {
2579
- const isCurrent = step.id === instance.currentStepId;
2580
- const isCompleted = definition.steps.indexOf(step) < definition.steps.findIndex((s) => s.id === instance.currentStepId);
2581
- let status = "⬜ Pending";
2582
- if (isCompleted)
2583
- status = "✅ Completed";
2584
- if (isCurrent)
2585
- status = "\uD83D\uDD04 In Progress";
2586
- lines.push(`- ${status} **${step.name}**`);
2587
- }
2588
- }
2589
- lines.push("");
2590
- lines.push("## Actions");
2591
- lines.push("");
2592
- lines.push("- **Approve** - Move to next step");
2593
- lines.push("- **Reject** - End the workflow with a rejection outcome");
2594
- lines.push("- **Delegate** - Assign to another approver");
2595
- return {
2596
- mimeType: "text/markdown",
2597
- body: lines.join(`
2598
- `)
2599
- };
2600
- }
2601
- };
2602
- // src/ui/WorkflowDashboard.visualizations.tsx
2603
- import {
2604
- ComparisonView,
2605
- VisualizationCard,
2606
- VisualizationGrid
2607
- } from "@contractspec/lib.design-system";
2608
- import { jsxDEV } from "react/jsx-dev-runtime";
2609
- "use client";
2610
- function WorkflowVisualizationOverview({
2611
- instances
2612
- }) {
2613
- const { primaryItems, comparisonItems } = createWorkflowVisualizationSections(instances);
2614
- return /* @__PURE__ */ jsxDEV("section", {
2615
- className: "space-y-4",
2616
- children: [
2617
- /* @__PURE__ */ jsxDEV("div", {
2618
- children: [
2619
- /* @__PURE__ */ jsxDEV("h3", {
2620
- className: "font-semibold text-lg",
2621
- children: "Workflow Visualizations"
2622
- }, undefined, false, undefined, this),
2623
- /* @__PURE__ */ jsxDEV("p", {
2624
- className: "text-muted-foreground text-sm",
2625
- children: "Contract-backed charts for workflow health and throughput."
2626
- }, undefined, false, undefined, this)
2627
- ]
2628
- }, undefined, true, undefined, this),
2629
- /* @__PURE__ */ jsxDEV(VisualizationGrid, {
2630
- children: primaryItems.map((item) => /* @__PURE__ */ jsxDEV(VisualizationCard, {
2631
- data: item.data,
2632
- description: item.description,
2633
- height: item.height,
2634
- spec: item.spec,
2635
- title: item.title
2636
- }, item.key, false, undefined, this))
2637
- }, undefined, false, undefined, this),
2638
- /* @__PURE__ */ jsxDEV(ComparisonView, {
2639
- description: "Shared comparison surface for active versus completed work.",
2640
- items: comparisonItems,
2641
- title: "Workload Comparison"
2642
- }, undefined, false, undefined, this)
2643
- ]
2644
- }, undefined, true, undefined, this);
2645
- }
2646
-
2647
- // src/ui/WorkflowDashboard.tsx
2648
- import {
2649
- Button,
2650
- ErrorState,
2651
- LoaderBlock,
2652
- StatCard,
2653
- StatCardGroup
2654
- } from "@contractspec/lib.design-system";
2655
- import { useState as useState2 } from "react";
2656
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
2657
- "use client";
2658
- var STATUS_COLORS = {
2659
- ACTIVE: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
2660
- DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
2661
- ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
2662
- PENDING: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
2663
- IN_PROGRESS: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
2664
- COMPLETED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
2665
- REJECTED: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
2666
- CANCELLED: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
2667
- };
2668
- function WorkflowDashboard() {
2669
- const [activeTab, setActiveTab] = useState2("definitions");
2670
- const { definitions, instances, loading, error, stats, refetch } = useWorkflowList();
2671
- const tabs = [
2672
- { id: "definitions", label: "Definitions", icon: "\uD83D\uDCCB" },
2673
- { id: "instances", label: "Instances", icon: "\uD83D\uDD04" }
2674
- ];
2675
- if (loading) {
2676
- return /* @__PURE__ */ jsxDEV2(LoaderBlock, {
2677
- label: "Loading Workflows..."
2678
- }, undefined, false, undefined, this);
2679
- }
2680
- if (error) {
2681
- return /* @__PURE__ */ jsxDEV2(ErrorState, {
2682
- title: "Failed to load Workflows",
2683
- description: error.message,
2684
- onRetry: refetch,
2685
- retryLabel: "Retry"
2686
- }, undefined, false, undefined, this);
2687
- }
2688
- return /* @__PURE__ */ jsxDEV2("div", {
2689
- className: "space-y-6",
2690
- children: [
2691
- /* @__PURE__ */ jsxDEV2("div", {
2692
- className: "flex items-center justify-between",
2693
- children: [
2694
- /* @__PURE__ */ jsxDEV2("h2", {
2695
- className: "font-bold text-2xl",
2696
- children: "Workflow System"
2697
- }, undefined, false, undefined, this),
2698
- /* @__PURE__ */ jsxDEV2(Button, {
2699
- onClick: () => void refetch(),
2700
- children: "Refresh"
2701
- }, undefined, false, undefined, this)
2702
- ]
2703
- }, undefined, true, undefined, this),
2704
- /* @__PURE__ */ jsxDEV2(StatCardGroup, {
2705
- children: [
2706
- /* @__PURE__ */ jsxDEV2(StatCard, {
2707
- label: "Workflows",
2708
- value: stats.totalDefinitions,
2709
- hint: `${stats.activeDefinitions} active`
2710
- }, undefined, false, undefined, this),
2711
- /* @__PURE__ */ jsxDEV2(StatCard, {
2712
- label: "Instances",
2713
- value: stats.totalInstances,
2714
- hint: "total runs"
2715
- }, undefined, false, undefined, this),
2716
- /* @__PURE__ */ jsxDEV2(StatCard, {
2717
- label: "Awaiting Action",
2718
- value: stats.pendingInstances + stats.inProgressInstances,
2719
- hint: "open approvals"
2720
- }, undefined, false, undefined, this),
2721
- /* @__PURE__ */ jsxDEV2(StatCard, {
2722
- label: "Completed",
2723
- value: stats.completedInstances,
2724
- hint: "finished"
2725
- }, undefined, false, undefined, this)
2726
- ]
2727
- }, undefined, true, undefined, this),
2728
- /* @__PURE__ */ jsxDEV2(WorkflowVisualizationOverview, {
2729
- instances
2730
- }, undefined, false, undefined, this),
2731
- /* @__PURE__ */ jsxDEV2("nav", {
2732
- className: "flex gap-1 rounded-lg bg-muted p-1",
2733
- role: "tablist",
2734
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV2(Button, {
2735
- type: "button",
2736
- role: "tab",
2737
- "aria-selected": activeTab === tab.id,
2738
- onClick: () => setActiveTab(tab.id),
2739
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
2740
- children: [
2741
- /* @__PURE__ */ jsxDEV2("span", {
2742
- children: tab.icon
2743
- }, undefined, false, undefined, this),
2744
- tab.label
2745
- ]
2746
- }, tab.id, true, undefined, this))
2747
- }, undefined, false, undefined, this),
2748
- /* @__PURE__ */ jsxDEV2("div", {
2749
- className: "min-h-[400px]",
2750
- role: "tabpanel",
2751
- children: [
2752
- activeTab === "definitions" && /* @__PURE__ */ jsxDEV2("div", {
2753
- className: "rounded-lg border border-border",
2754
- children: /* @__PURE__ */ jsxDEV2("table", {
2755
- className: "w-full",
2756
- children: [
2757
- /* @__PURE__ */ jsxDEV2("thead", {
2758
- className: "border-border border-b bg-muted/30",
2759
- children: /* @__PURE__ */ jsxDEV2("tr", {
2760
- children: [
2761
- /* @__PURE__ */ jsxDEV2("th", {
2762
- className: "px-4 py-3 text-left font-medium text-sm",
2763
- children: "Name"
2764
- }, undefined, false, undefined, this),
2765
- /* @__PURE__ */ jsxDEV2("th", {
2766
- className: "px-4 py-3 text-left font-medium text-sm",
2767
- children: "Type"
2768
- }, undefined, false, undefined, this),
2769
- /* @__PURE__ */ jsxDEV2("th", {
2770
- className: "px-4 py-3 text-left font-medium text-sm",
2771
- children: "Status"
2772
- }, undefined, false, undefined, this),
2773
- /* @__PURE__ */ jsxDEV2("th", {
2774
- className: "px-4 py-3 text-left font-medium text-sm",
2775
- children: "Created"
2776
- }, undefined, false, undefined, this)
2777
- ]
2778
- }, undefined, true, undefined, this)
2779
- }, undefined, false, undefined, this),
2780
- /* @__PURE__ */ jsxDEV2("tbody", {
2781
- className: "divide-y divide-border",
2782
- children: [
2783
- definitions.map((def) => /* @__PURE__ */ jsxDEV2("tr", {
2784
- className: "hover:bg-muted/50",
2785
- children: [
2786
- /* @__PURE__ */ jsxDEV2("td", {
2787
- className: "px-4 py-3",
2788
- children: [
2789
- /* @__PURE__ */ jsxDEV2("div", {
2790
- className: "font-medium",
2791
- children: def.name
2792
- }, undefined, false, undefined, this),
2793
- /* @__PURE__ */ jsxDEV2("div", {
2794
- className: "text-muted-foreground text-sm",
2795
- children: def.description
2796
- }, undefined, false, undefined, this)
2797
- ]
2798
- }, undefined, true, undefined, this),
2799
- /* @__PURE__ */ jsxDEV2("td", {
2800
- className: "px-4 py-3 font-mono text-sm",
2801
- children: def.type
2802
- }, undefined, false, undefined, this),
2803
- /* @__PURE__ */ jsxDEV2("td", {
2804
- className: "px-4 py-3",
2805
- children: /* @__PURE__ */ jsxDEV2("span", {
2806
- className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[def.status] ?? ""}`,
2807
- children: def.status
2808
- }, undefined, false, undefined, this)
2809
- }, undefined, false, undefined, this),
2810
- /* @__PURE__ */ jsxDEV2("td", {
2811
- className: "px-4 py-3 text-muted-foreground text-sm",
2812
- children: def.createdAt.toLocaleDateString()
2813
- }, undefined, false, undefined, this)
2814
- ]
2815
- }, def.id, true, undefined, this)),
2816
- definitions.length === 0 && /* @__PURE__ */ jsxDEV2("tr", {
2817
- children: /* @__PURE__ */ jsxDEV2("td", {
2818
- colSpan: 4,
2819
- className: "px-4 py-8 text-center text-muted-foreground",
2820
- children: "No workflow definitions found"
2821
- }, undefined, false, undefined, this)
2822
- }, undefined, false, undefined, this)
2823
- ]
2824
- }, undefined, true, undefined, this)
2825
- ]
2826
- }, undefined, true, undefined, this)
2827
- }, undefined, false, undefined, this),
2828
- activeTab === "instances" && /* @__PURE__ */ jsxDEV2("div", {
2829
- className: "rounded-lg border border-border",
2830
- children: /* @__PURE__ */ jsxDEV2("table", {
2831
- className: "w-full",
2832
- children: [
2833
- /* @__PURE__ */ jsxDEV2("thead", {
2834
- className: "border-border border-b bg-muted/30",
2835
- children: /* @__PURE__ */ jsxDEV2("tr", {
2836
- children: [
2837
- /* @__PURE__ */ jsxDEV2("th", {
2838
- className: "px-4 py-3 text-left font-medium text-sm",
2839
- children: "Instance ID"
2840
- }, undefined, false, undefined, this),
2841
- /* @__PURE__ */ jsxDEV2("th", {
2842
- className: "px-4 py-3 text-left font-medium text-sm",
2843
- children: "Status"
2844
- }, undefined, false, undefined, this),
2845
- /* @__PURE__ */ jsxDEV2("th", {
2846
- className: "px-4 py-3 text-left font-medium text-sm",
2847
- children: "Requested By"
2848
- }, undefined, false, undefined, this),
2849
- /* @__PURE__ */ jsxDEV2("th", {
2850
- className: "px-4 py-3 text-left font-medium text-sm",
2851
- children: "Started"
2852
- }, undefined, false, undefined, this)
2853
- ]
2854
- }, undefined, true, undefined, this)
2855
- }, undefined, false, undefined, this),
2856
- /* @__PURE__ */ jsxDEV2("tbody", {
2857
- className: "divide-y divide-border",
2858
- children: [
2859
- instances.map((inst) => /* @__PURE__ */ jsxDEV2("tr", {
2860
- className: "hover:bg-muted/50",
2861
- children: [
2862
- /* @__PURE__ */ jsxDEV2("td", {
2863
- className: "px-4 py-3 font-mono text-sm",
2864
- children: inst.id
2865
- }, undefined, false, undefined, this),
2866
- /* @__PURE__ */ jsxDEV2("td", {
2867
- className: "px-4 py-3",
2868
- children: /* @__PURE__ */ jsxDEV2("span", {
2869
- className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[inst.status] ?? ""}`,
2870
- children: inst.status
2871
- }, undefined, false, undefined, this)
2872
- }, undefined, false, undefined, this),
2873
- /* @__PURE__ */ jsxDEV2("td", {
2874
- className: "px-4 py-3 text-sm",
2875
- children: inst.requestedBy
2876
- }, undefined, false, undefined, this),
2877
- /* @__PURE__ */ jsxDEV2("td", {
2878
- className: "px-4 py-3 text-muted-foreground text-sm",
2879
- children: inst.startedAt.toLocaleDateString()
2880
- }, undefined, false, undefined, this)
2881
- ]
2882
- }, inst.id, true, undefined, this)),
2883
- instances.length === 0 && /* @__PURE__ */ jsxDEV2("tr", {
2884
- children: /* @__PURE__ */ jsxDEV2("td", {
2885
- colSpan: 4,
2886
- className: "px-4 py-8 text-center text-muted-foreground",
2887
- children: "No workflow instances found"
2888
- }, undefined, false, undefined, this)
2889
- }, undefined, false, undefined, this)
2890
- ]
2891
- }, undefined, true, undefined, this)
2892
- ]
2893
- }, undefined, true, undefined, this)
2894
- }, undefined, false, undefined, this)
2895
- ]
2896
- }, undefined, true, undefined, this)
2897
- ]
2898
- }, undefined, true, undefined, this);
2899
- }
2900
- // src/workflow/workflow.event.ts
2901
- import { defineEvent as defineEvent3 } from "@contractspec/lib.contracts-spec";
2902
- import { defineSchemaModel as defineSchemaModel8, ScalarTypeEnum as ScalarTypeEnum8 } from "@contractspec/lib.schema";
2903
- var WorkflowDefinitionPayload = defineSchemaModel8({
2904
- name: "WorkflowDefinitionEventPayload",
2905
- description: "Payload for workflow definition events",
2906
- fields: {
2907
- workflowId: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2908
- key: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2909
- name: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2910
- version: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2911
- organizationId: {
2912
- type: ScalarTypeEnum8.String_unsecure(),
2913
- isOptional: false
2914
- },
2915
- createdBy: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2916
- timestamp: { type: ScalarTypeEnum8.DateTime(), isOptional: false }
2917
- }
2918
- });
2919
- var StepAddedPayload = defineSchemaModel8({
2920
- name: "StepAddedEventPayload",
2921
- description: "Payload when a step is added",
2922
- fields: {
2923
- stepId: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2924
- workflowId: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2925
- stepKey: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2926
- stepType: { type: ScalarTypeEnum8.String_unsecure(), isOptional: false },
2927
- position: { type: ScalarTypeEnum8.Int_unsecure(), isOptional: false },
2928
- timestamp: { type: ScalarTypeEnum8.DateTime(), isOptional: false }
2929
- }
2930
- });
2931
- var WorkflowCreatedEvent = defineEvent3({
2932
- meta: {
2933
- key: "workflow.definition.created",
2934
- version: "1.0.0",
2935
- description: "A new workflow definition has been created.",
2936
- stability: "stable",
2937
- owners: ["@workflow-team"],
2938
- tags: ["workflow", "definition", "created"]
2939
- },
2940
- payload: WorkflowDefinitionPayload
2941
- });
2942
- var WorkflowUpdatedEvent = defineEvent3({
2943
- meta: {
2944
- key: "workflow.definition.updated",
2945
- version: "1.0.0",
2946
- description: "A workflow definition has been updated.",
2947
- stability: "stable",
2948
- owners: ["@workflow-team"],
2949
- tags: ["workflow", "definition", "updated"]
2950
- },
2951
- payload: WorkflowDefinitionPayload
2952
- });
2953
- var WorkflowPublishedEvent = defineEvent3({
2954
- meta: {
2955
- key: "workflow.definition.published",
2956
- version: "1.0.0",
2957
- description: "A workflow definition has been published and is now active.",
2958
- stability: "stable",
2959
- owners: ["@workflow-team"],
2960
- tags: ["workflow", "definition", "published"]
2961
- },
2962
- payload: WorkflowDefinitionPayload
2963
- });
2964
- var StepAddedEvent = defineEvent3({
2965
- meta: {
2966
- key: "workflow.step.added",
2967
- version: "1.0.0",
2968
- description: "A step has been added to a workflow definition.",
2969
- stability: "stable",
2970
- owners: ["@workflow-team"],
2971
- tags: ["workflow", "step", "added"]
2972
- },
2973
- payload: StepAddedPayload
2974
- });
2975
-
2976
- // src/workflow/workflow.operations.ts
2977
- import {
2978
- defineCommand as defineCommand3,
2979
- defineQuery as defineQuery3
2980
- } from "@contractspec/lib.contracts-spec/operations";
2981
- import { defineSchemaModel as defineSchemaModel9, ScalarTypeEnum as ScalarTypeEnum9 } from "@contractspec/lib.schema";
2982
- var OWNERS3 = ["@example.workflow-system"];
2983
- var CreateWorkflowContract = defineCommand3({
2984
- meta: {
2985
- key: "workflow.definition.create",
2986
- version: "1.0.0",
2987
- stability: "stable",
2988
- owners: [...OWNERS3],
2989
- tags: ["workflow", "definition", "create"],
2990
- description: "Create a new workflow definition.",
2991
- goal: "Allow users to define new workflow blueprints.",
2992
- context: "Workflow designer, admin panel."
2993
- },
2994
- io: {
2995
- input: CreateWorkflowInputModel,
2996
- output: WorkflowDefinitionModel
2997
- },
2998
- policy: { auth: "user" },
2999
- sideEffects: {
3000
- emits: [
3001
- {
3002
- key: "workflow.definition.created",
3003
- version: "1.0.0",
3004
- when: "Workflow is created",
3005
- payload: WorkflowDefinitionModel
3006
- }
3007
- ],
3008
- audit: ["workflow.definition.created"]
3009
- },
3010
- acceptance: {
3011
- scenarios: [
3012
- {
3013
- key: "create-workflow-happy-path",
3014
- given: ["User is admin"],
3015
- when: ["User creates new workflow definition"],
3016
- then: [
3017
- "Definition is created",
3018
- "WorkflowDefinitionCreated event is emitted"
3019
- ]
3020
- }
3021
- ],
3022
- examples: [
3023
- {
3024
- key: "create-onboarding",
3025
- input: {
3026
- key: "onboarding-v1",
3027
- name: "Employee Onboarding",
3028
- version: "1.0.0"
3029
- },
3030
- output: { id: "def-123", status: "draft" }
3031
- }
3032
- ]
3033
- }
3034
- });
3035
- var UpdateWorkflowContract = defineCommand3({
3036
- meta: {
3037
- key: "workflow.definition.update",
3038
- version: "1.0.0",
3039
- stability: "stable",
3040
- owners: [...OWNERS3],
3041
- tags: ["workflow", "definition", "update"],
3042
- description: "Update an existing workflow definition.",
3043
- goal: "Allow users to modify workflow blueprints.",
3044
- context: "Workflow designer."
3045
- },
3046
- io: {
3047
- input: UpdateWorkflowInputModel,
3048
- output: WorkflowDefinitionModel
3049
- },
3050
- policy: { auth: "user" },
3051
- sideEffects: {
3052
- emits: [
3053
- {
3054
- key: "workflow.definition.updated",
3055
- version: "1.0.0",
3056
- when: "Workflow is updated",
3057
- payload: WorkflowDefinitionModel
3058
- }
3059
- ],
3060
- audit: ["workflow.definition.updated"]
3061
- },
3062
- acceptance: {
3063
- scenarios: [
3064
- {
3065
- key: "update-workflow-happy-path",
3066
- given: ["Workflow definition exists"],
3067
- when: ["User updates definition"],
3068
- then: [
3069
- "Definition is updated",
3070
- "WorkflowDefinitionUpdated event is emitted"
3071
- ]
3072
- }
3073
- ],
3074
- examples: [
3075
- {
3076
- key: "update-name",
3077
- input: { workflowId: "def-123", name: "New Employee Onboarding" },
3078
- output: { id: "def-123", name: "New Employee Onboarding" }
3079
- }
3080
- ]
3081
- }
3082
- });
3083
- var AddStepContract = defineCommand3({
3084
- meta: {
3085
- key: "workflow.step.add",
3086
- version: "1.0.0",
3087
- stability: "stable",
3088
- owners: [...OWNERS3],
3089
- tags: ["workflow", "step", "add"],
3090
- description: "Add a step to a workflow definition.",
3091
- goal: "Build workflow structure step by step.",
3092
- context: "Workflow designer."
3093
- },
3094
- io: {
3095
- input: AddStepInputModel,
3096
- output: WorkflowStepModel
3097
- },
3098
- policy: { auth: "user" },
3099
- sideEffects: {
3100
- emits: [
3101
- {
3102
- key: "workflow.step.added",
3103
- version: "1.0.0",
3104
- when: "Step is added",
3105
- payload: WorkflowStepModel
3106
- }
3107
- ],
3108
- audit: ["workflow.step.added"]
3109
- },
3110
- acceptance: {
3111
- scenarios: [
3112
- {
3113
- key: "add-step-happy-path",
3114
- given: ["Workflow definition exists"],
3115
- when: ["User adds a step"],
3116
- then: ["Step is added", "StepAdded event is emitted"]
3117
- }
3118
- ],
3119
- examples: [
3120
- {
3121
- key: "add-approval-step",
3122
- input: {
3123
- workflowId: "def-123",
3124
- stepKey: "approve-contract",
3125
- type: "approval"
3126
- },
3127
- output: { id: "step-456", key: "approve-contract" }
3128
- }
3129
- ]
3130
- }
3131
- });
3132
- var PublishWorkflowContract = defineCommand3({
3133
- meta: {
3134
- key: "workflow.definition.publish",
3135
- version: "1.0.0",
3136
- stability: "stable",
3137
- owners: [...OWNERS3],
3138
- tags: ["workflow", "definition", "publish"],
3139
- description: "Publish a workflow definition to make it available for use.",
3140
- goal: "Activate workflow for production use.",
3141
- context: "Workflow designer, deployment."
3142
- },
3143
- io: {
3144
- input: defineSchemaModel9({
3145
- name: "PublishWorkflowInput",
3146
- fields: {
3147
- workflowId: {
3148
- type: ScalarTypeEnum9.String_unsecure(),
3149
- isOptional: false
3150
- }
3151
- }
3152
- }),
3153
- output: WorkflowDefinitionModel
3154
- },
3155
- policy: { auth: "user" },
3156
- sideEffects: {
3157
- emits: [
3158
- {
3159
- key: "workflow.definition.published",
3160
- version: "1.0.0",
3161
- when: "Workflow is published",
3162
- payload: WorkflowDefinitionModel
3163
- }
3164
- ],
3165
- audit: ["workflow.definition.published"]
3166
- },
3167
- acceptance: {
3168
- scenarios: [
3169
- {
3170
- key: "publish-workflow-happy-path",
3171
- given: ["Workflow definition is valid"],
3172
- when: ["User publishes workflow"],
3173
- then: ["Workflow becomes active", "WorkflowPublished event is emitted"]
3174
- }
3175
- ],
3176
- examples: [
3177
- {
3178
- key: "publish-onboarding",
3179
- input: { workflowId: "def-123" },
3180
- output: { id: "def-123", status: "published" }
3181
- }
3182
- ]
3183
- }
3184
- });
3185
- var ListWorkflowsContract = defineQuery3({
3186
- meta: {
3187
- key: "workflow.definition.list",
3188
- version: "1.0.0",
3189
- stability: "stable",
3190
- owners: [...OWNERS3],
3191
- tags: ["workflow", "definition", "list"],
3192
- description: "List workflow definitions with filtering.",
3193
- goal: "Browse and search available workflows.",
3194
- context: "Workflow list, search."
3195
- },
3196
- io: {
3197
- input: defineSchemaModel9({
3198
- name: "ListWorkflowsInput",
3199
- fields: {
3200
- status: { type: WorkflowStatusEnum, isOptional: true },
3201
- search: { type: ScalarTypeEnum9.String_unsecure(), isOptional: true },
3202
- limit: {
3203
- type: ScalarTypeEnum9.Int_unsecure(),
3204
- isOptional: true,
3205
- defaultValue: 20
3206
- },
3207
- offset: {
3208
- type: ScalarTypeEnum9.Int_unsecure(),
3209
- isOptional: true,
3210
- defaultValue: 0
3211
- }
3212
- }
3213
- }),
3214
- output: defineSchemaModel9({
3215
- name: "ListWorkflowsOutput",
3216
- fields: {
3217
- workflows: {
3218
- type: WorkflowDefinitionModel,
3219
- isArray: true,
3220
- isOptional: false
3221
- },
3222
- total: { type: ScalarTypeEnum9.Int_unsecure(), isOptional: false }
3223
- }
3224
- })
3225
- },
3226
- policy: { auth: "user" },
3227
- acceptance: {
3228
- scenarios: [
3229
- {
3230
- key: "list-workflows-happy-path",
3231
- given: ["Workflow definitions exist"],
3232
- when: ["User lists workflows"],
3233
- then: ["List of workflows is returned"]
3234
- }
3235
- ],
3236
- examples: [
3237
- {
3238
- key: "list-all",
3239
- input: { limit: 10 },
3240
- output: { workflows: [], total: 5 }
3241
- }
3242
- ]
3243
- }
3244
- });
3245
- var GetWorkflowContract = defineQuery3({
3246
- meta: {
3247
- key: "workflow.definition.get",
3248
- version: "1.0.0",
3249
- stability: "stable",
3250
- owners: [...OWNERS3],
3251
- tags: ["workflow", "definition", "get"],
3252
- description: "Get a workflow definition with all steps.",
3253
- goal: "View workflow details.",
3254
- context: "Workflow designer, detail view."
3255
- },
3256
- io: {
3257
- input: defineSchemaModel9({
3258
- name: "GetWorkflowInput",
3259
- fields: {
3260
- workflowId: {
3261
- type: ScalarTypeEnum9.String_unsecure(),
3262
- isOptional: false
3263
- }
3264
- }
3265
- }),
3266
- output: WorkflowDefinitionModel
3267
- },
3268
- policy: { auth: "user" },
3269
- acceptance: {
3270
- scenarios: [
3271
- {
3272
- key: "get-workflow-happy-path",
3273
- given: ["Workflow definition exists"],
3274
- when: ["User requests workflow details"],
3275
- then: ["Workflow details are returned"]
3276
- }
3277
- ],
3278
- examples: [
3279
- {
3280
- key: "get-details",
3281
- input: { workflowId: "def-123" },
3282
- output: { id: "def-123", name: "Employee Onboarding" }
3283
- }
3284
- ]
3285
- }
3286
- });
3287
- // src/workflow-system.feature.ts
3288
- import { defineFeature } from "@contractspec/lib.contracts-spec";
3289
- var WorkflowSystemFeature = defineFeature({
3290
- meta: {
3291
- key: "workflow-system",
3292
- title: "Workflow & Approval System",
3293
- description: "State machine-based workflow engine with role-based approvals, delegation, and escalation",
3294
- domain: "workflow",
3295
- owners: ["@workflow-team"],
3296
- tags: ["workflow", "approval", "state-machine", "automation"],
3297
- stability: "experimental",
3298
- version: "1.0.0"
3299
- },
3300
- operations: [
3301
- { key: "workflow.definition.create", version: "1.0.0" },
3302
- { key: "workflow.definition.update", version: "1.0.0" },
3303
- { key: "workflow.step.add", version: "1.0.0" },
3304
- { key: "workflow.definition.publish", version: "1.0.0" },
3305
- { key: "workflow.definition.list", version: "1.0.0" },
3306
- { key: "workflow.definition.get", version: "1.0.0" },
3307
- { key: "workflow.instance.start", version: "1.0.0" },
3308
- { key: "workflow.instance.transition", version: "1.0.0" },
3309
- { key: "workflow.instance.pause", version: "1.0.0" },
3310
- { key: "workflow.instance.resume", version: "1.0.0" },
3311
- { key: "workflow.instance.cancel", version: "1.0.0" },
3312
- { key: "workflow.instance.list", version: "1.0.0" },
3313
- { key: "workflow.instance.get", version: "1.0.0" },
3314
- { key: "workflow.approval.decide", version: "1.0.0" },
3315
- { key: "workflow.approval.delegate", version: "1.0.0" },
3316
- { key: "workflow.approval.comment.add", version: "1.0.0" },
3317
- { key: "workflow.approval.list.mine", version: "1.0.0" },
3318
- { key: "workflow.approval.get", version: "1.0.0" }
3319
- ],
3320
- events: [
3321
- { key: "workflow.definition.created", version: "1.0.0" },
3322
- { key: "workflow.definition.updated", version: "1.0.0" },
3323
- { key: "workflow.definition.published", version: "1.0.0" },
3324
- { key: "workflow.step.added", version: "1.0.0" },
3325
- { key: "workflow.instance.started", version: "1.0.0" },
3326
- { key: "workflow.step.entered", version: "1.0.0" },
3327
- { key: "workflow.step.exited", version: "1.0.0" },
3328
- { key: "workflow.instance.completed", version: "1.0.0" },
3329
- { key: "workflow.instance.cancelled", version: "1.0.0" },
3330
- { key: "workflow.instance.paused", version: "1.0.0" },
3331
- { key: "workflow.instance.resumed", version: "1.0.0" },
3332
- { key: "workflow.instance.failed", version: "1.0.0" },
3333
- { key: "workflow.instance.timedOut", version: "1.0.0" },
3334
- { key: "workflow.approval.requested", version: "1.0.0" },
3335
- { key: "workflow.approval.decided", version: "1.0.0" },
3336
- { key: "workflow.approval.delegated", version: "1.0.0" },
3337
- { key: "workflow.approval.escalated", version: "1.0.0" }
3338
- ],
3339
- presentations: [
3340
- { key: "workflow.designer", version: "1.0.0" },
3341
- { key: "workflow.definition.viewList", version: "1.0.0" },
3342
- { key: "workflow.definition.detail", version: "1.0.0" },
3343
- { key: "workflow.instance.viewList", version: "1.0.0" },
3344
- { key: "workflow.instance.detail", version: "1.0.0" },
3345
- { key: "workflow.instance.progress", version: "1.0.0" },
3346
- { key: "workflow.approval.inbox", version: "1.0.0" },
3347
- { key: "workflow.approval.detail", version: "1.0.0" },
3348
- { key: "workflow.approval.form", version: "1.0.0" },
3349
- { key: "workflow.approval.badge", version: "1.0.0" },
3350
- { key: "workflow.metrics", version: "1.0.0" }
3351
- ],
3352
- opToPresentation: [
3353
- {
3354
- op: { key: "workflow.definition.list", version: "1.0.0" },
3355
- pres: { key: "workflow.definition.viewList", version: "1.0.0" }
3356
- },
3357
- {
3358
- op: { key: "workflow.instance.list", version: "1.0.0" },
3359
- pres: { key: "workflow.instance.viewList", version: "1.0.0" }
3360
- },
3361
- {
3362
- op: { key: "workflow.approval.list.mine", version: "1.0.0" },
3363
- pres: { key: "workflow.approval.inbox", version: "1.0.0" }
3364
- },
3365
- {
3366
- op: { key: "workflow.approval.decide", version: "1.0.0" },
3367
- pres: { key: "workflow.approval.form", version: "1.0.0" }
3368
- }
3369
- ],
3370
- presentationsTargets: [
3371
- { key: "workflow.designer", version: "1.0.0", targets: ["react"] },
3372
- {
3373
- key: "workflow.definition.viewList",
3374
- version: "1.0.0",
3375
- targets: ["react", "markdown"]
3376
- },
3377
- {
3378
- key: "workflow.definition.detail",
3379
- version: "1.0.0",
3380
- targets: ["react", "markdown"]
3381
- },
3382
- {
3383
- key: "workflow.instance.viewList",
3384
- version: "1.0.0",
3385
- targets: ["react", "markdown"]
3386
- },
3387
- {
3388
- key: "workflow.instance.detail",
3389
- version: "1.0.0",
3390
- targets: ["react", "markdown"]
3391
- },
3392
- { key: "workflow.instance.progress", version: "1.0.0", targets: ["react"] },
3393
- {
3394
- key: "workflow.approval.inbox",
3395
- version: "1.0.0",
3396
- targets: ["react", "markdown"]
3397
- },
3398
- {
3399
- key: "workflow.approval.detail",
3400
- version: "1.0.0",
3401
- targets: ["react", "markdown"]
3402
- },
3403
- {
3404
- key: "workflow.metrics",
3405
- version: "1.0.0",
3406
- targets: ["react", "markdown"]
3407
- }
3408
- ],
3409
- visualizations: WorkflowVisualizationRefs,
3410
- capabilities: {
3411
- requires: [
3412
- { key: "identity", version: "1.0.0" },
3413
- { key: "audit-trail", version: "1.0.0" },
3414
- { key: "notifications", version: "1.0.0" },
3415
- { key: "feature-flags", version: "1.0.0" }
3416
- ],
3417
- provides: [
3418
- { key: "workflow", version: "1.0.0" },
3419
- { key: "approval", version: "1.0.0" },
3420
- { key: "state-machine", version: "1.0.0" }
3421
- ]
3422
- },
3423
- workflows: [
3424
- { key: "workflow-system.workflow.approval-chain", version: "1.0.0" }
3425
- ],
3426
- telemetry: [{ key: "workflow-system.telemetry", version: "1.0.0" }],
3427
- jobs: [
3428
- { key: "workflow-system.job.instance-timeout", version: "1.0.0" },
3429
- { key: "workflow-system.job.escalation", version: "1.0.0" }
3430
- ],
3431
- docs: [
3432
- "docs.examples.workflow-system",
3433
- "docs.examples.workflow-system.goal",
3434
- "docs.examples.workflow-system.usage",
3435
- "docs.examples.workflow-system.constraints"
3436
- ]
3437
- });
3438
- export {
3439
- workflowInstanceDetailMarkdownRenderer,
3440
- workflowDefinitionListMarkdownRenderer,
3441
- workflowDashboardMarkdownRenderer,
3442
- useWorkflowList,
3443
- mockDataStore,
3444
- createWorkflowVisualizationSections,
3445
- createWorkflowHandlers,
3446
- createStateMachineEngine,
3447
- createInitialState,
3448
- buildStateMachineDefinition,
3449
- WorkflowVisualizationSpecs,
3450
- WorkflowVisualizationRegistry,
3451
- WorkflowVisualizationRefs,
3452
- WorkflowUpdatedEvent,
3453
- WorkflowThroughputVisualization,
3454
- WorkflowSystemPresentations,
3455
- WorkflowSystemFeature,
3456
- WorkflowStepModel,
3457
- WorkflowStatusEnum,
3458
- WorkflowPublishedEvent,
3459
- WorkflowMetricsPresentation,
3460
- WorkflowListPresentation,
3461
- WorkflowInstanceStatusVisualization,
3462
- WorkflowInstanceModel,
3463
- WorkflowDetailPresentation,
3464
- WorkflowDesignerPresentation,
3465
- WorkflowDefinitionModel,
3466
- WorkflowDashboard,
3467
- WorkflowCreatedEvent,
3468
- WorkflowCompletedMetricVisualization,
3469
- WorkflowActiveMetricVisualization,
3470
- UpdateWorkflowInputModel,
3471
- UpdateWorkflowContract,
3472
- TriggerTypeEnum,
3473
- TransitionWorkflowContract,
3474
- TransitionResultModel,
3475
- TransitionInputModel,
3476
- SubmitDecisionContract,
3477
- StepTypeEnum,
3478
- StepExitedEvent,
3479
- StepEnteredEvent,
3480
- StepAddedEvent,
3481
- StartWorkflowInputModel,
3482
- StartWorkflowContract,
3483
- ResumeWorkflowContract,
3484
- PublishWorkflowContract,
3485
- ProgressTrackerPresentation,
3486
- PendingApprovalsBadgePresentation,
3487
- PauseWorkflowContract,
3488
- ListWorkflowsContract,
3489
- ListMyApprovalsContract,
3490
- ListInstancesContract,
3491
- InstanceTimedOutEvent,
3492
- InstanceStatusEnum,
3493
- InstanceStartedEvent,
3494
- InstanceResumedEvent,
3495
- InstancePausedEvent,
3496
- InstanceListPresentation,
3497
- InstanceFailedEvent,
3498
- InstanceDetailPresentation,
3499
- InstanceCompletedEvent,
3500
- InstanceCancelledEvent,
3501
- GetWorkflowContract,
3502
- GetInstanceContract,
3503
- GetApprovalContract,
3504
- DelegateApprovalContract,
3505
- CreateWorkflowInputModel,
3506
- CreateWorkflowContract,
3507
- CancelWorkflowContract,
3508
- BasicStateMachineEngine,
3509
- ApprovalStatusEnum,
3510
- ApprovalRequestedEvent,
3511
- ApprovalRequestModel,
3512
- ApprovalModeEnum,
3513
- ApprovalInboxPresentation,
3514
- ApprovalFormPresentation,
3515
- ApprovalEscalatedEvent,
3516
- ApprovalDetailPresentation,
3517
- ApprovalDelegatedEvent,
3518
- ApprovalDecisionEnum,
3519
- ApprovalDecidedEvent,
3520
- ApprovalCommentModel,
3521
- AddStepInputModel,
3522
- AddStepContract,
3523
- AddApprovalCommentContract
3524
- };
1
+ import{defineEnum as r0}from"@contractspec/lib.schema";var y=r0("ApprovalStatus",["PENDING","APPROVED","REJECTED","DELEGATED","ESCALATED","WITHDRAWN","EXPIRED"]),m=r0("ApprovalDecision",["APPROVE","REJECT","REQUEST_CHANGES","DELEGATE","ABSTAIN"]);import{defineEvent as A0}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as g0,ScalarTypeEnum as J}from"@contractspec/lib.schema";var gA=g0({name:"ApprovalRequestedEventPayload",description:"Payload when approval is requested",fields:{requestId:{type:J.String_unsecure(),isOptional:!1},instanceId:{type:J.String_unsecure(),isOptional:!1},workflowKey:{type:J.String_unsecure(),isOptional:!1},approverId:{type:J.String_unsecure(),isOptional:!1},approverRole:{type:J.String_unsecure(),isOptional:!0},title:{type:J.String_unsecure(),isOptional:!1},dueAt:{type:J.DateTime(),isOptional:!0},timestamp:{type:J.DateTime(),isOptional:!1}}}),_A=g0({name:"ApprovalDecidedEventPayload",description:"Payload when approval decision is made",fields:{requestId:{type:J.String_unsecure(),isOptional:!1},instanceId:{type:J.String_unsecure(),isOptional:!1},decision:{type:J.String_unsecure(),isOptional:!1},decidedBy:{type:J.String_unsecure(),isOptional:!1},comment:{type:J.String_unsecure(),isOptional:!0},timestamp:{type:J.DateTime(),isOptional:!1}}}),DA=g0({name:"ApprovalDelegatedEventPayload",description:"Payload when approval is delegated",fields:{requestId:{type:J.String_unsecure(),isOptional:!1},instanceId:{type:J.String_unsecure(),isOptional:!1},fromUserId:{type:J.String_unsecure(),isOptional:!1},toUserId:{type:J.String_unsecure(),isOptional:!1},reason:{type:J.String_unsecure(),isOptional:!0},timestamp:{type:J.DateTime(),isOptional:!1}}}),RA=g0({name:"ApprovalEscalatedEventPayload",description:"Payload when approval is escalated",fields:{requestId:{type:J.String_unsecure(),isOptional:!1},instanceId:{type:J.String_unsecure(),isOptional:!1},escalationLevel:{type:J.Int_unsecure(),isOptional:!1},escalatedTo:{type:J.String_unsecure(),isOptional:!1},reason:{type:J.String_unsecure(),isOptional:!1},timestamp:{type:J.DateTime(),isOptional:!1}}}),LA=A0({meta:{key:"workflow.approval.requested",version:"1.0.0",description:"An approval has been requested.",stability:"stable",owners:["@workflow-team"],tags:["workflow","approval","requested"]},payload:gA}),ZA=A0({meta:{key:"workflow.approval.decided",version:"1.0.0",description:"An approval decision has been made.",stability:"stable",owners:["@workflow-team"],tags:["workflow","approval","decided"]},payload:_A}),OA=A0({meta:{key:"workflow.approval.delegated",version:"1.0.0",description:"An approval has been delegated.",stability:"stable",owners:["@workflow-team"],tags:["workflow","approval","delegated"]},payload:DA}),IA=A0({meta:{key:"workflow.approval.escalated",version:"1.0.0",description:"An approval has been escalated.",stability:"stable",owners:["@workflow-team"],tags:["workflow","approval","escalated"]},payload:RA});var zg={workflows:new Map,steps:new Map,instances:new Map,approvals:new Map,stepExecutions:new Map};class w0{canTransition(A,_,g,R){if(_.status!=="RUNNING"&&_.status!=="WAITING")return{allowed:!1,reason:`Workflow is ${_.status}, cannot transition`};let O=A.steps[_.currentStepKey];if(!O)return{allowed:!1,reason:`Step ${_.currentStepKey} not found`};let P=O.transitions[g];if(!P)return{allowed:!1,reason:`Action ${g} not available in step ${_.currentStepKey}`};if(O.allowedRoles&&O.allowedRoles.length>0){if(!O.allowedRoles.some((D)=>R.userRoles.includes(D)))return{allowed:!1,reason:"User lacks required role for this action"}}if(typeof P==="object"&&P.allowedRoles&&P.allowedRoles.length>0){if(!P.allowedRoles.some((D)=>R.userRoles.includes(D)))return{allowed:!1,reason:`User lacks required role for action ${g}`}}return{allowed:!0}}getAvailableActions(A,_,g){if(_.status!=="RUNNING"&&_.status!=="WAITING")return[];let R=A.steps[_.currentStepKey];if(!R)return[];return Object.keys(R.transitions).filter((O)=>{return this.canTransition(A,_,O,g).allowed})}transition(A,_,g,R){let O=this.canTransition(A,_,g,R);if(!O.allowed)return{success:!1,previousStepKey:_.currentStepKey,currentStepKey:_.currentStepKey,status:_.status,error:O.reason};let P=A.steps[_.currentStepKey];if(!P)return{success:!1,previousStepKey:_.currentStepKey,currentStepKey:_.currentStepKey,status:_.status,error:`Current step ${_.currentStepKey} not found`};let Z=P.transitions[g];if(!Z)return{success:!1,previousStepKey:_.currentStepKey,currentStepKey:_.currentStepKey,status:_.status,error:`Transition for action ${g} not found`};let D=typeof Z==="string"?Z:Z.targetStepKey,H=A.steps[D];if(!H)return{success:!1,previousStepKey:_.currentStepKey,currentStepKey:_.currentStepKey,status:_.status,error:`Target step ${D} not found`};let G="RUNNING";if(H.type==="END")G="COMPLETED";else if(H.type==="APPROVAL"||H.type==="WAIT")G="WAITING";return{success:!0,previousStepKey:_.currentStepKey,currentStepKey:D,status:G}}evaluateCondition(A,_){try{let g=A.match(/^(\w+)\s*(>=|<=|>|<|===|!==|==|!=)\s*(.+)$/);if(g){let[,R,O,P]=g;if(!R||!O||P===void 0)return!1;let Z=_[R],D=JSON.parse(P);switch(O){case">":return Number(Z)>Number(D);case"<":return Number(Z)<Number(D);case">=":return Number(Z)>=Number(D);case"<=":return Number(Z)<=Number(D);case"===":case"==":return Z===D;case"!==":case"!=":return Z!==D}}if(A in _)return Boolean(_[A]);return!1}catch{return!1}}}function Wg(){return new w0}function dg(A,_){let g={};for(let P of _)g[P.key]={key:P.key,name:P.name,type:P.type,transitions:P.transitions,approvalMode:P.approvalMode,allowedRoles:P.approverRoles,timeoutSeconds:P.timeoutSeconds,conditionExpression:P.conditionExpression};let O=_.find((P)=>P.type==="START")?.key??_[0]?.key??"";return{key:A.key,name:A.name,version:A.version,initialStepKey:O,steps:g}}function bg(A,_={}){return{currentStepKey:A.initialStepKey,status:"RUNNING",contextData:_,history:[]}}import{defineSchemaModel as T0,ScalarTypeEnum as k}from"@contractspec/lib.schema";var b=T0({name:"ApprovalRequestModel",description:"An approval request",fields:{id:{type:k.String_unsecure(),isOptional:!1},workflowInstanceId:{type:k.String_unsecure(),isOptional:!1},stepExecutionId:{type:k.String_unsecure(),isOptional:!1},approverId:{type:k.String_unsecure(),isOptional:!1},approverRole:{type:k.String_unsecure(),isOptional:!0},title:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!0},status:{type:y,isOptional:!1},decision:{type:m,isOptional:!0},decisionComment:{type:k.String_unsecure(),isOptional:!0},decidedAt:{type:k.DateTime(),isOptional:!0},dueAt:{type:k.DateTime(),isOptional:!0},contextSnapshot:{type:k.JSON(),isOptional:!0},sequenceOrder:{type:k.Int_unsecure(),isOptional:!1},createdAt:{type:k.DateTime(),isOptional:!1}}}),_0=T0({name:"ApprovalCommentModel",description:"A comment on an approval",fields:{id:{type:k.String_unsecure(),isOptional:!1},approvalRequestId:{type:k.String_unsecure(),isOptional:!1},authorId:{type:k.String_unsecure(),isOptional:!1},content:{type:k.String_unsecure(),isOptional:!1},isInternal:{type:k.Boolean(),isOptional:!1},createdAt:{type:k.DateTime(),isOptional:!1}}});import{defineCommand as K0,defineQuery as E0}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as r,ScalarTypeEnum as $}from"@contractspec/lib.schema";var o=["@example.workflow-system"],PA=K0({meta:{key:"workflow.approval.decide",version:"1.0.0",stability:"stable",owners:[...o],tags:["workflow","approval","decision"],description:"Submit an approval decision (approve/reject).",goal:"Allow approvers to make decisions on requests.",context:"Approval inbox, workflow detail."},io:{input:r({name:"ApproveRejectInput",fields:{requestId:{type:$.String_unsecure(),isOptional:!1},decision:{type:m,isOptional:!1},comment:{type:$.String_unsecure(),isOptional:!0},data:{type:$.JSON(),isOptional:!0}}}),output:b},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.approval.decided",version:"1.0.0",when:"Decision is made",payload:b}],audit:["workflow.approval.decided"]},acceptance:{scenarios:[{key:"approve-request-happy-path",given:["Approval request is pending","User is assignee"],when:["User approves request"],then:["Request is approved","ApprovalDecided event is emitted"]}],examples:[{key:"approve-basic",input:{requestId:"req-123",decision:"approve",comment:"Looks good"},output:{id:"req-123",status:"approved"}}]}}),CA=K0({meta:{key:"workflow.approval.delegate",version:"1.0.0",stability:"stable",owners:[...o],tags:["workflow","approval","delegate"],description:"Delegate an approval request to another user.",goal:"Allow approvers to pass approval to others.",context:"Approval inbox."},io:{input:r({name:"DelegateInput",fields:{requestId:{type:$.String_unsecure(),isOptional:!1},delegateTo:{type:$.String_unsecure(),isOptional:!1},reason:{type:$.String_unsecure(),isOptional:!0}}}),output:b},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.approval.delegated",version:"1.0.0",when:"Approval is delegated",payload:b}],audit:["workflow.approval.delegated"]},acceptance:{scenarios:[{key:"delegate-approval-happy-path",given:["Approval request is pending","User is assignee"],when:["User delegates to another user"],then:["Assignee is updated","ApprovalDelegated event is emitted"]}],examples:[{key:"delegate-to-manager",input:{requestId:"req-123",delegateTo:"user-456",reason:"Out of office"},output:{id:"req-123",assigneeId:"user-456"}}]}}),NA=K0({meta:{key:"workflow.approval.comment.add",version:"1.0.0",stability:"stable",owners:[...o],tags:["workflow","approval","comment"],description:"Add a comment to an approval request.",goal:"Allow discussion on approval requests.",context:"Approval detail view."},io:{input:r({name:"AddCommentInput",fields:{requestId:{type:$.String_unsecure(),isOptional:!1},content:{type:$.NonEmptyString(),isOptional:!1},isInternal:{type:$.Boolean(),isOptional:!0}}}),output:_0},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.approval.comment.added",version:"1.0.0",when:"Comment is added",payload:_0}]},acceptance:{scenarios:[{key:"add-comment-happy-path",given:["Approval request exists"],when:["User adds a comment"],then:["Comment is added","CommentAdded event is emitted"]}],examples:[{key:"add-question",input:{requestId:"req-123",content:"Can you clarify budget?",isInternal:!1},output:{id:"com-789",content:"Can you clarify budget?"}}]}}),GA=E0({meta:{key:"workflow.approval.list.mine",version:"1.0.0",stability:"stable",owners:[...o],tags:["workflow","approval","list","inbox"],description:"List approval requests assigned to current user.",goal:"Show pending approvals in user inbox.",context:"Approval inbox, dashboard widget."},io:{input:r({name:"ListMyApprovalsInput",fields:{status:{type:y,isOptional:!0},limit:{type:$.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:$.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:r({name:"ListMyApprovalsOutput",fields:{requests:{type:b,isArray:!0,isOptional:!1},total:{type:$.Int_unsecure(),isOptional:!1},pendingCount:{type:$.Int_unsecure(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-approvals-happy-path",given:["User has assigned approvals"],when:["User lists approvals"],then:["List of requests is returned"]}],examples:[{key:"list-pending",input:{status:"pending",limit:10},output:{requests:[],total:2,pendingCount:2}}]}}),UA=E0({meta:{key:"workflow.approval.get",version:"1.0.0",stability:"stable",owners:[...o],tags:["workflow","approval","get"],description:"Get an approval request with details.",goal:"View approval request details.",context:"Approval detail view."},io:{input:r({name:"GetApprovalInput",fields:{requestId:{type:$.String_unsecure(),isOptional:!1}}}),output:b},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-approval-happy-path",given:["Approval request exists"],when:["User requests approval details"],then:["Approval details are returned"]}],examples:[{key:"get-basic",input:{requestId:"req-123"},output:{id:"req-123",status:"pending"}}]}});import{web as FA}from"@contractspec/lib.runtime-sandbox";var{generateId:S}=FA;function p0(A){return{id:A.id,projectId:A.projectId,organizationId:A.organizationId,name:A.name,description:A.description??void 0,type:A.type,status:A.status,createdAt:new Date(A.createdAt),updatedAt:new Date(A.updatedAt)}}function y0(A){return{id:A.id,definitionId:A.definitionId,name:A.name,description:A.description??void 0,stepOrder:A.stepOrder,type:A.type,requiredRoles:A.requiredRoles?JSON.parse(A.requiredRoles):[],autoApproveCondition:A.autoApproveCondition??void 0,timeoutHours:A.timeoutHours??void 0,createdAt:new Date(A.createdAt)}}function D0(A){return{id:A.id,projectId:A.projectId,definitionId:A.definitionId,status:A.status,currentStepId:A.currentStepId??void 0,data:A.data?JSON.parse(A.data):void 0,requestedBy:A.requestedBy,startedAt:new Date(A.startedAt),completedAt:A.completedAt?new Date(A.completedAt):void 0}}function JA(A){return{id:A.id,instanceId:A.instanceId,stepId:A.stepId,status:A.status,actorId:A.actorId??void 0,comment:A.comment??void 0,decidedAt:A.decidedAt?new Date(A.decidedAt):void 0,createdAt:new Date(A.createdAt)}}function sg(A){function _(L){let F=0;return L.replace(/\?/g,()=>`$${++F}`)}async function g(L,F=[]){return(await A.query(_(L),F)).rows}async function R(L,F=[]){await A.execute(_(L),F)}async function O(L){let{projectId:F,status:N,search:Y,limit:X=20,offset:q=0}=L,W='WHERE "projectId" = ?',d=[F];if(N&&N!=="all")W+=" AND status = ?",d.push(N);if(Y)W+=" AND name LIKE ?",d.push(`%${Y}%`);let j0=(await g(`SELECT COUNT(*) as count FROM workflow_definition ${W}`,d))[0]?.count??0;return{definitions:(await g(`SELECT * FROM workflow_definition ${W} ORDER BY "updatedAt" DESC LIMIT ? OFFSET ?`,[...d,X,q])).map(p0),total:j0}}async function P(L,F){let N=S("wfdef"),Y=new Date().toISOString();await R(`INSERT INTO workflow_definition (id, "projectId", "organizationId", name, description, type, status, "createdAt", "updatedAt")
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,F.projectId,F.organizationId,L.name,L.description??null,L.type??"APPROVAL","DRAFT",Y,Y]);let X=await g("SELECT * FROM workflow_definition WHERE id = ?",[N]);return p0(X[0])}async function Z(L){let F=S("wfstep"),N=new Date().toISOString(),X=((await g('SELECT MAX("stepOrder") as maxOrder FROM workflow_step WHERE "definitionId" = ?',[L.definitionId]))[0]?.maxOrder??0)+1;await R(`INSERT INTO workflow_step (id, "definitionId", name, description, "stepOrder", type, "requiredRoles", "autoApproveCondition", "timeoutHours", "createdAt")
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[F,L.definitionId,L.name,L.description??null,X,L.type??"APPROVAL",JSON.stringify(L.requiredRoles),L.autoApproveCondition??null,L.timeoutHours??null,N]);let q=await g("SELECT * FROM workflow_step WHERE id = ?",[F]);return y0(q[0])}async function D(L){return(await g('SELECT * FROM workflow_step WHERE "definitionId" = ? ORDER BY "stepOrder"',[L])).map(y0)}async function H(L){let{projectId:F,definitionId:N,status:Y,requestedBy:X,limit:q=20,offset:W=0}=L,d='WHERE "projectId" = ?',f=[F];if(N)d+=' AND "definitionId" = ?',f.push(N);if(Y&&Y!=="all")d+=" AND status = ?",f.push(Y);if(X)d+=' AND "requestedBy" = ?',f.push(X);let f0=(await g(`SELECT COUNT(*) as count FROM workflow_instance ${d}`,f))[0]?.count??0;return{instances:(await g(`SELECT * FROM workflow_instance ${d} ORDER BY "startedAt" DESC LIMIT ? OFFSET ?`,[...f,q,W])).map(D0),total:f0}}async function G(L,F){let N=S("wfinst"),Y=new Date().toISOString(),q=(await g('SELECT * FROM workflow_step WHERE "definitionId" = ? ORDER BY "stepOrder" LIMIT 1',[L.definitionId]))[0]?.id??null;if(await R(`INSERT INTO workflow_instance (id, "projectId", "definitionId", status, "currentStepId", data, "requestedBy", "startedAt")
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[N,F.projectId,L.definitionId,q?"IN_PROGRESS":"PENDING",q,L.data?JSON.stringify(L.data):null,F.requestedBy,Y]),q)await R(`INSERT INTO workflow_approval (id, "instanceId", "stepId", status, "createdAt")
5
+ VALUES (?, ?, ?, ?, ?)`,[S("wfappr"),N,q,"PENDING",Y]);let W=await g("SELECT * FROM workflow_instance WHERE id = ?",[N]);return D0(W[0])}async function n(L,F){let N=new Date().toISOString(),Y=await g("SELECT * FROM workflow_instance WHERE id = ?",[L.instanceId]);if(!Y[0])throw Error("NOT_FOUND");let X=Y[0];await R(`UPDATE workflow_approval SET status = 'APPROVED', "actorId" = ?, comment = ?, "decidedAt" = ?
6
+ WHERE "instanceId" = ? AND "stepId" = ? AND status = 'PENDING'`,[F.actorId,L.comment??null,N,L.instanceId,X.currentStepId]);let q=await g("SELECT * FROM workflow_step WHERE id = ?",[X.currentStepId]),W=await g('SELECT * FROM workflow_step WHERE "definitionId" = ? AND "stepOrder" > ? ORDER BY "stepOrder" LIMIT 1',[X.definitionId,q[0]?.stepOrder??0]);if(W[0])await R('UPDATE workflow_instance SET "currentStepId" = ? WHERE id = ?',[W[0].id,L.instanceId]),await R(`INSERT INTO workflow_approval (id, "instanceId", "stepId", status, "createdAt")
7
+ VALUES (?, ?, ?, ?, ?)`,[S("wfappr"),L.instanceId,W[0].id,"PENDING",N]);else await R(`UPDATE workflow_instance SET status = 'COMPLETED', "currentStepId" = NULL, "completedAt" = ? WHERE id = ?`,[N,L.instanceId]);let d=await g("SELECT * FROM workflow_instance WHERE id = ?",[L.instanceId]);return D0(d[0])}async function Y0(L,F){let N=new Date().toISOString(),Y=await g("SELECT * FROM workflow_instance WHERE id = ?",[L.instanceId]);if(!Y[0])throw Error("NOT_FOUND");await R(`UPDATE workflow_approval SET status = 'REJECTED', "actorId" = ?, comment = ?, "decidedAt" = ?
8
+ WHERE "instanceId" = ? AND "stepId" = ? AND status = 'PENDING'`,[F.actorId,L.reason,N,L.instanceId,Y[0].currentStepId]),await R(`UPDATE workflow_instance SET status = 'REJECTED', "completedAt" = ? WHERE id = ?`,[N,L.instanceId]);let X=await g("SELECT * FROM workflow_instance WHERE id = ?",[L.instanceId]);return D0(X[0])}async function a(L){return(await g('SELECT * FROM workflow_approval WHERE "instanceId" = ? ORDER BY "createdAt"',[L])).map(JA)}return{listDefinitions:O,createDefinition:P,addStep:Z,getSteps:D,listInstances:H,startInstance:G,approveStep:n,rejectStep:Y0,getApprovals:a}}import{defineEnum as VA}from"@contractspec/lib.schema";var t=VA("InstanceStatus",["PENDING","RUNNING","WAITING","PAUSED","COMPLETED","CANCELLED","FAILED","TIMEOUT"]);import{defineEvent as h}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as k0,ScalarTypeEnum as V}from"@contractspec/lib.schema";var w=k0({name:"InstanceEventPayload",description:"Base payload for instance events",fields:{instanceId:{type:V.String_unsecure(),isOptional:!1},workflowId:{type:V.String_unsecure(),isOptional:!1},workflowKey:{type:V.String_unsecure(),isOptional:!1},status:{type:V.String_unsecure(),isOptional:!1},referenceId:{type:V.String_unsecure(),isOptional:!0},referenceType:{type:V.String_unsecure(),isOptional:!0},triggeredBy:{type:V.String_unsecure(),isOptional:!1},organizationId:{type:V.String_unsecure(),isOptional:!1},timestamp:{type:V.DateTime(),isOptional:!1}}}),m0=k0({name:"StepTransitionEventPayload",description:"Payload for step transition events",fields:{instanceId:{type:V.String_unsecure(),isOptional:!1},workflowId:{type:V.String_unsecure(),isOptional:!1},fromStepKey:{type:V.String_unsecure(),isOptional:!0},toStepKey:{type:V.String_unsecure(),isOptional:!1},action:{type:V.String_unsecure(),isOptional:!0},executedBy:{type:V.String_unsecure(),isOptional:!1},timestamp:{type:V.DateTime(),isOptional:!1}}}),HA=k0({name:"InstanceCompletedEventPayload",description:"Payload when instance completes",fields:{instanceId:{type:V.String_unsecure(),isOptional:!1},workflowId:{type:V.String_unsecure(),isOptional:!1},workflowKey:{type:V.String_unsecure(),isOptional:!1},outcome:{type:V.String_unsecure(),isOptional:!1},referenceId:{type:V.String_unsecure(),isOptional:!0},referenceType:{type:V.String_unsecure(),isOptional:!0},duration:{type:V.Int_unsecure(),isOptional:!1},timestamp:{type:V.DateTime(),isOptional:!1}}}),YA=h({meta:{key:"workflow.instance.started",version:"1.0.0",description:"A new workflow instance has been started.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","started"]},payload:w}),KA=h({meta:{key:"workflow.step.entered",version:"1.0.0",description:"A workflow instance has entered a new step.",stability:"stable",owners:["@workflow-team"],tags:["workflow","step","entered"]},payload:m0}),kA=h({meta:{key:"workflow.step.exited",version:"1.0.0",description:"A workflow instance has exited a step.",stability:"stable",owners:["@workflow-team"],tags:["workflow","step","exited"]},payload:m0}),XA=h({meta:{key:"workflow.instance.completed",version:"1.0.0",description:"A workflow instance has completed.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","completed"]},payload:HA}),$A=h({meta:{key:"workflow.instance.cancelled",version:"1.0.0",description:"A workflow instance has been cancelled.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","cancelled"]},payload:w}),QA=h({meta:{key:"workflow.instance.paused",version:"1.0.0",description:"A workflow instance has been paused.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","paused"]},payload:w}),BA=h({meta:{key:"workflow.instance.resumed",version:"1.0.0",description:"A workflow instance has been resumed.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","resumed"]},payload:w}),vA=h({meta:{key:"workflow.instance.failed",version:"1.0.0",description:"A workflow instance has failed.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","failed"]},payload:w}),zA=h({meta:{key:"workflow.instance.timedOut",version:"1.0.0",description:"A workflow instance has timed out.",stability:"stable",owners:["@workflow-team"],tags:["workflow","instance","timeout"]},payload:w});import{defineSchemaModel as R0,ScalarTypeEnum as U}from"@contractspec/lib.schema";var K=R0({name:"WorkflowInstanceModel",description:"A running workflow instance",fields:{id:{type:U.String_unsecure(),isOptional:!1},workflowDefinitionId:{type:U.String_unsecure(),isOptional:!1},referenceId:{type:U.String_unsecure(),isOptional:!0},referenceType:{type:U.String_unsecure(),isOptional:!0},status:{type:t,isOptional:!1},currentStepId:{type:U.String_unsecure(),isOptional:!0},contextData:{type:U.JSON(),isOptional:!0},triggeredBy:{type:U.String_unsecure(),isOptional:!1},organizationId:{type:U.String_unsecure(),isOptional:!1},priority:{type:U.Int_unsecure(),isOptional:!1},dueAt:{type:U.DateTime(),isOptional:!0},outcome:{type:U.String_unsecure(),isOptional:!0},resultData:{type:U.JSON(),isOptional:!0},errorMessage:{type:U.String_unsecure(),isOptional:!0},createdAt:{type:U.DateTime(),isOptional:!1},startedAt:{type:U.DateTime(),isOptional:!0},completedAt:{type:U.DateTime(),isOptional:!0}}}),X0=R0({name:"StartWorkflowInput",description:"Input for starting a workflow",fields:{workflowKey:{type:U.NonEmptyString(),isOptional:!1},contextData:{type:U.JSON(),isOptional:!0},referenceId:{type:U.String_unsecure(),isOptional:!0},referenceType:{type:U.String_unsecure(),isOptional:!0},priority:{type:U.Int_unsecure(),isOptional:!0},dueAt:{type:U.DateTime(),isOptional:!0}}}),$0=R0({name:"TransitionInput",description:"Input for transitioning a workflow",fields:{instanceId:{type:U.String_unsecure(),isOptional:!1},action:{type:U.NonEmptyString(),isOptional:!1},data:{type:U.JSON(),isOptional:!0},comment:{type:U.String_unsecure(),isOptional:!0}}}),Q0=R0({name:"TransitionResult",description:"Result of a workflow transition",fields:{success:{type:U.Boolean(),isOptional:!1},instance:{type:K,isOptional:!1},previousStepKey:{type:U.String_unsecure(),isOptional:!0},currentStepKey:{type:U.String_unsecure(),isOptional:!0},message:{type:U.String_unsecure(),isOptional:!0}}});import{defineCommand as s,defineQuery as o0}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as T,ScalarTypeEnum as Q}from"@contractspec/lib.schema";var j=["@example.workflow-system"],qA=s({meta:{key:"workflow.instance.start",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","start"],description:"Start a new workflow instance.",goal:"Initiate a workflow for a business process.",context:"Order creation, request submission, etc."},io:{input:X0,output:K},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.instance.started",version:"1.0.0",when:"Workflow starts",payload:K},{key:"workflow.step.entered",version:"1.0.0",when:"First step entered",payload:K}],audit:["workflow.instance.started"]},acceptance:{scenarios:[{key:"start-workflow-happy-path",given:["Workflow definition exists"],when:["User starts workflow"],then:["Instance is created and started"]}],examples:[{key:"start-onboarding",input:{workflowKey:"onboarding-v1",context:{employeeId:"emp-123"}},output:{id:"inst-456",status:"running"}}]}}),WA=s({meta:{key:"workflow.instance.transition",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","transition","state-machine"],description:"Transition a workflow instance to the next step.",goal:"Move workflow forward based on action.",context:"Task completion, approval decisions."},io:{input:$0,output:Q0},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.step.exited",version:"1.0.0",when:"Step is exited",payload:K},{key:"workflow.step.entered",version:"1.0.0",when:"New step is entered",payload:K},{key:"workflow.instance.completed",version:"1.0.0",when:"Workflow reaches end",payload:K}],audit:["workflow.instance.transitioned"]},acceptance:{scenarios:[{key:"transition-workflow-happy-path",given:["Workflow instance is waiting at step"],when:["User provides input"],then:["Instance moves to next step"]}],examples:[{key:"complete-task",input:{instanceId:"inst-456",action:"complete",data:{approved:!0}},output:{success:!0,nextStep:"notify-hr"}}]}}),dA=s({meta:{key:"workflow.instance.pause",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","pause"],description:"Pause a running workflow instance.",goal:"Temporarily halt workflow execution.",context:"Administrative action, emergency stop."},io:{input:T({name:"PauseResumeInput",fields:{instanceId:{type:Q.String_unsecure(),isOptional:!1},reason:{type:Q.String_unsecure(),isOptional:!0}}}),output:K},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.instance.paused",version:"1.0.0",when:"Workflow is paused",payload:K}],audit:["workflow.instance.paused"]},acceptance:{scenarios:[{key:"pause-workflow-happy-path",given:["Workflow is running"],when:["Admin pauses workflow"],then:["Instance status becomes PAUSED"]}],examples:[{key:"pause-maintenance",input:{instanceId:"inst-456",reason:"System maintenance"},output:{id:"inst-456",status:"paused"}}]}}),bA=s({meta:{key:"workflow.instance.resume",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","resume"],description:"Resume a paused workflow instance.",goal:"Continue workflow execution.",context:"Administrative action."},io:{input:T({name:"PauseResumeInput",fields:{instanceId:{type:Q.String_unsecure(),isOptional:!1},reason:{type:Q.String_unsecure(),isOptional:!0}}}),output:K},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.instance.resumed",version:"1.0.0",when:"Workflow is resumed",payload:K}],audit:["workflow.instance.resumed"]},acceptance:{scenarios:[{key:"resume-workflow-happy-path",given:["Workflow is paused"],when:["Admin resumes workflow"],then:["Instance status becomes RUNNING"]}],examples:[{key:"resume-normal",input:{instanceId:"inst-456",reason:"Issue resolved"},output:{id:"inst-456",status:"running"}}]}}),xA=s({meta:{key:"workflow.instance.cancel",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","cancel"],description:"Cancel a workflow instance.",goal:"Terminate workflow without completion.",context:"User request, system cancellation."},io:{input:T({name:"CancelWorkflowInput",fields:{instanceId:{type:Q.String_unsecure(),isOptional:!1},reason:{type:Q.String_unsecure(),isOptional:!1}}}),output:K},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.instance.cancelled",version:"1.0.0",when:"Workflow is cancelled",payload:K}],audit:["workflow.instance.cancelled"]},acceptance:{scenarios:[{key:"cancel-workflow-happy-path",given:["Workflow is running"],when:["User cancels workflow"],then:["Instance status becomes CANCELLED"]}],examples:[{key:"cancel-mistake",input:{instanceId:"inst-456",reason:"Created by mistake"},output:{id:"inst-456",status:"cancelled"}}]}}),MA=o0({meta:{key:"workflow.instance.list",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","list"],description:"List workflow instances with filtering.",goal:"Browse and search running workflows.",context:"Dashboard, monitoring."},io:{input:T({name:"ListInstancesInput",fields:{workflowKey:{type:Q.String_unsecure(),isOptional:!0},status:{type:t,isOptional:!0},referenceType:{type:Q.String_unsecure(),isOptional:!0},referenceId:{type:Q.String_unsecure(),isOptional:!0},triggeredBy:{type:Q.String_unsecure(),isOptional:!0},limit:{type:Q.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:Q.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:T({name:"ListInstancesOutput",fields:{instances:{type:K,isArray:!0,isOptional:!1},total:{type:Q.Int_unsecure(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-instances-happy-path",given:["Workflow instances exist"],when:["User lists instances"],then:["List of instances is returned"]}],examples:[{key:"list-running",input:{status:"running",limit:10},output:{instances:[],total:5}}]}}),hA=o0({meta:{key:"workflow.instance.get",version:"1.0.0",stability:"stable",owners:[...j],tags:["workflow","instance","get"],description:"Get a workflow instance with details.",goal:"View workflow instance details.",context:"Instance detail view."},io:{input:T({name:"GetInstanceInput",fields:{instanceId:{type:Q.String_unsecure(),isOptional:!1}}}),output:K},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-instance-happy-path",given:["Instance exists"],when:["User requests instance details"],then:["Instance details are returned"]}],examples:[{key:"get-details",input:{instanceId:"inst-456"},output:{id:"inst-456",workflowKey:"onboarding-v1"}}]}});import{defineEnum as L0}from"@contractspec/lib.schema";var c=L0("WorkflowStatus",["DRAFT","ACTIVE","DEPRECATED","ARCHIVED"]),u=L0("WorkflowTriggerType",["MANUAL","EVENT","SCHEDULED","API"]),Z0=L0("StepType",["START","APPROVAL","TASK","CONDITION","PARALLEL","WAIT","ACTION","END"]),O0=L0("ApprovalMode",["ANY","ALL","MAJORITY","SEQUENTIAL"]);import{defineSchemaModel as i,ScalarTypeEnum as I}from"@contractspec/lib.schema";var l=i({name:"WorkflowStepModel",description:"A step in a workflow definition",fields:{id:{type:I.String_unsecure(),isOptional:!1},key:{type:I.String_unsecure(),isOptional:!1},name:{type:I.String_unsecure(),isOptional:!1},description:{type:I.String_unsecure(),isOptional:!0},type:{type:Z0,isOptional:!1},position:{type:I.Int_unsecure(),isOptional:!1},transitions:{type:I.JSON(),isOptional:!1},approvalMode:{type:O0,isOptional:!0},approverRoles:{type:I.String_unsecure(),isArray:!0,isOptional:!0}}}),B=i({name:"WorkflowDefinitionModel",description:"A workflow definition",fields:{id:{type:I.String_unsecure(),isOptional:!1},name:{type:I.String_unsecure(),isOptional:!1},key:{type:I.String_unsecure(),isOptional:!1},description:{type:I.String_unsecure(),isOptional:!0},version:{type:I.String_unsecure(),isOptional:!1},status:{type:c,isOptional:!1},triggerType:{type:u,isOptional:!1},initialStepId:{type:I.String_unsecure(),isOptional:!0},featureFlagKey:{type:I.String_unsecure(),isOptional:!0},organizationId:{type:I.String_unsecure(),isOptional:!1},createdAt:{type:I.DateTime(),isOptional:!1},updatedAt:{type:I.DateTime(),isOptional:!1},steps:{type:l,isArray:!0,isOptional:!0}}}),B0=i({name:"CreateWorkflowInput",description:"Input for creating a workflow definition",fields:{name:{type:I.NonEmptyString(),isOptional:!1},key:{type:I.NonEmptyString(),isOptional:!1},description:{type:I.String_unsecure(),isOptional:!0},triggerType:{type:u,isOptional:!0},triggerConfig:{type:I.JSON(),isOptional:!0},featureFlagKey:{type:I.String_unsecure(),isOptional:!0},settings:{type:I.JSON(),isOptional:!0}}}),v0=i({name:"UpdateWorkflowInput",description:"Input for updating a workflow definition",fields:{workflowId:{type:I.String_unsecure(),isOptional:!1},name:{type:I.String_unsecure(),isOptional:!0},description:{type:I.String_unsecure(),isOptional:!0},triggerType:{type:u,isOptional:!0},triggerConfig:{type:I.JSON(),isOptional:!0},featureFlagKey:{type:I.String_unsecure(),isOptional:!0},settings:{type:I.JSON(),isOptional:!0}}}),z0=i({name:"AddStepInput",description:"Input for adding a step to a workflow",fields:{workflowId:{type:I.String_unsecure(),isOptional:!1},key:{type:I.NonEmptyString(),isOptional:!1},name:{type:I.NonEmptyString(),isOptional:!1},description:{type:I.String_unsecure(),isOptional:!0},type:{type:Z0,isOptional:!1},position:{type:I.Int_unsecure(),isOptional:!0},transitions:{type:I.JSON(),isOptional:!1},approvalMode:{type:O0,isOptional:!0},approverRoles:{type:I.String_unsecure(),isArray:!0,isOptional:!0},approverUserIds:{type:I.String_unsecure(),isArray:!0,isOptional:!0},timeoutSeconds:{type:I.Int_unsecure(),isOptional:!0},slaSeconds:{type:I.Int_unsecure(),isOptional:!0}}});import{definePresentation as x,StabilityEnum as M}from"@contractspec/lib.contracts-spec";var jA=x({meta:{key:"workflow.designer",version:"1.0.0",title:"Workflow Designer",description:"Visual workflow designer with drag-and-drop steps",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","designer","admin"],stability:M.Experimental,goal:"Building and modifying workflow definitions",context:"Workflow administration and setup"},source:{type:"component",framework:"react",componentKey:"WorkflowDesigner",props:B},targets:["react"],policy:{flags:["workflow.designer.enabled"]}}),fA=x({meta:{key:"workflow.definition.viewList",version:"1.0.0",title:"Workflow List",description:"List of workflow definitions with status and actions",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","list","admin"],stability:M.Experimental,goal:"Overview of all defined workflows",context:"Workflow management dashboard"},source:{type:"component",framework:"react",componentKey:"WorkflowDefinitionList",props:B},targets:["react","markdown"],policy:{flags:["workflow.enabled"]}}),rA=x({meta:{key:"workflow.definition.detail",version:"1.0.0",title:"Workflow Details",description:"Detailed view of a workflow definition with steps",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","detail"],stability:M.Experimental,goal:"Viewing technical details of a workflow definition",context:"Workflow inspection and debugging"},source:{type:"component",framework:"react",componentKey:"WorkflowDefinitionDetail",props:B},targets:["react","markdown"],policy:{flags:["workflow.enabled"]}}),wA=x({meta:{key:"workflow.instance.viewList",version:"1.0.0",title:"Instance List",description:"List of workflow instances with status and progress",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","instance","list"],stability:M.Experimental,goal:"Monitoring active and past workflow executions",context:"Operations monitoring"},source:{type:"component",framework:"react",componentKey:"WorkflowInstanceList",props:K},targets:["react","markdown"],policy:{flags:["workflow.enabled"]}}),TA=x({meta:{key:"workflow.instance.detail",version:"1.0.0",title:"Instance Details",description:"Detailed view of a workflow instance with step timeline",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","instance","detail","timeline"],stability:M.Experimental,goal:"Detailed inspection of a specific workflow instance",context:"Case management and troubleshooting"},source:{type:"component",framework:"react",componentKey:"WorkflowInstanceDetail",props:K},targets:["react","markdown"],policy:{flags:["workflow.enabled"]}}),EA=x({meta:{key:"workflow.instance.progress",version:"1.0.0",title:"Progress Tracker",description:"Visual progress tracker showing current step in workflow",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","progress","widget"],stability:M.Experimental,goal:"Quick view of current progress for a workflow",context:"Embedded progress indicator in entity views"},source:{type:"component",framework:"react",componentKey:"WorkflowProgressTracker",props:K},targets:["react"],policy:{flags:["workflow.enabled"]}}),pA=x({meta:{key:"workflow.approval.inbox",version:"1.0.0",title:"Approval Inbox",description:"Inbox showing pending approval requests for current user",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","approval","inbox"],stability:M.Experimental,goal:"Managing personal workload of approval requests",context:"Personal task management"},source:{type:"component",framework:"react",componentKey:"ApprovalInbox",props:b},targets:["react","markdown"],policy:{flags:["workflow.approvals.enabled"]}}),yA=x({meta:{key:"workflow.approval.detail",version:"1.0.0",title:"Approval Details",description:"Detailed approval request view with context and actions",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","approval","detail"],stability:M.Experimental,goal:"Decision support for an approval request",context:"Specific approval action"},source:{type:"component",framework:"react",componentKey:"ApprovalRequestDetail",props:b},targets:["react","markdown"],policy:{flags:["workflow.approvals.enabled"]}}),mA=x({meta:{key:"workflow.approval.form",version:"1.0.0",title:"Approval Form",description:"Form for submitting approval decisions",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","approval","form"],stability:M.Experimental,goal:"Submitting a decision on an approval request",context:"Approval decision dialog"},source:{type:"component",framework:"react",componentKey:"ApprovalDecisionForm"},targets:["react"],policy:{flags:["workflow.approvals.enabled"]}}),oA=x({meta:{key:"workflow.approval.badge",version:"1.0.0",title:"Pending Approvals Badge",description:"Badge showing count of pending approvals",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","approval","badge","widget"],stability:M.Experimental,goal:"Visual notification of pending approvals",context:"Global navigation or sidebar"},source:{type:"component",framework:"react",componentKey:"PendingApprovalsBadge"},targets:["react"],policy:{flags:["workflow.approvals.enabled"]}}),SA=x({meta:{key:"workflow.metrics",version:"1.0.0",title:"Workflow Metrics",description:"Dashboard widget showing workflow metrics and statistics",domain:"workflow-system",owners:["@workflow-team"],tags:["workflow","metrics","dashboard"],stability:M.Experimental,goal:"Monitoring throughput and bottlenecks",context:"System performance dashboard"},source:{type:"component",framework:"react",componentKey:"WorkflowMetricsDashboard"},targets:["react","markdown"],policy:{flags:["workflow.metrics.enabled"]}}),X2={WorkflowDesignerPresentation:jA,WorkflowListPresentation:fA,WorkflowDetailPresentation:rA,InstanceListPresentation:wA,InstanceDetailPresentation:TA,ProgressTrackerPresentation:EA,ApprovalInboxPresentation:pA,ApprovalDetailPresentation:yA,ApprovalFormPresentation:mA,PendingApprovalsBadgePresentation:oA,WorkflowMetricsPresentation:SA};import{useTemplateRuntime as tA}from"@contractspec/lib.example-shared-ui";import{useCallback as sA,useEffect as cA,useState as I0}from"react";function q0(A){let{handlers:_,projectId:g}=tA(),R=A??g,O=_.workflow,[P,Z]=I0([]),[D,H]=I0([]),[G,n]=I0(!0),[Y0,a]=I0(null),L=sA(async()=>{try{n(!0),a(null);let[N,Y]=await Promise.all([O.listDefinitions({projectId:R,limit:100}),O.listInstances({projectId:R,limit:100})]);Z(N.definitions),H(Y.instances)}catch(N){a(N instanceof Error?N:Error("Failed to load workflows"))}finally{n(!1)}},[R,O]);cA(()=>{L()},[L]);let F={totalDefinitions:P.length,activeDefinitions:P.filter((N)=>N.status==="ACTIVE").length,totalInstances:D.length,pendingInstances:D.filter((N)=>N.status==="PENDING").length,inProgressInstances:D.filter((N)=>N.status==="IN_PROGRESS").length,completedInstances:D.filter((N)=>N.status==="COMPLETED").length,rejectedInstances:D.filter((N)=>N.status==="REJECTED").length};return{definitions:P,instances:D,loading:G,error:Y0,stats:F,refetch:L}}var x2="workflow-system-demo",M2="org_demo",S0=[{id:"wf_expense",name:"Expense Approval",description:"Approve non-trivial spend before finance releases budget.",type:"APPROVAL",status:"ACTIVE",createdAt:"2026-03-10T09:00:00.000Z",updatedAt:"2026-03-20T08:15:00.000Z",steps:[{id:"wfstep_expense_manager",name:"Manager Review",description:"Validate business value and team budget.",stepOrder:1,type:"APPROVAL",requiredRoles:["manager"],createdAt:"2026-03-10T09:00:00.000Z"},{id:"wfstep_expense_finance",name:"Finance Review",description:"Confirm ledger coding and spending threshold.",stepOrder:2,type:"APPROVAL",requiredRoles:["finance"],createdAt:"2026-03-10T09:10:00.000Z"}]},{id:"wf_vendor",name:"Vendor Onboarding",description:"Sequence security, procurement, and legal before activation.",type:"SEQUENTIAL",status:"ACTIVE",createdAt:"2026-03-08T11:00:00.000Z",updatedAt:"2026-03-19T13:10:00.000Z",steps:[{id:"wfstep_vendor_security",name:"Security Check",description:"Review data access and integration scope.",stepOrder:1,type:"APPROVAL",requiredRoles:["security"],createdAt:"2026-03-08T11:00:00.000Z"},{id:"wfstep_vendor_procurement",name:"Procurement Check",description:"Validate pricing, procurement policy, and owner.",stepOrder:2,type:"APPROVAL",requiredRoles:["procurement"],createdAt:"2026-03-08T11:05:00.000Z"},{id:"wfstep_vendor_legal",name:"Legal Sign-off",description:"Approve terms before the vendor goes live.",stepOrder:3,type:"APPROVAL",requiredRoles:["legal"],createdAt:"2026-03-08T11:10:00.000Z"}]},{id:"wf_policy_exception",name:"Policy Exception",description:"Escalate a temporary exception through team lead and compliance.",type:"APPROVAL",status:"DRAFT",createdAt:"2026-03-15T07:30:00.000Z",updatedAt:"2026-03-18T11:20:00.000Z",steps:[{id:"wfstep_policy_lead",name:"Team Lead Review",description:"Check urgency and expected blast radius.",stepOrder:1,type:"APPROVAL",requiredRoles:["team-lead"],createdAt:"2026-03-15T07:30:00.000Z"},{id:"wfstep_policy_compliance",name:"Compliance Review",description:"Accept or reject the exception request.",stepOrder:2,type:"APPROVAL",requiredRoles:["compliance"],createdAt:"2026-03-15T07:40:00.000Z"}]}],t0=[{id:"wfinst_expense_open",definitionId:"wf_expense",status:"IN_PROGRESS",currentStepId:"wfstep_expense_finance",data:{amount:4200,currency:"EUR",vendor:"Nimbus AI"},requestedBy:"sarah@contractspec.io",startedAt:"2026-03-20T08:00:00.000Z",approvals:[{id:"wfappr_expense_manager",stepId:"wfstep_expense_manager",status:"APPROVED",actorId:"manager.demo",comment:"Approved for the Q2 automation budget.",decidedAt:"2026-03-20T08:15:00.000Z",createdAt:"2026-03-20T08:05:00.000Z"},{id:"wfappr_expense_finance",stepId:"wfstep_expense_finance",status:"PENDING",createdAt:"2026-03-20T08:15:00.000Z"}]},{id:"wfinst_vendor_done",definitionId:"wf_vendor",status:"COMPLETED",data:{vendor:"Acme Cloud",riskTier:"medium"},requestedBy:"leo@contractspec.io",startedAt:"2026-03-19T09:30:00.000Z",completedAt:"2026-03-19T13:10:00.000Z",approvals:[{id:"wfappr_vendor_security",stepId:"wfstep_vendor_security",status:"APPROVED",actorId:"security.demo",comment:"SOC2 scope is acceptable.",decidedAt:"2026-03-19T10:10:00.000Z",createdAt:"2026-03-19T09:35:00.000Z"},{id:"wfappr_vendor_procurement",stepId:"wfstep_vendor_procurement",status:"APPROVED",actorId:"procurement.demo",comment:"Commercial terms match the preferred vendor tier.",decidedAt:"2026-03-19T11:25:00.000Z",createdAt:"2026-03-19T10:15:00.000Z"},{id:"wfappr_vendor_legal",stepId:"wfstep_vendor_legal",status:"APPROVED",actorId:"legal.demo",comment:"MSA redlines are complete.",decidedAt:"2026-03-19T13:05:00.000Z",createdAt:"2026-03-19T11:30:00.000Z"}]},{id:"wfinst_policy_rejected",definitionId:"wf_policy_exception",status:"REJECTED",currentStepId:"wfstep_policy_compliance",data:{policy:"Model rollout freeze",durationDays:14},requestedBy:"maya@contractspec.io",startedAt:"2026-03-18T10:00:00.000Z",completedAt:"2026-03-18T11:20:00.000Z",approvals:[{id:"wfappr_policy_lead",stepId:"wfstep_policy_lead",status:"APPROVED",actorId:"lead.demo",comment:"Escalation justified for the release train.",decidedAt:"2026-03-18T10:30:00.000Z",createdAt:"2026-03-18T10:05:00.000Z"},{id:"wfappr_policy_compliance",stepId:"wfstep_policy_compliance",status:"REJECTED",actorId:"compliance.demo",comment:"Exception exceeds the allowed blast radius.",decidedAt:"2026-03-18T11:15:00.000Z",createdAt:"2026-03-18T10:35:00.000Z"}]}];import{defineVisualization as P0,VisualizationRegistry as uA}from"@contractspec/lib.contracts-spec/visualizations";var C0={key:"workflow.instance.list",version:"1.0.0"},N0={version:"1.0.0",domain:"workflow",stability:"experimental",owners:["@example.workflow-system"],tags:["workflow","visualization","operations"]},W0=P0({meta:{...N0,key:"workflow-system.visualization.instance-status",title:"Instance Status Breakdown",description:"Distribution of workflow instance states.",goal:"Surface the current workload mix.",context:"Workflow operations overview."},source:{primary:C0,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"instances",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"instances",label:"Instances",dataPath:"instances",format:"number"}],table:{caption:"Workflow instance counts by status."}}}),d0=P0({meta:{...N0,key:"workflow-system.visualization.throughput",title:"Run Throughput",description:"Daily workflow instance starts.",goal:"Show operational throughput over time.",context:"Workflow trend monitoring."},source:{primary:C0,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["instances"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"instances",label:"Instances",dataPath:"instances",format:"number",color:"#0f766e"}],table:{caption:"Daily workflow instance starts."}}}),b0=P0({meta:{...N0,key:"workflow-system.visualization.active-work",title:"Active Work",description:"Current in-flight or pending workflow instances.",goal:"Expose active operational workload.",context:"Workflow workload comparison."},source:{primary:C0,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Instances",dataPath:"value",format:"number"}],table:{caption:"Active workflow count."}}}),x0=P0({meta:{...N0,key:"workflow-system.visualization.completed-work",title:"Completed Work",description:"Completed workflow instances in the current sample.",goal:"Show output against active workload.",context:"Workflow workload comparison."},source:{primary:C0,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Instances",dataPath:"value",format:"number"}],table:{caption:"Completed workflow count."}}}),s0=[W0,d0,b0,x0],f2=new uA([...s0]),c0=s0.map((A)=>({key:A.meta.key,version:A.meta.version}));function iA(A){return(A instanceof Date?A:new Date(A)).toISOString().slice(0,10)}function G0(A){let _=new Map,g=new Map,R=0,O=0;for(let D of A){_.set(D.status,(_.get(D.status)??0)+1);let H=iA(D.startedAt);if(g.set(H,(g.get(H)??0)+1),D.status==="PENDING"||D.status==="IN_PROGRESS")R+=1;if(D.status==="COMPLETED")O+=1}return{primaryItems:[{key:"workflow-status",spec:W0,data:{data:Array.from(_.entries()).map(([D,H])=>({status:D,instances:H}))},title:"Instance Status Breakdown",description:"Status mix across workflow instances.",height:260},{key:"workflow-throughput",spec:d0,data:{data:Array.from(g.entries()).sort(([D],[H])=>D.localeCompare(H)).map(([D,H])=>({day:D,instances:H}))},title:"Run Throughput",description:"Daily workflow starts from current instances."}],comparisonItems:[{key:"workflow-active",spec:b0,data:{data:[{value:R}]},title:"Active Work",description:"Pending and in-progress workflows.",height:200},{key:"workflow-completed",spec:x0,data:{data:[{value:O}]},title:"Completed Work",description:"Completed workflows in the current sample.",height:200}]}}var U0=S0,M0=t0,lA=new Map(U0.map((A)=>[A.id,A]));function u0(A){return new Date(A).toISOString().slice(0,10)}var eA={target:"markdown",render:async(A)=>{if(A.source.type!=="component"||A.source.componentKey!=="WorkflowDashboard")throw Error("workflowDashboardMarkdownRenderer: not WorkflowDashboard");let _=U0,g=M0,R=G0(g),O=_.filter((D)=>D.status==="ACTIVE"),P=g.filter((D)=>D.status==="PENDING"||D.status==="IN_PROGRESS"),Z=["# Workflow Dashboard","","> Seeded workflow and approval overview for the sandbox demo.","","## Summary","","| Metric | Value |","|--------|-------|",`| Active Workflows | ${O.length} |`,`| Awaiting Action | ${P.length} |`,`| Completed | ${g.filter((D)=>D.status==="COMPLETED").length} |`,`| Rejected | ${g.filter((D)=>D.status==="REJECTED").length} |`,""];Z.push("## Visualization Overview"),Z.push("");for(let D of[...R.primaryItems,...R.comparisonItems])Z.push(`- **${D.title}** via \`${D.spec.meta.key}\``);if(Z.push(""),Z.push("## Active Workflow Definitions"),Z.push(""),O.length===0)Z.push("_No active workflow definitions._");else{Z.push("| Name | Type | Steps | Status |"),Z.push("|------|------|-------|--------|");for(let D of O)Z.push(`| ${D.name} | ${D.type} | ${D.steps.length} | ${D.status} |`)}if(Z.push(""),Z.push("## Recent Instances"),Z.push(""),g.length===0)Z.push("_No workflow instances._");else{Z.push("| Workflow | Requested By | Status | Started |"),Z.push("|----------|--------------|--------|---------|");for(let D of g.slice(0,10)){let H=u0(D.startedAt),G=lA.get(D.definitionId)?.name??D.definitionId;Z.push(`| ${G} | ${D.requestedBy} | ${D.status} | ${H} |`)}}return{mimeType:"text/markdown",body:Z.join(`
9
+ `)}}},nA={target:"markdown",render:async(A)=>{if(A.source.type!=="component"||A.source.componentKey!=="WorkflowDefinitionList")throw Error("workflowDefinitionListMarkdownRenderer: not WorkflowDefinitionList");let _=U0,g=["# Workflow Definitions","","> Configure automated approval and process workflows",""];for(let R of _){g.push(`## ${R.name}`),g.push(""),g.push(`**Type:** ${R.type} | **Status:** ${R.status}`),g.push(""),g.push("### Steps"),g.push("");for(let O of R.steps)g.push(`${O.stepOrder}. **${O.name}** - Roles: ${O.requiredRoles.join(", ")}`);g.push("")}return{mimeType:"text/markdown",body:g.join(`
10
+ `)}}},aA={target:"markdown",render:async(A)=>{if(A.source.type!=="component"||A.source.componentKey!=="WorkflowInstanceDetail")throw Error("workflowInstanceDetailMarkdownRenderer: not WorkflowInstanceDetail");let _=M0.find((O)=>O.status==="IN_PROGRESS")??M0[0];if(!_)return{mimeType:"text/markdown",body:`# No Workflow Instances
11
+
12
+ No workflow instances available.`};let g=U0.find((O)=>O.id===_.definitionId),R=[`# Workflow: ${g?.name??_.definitionId}`,"",`**Instance ID:** ${_.id}`,`**Status:** ${_.status}`,`**Requested By:** ${_.requestedBy}`,`**Started:** ${u0(_.startedAt)}`,"","## Steps Progress",""];if(g)for(let O of g.steps){let P=O.id===_.currentStepId,Z=g.steps.indexOf(O)<g.steps.findIndex((H)=>H.id===_.currentStepId),D="⬜ Pending";if(Z)D="✅ Completed";if(P)D="\uD83D\uDD04 In Progress";R.push(`- ${D} **${O.name}**`)}return R.push(""),R.push("## Actions"),R.push(""),R.push("- **Approve** - Move to next step"),R.push("- **Reject** - End the workflow with a rejection outcome"),R.push("- **Delegate** - Assign to another approver"),{mimeType:"text/markdown",body:R.join(`
13
+ `)}}};import{ComparisonView as Ag,VisualizationCard as gg,VisualizationGrid as _g}from"@contractspec/lib.design-system";import{jsx as e,jsxs as i0}from"react/jsx-runtime";function l0({instances:A}){let{primaryItems:_,comparisonItems:g}=G0(A);return i0("section",{className:"space-y-4",children:[i0("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Workflow Visualizations"}),e("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts for workflow health and throughput."})]}),e(_g,{children:_.map((R)=>e(gg,{data:R.data,description:R.description,height:R.height,spec:R.spec,title:R.title},R.key))}),e(Ag,{description:"Shared comparison surface for active versus completed work.",items:g,title:"Workload Comparison"})]})}import{Button as e0,ErrorState as Dg,LoaderBlock as Rg,StatCard as F0,StatCardGroup as Lg}from"@contractspec/lib.design-system";import{useState as Zg}from"react";import{jsx as C,jsxs as v}from"react/jsx-runtime";var n0={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",ARCHIVED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",PENDING:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",IN_PROGRESS:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",COMPLETED:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",REJECTED:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",CANCELLED:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"};function Og(){let[A,_]=Zg("definitions"),{definitions:g,instances:R,loading:O,error:P,stats:Z,refetch:D}=q0(),H=[{id:"definitions",label:"Definitions",icon:"\uD83D\uDCCB"},{id:"instances",label:"Instances",icon:"\uD83D\uDD04"}];if(O)return C(Rg,{label:"Loading Workflows..."});if(P)return C(Dg,{title:"Failed to load Workflows",description:P.message,onRetry:D,retryLabel:"Retry"});return v("div",{className:"space-y-6",children:[v("div",{className:"flex items-center justify-between",children:[C("h2",{className:"font-bold text-2xl",children:"Workflow System"}),C(e0,{onClick:()=>void D(),children:"Refresh"})]}),v(Lg,{children:[C(F0,{label:"Workflows",value:Z.totalDefinitions,hint:`${Z.activeDefinitions} active`}),C(F0,{label:"Instances",value:Z.totalInstances,hint:"total runs"}),C(F0,{label:"Awaiting Action",value:Z.pendingInstances+Z.inProgressInstances,hint:"open approvals"}),C(F0,{label:"Completed",value:Z.completedInstances,hint:"finished"})]}),C(l0,{instances:R}),C("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:H.map((G)=>v(e0,{type:"button",role:"tab","aria-selected":A===G.id,onClick:()=>_(G.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${A===G.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[C("span",{children:G.icon}),G.label]},G.id))}),v("div",{className:"min-h-[400px]",role:"tabpanel",children:[A==="definitions"&&C("div",{className:"rounded-lg border border-border",children:v("table",{className:"w-full",children:[C("thead",{className:"border-border border-b bg-muted/30",children:v("tr",{children:[C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Name"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Type"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Status"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Created"})]})}),v("tbody",{className:"divide-y divide-border",children:[g.map((G)=>v("tr",{className:"hover:bg-muted/50",children:[v("td",{className:"px-4 py-3",children:[C("div",{className:"font-medium",children:G.name}),C("div",{className:"text-muted-foreground text-sm",children:G.description})]}),C("td",{className:"px-4 py-3 font-mono text-sm",children:G.type}),C("td",{className:"px-4 py-3",children:C("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${n0[G.status]??""}`,children:G.status})}),C("td",{className:"px-4 py-3 text-muted-foreground text-sm",children:G.createdAt.toLocaleDateString()})]},G.id)),g.length===0&&C("tr",{children:C("td",{colSpan:4,className:"px-4 py-8 text-center text-muted-foreground",children:"No workflow definitions found"})})]})]})}),A==="instances"&&C("div",{className:"rounded-lg border border-border",children:v("table",{className:"w-full",children:[C("thead",{className:"border-border border-b bg-muted/30",children:v("tr",{children:[C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Instance ID"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Status"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Requested By"}),C("th",{className:"px-4 py-3 text-left font-medium text-sm",children:"Started"})]})}),v("tbody",{className:"divide-y divide-border",children:[R.map((G)=>v("tr",{className:"hover:bg-muted/50",children:[C("td",{className:"px-4 py-3 font-mono text-sm",children:G.id}),C("td",{className:"px-4 py-3",children:C("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${n0[G.status]??""}`,children:G.status})}),C("td",{className:"px-4 py-3 text-sm",children:G.requestedBy}),C("td",{className:"px-4 py-3 text-muted-foreground text-sm",children:G.startedAt.toLocaleDateString()})]},G.id)),R.length===0&&C("tr",{children:C("td",{colSpan:4,className:"px-4 py-8 text-center text-muted-foreground",children:"No workflow instances found"})})]})]})})]})]})}import{defineEvent as J0}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as a0,ScalarTypeEnum as z}from"@contractspec/lib.schema";var h0=a0({name:"WorkflowDefinitionEventPayload",description:"Payload for workflow definition events",fields:{workflowId:{type:z.String_unsecure(),isOptional:!1},key:{type:z.String_unsecure(),isOptional:!1},name:{type:z.String_unsecure(),isOptional:!1},version:{type:z.String_unsecure(),isOptional:!1},organizationId:{type:z.String_unsecure(),isOptional:!1},createdBy:{type:z.String_unsecure(),isOptional:!1},timestamp:{type:z.DateTime(),isOptional:!1}}}),Ig=a0({name:"StepAddedEventPayload",description:"Payload when a step is added",fields:{stepId:{type:z.String_unsecure(),isOptional:!1},workflowId:{type:z.String_unsecure(),isOptional:!1},stepKey:{type:z.String_unsecure(),isOptional:!1},stepType:{type:z.String_unsecure(),isOptional:!1},position:{type:z.Int_unsecure(),isOptional:!1},timestamp:{type:z.DateTime(),isOptional:!1}}}),Pg=J0({meta:{key:"workflow.definition.created",version:"1.0.0",description:"A new workflow definition has been created.",stability:"stable",owners:["@workflow-team"],tags:["workflow","definition","created"]},payload:h0}),Cg=J0({meta:{key:"workflow.definition.updated",version:"1.0.0",description:"A workflow definition has been updated.",stability:"stable",owners:["@workflow-team"],tags:["workflow","definition","updated"]},payload:h0}),Ng=J0({meta:{key:"workflow.definition.published",version:"1.0.0",description:"A workflow definition has been published and is now active.",stability:"stable",owners:["@workflow-team"],tags:["workflow","definition","published"]},payload:h0}),Gg=J0({meta:{key:"workflow.step.added",version:"1.0.0",description:"A step has been added to a workflow definition.",stability:"stable",owners:["@workflow-team"],tags:["workflow","step","added"]},payload:Ig});import{defineCommand as H0,defineQuery as AA}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as V0,ScalarTypeEnum as E}from"@contractspec/lib.schema";var p=["@example.workflow-system"],Ug=H0({meta:{key:"workflow.definition.create",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","definition","create"],description:"Create a new workflow definition.",goal:"Allow users to define new workflow blueprints.",context:"Workflow designer, admin panel."},io:{input:B0,output:B},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.definition.created",version:"1.0.0",when:"Workflow is created",payload:B}],audit:["workflow.definition.created"]},acceptance:{scenarios:[{key:"create-workflow-happy-path",given:["User is admin"],when:["User creates new workflow definition"],then:["Definition is created","WorkflowDefinitionCreated event is emitted"]}],examples:[{key:"create-onboarding",input:{key:"onboarding-v1",name:"Employee Onboarding",version:"1.0.0"},output:{id:"def-123",status:"draft"}}]}}),Fg=H0({meta:{key:"workflow.definition.update",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","definition","update"],description:"Update an existing workflow definition.",goal:"Allow users to modify workflow blueprints.",context:"Workflow designer."},io:{input:v0,output:B},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.definition.updated",version:"1.0.0",when:"Workflow is updated",payload:B}],audit:["workflow.definition.updated"]},acceptance:{scenarios:[{key:"update-workflow-happy-path",given:["Workflow definition exists"],when:["User updates definition"],then:["Definition is updated","WorkflowDefinitionUpdated event is emitted"]}],examples:[{key:"update-name",input:{workflowId:"def-123",name:"New Employee Onboarding"},output:{id:"def-123",name:"New Employee Onboarding"}}]}}),Jg=H0({meta:{key:"workflow.step.add",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","step","add"],description:"Add a step to a workflow definition.",goal:"Build workflow structure step by step.",context:"Workflow designer."},io:{input:z0,output:l},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.step.added",version:"1.0.0",when:"Step is added",payload:l}],audit:["workflow.step.added"]},acceptance:{scenarios:[{key:"add-step-happy-path",given:["Workflow definition exists"],when:["User adds a step"],then:["Step is added","StepAdded event is emitted"]}],examples:[{key:"add-approval-step",input:{workflowId:"def-123",stepKey:"approve-contract",type:"approval"},output:{id:"step-456",key:"approve-contract"}}]}}),Vg=H0({meta:{key:"workflow.definition.publish",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","definition","publish"],description:"Publish a workflow definition to make it available for use.",goal:"Activate workflow for production use.",context:"Workflow designer, deployment."},io:{input:V0({name:"PublishWorkflowInput",fields:{workflowId:{type:E.String_unsecure(),isOptional:!1}}}),output:B},policy:{auth:"user"},sideEffects:{emits:[{key:"workflow.definition.published",version:"1.0.0",when:"Workflow is published",payload:B}],audit:["workflow.definition.published"]},acceptance:{scenarios:[{key:"publish-workflow-happy-path",given:["Workflow definition is valid"],when:["User publishes workflow"],then:["Workflow becomes active","WorkflowPublished event is emitted"]}],examples:[{key:"publish-onboarding",input:{workflowId:"def-123"},output:{id:"def-123",status:"published"}}]}}),Hg=AA({meta:{key:"workflow.definition.list",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","definition","list"],description:"List workflow definitions with filtering.",goal:"Browse and search available workflows.",context:"Workflow list, search."},io:{input:V0({name:"ListWorkflowsInput",fields:{status:{type:c,isOptional:!0},search:{type:E.String_unsecure(),isOptional:!0},limit:{type:E.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:E.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:V0({name:"ListWorkflowsOutput",fields:{workflows:{type:B,isArray:!0,isOptional:!1},total:{type:E.Int_unsecure(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-workflows-happy-path",given:["Workflow definitions exist"],when:["User lists workflows"],then:["List of workflows is returned"]}],examples:[{key:"list-all",input:{limit:10},output:{workflows:[],total:5}}]}}),Yg=AA({meta:{key:"workflow.definition.get",version:"1.0.0",stability:"stable",owners:[...p],tags:["workflow","definition","get"],description:"Get a workflow definition with all steps.",goal:"View workflow details.",context:"Workflow designer, detail view."},io:{input:V0({name:"GetWorkflowInput",fields:{workflowId:{type:E.String_unsecure(),isOptional:!1}}}),output:B},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-workflow-happy-path",given:["Workflow definition exists"],when:["User requests workflow details"],then:["Workflow details are returned"]}],examples:[{key:"get-details",input:{workflowId:"def-123"},output:{id:"def-123",name:"Employee Onboarding"}}]}});import{defineFeature as Kg}from"@contractspec/lib.contracts-spec";var $_=Kg({meta:{key:"workflow-system",title:"Workflow & Approval System",description:"State machine-based workflow engine with role-based approvals, delegation, and escalation",domain:"workflow",owners:["@workflow-team"],tags:["workflow","approval","state-machine","automation"],stability:"experimental",version:"1.0.0"},operations:[{key:"workflow.definition.create",version:"1.0.0"},{key:"workflow.definition.update",version:"1.0.0"},{key:"workflow.step.add",version:"1.0.0"},{key:"workflow.definition.publish",version:"1.0.0"},{key:"workflow.definition.list",version:"1.0.0"},{key:"workflow.definition.get",version:"1.0.0"},{key:"workflow.instance.start",version:"1.0.0"},{key:"workflow.instance.transition",version:"1.0.0"},{key:"workflow.instance.pause",version:"1.0.0"},{key:"workflow.instance.resume",version:"1.0.0"},{key:"workflow.instance.cancel",version:"1.0.0"},{key:"workflow.instance.list",version:"1.0.0"},{key:"workflow.instance.get",version:"1.0.0"},{key:"workflow.approval.decide",version:"1.0.0"},{key:"workflow.approval.delegate",version:"1.0.0"},{key:"workflow.approval.comment.add",version:"1.0.0"},{key:"workflow.approval.list.mine",version:"1.0.0"},{key:"workflow.approval.get",version:"1.0.0"}],events:[{key:"workflow.definition.created",version:"1.0.0"},{key:"workflow.definition.updated",version:"1.0.0"},{key:"workflow.definition.published",version:"1.0.0"},{key:"workflow.step.added",version:"1.0.0"},{key:"workflow.instance.started",version:"1.0.0"},{key:"workflow.step.entered",version:"1.0.0"},{key:"workflow.step.exited",version:"1.0.0"},{key:"workflow.instance.completed",version:"1.0.0"},{key:"workflow.instance.cancelled",version:"1.0.0"},{key:"workflow.instance.paused",version:"1.0.0"},{key:"workflow.instance.resumed",version:"1.0.0"},{key:"workflow.instance.failed",version:"1.0.0"},{key:"workflow.instance.timedOut",version:"1.0.0"},{key:"workflow.approval.requested",version:"1.0.0"},{key:"workflow.approval.decided",version:"1.0.0"},{key:"workflow.approval.delegated",version:"1.0.0"},{key:"workflow.approval.escalated",version:"1.0.0"}],presentations:[{key:"workflow.designer",version:"1.0.0"},{key:"workflow.definition.viewList",version:"1.0.0"},{key:"workflow.definition.detail",version:"1.0.0"},{key:"workflow.instance.viewList",version:"1.0.0"},{key:"workflow.instance.detail",version:"1.0.0"},{key:"workflow.instance.progress",version:"1.0.0"},{key:"workflow.approval.inbox",version:"1.0.0"},{key:"workflow.approval.detail",version:"1.0.0"},{key:"workflow.approval.form",version:"1.0.0"},{key:"workflow.approval.badge",version:"1.0.0"},{key:"workflow.metrics",version:"1.0.0"}],opToPresentation:[{op:{key:"workflow.definition.list",version:"1.0.0"},pres:{key:"workflow.definition.viewList",version:"1.0.0"}},{op:{key:"workflow.instance.list",version:"1.0.0"},pres:{key:"workflow.instance.viewList",version:"1.0.0"}},{op:{key:"workflow.approval.list.mine",version:"1.0.0"},pres:{key:"workflow.approval.inbox",version:"1.0.0"}},{op:{key:"workflow.approval.decide",version:"1.0.0"},pres:{key:"workflow.approval.form",version:"1.0.0"}}],presentationsTargets:[{key:"workflow.designer",version:"1.0.0",targets:["react"]},{key:"workflow.definition.viewList",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.definition.detail",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.instance.viewList",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.instance.detail",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.instance.progress",version:"1.0.0",targets:["react"]},{key:"workflow.approval.inbox",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.approval.detail",version:"1.0.0",targets:["react","markdown"]},{key:"workflow.metrics",version:"1.0.0",targets:["react","markdown"]}],visualizations:c0,capabilities:{requires:[{key:"identity",version:"1.0.0"},{key:"audit-trail",version:"1.0.0"},{key:"notifications",version:"1.0.0"},{key:"feature-flags",version:"1.0.0"}],provides:[{key:"workflow",version:"1.0.0"},{key:"approval",version:"1.0.0"},{key:"state-machine",version:"1.0.0"}]},workflows:[{key:"workflow-system.workflow.approval-chain",version:"1.0.0"}],telemetry:[{key:"workflow-system.telemetry",version:"1.0.0"}],jobs:[{key:"workflow-system.job.instance-timeout",version:"1.0.0"},{key:"workflow-system.job.escalation",version:"1.0.0"}],docs:["docs.examples.workflow-system","docs.examples.workflow-system.goal","docs.examples.workflow-system.usage","docs.examples.workflow-system.constraints"]});export{aA as workflowInstanceDetailMarkdownRenderer,nA as workflowDefinitionListMarkdownRenderer,eA as workflowDashboardMarkdownRenderer,q0 as useWorkflowList,zg as mockDataStore,G0 as createWorkflowVisualizationSections,sg as createWorkflowHandlers,Wg as createStateMachineEngine,bg as createInitialState,dg as buildStateMachineDefinition,s0 as WorkflowVisualizationSpecs,f2 as WorkflowVisualizationRegistry,c0 as WorkflowVisualizationRefs,Cg as WorkflowUpdatedEvent,d0 as WorkflowThroughputVisualization,X2 as WorkflowSystemPresentations,$_ as WorkflowSystemFeature,l as WorkflowStepModel,c as WorkflowStatusEnum,Ng as WorkflowPublishedEvent,SA as WorkflowMetricsPresentation,fA as WorkflowListPresentation,W0 as WorkflowInstanceStatusVisualization,K as WorkflowInstanceModel,rA as WorkflowDetailPresentation,jA as WorkflowDesignerPresentation,B as WorkflowDefinitionModel,Og as WorkflowDashboard,Pg as WorkflowCreatedEvent,x0 as WorkflowCompletedMetricVisualization,b0 as WorkflowActiveMetricVisualization,v0 as UpdateWorkflowInputModel,Fg as UpdateWorkflowContract,u as TriggerTypeEnum,WA as TransitionWorkflowContract,Q0 as TransitionResultModel,$0 as TransitionInputModel,PA as SubmitDecisionContract,Z0 as StepTypeEnum,kA as StepExitedEvent,KA as StepEnteredEvent,Gg as StepAddedEvent,X0 as StartWorkflowInputModel,qA as StartWorkflowContract,bA as ResumeWorkflowContract,Vg as PublishWorkflowContract,EA as ProgressTrackerPresentation,oA as PendingApprovalsBadgePresentation,dA as PauseWorkflowContract,Hg as ListWorkflowsContract,GA as ListMyApprovalsContract,MA as ListInstancesContract,zA as InstanceTimedOutEvent,t as InstanceStatusEnum,YA as InstanceStartedEvent,BA as InstanceResumedEvent,QA as InstancePausedEvent,wA as InstanceListPresentation,vA as InstanceFailedEvent,TA as InstanceDetailPresentation,XA as InstanceCompletedEvent,$A as InstanceCancelledEvent,Yg as GetWorkflowContract,hA as GetInstanceContract,UA as GetApprovalContract,CA as DelegateApprovalContract,B0 as CreateWorkflowInputModel,Ug as CreateWorkflowContract,xA as CancelWorkflowContract,w0 as BasicStateMachineEngine,y as ApprovalStatusEnum,LA as ApprovalRequestedEvent,b as ApprovalRequestModel,O0 as ApprovalModeEnum,pA as ApprovalInboxPresentation,mA as ApprovalFormPresentation,IA as ApprovalEscalatedEvent,yA as ApprovalDetailPresentation,OA as ApprovalDelegatedEvent,m as ApprovalDecisionEnum,ZA as ApprovalDecidedEvent,_0 as ApprovalCommentModel,z0 as AddStepInputModel,Jg as AddStepContract,NA as AddApprovalCommentContract};