@contractspec/lib.example-shared-ui 6.0.19 → 6.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +18 -15
- package/CHANGELOG.md +47 -0
- package/dist/browser/example-shared-ui.feature.js +1 -0
- package/dist/browser/index.js +6 -6
- package/dist/example-shared-ui.feature.d.ts +1 -0
- package/dist/example-shared-ui.feature.js +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +6 -6
- package/dist/node/example-shared-ui.feature.js +1 -0
- package/dist/node/index.js +6 -6
- package/package.json +22 -8
- package/src/example-shared-ui.feature.ts +15 -0
- package/src/index.ts +1 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
$ contractspec-bun-build prebuild
|
|
2
2
|
$ bun run build:bundle && bun run build:types
|
|
3
3
|
$ contractspec-bun-build transpile
|
|
4
|
-
[contractspec-bun-build] transpile target=bun root=src entries=
|
|
5
|
-
Bundled
|
|
4
|
+
[contractspec-bun-build] transpile target=bun root=src entries=29 noBundle=false
|
|
5
|
+
Bundled 29 modules in 23ms
|
|
6
6
|
|
|
7
7
|
./EvolutionDashboard.js 14.12 KB (entry point)
|
|
8
|
-
./index.js
|
|
8
|
+
./index.js 59.14 KB (entry point)
|
|
9
9
|
./overlay-types.js 8 bytes (entry point)
|
|
10
10
|
utils/index.js 9.13 KB (entry point)
|
|
11
11
|
utils/fetchPresentationData.js 277 bytes (entry point)
|
|
@@ -15,16 +15,17 @@ Bundled 28 modules in 44ms
|
|
|
15
15
|
./TemplateShell.js 3.24 KB (entry point)
|
|
16
16
|
bundles/index.js 1.55 KB (entry point)
|
|
17
17
|
bundles/ExampleTemplateBundle.js 1.55 KB (entry point)
|
|
18
|
+
./example-shared-ui.feature.js 422 bytes (entry point)
|
|
18
19
|
hooks/index.js 26.81 KB (entry point)
|
|
20
|
+
hooks/useRegistryTemplates.js 0.58 KB (entry point)
|
|
19
21
|
hooks/useWorkflowComposer.js 6.91 KB (entry point)
|
|
20
22
|
hooks/useSpecContent.js 11.0 KB (entry point)
|
|
21
23
|
utils/generateSpecFromTemplate.js 8.87 KB (entry point)
|
|
22
|
-
hooks/useRegistryTemplates.js 0.58 KB (entry point)
|
|
23
24
|
./EvolutionSidebar.js 10.0 KB (entry point)
|
|
24
25
|
hooks/useEvolution.js 5.37 KB (entry point)
|
|
25
26
|
./MarkdownView.js 3.13 KB (entry point)
|
|
26
|
-
markdown/formatPresentationName.js 171 bytes (entry point)
|
|
27
27
|
markdown/useMarkdownPresentation.js 0.87 KB (entry point)
|
|
28
|
+
markdown/formatPresentationName.js 171 bytes (entry point)
|
|
28
29
|
./OverlayContextProvider.js 2.98 KB (entry point)
|
|
29
30
|
./PersonalizationInsights.js 7.83 KB (entry point)
|
|
30
31
|
hooks/useBehaviorTracking.js 2.94 KB (entry point)
|
|
@@ -33,11 +34,11 @@ Bundled 28 modules in 44ms
|
|
|
33
34
|
./SaveToStudioButton.js 1.34 KB (entry point)
|
|
34
35
|
lib/runtime-context.js 390 bytes (entry point)
|
|
35
36
|
|
|
36
|
-
[contractspec-bun-build] transpile target=node root=src entries=
|
|
37
|
-
Bundled
|
|
37
|
+
[contractspec-bun-build] transpile target=node root=src entries=29 noBundle=false
|
|
38
|
+
Bundled 29 modules in 23ms
|
|
38
39
|
|
|
39
40
|
./EvolutionDashboard.js 14.1 KB (entry point)
|
|
40
|
-
./index.js
|
|
41
|
+
./index.js 59.1 KB (entry point)
|
|
41
42
|
./overlay-types.js 0 KB (entry point)
|
|
42
43
|
utils/index.js 9.12 KB (entry point)
|
|
43
44
|
utils/fetchPresentationData.js 269 bytes (entry point)
|
|
@@ -47,16 +48,17 @@ Bundled 28 modules in 38ms
|
|
|
47
48
|
./TemplateShell.js 3.22 KB (entry point)
|
|
48
49
|
bundles/index.js 1.54 KB (entry point)
|
|
49
50
|
bundles/ExampleTemplateBundle.js 1.54 KB (entry point)
|
|
51
|
+
./example-shared-ui.feature.js 414 bytes (entry point)
|
|
50
52
|
hooks/index.js 26.80 KB (entry point)
|
|
53
|
+
hooks/useRegistryTemplates.js 0.57 KB (entry point)
|
|
51
54
|
hooks/useWorkflowComposer.js 6.90 KB (entry point)
|
|
52
55
|
hooks/useSpecContent.js 11.0 KB (entry point)
|
|
53
56
|
utils/generateSpecFromTemplate.js 8.86 KB (entry point)
|
|
54
|
-
hooks/useRegistryTemplates.js 0.57 KB (entry point)
|
|
55
57
|
./EvolutionSidebar.js 10.0 KB (entry point)
|
|
56
58
|
hooks/useEvolution.js 5.36 KB (entry point)
|
|
57
59
|
./MarkdownView.js 3.13 KB (entry point)
|
|
58
|
-
markdown/formatPresentationName.js 163 bytes (entry point)
|
|
59
60
|
markdown/useMarkdownPresentation.js 0.87 KB (entry point)
|
|
61
|
+
markdown/formatPresentationName.js 163 bytes (entry point)
|
|
60
62
|
./OverlayContextProvider.js 2.97 KB (entry point)
|
|
61
63
|
./PersonalizationInsights.js 7.80 KB (entry point)
|
|
62
64
|
hooks/useBehaviorTracking.js 2.93 KB (entry point)
|
|
@@ -65,11 +67,11 @@ Bundled 28 modules in 38ms
|
|
|
65
67
|
./SaveToStudioButton.js 1.33 KB (entry point)
|
|
66
68
|
lib/runtime-context.js 382 bytes (entry point)
|
|
67
69
|
|
|
68
|
-
[contractspec-bun-build] transpile target=browser root=src entries=
|
|
69
|
-
Bundled
|
|
70
|
+
[contractspec-bun-build] transpile target=browser root=src entries=29 noBundle=false
|
|
71
|
+
Bundled 29 modules in 24ms
|
|
70
72
|
|
|
71
73
|
./EvolutionDashboard.js 14.1 KB (entry point)
|
|
72
|
-
./index.js
|
|
74
|
+
./index.js 59.1 KB (entry point)
|
|
73
75
|
./overlay-types.js 0 KB (entry point)
|
|
74
76
|
utils/index.js 9.12 KB (entry point)
|
|
75
77
|
utils/fetchPresentationData.js 269 bytes (entry point)
|
|
@@ -79,16 +81,17 @@ Bundled 28 modules in 42ms
|
|
|
79
81
|
./TemplateShell.js 3.22 KB (entry point)
|
|
80
82
|
bundles/index.js 1.54 KB (entry point)
|
|
81
83
|
bundles/ExampleTemplateBundle.js 1.54 KB (entry point)
|
|
84
|
+
./example-shared-ui.feature.js 414 bytes (entry point)
|
|
82
85
|
hooks/index.js 26.80 KB (entry point)
|
|
86
|
+
hooks/useRegistryTemplates.js 0.57 KB (entry point)
|
|
83
87
|
hooks/useWorkflowComposer.js 6.90 KB (entry point)
|
|
84
88
|
hooks/useSpecContent.js 11.0 KB (entry point)
|
|
85
89
|
utils/generateSpecFromTemplate.js 8.86 KB (entry point)
|
|
86
|
-
hooks/useRegistryTemplates.js 0.57 KB (entry point)
|
|
87
90
|
./EvolutionSidebar.js 10.0 KB (entry point)
|
|
88
91
|
hooks/useEvolution.js 5.36 KB (entry point)
|
|
89
92
|
./MarkdownView.js 3.13 KB (entry point)
|
|
90
|
-
markdown/formatPresentationName.js 163 bytes (entry point)
|
|
91
93
|
markdown/useMarkdownPresentation.js 0.87 KB (entry point)
|
|
94
|
+
markdown/formatPresentationName.js 163 bytes (entry point)
|
|
92
95
|
./OverlayContextProvider.js 2.97 KB (entry point)
|
|
93
96
|
./PersonalizationInsights.js 7.80 KB (entry point)
|
|
94
97
|
hooks/useBehaviorTracking.js 2.93 KB (entry point)
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# @contractspec/lib.example-shared-ui
|
|
2
2
|
|
|
3
|
+
## 6.0.22
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- chore: auto-bump internal dependents
|
|
8
|
+
- Updated dependencies because of chore: auto-bump internal dependents
|
|
9
|
+
- Updated dependencies because of Add focused design-system subpaths and harden ThemeSpec runtime, Tailwind bridge, form-control helpers, and form renderer internals without changing root-import compatibility.
|
|
10
|
+
- Updated dependencies because of Add a ThemeSpec-aware and TranslationSpec-aware design-system form/control layer with stack primitives, exported control wrappers, and FormSpec renderer alignment.
|
|
11
|
+
- Updated dependencies because of Add FormSpec layout hints, semantic field rendering, and portable text/textarea input-group addons.
|
|
12
|
+
- Updated dependencies because of Keep design-system FormRender mobile-safe by preserving shared renderer imports for Metro aliases and hardening generated package artifacts.
|
|
13
|
+
- Updated dependencies because of Replace the old Next alias helper with explicit Webpack and Turbopack helpers, keep Metro stable, publish bundler helpers from dist artifacts, and refresh the public docs to teach the current Next.js bundler path.
|
|
14
|
+
- Updated dependencies because of Add ThemeSpec light/dark modes and a design-system Tailwind bridge for CSS variables, presets, CSS text, and OKLCH color pass-through.
|
|
15
|
+
- Updated dependencies because of Add a canonical typed result system for ContractSpec success and failure propagation across operations, workflows, jobs, server adapters, MCP, GraphQL, and React clients.
|
|
16
|
+
- @contractspec/lib.surface-runtime@0.5.21
|
|
17
|
+
- @contractspec/lib.design-system@3.11.0
|
|
18
|
+
- @contractspec/lib.contracts-spec@5.5.0
|
|
19
|
+
- @contractspec/lib.ui-kit-web@3.10.3
|
|
20
|
+
- @contractspec/lib.presentation-runtime-core@5.0.0
|
|
21
|
+
|
|
22
|
+
## 6.0.21
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- chore: auto-bump internal dependents
|
|
27
|
+
- Updated dependencies because of chore: auto-bump internal dependents
|
|
28
|
+
- Updated dependencies because of Replace the old Next alias helper with explicit Webpack and Turbopack helpers, keep Metro stable, and refresh the public docs to teach the current Next.js bundler path.
|
|
29
|
+
- @contractspec/lib.design-system@3.10.1
|
|
30
|
+
- @contractspec/lib.ui-kit-web@3.10.2
|
|
31
|
+
- @contractspec/lib.presentation-runtime-core@4.0.0
|
|
32
|
+
|
|
33
|
+
## 6.0.20
|
|
34
|
+
|
|
35
|
+
### Patch Changes
|
|
36
|
+
|
|
37
|
+
- chore: auto-bump internal dependents
|
|
38
|
+
- Updated dependencies because of Add a family-aware ContractSpec Adoption Engine, expand contract authoring targets across CLI and VS Code tooling, and refresh release-facing schema and policy artifacts for downstream workspaces.
|
|
39
|
+
- Updated dependencies because of chore: auto-bump internal dependents
|
|
40
|
+
- Updated dependencies because of Improve app-config, theme, and feature authoring with explicit validation APIs, first-class theme discovery and scaffolding, and key-based app-config generation across contracts, workspace tooling, and the CLI.
|
|
41
|
+
- Updated dependencies because of Harden the shared data-table stack and add a first-class composed toolbar for search, filter chips, selection summary, and hidden-column recovery.
|
|
42
|
+
- Updated dependencies because of Refresh root, package, website, and LLM-facing docs so Connect, Builder, release capsules, and the current contracts-spec export surface stay aligned.
|
|
43
|
+
- Updated dependencies because of Persist canonical knowledge payload text during indexing and align the retrieval/query docs with the corrected behavior.
|
|
44
|
+
- @contractspec/lib.contracts-spec@5.4.0
|
|
45
|
+
- @contractspec/lib.presentation-runtime-core@3.9.8
|
|
46
|
+
- @contractspec/lib.surface-runtime@0.5.20
|
|
47
|
+
- @contractspec/lib.design-system@3.10.0
|
|
48
|
+
- @contractspec/lib.ui-kit-web@3.10.1
|
|
49
|
+
|
|
3
50
|
## 6.0.19
|
|
4
51
|
|
|
5
52
|
### Patch Changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineFeature as g}from"@contractspec/lib.contracts-spec/features";var j=g({meta:{key:"libs.example-shared-ui",version:"1.0.0",title:"Example Shared Ui",description:"ContractSpec package declaration for @contractspec/lib.example-shared-ui.",domain:"example-shared-ui",owners:["@contractspec-core"],tags:["package","libs","example-shared-ui"],stability:"experimental"}});export{j as ExampleSharedUiFeature};
|
package/dist/browser/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{useCallback as d,useEffect as B0,useMemo as $1,useRef as N1,useState as m}from"react";var D0="contractspec-evolution-data";function q0($){let[N,q]=m([]),[J,X]=m([]),[K,z]=m([]),[U,w]=m([]),[V,f]=m(!1),F=N1([]),[Y,b]=m(0);B0(()=>{try{let P=localStorage.getItem(`${D0}-${$}`);if(P){let G=JSON.parse(P);z(G.suggestions.map((M)=>({...M,createdAt:new Date(M.createdAt)})))}}catch{}},[$]),B0(()=>{try{localStorage.setItem(`${D0}-${$}`,JSON.stringify({suggestions:K}))}catch{}},[K,$]);let W=d((P,G,M,E)=>{let u={operation:{name:P,version:"1.0.0",tenantId:"sandbox"},durationMs:G,success:M,timestamp:new Date,errorCode:E};F.current.push(u),b((B)=>B+1)},[]),Q=d(()=>{let P=F.current;if(P.length<5)return;let G=new Map;for(let B of P){let y=`${B.operation.name}.v${B.operation.version}`,a=G.get(y)??[];a.push(B),G.set(y,a)}let M=[],E=[];G.forEach((B)=>{if(B.length<3)return;let y=B.map((k)=>k.durationMs).sort((k,x)=>k-x),a=B.filter((k)=>!k.success),F0=B.length,j=a.length/F0,e0=y.reduce((k,x)=>k+x,0)/F0,Y0=B.map((k)=>k.timestamp.getTime()),O0=B[0];if(!O0)return;let c={operation:O0.operation,totalCalls:F0,successRate:1-j,errorRate:j,averageLatencyMs:e0,p95LatencyMs:L0(y,0.95),p99LatencyMs:L0(y,0.99),maxLatencyMs:Math.max(...y),lastSeenAt:new Date(Math.max(...Y0)),windowStart:new Date(Math.min(...Y0)),windowEnd:new Date(Math.max(...Y0)),topErrors:a.reduce((k,x)=>{if(x.errorCode)k[x.errorCode]=(k[x.errorCode]??0)+1;return k},{})};if(M.push(c),j>0.1)E.push({operation:c.operation,severity:j>0.3?"high":j>0.2?"medium":"low",metric:"error-rate",description:`Error rate ${(j*100).toFixed(1)}% exceeds threshold`,detectedAt:new Date,threshold:0.1,observedValue:j});if(c.p99LatencyMs>500)E.push({operation:c.operation,severity:c.p99LatencyMs>1000?"high":c.p99LatencyMs>750?"medium":"low",metric:"latency",description:`P99 latency ${c.p99LatencyMs.toFixed(0)}ms exceeds threshold`,detectedAt:new Date,threshold:500,observedValue:c.p99LatencyMs})}),q(M),X(E);let u=E.map((B)=>({operation:B.operation,category:B.metric==="latency"?"performance":"error-handling",summary:B.metric==="latency"?"Latency regression detected":"Error spike detected",justification:B.description,recommendedActions:B.metric==="latency"?["Add caching layer","Optimize database queries","Consider pagination"]:["Add retry logic","Improve error handling","Add circuit breaker"]}));w(u)},[]),H=d(async()=>{if(J.length===0)return;f(!0),await new Promise((G)=>setTimeout(G,800));let P=J.map((G)=>({id:`suggestion-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,intent:{id:`intent-${G.operation.name}`,type:G.metric==="latency"?"latency-regression":G.metric==="error-rate"?"error-spike":"throughput-drop",description:G.description,operation:G.operation,confidence:{score:G.severity==="high"?0.9:G.severity==="medium"?0.7:0.5,sampleSize:N.find((M)=>M.operation.name===G.operation.name)?.totalCalls??0}},target:G.operation,proposal:{summary:q1(G),rationale:P1(G),changeType:G.metric==="error-rate"?"policy-update":"revision",recommendedActions:J1(G)},confidence:G.severity==="high"?0.85:G.severity==="medium"?0.7:0.55,createdAt:new Date,createdBy:"ai-evolution-agent",status:"pending",priority:G.severity}));z((G)=>[...G,...P]),f(!1)},[J,N]),Z=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"approved"}:E))},[]),A=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"rejected"}:E))},[]),L=d(()=>{F.current=[],b(0),q([]),X([]),z([]),w([]),localStorage.removeItem(`${D0}-${$}`)},[$]);return $1(()=>({usageStats:N,anomalies:J,suggestions:K,hints:U,loading:V,trackOperation:W,analyzeUsage:Q,generateSuggestions:H,approveSuggestion:Z,rejectSuggestion:A,clear:L,operationCount:Y}),[N,J,K,U,V,W,Q,H,Z,A,L,Y])}function L0($,N){if(!$.length)return 0;if($.length===1)return $[0]??0;let q=Math.min($.length-1,Math.floor(N*$.length));return $[q]??0}function q1($){if($.metric==="latency")return`Add caching and pagination to ${$.operation.name} to reduce latency`;if($.metric==="error-rate")return`Add retry policy and circuit breaker to ${$.operation.name}`;return`Optimize ${$.operation.name} for improved throughput`}function P1($){if($.metric==="latency")return`The operation ${$.operation.name} is experiencing P99 latency of ${$.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${$.threshold}ms. This can impact user experience and downstream operations.`;if($.metric==="error-rate")return`The error rate for ${$.operation.name} is ${(($.observedValue??0)*100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;return`Throughput for ${$.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`}function J1($){if($.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($.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{Button as n,LoaderBlock as Z1}from"@contractspec/lib.design-system";import{Badge as g}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as l}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as t,useMemo as Q1}from"react";import{jsx as D,jsxs as _}from"react/jsx-runtime";function K2({templateId:$,onLog:N}){let{usageStats:q,anomalies:J,suggestions:X,hints:K,loading:z,trackOperation:U,analyzeUsage:w,generateSuggestions:V,approveSuggestion:f,rejectSuggestion:F,clear:Y,operationCount:b}=q0($),W=t(()=>{let P=[{name:`${$}.list`,duration:150,success:!0},{name:`${$}.list`,duration:180,success:!0},{name:`${$}.create`,duration:350,success:!0},{name:`${$}.create`,duration:420,success:!1,error:"VALIDATION_ERROR"},{name:`${$}.list`,duration:200,success:!0},{name:`${$}.get`,duration:80,success:!0},{name:`${$}.update`,duration:280,success:!0},{name:`${$}.list`,duration:950,success:!0},{name:`${$}.delete`,duration:150,success:!1,error:"NOT_FOUND"},{name:`${$}.create`,duration:380,success:!0}];for(let G of P)U(G.name,G.duration,G.success,G.error);N?.(`Simulated ${P.length} operations`),setTimeout(()=>{w(),N?.("Analysis complete")},100)},[$,U,w,N]),Q=t(async()=>{await V(),N?.("AI suggestions generated")},[V,N]),H=t((P)=>{f(P),N?.(`Suggestion ${P.slice(0,8)} approved`)},[f,N]),Z=t((P)=>{F(P),N?.(`Suggestion ${P.slice(0,8)} rejected`)},[F,N]),A=t(()=>{Y(),N?.("Evolution data cleared")},[Y,N]),L=Q1(()=>X.filter((P)=>P.status==="pending"),[X]);return _("div",{className:"space-y-6",children:[_("div",{className:"flex items-center justify-between",children:[_("div",{children:[D("h2",{className:"font-semibold text-xl",children:"AI Evolution Engine"}),D("p",{className:"text-muted-foreground text-sm",children:"Analyze usage patterns and get AI-powered suggestions"})]}),_("div",{className:"flex items-center gap-2",children:[_(g,{variant:"secondary",children:[b," ops tracked"]}),D(n,{variant:"ghost",size:"sm",onPress:A,children:"Clear"})]})]}),_(l,{className:"p-4",children:[_("div",{className:"flex flex-wrap items-center gap-3",children:[D(n,{variant:"default",size:"sm",onPress:W,children:"Simulate Operations"}),D(n,{variant:"outline",size:"sm",onPress:w,disabled:b<5,children:"Analyze Usage"}),D(n,{variant:"outline",size:"sm",onPress:Q,disabled:J.length===0||z,children:z?"Generating...":"Generate AI Suggestions"})]}),D("p",{className:"mt-2 text-muted-foreground text-xs",children:"Simulate sandbox operations, analyze patterns, and generate AI improvement suggestions."})]}),z&&D(Z1,{label:"Generating AI suggestions..."}),q.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Usage Statistics"}),D("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:q.map((P)=>D(X1,{stat:P},P.operation.name))})]}),J.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"Detected Anomalies"}),_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[J.length," issues"]})]}),D("div",{className:"space-y-2",children:J.map((P,G)=>D(z1,{anomaly:P},`${P.operation.name}-${G}`))})]}),X.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"AI Suggestions"}),D("div",{className:"flex items-center gap-2",children:L.length>0&&_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[L.length," pending"]})})]}),D("div",{className:"space-y-3",children:X.map((P)=>D(H1,{suggestion:P,onApprove:H,onReject:Z},P.id))})]}),K.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Optimization Hints"}),D("div",{className:"space-y-2",children:K.map((P,G)=>D(G1,{hint:P},`${P.operation.name}-${G}`))})]}),q.length===0&&J.length===0&&X.length===0&&D(l,{className:"p-8 text-center",children:D("p",{className:"text-muted-foreground",children:'Click "Simulate Operations" to generate sample data for analysis.'})})]})}function X1({stat:$}){return _("div",{className:"rounded-lg border border-violet-500/20 bg-violet-500/5 p-3",children:[_("div",{className:"mb-2 flex items-center justify-between",children:[D("span",{className:"font-medium font-mono text-sm",children:$.operation.name}),_(g,{variant:$.errorRate>0.1?"destructive":"default",className:$.errorRate>0.1?"":"border-green-500/30 bg-green-500/20 text-green-400",children:[((1-$.errorRate)*100).toFixed(0),"% success"]})]}),_("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[_("div",{children:[D("span",{className:"text-muted-foreground",children:"Total Calls:"})," ",D("span",{className:"font-medium",children:$.totalCalls})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"Avg Latency:"})," ",_("span",{className:"font-medium",children:[$.averageLatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P95:"})," ",_("span",{className:"font-medium",children:[$.p95LatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P99:"})," ",_("span",{className:"font-medium",children:[$.p99LatencyMs.toFixed(0),"ms"]})]})]})]})}function z1({anomaly:$}){return _("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",children:[_("div",{className:"flex items-center gap-3",children:[D("span",{className:`text-lg ${{low:"text-amber-400",medium:"text-orange-400",high:"text-red-400"}[$.severity]}`,title:`${$.severity} severity`,children:$.severity==="high"?"\uD83D\uDD34":$.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),_("div",{children:[D("p",{className:"font-medium text-sm",children:$.description}),_("p",{className:"text-muted-foreground text-xs",children:[$.operation.name," • ",$.metric]})]})]}),D(g,{variant:$.severity==="high"?"destructive":"secondary",className:$.severity==="medium"?"border-amber-500/30 bg-amber-500/20 text-amber-400":"",children:$.severity})]})}function H1({suggestion:$,onApprove:N,onReject:q}){let X=((K)=>{switch(K){case"pending":return{variant:"secondary",className:"bg-amber-500/20 text-amber-400 border-amber-500/30"};case"approved":return{variant:"default",className:"bg-green-500/20 text-green-400 border-green-500/30"};case"rejected":return{variant:"destructive",className:""};default:return{variant:"secondary",className:""}}})($.status);return _("div",{className:"rounded-lg border border-violet-500/30 bg-violet-500/5 p-4",children:[_("div",{className:"mb-2 flex items-start justify-between",children:[_("div",{className:"flex-1",children:[_("div",{className:"flex items-center gap-2",children:[D("span",{className:"text-lg",children:$.intent.type==="latency-regression"?"⚡":$.intent.type==="error-spike"?"\uD83D\uDD25":"\uD83D\uDCC9"}),D("h4",{className:"font-medium",children:$.proposal.summary})]}),D("p",{className:"mt-1 text-muted-foreground text-sm",children:$.proposal.rationale})]}),D(g,{variant:X.variant,className:X.className,children:$.status})]}),$.proposal.recommendedActions&&$.proposal.recommendedActions.length>0&&_("div",{className:"mt-3",children:[D("p",{className:"mb-1 font-semibold text-violet-400 text-xs uppercase",children:"Recommended Actions"}),D("ul",{className:"list-inside list-disc space-y-1 text-xs",children:$.proposal.recommendedActions.slice(0,3).map((K,z)=>D("li",{children:K},z))})]}),_("div",{className:"mt-3 flex items-center justify-between",children:[_("div",{className:"flex items-center gap-2 text-xs",children:[_("span",{className:"text-muted-foreground",children:["Confidence: ",($.confidence*100).toFixed(0),"%"]}),D("span",{className:"text-muted-foreground",children:"•"}),D(g,{variant:"secondary",children:$.priority})]}),$.status==="pending"&&_("div",{className:"flex items-center gap-2",children:[D(n,{variant:"outline",size:"sm",onPress:()=>q($.id),children:"Reject"}),D(n,{variant:"default",size:"sm",onPress:()=>N($.id),children:"Approve"})]})]})]})}function G1({hint:$}){return D("div",{className:"rounded-lg border border-blue-500/20 bg-blue-500/5 p-3",children:_("div",{className:"flex items-start gap-3",children:[D("span",{className:"text-lg",children:{schema:"\uD83D\uDCD0",policy:"\uD83D\uDD12",performance:"⚡","error-handling":"\uD83D\uDEE1️"}[$.category]}),_("div",{className:"flex-1",children:[D("p",{className:"font-medium",children:$.summary}),D("p",{className:"mt-1 text-muted-foreground text-xs",children:$.justification}),$.recommendedActions.length>0&&D("ul",{className:"mt-2 list-inside list-disc text-xs",children:$.recommendedActions.slice(0,2).map((q,J)=>D("li",{children:q},J))})]})]})})}import{Button as E0}from"@contractspec/lib.design-system";import{Badge as s}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as K1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as k0,useMemo as C0}from"react";import{jsx as h,jsxs as T}from"react/jsx-runtime";function U2({templateId:$,expanded:N=!1,onToggle:q,onLog:J,onOpenEvolution:X}){let{anomalies:K,suggestions:z,loading:U,approveSuggestion:w,rejectSuggestion:V,operationCount:f}=q0($),F=C0(()=>z.filter((Q)=>Q.status==="pending"),[z]),Y=C0(()=>K.sort((Q,H)=>{let Z={high:0,medium:1,low:2};return Z[Q.severity]-Z[H.severity]}).slice(0,3),[K]),b=k0((Q)=>{w(Q),J?.(`Approved suggestion ${Q.slice(0,8)}`)},[w,J]),W=k0((Q)=>{V(Q),J?.(`Rejected suggestion ${Q.slice(0,8)}`)},[V,J]);if(!N)return T("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm transition hover:bg-violet-500/20",type:"button",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{children:"Evolution"}),F.length>0&&h(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:F.length}),K.length>0&&F.length===0&&h(s,{variant:"destructive",children:K.length})]});return T(K1,{className:"w-80 overflow-hidden",children:[T("div",{className:"flex items-center justify-between border-violet-500/20 border-b bg-violet-500/5 px-3 py-2",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{className:"font-semibold text-sm",children:"Evolution"})]}),T("div",{className:"flex items-center gap-1",children:[X&&h(E0,{variant:"ghost",size:"sm",onPress:X,children:"Expand"}),h("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),T("div",{className:"max-h-96 overflow-y-auto p-3",children:[T("div",{className:"mb-3 flex items-center justify-between text-xs",children:[T("span",{className:"text-muted-foreground",children:[f," ops tracked"]}),T("div",{className:"flex items-center gap-2",children:[K.length>0&&T(s,{variant:"destructive",children:[K.length," anomalies"]}),F.length>0&&T(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[F.length," pending"]})]})]}),U&&h("div",{className:"py-4 text-center text-muted-foreground text-sm",children:"Generating suggestions..."}),Y.length>0&&T("div",{className:"mb-4",children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Top Issues"}),h("div",{className:"space-y-2",children:Y.map((Q,H)=>T("div",{className:"rounded border border-amber-500/20 bg-amber-500/5 p-2 text-xs",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:Q.severity==="high"?"\uD83D\uDD34":Q.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),h("span",{className:"truncate font-medium",children:Q.operation.name})]}),h("p",{className:"mt-1 truncate text-muted-foreground",children:Q.description})]},`${Q.operation.name}-${H}`))})]}),F.length>0&&T("div",{children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Pending Suggestions"}),T("div",{className:"space-y-2",children:[F.slice(0,3).map((Q)=>h(V1,{suggestion:Q,onApprove:b,onReject:W},Q.id)),F.length>3&&T("p",{className:"text-center text-muted-foreground text-xs",children:["+",F.length-3," more suggestions"]})]})]}),K.length===0&&F.length===0&&!U&&h("div",{className:"py-4 text-center text-muted-foreground text-xs",children:"No issues detected. Keep coding!"})]}),X&&h("div",{className:"border-violet-500/20 border-t p-2",children:h(E0,{variant:"ghost",size:"sm",className:"w-full",onPress:X,children:"Open Evolution Dashboard →"})})]})}function V1({suggestion:$,onApprove:N,onReject:q}){return T("div",{className:"rounded border border-violet-500/20 bg-violet-500/5 p-2",children:[h("div",{className:"flex items-start justify-between gap-2",children:T("div",{className:"min-w-0 flex-1",children:[h("p",{className:"truncate font-medium text-xs",children:$.proposal.summary}),T("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[h(s,{variant:"secondary",children:$.priority}),T("span",{className:"text-muted-foreground",children:[($.confidence*100).toFixed(0),"%"]})]})]})}),T("div",{className:"mt-2 flex justify-end gap-1",children:[h("button",{onClick:()=>q($.id),className:"rounded px-2 py-0.5 text-red-400 text-xs hover:bg-red-400/10",type:"button",children:"Reject"}),h("button",{onClick:()=>N($.id),className:"rounded bg-violet-500/20 px-2 py-0.5 text-violet-400 text-xs hover:bg-violet-500/30",type:"button",children:"Approve"})]})]})}import{createContext as F1,useContext as Y1}from"react";var I0=Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");function D1(){let $=globalThis;return $[I0]??=F1(null),$[I0]}var f1=D1();function r(){let $=Y1(f1);if(!$)throw Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");return $}import{RefreshCw as W1,Shield as _1}from"lucide-react";import{useState as U1}from"react";import{jsx as f0,jsxs as W0}from"react/jsx-runtime";function P0(){let{projectId:$,templateId:N,template:q,installer:J}=r(),[X,K]=U1(!1),z=async()=>{K(!0);try{await J.install(N,{projectId:$})}finally{K(!1)}};return W0("div",{className:"inline-flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-muted-foreground text-xs",children:[f0(_1,{className:"h-3.5 w-3.5 text-violet-400"}),W0("span",{children:["Local runtime ·"," ",f0("span",{className:"font-semibold text-foreground",children:q.name})]}),W0("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-semibold text-[11px] text-muted-foreground hover:text-foreground",onClick:z,disabled:X,children:[f0(W1,{className:"h-3 w-3"}),X?"Resetting…":"Reset data"]})]})}function S0($){let N=$.split(".");return(N[N.length-1]??$).split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}import{useCallback as A1,useEffect as v0,useState as J0}from"react";function y0({engine:$,fetchData:N,presentationId:q,presentations:J,resolvePresentation:X,templateId:K}){let[z,U]=J0(""),[w,V]=J0(""),[f,F]=J0(!1),[Y,b]=J0(null);v0(()=>{if(q&&J.includes(q)){U(q);return}if(J.length===0){U("");return}if(!J.includes(z))U(J[0]??"")},[q,J,z,K]);let W=A1(async()=>{if(!z||!$)return;F(!0),b(null);try{if(!X)throw Error("resolvePresentation not available in runtime context");let Q=X(z);if(!Q)throw Error(`Presentation descriptor not found: ${z}`);let H=await N(z),Z=await $.render("markdown",Q,{data:H.data});V(Z.body)}catch(Q){b(Q instanceof Error?Q:Error("Failed to render markdown"))}finally{F(!1)}},[$,N,X,z]);return v0(()=>{W()},[W]),{error:Y,loading:f,markdownContent:w,renderMarkdown:W,selectedPresentation:z,setSelectedPresentation:U}}import{Button as c0,ErrorState as w1,LoaderBlock as b1,MarkdownRenderer as R1}from"@contractspec/lib.design-system";import{Badge as h1}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as r0}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as M1}from"react";import{jsx as C,jsxs as Z0}from"react/jsx-runtime";function i2({templateId:$,presentationId:N,className:q}){let{engine:J,template:X,templateId:K,resolvePresentation:z,fetchData:U}=r(),w=$??K,V=X?.presentations??[],{error:f,loading:F,markdownContent:Y,renderMarkdown:b,selectedPresentation:W,setSelectedPresentation:Q}=y0({engine:J,fetchData:U,presentationId:N,presentations:V,resolvePresentation:z,templateId:w});if(!V.length)return C(r0,{className:q,children:C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"No presentations available for this template."})})});let H=M1(()=>{if(Y)navigator.clipboard.writeText(Y)},[Y]);return Z0("div",{className:q,children:[Z0("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[C("span",{className:"font-medium text-muted-foreground text-sm",children:"Presentation:"}),V.map((Z)=>C(c0,{variant:W===Z?"default":"outline",size:"sm",onPress:()=>Q(Z),children:S0(Z)},Z)),Z0("div",{className:"ml-auto flex items-center gap-2",children:[C(h1,{variant:"secondary",children:"LLM-friendly"}),C(c0,{variant:"outline",size:"sm",onPress:H,disabled:!Y||F,children:"Copy"})]})]}),Z0(r0,{className:"overflow-hidden",children:[F&&C(b1,{label:"Rendering markdown..."}),f&&C(w1,{title:"Render failed",description:f.message,onRetry:b,retryLabel:"Retry"}),!F&&!f&&Y&&C("div",{className:"p-6",children:C(R1,{content:Y})}),!F&&!f&&!Y&&C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"Select a presentation to view its markdown output."})})]})]})}import*as i0 from"react";import{useContext as j0,useMemo as I}from"react";import{jsx as O1}from"react/jsx-runtime";var _0=i0.createContext(null);function p2({templateId:$,role:N="user",device:q="desktop",children:J}){let X=I(()=>T1($,N),[$,N]),K=I(()=>{return X.filter((W)=>{let Q=W.conditions;if(!Q)return!0;if(Q.role&&!Q.role.includes(N))return!1;if(Q.device&&Q.device!=="any"&&Q.device!==q)return!1;return!0})},[X,N,q]),z=I(()=>{let W=new Map;for(let Q of K)W.set(Q.target,Q);return W},[K]),U=I(()=>(W,Q)=>{let H=z.get(W);if(!H)return Q;let Z={...Q};for(let A of H.modifications)switch(A.op){case"hide":Z={...Z,hidden:!0};break;case"relabel":Z={...Z,label:A.label};break;case"reorder":Z={...Z,position:A.position};break;case"restyle":Z={...Z,className:A.className,variant:A.variant};break;case"set-default":Z={...Z,defaultValue:A.value};break}return Z},[z]),w=I(()=>(W)=>{return z.get(W)?.modifications.some((H)=>H.op==="hide")??!1},[z]),V=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="relabel");return Z&&Z.op==="relabel"?Z.label:Q},[z]),f=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="reorder");return Z&&Z.op==="reorder"?Z.position:Q},[z]),F=I(()=>(W)=>{let H=z.get(W)?.modifications.find((Z)=>Z.op==="restyle");if(H&&H.op==="restyle")return{className:H.className,variant:H.variant};return{}},[z]),Y=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="set-default");return Z&&Z.op==="set-default"?Z.value:Q},[z]),b=I(()=>({overlays:K,applyOverlay:U,isHidden:w,getLabel:V,getPosition:f,getStyle:F,getDefault:Y,role:N,device:q}),[K,U,w,V,f,F,Y,N,q]);return O1(_0.Provider,{value:b,children:J})}function u2(){let $=j0(_0);if(!$)throw Error("useOverlayContext must be used within an OverlayContextProvider");return $}function d2(){return j0(_0)!==null}function T1($,N){return{"crm-pipeline":[{id:"crm-hide-internal-fields",target:"deal.internalNotes",modifications:[{op:"hide"}],conditions:{role:["viewer","user"]}},{id:"crm-relabel-value",target:"deal.value",modifications:[{op:"relabel",label:"Deal Amount"}]}],"saas-boilerplate":[{id:"saas-hide-billing",target:"settings.billing",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"saas-restyle-plan",target:"settings.plan",modifications:[{op:"restyle",variant:"premium"}],conditions:{role:["admin"]}}],"agent-console":[{id:"agent-hide-cost",target:"run.cost",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"agent-relabel-tokens",target:"run.tokens",modifications:[{op:"relabel",label:"Token Usage"}]}],"todos-app":[{id:"todos-hide-assignee",target:"task.assignee",modifications:[{op:"hide"}],conditions:{device:"mobile"}}],"messaging-app":[{id:"messaging-reorder-timestamp",target:"message.timestamp",modifications:[{op:"reorder",position:0}]}],"recipe-app-i18n":[{id:"recipe-relabel-servings",target:"recipe.servings",modifications:[{op:"relabel",label:"Portions"}]}]}[$]??[]}import{useCallback as Q0,useEffect as x0,useMemo as B1,useRef as L1,useState as g0}from"react";var U0="contractspec-behavior-data",E1=["playground","specs","builder","markdown","evolution","canvas_add","canvas_delete","spec_save","spec_validate","ai_suggestions"];function p0($){let[N,q]=g0([]),J=L1(new Date),[X,K]=g0(0);x0(()=>{try{let f=localStorage.getItem(U0);if(f){let F=JSON.parse(f);q(F.events.map((Y)=>({...Y,timestamp:new Date(Y.timestamp)}))),J.current=new Date(F.sessionStart)}}catch{}},[]),x0(()=>{if(N.length>0)try{localStorage.setItem(U0,JSON.stringify({events:N.map((f)=>({...f,timestamp:f.timestamp.toISOString()})),sessionStart:J.current.toISOString()}))}catch{}},[N]);let z=Q0((f,F)=>{let Y={type:f,timestamp:new Date,templateId:$,metadata:F};q((b)=>[...b,Y]),K((b)=>b+1)},[$]),U=Q0((f)=>{return N.filter((F)=>F.type===f)},[N]),w=Q0(()=>{let F=new Date().getTime()-J.current.getTime(),Y=new Map;for(let P of N){let G=Y.get(P.templateId)??0;Y.set(P.templateId,G+1)}let b=Array.from(Y.entries()).map(([P,G])=>({templateId:P,count:G})).sort((P,G)=>G.count-P.count).slice(0,3),W=new Map;for(let P of N)if(P.type==="mode_change"&&P.metadata?.mode){let G=P.metadata.mode,M=W.get(G)??0;W.set(G,M+1)}let Q=Array.from(W.entries()).map(([P,G])=>({mode:P,count:G})).sort((P,G)=>G.count-P.count),H=new Set;for(let P of N){if(P.type==="mode_change"&&P.metadata?.mode)H.add(P.metadata.mode);if(P.type==="feature_usage"&&P.metadata?.feature)H.add(P.metadata.feature);if(P.type==="canvas_interaction"){let G=P.metadata?.action;if(G==="add")H.add("canvas_add");if(G==="delete")H.add("canvas_delete")}if(P.type==="spec_edit"){let G=P.metadata?.action;if(G==="save")H.add("spec_save");if(G==="validate")H.add("spec_validate")}}let Z=E1.filter((P)=>!H.has(P)),A=N.filter((P)=>P.type==="error").length,L=k1(Array.from(H),Z,Q,N.length);return{totalEvents:N.length,sessionDuration:F,mostUsedTemplates:b,mostUsedModes:Q,featuresUsed:Array.from(H),unusedFeatures:Z,errorCount:A,recommendations:L}},[N]),V=Q0(()=>{q([]),K(0),J.current=new Date,localStorage.removeItem(U0)},[]);return B1(()=>({trackEvent:z,getSummary:w,getEventsByType:U,eventCount:X,sessionStart:J.current,clear:V}),[z,w,U,X,V])}function k1($,N,q,J){let X=[];if(N.includes("evolution"))X.push("Try the AI Evolution mode to get automated improvement suggestions");if(N.includes("markdown"))X.push("Use Markdown preview to see documentation for your specs");if(N.includes("builder"))X.push("Explore the Visual Builder to design your UI components");if(!$.includes("spec_validate")&&$.includes("specs"))X.push("Don't forget to validate your specs before saving");if($.includes("evolution")&&!$.includes("ai_suggestions"))X.push("Generate AI suggestions to get actionable improvement recommendations");if(J>50)X.push("Great engagement! Consider saving your work regularly");if(q.length===1)X.push("Try different modes to explore all sandbox capabilities");return X}import{Button as u0}from"@contractspec/lib.design-system";import{Badge as A0}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as C1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as d0,useMemo as I1,useState as S1}from"react";import{jsx as R,jsxs as O}from"react/jsx-runtime";function N4({templateId:$,collapsed:N=!1,onToggle:q}){let{getSummary:J,eventCount:X,clear:K,sessionStart:z}=p0($),[U,w]=S1(!1),V=I1(()=>J(),[J]),f=d0((Y)=>{let b=Math.floor(Y/1000),W=Math.floor(b/60),Q=Math.floor(W/60);if(Q>0)return`${Q}h ${W%60}m`;if(W>0)return`${W}m ${b%60}s`;return`${b}s`},[]),F=d0(()=>{K()},[K]);if(N)return O("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 text-sm transition hover:bg-blue-500/20",type:"button",children:[R("span",{children:"\uD83D\uDCCA"}),R("span",{children:"Insights"}),R(A0,{variant:"secondary",children:X})]});return O(C1,{className:"overflow-hidden",children:[O("div",{className:"flex items-center justify-between border-blue-500/20 border-b bg-blue-500/5 px-4 py-3",children:[O("div",{className:"flex items-center gap-2",children:[R("span",{children:"\uD83D\uDCCA"}),R("span",{className:"font-semibold",children:"Personalization Insights"})]}),O("div",{className:"flex items-center gap-2",children:[R(u0,{variant:"ghost",size:"sm",onPress:()=>w(!U),children:U?"Hide Details":"Show Details"}),q&&R("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),O("div",{className:"p-4",children:[O("div",{className:"mb-4 grid grid-cols-2 gap-3 md:grid-cols-4",children:[R(X0,{label:"Session Time",value:f(V.sessionDuration),icon:"⏱️"}),R(X0,{label:"Events Tracked",value:V.totalEvents.toString(),icon:"\uD83D\uDCC8"}),R(X0,{label:"Features Used",value:`${V.featuresUsed.length}/${V.featuresUsed.length+V.unusedFeatures.length}`,icon:"✨"}),R(X0,{label:"Errors",value:V.errorCount.toString(),icon:"⚠️",variant:V.errorCount>0?"warning":"success"})]}),V.recommendations.length>0&&O("div",{className:"mb-4",children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Recommendations"}),R("ul",{className:"space-y-1",children:V.recommendations.map((Y,b)=>O("li",{className:"flex items-start gap-2 text-sm",children:[R("span",{className:"text-blue-400",children:"\uD83D\uDCA1"}),R("span",{children:Y})]},b))})]}),V.unusedFeatures.length>0&&O("div",{className:"mb-4",children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Try These Features"}),R("div",{className:"flex flex-wrap gap-2",children:V.unusedFeatures.slice(0,5).map((Y)=>R(A0,{variant:"secondary",children:w0(Y)},Y))})]}),U&&R(v1,{summary:V,sessionStart:z}),R("div",{className:"mt-4 flex justify-end border-blue-500/10 border-t pt-4",children:R(u0,{variant:"ghost",size:"sm",onPress:F,children:"Clear Data"})})]})]})}function X0({label:$,value:N,icon:q,variant:J="default"}){return O("div",{className:`rounded-lg border p-3 text-center ${{default:"bg-blue-500/5 border-blue-500/20",warning:"bg-amber-500/5 border-amber-500/20",success:"bg-green-500/5 border-green-500/20"}[J]}`,children:[R("div",{className:"mb-1 text-lg",children:q}),R("div",{className:"font-bold text-lg",children:N}),R("div",{className:"text-muted-foreground text-xs",children:$})]})}function v1({summary:$,sessionStart:N}){return O("div",{className:"mt-4 space-y-4 border-blue-500/10 border-t pt-4",children:[$.mostUsedTemplates.length>0&&O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Most Used Templates"}),R("div",{className:"space-y-1",children:$.mostUsedTemplates.map(({templateId:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[R("span",{children:y1(q)}),O("span",{className:"text-muted-foreground",children:[J," events"]})]},q))})]}),$.mostUsedModes.length>0&&O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Mode Usage"}),R("div",{className:"space-y-1",children:$.mostUsedModes.map(({mode:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[R("span",{children:w0(q)}),O("span",{className:"text-muted-foreground",children:[J," switches"]})]},q))})]}),O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Features Used"}),R("div",{className:"flex flex-wrap gap-2",children:$.featuresUsed.map((q)=>O(A0,{variant:"default",className:"border-green-500/30 bg-green-500/20 text-green-400",children:["✓ ",w0(q)]},q))})]}),O("div",{className:"text-muted-foreground text-xs",children:["Session started: ",N.toLocaleString()]})]})}function w0($){return $.replace(/_/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}function y1($){return $.replace(/-/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}import{Sparkles as c1}from"lucide-react";import{useState as m0}from"react";import{jsx as b0,jsxs as l0}from"react/jsx-runtime";function z0({organizationId:$="demo-org",projectName:N,endpoint:q,token:J}){let{installer:X,templateId:K,template:z}=r(),[U,w]=m0("idle"),[V,f]=m0(null);return l0("div",{className:"flex flex-col items-end gap-1",children:[l0("button",{type:"button",className:"btn-primary inline-flex items-center gap-2 text-sm",onClick:async()=>{w("saving"),f(null);try{await X.saveToStudio({templateId:K,projectName:N??`${z.name} demo`,organizationId:$,endpoint:q,token:J}),w("saved"),setTimeout(()=>w("idle"),3000)}catch(Y){w("error"),f(Y instanceof Error?Y.message:"Unknown error")}},disabled:U==="saving",children:[b0(c1,{className:"h-4 w-4"}),U==="saving"?"Publishing…":"Save to Studio"]}),U==="error"&&V?b0("p",{className:"text-destructive text-xs",children:V}):null,U==="saved"?b0("p",{className:"text-emerald-400 text-xs",children:"Template sent to Studio."}):null]})}import{BundleProvider as r1,BundleRenderer as i1}from"@contractspec/lib.surface-runtime/react";import{jsx as S,jsxs as H0}from"react/jsx-runtime";function V4({plan:$,title:N,description:q,sidebar:J,actions:X,showSaveAction:K=!0,saveProps:z,children:U}){let V={header:H0("header",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm",children:[H0("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[H0("div",{children:[S("p",{className:"font-semibold text-muted-foreground text-sm uppercase tracking-wide",children:"ContractSpec Templates"}),S("h1",{className:"font-bold text-3xl",children:N}),q?S("p",{className:"mt-2 max-w-2xl text-muted-foreground text-sm",children:q}):null]}),H0("div",{className:"flex flex-col items-end gap-2",children:[S(P0,{}),K?S(z0,{...z}):null]})]}),X?S("div",{className:"mt-4",children:X}):null]}),primary:S("main",{className:"space-y-4 p-2",children:U})};if(J!=null)V.sidebar=S("aside",{className:"rounded-2xl border border-border bg-card p-4",children:J});return S(r1,{plan:$,children:S(i1,{slotContent:V})})}function e($){let N=$?.id??"unknown";if(!$)return n0(N);switch(N){case"crm-pipeline":return j1($.schema.contracts);case"saas-boilerplate":return x1($.schema.contracts);case"agent-console":return g1($.schema.contracts);case"todos-app":return p1($.schema.contracts);case"messaging-app":return u1($.schema.contracts);case"recipe-app-i18n":return d1($.schema.contracts);default:return n0(N)}}function j1($){return`// CRM Pipeline Specs
|
|
1
|
+
import{useCallback as d,useEffect as B0,useMemo as $1,useRef as N1,useState as m}from"react";var D0="contractspec-evolution-data";function q0($){let[N,q]=m([]),[J,X]=m([]),[K,z]=m([]),[U,w]=m([]),[V,f]=m(!1),Y=N1([]),[F,R]=m(0);B0(()=>{try{let P=localStorage.getItem(`${D0}-${$}`);if(P){let G=JSON.parse(P);z(G.suggestions.map((M)=>({...M,createdAt:new Date(M.createdAt)})))}}catch{}},[$]),B0(()=>{try{localStorage.setItem(`${D0}-${$}`,JSON.stringify({suggestions:K}))}catch{}},[K,$]);let W=d((P,G,M,E)=>{let u={operation:{name:P,version:"1.0.0",tenantId:"sandbox"},durationMs:G,success:M,timestamp:new Date,errorCode:E};Y.current.push(u),R((B)=>B+1)},[]),Q=d(()=>{let P=Y.current;if(P.length<5)return;let G=new Map;for(let B of P){let y=`${B.operation.name}.v${B.operation.version}`,a=G.get(y)??[];a.push(B),G.set(y,a)}let M=[],E=[];G.forEach((B)=>{if(B.length<3)return;let y=B.map((k)=>k.durationMs).sort((k,i)=>k-i),a=B.filter((k)=>!k.success),Y0=B.length,x=a.length/Y0,e0=y.reduce((k,i)=>k+i,0)/Y0,F0=B.map((k)=>k.timestamp.getTime()),O0=B[0];if(!O0)return;let c={operation:O0.operation,totalCalls:Y0,successRate:1-x,errorRate:x,averageLatencyMs:e0,p95LatencyMs:L0(y,0.95),p99LatencyMs:L0(y,0.99),maxLatencyMs:Math.max(...y),lastSeenAt:new Date(Math.max(...F0)),windowStart:new Date(Math.min(...F0)),windowEnd:new Date(Math.max(...F0)),topErrors:a.reduce((k,i)=>{if(i.errorCode)k[i.errorCode]=(k[i.errorCode]??0)+1;return k},{})};if(M.push(c),x>0.1)E.push({operation:c.operation,severity:x>0.3?"high":x>0.2?"medium":"low",metric:"error-rate",description:`Error rate ${(x*100).toFixed(1)}% exceeds threshold`,detectedAt:new Date,threshold:0.1,observedValue:x});if(c.p99LatencyMs>500)E.push({operation:c.operation,severity:c.p99LatencyMs>1000?"high":c.p99LatencyMs>750?"medium":"low",metric:"latency",description:`P99 latency ${c.p99LatencyMs.toFixed(0)}ms exceeds threshold`,detectedAt:new Date,threshold:500,observedValue:c.p99LatencyMs})}),q(M),X(E);let u=E.map((B)=>({operation:B.operation,category:B.metric==="latency"?"performance":"error-handling",summary:B.metric==="latency"?"Latency regression detected":"Error spike detected",justification:B.description,recommendedActions:B.metric==="latency"?["Add caching layer","Optimize database queries","Consider pagination"]:["Add retry logic","Improve error handling","Add circuit breaker"]}));w(u)},[]),H=d(async()=>{if(J.length===0)return;f(!0),await new Promise((G)=>setTimeout(G,800));let P=J.map((G)=>({id:`suggestion-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,intent:{id:`intent-${G.operation.name}`,type:G.metric==="latency"?"latency-regression":G.metric==="error-rate"?"error-spike":"throughput-drop",description:G.description,operation:G.operation,confidence:{score:G.severity==="high"?0.9:G.severity==="medium"?0.7:0.5,sampleSize:N.find((M)=>M.operation.name===G.operation.name)?.totalCalls??0}},target:G.operation,proposal:{summary:q1(G),rationale:P1(G),changeType:G.metric==="error-rate"?"policy-update":"revision",recommendedActions:J1(G)},confidence:G.severity==="high"?0.85:G.severity==="medium"?0.7:0.55,createdAt:new Date,createdBy:"ai-evolution-agent",status:"pending",priority:G.severity}));z((G)=>[...G,...P]),f(!1)},[J,N]),Z=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"approved"}:E))},[]),A=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"rejected"}:E))},[]),L=d(()=>{Y.current=[],R(0),q([]),X([]),z([]),w([]),localStorage.removeItem(`${D0}-${$}`)},[$]);return $1(()=>({usageStats:N,anomalies:J,suggestions:K,hints:U,loading:V,trackOperation:W,analyzeUsage:Q,generateSuggestions:H,approveSuggestion:Z,rejectSuggestion:A,clear:L,operationCount:F}),[N,J,K,U,V,W,Q,H,Z,A,L,F])}function L0($,N){if(!$.length)return 0;if($.length===1)return $[0]??0;let q=Math.min($.length-1,Math.floor(N*$.length));return $[q]??0}function q1($){if($.metric==="latency")return`Add caching and pagination to ${$.operation.name} to reduce latency`;if($.metric==="error-rate")return`Add retry policy and circuit breaker to ${$.operation.name}`;return`Optimize ${$.operation.name} for improved throughput`}function P1($){if($.metric==="latency")return`The operation ${$.operation.name} is experiencing P99 latency of ${$.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${$.threshold}ms. This can impact user experience and downstream operations.`;if($.metric==="error-rate")return`The error rate for ${$.operation.name} is ${(($.observedValue??0)*100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;return`Throughput for ${$.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`}function J1($){if($.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($.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{Button as n,LoaderBlock as Z1}from"@contractspec/lib.design-system";import{Badge as g}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as l}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as t,useMemo as Q1}from"react";import{jsx as D,jsxs as _}from"react/jsx-runtime";function V2({templateId:$,onLog:N}){let{usageStats:q,anomalies:J,suggestions:X,hints:K,loading:z,trackOperation:U,analyzeUsage:w,generateSuggestions:V,approveSuggestion:f,rejectSuggestion:Y,clear:F,operationCount:R}=q0($),W=t(()=>{let P=[{name:`${$}.list`,duration:150,success:!0},{name:`${$}.list`,duration:180,success:!0},{name:`${$}.create`,duration:350,success:!0},{name:`${$}.create`,duration:420,success:!1,error:"VALIDATION_ERROR"},{name:`${$}.list`,duration:200,success:!0},{name:`${$}.get`,duration:80,success:!0},{name:`${$}.update`,duration:280,success:!0},{name:`${$}.list`,duration:950,success:!0},{name:`${$}.delete`,duration:150,success:!1,error:"NOT_FOUND"},{name:`${$}.create`,duration:380,success:!0}];for(let G of P)U(G.name,G.duration,G.success,G.error);N?.(`Simulated ${P.length} operations`),setTimeout(()=>{w(),N?.("Analysis complete")},100)},[$,U,w,N]),Q=t(async()=>{await V(),N?.("AI suggestions generated")},[V,N]),H=t((P)=>{f(P),N?.(`Suggestion ${P.slice(0,8)} approved`)},[f,N]),Z=t((P)=>{Y(P),N?.(`Suggestion ${P.slice(0,8)} rejected`)},[Y,N]),A=t(()=>{F(),N?.("Evolution data cleared")},[F,N]),L=Q1(()=>X.filter((P)=>P.status==="pending"),[X]);return _("div",{className:"space-y-6",children:[_("div",{className:"flex items-center justify-between",children:[_("div",{children:[D("h2",{className:"font-semibold text-xl",children:"AI Evolution Engine"}),D("p",{className:"text-muted-foreground text-sm",children:"Analyze usage patterns and get AI-powered suggestions"})]}),_("div",{className:"flex items-center gap-2",children:[_(g,{variant:"secondary",children:[R," ops tracked"]}),D(n,{variant:"ghost",size:"sm",onPress:A,children:"Clear"})]})]}),_(l,{className:"p-4",children:[_("div",{className:"flex flex-wrap items-center gap-3",children:[D(n,{variant:"default",size:"sm",onPress:W,children:"Simulate Operations"}),D(n,{variant:"outline",size:"sm",onPress:w,disabled:R<5,children:"Analyze Usage"}),D(n,{variant:"outline",size:"sm",onPress:Q,disabled:J.length===0||z,children:z?"Generating...":"Generate AI Suggestions"})]}),D("p",{className:"mt-2 text-muted-foreground text-xs",children:"Simulate sandbox operations, analyze patterns, and generate AI improvement suggestions."})]}),z&&D(Z1,{label:"Generating AI suggestions..."}),q.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Usage Statistics"}),D("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:q.map((P)=>D(X1,{stat:P},P.operation.name))})]}),J.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"Detected Anomalies"}),_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[J.length," issues"]})]}),D("div",{className:"space-y-2",children:J.map((P,G)=>D(z1,{anomaly:P},`${P.operation.name}-${G}`))})]}),X.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"AI Suggestions"}),D("div",{className:"flex items-center gap-2",children:L.length>0&&_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[L.length," pending"]})})]}),D("div",{className:"space-y-3",children:X.map((P)=>D(H1,{suggestion:P,onApprove:H,onReject:Z},P.id))})]}),K.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Optimization Hints"}),D("div",{className:"space-y-2",children:K.map((P,G)=>D(G1,{hint:P},`${P.operation.name}-${G}`))})]}),q.length===0&&J.length===0&&X.length===0&&D(l,{className:"p-8 text-center",children:D("p",{className:"text-muted-foreground",children:'Click "Simulate Operations" to generate sample data for analysis.'})})]})}function X1({stat:$}){return _("div",{className:"rounded-lg border border-violet-500/20 bg-violet-500/5 p-3",children:[_("div",{className:"mb-2 flex items-center justify-between",children:[D("span",{className:"font-medium font-mono text-sm",children:$.operation.name}),_(g,{variant:$.errorRate>0.1?"destructive":"default",className:$.errorRate>0.1?"":"border-green-500/30 bg-green-500/20 text-green-400",children:[((1-$.errorRate)*100).toFixed(0),"% success"]})]}),_("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[_("div",{children:[D("span",{className:"text-muted-foreground",children:"Total Calls:"})," ",D("span",{className:"font-medium",children:$.totalCalls})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"Avg Latency:"})," ",_("span",{className:"font-medium",children:[$.averageLatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P95:"})," ",_("span",{className:"font-medium",children:[$.p95LatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P99:"})," ",_("span",{className:"font-medium",children:[$.p99LatencyMs.toFixed(0),"ms"]})]})]})]})}function z1({anomaly:$}){return _("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",children:[_("div",{className:"flex items-center gap-3",children:[D("span",{className:`text-lg ${{low:"text-amber-400",medium:"text-orange-400",high:"text-red-400"}[$.severity]}`,title:`${$.severity} severity`,children:$.severity==="high"?"\uD83D\uDD34":$.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),_("div",{children:[D("p",{className:"font-medium text-sm",children:$.description}),_("p",{className:"text-muted-foreground text-xs",children:[$.operation.name," • ",$.metric]})]})]}),D(g,{variant:$.severity==="high"?"destructive":"secondary",className:$.severity==="medium"?"border-amber-500/30 bg-amber-500/20 text-amber-400":"",children:$.severity})]})}function H1({suggestion:$,onApprove:N,onReject:q}){let X=((K)=>{switch(K){case"pending":return{variant:"secondary",className:"bg-amber-500/20 text-amber-400 border-amber-500/30"};case"approved":return{variant:"default",className:"bg-green-500/20 text-green-400 border-green-500/30"};case"rejected":return{variant:"destructive",className:""};default:return{variant:"secondary",className:""}}})($.status);return _("div",{className:"rounded-lg border border-violet-500/30 bg-violet-500/5 p-4",children:[_("div",{className:"mb-2 flex items-start justify-between",children:[_("div",{className:"flex-1",children:[_("div",{className:"flex items-center gap-2",children:[D("span",{className:"text-lg",children:$.intent.type==="latency-regression"?"⚡":$.intent.type==="error-spike"?"\uD83D\uDD25":"\uD83D\uDCC9"}),D("h4",{className:"font-medium",children:$.proposal.summary})]}),D("p",{className:"mt-1 text-muted-foreground text-sm",children:$.proposal.rationale})]}),D(g,{variant:X.variant,className:X.className,children:$.status})]}),$.proposal.recommendedActions&&$.proposal.recommendedActions.length>0&&_("div",{className:"mt-3",children:[D("p",{className:"mb-1 font-semibold text-violet-400 text-xs uppercase",children:"Recommended Actions"}),D("ul",{className:"list-inside list-disc space-y-1 text-xs",children:$.proposal.recommendedActions.slice(0,3).map((K,z)=>D("li",{children:K},z))})]}),_("div",{className:"mt-3 flex items-center justify-between",children:[_("div",{className:"flex items-center gap-2 text-xs",children:[_("span",{className:"text-muted-foreground",children:["Confidence: ",($.confidence*100).toFixed(0),"%"]}),D("span",{className:"text-muted-foreground",children:"•"}),D(g,{variant:"secondary",children:$.priority})]}),$.status==="pending"&&_("div",{className:"flex items-center gap-2",children:[D(n,{variant:"outline",size:"sm",onPress:()=>q($.id),children:"Reject"}),D(n,{variant:"default",size:"sm",onPress:()=>N($.id),children:"Approve"})]})]})]})}function G1({hint:$}){return D("div",{className:"rounded-lg border border-blue-500/20 bg-blue-500/5 p-3",children:_("div",{className:"flex items-start gap-3",children:[D("span",{className:"text-lg",children:{schema:"\uD83D\uDCD0",policy:"\uD83D\uDD12",performance:"⚡","error-handling":"\uD83D\uDEE1️"}[$.category]}),_("div",{className:"flex-1",children:[D("p",{className:"font-medium",children:$.summary}),D("p",{className:"mt-1 text-muted-foreground text-xs",children:$.justification}),$.recommendedActions.length>0&&D("ul",{className:"mt-2 list-inside list-disc text-xs",children:$.recommendedActions.slice(0,2).map((q,J)=>D("li",{children:q},J))})]})]})})}import{Button as E0}from"@contractspec/lib.design-system";import{Badge as s}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as K1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as k0,useMemo as C0}from"react";import{jsx as h,jsxs as T}from"react/jsx-runtime";function A2({templateId:$,expanded:N=!1,onToggle:q,onLog:J,onOpenEvolution:X}){let{anomalies:K,suggestions:z,loading:U,approveSuggestion:w,rejectSuggestion:V,operationCount:f}=q0($),Y=C0(()=>z.filter((Q)=>Q.status==="pending"),[z]),F=C0(()=>K.sort((Q,H)=>{let Z={high:0,medium:1,low:2};return Z[Q.severity]-Z[H.severity]}).slice(0,3),[K]),R=k0((Q)=>{w(Q),J?.(`Approved suggestion ${Q.slice(0,8)}`)},[w,J]),W=k0((Q)=>{V(Q),J?.(`Rejected suggestion ${Q.slice(0,8)}`)},[V,J]);if(!N)return T("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm transition hover:bg-violet-500/20",type:"button",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{children:"Evolution"}),Y.length>0&&h(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:Y.length}),K.length>0&&Y.length===0&&h(s,{variant:"destructive",children:K.length})]});return T(K1,{className:"w-80 overflow-hidden",children:[T("div",{className:"flex items-center justify-between border-violet-500/20 border-b bg-violet-500/5 px-3 py-2",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{className:"font-semibold text-sm",children:"Evolution"})]}),T("div",{className:"flex items-center gap-1",children:[X&&h(E0,{variant:"ghost",size:"sm",onPress:X,children:"Expand"}),h("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),T("div",{className:"max-h-96 overflow-y-auto p-3",children:[T("div",{className:"mb-3 flex items-center justify-between text-xs",children:[T("span",{className:"text-muted-foreground",children:[f," ops tracked"]}),T("div",{className:"flex items-center gap-2",children:[K.length>0&&T(s,{variant:"destructive",children:[K.length," anomalies"]}),Y.length>0&&T(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[Y.length," pending"]})]})]}),U&&h("div",{className:"py-4 text-center text-muted-foreground text-sm",children:"Generating suggestions..."}),F.length>0&&T("div",{className:"mb-4",children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Top Issues"}),h("div",{className:"space-y-2",children:F.map((Q,H)=>T("div",{className:"rounded border border-amber-500/20 bg-amber-500/5 p-2 text-xs",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:Q.severity==="high"?"\uD83D\uDD34":Q.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),h("span",{className:"truncate font-medium",children:Q.operation.name})]}),h("p",{className:"mt-1 truncate text-muted-foreground",children:Q.description})]},`${Q.operation.name}-${H}`))})]}),Y.length>0&&T("div",{children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Pending Suggestions"}),T("div",{className:"space-y-2",children:[Y.slice(0,3).map((Q)=>h(V1,{suggestion:Q,onApprove:R,onReject:W},Q.id)),Y.length>3&&T("p",{className:"text-center text-muted-foreground text-xs",children:["+",Y.length-3," more suggestions"]})]})]}),K.length===0&&Y.length===0&&!U&&h("div",{className:"py-4 text-center text-muted-foreground text-xs",children:"No issues detected. Keep coding!"})]}),X&&h("div",{className:"border-violet-500/20 border-t p-2",children:h(E0,{variant:"ghost",size:"sm",className:"w-full",onPress:X,children:"Open Evolution Dashboard →"})})]})}function V1({suggestion:$,onApprove:N,onReject:q}){return T("div",{className:"rounded border border-violet-500/20 bg-violet-500/5 p-2",children:[h("div",{className:"flex items-start justify-between gap-2",children:T("div",{className:"min-w-0 flex-1",children:[h("p",{className:"truncate font-medium text-xs",children:$.proposal.summary}),T("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[h(s,{variant:"secondary",children:$.priority}),T("span",{className:"text-muted-foreground",children:[($.confidence*100).toFixed(0),"%"]})]})]})}),T("div",{className:"mt-2 flex justify-end gap-1",children:[h("button",{onClick:()=>q($.id),className:"rounded px-2 py-0.5 text-red-400 text-xs hover:bg-red-400/10",type:"button",children:"Reject"}),h("button",{onClick:()=>N($.id),className:"rounded bg-violet-500/20 px-2 py-0.5 text-violet-400 text-xs hover:bg-violet-500/30",type:"button",children:"Approve"})]})]})}import{createContext as Y1,useContext as F1}from"react";var I0=Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");function D1(){let $=globalThis;return $[I0]??=Y1(null),$[I0]}var f1=D1();function r(){let $=F1(f1);if(!$)throw Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");return $}import{RefreshCw as W1,Shield as _1}from"lucide-react";import{useState as U1}from"react";import{jsx as f0,jsxs as W0}from"react/jsx-runtime";function P0(){let{projectId:$,templateId:N,template:q,installer:J}=r(),[X,K]=U1(!1),z=async()=>{K(!0);try{await J.install(N,{projectId:$})}finally{K(!1)}};return W0("div",{className:"inline-flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-muted-foreground text-xs",children:[f0(_1,{className:"h-3.5 w-3.5 text-violet-400"}),W0("span",{children:["Local runtime ·"," ",f0("span",{className:"font-semibold text-foreground",children:q.name})]}),W0("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-semibold text-[11px] text-muted-foreground hover:text-foreground",onClick:z,disabled:X,children:[f0(W1,{className:"h-3 w-3"}),X?"Resetting…":"Reset data"]})]})}function S0($){let N=$.split(".");return(N[N.length-1]??$).split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}import{useCallback as A1,useEffect as v0,useState as J0}from"react";function y0({engine:$,fetchData:N,presentationId:q,presentations:J,resolvePresentation:X,templateId:K}){let[z,U]=J0(""),[w,V]=J0(""),[f,Y]=J0(!1),[F,R]=J0(null);v0(()=>{if(q&&J.includes(q)){U(q);return}if(J.length===0){U("");return}if(!J.includes(z))U(J[0]??"")},[q,J,z,K]);let W=A1(async()=>{if(!z||!$)return;Y(!0),R(null);try{if(!X)throw Error("resolvePresentation not available in runtime context");let Q=X(z);if(!Q)throw Error(`Presentation descriptor not found: ${z}`);let H=await N(z),Z=await $.render("markdown",Q,{data:H.data});V(Z.body)}catch(Q){R(Q instanceof Error?Q:Error("Failed to render markdown"))}finally{Y(!1)}},[$,N,X,z]);return v0(()=>{W()},[W]),{error:F,loading:f,markdownContent:w,renderMarkdown:W,selectedPresentation:z,setSelectedPresentation:U}}import{Button as c0,ErrorState as w1,LoaderBlock as R1,MarkdownRenderer as b1}from"@contractspec/lib.design-system";import{Badge as h1}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as r0}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as M1}from"react";import{jsx as C,jsxs as Z0}from"react/jsx-runtime";function x2({templateId:$,presentationId:N,className:q}){let{engine:J,template:X,templateId:K,resolvePresentation:z,fetchData:U}=r(),w=$??K,V=X?.presentations??[],{error:f,loading:Y,markdownContent:F,renderMarkdown:R,selectedPresentation:W,setSelectedPresentation:Q}=y0({engine:J,fetchData:U,presentationId:N,presentations:V,resolvePresentation:z,templateId:w});if(!V.length)return C(r0,{className:q,children:C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"No presentations available for this template."})})});let H=M1(()=>{if(F)navigator.clipboard.writeText(F)},[F]);return Z0("div",{className:q,children:[Z0("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[C("span",{className:"font-medium text-muted-foreground text-sm",children:"Presentation:"}),V.map((Z)=>C(c0,{variant:W===Z?"default":"outline",size:"sm",onPress:()=>Q(Z),children:S0(Z)},Z)),Z0("div",{className:"ml-auto flex items-center gap-2",children:[C(h1,{variant:"secondary",children:"LLM-friendly"}),C(c0,{variant:"outline",size:"sm",onPress:H,disabled:!F||Y,children:"Copy"})]})]}),Z0(r0,{className:"overflow-hidden",children:[Y&&C(R1,{label:"Rendering markdown..."}),f&&C(w1,{title:"Render failed",description:f.message,onRetry:R,retryLabel:"Retry"}),!Y&&!f&&F&&C("div",{className:"p-6",children:C(b1,{content:F})}),!Y&&!f&&!F&&C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"Select a presentation to view its markdown output."})})]})]})}import*as j0 from"react";import{useContext as x0,useMemo as I}from"react";import{jsx as O1}from"react/jsx-runtime";var _0=j0.createContext(null);function u2({templateId:$,role:N="user",device:q="desktop",children:J}){let X=I(()=>T1($,N),[$,N]),K=I(()=>{return X.filter((W)=>{let Q=W.conditions;if(!Q)return!0;if(Q.role&&!Q.role.includes(N))return!1;if(Q.device&&Q.device!=="any"&&Q.device!==q)return!1;return!0})},[X,N,q]),z=I(()=>{let W=new Map;for(let Q of K)W.set(Q.target,Q);return W},[K]),U=I(()=>(W,Q)=>{let H=z.get(W);if(!H)return Q;let Z={...Q};for(let A of H.modifications)switch(A.op){case"hide":Z={...Z,hidden:!0};break;case"relabel":Z={...Z,label:A.label};break;case"reorder":Z={...Z,position:A.position};break;case"restyle":Z={...Z,className:A.className,variant:A.variant};break;case"set-default":Z={...Z,defaultValue:A.value};break}return Z},[z]),w=I(()=>(W)=>{return z.get(W)?.modifications.some((H)=>H.op==="hide")??!1},[z]),V=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="relabel");return Z&&Z.op==="relabel"?Z.label:Q},[z]),f=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="reorder");return Z&&Z.op==="reorder"?Z.position:Q},[z]),Y=I(()=>(W)=>{let H=z.get(W)?.modifications.find((Z)=>Z.op==="restyle");if(H&&H.op==="restyle")return{className:H.className,variant:H.variant};return{}},[z]),F=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="set-default");return Z&&Z.op==="set-default"?Z.value:Q},[z]),R=I(()=>({overlays:K,applyOverlay:U,isHidden:w,getLabel:V,getPosition:f,getStyle:Y,getDefault:F,role:N,device:q}),[K,U,w,V,f,Y,F,N,q]);return O1(_0.Provider,{value:R,children:J})}function d2(){let $=x0(_0);if(!$)throw Error("useOverlayContext must be used within an OverlayContextProvider");return $}function m2(){return x0(_0)!==null}function T1($,N){return{"crm-pipeline":[{id:"crm-hide-internal-fields",target:"deal.internalNotes",modifications:[{op:"hide"}],conditions:{role:["viewer","user"]}},{id:"crm-relabel-value",target:"deal.value",modifications:[{op:"relabel",label:"Deal Amount"}]}],"saas-boilerplate":[{id:"saas-hide-billing",target:"settings.billing",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"saas-restyle-plan",target:"settings.plan",modifications:[{op:"restyle",variant:"premium"}],conditions:{role:["admin"]}}],"agent-console":[{id:"agent-hide-cost",target:"run.cost",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"agent-relabel-tokens",target:"run.tokens",modifications:[{op:"relabel",label:"Token Usage"}]}],"todos-app":[{id:"todos-hide-assignee",target:"task.assignee",modifications:[{op:"hide"}],conditions:{device:"mobile"}}],"messaging-app":[{id:"messaging-reorder-timestamp",target:"message.timestamp",modifications:[{op:"reorder",position:0}]}],"recipe-app-i18n":[{id:"recipe-relabel-servings",target:"recipe.servings",modifications:[{op:"relabel",label:"Portions"}]}]}[$]??[]}import{useCallback as Q0,useEffect as i0,useMemo as B1,useRef as L1,useState as g0}from"react";var U0="contractspec-behavior-data",E1=["playground","specs","builder","markdown","evolution","canvas_add","canvas_delete","spec_save","spec_validate","ai_suggestions"];function p0($){let[N,q]=g0([]),J=L1(new Date),[X,K]=g0(0);i0(()=>{try{let f=localStorage.getItem(U0);if(f){let Y=JSON.parse(f);q(Y.events.map((F)=>({...F,timestamp:new Date(F.timestamp)}))),J.current=new Date(Y.sessionStart)}}catch{}},[]),i0(()=>{if(N.length>0)try{localStorage.setItem(U0,JSON.stringify({events:N.map((f)=>({...f,timestamp:f.timestamp.toISOString()})),sessionStart:J.current.toISOString()}))}catch{}},[N]);let z=Q0((f,Y)=>{let F={type:f,timestamp:new Date,templateId:$,metadata:Y};q((R)=>[...R,F]),K((R)=>R+1)},[$]),U=Q0((f)=>{return N.filter((Y)=>Y.type===f)},[N]),w=Q0(()=>{let Y=new Date().getTime()-J.current.getTime(),F=new Map;for(let P of N){let G=F.get(P.templateId)??0;F.set(P.templateId,G+1)}let R=Array.from(F.entries()).map(([P,G])=>({templateId:P,count:G})).sort((P,G)=>G.count-P.count).slice(0,3),W=new Map;for(let P of N)if(P.type==="mode_change"&&P.metadata?.mode){let G=P.metadata.mode,M=W.get(G)??0;W.set(G,M+1)}let Q=Array.from(W.entries()).map(([P,G])=>({mode:P,count:G})).sort((P,G)=>G.count-P.count),H=new Set;for(let P of N){if(P.type==="mode_change"&&P.metadata?.mode)H.add(P.metadata.mode);if(P.type==="feature_usage"&&P.metadata?.feature)H.add(P.metadata.feature);if(P.type==="canvas_interaction"){let G=P.metadata?.action;if(G==="add")H.add("canvas_add");if(G==="delete")H.add("canvas_delete")}if(P.type==="spec_edit"){let G=P.metadata?.action;if(G==="save")H.add("spec_save");if(G==="validate")H.add("spec_validate")}}let Z=E1.filter((P)=>!H.has(P)),A=N.filter((P)=>P.type==="error").length,L=k1(Array.from(H),Z,Q,N.length);return{totalEvents:N.length,sessionDuration:Y,mostUsedTemplates:R,mostUsedModes:Q,featuresUsed:Array.from(H),unusedFeatures:Z,errorCount:A,recommendations:L}},[N]),V=Q0(()=>{q([]),K(0),J.current=new Date,localStorage.removeItem(U0)},[]);return B1(()=>({trackEvent:z,getSummary:w,getEventsByType:U,eventCount:X,sessionStart:J.current,clear:V}),[z,w,U,X,V])}function k1($,N,q,J){let X=[];if(N.includes("evolution"))X.push("Try the AI Evolution mode to get automated improvement suggestions");if(N.includes("markdown"))X.push("Use Markdown preview to see documentation for your specs");if(N.includes("builder"))X.push("Explore the Visual Builder to design your UI components");if(!$.includes("spec_validate")&&$.includes("specs"))X.push("Don't forget to validate your specs before saving");if($.includes("evolution")&&!$.includes("ai_suggestions"))X.push("Generate AI suggestions to get actionable improvement recommendations");if(J>50)X.push("Great engagement! Consider saving your work regularly");if(q.length===1)X.push("Try different modes to explore all sandbox capabilities");return X}import{Button as u0}from"@contractspec/lib.design-system";import{Badge as A0}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as C1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as d0,useMemo as I1,useState as S1}from"react";import{jsx as b,jsxs as O}from"react/jsx-runtime";function q4({templateId:$,collapsed:N=!1,onToggle:q}){let{getSummary:J,eventCount:X,clear:K,sessionStart:z}=p0($),[U,w]=S1(!1),V=I1(()=>J(),[J]),f=d0((F)=>{let R=Math.floor(F/1000),W=Math.floor(R/60),Q=Math.floor(W/60);if(Q>0)return`${Q}h ${W%60}m`;if(W>0)return`${W}m ${R%60}s`;return`${R}s`},[]),Y=d0(()=>{K()},[K]);if(N)return O("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 text-sm transition hover:bg-blue-500/20",type:"button",children:[b("span",{children:"\uD83D\uDCCA"}),b("span",{children:"Insights"}),b(A0,{variant:"secondary",children:X})]});return O(C1,{className:"overflow-hidden",children:[O("div",{className:"flex items-center justify-between border-blue-500/20 border-b bg-blue-500/5 px-4 py-3",children:[O("div",{className:"flex items-center gap-2",children:[b("span",{children:"\uD83D\uDCCA"}),b("span",{className:"font-semibold",children:"Personalization Insights"})]}),O("div",{className:"flex items-center gap-2",children:[b(u0,{variant:"ghost",size:"sm",onPress:()=>w(!U),children:U?"Hide Details":"Show Details"}),q&&b("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),O("div",{className:"p-4",children:[O("div",{className:"mb-4 grid grid-cols-2 gap-3 md:grid-cols-4",children:[b(X0,{label:"Session Time",value:f(V.sessionDuration),icon:"⏱️"}),b(X0,{label:"Events Tracked",value:V.totalEvents.toString(),icon:"\uD83D\uDCC8"}),b(X0,{label:"Features Used",value:`${V.featuresUsed.length}/${V.featuresUsed.length+V.unusedFeatures.length}`,icon:"✨"}),b(X0,{label:"Errors",value:V.errorCount.toString(),icon:"⚠️",variant:V.errorCount>0?"warning":"success"})]}),V.recommendations.length>0&&O("div",{className:"mb-4",children:[b("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Recommendations"}),b("ul",{className:"space-y-1",children:V.recommendations.map((F,R)=>O("li",{className:"flex items-start gap-2 text-sm",children:[b("span",{className:"text-blue-400",children:"\uD83D\uDCA1"}),b("span",{children:F})]},R))})]}),V.unusedFeatures.length>0&&O("div",{className:"mb-4",children:[b("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Try These Features"}),b("div",{className:"flex flex-wrap gap-2",children:V.unusedFeatures.slice(0,5).map((F)=>b(A0,{variant:"secondary",children:w0(F)},F))})]}),U&&b(v1,{summary:V,sessionStart:z}),b("div",{className:"mt-4 flex justify-end border-blue-500/10 border-t pt-4",children:b(u0,{variant:"ghost",size:"sm",onPress:Y,children:"Clear Data"})})]})]})}function X0({label:$,value:N,icon:q,variant:J="default"}){return O("div",{className:`rounded-lg border p-3 text-center ${{default:"bg-blue-500/5 border-blue-500/20",warning:"bg-amber-500/5 border-amber-500/20",success:"bg-green-500/5 border-green-500/20"}[J]}`,children:[b("div",{className:"mb-1 text-lg",children:q}),b("div",{className:"font-bold text-lg",children:N}),b("div",{className:"text-muted-foreground text-xs",children:$})]})}function v1({summary:$,sessionStart:N}){return O("div",{className:"mt-4 space-y-4 border-blue-500/10 border-t pt-4",children:[$.mostUsedTemplates.length>0&&O("div",{children:[b("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Most Used Templates"}),b("div",{className:"space-y-1",children:$.mostUsedTemplates.map(({templateId:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[b("span",{children:y1(q)}),O("span",{className:"text-muted-foreground",children:[J," events"]})]},q))})]}),$.mostUsedModes.length>0&&O("div",{children:[b("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Mode Usage"}),b("div",{className:"space-y-1",children:$.mostUsedModes.map(({mode:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[b("span",{children:w0(q)}),O("span",{className:"text-muted-foreground",children:[J," switches"]})]},q))})]}),O("div",{children:[b("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Features Used"}),b("div",{className:"flex flex-wrap gap-2",children:$.featuresUsed.map((q)=>O(A0,{variant:"default",className:"border-green-500/30 bg-green-500/20 text-green-400",children:["✓ ",w0(q)]},q))})]}),O("div",{className:"text-muted-foreground text-xs",children:["Session started: ",N.toLocaleString()]})]})}function w0($){return $.replace(/_/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}function y1($){return $.replace(/-/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}import{Sparkles as c1}from"lucide-react";import{useState as m0}from"react";import{jsx as R0,jsxs as l0}from"react/jsx-runtime";function z0({organizationId:$="demo-org",projectName:N,endpoint:q,token:J}){let{installer:X,templateId:K,template:z}=r(),[U,w]=m0("idle"),[V,f]=m0(null);return l0("div",{className:"flex flex-col items-end gap-1",children:[l0("button",{type:"button",className:"btn-primary inline-flex items-center gap-2 text-sm",onClick:async()=>{w("saving"),f(null);try{await X.saveToStudio({templateId:K,projectName:N??`${z.name} demo`,organizationId:$,endpoint:q,token:J}),w("saved"),setTimeout(()=>w("idle"),3000)}catch(F){w("error"),f(F instanceof Error?F.message:"Unknown error")}},disabled:U==="saving",children:[R0(c1,{className:"h-4 w-4"}),U==="saving"?"Publishing…":"Save to Studio"]}),U==="error"&&V?R0("p",{className:"text-destructive text-xs",children:V}):null,U==="saved"?R0("p",{className:"text-emerald-400 text-xs",children:"Template sent to Studio."}):null]})}import{BundleProvider as r1,BundleRenderer as j1}from"@contractspec/lib.surface-runtime/react";import{jsx as S,jsxs as H0}from"react/jsx-runtime";function Y4({plan:$,title:N,description:q,sidebar:J,actions:X,showSaveAction:K=!0,saveProps:z,children:U}){let V={header:H0("header",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm",children:[H0("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[H0("div",{children:[S("p",{className:"font-semibold text-muted-foreground text-sm uppercase tracking-wide",children:"ContractSpec Templates"}),S("h1",{className:"font-bold text-3xl",children:N}),q?S("p",{className:"mt-2 max-w-2xl text-muted-foreground text-sm",children:q}):null]}),H0("div",{className:"flex flex-col items-end gap-2",children:[S(P0,{}),K?S(z0,{...z}):null]})]}),X?S("div",{className:"mt-4",children:X}):null]}),primary:S("main",{className:"space-y-4 p-2",children:U})};if(J!=null)V.sidebar=S("aside",{className:"rounded-2xl border border-border bg-card p-4",children:J});return S(r1,{plan:$,children:S(j1,{slotContent:V})})}function e($){let N=$?.id??"unknown";if(!$)return n0(N);switch(N){case"crm-pipeline":return x1($.schema.contracts);case"saas-boilerplate":return i1($.schema.contracts);case"agent-console":return g1($.schema.contracts);case"todos-app":return p1($.schema.contracts);case"messaging-app":return u1($.schema.contracts);case"recipe-app-i18n":return d1($.schema.contracts);default:return n0(N)}}function x1($){return`// CRM Pipeline Specs
|
|
2
2
|
// Contracts: ${$.join(", ")}
|
|
3
3
|
|
|
4
4
|
contractSpec("crm.deal.updateStage.v1", {
|
|
@@ -68,7 +68,7 @@ contractSpec("crm.contact.list.v1", {
|
|
|
68
68
|
hasMore: "boolean"
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
|
-
});`}function
|
|
71
|
+
});`}function i1($){return`// SaaS Boilerplate Specs
|
|
72
72
|
// Contracts: ${$.join(", ")}
|
|
73
73
|
|
|
74
74
|
contractSpec("saas.project.create.v1", {
|
|
@@ -374,8 +374,8 @@ contractSpec("${$}.main.v1", {
|
|
|
374
374
|
result: "unknown"
|
|
375
375
|
}
|
|
376
376
|
}
|
|
377
|
-
});`}import{useCallback as G0,useEffect as m1,useState as $0}from"react";var
|
|
378
|
-
`);if(!q.includes("contractSpec("))H.push({line:1,message:"Spec must contain a contractSpec() definition",severity:"error"});if(!q.includes("goal:"))H.push({line:1,message:"Spec should have a goal field",severity:"warning"});if(!q.includes("io:"))H.push({line:1,message:"Spec should define io (input/output)",severity:"warning"});let A=(q.match(/{/g)??[]).length,L=(q.match(/}/g)??[]).length;if(A!==L)H.push({line:Z.length,message:`Unbalanced braces: ${A} opening, ${L} closing`,severity:"error"});let P=(q.match(/\(/g)??[]).length,G=(q.match(/\)/g)??[]).length;if(P!==G)H.push({line:Z.length,message:`Unbalanced parentheses: ${P} opening, ${G} closing`,severity:"error"});Z.forEach((E,u)=>{let B=(E.match(/'/g)??[]).length,y=(E.match(/"/g)??[]).length;if(B%2!==0)H.push({line:u+1,message:"Unclosed single quote",severity:"error"});if(y%2!==0)H.push({line:u+1,message:"Unclosed double quote",severity:"error"})});let M={valid:H.filter((E)=>E.severity==="error").length===0,errors:H};return V(M),M},[q]),Q=G0(()=>{let H=e(N);J(H),K(H),V(null),
|
|
377
|
+
});`}import{useCallback as G0,useEffect as m1,useState as $0}from"react";var b0="contractspec-spec-content";function o0($){let{template:N}=r(),[q,J]=$0(""),[X,K]=$0(""),[z,U]=$0(!0),[w,V]=$0(null),[f,Y]=$0(null);m1(()=>{U(!0);try{let H=localStorage.getItem(`${b0}-${$}`);if(H){let Z=JSON.parse(H);if(Z.content)J(Z.content),K(Z.content),Y(Z.savedAt);else{let A=e(N);J(A),K(A)}}else{let Z=e(N);J(Z),K(Z)}}catch{let H=e(N);J(H),K(H)}U(!1)},[$]);let F=G0((H)=>{J(H),V(null)},[]),R=G0(()=>{try{let H=new Date().toISOString();localStorage.setItem(`${b0}-${$}`,JSON.stringify({content:q,savedAt:H})),K(q),Y(H)}catch{}},[q,$]),W=G0(()=>{let H=[],Z=q.split(`
|
|
378
|
+
`);if(!q.includes("contractSpec("))H.push({line:1,message:"Spec must contain a contractSpec() definition",severity:"error"});if(!q.includes("goal:"))H.push({line:1,message:"Spec should have a goal field",severity:"warning"});if(!q.includes("io:"))H.push({line:1,message:"Spec should define io (input/output)",severity:"warning"});let A=(q.match(/{/g)??[]).length,L=(q.match(/}/g)??[]).length;if(A!==L)H.push({line:Z.length,message:`Unbalanced braces: ${A} opening, ${L} closing`,severity:"error"});let P=(q.match(/\(/g)??[]).length,G=(q.match(/\)/g)??[]).length;if(P!==G)H.push({line:Z.length,message:`Unbalanced parentheses: ${P} opening, ${G} closing`,severity:"error"});Z.forEach((E,u)=>{let B=(E.match(/'/g)??[]).length,y=(E.match(/"/g)??[]).length;if(B%2!==0)H.push({line:u+1,message:"Unclosed single quote",severity:"error"});if(y%2!==0)H.push({line:u+1,message:"Unclosed double quote",severity:"error"})});let M={valid:H.filter((E)=>E.severity==="error").length===0,errors:H};return V(M),M},[q]),Q=G0(()=>{let H=e(N);J(H),K(H),V(null),Y(null);try{localStorage.removeItem(`${b0}-${$}`)}catch{}},[$]);return{content:q,loading:z,isDirty:q!==X,validation:w,setContent:F,save:R,validate:W,reset:Q,lastSaved:f}}import{Button as h0,LoaderBlock as l1}from"@contractspec/lib.design-system";import{Badge as a0}from"@contractspec/lib.ui-kit-web/ui/badge";import{useCallback as M0,useEffect as n1}from"react";import{jsx as v,jsxs as p}from"react/jsx-runtime";function M4({templateId:$,SpecEditor:N,onLog:q}){let{content:J,loading:X,isDirty:K,validation:z,setContent:U,save:w,validate:V,reset:f,lastSaved:Y}=o0($);n1(()=>{if(!X&&J)q?.(`Spec loaded for ${$}`)},[X,J,$,q]);let F=M0(()=>{w(),q?.("Spec saved locally")},[w,q]),R=M0(()=>{let Q=V();if(Q.valid)q?.("Spec validation passed");else{let H=Q.errors.filter((A)=>A.severity==="error").length,Z=Q.errors.filter((A)=>A.severity==="warning").length;q?.(`Spec validation: ${H} errors, ${Z} warnings`)}},[V,q]),W=M0(()=>{f(),q?.("Spec reset to template defaults")},[f,q]);if(X)return v(l1,{label:"Loading spec..."});return p("div",{className:"space-y-4",children:[p("div",{className:"flex items-center justify-between",children:[p("div",{className:"flex items-center gap-2",children:[v(h0,{variant:"default",size:"sm",onClick:F,children:"Save"}),v(h0,{variant:"outline",size:"sm",onClick:R,children:"Validate"}),K&&v(a0,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:"Unsaved changes"}),z&&v(a0,{variant:z.valid?"default":"destructive",className:z.valid?"border-green-500/30 bg-green-500/20 text-green-400":"",children:z.valid?"Valid":`${z.errors.filter((Q)=>Q.severity==="error").length} errors`})]}),p("div",{className:"flex items-center gap-2",children:[Y&&p("span",{className:"text-muted-foreground text-xs",children:["Last saved: ",new Date(Y).toLocaleTimeString()]}),v(h0,{variant:"ghost",size:"sm",onPress:W,children:"Reset"})]})]}),z&&z.errors.length>0&&p("div",{className:"rounded-lg border border-amber-500/50 bg-amber-500/10 p-3",children:[v("p",{className:"mb-2 font-semibold text-amber-400 text-xs uppercase",children:"Validation Issues"}),v("ul",{className:"space-y-1",children:z.errors.map((Q,H)=>p("li",{className:`text-xs ${Q.severity==="error"?"text-red-400":"text-amber-400"}`,children:["Line ",Q.line,": ",Q.message]},`${Q.line}-${Q.message}-${H}`))})]}),v("div",{className:"rounded-2xl border border-border bg-card p-4",children:v(N,{projectId:"sandbox",type:"CAPABILITY",content:J,onChange:U,metadata:{template:$},onSave:F,onValidate:R})})]})}import{jsx as j,jsxs as o}from"react/jsx-runtime";var E4=({title:$,description:N,sidebar:q,actions:J,showSaveAction:X=!0,saveProps:K,children:z})=>o("div",{className:"space-y-6",children:[o("header",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm",children:[o("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o("div",{children:[j("p",{className:"font-semibold text-muted-foreground text-sm uppercase tracking-wide",children:"ContractSpec Templates"}),j("h1",{className:"font-bold text-3xl",children:$}),N?j("p",{className:"mt-2 max-w-2xl text-muted-foreground text-sm",children:N}):null]}),o("div",{className:"flex flex-col items-end gap-2",children:[j(P0,{}),X?j(z0,{...K}):null]})]}),J?j("div",{className:"mt-4",children:J}):null]}),o("div",{className:q?"grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]":"w-full",children:[j("main",{className:"space-y-4 p-2",children:z}),q?j("aside",{className:"rounded-2xl border border-border bg-card p-4",children:q}):null]})]});import{defineFeature as o1}from"@contractspec/lib.contracts-spec/features";var S4=o1({meta:{key:"libs.example-shared-ui",version:"1.0.0",title:"Example Shared Ui",description:"ContractSpec package declaration for @contractspec/lib.example-shared-ui.",domain:"example-shared-ui",owners:["@contractspec-core"],tags:["package","libs","example-shared-ui"],stability:"experimental"}});import{useQuery as a1}from"@tanstack/react-query";function c4(){return a1({queryKey:["registryTemplates"],queryFn:async()=>{let $=process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL??"";if(!$)return[];let N=await fetch(`${$.replace(/\/$/,"")}/r/contractspec.json`,{method:"GET",headers:{Accept:"application/json"}});if(!N.ok)return[];return((await N.json()).items??[]).filter((X)=>X.type==="contractspec:template").map((X)=>({id:X.name,name:X.title??X.name,description:X.description,tags:X.meta?.tags??[],source:"registry",registryUrl:$}))}})}import{useCallback as N0,useEffect as t1,useMemo as T0,useState as K0}from"react";function x4($){let[N,q]=K0(null),[J,X]=K0([]),[K,z]=K0(!1),[U,w]=K0(null),V=T0(()=>N2($),[$]);t1(()=>{let Z=V[0];if(V.length>0&&!N&&Z)q(Z.meta.key)},[V,N]);let f=T0(()=>{return V.find((Z)=>Z.meta.key===N)??null},[V,N]),Y=N0((Z)=>{if(!f)return null;let A=J.filter((P)=>P.workflow===f.meta.key).filter((P)=>s1(P,Z)).sort((P,G)=>(P.priority??0)-(G.priority??0));if(A.length===0)return f;let L={...f,steps:[...f.steps]};for(let P of A)L=e1(L,P);return L},[f,J]),F=T0(()=>Y(),[Y]),R=N0((Z)=>{q(Z)},[]),W=N0((Z)=>{X((A)=>[...A,Z])},[]),Q=N0((Z,A)=>{X((L)=>{let P=L.filter((M)=>M.workflow===Z),G=L.filter((M)=>M.workflow!==Z);return P.splice(A,1),[...G,...P]})},[]),H=N0(()=>{let Z=F;if(!Z)return"// No workflow selected";let A=Z.steps.map((P)=>` {
|
|
379
379
|
id: '${P.id}',
|
|
380
380
|
name: '${P.name}',
|
|
381
381
|
type: '${P.type}',${P.description?`
|
|
@@ -396,7 +396,7 @@ ${L}
|
|
|
396
396
|
|
|
397
397
|
import { workflowSpec } from '@contractspec/lib.contracts-spec/workflow';
|
|
398
398
|
|
|
399
|
-
export const ${
|
|
399
|
+
export const ${$2(Z.meta.key)}Workflow = workflowSpec({
|
|
400
400
|
meta: {
|
|
401
401
|
key: '${Z.meta.key}',
|
|
402
402
|
version: ${Z.meta.version},${Z.meta.description?`
|
|
@@ -408,4 +408,4 @@ ${A}
|
|
|
408
408
|
],${Z.context?`
|
|
409
409
|
context: ${JSON.stringify(Z.context,null,2)},`:""}
|
|
410
410
|
});
|
|
411
|
-
`},[
|
|
411
|
+
`},[F,J,$]);return{workflow:F,baseWorkflows:V,extensions:J,selectWorkflow:R,addExtension:W,removeExtension:Q,compose:Y,generateSpecCode:H,loading:K,error:U}}function s1($,N){if(!N)return!0;if($.tenantId&&$.tenantId!==N.tenantId)return!1;if($.role&&$.role!==N.role)return!1;if($.device&&$.device!==N.device)return!1;return!0}function e1($,N){let q=[...$.steps];if(N.hiddenSteps)q=q.filter((J)=>!N.hiddenSteps?.includes(J.id));if(N.customSteps)for(let J of N.customSteps){let X={...J.inject,id:J.id??J.inject.id};if(J.after){let K=q.findIndex((z)=>z.id===J.after);if(K!==-1)q.splice(K+1,0,X)}else if(J.before){let K=q.findIndex((z)=>z.id===J.before);if(K!==-1)q.splice(K,0,X)}else q.push(X)}return{...$,steps:q}}function $2($){return $.replace(/[^a-zA-Z0-9]+(.)/g,(N,q)=>q.toUpperCase()).replace(/^./,(N)=>N.toLowerCase())}function N2($){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"}]}]}[$]??[]}import{useEffect as q2,useState as P2}from"react";class s0{components=new Map;listeners=new Set;register($,N){this.components.set($,N),this.listeners.forEach((q)=>q($))}get($){return this.components.get($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}}var t0=Symbol.for("@contractspec/lib.example-shared-ui/template-component-registry");function J2(){let $=globalThis;return $[t0]??=new s0,$[t0]}var V0=J2();function a4($,N){V0.register($,N)}function t4($){let[N,q]=P2(()=>V0.get($));return q2(()=>{return V0.subscribe((J)=>{if(J===$)q(V0.get($))})},[$]),N}async function e4($,N){throw Error("fetchPresentationData is deprecated. Use fetchData from TemplateRuntimeContext.")}function $3($){return!1}function N3(){return[]}import{MarkdownRenderer as z3}from"@contractspec/lib.design-system";export{x4 as useWorkflowComposer,r as useTemplateRuntime,t4 as useTemplateComponents,o0 as useSpecContent,c4 as useRegistryTemplates,d2 as useOverlayContext,m2 as useIsInOverlayContext,q0 as useEvolution,p0 as useBehaviorTracking,V0 as templateComponentRegistry,a4 as registerTemplateComponents,$3 as hasPresentationDataFetcher,N3 as getRegisteredPresentationFetchers,e as generateSpecFromTemplate,e4 as fetchPresentationData,E4 as TemplateShell,f1 as TemplateRuntimeContext,s0 as TemplateComponentRegistry,M4 as SpecEditorPanel,Y4 as SpecDrivenTemplateShell,z0 as SaveToStudioButton,q4 as PersonalizationInsights,u2 as OverlayContextProvider,x2 as MarkdownView,z3 as MarkdownRenderer,P0 as LocalDataIndicator,S4 as ExampleSharedUiFeature,A2 as EvolutionSidebar,V2 as EvolutionDashboard};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ExampleSharedUiFeature: import("@contractspec/lib.contracts-spec").FeatureModuleSpec;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{defineFeature as g}from"@contractspec/lib.contracts-spec/features";var j=g({meta:{key:"libs.example-shared-ui",version:"1.0.0",title:"Example Shared Ui",description:"ContractSpec package declaration for @contractspec/lib.example-shared-ui.",domain:"example-shared-ui",owners:["@contractspec-core"],tags:["package","libs","example-shared-ui"],stability:"experimental"}});export{j as ExampleSharedUiFeature};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { MarkdownRenderer } from '@contractspec/lib.design-system';
|
|
2
2
|
export * from './EvolutionDashboard';
|
|
3
3
|
export * from './EvolutionSidebar';
|
|
4
|
+
export * from './example-shared-ui.feature';
|
|
4
5
|
export * from './hooks';
|
|
5
6
|
export * from './LocalDataIndicator';
|
|
6
7
|
export * from './lib/component-registry';
|