@critical-path/core 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +57 -21
  3. package/dist/domain/custom-fields.d.ts +9 -0
  4. package/dist/domain/custom-fields.d.ts.map +1 -0
  5. package/dist/domain/custom-fields.js +72 -0
  6. package/dist/domain/custom-fields.js.map +1 -0
  7. package/dist/domain/ddd.test.d.ts +2 -0
  8. package/dist/domain/ddd.test.d.ts.map +1 -0
  9. package/dist/domain/ddd.test.js +246 -0
  10. package/dist/domain/ddd.test.js.map +1 -0
  11. package/dist/domain/entities.d.ts +82 -0
  12. package/dist/domain/entities.d.ts.map +1 -0
  13. package/dist/domain/entities.js +321 -0
  14. package/dist/domain/entities.js.map +1 -0
  15. package/dist/domain/events.d.ts +153 -0
  16. package/dist/domain/events.d.ts.map +1 -0
  17. package/dist/domain/events.js +35 -0
  18. package/dist/domain/events.js.map +1 -0
  19. package/dist/domain/graph.d.ts +19 -0
  20. package/dist/domain/graph.d.ts.map +1 -0
  21. package/dist/domain/graph.js +58 -0
  22. package/dist/domain/graph.js.map +1 -0
  23. package/dist/domain/index.d.ts +5 -0
  24. package/dist/domain/index.d.ts.map +1 -0
  25. package/dist/domain/index.js +5 -0
  26. package/dist/domain/index.js.map +1 -0
  27. package/dist/engine/index.d.ts +32 -2
  28. package/dist/engine/index.d.ts.map +1 -1
  29. package/dist/engine/index.js +416 -6
  30. package/dist/engine/index.js.map +1 -1
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +2 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/storage/file-storage.d.ts +24 -0
  36. package/dist/storage/file-storage.d.ts.map +1 -0
  37. package/dist/storage/file-storage.js +73 -0
  38. package/dist/storage/file-storage.js.map +1 -0
  39. package/dist/storage/firebase-storage.d.ts +48 -0
  40. package/dist/storage/firebase-storage.d.ts.map +1 -0
  41. package/dist/storage/firebase-storage.js +142 -0
  42. package/dist/storage/firebase-storage.js.map +1 -0
  43. package/dist/storage/index.d.ts +4 -0
  44. package/dist/storage/index.d.ts.map +1 -0
  45. package/dist/storage/index.js +4 -0
  46. package/dist/storage/index.js.map +1 -0
  47. package/dist/storage/s3.d.ts +36 -0
  48. package/dist/storage/s3.d.ts.map +1 -0
  49. package/dist/storage/s3.js +135 -0
  50. package/dist/storage/s3.js.map +1 -0
  51. package/dist/storage/storage.test.d.ts +2 -0
  52. package/dist/storage/storage.test.d.ts.map +1 -0
  53. package/dist/storage/storage.test.js +117 -0
  54. package/dist/storage/storage.test.js.map +1 -0
  55. package/dist/store/firebase.d.ts +12 -1
  56. package/dist/store/firebase.d.ts.map +1 -1
  57. package/dist/store/firebase.js +63 -1
  58. package/dist/store/firebase.js.map +1 -1
  59. package/dist/store/index.d.ts +49 -2
  60. package/dist/store/index.d.ts.map +1 -1
  61. package/dist/store/index.js +49 -0
  62. package/dist/store/index.js.map +1 -1
  63. package/dist/store/sqlite.d.ts +12 -1
  64. package/dist/store/sqlite.d.ts.map +1 -1
  65. package/dist/store/sqlite.js +128 -6
  66. package/dist/store/sqlite.js.map +1 -1
  67. package/dist/store/sqlite.test.js +47 -1
  68. package/dist/store/sqlite.test.js.map +1 -1
  69. package/dist/types/index.d.ts +57 -1
  70. package/dist/types/index.d.ts.map +1 -1
  71. package/package.json +1 -1
  72. package/src/domain/custom-fields.ts +131 -0
  73. package/src/domain/ddd.test.ts +307 -0
  74. package/src/domain/entities.ts +390 -0
  75. package/src/domain/events.ts +196 -0
  76. package/src/domain/graph.ts +70 -0
  77. package/src/domain/index.ts +4 -0
  78. package/src/engine/index.ts +518 -8
  79. package/src/index.ts +2 -0
  80. package/src/storage/file-storage.ts +96 -0
  81. package/src/storage/firebase-storage.ts +177 -0
  82. package/src/storage/index.ts +3 -0
  83. package/src/storage/s3.ts +165 -0
  84. package/src/storage/storage.test.ts +146 -0
  85. package/src/store/firebase.ts +64 -1
  86. package/src/store/index.ts +99 -11
  87. package/src/store/sqlite.test.ts +59 -1
  88. package/src/store/sqlite.ts +172 -6
  89. package/src/types/index.ts +70 -0
  90. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,131 @@
