@girardmedia/bootspring 1.2.0 → 2.0.3
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/README.md +107 -14
- package/bin/bootspring.js +166 -27
- package/cli/agent.js +189 -17
- package/cli/analyze.js +499 -0
- package/cli/audit.js +557 -0
- package/cli/auth.js +495 -38
- package/cli/billing.js +302 -0
- package/cli/build.js +695 -0
- package/cli/business.js +109 -26
- package/cli/checkpoint-utils.js +168 -0
- package/cli/checkpoint.js +639 -0
- package/cli/cloud-sync.js +447 -0
- package/cli/content.js +198 -0
- package/cli/context.js +1 -1
- package/cli/deploy.js +543 -0
- package/cli/fundraise.js +112 -50
- package/cli/github-cmd.js +435 -0
- package/cli/health.js +477 -0
- package/cli/init.js +84 -13
- package/cli/legal.js +107 -95
- package/cli/log.js +2 -2
- package/cli/loop.js +976 -73
- package/cli/manager.js +711 -0
- package/cli/metrics.js +480 -0
- package/cli/monitor.js +812 -0
- package/cli/onboard.js +521 -0
- package/cli/orchestrator.js +12 -24
- package/cli/prd.js +594 -0
- package/cli/preseed-start.js +1483 -0
- package/cli/preseed.js +2302 -0
- package/cli/project.js +436 -0
- package/cli/quality.js +233 -0
- package/cli/security.js +913 -0
- package/cli/seed.js +1441 -5
- package/cli/skill.js +273 -211
- package/cli/suggest.js +989 -0
- package/cli/switch.js +453 -0
- package/cli/visualize.js +527 -0
- package/cli/watch.js +769 -0
- package/cli/workspace.js +607 -0
- package/core/analyze-workflow.js +1134 -0
- package/core/api-client.js +535 -22
- package/core/audit-workflow.js +1350 -0
- package/core/build-orchestrator.js +480 -0
- package/core/build-state.js +577 -0
- package/core/checkpoint-engine.js +408 -0
- package/core/config.js +1109 -26
- package/core/context-loader.js +21 -1
- package/core/deploy-workflow.js +836 -0
- package/core/entitlements.js +93 -22
- package/core/github-sync.js +610 -0
- package/core/index.js +8 -1
- package/core/ingest.js +1111 -0
- package/core/metrics-engine.js +768 -0
- package/core/onboard-workflow.js +1007 -0
- package/core/preseed-workflow.js +934 -0
- package/core/preseed.js +1617 -0
- package/core/project-context.js +325 -0
- package/core/project-state.js +694 -0
- package/core/r2-sync.js +583 -0
- package/core/scaffold.js +525 -7
- package/core/session.js +258 -0
- package/core/task-extractor.js +758 -0
- package/core/telemetry.js +28 -6
- package/core/tier-enforcement.js +737 -0
- package/core/utils.js +38 -14
- package/generators/questionnaire.js +15 -12
- package/generators/sections/ai.js +7 -7
- package/generators/sections/content.js +300 -0
- package/generators/sections/index.js +3 -0
- package/generators/sections/plugins.js +7 -6
- package/generators/templates/build-planning.template.js +596 -0
- package/generators/templates/content.template.js +819 -0
- package/generators/templates/index.js +2 -1
- package/hooks/git-autopilot.js +1250 -0
- package/hooks/index.js +9 -0
- package/intelligence/agent-collab.js +2057 -0
- package/intelligence/auto-suggest.js +634 -0
- package/intelligence/content-gen.js +1589 -0
- package/intelligence/cross-project.js +1647 -0
- package/intelligence/index.js +184 -0
- package/intelligence/learning/insights.json +517 -7
- package/intelligence/learning/pattern-learner.js +1008 -14
- package/intelligence/memory/decision-tracker.js +1431 -31
- package/intelligence/memory/decisions.jsonl +0 -0
- package/intelligence/orchestrator.js +2896 -1
- package/intelligence/prd.js +92 -1
- package/intelligence/recommendation-weights.json +14 -2
- package/intelligence/recommendations.js +463 -9
- package/intelligence/workflow-composer.js +1451 -0
- package/marketplace/index.d.ts +324 -0
- package/marketplace/index.js +1921 -0
- package/mcp/contracts/mcp-contract.v1.json +342 -4
- package/mcp/registry.js +680 -3
- package/mcp/response-formatter.js +23 -0
- package/mcp/tools/assist-tool.js +78 -4
- package/mcp/tools/autopilot-tool.js +408 -0
- package/mcp/tools/content-tool.js +571 -0
- package/mcp/tools/dashboard-tool.js +251 -5
- package/mcp/tools/mvp-tool.js +344 -0
- package/mcp/tools/plugin-tool.js +23 -1
- package/mcp/tools/prd-tool.js +579 -0
- package/mcp/tools/seed-tool.js +447 -0
- package/mcp/tools/skill-tool.js +43 -14
- package/mcp/tools/suggest-tool.js +147 -0
- package/package.json +15 -6
- package/agents/README.md +0 -93
- package/agents/ai-integration-expert/context.md +0 -386
- package/agents/api-expert/context.md +0 -416
- package/agents/architecture-expert/context.md +0 -454
- package/agents/auth-expert/context.md +0 -399
- package/agents/backend-expert/context.md +0 -483
- package/agents/business-strategy-expert/context.md +0 -180
- package/agents/code-review-expert/context.md +0 -365
- package/agents/competitive-analysis-expert/context.md +0 -239
- package/agents/data-modeling-expert/context.md +0 -352
- package/agents/database-expert/context.md +0 -250
- package/agents/devops-expert/context.md +0 -446
- package/agents/email-expert/context.md +0 -379
- package/agents/financial-expert/context.md +0 -213
- package/agents/frontend-expert/context.md +0 -364
- package/agents/fundraising-expert/context.md +0 -257
- package/agents/growth-expert/context.md +0 -249
- package/agents/index.js +0 -140
- package/agents/investor-relations-expert/context.md +0 -266
- package/agents/legal-expert/context.md +0 -284
- package/agents/marketing-expert/context.md +0 -236
- package/agents/monitoring-expert/context.md +0 -362
- package/agents/operations-expert/context.md +0 -279
- package/agents/partnerships-expert/context.md +0 -286
- package/agents/payment-expert/context.md +0 -340
- package/agents/performance-expert/context.md +0 -377
- package/agents/private-equity-expert/context.md +0 -246
- package/agents/railway-expert/context.md +0 -284
- package/agents/research-expert/context.md +0 -245
- package/agents/sales-expert/context.md +0 -241
- package/agents/security-expert/context.md +0 -343
- package/agents/testing-expert/context.md +0 -414
- package/agents/ui-ux-expert/context.md +0 -448
- package/agents/vercel-expert/context.md +0 -426
- package/skills/index.js +0 -787
- package/skills/patterns/README.md +0 -163
- package/skills/patterns/ai/agents.md +0 -281
- package/skills/patterns/ai/claude.md +0 -138
- package/skills/patterns/ai/embeddings.md +0 -150
- package/skills/patterns/ai/rag.md +0 -266
- package/skills/patterns/ai/streaming.md +0 -170
- package/skills/patterns/ai/structured-output.md +0 -162
- package/skills/patterns/ai/tools.md +0 -154
- package/skills/patterns/analytics/tracking.md +0 -220
- package/skills/patterns/api/errors.md +0 -296
- package/skills/patterns/api/graphql.md +0 -440
- package/skills/patterns/api/middleware.md +0 -279
- package/skills/patterns/api/openapi.md +0 -285
- package/skills/patterns/api/rate-limiting.md +0 -231
- package/skills/patterns/api/route-handler.md +0 -217
- package/skills/patterns/api/server-action.md +0 -249
- package/skills/patterns/api/versioning.md +0 -443
- package/skills/patterns/api/webhooks.md +0 -247
- package/skills/patterns/auth/clerk.md +0 -132
- package/skills/patterns/auth/mfa.md +0 -313
- package/skills/patterns/auth/nextauth.md +0 -140
- package/skills/patterns/auth/oauth.md +0 -237
- package/skills/patterns/auth/rbac.md +0 -152
- package/skills/patterns/auth/session-management.md +0 -367
- package/skills/patterns/auth/session.md +0 -120
- package/skills/patterns/database/audit.md +0 -177
- package/skills/patterns/database/migrations.md +0 -177
- package/skills/patterns/database/pagination.md +0 -230
- package/skills/patterns/database/pooling.md +0 -357
- package/skills/patterns/database/prisma.md +0 -180
- package/skills/patterns/database/relations.md +0 -187
- package/skills/patterns/database/seeding.md +0 -246
- package/skills/patterns/database/soft-delete.md +0 -153
- package/skills/patterns/database/transactions.md +0 -162
- package/skills/patterns/deployment/ci-cd.md +0 -231
- package/skills/patterns/deployment/docker.md +0 -188
- package/skills/patterns/deployment/monitoring.md +0 -387
- package/skills/patterns/deployment/vercel.md +0 -160
- package/skills/patterns/email/resend.md +0 -143
- package/skills/patterns/email/templates.md +0 -245
- package/skills/patterns/email/transactional.md +0 -503
- package/skills/patterns/email/verification.md +0 -176
- package/skills/patterns/files/download.md +0 -243
- package/skills/patterns/files/upload.md +0 -239
- package/skills/patterns/i18n/nextintl.md +0 -188
- package/skills/patterns/logging/structured.md +0 -292
- package/skills/patterns/notifications/email-queue.md +0 -248
- package/skills/patterns/notifications/push.md +0 -279
- package/skills/patterns/payments/checkout.md +0 -303
- package/skills/patterns/payments/invoices.md +0 -287
- package/skills/patterns/payments/portal.md +0 -245
- package/skills/patterns/payments/stripe.md +0 -272
- package/skills/patterns/payments/subscriptions.md +0 -300
- package/skills/patterns/payments/usage.md +0 -279
- package/skills/patterns/performance/caching.md +0 -276
- package/skills/patterns/performance/code-splitting.md +0 -233
- package/skills/patterns/performance/edge.md +0 -254
- package/skills/patterns/performance/isr.md +0 -266
- package/skills/patterns/performance/lazy-loading.md +0 -281
- package/skills/patterns/realtime/sse.md +0 -327
- package/skills/patterns/realtime/websockets.md +0 -336
- package/skills/patterns/search/filtering.md +0 -329
- package/skills/patterns/search/fulltext.md +0 -260
- package/skills/patterns/security/audit-logging.md +0 -444
- package/skills/patterns/security/csrf.md +0 -234
- package/skills/patterns/security/headers.md +0 -252
- package/skills/patterns/security/sanitization.md +0 -258
- package/skills/patterns/security/secrets.md +0 -261
- package/skills/patterns/security/validation.md +0 -268
- package/skills/patterns/security/xss.md +0 -229
- package/skills/patterns/seo/metadata.md +0 -252
- package/skills/patterns/state/context.md +0 -349
- package/skills/patterns/state/react-query.md +0 -313
- package/skills/patterns/state/url-state.md +0 -482
- package/skills/patterns/state/zustand.md +0 -262
- package/skills/patterns/testing/api.md +0 -259
- package/skills/patterns/testing/component.md +0 -233
- package/skills/patterns/testing/coverage.md +0 -207
- package/skills/patterns/testing/fixtures.md +0 -225
- package/skills/patterns/testing/integration.md +0 -436
- package/skills/patterns/testing/mocking.md +0 -177
- package/skills/patterns/testing/playwright.md +0 -162
- package/skills/patterns/testing/snapshot.md +0 -175
- package/skills/patterns/testing/vitest.md +0 -307
- package/skills/patterns/ui/accordions.md +0 -395
- package/skills/patterns/ui/cards.md +0 -299
- package/skills/patterns/ui/dropdowns.md +0 -476
- package/skills/patterns/ui/empty-states.md +0 -320
- package/skills/patterns/ui/forms.md +0 -405
- package/skills/patterns/ui/inputs.md +0 -319
- package/skills/patterns/ui/layouts.md +0 -282
- package/skills/patterns/ui/loading.md +0 -291
- package/skills/patterns/ui/modals.md +0 -338
- package/skills/patterns/ui/navigation.md +0 -374
- package/skills/patterns/ui/tables.md +0 -407
- package/skills/patterns/ui/toasts.md +0 -300
- package/skills/patterns/ui/tooltips.md +0 -396
- package/skills/patterns/utils/dates.md +0 -435
- package/skills/patterns/utils/errors.md +0 -451
- package/skills/patterns/utils/formatting.md +0 -345
- package/skills/patterns/utils/validation.md +0 -434
- package/templates/bootspring.config.js +0 -83
- package/templates/business/business-model-canvas.md +0 -246
- package/templates/business/business-plan.md +0 -266
- package/templates/business/competitive-analysis.md +0 -312
- package/templates/fundraising/data-room-checklist.md +0 -300
- package/templates/fundraising/investor-research.md +0 -243
- package/templates/fundraising/pitch-deck-outline.md +0 -253
- package/templates/legal/gdpr-checklist.md +0 -339
- package/templates/legal/privacy-policy.md +0 -285
- package/templates/legal/terms-of-service.md +0 -222
- package/templates/mcp.json +0 -9
|
@@ -1,327 +0,0 @@
|
|
|
1
|
-
# Server-Sent Events Patterns
|
|
2
|
-
|
|
3
|
-
Patterns for real-time updates with Server-Sent Events.
|
|
4
|
-
|
|
5
|
-
## SSE API Route
|
|
6
|
-
|
|
7
|
-
```typescript
|
|
8
|
-
// app/api/events/route.ts
|
|
9
|
-
export const dynamic = 'force-dynamic'
|
|
10
|
-
|
|
11
|
-
export async function GET(request: Request) {
|
|
12
|
-
const encoder = new TextEncoder()
|
|
13
|
-
|
|
14
|
-
const stream = new ReadableStream({
|
|
15
|
-
async start(controller) {
|
|
16
|
-
// Send initial connection message
|
|
17
|
-
controller.enqueue(
|
|
18
|
-
encoder.encode(`data: ${JSON.stringify({ type: 'connected' })}\n\n`)
|
|
19
|
-
)
|
|
20
|
-
|
|
21
|
-
// Simulated event source
|
|
22
|
-
const interval = setInterval(() => {
|
|
23
|
-
const event = {
|
|
24
|
-
type: 'update',
|
|
25
|
-
data: { timestamp: new Date().toISOString() }
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
controller.enqueue(
|
|
29
|
-
encoder.encode(`data: ${JSON.stringify(event)}\n\n`)
|
|
30
|
-
)
|
|
31
|
-
}, 5000)
|
|
32
|
-
|
|
33
|
-
// Clean up on close
|
|
34
|
-
request.signal.addEventListener('abort', () => {
|
|
35
|
-
clearInterval(interval)
|
|
36
|
-
controller.close()
|
|
37
|
-
})
|
|
38
|
-
}
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
return new Response(stream, {
|
|
42
|
-
headers: {
|
|
43
|
-
'Content-Type': 'text/event-stream',
|
|
44
|
-
'Cache-Control': 'no-cache',
|
|
45
|
-
'Connection': 'keep-alive'
|
|
46
|
-
}
|
|
47
|
-
})
|
|
48
|
-
}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
## SSE Client Hook
|
|
52
|
-
|
|
53
|
-
```tsx
|
|
54
|
-
// hooks/useEventSource.ts
|
|
55
|
-
'use client'
|
|
56
|
-
|
|
57
|
-
import { useEffect, useRef, useState, useCallback } from 'react'
|
|
58
|
-
|
|
59
|
-
interface UseEventSourceOptions {
|
|
60
|
-
url: string
|
|
61
|
-
onMessage?: (event: MessageEvent) => void
|
|
62
|
-
onError?: (error: Event) => void
|
|
63
|
-
onOpen?: () => void
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function useEventSource({ url, onMessage, onError, onOpen }: UseEventSourceOptions) {
|
|
67
|
-
const eventSourceRef = useRef<EventSource | null>(null)
|
|
68
|
-
const [isConnected, setIsConnected] = useState(false)
|
|
69
|
-
|
|
70
|
-
useEffect(() => {
|
|
71
|
-
const eventSource = new EventSource(url)
|
|
72
|
-
eventSourceRef.current = eventSource
|
|
73
|
-
|
|
74
|
-
eventSource.onopen = () => {
|
|
75
|
-
setIsConnected(true)
|
|
76
|
-
onOpen?.()
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
eventSource.onmessage = (event) => {
|
|
80
|
-
onMessage?.(event)
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
eventSource.onerror = (error) => {
|
|
84
|
-
setIsConnected(false)
|
|
85
|
-
onError?.(error)
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
return () => {
|
|
89
|
-
eventSource.close()
|
|
90
|
-
}
|
|
91
|
-
}, [url, onMessage, onError, onOpen])
|
|
92
|
-
|
|
93
|
-
const close = useCallback(() => {
|
|
94
|
-
eventSourceRef.current?.close()
|
|
95
|
-
}, [])
|
|
96
|
-
|
|
97
|
-
return { isConnected, close }
|
|
98
|
-
}
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
## Notification Stream
|
|
102
|
-
|
|
103
|
-
```tsx
|
|
104
|
-
// components/NotificationStream.tsx
|
|
105
|
-
'use client'
|
|
106
|
-
|
|
107
|
-
import { useState } from 'react'
|
|
108
|
-
import { useEventSource } from '@/hooks/useEventSource'
|
|
109
|
-
|
|
110
|
-
interface Notification {
|
|
111
|
-
id: string
|
|
112
|
-
type: string
|
|
113
|
-
message: string
|
|
114
|
-
timestamp: string
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function NotificationStream({ userId }: { userId: string }) {
|
|
118
|
-
const [notifications, setNotifications] = useState<Notification[]>([])
|
|
119
|
-
|
|
120
|
-
useEventSource({
|
|
121
|
-
url: `/api/notifications/stream?userId=${userId}`,
|
|
122
|
-
onMessage: (event) => {
|
|
123
|
-
const data = JSON.parse(event.data)
|
|
124
|
-
|
|
125
|
-
if (data.type === 'notification') {
|
|
126
|
-
setNotifications(prev => [data.notification, ...prev].slice(0, 50))
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
})
|
|
130
|
-
|
|
131
|
-
return (
|
|
132
|
-
<div className="space-y-2">
|
|
133
|
-
{notifications.map(notification => (
|
|
134
|
-
<div key={notification.id} className="rounded border p-3">
|
|
135
|
-
<p>{notification.message}</p>
|
|
136
|
-
<span className="text-sm text-gray-500">
|
|
137
|
-
{new Date(notification.timestamp).toLocaleTimeString()}
|
|
138
|
-
</span>
|
|
139
|
-
</div>
|
|
140
|
-
))}
|
|
141
|
-
</div>
|
|
142
|
-
)
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// API route
|
|
146
|
-
// app/api/notifications/stream/route.ts
|
|
147
|
-
export async function GET(request: Request) {
|
|
148
|
-
const { searchParams } = new URL(request.url)
|
|
149
|
-
const userId = searchParams.get('userId')
|
|
150
|
-
|
|
151
|
-
const encoder = new TextEncoder()
|
|
152
|
-
|
|
153
|
-
const stream = new ReadableStream({
|
|
154
|
-
async start(controller) {
|
|
155
|
-
// Subscribe to notification events
|
|
156
|
-
const unsubscribe = subscribeToNotifications(userId!, (notification) => {
|
|
157
|
-
controller.enqueue(
|
|
158
|
-
encoder.encode(`data: ${JSON.stringify({
|
|
159
|
-
type: 'notification',
|
|
160
|
-
notification
|
|
161
|
-
})}\n\n`)
|
|
162
|
-
)
|
|
163
|
-
})
|
|
164
|
-
|
|
165
|
-
request.signal.addEventListener('abort', () => {
|
|
166
|
-
unsubscribe()
|
|
167
|
-
controller.close()
|
|
168
|
-
})
|
|
169
|
-
}
|
|
170
|
-
})
|
|
171
|
-
|
|
172
|
-
return new Response(stream, {
|
|
173
|
-
headers: {
|
|
174
|
-
'Content-Type': 'text/event-stream',
|
|
175
|
-
'Cache-Control': 'no-cache',
|
|
176
|
-
'Connection': 'keep-alive'
|
|
177
|
-
}
|
|
178
|
-
})
|
|
179
|
-
}
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
## Progress Streaming
|
|
183
|
-
|
|
184
|
-
```typescript
|
|
185
|
-
// app/api/process/route.ts
|
|
186
|
-
export async function POST(request: Request) {
|
|
187
|
-
const { taskId } = await request.json()
|
|
188
|
-
|
|
189
|
-
const encoder = new TextEncoder()
|
|
190
|
-
|
|
191
|
-
const stream = new ReadableStream({
|
|
192
|
-
async start(controller) {
|
|
193
|
-
// Simulate long-running process with progress updates
|
|
194
|
-
const steps = ['Initializing', 'Processing', 'Validating', 'Completing']
|
|
195
|
-
|
|
196
|
-
for (let i = 0; i < steps.length; i++) {
|
|
197
|
-
// Send progress update
|
|
198
|
-
controller.enqueue(
|
|
199
|
-
encoder.encode(`data: ${JSON.stringify({
|
|
200
|
-
type: 'progress',
|
|
201
|
-
step: steps[i],
|
|
202
|
-
progress: ((i + 1) / steps.length) * 100
|
|
203
|
-
})}\n\n`)
|
|
204
|
-
)
|
|
205
|
-
|
|
206
|
-
// Simulate work
|
|
207
|
-
await new Promise(resolve => setTimeout(resolve, 1000))
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Send completion
|
|
211
|
-
controller.enqueue(
|
|
212
|
-
encoder.encode(`data: ${JSON.stringify({
|
|
213
|
-
type: 'complete',
|
|
214
|
-
result: { success: true }
|
|
215
|
-
})}\n\n`)
|
|
216
|
-
)
|
|
217
|
-
|
|
218
|
-
controller.close()
|
|
219
|
-
}
|
|
220
|
-
})
|
|
221
|
-
|
|
222
|
-
return new Response(stream, {
|
|
223
|
-
headers: {
|
|
224
|
-
'Content-Type': 'text/event-stream',
|
|
225
|
-
'Cache-Control': 'no-cache'
|
|
226
|
-
}
|
|
227
|
-
})
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// Client component
|
|
231
|
-
function ProcessTracker({ taskId }: { taskId: string }) {
|
|
232
|
-
const [progress, setProgress] = useState(0)
|
|
233
|
-
const [step, setStep] = useState('')
|
|
234
|
-
const [isComplete, setIsComplete] = useState(false)
|
|
235
|
-
|
|
236
|
-
useEffect(() => {
|
|
237
|
-
const eventSource = new EventSource(`/api/process?taskId=${taskId}`)
|
|
238
|
-
|
|
239
|
-
eventSource.onmessage = (event) => {
|
|
240
|
-
const data = JSON.parse(event.data)
|
|
241
|
-
|
|
242
|
-
if (data.type === 'progress') {
|
|
243
|
-
setProgress(data.progress)
|
|
244
|
-
setStep(data.step)
|
|
245
|
-
} else if (data.type === 'complete') {
|
|
246
|
-
setIsComplete(true)
|
|
247
|
-
eventSource.close()
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
return () => eventSource.close()
|
|
252
|
-
}, [taskId])
|
|
253
|
-
|
|
254
|
-
return (
|
|
255
|
-
<div>
|
|
256
|
-
<div className="mb-2">{step}</div>
|
|
257
|
-
<div className="h-2 rounded-full bg-gray-200">
|
|
258
|
-
<div
|
|
259
|
-
className="h-2 rounded-full bg-blue-600 transition-all"
|
|
260
|
-
style={{ width: `${progress}%` }}
|
|
261
|
-
/>
|
|
262
|
-
</div>
|
|
263
|
-
{isComplete && <p className="mt-2 text-green-600">Complete!</p>}
|
|
264
|
-
</div>
|
|
265
|
-
)
|
|
266
|
-
}
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
## Named Events
|
|
270
|
-
|
|
271
|
-
```typescript
|
|
272
|
-
// app/api/events/route.ts
|
|
273
|
-
export async function GET(request: Request) {
|
|
274
|
-
const encoder = new TextEncoder()
|
|
275
|
-
|
|
276
|
-
const stream = new ReadableStream({
|
|
277
|
-
async start(controller) {
|
|
278
|
-
// Send named events
|
|
279
|
-
const sendEvent = (eventName: string, data: any) => {
|
|
280
|
-
controller.enqueue(
|
|
281
|
-
encoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`)
|
|
282
|
-
)
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
sendEvent('user_online', { userId: '123', name: 'John' })
|
|
286
|
-
sendEvent('message', { text: 'Hello!' })
|
|
287
|
-
sendEvent('notification', { type: 'alert', message: 'New update' })
|
|
288
|
-
|
|
289
|
-
// Keep alive
|
|
290
|
-
const keepAlive = setInterval(() => {
|
|
291
|
-
controller.enqueue(encoder.encode(`: keep-alive\n\n`))
|
|
292
|
-
}, 15000)
|
|
293
|
-
|
|
294
|
-
request.signal.addEventListener('abort', () => {
|
|
295
|
-
clearInterval(keepAlive)
|
|
296
|
-
controller.close()
|
|
297
|
-
})
|
|
298
|
-
}
|
|
299
|
-
})
|
|
300
|
-
|
|
301
|
-
return new Response(stream, {
|
|
302
|
-
headers: { 'Content-Type': 'text/event-stream' }
|
|
303
|
-
})
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
// Client with named events
|
|
307
|
-
const eventSource = new EventSource('/api/events')
|
|
308
|
-
|
|
309
|
-
eventSource.addEventListener('user_online', (e) => {
|
|
310
|
-
console.log('User online:', JSON.parse(e.data))
|
|
311
|
-
})
|
|
312
|
-
|
|
313
|
-
eventSource.addEventListener('message', (e) => {
|
|
314
|
-
console.log('Message:', JSON.parse(e.data))
|
|
315
|
-
})
|
|
316
|
-
|
|
317
|
-
eventSource.addEventListener('notification', (e) => {
|
|
318
|
-
console.log('Notification:', JSON.parse(e.data))
|
|
319
|
-
})
|
|
320
|
-
```
|
|
321
|
-
|
|
322
|
-
## When to Use
|
|
323
|
-
|
|
324
|
-
- Live updates
|
|
325
|
-
- Progress tracking
|
|
326
|
-
- Notifications
|
|
327
|
-
- Stock prices
|
|
@@ -1,336 +0,0 @@
|
|
|
1
|
-
# WebSocket Patterns
|
|
2
|
-
|
|
3
|
-
Patterns for real-time communication with WebSockets.
|
|
4
|
-
|
|
5
|
-
## WebSocket Client Hook
|
|
6
|
-
|
|
7
|
-
```tsx
|
|
8
|
-
// hooks/useWebSocket.ts
|
|
9
|
-
'use client'
|
|
10
|
-
|
|
11
|
-
import { useEffect, useRef, useState, useCallback } from 'react'
|
|
12
|
-
|
|
13
|
-
interface UseWebSocketOptions {
|
|
14
|
-
url: string
|
|
15
|
-
onMessage?: (data: any) => void
|
|
16
|
-
onOpen?: () => void
|
|
17
|
-
onClose?: () => void
|
|
18
|
-
onError?: (error: Event) => void
|
|
19
|
-
reconnect?: boolean
|
|
20
|
-
reconnectInterval?: number
|
|
21
|
-
maxReconnectAttempts?: number
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export function useWebSocket({
|
|
25
|
-
url,
|
|
26
|
-
onMessage,
|
|
27
|
-
onOpen,
|
|
28
|
-
onClose,
|
|
29
|
-
onError,
|
|
30
|
-
reconnect = true,
|
|
31
|
-
reconnectInterval = 3000,
|
|
32
|
-
maxReconnectAttempts = 5
|
|
33
|
-
}: UseWebSocketOptions) {
|
|
34
|
-
const wsRef = useRef<WebSocket | null>(null)
|
|
35
|
-
const reconnectAttemptsRef = useRef(0)
|
|
36
|
-
const [isConnected, setIsConnected] = useState(false)
|
|
37
|
-
|
|
38
|
-
const connect = useCallback(() => {
|
|
39
|
-
try {
|
|
40
|
-
wsRef.current = new WebSocket(url)
|
|
41
|
-
|
|
42
|
-
wsRef.current.onopen = () => {
|
|
43
|
-
setIsConnected(true)
|
|
44
|
-
reconnectAttemptsRef.current = 0
|
|
45
|
-
onOpen?.()
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
wsRef.current.onmessage = (event) => {
|
|
49
|
-
const data = JSON.parse(event.data)
|
|
50
|
-
onMessage?.(data)
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
wsRef.current.onclose = () => {
|
|
54
|
-
setIsConnected(false)
|
|
55
|
-
onClose?.()
|
|
56
|
-
|
|
57
|
-
if (reconnect && reconnectAttemptsRef.current < maxReconnectAttempts) {
|
|
58
|
-
reconnectAttemptsRef.current++
|
|
59
|
-
setTimeout(connect, reconnectInterval)
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
wsRef.current.onerror = (error) => {
|
|
64
|
-
onError?.(error)
|
|
65
|
-
}
|
|
66
|
-
} catch (error) {
|
|
67
|
-
console.error('WebSocket connection error:', error)
|
|
68
|
-
}
|
|
69
|
-
}, [url, onMessage, onOpen, onClose, onError, reconnect, reconnectInterval, maxReconnectAttempts])
|
|
70
|
-
|
|
71
|
-
useEffect(() => {
|
|
72
|
-
connect()
|
|
73
|
-
|
|
74
|
-
return () => {
|
|
75
|
-
wsRef.current?.close()
|
|
76
|
-
}
|
|
77
|
-
}, [connect])
|
|
78
|
-
|
|
79
|
-
const send = useCallback((data: any) => {
|
|
80
|
-
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
|
81
|
-
wsRef.current.send(JSON.stringify(data))
|
|
82
|
-
}
|
|
83
|
-
}, [])
|
|
84
|
-
|
|
85
|
-
return { isConnected, send }
|
|
86
|
-
}
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
## Chat Application
|
|
90
|
-
|
|
91
|
-
```tsx
|
|
92
|
-
// components/Chat.tsx
|
|
93
|
-
'use client'
|
|
94
|
-
|
|
95
|
-
import { useState, useEffect, useRef } from 'react'
|
|
96
|
-
import { useWebSocket } from '@/hooks/useWebSocket'
|
|
97
|
-
|
|
98
|
-
interface Message {
|
|
99
|
-
id: string
|
|
100
|
-
userId: string
|
|
101
|
-
content: string
|
|
102
|
-
timestamp: string
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export function Chat({ roomId, userId }: { roomId: string; userId: string }) {
|
|
106
|
-
const [messages, setMessages] = useState<Message[]>([])
|
|
107
|
-
const [input, setInput] = useState('')
|
|
108
|
-
const messagesEndRef = useRef<HTMLDivElement>(null)
|
|
109
|
-
|
|
110
|
-
const { isConnected, send } = useWebSocket({
|
|
111
|
-
url: `${process.env.NEXT_PUBLIC_WS_URL}/chat/${roomId}`,
|
|
112
|
-
onMessage: (data) => {
|
|
113
|
-
switch (data.type) {
|
|
114
|
-
case 'message':
|
|
115
|
-
setMessages(prev => [...prev, data.message])
|
|
116
|
-
break
|
|
117
|
-
case 'history':
|
|
118
|
-
setMessages(data.messages)
|
|
119
|
-
break
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
})
|
|
123
|
-
|
|
124
|
-
// Auto-scroll to bottom
|
|
125
|
-
useEffect(() => {
|
|
126
|
-
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
|
127
|
-
}, [messages])
|
|
128
|
-
|
|
129
|
-
const handleSend = () => {
|
|
130
|
-
if (!input.trim()) return
|
|
131
|
-
|
|
132
|
-
send({
|
|
133
|
-
type: 'message',
|
|
134
|
-
content: input,
|
|
135
|
-
userId
|
|
136
|
-
})
|
|
137
|
-
|
|
138
|
-
setInput('')
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
return (
|
|
142
|
-
<div className="flex h-[500px] flex-col rounded-lg border">
|
|
143
|
-
{/* Status */}
|
|
144
|
-
<div className="border-b p-2 text-sm">
|
|
145
|
-
{isConnected ? (
|
|
146
|
-
<span className="text-green-600">Connected</span>
|
|
147
|
-
) : (
|
|
148
|
-
<span className="text-red-600">Disconnected</span>
|
|
149
|
-
)}
|
|
150
|
-
</div>
|
|
151
|
-
|
|
152
|
-
{/* Messages */}
|
|
153
|
-
<div className="flex-1 overflow-y-auto p-4 space-y-2">
|
|
154
|
-
{messages.map(msg => (
|
|
155
|
-
<div
|
|
156
|
-
key={msg.id}
|
|
157
|
-
className={`rounded-lg p-2 ${
|
|
158
|
-
msg.userId === userId ? 'ml-auto bg-blue-500 text-white' : 'bg-gray-100'
|
|
159
|
-
}`}
|
|
160
|
-
>
|
|
161
|
-
{msg.content}
|
|
162
|
-
</div>
|
|
163
|
-
))}
|
|
164
|
-
<div ref={messagesEndRef} />
|
|
165
|
-
</div>
|
|
166
|
-
|
|
167
|
-
{/* Input */}
|
|
168
|
-
<div className="border-t p-2">
|
|
169
|
-
<div className="flex gap-2">
|
|
170
|
-
<input
|
|
171
|
-
value={input}
|
|
172
|
-
onChange={(e) => setInput(e.target.value)}
|
|
173
|
-
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
|
|
174
|
-
placeholder="Type a message..."
|
|
175
|
-
className="flex-1 rounded-lg border px-3 py-2"
|
|
176
|
-
/>
|
|
177
|
-
<button
|
|
178
|
-
onClick={handleSend}
|
|
179
|
-
disabled={!isConnected}
|
|
180
|
-
className="rounded-lg bg-blue-500 px-4 py-2 text-white"
|
|
181
|
-
>
|
|
182
|
-
Send
|
|
183
|
-
</button>
|
|
184
|
-
</div>
|
|
185
|
-
</div>
|
|
186
|
-
</div>
|
|
187
|
-
)
|
|
188
|
-
}
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
## Server-Side WebSocket (Node.js)
|
|
192
|
-
|
|
193
|
-
```typescript
|
|
194
|
-
// server/websocket.ts
|
|
195
|
-
import { WebSocketServer, WebSocket } from 'ws'
|
|
196
|
-
|
|
197
|
-
interface Client {
|
|
198
|
-
ws: WebSocket
|
|
199
|
-
userId: string
|
|
200
|
-
roomId: string
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const clients = new Map<string, Client>()
|
|
204
|
-
|
|
205
|
-
export function setupWebSocket(server: any) {
|
|
206
|
-
const wss = new WebSocketServer({ server, path: '/ws' })
|
|
207
|
-
|
|
208
|
-
wss.on('connection', (ws, request) => {
|
|
209
|
-
const url = new URL(request.url!, `http://${request.headers.host}`)
|
|
210
|
-
const roomId = url.searchParams.get('room')
|
|
211
|
-
const userId = url.searchParams.get('user')
|
|
212
|
-
|
|
213
|
-
if (!roomId || !userId) {
|
|
214
|
-
ws.close(1008, 'Missing room or user')
|
|
215
|
-
return
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const clientId = `${userId}-${Date.now()}`
|
|
219
|
-
clients.set(clientId, { ws, userId, roomId })
|
|
220
|
-
|
|
221
|
-
// Send history
|
|
222
|
-
ws.send(JSON.stringify({
|
|
223
|
-
type: 'history',
|
|
224
|
-
messages: getMessageHistory(roomId)
|
|
225
|
-
}))
|
|
226
|
-
|
|
227
|
-
// Notify room
|
|
228
|
-
broadcastToRoom(roomId, {
|
|
229
|
-
type: 'user_joined',
|
|
230
|
-
userId
|
|
231
|
-
}, clientId)
|
|
232
|
-
|
|
233
|
-
ws.on('message', (data) => {
|
|
234
|
-
try {
|
|
235
|
-
const message = JSON.parse(data.toString())
|
|
236
|
-
|
|
237
|
-
if (message.type === 'message') {
|
|
238
|
-
const savedMessage = saveMessage({
|
|
239
|
-
roomId,
|
|
240
|
-
userId,
|
|
241
|
-
content: message.content
|
|
242
|
-
})
|
|
243
|
-
|
|
244
|
-
broadcastToRoom(roomId, {
|
|
245
|
-
type: 'message',
|
|
246
|
-
message: savedMessage
|
|
247
|
-
})
|
|
248
|
-
}
|
|
249
|
-
} catch (error) {
|
|
250
|
-
console.error('Message handling error:', error)
|
|
251
|
-
}
|
|
252
|
-
})
|
|
253
|
-
|
|
254
|
-
ws.on('close', () => {
|
|
255
|
-
clients.delete(clientId)
|
|
256
|
-
broadcastToRoom(roomId, {
|
|
257
|
-
type: 'user_left',
|
|
258
|
-
userId
|
|
259
|
-
})
|
|
260
|
-
})
|
|
261
|
-
})
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
function broadcastToRoom(roomId: string, data: any, excludeClient?: string) {
|
|
265
|
-
const message = JSON.stringify(data)
|
|
266
|
-
|
|
267
|
-
clients.forEach((client, clientId) => {
|
|
268
|
-
if (client.roomId === roomId && clientId !== excludeClient) {
|
|
269
|
-
if (client.ws.readyState === WebSocket.OPEN) {
|
|
270
|
-
client.ws.send(message)
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
})
|
|
274
|
-
}
|
|
275
|
-
```
|
|
276
|
-
|
|
277
|
-
## Presence System
|
|
278
|
-
|
|
279
|
-
```tsx
|
|
280
|
-
// hooks/usePresence.ts
|
|
281
|
-
'use client'
|
|
282
|
-
|
|
283
|
-
import { useState, useEffect } from 'react'
|
|
284
|
-
import { useWebSocket } from './useWebSocket'
|
|
285
|
-
|
|
286
|
-
interface User {
|
|
287
|
-
id: string
|
|
288
|
-
name: string
|
|
289
|
-
status: 'online' | 'away' | 'offline'
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
export function usePresence(roomId: string, currentUser: User) {
|
|
293
|
-
const [users, setUsers] = useState<User[]>([])
|
|
294
|
-
|
|
295
|
-
const { send } = useWebSocket({
|
|
296
|
-
url: `${process.env.NEXT_PUBLIC_WS_URL}/presence/${roomId}`,
|
|
297
|
-
onMessage: (data) => {
|
|
298
|
-
switch (data.type) {
|
|
299
|
-
case 'presence_update':
|
|
300
|
-
setUsers(data.users)
|
|
301
|
-
break
|
|
302
|
-
case 'user_status':
|
|
303
|
-
setUsers(prev =>
|
|
304
|
-
prev.map(u => u.id === data.userId ? { ...u, status: data.status } : u)
|
|
305
|
-
)
|
|
306
|
-
break
|
|
307
|
-
}
|
|
308
|
-
},
|
|
309
|
-
onOpen: () => {
|
|
310
|
-
send({ type: 'join', user: currentUser })
|
|
311
|
-
}
|
|
312
|
-
})
|
|
313
|
-
|
|
314
|
-
// Send heartbeat
|
|
315
|
-
useEffect(() => {
|
|
316
|
-
const interval = setInterval(() => {
|
|
317
|
-
send({ type: 'heartbeat' })
|
|
318
|
-
}, 30000)
|
|
319
|
-
|
|
320
|
-
return () => clearInterval(interval)
|
|
321
|
-
}, [send])
|
|
322
|
-
|
|
323
|
-
const updateStatus = (status: User['status']) => {
|
|
324
|
-
send({ type: 'status', status })
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
return { users, updateStatus }
|
|
328
|
-
}
|
|
329
|
-
```
|
|
330
|
-
|
|
331
|
-
## When to Use
|
|
332
|
-
|
|
333
|
-
- Real-time chat
|
|
334
|
-
- Live notifications
|
|
335
|
-
- Collaborative editing
|
|
336
|
-
- Gaming
|