business-as-code 2.0.1 → 2.1.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.
package/src/service.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Service definition and management
3
+ */
4
+ /**
5
+ * Define a service with pricing, SLA, and delivery information
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const service = Service({
10
+ * name: 'Widget Consulting',
11
+ * description: 'Expert widget implementation and optimization',
12
+ * category: 'Consulting',
13
+ * targetSegment: 'Enterprise',
14
+ * valueProposition: 'Get expert help implementing widgets in 2 weeks',
15
+ * pricingModel: 'fixed',
16
+ * price: 5000,
17
+ * currency: 'USD',
18
+ * deliveryTime: '2 weeks',
19
+ * sla: {
20
+ * uptime: 99.9,
21
+ * responseTime: '< 24 hours',
22
+ * supportHours: 'Business hours (9-5 EST)',
23
+ * penalties: '10% refund per day of delay',
24
+ * },
25
+ * })
26
+ * ```
27
+ */
28
+ export function Service(definition) {
29
+ if (!definition.name) {
30
+ throw new Error('Service name is required');
31
+ }
32
+ return {
33
+ ...definition,
34
+ pricingModel: definition.pricingModel || 'hourly',
35
+ currency: definition.currency || 'USD',
36
+ metadata: definition.metadata || {},
37
+ };
38
+ }
39
+ /**
40
+ * Calculate service price based on hours (for hourly pricing)
41
+ */
42
+ export function calculateHourlyPrice(service, hours) {
43
+ if (service.pricingModel !== 'hourly' || !service.price) {
44
+ throw new Error('Service must use hourly pricing model');
45
+ }
46
+ return service.price * hours;
47
+ }
48
+ /**
49
+ * Calculate monthly retainer equivalent
50
+ */
51
+ export function calculateMonthlyRetainer(service, hoursPerMonth) {
52
+ if (service.pricingModel !== 'hourly' || !service.price) {
53
+ throw new Error('Service must use hourly pricing model');
54
+ }
55
+ return service.price * hoursPerMonth;
56
+ }
57
+ /**
58
+ * Check if service meets SLA uptime requirement
59
+ */
60
+ export function checkSLAUptime(service, actualUptime) {
61
+ if (!service.sla?.uptime)
62
+ return true;
63
+ return actualUptime >= service.sla.uptime;
64
+ }
65
+ /**
66
+ * Parse delivery time to days
67
+ */
68
+ export function parseDeliveryTimeToDays(deliveryTime) {
69
+ if (!deliveryTime)
70
+ return 0;
71
+ const lower = deliveryTime.toLowerCase();
72
+ // Parse patterns like "2 weeks", "3 days", "1 month"
73
+ const match = lower.match(/(\d+)\s*(day|days|week|weeks|month|months|hour|hours)/);
74
+ if (!match)
75
+ return 0;
76
+ const value = parseInt(match[1] || '0', 10);
77
+ const unit = match[2];
78
+ switch (unit) {
79
+ case 'hour':
80
+ case 'hours':
81
+ return value / 24;
82
+ case 'day':
83
+ case 'days':
84
+ return value;
85
+ case 'week':
86
+ case 'weeks':
87
+ return value * 7;
88
+ case 'month':
89
+ case 'months':
90
+ return value * 30;
91
+ default:
92
+ return 0;
93
+ }
94
+ }
95
+ /**
96
+ * Estimate service completion date
97
+ */
98
+ export function estimateCompletionDate(service, startDate) {
99
+ const start = startDate || new Date();
100
+ const days = parseDeliveryTimeToDays(service.deliveryTime);
101
+ const completion = new Date(start);
102
+ completion.setDate(completion.getDate() + days);
103
+ return completion;
104
+ }
105
+ /**
106
+ * Calculate service value (for value-based pricing)
107
+ */
108
+ export function calculateValueBasedPrice(service, customerValue, valueSharePercentage) {
109
+ if (service.pricingModel !== 'value-based') {
110
+ throw new Error('Service must use value-based pricing model');
111
+ }
112
+ if (valueSharePercentage < 0 || valueSharePercentage > 100) {
113
+ throw new Error('Value share percentage must be between 0 and 100');
114
+ }
115
+ return customerValue * (valueSharePercentage / 100);
116
+ }
117
+ /**
118
+ * Validate service definition
119
+ */
120
+ export function validateService(service) {
121
+ const errors = [];
122
+ if (!service.name) {
123
+ errors.push('Service name is required');
124
+ }
125
+ if (service.price && service.price < 0) {
126
+ errors.push('Service price cannot be negative');
127
+ }
128
+ if (service.sla?.uptime && (service.sla.uptime < 0 || service.sla.uptime > 100)) {
129
+ errors.push('SLA uptime must be between 0 and 100');
130
+ }
131
+ if (service.pricingModel &&
132
+ !['hourly', 'fixed', 'retainer', 'value-based'].includes(service.pricingModel)) {
133
+ errors.push('Invalid pricing model');
134
+ }
135
+ return {
136
+ valid: errors.length === 0,
137
+ errors,
138
+ };
139
+ }
package/src/types.js ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Core types for business-as-code primitives
3
+ */
4
+ export {};
package/src/vision.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Vision statement definition
3
+ */
4
+ /**
5
+ * Define a business vision statement with timeframe and success indicators
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const vision = Vision({
10
+ * statement: 'To become the world\'s most trusted widget platform',
11
+ * timeframe: '5 years',
12
+ * successIndicators: [
13
+ * '10M+ active users',
14
+ * 'Present in 50+ countries',
15
+ * 'Industry-leading NPS score',
16
+ * '$1B+ annual revenue',
17
+ * ],
18
+ * })
19
+ * ```
20
+ */
21
+ export function Vision(definition) {
22
+ // Validate required fields
23
+ if (!definition.statement) {
24
+ throw new Error('Vision statement is required');
25
+ }
26
+ // Return validated vision definition
27
+ return {
28
+ ...definition,
29
+ successIndicators: definition.successIndicators || [],
30
+ metadata: definition.metadata || {},
31
+ };
32
+ }
33
+ /**
34
+ * Check if a success indicator has been achieved
35
+ */
36
+ export function checkIndicator(vision, indicator, currentMetrics) {
37
+ // Simple check - would need more sophisticated parsing in production
38
+ return Object.entries(currentMetrics).some(([key, value]) => {
39
+ return indicator.toLowerCase().includes(key.toLowerCase()) && Boolean(value);
40
+ });
41
+ }
42
+ /**
43
+ * Calculate vision progress based on achieved indicators
44
+ */
45
+ export function calculateProgress(vision, currentMetrics) {
46
+ if (!vision.successIndicators || vision.successIndicators.length === 0) {
47
+ return 0;
48
+ }
49
+ const achieved = vision.successIndicators.filter(indicator => checkIndicator(vision, indicator, currentMetrics)).length;
50
+ return (achieved / vision.successIndicators.length) * 100;
51
+ }
52
+ /**
53
+ * Validate vision definition
54
+ */
55
+ export function validateVision(vision) {
56
+ const errors = [];
57
+ if (!vision.statement) {
58
+ errors.push('Vision statement is required');
59
+ }
60
+ if (vision.statement && vision.statement.length < 10) {
61
+ errors.push('Vision statement should be at least 10 characters');
62
+ }
63
+ return {
64
+ valid: errors.length === 0,
65
+ errors,
66
+ };
67
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Workflow definition (automation sequences)
3
+ */
4
+ /**
5
+ * Define an automated workflow with triggers and actions
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const workflow = Workflow({
10
+ * name: 'New Customer Welcome',
11
+ * description: 'Automated welcome sequence for new customers',
12
+ * trigger: {
13
+ * type: 'event',
14
+ * event: 'Customer.created',
15
+ * },
16
+ * actions: [
17
+ * {
18
+ * order: 1,
19
+ * type: 'send',
20
+ * description: 'Send welcome email',
21
+ * params: {
22
+ * template: 'welcome_email',
23
+ * to: '{{customer.email}}',
24
+ * },
25
+ * },
26
+ * {
27
+ * order: 2,
28
+ * type: 'create',
29
+ * description: 'Create onboarding task',
30
+ * params: {
31
+ * type: 'Task',
32
+ * title: 'Onboard {{customer.name}}',
33
+ * assignee: 'customer_success_team',
34
+ * },
35
+ * },
36
+ * {
37
+ * order: 3,
38
+ * type: 'wait',
39
+ * description: 'Wait 24 hours',
40
+ * params: {
41
+ * duration: '24 hours',
42
+ * },
43
+ * },
44
+ * {
45
+ * order: 4,
46
+ * type: 'notify',
47
+ * description: 'Send setup reminder',
48
+ * params: {
49
+ * channel: 'email',
50
+ * message: 'Reminder to complete setup',
51
+ * },
52
+ * condition: 'customer.setupCompleted === false',
53
+ * },
54
+ * ],
55
+ * })
56
+ * ```
57
+ */
58
+ export function Workflow(definition) {
59
+ if (!definition.name) {
60
+ throw new Error('Workflow name is required');
61
+ }
62
+ if (!definition.trigger) {
63
+ throw new Error('Workflow trigger is required');
64
+ }
65
+ return {
66
+ ...definition,
67
+ actions: definition.actions || [],
68
+ metadata: definition.metadata || {},
69
+ };
70
+ }
71
+ /**
72
+ * Get actions in execution order
73
+ */
74
+ export function getActionsInOrder(workflow) {
75
+ return [...(workflow.actions || [])].sort((a, b) => a.order - b.order);
76
+ }
77
+ /**
78
+ * Get actions by type
79
+ */
80
+ export function getActionsByType(workflow, type) {
81
+ return workflow.actions?.filter(action => action.type === type) || [];
82
+ }
83
+ /**
84
+ * Get conditional actions
85
+ */
86
+ export function getConditionalActions(workflow) {
87
+ return workflow.actions?.filter(action => action.condition) || [];
88
+ }
89
+ /**
90
+ * Add action to workflow
91
+ */
92
+ export function addAction(workflow, action) {
93
+ return {
94
+ ...workflow,
95
+ actions: [...(workflow.actions || []), action],
96
+ };
97
+ }
98
+ /**
99
+ * Remove action from workflow
100
+ */
101
+ export function removeAction(workflow, order) {
102
+ return {
103
+ ...workflow,
104
+ actions: workflow.actions?.filter(a => a.order !== order),
105
+ };
106
+ }
107
+ /**
108
+ * Update action in workflow
109
+ */
110
+ export function updateAction(workflow, order, updates) {
111
+ const actions = workflow.actions?.map(action => action.order === order ? { ...action, ...updates } : action);
112
+ return {
113
+ ...workflow,
114
+ actions,
115
+ };
116
+ }
117
+ /**
118
+ * Check if trigger is event-based
119
+ */
120
+ export function isEventTrigger(trigger) {
121
+ return trigger.type === 'event';
122
+ }
123
+ /**
124
+ * Check if trigger is schedule-based
125
+ */
126
+ export function isScheduleTrigger(trigger) {
127
+ return trigger.type === 'schedule';
128
+ }
129
+ /**
130
+ * Check if trigger is webhook-based
131
+ */
132
+ export function isWebhookTrigger(trigger) {
133
+ return trigger.type === 'webhook';
134
+ }
135
+ /**
136
+ * Parse wait duration to milliseconds
137
+ */
138
+ export function parseWaitDuration(duration) {
139
+ const match = duration.match(/(\d+)\s*(ms|millisecond|milliseconds|s|second|seconds|m|minute|minutes|h|hour|hours|d|day|days)/);
140
+ if (!match)
141
+ return 0;
142
+ const value = parseInt(match[1] || '0', 10);
143
+ const unit = match[2];
144
+ switch (unit) {
145
+ case 'ms':
146
+ case 'millisecond':
147
+ case 'milliseconds':
148
+ return value;
149
+ case 's':
150
+ case 'second':
151
+ case 'seconds':
152
+ return value * 1000;
153
+ case 'm':
154
+ case 'minute':
155
+ case 'minutes':
156
+ return value * 60 * 1000;
157
+ case 'h':
158
+ case 'hour':
159
+ case 'hours':
160
+ return value * 60 * 60 * 1000;
161
+ case 'd':
162
+ case 'day':
163
+ case 'days':
164
+ return value * 24 * 60 * 60 * 1000;
165
+ default:
166
+ return 0;
167
+ }
168
+ }
169
+ /**
170
+ * Evaluate condition (simple implementation)
171
+ */
172
+ export function evaluateCondition(condition, context) {
173
+ // This is a simplified implementation
174
+ // In production, use a proper expression evaluator
175
+ try {
176
+ // Replace variable references with actual values
177
+ let expression = condition;
178
+ for (const [key, value] of Object.entries(context)) {
179
+ const regex = new RegExp(`\\b${key}\\b`, 'g');
180
+ expression = expression.replace(regex, JSON.stringify(value));
181
+ }
182
+ // Evaluate the expression (unsafe in production - use a proper evaluator)
183
+ return Boolean(eval(expression));
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ }
189
+ /**
190
+ * Fill template with context values
191
+ */
192
+ export function fillTemplate(template, context) {
193
+ return template.replace(/\{\{([^}]+)\}\}/g, (_, path) => {
194
+ const value = getNestedValue(context, path.trim());
195
+ return String(value ?? '');
196
+ });
197
+ }
198
+ /**
199
+ * Get nested value from object by path
200
+ */
201
+ function getNestedValue(obj, path) {
202
+ return path.split('.').reduce((acc, part) => acc?.[part], obj);
203
+ }
204
+ /**
205
+ * Validate workflow definition
206
+ */
207
+ export function validateWorkflow(workflow) {
208
+ const errors = [];
209
+ if (!workflow.name) {
210
+ errors.push('Workflow name is required');
211
+ }
212
+ if (!workflow.trigger) {
213
+ errors.push('Workflow trigger is required');
214
+ }
215
+ else {
216
+ if (workflow.trigger.type === 'event' && !workflow.trigger.event) {
217
+ errors.push('Event trigger must specify an event name');
218
+ }
219
+ if (workflow.trigger.type === 'schedule' && !workflow.trigger.schedule) {
220
+ errors.push('Schedule trigger must specify a schedule expression');
221
+ }
222
+ if (workflow.trigger.type === 'webhook' && !workflow.trigger.webhook) {
223
+ errors.push('Webhook trigger must specify a webhook URL');
224
+ }
225
+ }
226
+ if (workflow.actions) {
227
+ const orders = new Set();
228
+ for (const action of workflow.actions) {
229
+ if (!action.type) {
230
+ errors.push(`Action at order ${action.order} must have a type`);
231
+ }
232
+ if (orders.has(action.order)) {
233
+ errors.push(`Duplicate action order: ${action.order}`);
234
+ }
235
+ orders.add(action.order);
236
+ // Validate action-specific requirements
237
+ if (action.type === 'wait' && !action.params?.duration) {
238
+ errors.push(`Wait action at order ${action.order} must specify duration`);
239
+ }
240
+ }
241
+ }
242
+ return {
243
+ valid: errors.length === 0,
244
+ errors,
245
+ };
246
+ }