1
+ import type { CustomFieldDefinition } from '../types/index.js';
2
+
3
+ export class CustomFieldValidationError extends Error {
4
+ public readonly fieldKey: string;
5
+ public readonly expectedType?: string;
6
+ public readonly receivedValue?: unknown;
7
+
8
+ constructor(message: string, fieldKey: string, expectedType?: string, receivedValue?: unknown) {
9
+ super(message);
10
+ this.name = 'CustomFieldValidationError';
11
+ this.fieldKey = fieldKey;
12
+ this.expectedType = expectedType;
13
+ this.receivedValue = receivedValue;
14
+ }
15
+ }
16
+
17
+ export function validateCustomFieldValues(
18
+ definitions: CustomFieldDefinition[] | undefined,
19
+ values: Record<string, unknown> | undefined
20
+ ): void {
21
+ if (!definitions || definitions.length === 0) return;
22
+ const customValues = values || {};
23
+
24
+ for (const def of definitions) {
25
+ const value = customValues[def.key];
26
+
27
+ // Check required invariant
28
+ if (def.required && (value === undefined || value === null || value === '')) {
29
+ throw new CustomFieldValidationError(
30
+ `Custom field "${def.label || def.key}" (${def.key}) is required.`,
31
+ def.key,
32
+ def.type,
33
+ value
34
+ );
35
+ }
36
+
37
+ if (value === undefined || value === null) {
38
+ continue;
39
+ }
40
+
41
+ // Type and schema validation
42
+ switch (def.type) {
43
+ case 'number':
44
+ if (typeof value !== 'number' || isNaN(value)) {
45
+ throw new CustomFieldValidationError(
46
+ `Custom field "${def.label || def.key}" must be a valid number. Received: ${typeof value}`,
47
+ def.key,
48
+ 'number',
49
+ value
50
+ );
51
+ }
52
+ break;
53
+
54
+ case 'text':
55
+ case 'user':
56
+ if (typeof value !== 'string') {
57
+ throw new CustomFieldValidationError(
58
+ `Custom field "${def.label || def.key}" must be a string. Received: ${typeof value}`,
59
+ def.key,
60
+ def.type,
61
+ value
62
+ );
63
+ }
64
+ break;
65
+
66
+ case 'boolean':
67
+ if (typeof value !== 'boolean') {
68
+ throw new CustomFieldValidationError(
69
+ `Custom field "${def.label || def.key}" must be a boolean. Received: ${typeof value}`,
70
+ def.key,
71
+ 'boolean',
72
+ value
73
+ );
74
+ }
75
+ break;
76
+
77
+ case 'date':
78
+ if (typeof value !== 'string' || isNaN(new Date(value).getTime())) {
79
+ throw new CustomFieldValidationError(
80
+ `Custom field "${def.label || def.key}" must be a valid ISO date string. Received: ${JSON.stringify(value)}`,
81
+ def.key,
82
+ 'date',
83
+ value
84
+ );
85
+ }
86
+ break;
87
+
88
+ case 'single_select':
89
+ if (typeof value !== 'string') {
90
+ throw new CustomFieldValidationError(
91
+ `Custom field "${def.label || def.key}" must be a string option. Received: ${typeof value}`,
92
+ def.key,
93
+ 'single_select',
94
+ value
95
+ );
96
+ }
97
+ if (def.options && def.options.length > 0 && !def.options.includes(value)) {
98
+ throw new CustomFieldValidationError(
99
+ `Custom field "${def.label || def.key}" value "${value}" is not an allowed option [${def.options.join(', ')}].`,
100
+ def.key,
101
+ 'single_select',
102
+ value
103
+ );
104
+ }
105
+ break;
106
+
107
+ case 'multi_select':
108
+ if (!Array.isArray(value)) {
109
+ throw new CustomFieldValidationError(
110
+ `Custom field "${def.label || def.key}" must be an array of string options. Received: ${typeof value}`,
111
+ def.key,
112
+ 'multi_select',
113
+ value
114
+ );
115
+ }
116
+ if (def.options && def.options.length > 0) {
117
+ for (const item of value) {
118
+ if (typeof item !== 'string' || !def.options.includes(item)) {
119
+ throw new CustomFieldValidationError(
120
+ `Custom field "${def.label || def.key}" option "${item}" is not allowed in [${def.options.join(', ')}].`,
121
+ def.key,
122
+ 'multi_select',
123
+ item
124
+ );
125
+ }
126
+ }
127
+ }
128
+ break;
129
+ }
130
+ }
131
+ }
@@ -0,0 +1,307 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import {
3
+ CriticalPathEngine,
4
+ TaskEntity,
5
+ ProjectEntity,
6
+ DomainEventBus,
7
+ CircularDependencyError,
8
+ CustomFieldValidationError,
9
+ DEFAULT_SOFTWARE_WORKFLOW,
10
+ detectDependencyCycle,
11
+ validateCustomFieldValues,
12
+ type CustomFieldDefinition,
13
+ type TaskStatusChangedEvent,
14
+ type TimeLoggedEvent
15
+ } from '../index.js';
16
+
17
+ describe('Domain-Driven Design (DDD) Enhancements Suite', () => {
18
+ describe('Domain Event Bus & Typed Events', () => {
19
+ it('publishes and subscribes to typed domain events', async () => {
20
+ const bus = new DomainEventBus();
21
+ const statusChangedHandler = vi.fn();
22
+ const wildcardHandler = vi.fn();
23
+
24
+ const unsubscribe = bus.subscribe<TaskStatusChangedEvent>('task.status_changed', statusChangedHandler);
25
+ bus.subscribe('*', wildcardHandler);
26
+
27
+ const sampleEvent: TaskStatusChangedEvent = {
28
+ id: 'evt_123',
29
+ name: 'task.status_changed',
30
+ aggregateId: 'task_1',
31
+ aggregateType: 'Task',
32
+ occurredAt: new Date().toISOString(),
33
+ payload: {
34
+ task: {
35
+ id: 'task_1',
36
+ projectId: 'proj_1',
37
+ title: 'Sample Task',
38
+ status: 'in_progress',
39
+ priority: 'high',
40
+ createdAt: '2026-01-01T00:00:00Z',
41
+ updatedAt: '2026-01-01T00:00:00Z'
42
+ },
43
+ previousStatus: 'todo',
44
+ newStatus: 'in_progress'
45
+ }
46
+ };
47
+
48
+ await bus.publish(sampleEvent);
49
+
50
+ expect(statusChangedHandler).toHaveBeenCalledWith(sampleEvent);
51
+ expect(wildcardHandler).toHaveBeenCalledWith(sampleEvent);
52
+
53
+ unsubscribe();
54
+ await bus.publish(sampleEvent);
55
+ expect(statusChangedHandler).toHaveBeenCalledTimes(1);
56
+ expect(wildcardHandler).toHaveBeenCalledTimes(2);
57
+ });
58
+
59
+ it('publishes domain events from CriticalPathEngine during aggregate mutations', async () => {
60
+ const engine = new CriticalPathEngine();
61
+ const taskCreatedEvents: any[] = [];
62
+ const statusChangedEvents: any[] = [];
63
+ const timeLoggedEvents: any[] = [];
64
+
65
+ engine.events.subscribe('task.created', (evt) => {
66
+ taskCreatedEvents.push(evt);
67
+ });
68
+ engine.events.subscribe('task.status_changed', (evt) => {
69
+ statusChangedEvents.push(evt);
70
+ });
71
+ engine.events.subscribe('time.logged', (evt) => {
72
+ timeLoggedEvents.push(evt);
73
+ });
74
+
75
+ const project = await engine.createProject({
76
+ name: 'DDD Mobile App'
77
+ });
78
+
79
+ const task = await engine.createTask({
80
+ projectId: project.id,
81
+ title: 'Design Domain Aggregates',
82
+ status: 'todo'
83
+ });
84
+
85
+ expect(taskCreatedEvents.length).toBe(1);
86
+ expect(taskCreatedEvents[0].aggregateId).toBe(task.id);
87
+ expect(taskCreatedEvents[0].payload.task.title).toBe('Design Domain Aggregates');
88
+
89
+ await engine.updateTask(task.id, { status: 'in_progress' });
90
+ expect(statusChangedEvents.length).toBe(1);
91
+ expect(statusChangedEvents[0].payload.fromStatus || statusChangedEvents[0].payload.previousStatus).toBe('todo');
92
+ expect(statusChangedEvents[0].payload.toStatus || statusChangedEvents[0].payload.newStatus).toBe('in_progress');
93
+
94
+ await engine.logTime({
95
+ taskId: task.id,
96
+ hours: 3.5,
97
+ description: 'Implemented aggregate root logic'
98
+ });
99
+ expect(timeLoggedEvents.length).toBe(1);
100
+ expect(timeLoggedEvents[0].payload.timeEntry.hours).toBe(3.5);
101
+
102
+ const updatedTask = await engine.getTask(task.id);
103
+ expect(updatedTask?.loggedHours).toBe(3.5);
104
+ });
105
+ });
106
+
107
+ describe('Value Object Validation for Custom Fields', () => {
108
+ const definitions: CustomFieldDefinition[] = [
109
+ { id: 'cf_sp', key: 'storyPoints', label: 'Story Points', type: 'number', required: true },
110
+ { id: 'cf_severity', key: 'severity', label: 'Severity', type: 'single_select', options: ['low', 'medium', 'high'] },
111
+ { id: 'cf_tags', key: 'domains', label: 'Domains', type: 'multi_select', options: ['frontend', 'backend', 'devops'] },
112
+ { id: 'cf_date', key: 'targetRelease', label: 'Target Release', type: 'date' }
113
+ ];
114
+
115
+ it('passes validation when valid custom field values are provided', () => {
116
+ expect(() => {
117
+ validateCustomFieldValues(definitions, {
118
+ storyPoints: 5,
119
+ severity: 'high',
120
+ domains: ['frontend', 'backend'],
121
+ targetRelease: '2026-10-01T00:00:00.000Z'
122
+ });
123
+ }).not.toThrow();
124
+ });
125
+
126
+ it('throws CustomFieldValidationError when required field is missing', () => {
127
+ expect(() => {
128
+ validateCustomFieldValues(definitions, {
129
+ severity: 'high'
130
+ });
131
+ }).toThrow(CustomFieldValidationError);
132
+ });
133
+
134
+ it('throws CustomFieldValidationError on type mismatch or invalid option', () => {
135
+ expect(() => {
136
+ validateCustomFieldValues(definitions, {
137
+ storyPoints: 'five' as any
138
+ });
139
+ }).toThrow(CustomFieldValidationError);
140
+
141
+ expect(() => {
142
+ validateCustomFieldValues(definitions, {
143
+ storyPoints: 5,
144
+ severity: 'critical' // Not in ['low', 'medium', 'high']
145
+ });
146
+ }).toThrow(CustomFieldValidationError);
147
+
148
+ expect(() => {
149
+ validateCustomFieldValues(definitions, {
150
+ storyPoints: 5,
151
+ domains: ['frontend', 'ai'] // 'ai' not allowed
152
+ });
153
+ }).toThrow(CustomFieldValidationError);
154
+ });
155
+
156
+ it('integrates custom field validation in CriticalPathEngine task creation and update', async () => {
157
+ const engine = new CriticalPathEngine();
158
+ const project = await engine.createProject({
159
+ name: 'Strict Project',
160
+ customFieldDefinitions: definitions
161
+ });
162
+
163
+ // Fails creation due to missing required storyPoints
164
+ await expect(
165
+ engine.createTask({
166
+ projectId: project.id,
167
+ title: 'Invalid Task',
168
+ customFields: { severity: 'low' }
169
+ })
170
+ ).rejects.toThrow(CustomFieldValidationError);
171
+
172
+ // Successfully creates with valid fields
173
+ const validTask = await engine.createTask({
174
+ projectId: project.id,
175
+ title: 'Valid Task',
176
+ customFields: { storyPoints: 8, severity: 'medium' }
177
+ });
178
+ expect(validTask.id).toBeDefined();
179
+
180
+ // Fails update with invalid option
181
+ await expect(
182
+ engine.updateTask(validTask.id, {
183
+ customFields: { severity: 'extreme' }
184
+ })
185
+ ).rejects.toThrow(CustomFieldValidationError);
186
+ });
187
+ });
188
+
189
+ describe('DAG Cycle Detection & Graph Invariant Protection', () => {
190
+ it('detects self-dependency cycles', () => {
191
+ const result = detectDependencyCycle([], { taskId: 'task_1', dependsOnTaskId: 'task_1' });
192
+ expect(result.hasCycle).toBe(true);
193
+ });
194
+
195
+ it('detects multi-node transitive cycles', () => {
196
+ // Existing: A -> B, B -> C
197
+ const existing = [
198
+ { id: '1', taskId: 'task_A', dependsOnTaskId: 'task_B', type: 'blocking' as const },
199
+ { id: '2', taskId: 'task_B', dependsOnTaskId: 'task_C', type: 'blocking' as const }
200
+ ];
201
+
202
+ // Try to add C -> A (creates C -> A -> B -> C cycle)
203
+ const result = detectDependencyCycle(existing, { taskId: 'task_C', dependsOnTaskId: 'task_A' });
204
+ expect(result.hasCycle).toBe(true);
205
+ expect(result.cyclePath).toEqual(['task_C', 'task_A', 'task_B', 'task_C']);
206
+ });
207
+
208
+ it('allows valid acyclic dependencies', () => {
209
+ const existing = [
210
+ { id: '1', taskId: 'task_A', dependsOnTaskId: 'task_B', type: 'blocking' as const },
211
+ { id: '2', taskId: 'task_B', dependsOnTaskId: 'task_C', type: 'blocking' as const }
212
+ ];
213
+
214
+ // Add A -> D (valid DAG)
215
+ const result = detectDependencyCycle(existing, { taskId: 'task_A', dependsOnTaskId: 'task_D' });
216
+ expect(result.hasCycle).toBe(false);
217
+ });
218
+
219
+ it('throws CircularDependencyError when engine.addDependency attempts to create a cycle', async () => {
220
+ const engine = new CriticalPathEngine();
221
+ const project = await engine.createProject({ name: 'Graph Test' });
222
+
223
+ const taskA = await engine.createTask({ projectId: project.id, title: 'Task A' });
224
+ const taskB = await engine.createTask({ projectId: project.id, title: 'Task B' });
225
+ const taskC = await engine.createTask({ projectId: project.id, title: 'Task C' });
226
+
227
+ await engine.addDependency({
228
+ taskId: taskA.id,
229
+ dependsOnTaskId: taskB.id,
230
+ type: 'blocking'
231
+ });
232
+
233
+ await engine.addDependency({
234
+ taskId: taskB.id,
235
+ dependsOnTaskId: taskC.id,
236
+ type: 'blocking'
237
+ });
238
+
239
+ // Attempt circular dependency: C depends on A
240
+ await expect(
241
+ engine.addDependency({
242
+ taskId: taskC.id,
243
+ dependsOnTaskId: taskA.id,
244
+ type: 'blocking'
245
+ })
246
+ ).rejects.toThrow(CircularDependencyError);
247
+ });
248
+ });
249
+
250
+ describe('Rich Domain Aggregates (TaskEntity & ProjectEntity)', () => {
251
+ it('encapsulates state transitions, timestamps, and raises uncommitted domain events', () => {
252
+ const task = TaskEntity.create({
253
+ projectId: 'proj_1',
254
+ title: 'Rich Entity Task',
255
+ status: 'todo',
256
+ priority: 'high'
257
+ });
258
+
259
+ expect(task.getUncommittedEvents().length).toBe(1);
260
+ expect(task.getUncommittedEvents()[0].name).toBe('task.created');
261
+ task.clearEvents();
262
+
263
+ // Transition to in_progress
264
+ task.transitionTo('in_progress', DEFAULT_SOFTWARE_WORKFLOW);
265
+ expect(task.status).toBe('in_progress');
266
+ expect(task.actualStartDate).toBeDefined();
267
+ expect(task.getUncommittedEvents().length).toBe(1);
268
+ expect(task.getUncommittedEvents()[0].name).toBe('task.status_changed');
269
+ task.clearEvents();
270
+
271
+ // Log time
272
+ task.logTime({ hours: 4.5, isBillable: true });
273
+ expect(task.loggedHours).toBe(4.5);
274
+ expect(task.billableHours).toBe(4.5);
275
+ expect(task.getUncommittedEvents().length).toBe(1);
276
+ expect(task.getUncommittedEvents()[0].name).toBe('time.logged');
277
+ task.clearEvents();
278
+
279
+ // Complete task
280
+ task.transitionTo('done', DEFAULT_SOFTWARE_WORKFLOW);
281
+ expect(task.status).toBe('done');
282
+ expect(task.actualEndDate).toBeDefined();
283
+ expect(task.progress).toBe(100);
284
+ });
285
+
286
+ it('creates ProjectEntity and handles key generation and custom field validation', () => {
287
+ const project = ProjectEntity.create({
288
+ name: 'Critical Path Core',
289
+ customFieldDefinitions: [
290
+ { id: 'cf_client', key: 'clientName', label: 'Client Name', type: 'text', required: true }
291
+ ]
292
+ });
293
+
294
+ expect(project.key).toBe('CPC');
295
+ expect(project.getUncommittedEvents().length).toBe(1);
296
+ expect(project.getUncommittedEvents()[0].name).toBe('project.created');
297
+
298
+ expect(() => {
299
+ project.validateCustomFields({});
300
+ }).toThrow(CustomFieldValidationError);
301
+
302
+ expect(() => {
303
+ project.validateCustomFields({ clientName: 'Acme Corp' });
304
+ }).not.toThrow();
305
+ });
306
+ });
307
+ });