@contractspec/lib.example-shared-ui 6.0.16 → 6.0.18

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 (86) hide show
  1. package/.turbo/turbo-build.log +81 -81
  2. package/CHANGELOG.md +32 -0
  3. package/dist/EvolutionDashboard.js +1 -803
  4. package/dist/EvolutionSidebar.js +1 -531
  5. package/dist/LocalDataIndicator.js +1 -62
  6. package/dist/MarkdownView.js +1 -207
  7. package/dist/OverlayContextProvider.js +1 -202
  8. package/dist/PersonalizationInsights.js +1 -455
  9. package/dist/SaveToStudioButton.js +1 -73
  10. package/dist/SpecDrivenTemplateShell.js +1 -197
  11. package/dist/SpecEditorPanel.js +17 -358
  12. package/dist/TemplateShell.js +1 -189
  13. package/dist/browser/EvolutionDashboard.js +1 -803
  14. package/dist/browser/EvolutionSidebar.js +1 -531
  15. package/dist/browser/LocalDataIndicator.js +1 -62
  16. package/dist/browser/MarkdownView.js +1 -207
  17. package/dist/browser/OverlayContextProvider.js +1 -202
  18. package/dist/browser/PersonalizationInsights.js +1 -455
  19. package/dist/browser/SaveToStudioButton.js +1 -73
  20. package/dist/browser/SpecDrivenTemplateShell.js +1 -197
  21. package/dist/browser/SpecEditorPanel.js +17 -358
  22. package/dist/browser/TemplateShell.js +1 -189
  23. package/dist/browser/bundles/ExampleTemplateBundle.js +1 -85
  24. package/dist/browser/bundles/index.js +1 -85
  25. package/dist/browser/hooks/index.js +40 -1145
  26. package/dist/browser/hooks/useBehaviorTracking.js +1 -157
  27. package/dist/browser/hooks/useEvolution.js +1 -260
  28. package/dist/browser/hooks/useRegistryTemplates.js +1 -31
  29. package/dist/browser/hooks/useSpecContent.js +17 -218
  30. package/dist/browser/hooks/useWorkflowComposer.js +24 -483
  31. package/dist/browser/index.js +40 -3110
  32. package/dist/browser/lib/component-registry.js +1 -42
  33. package/dist/browser/lib/runtime-context.js +1 -15
  34. package/dist/browser/markdown/formatPresentationName.js +1 -9
  35. package/dist/browser/markdown/useMarkdownPresentation.js +1 -65
  36. package/dist/browser/utils/fetchPresentationData.js +1 -15
  37. package/dist/browser/utils/generateSpecFromTemplate.js +16 -62
  38. package/dist/browser/utils/index.js +16 -76
  39. package/dist/bundles/ExampleTemplateBundle.js +1 -85
  40. package/dist/bundles/index.js +1 -85
  41. package/dist/hooks/index.js +40 -1145
  42. package/dist/hooks/useBehaviorTracking.js +1 -157
  43. package/dist/hooks/useEvolution.js +1 -260
  44. package/dist/hooks/useRegistryTemplates.js +1 -31
  45. package/dist/hooks/useSpecContent.js +17 -218
  46. package/dist/hooks/useWorkflowComposer.js +24 -483
  47. package/dist/index.js +40 -3110
  48. package/dist/lib/component-registry.js +1 -42
  49. package/dist/lib/runtime-context.d.ts +2 -1
  50. package/dist/lib/runtime-context.js +1 -15
  51. package/dist/lib/singletons.test.d.ts +1 -0
  52. package/dist/markdown/formatPresentationName.js +1 -9
  53. package/dist/markdown/useMarkdownPresentation.js +1 -65
  54. package/dist/node/EvolutionDashboard.js +1 -803
  55. package/dist/node/EvolutionSidebar.js +1 -531
  56. package/dist/node/LocalDataIndicator.js +1 -62
  57. package/dist/node/MarkdownView.js +1 -207
  58. package/dist/node/OverlayContextProvider.js +1 -202
  59. package/dist/node/PersonalizationInsights.js +1 -455
  60. package/dist/node/SaveToStudioButton.js +1 -73
  61. package/dist/node/SpecDrivenTemplateShell.js +1 -197
  62. package/dist/node/SpecEditorPanel.js +17 -358
  63. package/dist/node/TemplateShell.js +1 -189
  64. package/dist/node/bundles/ExampleTemplateBundle.js +1 -85
  65. package/dist/node/bundles/index.js +1 -85
  66. package/dist/node/hooks/index.js +40 -1145
  67. package/dist/node/hooks/useBehaviorTracking.js +1 -157
  68. package/dist/node/hooks/useEvolution.js +1 -260
  69. package/dist/node/hooks/useRegistryTemplates.js +1 -31
  70. package/dist/node/hooks/useSpecContent.js +17 -218
  71. package/dist/node/hooks/useWorkflowComposer.js +24 -483
  72. package/dist/node/index.js +40 -3110
  73. package/dist/node/lib/component-registry.js +1 -42
  74. package/dist/node/lib/runtime-context.js +1 -15
  75. package/dist/node/markdown/formatPresentationName.js +1 -9
  76. package/dist/node/markdown/useMarkdownPresentation.js +1 -65
  77. package/dist/node/utils/fetchPresentationData.js +1 -15
  78. package/dist/node/utils/generateSpecFromTemplate.js +16 -62
  79. package/dist/node/utils/index.js +16 -76
  80. package/dist/utils/fetchPresentationData.js +1 -15
  81. package/dist/utils/generateSpecFromTemplate.js +16 -62
  82. package/dist/utils/index.js +16 -76
  83. package/package.json +14 -14
  84. package/src/lib/component-registry.tsx +16 -1
  85. package/src/lib/runtime-context.tsx +17 -3
  86. package/src/lib/singletons.test.ts +51 -0
