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