@critical-path/core 0.36.0 → 0.36.1

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 (185) hide show
  1. package/package.json +5 -1
  2. package/CHANGELOG.md +0 -593
  3. package/dist/deliverables.test.d.ts +0 -2
  4. package/dist/deliverables.test.d.ts.map +0 -1
  5. package/dist/deliverables.test.js +0 -232
  6. package/dist/deliverables.test.js.map +0 -1
  7. package/dist/domain/calendar.test.d.ts +0 -2
  8. package/dist/domain/calendar.test.d.ts.map +0 -1
  9. package/dist/domain/calendar.test.js +0 -181
  10. package/dist/domain/calendar.test.js.map +0 -1
  11. package/dist/domain/cpm.test.d.ts +0 -2
  12. package/dist/domain/cpm.test.d.ts.map +0 -1
  13. package/dist/domain/cpm.test.js +0 -166
  14. package/dist/domain/cpm.test.js.map +0 -1
  15. package/dist/domain/ddd.test.d.ts +0 -2
  16. package/dist/domain/ddd.test.d.ts.map +0 -1
  17. package/dist/domain/ddd.test.js +0 -349
  18. package/dist/domain/ddd.test.js.map +0 -1
  19. package/dist/domain/ladder.test.d.ts +0 -2
  20. package/dist/domain/ladder.test.d.ts.map +0 -1
  21. package/dist/domain/ladder.test.js +0 -213
  22. package/dist/domain/ladder.test.js.map +0 -1
  23. package/dist/domain/metrics.test.d.ts +0 -2
  24. package/dist/domain/metrics.test.d.ts.map +0 -1
  25. package/dist/domain/metrics.test.js +0 -252
  26. package/dist/domain/metrics.test.js.map +0 -1
  27. package/dist/domain/task-duration.test.d.ts +0 -2
  28. package/dist/domain/task-duration.test.d.ts.map +0 -1
  29. package/dist/domain/task-duration.test.js +0 -307
  30. package/dist/domain/task-duration.test.js.map +0 -1
  31. package/dist/domain/workload.test.d.ts +0 -2
  32. package/dist/domain/workload.test.d.ts.map +0 -1
  33. package/dist/domain/workload.test.js +0 -261
  34. package/dist/domain/workload.test.js.map +0 -1
  35. package/dist/engine/actor.test.d.ts +0 -2
  36. package/dist/engine/actor.test.d.ts.map +0 -1
  37. package/dist/engine/actor.test.js +0 -54
  38. package/dist/engine/actor.test.js.map +0 -1
  39. package/dist/engine/authorization.test.d.ts +0 -2
  40. package/dist/engine/authorization.test.d.ts.map +0 -1
  41. package/dist/engine/authorization.test.js +0 -154
  42. package/dist/engine/authorization.test.js.map +0 -1
  43. package/dist/engine/cascade.test.d.ts +0 -2
  44. package/dist/engine/cascade.test.d.ts.map +0 -1
  45. package/dist/engine/cascade.test.js +0 -99
  46. package/dist/engine/cascade.test.js.map +0 -1
  47. package/dist/engine/config.test.d.ts +0 -2
  48. package/dist/engine/config.test.d.ts.map +0 -1
  49. package/dist/engine/config.test.js +0 -46
  50. package/dist/engine/config.test.js.map +0 -1
  51. package/dist/engine/entity-events.test.d.ts +0 -2
  52. package/dist/engine/entity-events.test.d.ts.map +0 -1
  53. package/dist/engine/entity-events.test.js +0 -61
  54. package/dist/engine/entity-events.test.js.map +0 -1
  55. package/dist/index.test.d.ts +0 -2
  56. package/dist/index.test.d.ts.map +0 -1
  57. package/dist/index.test.js +0 -429
  58. package/dist/index.test.js.map +0 -1
  59. package/dist/plugins/plugins.test.d.ts +0 -2
  60. package/dist/plugins/plugins.test.d.ts.map +0 -1
  61. package/dist/plugins/plugins.test.js +0 -137
  62. package/dist/plugins/plugins.test.js.map +0 -1
  63. package/dist/schemas/schemas.test.d.ts +0 -2
  64. package/dist/schemas/schemas.test.d.ts.map +0 -1
  65. package/dist/schemas/schemas.test.js +0 -58
  66. package/dist/schemas/schemas.test.js.map +0 -1
  67. package/dist/status.test.d.ts +0 -2
  68. package/dist/status.test.d.ts.map +0 -1
  69. package/dist/status.test.js +0 -295
  70. package/dist/status.test.js.map +0 -1
  71. package/dist/storage/storage.test.d.ts +0 -2
  72. package/dist/storage/storage.test.d.ts.map +0 -1
  73. package/dist/storage/storage.test.js +0 -236
  74. package/dist/storage/storage.test.js.map +0 -1
  75. package/dist/storage/upload-limits.test.d.ts +0 -2
  76. package/dist/storage/upload-limits.test.d.ts.map +0 -1
  77. package/dist/storage/upload-limits.test.js +0 -31
  78. package/dist/storage/upload-limits.test.js.map +0 -1
  79. package/dist/store/conformance.test.d.ts +0 -2
  80. package/dist/store/conformance.test.d.ts.map +0 -1
  81. package/dist/store/conformance.test.js +0 -15
  82. package/dist/store/conformance.test.js.map +0 -1
  83. package/dist/store/firebase.test.d.ts +0 -2
  84. package/dist/store/firebase.test.d.ts.map +0 -1
  85. package/dist/store/firebase.test.js +0 -103
  86. package/dist/store/firebase.test.js.map +0 -1
  87. package/dist/store/query.test.d.ts +0 -2
  88. package/dist/store/query.test.d.ts.map +0 -1
  89. package/dist/store/query.test.js +0 -89
  90. package/dist/store/query.test.js.map +0 -1
  91. package/dist/store/sqlite.test.d.ts +0 -2
  92. package/dist/store/sqlite.test.d.ts.map +0 -1
  93. package/dist/store/sqlite.test.js +0 -177
  94. package/dist/store/sqlite.test.js.map +0 -1
  95. package/dist/task-state.test.d.ts +0 -2
  96. package/dist/task-state.test.d.ts.map +0 -1
  97. package/dist/task-state.test.js +0 -423
  98. package/dist/task-state.test.js.map +0 -1
  99. package/dist/use-case-validation.test.d.ts +0 -2
  100. package/dist/use-case-validation.test.d.ts.map +0 -1
  101. package/dist/use-case-validation.test.js +0 -281
  102. package/dist/use-case-validation.test.js.map +0 -1
  103. package/dist/utils/fractional-index.test.d.ts +0 -2
  104. package/dist/utils/fractional-index.test.d.ts.map +0 -1
  105. package/dist/utils/fractional-index.test.js +0 -182
  106. package/dist/utils/fractional-index.test.js.map +0 -1
  107. package/dist/utils/key.test.d.ts +0 -2
  108. package/dist/utils/key.test.d.ts.map +0 -1
  109. package/dist/utils/key.test.js +0 -65
  110. package/dist/utils/key.test.js.map +0 -1
  111. package/dist/utils/mentions.test.d.ts +0 -2
  112. package/dist/utils/mentions.test.d.ts.map +0 -1
  113. package/dist/utils/mentions.test.js +0 -114
  114. package/dist/utils/mentions.test.js.map +0 -1
  115. package/dist/webhooks/webhooks.test.d.ts +0 -2
  116. package/dist/webhooks/webhooks.test.d.ts.map +0 -1
  117. package/dist/webhooks/webhooks.test.js +0 -154
  118. package/dist/webhooks/webhooks.test.js.map +0 -1
  119. package/src/deliverables.test.ts +0 -284
  120. package/src/domain/authorization.ts +0 -82
  121. package/src/domain/calendar.test.ts +0 -216
  122. package/src/domain/calendar.ts +0 -502
  123. package/src/domain/cpm.test.ts +0 -189
  124. package/src/domain/cpm.ts +0 -258
  125. package/src/domain/custom-fields.ts +0 -172
  126. package/src/domain/ddd.test.ts +0 -442
  127. package/src/domain/entities.ts +0 -798
  128. package/src/domain/errors.ts +0 -38
  129. package/src/domain/events.ts +0 -369
  130. package/src/domain/graph.ts +0 -70
  131. package/src/domain/index.ts +0 -12
  132. package/src/domain/ladder.test.ts +0 -251
  133. package/src/domain/ladder.ts +0 -474
  134. package/src/domain/metrics.test.ts +0 -288
  135. package/src/domain/metrics.ts +0 -497
  136. package/src/domain/task-duration.test.ts +0 -354
  137. package/src/domain/workload.test.ts +0 -311
  138. package/src/domain/workload.ts +0 -457
  139. package/src/engine/actor.test.ts +0 -63
  140. package/src/engine/authorization.test.ts +0 -199
  141. package/src/engine/cascade.test.ts +0 -121
  142. package/src/engine/config.test.ts +0 -51
  143. package/src/engine/entity-events.test.ts +0 -67
  144. package/src/engine/index.ts +0 -2495
  145. package/src/index.test.ts +0 -514
  146. package/src/index.ts +0 -9
  147. package/src/plugins/index.ts +0 -103
  148. package/src/plugins/plugins.test.ts +0 -161
  149. package/src/schemas/index.ts +0 -402
  150. package/src/schemas/schemas.test.ts +0 -116
  151. package/src/status.test.ts +0 -354
  152. package/src/storage/file-storage.ts +0 -200
  153. package/src/storage/firebase-storage.ts +0 -209
  154. package/src/storage/index.ts +0 -3
  155. package/src/storage/s3.ts +0 -151
  156. package/src/storage/storage.test.ts +0 -274
  157. package/src/storage/upload-limits.test.ts +0 -41
  158. package/src/store/conformance.test.ts +0 -15
  159. package/src/store/firebase.test.ts +0 -131
  160. package/src/store/firebase.ts +0 -658
  161. package/src/store/index.ts +0 -623
  162. package/src/store/query.test.ts +0 -110
  163. package/src/store/query.ts +0 -113
  164. package/src/store/sqlite.test.ts +0 -218
  165. package/src/store/sqlite.ts +0 -1480
  166. package/src/task-state.test.ts +0 -506
  167. package/src/testing/conformance.ts +0 -319
  168. package/src/testing/index.ts +0 -1
  169. package/src/types/index.ts +0 -871
  170. package/src/use-case-validation.test.ts +0 -324
  171. package/src/utils/fractional-index.test.ts +0 -228
  172. package/src/utils/fractional-index.ts +0 -254
  173. package/src/utils/index.ts +0 -7
  174. package/src/utils/key.test.ts +0 -76
  175. package/src/utils/key.ts +0 -62
  176. package/src/utils/mentions.test.ts +0 -132
  177. package/src/utils/mentions.ts +0 -131
  178. package/src/utils/status.ts +0 -419
  179. package/src/utils/workflow.ts +0 -306
  180. package/src/webhooks/dispatcher.ts +0 -190
  181. package/src/webhooks/index.ts +0 -2
  182. package/src/webhooks/signature.ts +0 -57
  183. package/src/webhooks/webhooks.test.ts +0 -201
  184. package/tsconfig.json +0 -8
  185. package/tsconfig.tsbuildinfo +0 -1