@@ -1,454 +1,5 @@
1
- // src/hooks/useEvolution.ts
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
- "use client";
4
- var EVOLUTION_STORAGE_KEY = "contractspec-evolution-data";
5
- function useEvolution(templateId) {
6
- const [usageStats, setUsageStats] = useState([]);
7
- const [anomalies, setAnomalies] = useState([]);
8
- const [suggestions, setSuggestions] = useState([]);
9
- const [hints, setHints] = useState([]);
10
- const [loading, setLoading] = useState(false);
11
- const metricsRef = useRef([]);
12
- const [operationCount, setOperationCount] = useState(0);
13
- useEffect(() => {
14
- try {
15
- const stored = localStorage.getItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
16
- if (stored) {
17
- const data = JSON.parse(stored);
18
- setSuggestions(data.suggestions.map((s) => ({
19
- ...s,
20
- createdAt: new Date(s.createdAt)
21
- })));
22
- }
23
- } catch {}
24
- }, [templateId]);
25
- useEffect(() => {
26
- try {
27
- localStorage.setItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`, JSON.stringify({ suggestions }));
28
- } catch {}
29
- }, [suggestions, templateId]);
30
- const trackOperation = useCallback((operationName, durationMs, success, errorCode) => {
31
- const sample = {
32
- operation: {
33
- name: operationName,
34
- version: "1.0.0",
35
- tenantId: "sandbox"
36
- },
37
- durationMs,
38
- success,
39
- timestamp: new Date,
40
- errorCode
41
- };
42
- metricsRef.current.push(sample);
43
- setOperationCount((prev) => prev + 1);
44
- }, []);
45
- const analyzeUsage = useCallback(() => {
46
- const samples = metricsRef.current;
47
- if (samples.length < 5)
48
- return;
49
- const groups = new Map;
50
- for (const sample of samples) {
51
- const key = `${sample.operation.name}.v${sample.operation.version}`;
52
- const arr = groups.get(key) ?? [];
53
- arr.push(sample);
54
- groups.set(key, arr);
55
- }
56
- const stats = [];
57
- const detectedAnomalies = [];
58
- groups.forEach((opSamples) => {
59
- if (opSamples.length < 3)
60
- return;
61
- const durations = opSamples.map((s) => s.durationMs).sort((a, b) => a - b);
62
- const errors = opSamples.filter((s) => !s.success);
63
- const totalCalls = opSamples.length;
64
- const errorRate = errors.length / totalCalls;
65
- const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
66
- const timestamps = opSamples.map((s) => s.timestamp.getTime());
67
- const firstSample = opSamples[0];
68
- if (!firstSample)
69
- return;
70
- const stat = {
71
- operation: firstSample.operation,
72
- totalCalls,
73
- successRate: 1 - errorRate,
74
- errorRate,
75
- averageLatencyMs,
76
- p95LatencyMs: percentile(durations, 0.95),
77
- p99LatencyMs: percentile(durations, 0.99),
78
- maxLatencyMs: Math.max(...durations),
79
- lastSeenAt: new Date(Math.max(...timestamps)),
80
- windowStart: new Date(Math.min(...timestamps)),
81
- windowEnd: new Date(Math.max(...timestamps)),
82
- topErrors: errors.reduce((acc, s) => {
83
- if (s.errorCode) {
84
- acc[s.errorCode] = (acc[s.errorCode] ?? 0) + 1;
85
- }
86
- return acc;
87
- }, {})
88
- };
89
- stats.push(stat);
90
- if (errorRate > 0.1) {
91
- detectedAnomalies.push({
92
- operation: stat.operation,
93
- severity: errorRate > 0.3 ? "high" : errorRate > 0.2 ? "medium" : "low",
94
- metric: "error-rate",
95
- description: `Error rate ${(errorRate * 100).toFixed(1)}% exceeds threshold`,
96
- detectedAt: new Date,
97
- threshold: 0.1,
98
- observedValue: errorRate
99
- });
100
- }
101
- if (stat.p99LatencyMs > 500) {
102
- detectedAnomalies.push({
103
- operation: stat.operation,
104
- severity: stat.p99LatencyMs > 1000 ? "high" : stat.p99LatencyMs > 750 ? "medium" : "low",
105
- metric: "latency",
106
- description: `P99 latency ${stat.p99LatencyMs.toFixed(0)}ms exceeds threshold`,
107
- detectedAt: new Date,
108
- threshold: 500,
109
- observedValue: stat.p99LatencyMs
110
- });
111
- }
112
- });
113
- setUsageStats(stats);
114
- setAnomalies(detectedAnomalies);
115
- const newHints = detectedAnomalies.map((anomaly) => ({
116
- operation: anomaly.operation,
117
- category: anomaly.metric === "latency" ? "performance" : "error-handling",
118
- summary: anomaly.metric === "latency" ? "Latency regression detected" : "Error spike detected",
119
- justification: anomaly.description,
120
- recommendedActions: anomaly.metric === "latency" ? [
121
- "Add caching layer",
122
- "Optimize database queries",
123
- "Consider pagination"
124
- ] : [
125
- "Add retry logic",
126
- "Improve error handling",
127
- "Add circuit breaker"
128
- ]
129
- }));
130
- setHints(newHints);
131
- }, []);
132
- const generateSuggestions = useCallback(async () => {
133
- if (anomalies.length === 0)
134
- return;
135
- setLoading(true);
136
- await new Promise((resolve) => setTimeout(resolve, 800));
137
- const newSuggestions = anomalies.map((anomaly) => ({
138
- id: `suggestion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
139
- intent: {
140
- id: `intent-${anomaly.operation.name}`,
141
- type: anomaly.metric === "latency" ? "latency-regression" : anomaly.metric === "error-rate" ? "error-spike" : "throughput-drop",
142
- description: anomaly.description,
143
- operation: anomaly.operation,
144
- confidence: {
145
- score: anomaly.severity === "high" ? 0.9 : anomaly.severity === "medium" ? 0.7 : 0.5,
146
- sampleSize: usageStats.find((s) => s.operation.name === anomaly.operation.name)?.totalCalls ?? 0
147
- }
148
- },
149
- target: anomaly.operation,
150
- proposal: {
151
- summary: generateSuggestionSummary(anomaly),
152
- rationale: generateSuggestionRationale(anomaly),
153
- changeType: anomaly.metric === "error-rate" ? "policy-update" : "revision",
154
- recommendedActions: generateRecommendedActions(anomaly)
155
- },
156
- confidence: anomaly.severity === "high" ? 0.85 : anomaly.severity === "medium" ? 0.7 : 0.55,
157
- createdAt: new Date,
158
- createdBy: "ai-evolution-agent",
159
- status: "pending",
160
- priority: anomaly.severity
161
- }));
162
- setSuggestions((prev) => [...prev, ...newSuggestions]);
163
- setLoading(false);
164
- }, [anomalies, usageStats]);
165
- const approveSuggestion = useCallback((id, _notes) => {
166
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "approved" } : s));
167
- }, []);
168
- const rejectSuggestion = useCallback((id, _notes) => {
169
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "rejected" } : s));
170
- }, []);
171
- const clear = useCallback(() => {
172
- metricsRef.current = [];
173
- setOperationCount(0);
174
- setUsageStats([]);
175
- setAnomalies([]);
176
- setSuggestions([]);
177
- setHints([]);
178
- localStorage.removeItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
179
- }, [templateId]);
180
- return useMemo(() => ({
181
- usageStats,
182
- anomalies,
183
- suggestions,
184
- hints,
185
- loading,
186
- trackOperation,
187
- analyzeUsage,
188
- generateSuggestions,
189
- approveSuggestion,
190
- rejectSuggestion,
191
- clear,
192
- operationCount
193
- }), [
194
- usageStats,
195
- anomalies,
196
- suggestions,
197
- hints,
198
- loading,
199
- trackOperation,
200
- analyzeUsage,
201
- generateSuggestions,
202
- approveSuggestion,
203
- rejectSuggestion,
204
- clear,
205
- operationCount
206
- ]);
207
- }
208
- function percentile(values, p) {
209
- if (!values.length)
210
- return 0;
211
- if (values.length === 1)
212
- return values[0] ?? 0;
213
- const idx = Math.min(values.length - 1, Math.floor(p * values.length));
214
- return values[idx] ?? 0;
215
- }
216
- function generateSuggestionSummary(anomaly) {
217
- if (anomaly.metric === "latency") {
218
- return `Add caching and pagination to ${anomaly.operation.name} to reduce latency`;
219
- }
220
- if (anomaly.metric === "error-rate") {
221
- return `Add retry policy and circuit breaker to ${anomaly.operation.name}`;
222
- }
223
- return `Optimize ${anomaly.operation.name} for improved throughput`;
224
- }
225
- function generateSuggestionRationale(anomaly) {
226
- if (anomaly.metric === "latency") {
227
- return `The operation ${anomaly.operation.name} is experiencing P99 latency of ${anomaly.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${anomaly.threshold}ms. This can impact user experience and downstream operations.`;
228
- }
229
- if (anomaly.metric === "error-rate") {
230
- return `The error rate for ${anomaly.operation.name} is ${((anomaly.observedValue ?? 0) * 100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;
231
- }
232
- return `Throughput for ${anomaly.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`;
233
- }
234
- function generateRecommendedActions(anomaly) {
235
- if (anomaly.metric === "latency") {
236
- return [
237
- "Add response caching for frequently accessed data",
238
- "Implement pagination for large result sets",
239
- "Optimize database queries with proper indexing",
240
- "Consider adding a GraphQL DataLoader for batching"
241
- ];
242
- }
243
- if (anomaly.metric === "error-rate") {
244
- return [
245
- "Add input validation at the contract level",
246
- "Implement retry policy with exponential backoff",
247
- "Add circuit breaker for external dependencies",
248
- "Enhance error logging for better debugging"
249
- ];
250
- }
251
- return [
252
- "Review resource allocation and scaling policies",
253
- "Check for upstream routing or load balancer issues",
254
- "Validate feature flag configurations",
255
- "Monitor dependency health metrics"
256
- ];
257
- }
258
-
259
- // src/lib/runtime-context.tsx
260
- import { createContext, useContext } from "react";
261
- "use client";
262
- var TemplateRuntimeContext = createContext(null);
263
- function useTemplateRuntime() {
264
- const context = useContext(TemplateRuntimeContext);
265
- if (!context) {
266
- throw new Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");
267
- }
268
- return context;
269
- }
270
-
271
- // src/hooks/useBehaviorTracking.ts
272
- import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
273
- "use client";
274
- var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
275
- var ALL_FEATURES = [
276
- "playground",
277
- "specs",
278
- "builder",
279
- "markdown",
280
- "evolution",
281
- "canvas_add",
282
- "canvas_delete",
283
- "spec_save",
284
- "spec_validate",
285
- "ai_suggestions"
286
- ];
287
- function useBehaviorTracking(templateId) {
288
- const [events, setEvents] = useState2([]);
289
- const sessionStartRef = useRef2(new Date);
290
- const [eventCount, setEventCount] = useState2(0);
291
- useEffect2(() => {
292
- try {
293
- const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
294
- if (stored) {
295
- const data = JSON.parse(stored);
296
- setEvents(data.events.map((e) => ({
297
- ...e,
298
- timestamp: new Date(e.timestamp)
299
- })));
300
- sessionStartRef.current = new Date(data.sessionStart);
301
- }
302
- } catch {}
303
- }, []);
304
- useEffect2(() => {
305
- if (events.length > 0) {
306
- try {
307
- localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
308
- events: events.map((e) => ({
309
- ...e,
310
- timestamp: e.timestamp.toISOString()
311
- })),
312
- sessionStart: sessionStartRef.current.toISOString()
313
- }));
314
- } catch {}
315
- }
316
- }, [events]);
317
- const trackEvent = useCallback2((type, metadata) => {
318
- const event = {
319
- type,
320
- timestamp: new Date,
321
- templateId,
322
- metadata
323
- };
324
- setEvents((prev) => [...prev, event]);
325
- setEventCount((prev) => prev + 1);
326
- }, [templateId]);
327
- const getEventsByType = useCallback2((type) => {
328
- return events.filter((e) => e.type === type);
329
- }, [events]);
330
- const getSummary = useCallback2(() => {
331
- const now = new Date;
332
- const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
333
- const templateCounts = new Map;
334
- for (const event of events) {
335
- const count = templateCounts.get(event.templateId) ?? 0;
336
- templateCounts.set(event.templateId, count + 1);
337
- }
338
- const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
339
- const modeCounts = new Map;
340
- for (const event of events) {
341
- if (event.type === "mode_change" && event.metadata?.mode) {
342
- const mode = event.metadata.mode;
343
- const count = modeCounts.get(mode) ?? 0;
344
- modeCounts.set(mode, count + 1);
345
- }
346
- }
347
- const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
348
- const featuresUsed = new Set;
349
- for (const event of events) {
350
- if (event.type === "mode_change" && event.metadata?.mode) {
351
- featuresUsed.add(event.metadata.mode);
352
- }
353
- if (event.type === "feature_usage" && event.metadata?.feature) {
354
- featuresUsed.add(event.metadata.feature);
355
- }
356
- if (event.type === "canvas_interaction") {
357
- const action = event.metadata?.action;
358
- if (action === "add")
359
- featuresUsed.add("canvas_add");
360
- if (action === "delete")
361
- featuresUsed.add("canvas_delete");
362
- }
363
- if (event.type === "spec_edit") {
364
- const action = event.metadata?.action;
365
- if (action === "save")
366
- featuresUsed.add("spec_save");
367
- if (action === "validate")
368
- featuresUsed.add("spec_validate");
369
- }
370
- }
371
- const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
372
- const errorCount = events.filter((e) => e.type === "error").length;
373
- const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
374
- return {
375
- totalEvents: events.length,
376
- sessionDuration,
377
- mostUsedTemplates,
378
- mostUsedModes,
379
- featuresUsed: Array.from(featuresUsed),
380
- unusedFeatures,
381
- errorCount,
382
- recommendations
383
- };
384
- }, [events]);
385
- const clear = useCallback2(() => {
386
- setEvents([]);
387
- setEventCount(0);
388
- sessionStartRef.current = new Date;
389
- localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
390
- }, []);
391
- return useMemo2(() => ({
392
- trackEvent,
393
- getSummary,
394
- getEventsByType,
395
- eventCount,
396
- sessionStart: sessionStartRef.current,
397
- clear
398
- }), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
399
- }
400
- function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
401
- const recommendations = [];
402
- if (unusedFeatures.includes("evolution")) {
403
- recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
404
- }
405
- if (unusedFeatures.includes("markdown")) {
406
- recommendations.push("Use Markdown preview to see documentation for your specs");
407
- }
408
- if (unusedFeatures.includes("builder")) {
409
- recommendations.push("Explore the Visual Builder to design your UI components");
410
- }
411
- if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
412
- recommendations.push("Don't forget to validate your specs before saving");
413
- }
414
- if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
415
- recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
416
- }
417
- if (totalEvents > 50) {
418
- recommendations.push("Great engagement! Consider saving your work regularly");
419
- }
420
- if (mostUsedModes.length === 1) {
421
- recommendations.push("Try different modes to explore all sandbox capabilities");
422
- }
423
- return recommendations;
424
- }
425
-
426
- // src/utils/generateSpecFromTemplate.ts
427
- function generateSpecFromTemplate(template) {
428
- const templateId = template?.id ?? "unknown";
429
- if (!template) {
430
- return generateDefaultSpec(templateId);
431
- }
432
- switch (templateId) {
433
- case "crm-pipeline":
434
- return generateCrmPipelineSpec(template.schema.contracts);
435
- case "saas-boilerplate":
436
- return generateSaasBoilerplateSpec(template.schema.contracts);
437
- case "agent-console":
438
- return generateAgentConsoleSpec(template.schema.contracts);
439
- case "todos-app":
440
- return generateTodosSpec(template.schema.contracts);
441
- case "messaging-app":
442
- return generateMessagingSpec(template.schema.contracts);
443
- case "recipe-app-i18n":
444
- return generateRecipeSpec(template.schema.contracts);
445
- default:
446
- return generateDefaultSpec(templateId);
447
- }
448
- }
449
- function generateCrmPipelineSpec(contracts) {
450
- return `// CRM Pipeline Specs
451
- // Contracts: ${contracts.join(", ")}
1
+ import{useCallback as k,useEffect as l,useMemo as $q,useRef as Jq,useState as x}from"react";var c="contractspec-evolution-data";function bq(q){let[Z,X]=x([]),[z,D]=x([]),[H,B]=x([]),[_,T]=x([]),[L,j]=x(!1),G=Jq([]),[F,W]=x(0);l(()=>{try{let $=localStorage.getItem(`${c}-${q}`);if($){let J=JSON.parse($);B(J.suggestions.map((P)=>({...P,createdAt:new Date(P.createdAt)})))}}catch{}},[q]),l(()=>{try{localStorage.setItem(`${c}-${q}`,JSON.stringify({suggestions:H}))}catch{}},[H,q]);let O=k(($,J,P,Y)=>{let E={operation:{name:$,version:"1.0.0",tenantId:"sandbox"},durationMs:J,success:P,timestamp:new Date,errorCode:Y};G.current.push(E),W((V)=>V+1)},[]),A=k(()=>{let $=G.current;if($.length<5)return;let J=new Map;for(let V of $){let U=`${V.operation.name}.v${V.operation.version}`,I=J.get(U)??[];I.push(V),J.set(U,I)}let P=[],Y=[];J.forEach((V)=>{if(V.length<3)return;let U=V.map((M)=>M.durationMs).sort((M,w)=>M-w),I=V.filter((M)=>!M.success),i=V.length,b=I.length/i,qq=U.reduce((M,w)=>M+w,0)/i,u=V.map((M)=>M.timestamp.getTime()),m=V[0];if(!m)return;let R={operation:m.operation,totalCalls:i,successRate:1-b,errorRate:b,averageLatencyMs:qq,p95LatencyMs:n(U,0.95),p99LatencyMs:n(U,0.99),maxLatencyMs:Math.max(...U),lastSeenAt:new Date(Math.max(...u)),windowStart:new Date(Math.min(...u)),windowEnd:new Date(Math.max(...u)),topErrors:I.reduce((M,w)=>{if(w.errorCode)M[w.errorCode]=(M[w.errorCode]??0)+1;return M},{})};if(P.push(R),b>0.1)Y.push({operation:R.operation,severity:b>0.3?"high":b>0.2?"medium":"low",metric:"error-rate",description:`Error rate ${(b*100).toFixed(1)}% exceeds threshold`,detectedAt:new Date,threshold:0.1,observedValue:b});if(R.p99LatencyMs>500)Y.push({operation:R.operation,severity:R.p99LatencyMs>1000?"high":R.p99LatencyMs>750?"medium":"low",metric:"latency",description:`P99 latency ${R.p99LatencyMs.toFixed(0)}ms exceeds threshold`,detectedAt:new Date,threshold:500,observedValue:R.p99LatencyMs})}),X(P),D(Y);let E=Y.map((V)=>({operation:V.operation,category:V.metric==="latency"?"performance":"error-handling",summary:V.metric==="latency"?"Latency regression detected":"Error spike detected",justification:V.description,recommendedActions:V.metric==="latency"?["Add caching layer","Optimize database queries","Consider pagination"]:["Add retry logic","Improve error handling","Add circuit breaker"]}));T(E)},[]),h=k(async()=>{if(z.length===0)return;j(!0),await new Promise((J)=>setTimeout(J,800));let $=z.map((J)=>({id:`suggestion-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,intent:{id:`intent-${J.operation.name}`,type:J.metric==="latency"?"latency-regression":J.metric==="error-rate"?"error-spike":"throughput-drop",description:J.description,operation:J.operation,confidence:{score:J.severity==="high"?0.9:J.severity==="medium"?0.7:0.5,sampleSize:Z.find((P)=>P.operation.name===J.operation.name)?.totalCalls??0}},target:J.operation,proposal:{summary:Zq(J),rationale:Qq(J),changeType:J.metric==="error-rate"?"policy-update":"revision",recommendedActions:Xq(J)},confidence:J.severity==="high"?0.85:J.severity==="medium"?0.7:0.55,createdAt:new Date,createdBy:"ai-evolution-agent",status:"pending",priority:J.severity}));B((J)=>[...J,...$]),j(!1)},[z,Z]),Q=k(($,J)=>{B((P)=>P.map((Y)=>Y.id===$?{...Y,status:"approved"}:Y))},[]),K=k(($,J)=>{B((P)=>P.map((Y)=>Y.id===$?{...Y,status:"rejected"}:Y))},[]),N=k(()=>{G.current=[],W(0),X([]),D([]),B([]),T([]),localStorage.removeItem(`${c}-${q}`)},[q]);return $q(()=>({usageStats:Z,anomalies:z,suggestions:H,hints:_,loading:L,trackOperation:O,analyzeUsage:A,generateSuggestions:h,approveSuggestion:Q,rejectSuggestion:K,clear:N,operationCount:F}),[Z,z,H,_,L,O,A,h,Q,K,N,F])}function n(q,Z){if(!q.length)return 0;if(q.length===1)return q[0]??0;let X=Math.min(q.length-1,Math.floor(Z*q.length));return q[X]??0}function Zq(q){if(q.metric==="latency")return`Add caching and pagination to ${q.operation.name} to reduce latency`;if(q.metric==="error-rate")return`Add retry policy and circuit breaker to ${q.operation.name}`;return`Optimize ${q.operation.name} for improved throughput`}function Qq(q){if(q.metric==="latency")return`The operation ${q.operation.name} is experiencing P99 latency of ${q.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${q.threshold}ms. This can impact user experience and downstream operations.`;if(q.metric==="error-rate")return`The error rate for ${q.operation.name} is ${((q.observedValue??0)*100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;return`Throughput for ${q.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`}function Xq(q){if(q.metric==="latency")return["Add response caching for frequently accessed data","Implement pagination for large result sets","Optimize database queries with proper indexing","Consider adding a GraphQL DataLoader for batching"];if(q.metric==="error-rate")return["Add input validation at the contract level","Implement retry policy with exponential backoff","Add circuit breaker for external dependencies","Enhance error logging for better debugging"];return["Review resource allocation and scaling policies","Check for upstream routing or load balancer issues","Validate feature flag configurations","Monitor dependency health metrics"]}import{createContext as zq,useContext as hq}from"react";var o=Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");function Dq(){let q=globalThis;return q[o]??=zq(null),q[o]}var Hq=Dq();function s(){let q=hq(Hq);if(!q)throw Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");return q}import{useCallback as f,useEffect as a,useMemo as jq,useRef as Pq,useState as t}from"react";var d="contractspec-behavior-data",Gq=["playground","specs","builder","markdown","evolution","canvas_add","canvas_delete","spec_save","spec_validate","ai_suggestions"];function Iq(q){let[Z,X]=t([]),z=Pq(new Date),[D,H]=t(0);a(()=>{try{let j=localStorage.getItem(d);if(j){let G=JSON.parse(j);X(G.events.map((F)=>({...F,timestamp:new Date(F.timestamp)}))),z.current=new Date(G.sessionStart)}}catch{}},[]),a(()=>{if(Z.length>0)try{localStorage.setItem(d,JSON.stringify({events:Z.map((j)=>({...j,timestamp:j.timestamp.toISOString()})),sessionStart:z.current.toISOString()}))}catch{}},[Z]);let B=f((j,G)=>{let F={type:j,timestamp:new Date,templateId:q,metadata:G};X((W)=>[...W,F]),H((W)=>W+1)},[q]),_=f((j)=>{return Z.filter((G)=>G.type===j)},[Z]),T=f(()=>{let G=new Date().getTime()-z.current.getTime(),F=new Map;for(let $ of Z){let J=F.get($.templateId)??0;F.set($.templateId,J+1)}let W=Array.from(F.entries()).map(([$,J])=>({templateId:$,count:J})).sort(($,J)=>J.count-$.count).slice(0,3),O=new Map;for(let $ of Z)if($.type==="mode_change"&&$.metadata?.mode){let J=$.metadata.mode,P=O.get(J)??0;O.set(J,P+1)}let A=Array.from(O.entries()).map(([$,J])=>({mode:$,count:J})).sort(($,J)=>J.count-$.count),h=new Set;for(let $ of Z){if($.type==="mode_change"&&$.metadata?.mode)h.add($.metadata.mode);if($.type==="feature_usage"&&$.metadata?.feature)h.add($.metadata.feature);if($.type==="canvas_interaction"){let J=$.metadata?.action;if(J==="add")h.add("canvas_add");if(J==="delete")h.add("canvas_delete")}if($.type==="spec_edit"){let J=$.metadata?.action;if(J==="save")h.add("spec_save");if(J==="validate")h.add("spec_validate")}}let Q=Gq.filter(($)=>!h.has($)),K=Z.filter(($)=>$.type==="error").length,N=Vq(Array.from(h),Q,A,Z.length);return{totalEvents:Z.length,sessionDuration:G,mostUsedTemplates:W,mostUsedModes:A,featuresUsed:Array.from(h),unusedFeatures:Q,errorCount:K,recommendations:N}},[Z]),L=f(()=>{X([]),H(0),z.current=new Date,localStorage.removeItem(d)},[]);return jq(()=>({trackEvent:B,getSummary:T,getEventsByType:_,eventCount:D,sessionStart:z.current,clear:L}),[B,T,_,D,L])}function Vq(q,Z,X,z){let D=[];if(Z.includes("evolution"))D.push("Try the AI Evolution mode to get automated improvement suggestions");if(Z.includes("markdown"))D.push("Use Markdown preview to see documentation for your specs");if(Z.includes("builder"))D.push("Explore the Visual Builder to design your UI components");if(!q.includes("spec_validate")&&q.includes("specs"))D.push("Don't forget to validate your specs before saving");if(q.includes("evolution")&&!q.includes("ai_suggestions"))D.push("Generate AI suggestions to get actionable improvement recommendations");if(z>50)D.push("Great engagement! Consider saving your work regularly");if(X.length===1)D.push("Try different modes to explore all sandbox capabilities");return D}function C(q){let Z=q?.id??"unknown";if(!q)return e(Z);switch(Z){case"crm-pipeline":return Kq(q.schema.contracts);case"saas-boilerplate":return Yq(q.schema.contracts);case"agent-console":return Fq(q.schema.contracts);case"todos-app":return Lq(q.schema.contracts);case"messaging-app":return Nq(q.schema.contracts);case"recipe-app-i18n":return Bq(q.schema.contracts);default:return e(Z)}}function Kq(q){return`// CRM Pipeline Specs
2
+ // Contracts: ${q.join(", ")}
452
3
 
453
4
  contractSpec("crm.deal.updateStage.v1", {
454
5
  goal: "Move a deal to a different pipeline stage",
@@ -517,11 +68,8 @@ contractSpec("crm.contact.list.v1", {
517
68
  hasMore: "boolean"
518
69
  }
519
70
  }
520
- });`;
521
- }
522
- function generateSaasBoilerplateSpec(contracts) {
523
- return `// SaaS Boilerplate Specs
524
- // Contracts: ${contracts.join(", ")}
71
+ });`}function Yq(q){return`// SaaS Boilerplate Specs
72
+ // Contracts: ${q.join(", ")}
525
73
 
526
74
  contractSpec("saas.project.create.v1", {
527
75
  goal: "Create a new project in an organization",
@@ -584,11 +132,8 @@ contractSpec("saas.settings.update.v1", {
584
132
  }
585
133
  },
586
134
  events: ["settings.updated"]
587
- });`;
588
- }
589
- function generateAgentConsoleSpec(contracts) {
590
- return `// Agent Console Specs
591
- // Contracts: ${contracts.join(", ")}
135
+ });`}function Fq(q){return`// Agent Console Specs
136
+ // Contracts: ${q.join(", ")}
592
137
 
593
138
  contractSpec("agent.run.execute.v1", {
594
139
  goal: "Execute an agent run with specified tools",
@@ -654,11 +199,8 @@ contractSpec("agent.agent.create.v1", {
654
199
  }
655
200
  },
656
201
  events: ["agent.created"]
657
- });`;
658
- }
659
- function generateTodosSpec(contracts) {
660
- return `// To-dos App Specs
661
- // Contracts: ${contracts.join(", ")}
202
+ });`}function Lq(q){return`// To-dos App Specs
203
+ // Contracts: ${q.join(", ")}
662
204
 
663
205
  contractSpec("tasks.board.v1", {
664
206
  goal: "Assign and approve craft work",
@@ -717,11 +259,8 @@ contractSpec("tasks.complete.v1", {
717
259
  }
718
260
  },
719
261
  events: ["task.completed"]
720
- });`;
721
- }
722
- function generateMessagingSpec(contracts) {
723
- return `// Messaging App Specs
724
- // Contracts: ${contracts.join(", ")}
262
+ });`}function Nq(q){return`// Messaging App Specs
263
+ // Contracts: ${q.join(", ")}
725
264
 
726
265
  contractSpec("messaging.send.v1", {
727
266
  goal: "Deliver intent-rich updates",
@@ -774,11 +313,8 @@ contractSpec("messaging.read.v1", {
774
313
  }
775
314
  },
776
315
  events: ["message.read"]
777
- });`;
778
- }
779
- function generateRecipeSpec(contracts) {
780
- return `// Recipe App (i18n) Specs
781
- // Contracts: ${contracts.join(", ")}
316
+ });`}function Bq(q){return`// Recipe App (i18n) Specs
317
+ // Contracts: ${q.join(", ")}
782
318
 
783
319
  contractSpec("recipes.lookup.v1", {
784
320
  goal: "Serve bilingual rituals",
@@ -825,13 +361,10 @@ contractSpec("recipes.favorite.toggle.v1", {
825
361
  }
826
362
  },
827
363
  events: ["recipe.favorited", "recipe.unfavorited"]
828
- });`;
829
- }
830
- function generateDefaultSpec(templateId) {
831
- return `// ${templateId} Specs
364
+ });`}function e(q){return`// ${q} Specs
832
365
 
833
- contractSpec("${templateId}.main.v1", {
834
- goal: "Main operation for ${templateId}",
366
+ contractSpec("${q}.main.v1", {
367
+ goal: "Main operation for ${q}",
835
368
  transport: { gql: { query: "main" } },
836
369
  io: {
837
370
  input: {
@@ -841,676 +374,38 @@ contractSpec("${templateId}.main.v1", {
841
374
  result: "unknown"
842
375
  }
843
376
  }
844
- });`;
845
- }
846
-
847
- // src/hooks/useSpecContent.ts
848
- import { useCallback as useCallback3, useEffect as useEffect3, useState as useState3 } from "react";
849
- "use client";
850
- var SPEC_STORAGE_KEY = "contractspec-spec-content";
851
- function useSpecContent(templateId) {
852
- const { template } = useTemplateRuntime();
853
- const [content, setContentState] = useState3("");
854
- const [savedContent, setSavedContent] = useState3("");
855
- const [loading, setLoading] = useState3(true);
856
- const [validation, setValidation] = useState3(null);
857
- const [lastSaved, setLastSaved] = useState3(null);
858
- useEffect3(() => {
859
- setLoading(true);
860
- try {
861
- const stored = localStorage.getItem(`${SPEC_STORAGE_KEY}-${templateId}`);
862
- if (stored) {
863
- const parsed = JSON.parse(stored);
864
- if (parsed.content) {
865
- setContentState(parsed.content);
866
- setSavedContent(parsed.content);
867
- setLastSaved(parsed.savedAt);
868
- } else {
869
- const generated = generateSpecFromTemplate(template);
870
- setContentState(generated);
871
- setSavedContent(generated);
872
- }
873
- } else {
874
- const generated = generateSpecFromTemplate(template);
875
- setContentState(generated);
876
- setSavedContent(generated);
877
- }
878
- } catch {
879
- const generated = generateSpecFromTemplate(template);
880
- setContentState(generated);
881
- setSavedContent(generated);
882
- }
883
- setLoading(false);
884
- }, [templateId]);
885
- const setContent = useCallback3((newContent) => {
886
- setContentState(newContent);
887
- setValidation(null);
888
- }, []);
889
- const save = useCallback3(() => {
890
- try {
891
- const savedAt = new Date().toISOString();
892
- localStorage.setItem(`${SPEC_STORAGE_KEY}-${templateId}`, JSON.stringify({
893
- content,
894
- savedAt
895
- }));
896
- setSavedContent(content);
897
- setLastSaved(savedAt);
898
- } catch {}
899
- }, [content, templateId]);
900
- const validate = useCallback3(() => {
901
- const errors = [];
902
- const lines = content.split(`
903
- `);
904
- if (!content.includes("contractSpec(")) {
905
- errors.push({
906
- line: 1,
907
- message: "Spec must contain a contractSpec() definition",
908
- severity: "error"
909
- });
910
- }
911
- if (!content.includes("goal:")) {
912
- errors.push({
913
- line: 1,
914
- message: "Spec should have a goal field",
915
- severity: "warning"
916
- });
917
- }
918
- if (!content.includes("io:")) {
919
- errors.push({
920
- line: 1,
921
- message: "Spec should define io (input/output)",
922
- severity: "warning"
923
- });
924
- }
925
- const openBraces = (content.match(/{/g) ?? []).length;
926
- const closeBraces = (content.match(/}/g) ?? []).length;
927
- if (openBraces !== closeBraces) {
928
- errors.push({
929
- line: lines.length,
930
- message: `Unbalanced braces: ${openBraces} opening, ${closeBraces} closing`,
931
- severity: "error"
932
- });
933
- }
934
- const openParens = (content.match(/\(/g) ?? []).length;
935
- const closeParens = (content.match(/\)/g) ?? []).length;
936
- if (openParens !== closeParens) {
937
- errors.push({
938
- line: lines.length,
939
- message: `Unbalanced parentheses: ${openParens} opening, ${closeParens} closing`,
940
- severity: "error"
941
- });
942
- }
943
- lines.forEach((line, index) => {
944
- const singleQuotes = (line.match(/'/g) ?? []).length;
945
- const doubleQuotes = (line.match(/"/g) ?? []).length;
946
- if (singleQuotes % 2 !== 0) {
947
- errors.push({
948
- line: index + 1,
949
- message: "Unclosed single quote",
950
- severity: "error"
951
- });
952
- }
953
- if (doubleQuotes % 2 !== 0) {
954
- errors.push({
955
- line: index + 1,
956
- message: "Unclosed double quote",
957
- severity: "error"
958
- });
959
- }
960
- });
961
- const result = {
962
- valid: errors.filter((e) => e.severity === "error").length === 0,
963
- errors
964
- };
965
- setValidation(result);
966
- return result;
967
- }, [content]);
968
- const reset = useCallback3(() => {
969
- const generated = generateSpecFromTemplate(template);
970
- setContentState(generated);
971
- setSavedContent(generated);
972
- setValidation(null);
973
- setLastSaved(null);
974
- try {
975
- localStorage.removeItem(`${SPEC_STORAGE_KEY}-${templateId}`);
976
- } catch {}
977
- }, [templateId]);
978
- return {
979
- content,
980
- loading,
981
- isDirty: content !== savedContent,
982
- validation,
983
- setContent,
984
- save,
985
- validate,
986
- reset,
987
- lastSaved
988
- };
989
- }
990
-
991
- // src/hooks/useRegistryTemplates.ts
992
- import { useQuery } from "@tanstack/react-query";
993
- function useRegistryTemplates() {
994
- return useQuery({
995
- queryKey: ["registryTemplates"],
996
- queryFn: async () => {
997
- const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
998
- if (!registryUrl)
999
- return [];
1000
- const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
1001
- method: "GET",
1002
- headers: { Accept: "application/json" }
1003
- });
1004
- if (!res.ok)
1005
- return [];
1006
- const json = await res.json();
1007
- const items = json.items ?? [];
1008
- return items.filter((i) => i.type === "contractspec:template").map((i) => ({
1009
- id: i.name,
1010
- name: i.title ?? i.name,
1011
- description: i.description,
1012
- tags: i.meta?.tags ?? [],
1013
- source: "registry",
1014
- registryUrl
1015
- }));
1016
- }
1017
- });
1018
- }
1019
-
1020
- // src/hooks/useWorkflowComposer.ts
1021
- import { useCallback as useCallback4, useEffect as useEffect4, useMemo as useMemo3, useState as useState4 } from "react";
1022
- "use client";
1023
- function useWorkflowComposer(templateId) {
1024
- const [selectedWorkflow, setSelectedWorkflow] = useState4(null);
1025
- const [extensions, setExtensions] = useState4([]);
1026
- const [loading, _setLoading] = useState4(false);
1027
- const [error, _setError] = useState4(null);
1028
- const baseWorkflows = useMemo3(() => getTemplateWorkflows(templateId), [templateId]);
1029
- useEffect4(() => {
1030
- const firstWorkflow = baseWorkflows[0];
1031
- if (baseWorkflows.length > 0 && !selectedWorkflow && firstWorkflow) {
1032
- setSelectedWorkflow(firstWorkflow.meta.key);
1033
- }
1034
- }, [baseWorkflows, selectedWorkflow]);
1035
- const currentBase = useMemo3(() => {
1036
- return baseWorkflows.find((w) => w.meta.key === selectedWorkflow) ?? null;
1037
- }, [baseWorkflows, selectedWorkflow]);
1038
- const compose = useCallback4((scope) => {
1039
- if (!currentBase)
1040
- return null;
1041
- const applicableExtensions = extensions.filter((ext) => ext.workflow === currentBase.meta.key).filter((ext) => matchesScope(ext, scope)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
1042
- if (applicableExtensions.length === 0) {
1043
- return currentBase;
1044
- }
1045
- let composedWorkflow = { ...currentBase, steps: [...currentBase.steps] };
1046
- for (const extension of applicableExtensions) {
1047
- composedWorkflow = applyExtension(composedWorkflow, extension);
1048
- }
1049
- return composedWorkflow;
1050
- }, [currentBase, extensions]);
1051
- const workflow = useMemo3(() => compose(), [compose]);
1052
- const selectWorkflow = useCallback4((workflowName) => {
1053
- setSelectedWorkflow(workflowName);
1054
- }, []);
1055
- const addExtension = useCallback4((extension) => {
1056
- setExtensions((prev) => [...prev, extension]);
1057
- }, []);
1058
- const removeExtension = useCallback4((workflowName, index) => {
1059
- setExtensions((prev) => {
1060
- const forWorkflow = prev.filter((e) => e.workflow === workflowName);
1061
- const others = prev.filter((e) => e.workflow !== workflowName);
1062
- forWorkflow.splice(index, 1);
1063
- return [...others, ...forWorkflow];
1064
- });
1065
- }, []);
1066
- const generateSpecCode = useCallback4(() => {
1067
- const composed = workflow;
1068
- if (!composed) {
1069
- return "// No workflow selected";
1070
- }
1071
- const stepsCode = composed.steps.map((step) => ` {
1072
- id: '${step.id}',
1073
- name: '${step.name}',
1074
- type: '${step.type}',${step.description ? `
1075
- description: '${step.description}',` : ""}${step.next ? `
1076
- next: ${JSON.stringify(step.next)},` : ""}${step.condition ? `
1077
- condition: '${step.condition}',` : ""}${step.timeout ? `
1078
- timeout: ${step.timeout},` : ""}${step.retries ? `
1079
- retries: ${step.retries},` : ""}${step.onError ? `
1080
- onError: '${step.onError}',` : ""}
377
+ });`}import{useCallback as v,useEffect as Mq,useState as g}from"react";var p="contractspec-spec-content";function Sq(q){let{template:Z}=s(),[X,z]=g(""),[D,H]=g(""),[B,_]=g(!0),[T,L]=g(null),[j,G]=g(null);Mq(()=>{_(!0);try{let h=localStorage.getItem(`${p}-${q}`);if(h){let Q=JSON.parse(h);if(Q.content)z(Q.content),H(Q.content),G(Q.savedAt);else{let K=C(Z);z(K),H(K)}}else{let Q=C(Z);z(Q),H(Q)}}catch{let h=C(Z);z(h),H(h)}_(!1)},[q]);let F=v((h)=>{z(h),L(null)},[]),W=v(()=>{try{let h=new Date().toISOString();localStorage.setItem(`${p}-${q}`,JSON.stringify({content:X,savedAt:h})),H(X),G(h)}catch{}},[X,q]),O=v(()=>{let h=[],Q=X.split(`
378
+ `);if(!X.includes("contractSpec("))h.push({line:1,message:"Spec must contain a contractSpec() definition",severity:"error"});if(!X.includes("goal:"))h.push({line:1,message:"Spec should have a goal field",severity:"warning"});if(!X.includes("io:"))h.push({line:1,message:"Spec should define io (input/output)",severity:"warning"});let K=(X.match(/{/g)??[]).length,N=(X.match(/}/g)??[]).length;if(K!==N)h.push({line:Q.length,message:`Unbalanced braces: ${K} opening, ${N} closing`,severity:"error"});let $=(X.match(/\(/g)??[]).length,J=(X.match(/\)/g)??[]).length;if($!==J)h.push({line:Q.length,message:`Unbalanced parentheses: ${$} opening, ${J} closing`,severity:"error"});Q.forEach((Y,E)=>{let V=(Y.match(/'/g)??[]).length,U=(Y.match(/"/g)??[]).length;if(V%2!==0)h.push({line:E+1,message:"Unclosed single quote",severity:"error"});if(U%2!==0)h.push({line:E+1,message:"Unclosed double quote",severity:"error"})});let P={valid:h.filter((Y)=>Y.severity==="error").length===0,errors:h};return L(P),P},[X]),A=v(()=>{let h=C(Z);z(h),H(h),L(null),G(null);try{localStorage.removeItem(`${p}-${q}`)}catch{}},[q]);return{content:X,loading:B,isDirty:X!==D,validation:T,setContent:F,save:W,validate:O,reset:A,lastSaved:j}}import{useQuery as Wq}from"@tanstack/react-query";function cq(){return Wq({queryKey:["registryTemplates"],queryFn:async()=>{let q=process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL??"";if(!q)return[];let Z=await fetch(`${q.replace(/\/$/,"")}/r/contractspec.json`,{method:"GET",headers:{Accept:"application/json"}});if(!Z.ok)return[];return((await Z.json()).items??[]).filter((D)=>D.type==="contractspec:template").map((D)=>({id:D.name,name:D.title??D.name,description:D.description,tags:D.meta?.tags??[],source:"registry",registryUrl:q}))}})}import{useCallback as y,useEffect as _q,useMemo as r,useState as S}from"react";function rq(q){let[Z,X]=S(null),[z,D]=S([]),[H,B]=S(!1),[_,T]=S(null),L=r(()=>Tq(q),[q]);_q(()=>{let Q=L[0];if(L.length>0&&!Z&&Q)X(Q.meta.key)},[L,Z]);let j=r(()=>{return L.find((Q)=>Q.meta.key===Z)??null},[L,Z]),G=y((Q)=>{if(!j)return null;let K=z.filter(($)=>$.workflow===j.meta.key).filter(($)=>Oq($,Q)).sort(($,J)=>($.priority??0)-(J.priority??0));if(K.length===0)return j;let N={...j,steps:[...j.steps]};for(let $ of K)N=Aq(N,$);return N},[j,z]),F=r(()=>G(),[G]),W=y((Q)=>{X(Q)},[]),O=y((Q)=>{D((K)=>[...K,Q])},[]),A=y((Q,K)=>{D((N)=>{let $=N.filter((P)=>P.workflow===Q),J=N.filter((P)=>P.workflow!==Q);return $.splice(K,1),[...J,...$]})},[]),h=y(()=>{let Q=F;if(!Q)return"// No workflow selected";let K=Q.steps.map(($)=>` {
379
+ id: '${$.id}',
380
+ name: '${$.name}',
381
+ type: '${$.type}',${$.description?`
382
+ description: '${$.description}',`:""}${$.next?`
383
+ next: ${JSON.stringify($.next)},`:""}${$.condition?`
384
+ condition: '${$.condition}',`:""}${$.timeout?`
385
+ timeout: ${$.timeout},`:""}${$.retries?`
386
+ retries: ${$.retries},`:""}${$.onError?`
387
+ onError: '${$.onError}',`:""}
1081
388
  }`).join(`,
1082
- `);
1083
- const extensionsCode = extensions.length > 0 ? `
389
+ `),N=z.length>0?`
1084
390
 
1085
391
  // Extensions applied:
1086
- ${extensions.map((ext) => `// - ${ext.workflow} (priority: ${ext.priority ?? 0})${ext.customSteps?.length ? ` +${ext.customSteps.length} steps` : ""}${ext.hiddenSteps?.length ? ` -${ext.hiddenSteps.length} hidden` : ""}`).join(`
1087
- `)}` : "";
1088
- return `// Workflow Spec: ${composed.meta.key} v${composed.meta.version}
1089
- // Generated from ${templateId} template
1090
- ${extensionsCode}
392
+ ${z.map(($)=>`// - ${$.workflow} (priority: ${$.priority??0})${$.customSteps?.length?` +${$.customSteps.length} steps`:""}${$.hiddenSteps?.length?` -${$.hiddenSteps.length} hidden`:""}`).join(`
393
+ `)}`:"";return`// Workflow Spec: ${Q.meta.key} v${Q.meta.version}
394
+ // Generated from ${q} template
395
+ ${N}
1091
396
 
1092
397
  import { workflowSpec } from '@contractspec/lib.contracts-spec/workflow';
1093
398
 
1094
- export const ${toCamelCase(composed.meta.key)}Workflow = workflowSpec({
399
+ export const ${Uq(Q.meta.key)}Workflow = workflowSpec({
1095
400
  meta: {
1096
- key: '${composed.meta.key}',
1097
- version: ${composed.meta.version},${composed.meta.description ? `
1098
- description: '${composed.meta.description}',` : ""}
401
+ key: '${Q.meta.key}',
402
+ version: ${Q.meta.version},${Q.meta.description?`
403
+ description: '${Q.meta.description}',`:""}
1099
404
  },
1100
- start: '${composed.start}',
405
+ start: '${Q.start}',
1101
406
  steps: [
1102
- ${stepsCode}
1103
- ],${composed.context ? `
1104
- context: ${JSON.stringify(composed.context, null, 2)},` : ""}
407
+ ${K}
408
+ ],${Q.context?`
409
+ context: ${JSON.stringify(Q.context,null,2)},`:""}
1105
410
  });
1106
- `;
1107
- }, [workflow, extensions, templateId]);
1108
- return {
1109
- workflow,
1110
- baseWorkflows,
1111
- extensions,
1112
- selectWorkflow,
1113
- addExtension,
1114
- removeExtension,
1115
- compose,
1116
- generateSpecCode,
1117
- loading,
1118
- error
1119
- };
1120
- }
1121
- function matchesScope(extension, scope) {
1122
- if (!scope)
1123
- return true;
1124
- if (extension.tenantId && extension.tenantId !== scope.tenantId) {
1125
- return false;
1126
- }
1127
- if (extension.role && extension.role !== scope.role) {
1128
- return false;
1129
- }
1130
- if (extension.device && extension.device !== scope.device) {
1131
- return false;
1132
- }
1133
- return true;
1134
- }
1135
- function applyExtension(workflow, extension) {
1136
- let steps = [...workflow.steps];
1137
- if (extension.hiddenSteps) {
1138
- steps = steps.filter((s) => !extension.hiddenSteps?.includes(s.id));
1139
- }
1140
- if (extension.customSteps) {
1141
- for (const injection of extension.customSteps) {
1142
- const stepToInject = {
1143
- ...injection.inject,
1144
- id: injection.id ?? injection.inject.id
1145
- };
1146
- if (injection.after) {
1147
- const afterIndex = steps.findIndex((s) => s.id === injection.after);
1148
- if (afterIndex !== -1) {
1149
- steps.splice(afterIndex + 1, 0, stepToInject);
1150
- }
1151
- } else if (injection.before) {
1152
- const beforeIndex = steps.findIndex((s) => s.id === injection.before);
1153
- if (beforeIndex !== -1) {
1154
- steps.splice(beforeIndex, 0, stepToInject);
1155
- }
1156
- } else {
1157
- steps.push(stepToInject);
1158
- }
1159
- }
1160
- }
1161
- return { ...workflow, steps };
1162
- }
1163
- function toCamelCase(str) {
1164
- return str.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
1165
- }
1166
- function getTemplateWorkflows(templateId) {
1167
- const templateWorkflows = {
1168
- "crm-pipeline": [
1169
- {
1170
- meta: {
1171
- key: "deal.qualification",
1172
- version: "1.0.0",
1173
- description: "Deal qualification workflow"
1174
- },
1175
- start: "lead-received",
1176
- steps: [
1177
- {
1178
- id: "lead-received",
1179
- name: "Lead Received",
1180
- type: "action",
1181
- description: "New lead enters the pipeline",
1182
- next: "qualify-lead"
1183
- },
1184
- {
1185
- id: "qualify-lead",
1186
- name: "Qualify Lead",
1187
- type: "decision",
1188
- description: "Determine if lead meets qualification criteria",
1189
- next: ["qualified", "disqualified"],
1190
- condition: "lead.score >= threshold"
1191
- },
1192
- {
1193
- id: "qualified",
1194
- name: "Lead Qualified",
1195
- type: "action",
1196
- next: "assign-rep"
1197
- },
1198
- {
1199
- id: "disqualified",
1200
- name: "Lead Disqualified",
1201
- type: "end"
1202
- },
1203
- {
1204
- id: "assign-rep",
1205
- name: "Assign Sales Rep",
1206
- type: "action",
1207
- next: "complete"
1208
- },
1209
- {
1210
- id: "complete",
1211
- name: "Workflow Complete",
1212
- type: "end"
1213
- }
1214
- ]
1215
- },
1216
- {
1217
- meta: {
1218
- key: "deal.closing",
1219
- version: "1.0.0",
1220
- description: "Deal closing workflow"
1221
- },
1222
- start: "proposal-sent",
1223
- steps: [
1224
- {
1225
- id: "proposal-sent",
1226
- name: "Proposal Sent",
1227
- type: "action",
1228
- next: "wait-response"
1229
- },
1230
- {
1231
- id: "wait-response",
1232
- name: "Wait for Response",
1233
- type: "wait",
1234
- timeout: 604800000,
1235
- next: "negotiate",
1236
- onError: "follow-up"
1237
- },
1238
- {
1239
- id: "follow-up",
1240
- name: "Follow Up",
1241
- type: "action",
1242
- next: "wait-response",
1243
- retries: 3
1244
- },
1245
- {
1246
- id: "negotiate",
1247
- name: "Negotiation",
1248
- type: "action",
1249
- next: "finalize"
1250
- },
1251
- {
1252
- id: "finalize",
1253
- name: "Finalize Deal",
1254
- type: "decision",
1255
- next: ["won", "lost"],
1256
- condition: "deal.accepted"
1257
- },
1258
- {
1259
- id: "won",
1260
- name: "Deal Won",
1261
- type: "end"
1262
- },
1263
- {
1264
- id: "lost",
1265
- name: "Deal Lost",
1266
- type: "end"
1267
- }
1268
- ]
1269
- }
1270
- ],
1271
- "saas-boilerplate": [
1272
- {
1273
- meta: {
1274
- key: "user.onboarding",
1275
- version: "1.0.0",
1276
- description: "User onboarding workflow"
1277
- },
1278
- start: "signup",
1279
- steps: [
1280
- {
1281
- id: "signup",
1282
- name: "User Signup",
1283
- type: "action",
1284
- next: "verify-email"
1285
- },
1286
- {
1287
- id: "verify-email",
1288
- name: "Verify Email",
1289
- type: "wait",
1290
- timeout: 86400000,
1291
- next: "profile-setup",
1292
- onError: "resend-verification"
1293
- },
1294
- {
1295
- id: "resend-verification",
1296
- name: "Resend Verification",
1297
- type: "action",
1298
- next: "verify-email",
1299
- retries: 2
1300
- },
1301
- {
1302
- id: "profile-setup",
1303
- name: "Setup Profile",
1304
- type: "action",
1305
- next: "onboarding-tour"
1306
- },
1307
- {
1308
- id: "onboarding-tour",
1309
- name: "Onboarding Tour",
1310
- type: "action",
1311
- next: "complete"
1312
- },
1313
- {
1314
- id: "complete",
1315
- name: "Onboarding Complete",
1316
- type: "end"
1317
- }
1318
- ]
1319
- }
1320
- ],
1321
- "agent-console": [
1322
- {
1323
- meta: {
1324
- key: "agent.execution",
1325
- version: "1.0.0",
1326
- description: "Agent execution workflow"
1327
- },
1328
- start: "receive-task",
1329
- steps: [
1330
- {
1331
- id: "receive-task",
1332
- name: "Receive Task",
1333
- type: "action",
1334
- next: "plan-execution"
1335
- },
1336
- {
1337
- id: "plan-execution",
1338
- name: "Plan Execution",
1339
- type: "action",
1340
- next: "execute-steps"
1341
- },
1342
- {
1343
- id: "execute-steps",
1344
- name: "Execute Steps",
1345
- type: "parallel",
1346
- next: ["tool-call", "observe", "reason"]
1347
- },
1348
- {
1349
- id: "tool-call",
1350
- name: "Tool Call",
1351
- type: "action",
1352
- next: "evaluate"
1353
- },
1354
- {
1355
- id: "observe",
1356
- name: "Observe",
1357
- type: "action",
1358
- next: "evaluate"
1359
- },
1360
- {
1361
- id: "reason",
1362
- name: "Reason",
1363
- type: "action",
1364
- next: "evaluate"
1365
- },
1366
- {
1367
- id: "evaluate",
1368
- name: "Evaluate Result",
1369
- type: "decision",
1370
- condition: "task.isComplete",
1371
- next: ["complete", "execute-steps"]
1372
- },
1373
- {
1374
- id: "complete",
1375
- name: "Task Complete",
1376
- type: "end"
1377
- }
1378
- ]
1379
- }
1380
- ],
1381
- "todos-app": [
1382
- {
1383
- meta: {
1384
- key: "task.lifecycle",
1385
- version: "1.0.0",
1386
- description: "Task lifecycle workflow"
1387
- },
1388
- start: "created",
1389
- steps: [
1390
- {
1391
- id: "created",
1392
- name: "Task Created",
1393
- type: "action",
1394
- next: "in-progress"
1395
- },
1396
- {
1397
- id: "in-progress",
1398
- name: "In Progress",
1399
- type: "action",
1400
- next: "review"
1401
- },
1402
- {
1403
- id: "review",
1404
- name: "Review",
1405
- type: "decision",
1406
- condition: "task.approved",
1407
- next: ["done", "in-progress"]
1408
- },
1409
- {
1410
- id: "done",
1411
- name: "Done",
1412
- type: "end"
1413
- }
1414
- ]
1415
- }
1416
- ],
1417
- "messaging-app": [
1418
- {
1419
- meta: {
1420
- key: "message.delivery",
1421
- version: "1.0.0",
1422
- description: "Message delivery workflow"
1423
- },
1424
- start: "compose",
1425
- steps: [
1426
- {
1427
- id: "compose",
1428
- name: "Compose Message",
1429
- type: "action",
1430
- next: "send"
1431
- },
1432
- {
1433
- id: "send",
1434
- name: "Send Message",
1435
- type: "action",
1436
- next: "deliver"
1437
- },
1438
- {
1439
- id: "deliver",
1440
- name: "Deliver",
1441
- type: "decision",
1442
- condition: "recipient.online",
1443
- next: ["delivered", "queue"]
1444
- },
1445
- {
1446
- id: "queue",
1447
- name: "Queue for Delivery",
1448
- type: "wait",
1449
- next: "deliver"
1450
- },
1451
- {
1452
- id: "delivered",
1453
- name: "Message Delivered",
1454
- type: "action",
1455
- next: "read"
1456
- },
1457
- {
1458
- id: "read",
1459
- name: "Message Read",
1460
- type: "end"
1461
- }
1462
- ]
1463
- }
1464
- ],
1465
- "recipe-app-i18n": [
1466
- {
1467
- meta: {
1468
- key: "recipe.creation",
1469
- version: "1.0.0",
1470
- description: "Recipe creation workflow"
1471
- },
1472
- start: "draft",
1473
- steps: [
1474
- {
1475
- id: "draft",
1476
- name: "Draft Recipe",
1477
- type: "action",
1478
- next: "add-ingredients"
1479
- },
1480
- {
1481
- id: "add-ingredients",
1482
- name: "Add Ingredients",
1483
- type: "action",
1484
- next: "add-steps"
1485
- },
1486
- {
1487
- id: "add-steps",
1488
- name: "Add Steps",
1489
- type: "action",
1490
- next: "review"
1491
- },
1492
- {
1493
- id: "review",
1494
- name: "Review Recipe",
1495
- type: "decision",
1496
- condition: "recipe.isComplete",
1497
- next: ["publish", "draft"]
1498
- },
1499
- {
1500
- id: "publish",
1501
- name: "Publish Recipe",
1502
- type: "end"
1503
- }
1504
- ]
1505
- }
1506
- ]
1507
- };
1508
- return templateWorkflows[templateId] ?? [];
1509
- }
1510
- export {
1511
- useWorkflowComposer,
1512
- useSpecContent,
1513
- useRegistryTemplates,
1514
- useEvolution,
1515
- useBehaviorTracking
1516
- };
411
+ `},[F,z,q]);return{workflow:F,baseWorkflows:L,extensions:z,selectWorkflow:W,addExtension:O,removeExtension:A,compose:G,generateSpecCode:h,loading:H,error:_}}function Oq(q,Z){if(!Z)return!0;if(q.tenantId&&q.tenantId!==Z.tenantId)return!1;if(q.role&&q.role!==Z.role)return!1;if(q.device&&q.device!==Z.device)return!1;return!0}function Aq(q,Z){let X=[...q.steps];if(Z.hiddenSteps)X=X.filter((z)=>!Z.hiddenSteps?.includes(z.id));if(Z.customSteps)for(let z of Z.customSteps){let D={...z.inject,id:z.id??z.inject.id};if(z.after){let H=X.findIndex((B)=>B.id===z.after);if(H!==-1)X.splice(H+1,0,D)}else if(z.before){let H=X.findIndex((B)=>B.id===z.before);if(H!==-1)X.splice(H,0,D)}else X.push(D)}return{...q,steps:X}}function Uq(q){return q.replace(/[^a-zA-Z0-9]+(.)/g,(Z,X)=>X.toUpperCase()).replace(/^./,(Z)=>Z.toLowerCase())}function Tq(q){return{"crm-pipeline":[{meta:{key:"deal.qualification",version:"1.0.0",description:"Deal qualification workflow"},start:"lead-received",steps:[{id:"lead-received",name:"Lead Received",type:"action",description:"New lead enters the pipeline",next:"qualify-lead"},{id:"qualify-lead",name:"Qualify Lead",type:"decision",description:"Determine if lead meets qualification criteria",next:["qualified","disqualified"],condition:"lead.score >= threshold"},{id:"qualified",name:"Lead Qualified",type:"action",next:"assign-rep"},{id:"disqualified",name:"Lead Disqualified",type:"end"},{id:"assign-rep",name:"Assign Sales Rep",type:"action",next:"complete"},{id:"complete",name:"Workflow Complete",type:"end"}]},{meta:{key:"deal.closing",version:"1.0.0",description:"Deal closing workflow"},start:"proposal-sent",steps:[{id:"proposal-sent",name:"Proposal Sent",type:"action",next:"wait-response"},{id:"wait-response",name:"Wait for Response",type:"wait",timeout:604800000,next:"negotiate",onError:"follow-up"},{id:"follow-up",name:"Follow Up",type:"action",next:"wait-response",retries:3},{id:"negotiate",name:"Negotiation",type:"action",next:"finalize"},{id:"finalize",name:"Finalize Deal",type:"decision",next:["won","lost"],condition:"deal.accepted"},{id:"won",name:"Deal Won",type:"end"},{id:"lost",name:"Deal Lost",type:"end"}]}],"saas-boilerplate":[{meta:{key:"user.onboarding",version:"1.0.0",description:"User onboarding workflow"},start:"signup",steps:[{id:"signup",name:"User Signup",type:"action",next:"verify-email"},{id:"verify-email",name:"Verify Email",type:"wait",timeout:86400000,next:"profile-setup",onError:"resend-verification"},{id:"resend-verification",name:"Resend Verification",type:"action",next:"verify-email",retries:2},{id:"profile-setup",name:"Setup Profile",type:"action",next:"onboarding-tour"},{id:"onboarding-tour",name:"Onboarding Tour",type:"action",next:"complete"},{id:"complete",name:"Onboarding Complete",type:"end"}]}],"agent-console":[{meta:{key:"agent.execution",version:"1.0.0",description:"Agent execution workflow"},start:"receive-task",steps:[{id:"receive-task",name:"Receive Task",type:"action",next:"plan-execution"},{id:"plan-execution",name:"Plan Execution",type:"action",next:"execute-steps"},{id:"execute-steps",name:"Execute Steps",type:"parallel",next:["tool-call","observe","reason"]},{id:"tool-call",name:"Tool Call",type:"action",next:"evaluate"},{id:"observe",name:"Observe",type:"action",next:"evaluate"},{id:"reason",name:"Reason",type:"action",next:"evaluate"},{id:"evaluate",name:"Evaluate Result",type:"decision",condition:"task.isComplete",next:["complete","execute-steps"]},{id:"complete",name:"Task Complete",type:"end"}]}],"todos-app":[{meta:{key:"task.lifecycle",version:"1.0.0",description:"Task lifecycle workflow"},start:"created",steps:[{id:"created",name:"Task Created",type:"action",next:"in-progress"},{id:"in-progress",name:"In Progress",type:"action",next:"review"},{id:"review",name:"Review",type:"decision",condition:"task.approved",next:["done","in-progress"]},{id:"done",name:"Done",type:"end"}]}],"messaging-app":[{meta:{key:"message.delivery",version:"1.0.0",description:"Message delivery workflow"},start:"compose",steps:[{id:"compose",name:"Compose Message",type:"action",next:"send"},{id:"send",name:"Send Message",type:"action",next:"deliver"},{id:"deliver",name:"Deliver",type:"decision",condition:"recipient.online",next:["delivered","queue"]},{id:"queue",name:"Queue for Delivery",type:"wait",next:"deliver"},{id:"delivered",name:"Message Delivered",type:"action",next:"read"},{id:"read",name:"Message Read",type:"end"}]}],"recipe-app-i18n":[{meta:{key:"recipe.creation",version:"1.0.0",description:"Recipe creation workflow"},start:"draft",steps:[{id:"draft",name:"Draft Recipe",type:"action",next:"add-ingredients"},{id:"add-ingredients",name:"Add Ingredients",type:"action",next:"add-steps"},{id:"add-steps",name:"Add Steps",type:"action",next:"review"},{id:"review",name:"Review Recipe",type:"decision",condition:"recipe.isComplete",next:["publish","draft"]},{id:"publish",name:"Publish Recipe",type:"end"}]}]}[q]??[]}export{rq as useWorkflowComposer,Sq as useSpecContent,cq as useRegistryTemplates,bq as useEvolution,Iq as useBehaviorTracking};