@@ -1,306 +0,0 @@
1
- import type {
2
- Workflow,
3
- StatusDefinition,
4
- TaskTypeDefinition
5
- } from '../types/index.js';
6
- import { DEFAULT_STATUS_DEFINITIONS } from './status.js';
7
-
8
- export class WorkflowValidationError extends Error {
9
- public readonly fromStatus: string;
10
- public readonly toStatus: string;
11
- public readonly workflowId?: string;
12
-
13
- constructor(fromStatus: string, toStatus: string, workflowId?: string, message?: string) {
14
- const msg = message || `Illegal status transition from "${fromStatus}" to "${toStatus}"${workflowId ? ` in workflow "${workflowId}"` : ''}.`;
15
- super(msg);
16
- this.name = 'WorkflowValidationError';
17
- this.fromStatus = fromStatus;
18
- this.toStatus = toStatus;
19
- this.workflowId = workflowId;
20
- }
21
- }
22
-
23
- export const DEFAULT_TASK_TYPES: TaskTypeDefinition[] = [
24
- { key: 'task', label: 'Task', description: 'A standard work item', icon: 'check-square' },
25
- { key: 'bug', label: 'Bug', description: 'A problem or defect that needs fixing', icon: 'bug' },
26
- { key: 'feature', label: 'Feature', description: 'A new capability or enhancement', icon: 'sparkles' },
27
- { key: 'epic', label: 'Epic', description: 'A large body of work that spans multiple tasks', icon: 'layers' },
28
- { key: 'subtask', label: 'Subtask', description: 'A piece of work required to complete a parent task', icon: 'corner-down-right' }
29
- ];
30
-
31
- export const DEFAULT_SOFTWARE_WORKFLOW: Workflow = {
32
- id: 'wf_software_default',
33
- name: 'Software Development Workflow',
34
- description: 'Standard software development lifecycle with backlog, review, and completion states.',
35
- statuses: [
36
- DEFAULT_STATUS_DEFINITIONS.backlog,
37
- DEFAULT_STATUS_DEFINITIONS.todo,
38
- DEFAULT_STATUS_DEFINITIONS.in_progress,
39
- DEFAULT_STATUS_DEFINITIONS.in_review,
40
- DEFAULT_STATUS_DEFINITIONS.done,
41
- DEFAULT_STATUS_DEFINITIONS.canceled
42
- ],
43
- transitions: [
44
- { name: 'Start Work', fromStatusKey: 'backlog', toStatusKey: 'todo' },
45
- { name: 'Return to Backlog', fromStatusKey: 'todo', toStatusKey: 'backlog' },
46
- { name: 'Start Implementation', fromStatusKey: 'todo', toStatusKey: 'in_progress' },
47
- { name: 'Return to To Do', fromStatusKey: 'in_progress', toStatusKey: 'todo' },
48
- { name: 'Complete Task', fromStatusKey: 'todo', toStatusKey: 'done' },
49
- { name: 'Submit for Review', fromStatusKey: 'in_progress', toStatusKey: 'in_review' },
50
- { name: 'Complete Implementation', fromStatusKey: 'in_progress', toStatusKey: 'done' },
51
- { name: 'Approve & Complete', fromStatusKey: 'in_review', toStatusKey: 'done' },
52
- { name: 'Request Changes', fromStatusKey: 'in_review', toStatusKey: 'in_progress' },
53
- { name: 'Reopen', fromStatusKey: 'done', toStatusKey: 'todo' },
54
- { name: 'Cancel', fromStatusKey: '*', toStatusKey: 'canceled' },
55
- { name: 'Restore', fromStatusKey: 'canceled', toStatusKey: 'todo' }
56
- ],
57
- taskTypes: DEFAULT_TASK_TYPES,
58
- defaultStatusKey: 'todo',
59
- isDefault: false,
60
- createdAt: '2026-01-01T00:00:00.000Z',
61
- updatedAt: '2026-01-01T00:00:00.000Z'
62
- };
63
-
64
- export const DEFAULT_SIMPLE_WORKFLOW: Workflow = {
65
- id: 'wf_simple_default',
66
- name: 'Simple Task Workflow',
67
- description: 'Lightweight workflow with To Do, In Progress, and Done states.',
68
- statuses: [
69
- DEFAULT_STATUS_DEFINITIONS.todo,
70
- DEFAULT_STATUS_DEFINITIONS.in_progress,
71
- DEFAULT_STATUS_DEFINITIONS.done
72
- ],
73
- transitions: [
74
- { name: 'Start', fromStatusKey: 'todo', toStatusKey: 'in_progress' },
75
- { name: 'Return to To Do', fromStatusKey: 'in_progress', toStatusKey: 'todo' },
76
- { name: 'Complete', fromStatusKey: 'todo', toStatusKey: 'done' },
77
- { name: 'Complete', fromStatusKey: 'in_progress', toStatusKey: 'done' },
78
- { name: 'Reopen', fromStatusKey: 'done', toStatusKey: 'todo' },
79
- { name: 'Return to In Progress', fromStatusKey: 'done', toStatusKey: 'in_progress' }
80
- ],
81
- taskTypes: DEFAULT_TASK_TYPES.filter((t) => ['task', 'subtask'].includes(t.key)),
82
- defaultStatusKey: 'todo',
83
- isDefault: true,
84
- createdAt: '2026-01-01T00:00:00.000Z',
85
- updatedAt: '2026-01-01T00:00:00.000Z'
86
- };
87
-
88
- export const DEFAULT_VFX_WORKFLOW: Workflow = {
89
- id: 'wf_vfx_default',
90
- name: 'VFX Production Workflow',
91
- description: 'Visual effects production pipeline from bidding and drafting to internal lead review and client supervisor approval.',
92
- statuses: [
93
- { key: 'bidding', label: 'Bidding & Draft', category: 'not_started' },
94
- { key: 'awarded', label: 'Awarded / Ready', category: 'not_started' },
95
- { key: 'in_production', label: 'In Production', category: 'in_progress' },
96
- { key: 'internal_review', label: 'Internal Review', category: 'in_progress' },
97
- { key: 'client_review', label: 'Client Review', category: 'in_progress' },
98
- { key: 'revision_requested', label: 'Revision Requested', category: 'in_progress' },
99
- { key: 'approved', label: 'Approved (Final)', category: 'completed' },
100
- DEFAULT_STATUS_DEFINITIONS.canceled
101
- ],
102
- transitions: [
103
- { name: 'Award Bid', fromStatusKey: 'bidding', toStatusKey: 'awarded' },
104
- { name: 'Start Directly from Bid', fromStatusKey: 'bidding', toStatusKey: 'in_production' },
105
- { name: 'Start Work', fromStatusKey: 'awarded', toStatusKey: 'in_production' },
106
- { name: 'Reopen Bid', fromStatusKey: 'awarded', toStatusKey: 'bidding' },
107
- { name: 'Submit to Lead Review', fromStatusKey: 'in_production', toStatusKey: 'internal_review' },
108
- { name: 'Fast-Track Client Review', fromStatusKey: 'in_production', toStatusKey: 'client_review' },
109
- { name: 'Direct Approval', fromStatusKey: 'in_production', toStatusKey: 'approved' },
110
- { name: 'Submit to Client Review', fromStatusKey: 'internal_review', toStatusKey: 'client_review' },
111
- { name: 'Request Internal Revisions', fromStatusKey: 'internal_review', toStatusKey: 'revision_requested' },
112
- { name: 'Return to Production', fromStatusKey: 'internal_review', toStatusKey: 'in_production' },
113
- { name: 'Approve from Lead Review', fromStatusKey: 'internal_review', toStatusKey: 'approved' },
114
- { name: 'Request Client Revisions', fromStatusKey: 'client_review', toStatusKey: 'revision_requested' },
115
- { name: 'Return to Lead Review', fromStatusKey: 'client_review', toStatusKey: 'internal_review' },
116
- { name: 'Approve Final Shot', fromStatusKey: 'client_review', toStatusKey: 'approved' },
117
- { name: 'Address Revisions in Production', fromStatusKey: 'revision_requested', toStatusKey: 'in_production' },
118
- { name: 'Resubmit to Lead Review', fromStatusKey: 'revision_requested', toStatusKey: 'internal_review' },
119
- { name: 'Resubmit to Client Review', fromStatusKey: 'revision_requested', toStatusKey: 'client_review' },
120
- { name: 'Reopen Shot', fromStatusKey: 'approved', toStatusKey: 'in_production' },
121
- { name: 'Reopen Lead Review', fromStatusKey: 'approved', toStatusKey: 'internal_review' },
122
- { name: 'Cancel', fromStatusKey: '*', toStatusKey: 'canceled' },
123
- { name: 'Restore to Bidding', fromStatusKey: 'canceled', toStatusKey: 'bidding' },
124
- { name: 'Restore to Production', fromStatusKey: 'canceled', toStatusKey: 'in_production' }
125
- ],
126
- taskTypes: [
127
- { key: 'vfx_task', label: 'VFX Task', description: 'Department task (e.g. Matchmove, Animation, FX, Comp)', icon: 'film' },
128
- { key: 'asset', label: 'Asset', description: '3D or 2D asset element', icon: 'box' },
129
- { key: 'subtask', label: 'Subtask', description: 'Element subtask required to complete a department task', icon: 'corner-down-right' }
130
- ],
131
- defaultStatusKey: 'bidding',
132
- isDefault: false,
133
- createdAt: '2026-01-01T00:00:00.000Z',
134
- updatedAt: '2026-01-01T00:00:00.000Z'
135
- };
136
-
137
- export const DEFAULT_CREATIVE_WORKFLOW: Workflow = {
138
- id: 'wf_creative_default',
139
- name: 'Creative Production Workflow',
140
- description: 'Production pipeline for creative deliverables from briefing and concepts to internal review, client feedback, and final delivery.',
141
- statuses: [
142
- { key: 'briefing', label: 'Briefing & Scoping', category: 'not_started' },
143
- { key: 'concept', label: 'Concept & Storyboarding', category: 'in_progress' },
144
- { key: 'in_production', label: 'In Production', category: 'in_progress' },
145
- { key: 'internal_review', label: 'Internal Review', category: 'in_progress' },
146
- { key: 'client_review', label: 'Client Review', category: 'in_progress' },
147
- { key: 'revision_requested', label: 'Revision Requested', category: 'in_progress' },
148
- { key: 'approved', label: 'Approved', category: 'completed' },
149
- { key: 'delivered', label: 'Delivered', category: 'completed' },
150
- DEFAULT_STATUS_DEFINITIONS.canceled
151
- ],
152
- transitions: [
153
- { name: 'Start Concepts', fromStatusKey: 'briefing', toStatusKey: 'concept' },
154
- { name: 'Approve Concept for Production', fromStatusKey: 'concept', toStatusKey: 'in_production' },
155
- { name: 'Return to Briefing', fromStatusKey: 'concept', toStatusKey: 'briefing' },
156
- { name: 'Submit for Internal Review', fromStatusKey: 'in_production', toStatusKey: 'internal_review' },
157
- { name: 'Submit for Client Review', fromStatusKey: 'in_production', toStatusKey: 'client_review' },
158
- { name: 'Submit for Client Review', fromStatusKey: 'internal_review', toStatusKey: 'client_review' },
159
- { name: 'Request Revisions (Internal)', fromStatusKey: 'internal_review', toStatusKey: 'revision_requested' },
160
- { name: 'Return to Production', fromStatusKey: 'internal_review', toStatusKey: 'in_production' },
161
- { name: 'Approve from Lead Review', fromStatusKey: 'internal_review', toStatusKey: 'approved' },
162
- { name: 'Request Revisions (Client)', fromStatusKey: 'client_review', toStatusKey: 'revision_requested' },
163
- { name: 'Return to Internal Review', fromStatusKey: 'client_review', toStatusKey: 'internal_review' },
164
- { name: 'Address Revisions', fromStatusKey: 'revision_requested', toStatusKey: 'in_production' },
165
- { name: 'Resubmit to Lead Review', fromStatusKey: 'revision_requested', toStatusKey: 'internal_review' },
166
- { name: 'Resubmit to Client Review', fromStatusKey: 'revision_requested', toStatusKey: 'client_review' },
167
- { name: 'Approve Work', fromStatusKey: 'client_review', toStatusKey: 'approved' },
168
- { name: 'Deliver Final Assets', fromStatusKey: 'approved', toStatusKey: 'delivered' },
169
- { name: 'Reopen Deliverable', fromStatusKey: 'delivered', toStatusKey: 'in_production' },
170
- { name: 'Cancel', fromStatusKey: '*', toStatusKey: 'canceled' },
171
- { name: 'Restore', fromStatusKey: 'canceled', toStatusKey: 'briefing' }
172
- ],
173
- taskTypes: [
174
- { key: 'deliverable', label: 'Deliverable', description: 'Finished asset, cutdown, or packaged export', icon: 'package' },
175
- { key: 'creative_task', label: 'Creative Task', description: 'Production task (e.g. Design, Copy, Editing, Color)', icon: 'pen-tool' },
176
- { key: 'review', label: 'Review Gate', description: 'Internal or external client sign-off', icon: 'check-circle' }
177
- ],
178
- defaultStatusKey: 'briefing',
179
- isDefault: false,
180
- createdAt: '2026-01-01T00:00:00.000Z',
181
- updatedAt: '2026-01-01T00:00:00.000Z'
182
- };
183
-
184
- export function validateTransition(
185
- workflow: Workflow | undefined,
186
- fromStatus: string,
187
- toStatus: string
188
- ): boolean {
189
- if (fromStatus === toStatus) return true;
190
- if (!workflow || !workflow.transitions || workflow.transitions.length === 0) return true;
191
-
192
- return workflow.transitions.some(
193
- (t) =>
194
- (t.fromStatusKey === '*' || t.fromStatusKey === fromStatus) &&
195
- (t.toStatusKey === '*' || t.toStatusKey === toStatus)
196
- );
197
- }
198
-
199
- export function getAllowedNextStatuses(
200
- workflow: Workflow | undefined,
201
- currentStatus: string
202
- ): string[] {
203
- if (!workflow || !workflow.statuses || workflow.statuses.length === 0) {
204
- return Object.keys(DEFAULT_STATUS_DEFINITIONS);
205
- }
206
-
207
- const allStatusKeys = workflow.statuses.map((s) => s.key);
208
- const currentIndex = allStatusKeys.indexOf(currentStatus);
209
- if (currentIndex === -1 || currentIndex >= allStatusKeys.length - 1) {
210
- return [];
211
- }
212
-
213
- const nextStatusKeys = allStatusKeys.slice(currentIndex + 1);
214
-
215
- if (workflow.transitions && workflow.transitions.length > 0) {
216
- const matches = workflow.transitions.filter(
217
- (t) => t.fromStatusKey === '*' || t.fromStatusKey === currentStatus
218
- );
219
-
220
- const allowed = new Set<string>();
221
- for (const t of matches) {
222
- if (t.toStatusKey === '*') {
223
- return nextStatusKeys;
224
- }
225
- if (nextStatusKeys.includes(t.toStatusKey)) {
226
- allowed.add(t.toStatusKey);
227
- }
228
- }
229
-
230
- return Array.from(allowed);
231
- }
232
-
233
- return [allStatusKeys[currentIndex + 1]];
234
- }
235
-
236
- export function getAllowedTransitions(
237
- workflow: Workflow | undefined,
238
- currentStatus: string
239
- ): string[] {
240
- if (!workflow || !workflow.statuses || workflow.statuses.length === 0) {
241
- return Object.keys(DEFAULT_STATUS_DEFINITIONS);
242
- }
243
-
244
- const allStatusKeys = workflow.statuses.map((s) => s.key);
245
- if (!allStatusKeys.includes(currentStatus)) {
246
- return [];
247
- }
248
-
249
- if (workflow.transitions && workflow.transitions.length > 0) {
250
- const matches = workflow.transitions.filter(
251
- (t) => t.fromStatusKey === '*' || t.fromStatusKey === currentStatus
252
- );
253
-
254
- const allowed = new Set<string>();
255
- for (const t of matches) {
256
- if (t.toStatusKey === '*') {
257
- allStatusKeys.filter((k) => k !== currentStatus).forEach((k) => allowed.add(k));
258
- } else if (t.toStatusKey !== currentStatus && allStatusKeys.includes(t.toStatusKey)) {
259
- allowed.add(t.toStatusKey);
260
- }
261
- }
262
-
263
- return Array.from(allowed);
264
- }
265
-
266
- const next = getAllowedNextStatuses(workflow, currentStatus);
267
- const prev = getAllowedPreviousStatuses(workflow, currentStatus);
268
- return Array.from(new Set([...next, ...prev]));
269
- }
270
-
271
- export function getAllowedPreviousStatuses(
272
- workflow: Workflow | undefined,
273
- currentStatus: string
274
- ): string[] {
275
- if (!workflow || !workflow.statuses || workflow.statuses.length === 0) {
276
- return [];
277
- }
278
-
279
- const allStatusKeys = workflow.statuses.map((s) => s.key);
280
- const currentIndex = allStatusKeys.indexOf(currentStatus);
281
- if (currentIndex <= 0) {
282
- return [];
283
- }
284
-
285
- const previousStatusKeys = allStatusKeys.slice(0, currentIndex);
286
-
287
- if (workflow.transitions && workflow.transitions.length > 0) {
288
- const matches = workflow.transitions.filter(
289
- (t) => t.fromStatusKey === '*' || t.fromStatusKey === currentStatus
290
- );
291
-
292
- const allowed = new Set<string>();
293
- for (const t of matches) {
294
- if (t.toStatusKey === '*') {
295
- return previousStatusKeys;
296
- }
297
- if (previousStatusKeys.includes(t.toStatusKey)) {
298
- allowed.add(t.toStatusKey);
299
- }
300
- }
301
-
302
- return Array.from(allowed);
303
- }
304
-
305
- return [allStatusKeys[currentIndex - 1]];
306
- }
@@ -1,190 +0,0 @@
1
- import type { Webhook } from '../types/index.js';
2
- import type { DomainEvent } from '../domain/events.js';
3
- import { signWebhookPayload } from './signature.js';
4
-
5
- /** One attempt to deliver one event to one webhook. Serializable, so durable queues can store it. */
6
- export interface WebhookDeliveryJob {
7
- /** Stable per event and webhook (`<eventId>:<webhookId>`); sent as `X-CriticalPath-Delivery`. */
8
- id: string;
9
- webhookId: string;
10
- url: string;
11
- secret?: string;
12
- event: string;
13
- /** JSON body, signed as-is. */
14
- body: string;
15
- /** 1-based attempt number. */
16
- attempt: number;
17
- }
18
-
19
- /**
20
- * Schedules delivery jobs. The default `InProcessWebhookQueue` keeps jobs in memory (lost on
21
- * restart). A durable queue persists `job` and, when `delayMs` has passed, calls
22
- * `engine.webhooks.deliver(job)` from a worker.
23
- */
24
- export interface WebhookDeliveryQueue {
25
- enqueue(job: WebhookDeliveryJob, delayMs: number): void | Promise<void>;
26
- }
27
-
28
- export interface WebhookDeliveryOptions {
29
- /** Custom queue (e.g. backed by a database or job runner). Default: in-process timers. */
30
- queue?: WebhookDeliveryQueue;
31
- /** Fetch implementation. Default: global `fetch`. */
32
- fetch?: typeof fetch;
33
- /** Per-attempt timeout. Default 10 000 ms. */
34
- timeoutMs?: number;
35
- /** Attempts before giving up. Default 5. */
36
- maxAttempts?: number;
37
- /** First retry delay; doubles each attempt. Default 1 000 ms. */
38
- retryBaseDelayMs?: number;
39
- /**
40
- * Allow webhook URLs that point at localhost or private network addresses. Default `false`,
41
- * which blocks literal private hosts to reduce SSRF risk (DNS-based tricks are not detected).
42
- */
43
- allowPrivateUrls?: boolean;
44
- onDelivered?: (job: WebhookDeliveryJob, status: number) => void;
45
- /** Called after the final failed attempt. Default: `console.warn`. */
46
- onDeliveryFailed?: (job: WebhookDeliveryJob, error: unknown) => void;
47
- }
48
-
49
- export interface WebhookSource {
50
- listWebhooks(): Promise<Webhook[]>;
51
- /** The tenant an event belongs to; only webhooks with the same `tenantId` receive it. */
52
- resolveTenant(event: DomainEvent): Promise<string | undefined>;
53
- }
54
-
55
- /** Default queue: runs jobs on timers in this process. Timers do not keep the process alive. */
56
- export class InProcessWebhookQueue implements WebhookDeliveryQueue {
57
- private outstanding = 0;
58
- private waiters: Array<() => void> = [];
59
-
60
- constructor(private readonly run: (job: WebhookDeliveryJob) => Promise<void>) {}
61
-
62
- enqueue(job: WebhookDeliveryJob, delayMs: number): void {
63
- this.outstanding++;
64
- const timer = setTimeout(async () => {
65
- try {
66
- await this.run(job);
67
- } finally {
68
- this.outstanding--;
69
- if (this.outstanding === 0) this.waiters.splice(0).forEach((resolve) => resolve());
70
- }
71
- }, delayMs);
72
- (timer as { unref?: () => void }).unref?.();
73
- }
74
-
75
- /** Resolves when no deliveries (including scheduled retries) are pending. */
76
- idle(): Promise<void> {
77
- return this.outstanding === 0 ? Promise.resolve() : new Promise((resolve) => this.waiters.push(resolve));
78
- }
79
- }
80
-
81
- const PRIVATE_HOST = /^(localhost|.*\.localhost|.*\.internal|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|0\.0\.0\.0|\[::1?\]|\[f[cd][0-9a-f]*:.*\]|\[fe80:.*\])$/i;
82
-
83
- /** Throws if `url` is not an acceptable webhook target. */
84
- export function assertWebhookUrl(url: string, allowPrivateUrls = false): void {
85
- let parsed: URL;
86
- try {
87
- parsed = new URL(url);
88
- } catch {
89
- throw new Error(`Invalid webhook URL "${url}".`);
90
- }
91
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
92
- throw new Error('Webhook URLs must use http or https.');
93
- }
94
- if (!allowPrivateUrls && PRIVATE_HOST.test(parsed.hostname)) {
95
- throw new Error(`Webhook URL host "${parsed.hostname}" is a private or local address. Set webhookDelivery.allowPrivateUrls to allow it.`);
96
- }
97
- }
98
-
99
- /**
100
- * Turns domain events into signed webhook deliveries with timeouts and exponential-backoff retries.
101
- * Subscribed to the engine's event bus, so every published event is deliverable.
102
- */
103
- export class WebhookDispatcher {
104
- private readonly queue: WebhookDeliveryQueue;
105
- private readonly fetchImpl: typeof fetch;
106
- private cache?: Promise<Webhook[]>;
107
-
108
- constructor(
109
- private readonly source: WebhookSource,
110
- private readonly options: WebhookDeliveryOptions = {}
111
- ) {
112
- this.queue = options.queue ?? new InProcessWebhookQueue((job) => this.deliver(job));
113
- this.fetchImpl = options.fetch ?? ((...args) => fetch(...args));
114
- }
115
-
116
- /** Drops cached webhooks; call after creating, updating or deleting one. */
117
- invalidate(): void {
118
- this.cache = undefined;
119
- }
120
-
121
- /** Resolves when the default in-process queue has nothing pending. */
122
- idle(): Promise<void> {
123
- return this.queue instanceof InProcessWebhookQueue ? this.queue.idle() : Promise.resolve();
124
- }
125
-
126
- async handle(event: DomainEvent): Promise<void> {
127
- this.cache ??= this.source.listWebhooks().catch((err) => {
128
- this.cache = undefined;
129
- throw err;
130
- });
131
- const subscribed = (await this.cache).filter(
132
- (w) => w.active && (w.events.includes('*') || w.events.includes(event.name as Webhook['events'][number]))
133
- );
134
- if (subscribed.length === 0) return;
135
-
136
- const tenantId = await this.source.resolveTenant(event);
137
- const targets = subscribed.filter((w) => w.tenantId === tenantId);
138
- if (targets.length === 0) return;
139
-
140
- const body = JSON.stringify({
141
- id: event.id,
142
- event: event.name,
143
- occurredAt: event.occurredAt,
144
- ...(tenantId ? { tenantId } : {}),
145
- data: event.payload
146
- });
147
- for (const webhook of targets) {
148
- await this.queue.enqueue(
149
- { id: `${event.id}:${webhook.id}`, webhookId: webhook.id, url: webhook.url, secret: webhook.secret, event: event.name, body, attempt: 1 },
150
- 0
151
- );
152
- }
153
- }
154
-
155
- /** Makes one delivery attempt, scheduling a retry (or reporting failure) if it does not succeed. */
156
- async deliver(job: WebhookDeliveryJob): Promise<void> {
157
- const maxAttempts = this.options.maxAttempts ?? 5;
158
- try {
159
- assertWebhookUrl(job.url, this.options.allowPrivateUrls);
160
- const timestamp = Math.floor(Date.now() / 1000);
161
- const headers: Record<string, string> = {
162
- 'Content-Type': 'application/json',
163
- 'User-Agent': 'CriticalPath-Webhooks/1',
164
- 'X-CriticalPath-Event': job.event,
165
- 'X-CriticalPath-Delivery': job.id,
166
- 'X-CriticalPath-Timestamp': String(timestamp)
167
- };
168
- if (job.secret) {
169
- headers['X-CriticalPath-Signature'] = await signWebhookPayload({ secret: job.secret, body: job.body, timestamp });
170
- }
171
- const response = await this.fetchImpl(job.url, {
172
- method: 'POST',
173
- headers,
174
- body: job.body,
175
- signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000)
176
- });
177
- if (!response.ok) throw new Error(`Webhook responded with HTTP ${response.status}`);
178
- this.options.onDelivered?.(job, response.status);
179
- } catch (error) {
180
- if (job.attempt < maxAttempts) {
181
- const delay = (this.options.retryBaseDelayMs ?? 1_000) * 2 ** (job.attempt - 1);
182
- await this.queue.enqueue({ ...job, attempt: job.attempt + 1 }, delay);
183
- } else if (this.options.onDeliveryFailed) {
184
- this.options.onDeliveryFailed(job, error);
185
- } else {
186
- console.warn(`[CriticalPath Webhooks] Giving up on delivery ${job.id} to ${job.url} after ${job.attempt} attempts:`, error);
187
- }
188
- }
189
- }
190
- }
@@ -1,2 +0,0 @@
1
- export * from './signature.js';
2
- export * from './dispatcher.js';
@@ -1,57 +0,0 @@
1
- /**
2
- * Webhook signing (HMAC-SHA256 over `"<timestamp>.<body>"`) using Web Crypto, so it works in
3
- * Node, edge runtimes and browsers alike.
4
- */
5
-
6
- const encoder = new TextEncoder();
7
-
8
- async function hmacHex(secret: string, message: string): Promise<string> {
9
- const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
10
- 'sign'
11
- ]);
12
- const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));
13
- return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, '0')).join('');
14
- }
15
-
16
- function constantTimeEqual(a: string, b: string): boolean {
17
- if (a.length !== b.length) return false;
18
- let diff = 0;
19
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
20
- return diff === 0;
21
- }
22
-
23
- /** Returns the `X-CriticalPath-Signature` header value: `sha256=<hex>`. */
24
- export async function signWebhookPayload(input: { secret: string; body: string; timestamp: number }): Promise<string> {
25
- return `sha256=${await hmacHex(input.secret, `${input.timestamp}.${input.body}`)}`;
26
- }
27
-
28
- export interface VerifyWebhookSignatureInput {
29
- secret: string;
30
- /** The raw request body, exactly as received. */
31
- body: string;
32
- /** `X-CriticalPath-Timestamp` header (Unix seconds). */
33
- timestamp: string | number;
34
- /** `X-CriticalPath-Signature` header. */
35
- signature: string;
36
- /** Reject deliveries older or newer than this many seconds (replay protection). Default 300. */
37
- toleranceSeconds?: number;
38
- /** Current time in milliseconds, for tests. */
39
- now?: number;
40
- }
41
-
42
- /** Verifies a delivery in a webhook receiver. */
43
- export async function verifyWebhookSignature(input: VerifyWebhookSignatureInput): Promise<boolean> {
44
- const timestamp = Number(input.timestamp);
45
- if (!Number.isFinite(timestamp)) return false;
46
- const tolerance = input.toleranceSeconds ?? 300;
47
- const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000);
48
- if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
49
- const expected = await signWebhookPayload({ secret: input.secret, body: input.body, timestamp });
50
- return constantTimeEqual(expected, input.signature);
51
- }
52
-
53
- /** Generates a random signing secret (`whsec_` + 64 hex characters). */
54
- export function generateWebhookSecret(): string {
55
- const bytes = crypto.getRandomValues(new Uint8Array(32));
56
- return `whsec_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
57
- }