@devbie/fewbie-cli 0.1.0 → 0.3.0
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/dist/registry/api-client/item.json +2 -2
- package/dist/registry/app-shell/item.json +20 -0
- package/dist/registry/page-header/item.json +2 -2
- package/dist/registry/password-checklist/item.json +15 -0
- package/dist/registry/query-client/item.json +23 -0
- package/dist/registry/settings-required-state/item.json +2 -5
- package/dist/registry/sse-stream/item.json +15 -0
- package/dist/registry/web-monitor-sdk/item.json +2 -2
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "api-client",
|
|
4
4
|
"type": "registry:lib",
|
|
5
5
|
"title": "API client",
|
|
6
|
-
"description": "
|
|
6
|
+
"description": "Envelope-aware axios instance with bearer-token auth, httpOnly refresh-cookie rotation, cross-tab Web Lock single-flight 401 retry, proactive token refresh, and UI-agnostic onError/onSessionExpired hooks.",
|
|
7
7
|
"dependencies": [
|
|
8
8
|
"axios@^1.20.0"
|
|
9
9
|
],
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"files": [
|
|
12
12
|
{
|
|
13
13
|
"path": "src/lib/api-client.ts",
|
|
14
|
-
"content": "import axios, { type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from \"axios\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Base URL of the API; same-origin by default. */\nconst BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? \"\";\n\n/** localStorage key of the short-lived access token. */\nconst ACCESS_TOKEN_KEY = \"access-token\";\n\n/** localStorage key of the access-token expiry epoch in milliseconds. */\nconst ACCESS_TOKEN_EXPIRES_AT_KEY = \"access-token-expires-at\";\n\n/** Endpoint that exchanges the httpOnly refresh cookie for a new access token. */\nconst REFRESH_PATH = \"/auth/refresh-access-token\";\n\n/** Paths that must never trigger a silent refresh (would recurse). */\nconst AUTH_PATH_PATTERN = /^\\/auth\\//;\n\n/** Refresh this early so business requests never carry an expired token. */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/** How often the proactive scheduler checks expiry. */\nconst PROACTIVE_REFRESH_CHECK_INTERVAL_MS = 30_000;\n\n/**\n * Pause before retrying a failed refresh. When another tab rotates the\n * refresh cookie, its Set-Cookie reaches this tab a moment later; the retry\n * then carries the renewed cookie.\n */\nconst REFRESH_RETRY_DELAY_MS = 1_500;\n\n// ---------------------------------------------------------------------------\n// Token storage\n// ---------------------------------------------------------------------------\n\nexport function getAccessToken(): string {\n if (typeof window === \"undefined\") return \"\";\n return window.localStorage.getItem(ACCESS_TOKEN_KEY) ?? \"\";\n}\n\n/** Persist token + expiry after login or refresh. */\nexport function setSession(token: string, expiresInSeconds?: number): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(ACCESS_TOKEN_KEY, token);\n if (typeof expiresInSeconds === \"number\" && expiresInSeconds > 0) {\n window.localStorage.setItem(ACCESS_TOKEN_EXPIRES_AT_KEY, String(Date.now() + expiresInSeconds * 1000));\n }\n}\n\n/** Remove all locally stored session data. */\nexport function clearSession(): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.removeItem(ACCESS_TOKEN_KEY);\n window.localStorage.removeItem(ACCESS_TOKEN_EXPIRES_AT_KEY);\n}\n\n/** Normalized error so callers never depend on the axios error shape. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly data: unknown;\n\n constructor(message: string, status: number, data: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.data = data;\n }\n}\n\n/**\n * Hook invoked when the refresh cookie is missing/expired. Wire it to your\n * router (e.g. redirect to the login page); the client itself stays\n * router-agnostic.\n */\nlet sessionExpiredHandler: (() => void) | null = null;\nexport function onSessionExpired(handler: () => void): void {\n sessionExpiredHandler = handler;\n}\n\n// ---------------------------------------------------------------------------\n// Refresh-token rotation\n// ---------------------------------------------------------------------------\n\nfunction isUnauthorized(error: unknown): boolean {\n return axios.isAxiosError(error) && error.response?.status === 401;\n}\n\n/** One refresh round-trip; persists the renewed token and its expiry. */\nasync function requestRefreshOnce(): Promise<string | null> {\n const response = await axios.get(`${BASE_URL}${REFRESH_PATH}`, {\n withCredentials: true,\n });\n // Default envelope: { token, tokenExpiresInSeconds }.\n const data = response.data as {\n token?: string;\n tokenExpiresInSeconds?: number;\n };\n if (!data?.token) return null;\n setSession(data.token, data.tokenExpiresInSeconds);\n return data.token;\n}\n\n// Shared in-flight refresh. The backend rotates the refresh cookie on every\n// call, so concurrent 401s must await the same request instead of issuing\n// parallel refreshes that invalidate each other's cookie.\nlet refreshPromise: Promise<string | null> | null = null;\n\n/** Exchange the httpOnly refresh cookie for a new access token (single-flight). */\nfunction refreshAccessToken(): Promise<string | null> {\n if (refreshPromise) return refreshPromise;\n\n refreshPromise = (async () => {\n try {\n return await requestRefreshOnce();\n } catch (firstError) {\n if (!isUnauthorized(firstError)) return null;\n // Possible cross-tab cookie rotation: retry once after a short pause.\n await new Promise((resolve) => setTimeout(resolve, REFRESH_RETRY_DELAY_MS));\n try {\n return await requestRefreshOnce();\n } catch {\n return null;\n }\n } finally {\n refreshPromise = null;\n }\n })();\n\n return refreshPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Proactive refresh scheduler (module-level singleton)\n// ---------------------------------------------------------------------------\n\nlet schedulerTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Start the scheduler that renews the token shortly before expiry. Call once\n * on the client (e.g. in the authenticated layout). Reactive 401 refresh\n * stays as a fallback for laptop sleep / scheduler drift.\n */\nexport function initProactiveTokenRefresh(): void {\n if (typeof window === \"undefined\" || schedulerTimer) return;\n\n const refreshIfDue = (): void => {\n const token = getAccessToken();\n const expiresAt = Number(window.localStorage.getItem(ACCESS_TOKEN_EXPIRES_AT_KEY) ?? 0);\n if (token && expiresAt && Date.now() >= expiresAt - PROACTIVE_REFRESH_LEAD_MS) {\n void refreshAccessToken();\n }\n };\n\n // Run immediately (tabs reopened after sleep) and then on an interval.\n refreshIfDue();\n schedulerTimer = setInterval(refreshIfDue, PROACTIVE_REFRESH_CHECK_INTERVAL_MS);\n}\n\n// ---------------------------------------------------------------------------\n// Axios instance\n// ---------------------------------------------------------------------------\n\nexport const api = axios.create({\n baseURL: BASE_URL,\n withCredentials: true,\n});\n\napi.interceptors.request.use((config) => {\n const token = getAccessToken();\n // Within the interceptor chain headers is always an AxiosHeaders instance.\n if (token) {\n config.headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return config;\n});\n\napi.interceptors.response.use(\n (response) => response,\n async (error) => {\n const original = error?.config as (InternalAxiosRequestConfig & { _retriedAfterRefresh?: boolean }) | undefined;\n const url: string = original?.url ?? \"\";\n const canSilentlyRefresh =\n typeof window !== \"undefined\" && !original?._retriedAfterRefresh && !AUTH_PATH_PATTERN.test(url);\n\n if (isUnauthorized(error) && original && canSilentlyRefresh) {\n original._retriedAfterRefresh = true;\n const renewed = await refreshAccessToken();\n if (renewed) {\n original.headers.set(\"Authorization\", `Bearer ${renewed}`);\n return api(original);\n }\n // Refresh cookie missing or expired: the session is over.\n clearSession();\n sessionExpiredHandler?.();\n }\n\n if (axios.isAxiosError(error)) {\n const data = error.response?.data as { message?: string } | undefined;\n throw new ApiError(data?.message ?? error.message, error.response?.status ?? 0, data);\n }\n throw error;\n },\n);\n\n// ---------------------------------------------------------------------------\n// Typed convenience methods — return the response body directly.\n// ---------------------------------------------------------------------------\n\nexport const apiClient = {\n get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.get<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.post<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.put<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.patch<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.delete<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n // HEAD/OPTIONS responses carry no body; resolve to the full AxiosResponse\n // so callers can still inspect status and headers.\n head<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.head<unknown, AxiosResponse<T>>(url, config);\n },\n options<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.options<unknown, AxiosResponse<T>>(url, config);\n },\n};\n",
|
|
14
|
+
"content": "import axios, { type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from \"axios\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Base URL of the API; same-origin by default. */\nconst BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? \"\";\n\n/** localStorage key of the short-lived access token. */\nconst ACCESS_TOKEN_KEY = \"access-token\";\n\n/** localStorage key of the access-token expiry epoch in milliseconds. */\nconst ACCESS_TOKEN_EXPIRES_AT_KEY = \"access-token-expires-at\";\n\n/** Endpoint that exchanges the httpOnly refresh cookie for a new access token. */\nconst REFRESH_PATH = \"/auth/refresh-access-token\";\n\n/** Paths that must never trigger a silent refresh (would recurse). */\nconst AUTH_PATH_PATTERN = /^\\/auth\\//;\n\n/** Cross-tab Web Lock that serializes refresh calls (see ADR-001). */\nconst REFRESH_LOCK_NAME = \"refresh-token\";\n\n/** Refresh this early so business requests never carry an expired token. */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/** How often the proactive scheduler checks expiry. */\nconst PROACTIVE_REFRESH_CHECK_INTERVAL_MS = 30_000;\n\n/**\n * Pause before retrying a failed refresh. When another tab rotates the\n * refresh cookie, the Set-Cookie reaches this tab a moment later; the retry\n * then carries the renewed cookie.\n */\nconst REFRESH_RETRY_DELAY_MS = 1_500;\n\n// ---------------------------------------------------------------------------\n// Response envelope (newbie backend contract)\n// ---------------------------------------------------------------------------\n\n/**\n * Standard JSON envelope: success is `{ code: 0, error: null, data }` and\n * failure is a non-2xx status with `{ code, error: { message }, data: null }`.\n */\nexport interface ApiEnvelope<T = unknown> {\n data?: T;\n code?: number;\n error?: { message?: string; description?: string } | null;\n}\n\n/** Whether a response body is a newbie envelope rather than a raw payload. */\nfunction isEnvelope(body: unknown): body is ApiEnvelope {\n if (body === null || typeof body !== \"object\") return false;\n if (Array.isArray(body)) return false;\n const record = body as Record<string, unknown>;\n // Every envelope carries both markers; a domain object that happens to\n // have a `data` field alone is not unwrapped.\n return \"code\" in record && \"data\" in record;\n}\n\n// ---------------------------------------------------------------------------\n// Token storage\n// ---------------------------------------------------------------------------\n\nexport function getAccessToken(): string {\n if (typeof window === \"undefined\") return \"\";\n return window.localStorage.getItem(ACCESS_TOKEN_KEY) ?? \"\";\n}\n\n/** Persist token + expiry after login or refresh. */\nexport function setSession(token: string, expiresInSeconds?: number): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(ACCESS_TOKEN_KEY, token);\n if (typeof expiresInSeconds === \"number\" && expiresInSeconds > 0) {\n window.localStorage.setItem(ACCESS_TOKEN_EXPIRES_AT_KEY, String(Date.now() + expiresInSeconds * 1000));\n }\n}\n\n/** Remove all locally stored session data. */\nexport function clearSession(): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.removeItem(ACCESS_TOKEN_KEY);\n window.localStorage.removeItem(ACCESS_TOKEN_EXPIRES_AT_KEY);\n}\n\n/** Normalized error so callers never depend on the axios error shape. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly code?: number;\n readonly data: unknown;\n\n constructor(message: string, status: number, data?: unknown, code?: number) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Hook invoked when the refresh cookie is missing/expired. Wire it to your\n * router (e.g. redirect to the login page); the client itself stays\n * router-agnostic.\n */\nlet sessionExpiredHandler: (() => void) | null = null;\nexport function onSessionExpired(handler: () => void): void {\n sessionExpiredHandler = handler;\n}\n\n/**\n * Hook invoked exactly once per failed request, after any 401 refresh/replay\n * attempt has been exhausted. Wire it to your toast layer; the client itself\n * never imports a UI library.\n */\nlet errorHandler: ((error: ApiError) => void) | null = null;\nexport function onError(handler: (error: ApiError) => void): void {\n errorHandler = handler;\n}\n\n// ---------------------------------------------------------------------------\n// Refresh-token rotation\n// ---------------------------------------------------------------------------\n\nfunction isUnauthorized(error: unknown): boolean {\n return axios.isAxiosError(error) && error.response?.status === 401;\n}\n\n/**\n * Whether the access token is still due for a refresh. After acquiring the\n * cross-tab lock, another tab may have already refreshed while we waited;\n * this check lets us skip the network call and reuse the new token.\n */\nfunction isRefreshStillDue(): boolean {\n const expiresAt = Number(window.localStorage.getItem(ACCESS_TOKEN_EXPIRES_AT_KEY) ?? 0);\n if (!expiresAt) return true;\n return Date.now() >= expiresAt - PROACTIVE_REFRESH_LEAD_MS;\n}\n\n/** One refresh round-trip; persists the renewed token and its expiry. */\nasync function requestRefreshOnce(): Promise<string | null> {\n const response = await axios.get(`${BASE_URL}${REFRESH_PATH}`, {\n withCredentials: true,\n });\n const body = response.data as ApiEnvelope<{\n token?: string;\n tokenExpiresInSeconds?: number;\n }>;\n const token = body?.data?.token ?? \"\";\n if (!token) return null;\n setSession(token, body.data?.tokenExpiresInSeconds);\n return token;\n}\n\n/** Send the refresh request with one retry on 401 (cross-tab cookie race). */\nasync function requestRefreshWithRetry(): Promise<string | null> {\n try {\n return await requestRefreshOnce();\n } catch (firstError) {\n if (isUnauthorized(firstError)) {\n // Possible cross-tab rotation race: retry once with the renewed cookie.\n await new Promise((resolve) => setTimeout(resolve, REFRESH_RETRY_DELAY_MS));\n try {\n return await requestRefreshOnce();\n } catch {\n return null;\n }\n }\n // Network or other non-auth failure: nothing a retry can fix.\n return null;\n }\n}\n\n// Shared in-flight refresh. The backend rotates the refresh cookie on every\n// call, so concurrent 401s must await the same request instead of issuing\n// parallel refreshes that invalidate each other's cookie.\nlet refreshPromise: Promise<string | null> | null = null;\n\n/**\n * Exchange the httpOnly refresh cookie for a new access token.\n *\n * Two layers of dedup prevent concurrent refresh calls that would trigger\n * the backend's refresh-token-reuse detection and revoke the session:\n * 1. Single-tab: module-level refreshPromise — concurrent 401s in this tab\n * reuse the same promise.\n * 2. Cross-tab: Web Locks (navigator.locks) serialize refreshes across tabs.\n * After acquiring the lock, re-check whether refresh is still needed.\n * Environments without Web Locks fall back to the single-flight + retry\n * mitigation.\n */\nfunction refreshAccessToken(): Promise<string | null> {\n if (refreshPromise) return refreshPromise;\n\n refreshPromise = (async () => {\n try {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return await navigator.locks.request(REFRESH_LOCK_NAME, async () => {\n if (!isRefreshStillDue()) return getAccessToken();\n return requestRefreshWithRetry();\n });\n }\n return requestRefreshWithRetry();\n } finally {\n refreshPromise = null;\n }\n })();\n\n return refreshPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Proactive refresh scheduler (module-level singleton)\n// ---------------------------------------------------------------------------\n\nlet schedulerTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Start the scheduler that renews the token shortly before expiry. Call once\n * on the client (e.g. in the authenticated layout). Reactive 401 refresh\n * stays as a fallback for laptop sleep / scheduler drift.\n */\nexport function initProactiveTokenRefresh(): void {\n if (typeof window === \"undefined\" || schedulerTimer) return;\n\n const refreshIfDue = (): void => {\n const token = getAccessToken();\n const expiresAt = Number(window.localStorage.getItem(ACCESS_TOKEN_EXPIRES_AT_KEY) ?? 0);\n if (token && expiresAt && Date.now() >= expiresAt - PROACTIVE_REFRESH_LEAD_MS) {\n void refreshAccessToken();\n }\n };\n\n // Run immediately (tabs reopened after sleep) and then on an interval.\n refreshIfDue();\n schedulerTimer = setInterval(refreshIfDue, PROACTIVE_REFRESH_CHECK_INTERVAL_MS);\n}\n\n// ---------------------------------------------------------------------------\n// Error normalization (the single failure channel)\n// ---------------------------------------------------------------------------\n\n/** Map any thrown value to the normalized ApiError shape. */\nfunction toApiError(error: unknown): ApiError {\n if (error instanceof ApiError) return error;\n if (axios.isAxiosError(error)) {\n const body = error.response?.data as ApiEnvelope | undefined;\n return new ApiError(\n body?.error?.message ?? error.message,\n error.response?.status ?? 0,\n body ?? error.response?.data,\n body?.code,\n );\n }\n if (error instanceof Error) return new ApiError(error.message, 0);\n return new ApiError(\"Request failed\", 0);\n}\n\n// ---------------------------------------------------------------------------\n// Axios instance\n// ---------------------------------------------------------------------------\n\nexport const api = axios.create({\n baseURL: BASE_URL,\n withCredentials: true,\n});\n\napi.interceptors.request.use((config) => {\n const token = getAccessToken();\n // Within the interceptor chain headers is always an AxiosHeaders instance.\n if (token) {\n config.headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return config;\n});\n\n// Success channel: only unwrap the envelope; failures never arrive here\n// (they carry non-2xx status — see newbie ADR-001).\napi.interceptors.response.use(\n (response) => {\n if (isEnvelope(response.data)) {\n return { ...response, data: response.data.data };\n }\n return response;\n },\n async (error) => {\n const original = error?.config as (InternalAxiosRequestConfig & { _retriedAfterRefresh?: boolean }) | undefined;\n const url: string = original?.url ?? \"\";\n const canSilentlyRefresh =\n typeof window !== \"undefined\" && !original?._retriedAfterRefresh && !AUTH_PATH_PATTERN.test(url);\n\n if (isUnauthorized(error) && original && canSilentlyRefresh) {\n original._retriedAfterRefresh = true;\n const renewed = await refreshAccessToken();\n if (renewed) {\n original.headers.set(\"Authorization\", `Bearer ${renewed}`);\n // Replay goes through the same interceptor chain; its outcome is\n // returned directly so this failure never reaches the handler.\n return api(original);\n }\n // Refresh cookie missing or expired: the session is over.\n clearSession();\n sessionExpiredHandler?.();\n }\n\n // Single exit for every final failure: normalize once, notify once.\n const normalized = toApiError(error);\n errorHandler?.(normalized);\n throw normalized;\n },\n);\n\n// ---------------------------------------------------------------------------\n// Typed convenience methods — resolve to the unwrapped response body.\n// ---------------------------------------------------------------------------\n\nexport const apiClient = {\n get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.get<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.post<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.put<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.patch<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.delete<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n // HEAD/OPTIONS responses carry no body; resolve to the full AxiosResponse\n // so callers can still inspect status and headers.\n head<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.head<unknown, AxiosResponse<T>>(url, config);\n },\n options<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.options<unknown, AxiosResponse<T>>(url, config);\n },\n};\n",
|
|
15
15
|
"type": "registry:lib"
|
|
16
16
|
}
|
|
17
17
|
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/r/registry-item.json",
|
|
3
|
+
"name": "app-shell",
|
|
4
|
+
"type": "registry:block",
|
|
5
|
+
"title": "Collapsible app shell",
|
|
6
|
+
"description": "Collapsible sidebar primitives (240px/64px rail, collapsed tooltips, hover flyout menus, persisted collapse state via an external store) plus a minimal nav-array-driven AppShell skeleton.",
|
|
7
|
+
"postInstall": "Run `npx shadcn add popover tooltip` (required ui primitives), fill NAV_ITEMS in src/components/app-shell/app-shell.tsx with your own navigation, and render <AppShell> from your authenticated layout. If you build your own shell from sidebar-chrome.tsx primitives instead of using <AppShell>, wrap it in a TooltipProvider (exported by the shadcn tooltip primitive). Rename DEFAULT_SIDEBAR_COLLAPSED_STORAGE_KEY in sidebar-chrome.tsx if you want a project-specific localStorage namespace.",
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "src/components/app-shell/sidebar-chrome.tsx",
|
|
11
|
+
"content": "\"use client\";\n\nimport * as React from \"react\";\nimport Link from \"next/link\";\nimport { usePathname } from \"next/navigation\";\nimport { ArrowLeft, PanelLeftClose, PanelLeftOpen, type LucideIcon } from \"lucide-react\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@/components/ui/tooltip\";\nimport { cn } from \"cn\";\n\nexport const DEFAULT_SIDEBAR_COLLAPSED_STORAGE_KEY = \"app-shell:sidebar-collapsed\";\n\n// External stores keyed by storage key, so every sidebar shell sharing a key\n// shares one preference without setState-in-effect hydration churn. Sidebars\n// render expanded on the server; the stored value is applied after hydration.\ninterface SidebarCollapsedStore {\n subscribe: (callback: () => void) => () => void;\n getSnapshot: () => boolean;\n set: (value: boolean) => void;\n}\n\nconst collapsedStores = new Map<string, SidebarCollapsedStore>();\n\nfunction getCollapsedStore(storageKey: string): SidebarCollapsedStore {\n const existing = collapsedStores.get(storageKey);\n if (existing) return existing;\n\n const listeners = new Set<() => void>();\n const store: SidebarCollapsedStore = {\n subscribe(callback) {\n listeners.add(callback);\n window.addEventListener(\"storage\", callback);\n return () => {\n listeners.delete(callback);\n window.removeEventListener(\"storage\", callback);\n };\n },\n getSnapshot() {\n return window.localStorage.getItem(storageKey) === \"1\";\n },\n set(value) {\n window.localStorage.setItem(storageKey, value ? \"1\" : \"0\");\n listeners.forEach((listener) => listener());\n },\n };\n collapsedStores.set(storageKey, store);\n return store;\n}\n\nexport function useSidebarCollapsed(\n storageKey: string = DEFAULT_SIDEBAR_COLLAPSED_STORAGE_KEY,\n): [boolean, (value: boolean) => void] {\n const store = getCollapsedStore(storageKey);\n const collapsed = React.useSyncExternalStore(store.subscribe, store.getSnapshot, () => false);\n return [collapsed, store.set];\n}\n\ninterface SidebarNavLinkProps {\n href: string;\n label: string;\n icon: LucideIcon;\n active: boolean;\n collapsed: boolean;\n /** Render as a non-clickable placeholder for upcoming features. */\n disabled?: boolean;\n /** Native hover title explaining why the entry is disabled. */\n disabledHint?: string;\n}\n\n// Leaf navigation row: full row when expanded, centered icon button with a\n// tooltip when collapsed.\nexport function SidebarNavLink({ href, label, icon: Icon, active, collapsed, disabled, disabledHint }: SidebarNavLinkProps) {\n const iconColor = disabled ? \"text-muted-foreground/50\" : active ? \"text-primary\" : \"text-muted-foreground\";\n\n const className = collapsed\n ? cn(\n \"mx-auto mt-1 flex h-10 w-10 items-center justify-center rounded-md\",\n disabled\n ? \"cursor-not-allowed text-muted-foreground/50\"\n : active\n ? \"bg-accent font-semibold text-primary\"\n : \"text-foreground hover:bg-accent\",\n )\n : cn(\n \"mt-1 flex min-h-10 items-center gap-3 rounded-md px-4\",\n disabled\n ? \"cursor-not-allowed text-muted-foreground/50\"\n : active\n ? \"bg-accent font-semibold text-primary\"\n : \"text-foreground hover:bg-accent\",\n );\n\n const inner = disabled ? (\n <div className={className} title={disabledHint} aria-disabled=\"true\">\n <Icon className={cn(\"size-4\", iconColor)} />\n {!collapsed && <span>{label}</span>}\n </div>\n ) : (\n <Link href={href} className={className} aria-current={active ? \"page\" : undefined}>\n <Icon className={cn(\"size-4\", iconColor)} />\n {!collapsed && <span>{label}</span>}\n </Link>\n );\n\n if (!collapsed) return inner;\n\n return (\n <Tooltip>\n <TooltipTrigger asChild>{inner}</TooltipTrigger>\n <TooltipContent side=\"right\">{label}</TooltipContent>\n </Tooltip>\n );\n}\n\ninterface SidebarBackButtonProps {\n collapsed: boolean;\n label: string;\n backAriaLabel: string;\n onClick: () => void;\n}\n\n// Header button: wide back-to-list button when expanded, square icon when\n// collapsed.\nexport function SidebarBackButton({ collapsed, label, backAriaLabel, onClick }: SidebarBackButtonProps) {\n if (collapsed) {\n return (\n <button\n type=\"button\"\n onClick={onClick}\n aria-label={backAriaLabel}\n className=\"mx-auto flex size-10 cursor-pointer items-center justify-center rounded-md border border-border bg-card text-foreground hover:border-primary hover:bg-accent hover:text-primary focus:outline-none\"\n >\n <ArrowLeft className=\"size-5 text-muted-foreground\" />\n </button>\n );\n }\n\n return (\n <button\n type=\"button\"\n onClick={onClick}\n className=\"flex w-full max-w-[240px] cursor-pointer items-center rounded-md border border-border bg-card text-base font-medium text-foreground hover:border-primary hover:bg-accent hover:text-primary focus:outline-none\"\n >\n <span className=\"flex w-14 items-center justify-center\">\n <ArrowLeft className=\"size-5 text-muted-foreground\" />\n </span>\n <span className=\"max-w-[170px] truncate pr-4 text-left\">{label}</span>\n </button>\n );\n}\n\ninterface SidebarCollapseToggleProps {\n collapsed: boolean;\n onToggle: (value: boolean) => void;\n collapseLabel: string;\n expandLabel: string;\n}\n\n// Footer button that flips the sidebar between 240px and 64px.\nexport function SidebarCollapseToggle({ collapsed, onToggle, collapseLabel, expandLabel }: SidebarCollapseToggleProps) {\n const button = (\n <button\n type=\"button\"\n onClick={() => onToggle(!collapsed)}\n aria-label={collapsed ? expandLabel : collapseLabel}\n aria-expanded={!collapsed}\n className={cn(\n \"flex h-10 w-full cursor-pointer items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus:outline-none\",\n collapsed ? \"justify-center\" : \"gap-2.5 px-3\",\n )}\n >\n {collapsed ? <PanelLeftOpen className=\"size-4\" /> : <PanelLeftClose className=\"size-4\" />}\n {!collapsed && <span className=\"text-sm\">{collapseLabel}</span>}\n </button>\n );\n\n return (\n <div className=\"shrink-0 border-t border-border p-2\">\n {collapsed ? (\n <Tooltip>\n <TooltipTrigger asChild>{button}</TooltipTrigger>\n <TooltipContent side=\"right\">{expandLabel}</TooltipContent>\n </Tooltip>\n ) : (\n button\n )}\n </div>\n );\n}\n\n// Hairline divider replacing text group labels in collapsed mode.\nexport function CollapsedGroupDivider() {\n return <div className=\"mx-2 border-t border-border\" />;\n}\n\ninterface CollapsedFlyoutMenuProps {\n icon: LucideIcon;\n /** Trigger aria label and flyout title (e.g. a group name). */\n label: string;\n active: boolean;\n children: React.ReactNode;\n}\n\n// Hover-opened flyout for groups whose children do not fit in the 64px rail.\nexport function CollapsedFlyoutMenu({ icon: Icon, label, active, children }: CollapsedFlyoutMenuProps) {\n const pathname = usePathname();\n const [open, setOpen] = React.useState(false);\n const [trackedPathname, setTrackedPathname] = React.useState(pathname);\n const closeTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Close after navigation; the shell layout outlives page changes. Adjusting\n // state during render (React's documented prop-change pattern) avoids an\n // effect that fires after the destination page paints.\n if (pathname !== trackedPathname) {\n setTrackedPathname(pathname);\n if (open) setOpen(false);\n }\n\n const cancelClose = React.useCallback(() => {\n if (closeTimer.current) {\n clearTimeout(closeTimer.current);\n closeTimer.current = null;\n }\n }, []);\n\n const openMenu = React.useCallback(() => {\n cancelClose();\n setOpen(true);\n }, [cancelClose]);\n\n const scheduleClose = React.useCallback(() => {\n cancelClose();\n closeTimer.current = setTimeout(() => setOpen(false), 120);\n }, [cancelClose]);\n\n // Clear any pending close timer on unmount.\n React.useEffect(() => cancelClose, [cancelClose]);\n\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n onMouseEnter={openMenu}\n onMouseLeave={scheduleClose}\n onFocus={openMenu}\n aria-label={label}\n className={cn(\n \"mx-auto mt-1 flex h-10 w-10 items-center justify-center rounded-md\",\n active ? \"bg-accent font-semibold text-primary\" : \"text-foreground hover:bg-accent\",\n )}\n >\n <Icon className={cn(\"size-4\", active ? \"text-primary\" : \"text-muted-foreground\")} />\n </button>\n </PopoverTrigger>\n <PopoverContent\n side=\"right\"\n align=\"start\"\n sideOffset={8}\n onMouseEnter={openMenu}\n onMouseLeave={scheduleClose}\n className=\"flex w-52 flex-col gap-0 p-1.5\"\n >\n <h2 className=\"truncate px-2 py-1.5 text-sm\">{label}</h2>\n {children}\n </PopoverContent>\n </Popover>\n );\n}\n\ninterface FlyoutLinkProps {\n href: string;\n label: string;\n active: boolean;\n indented?: boolean;\n}\n\nexport function FlyoutLink({ href, label, active, indented }: FlyoutLinkProps) {\n return (\n <Link\n href={href}\n aria-current={active ? \"page\" : undefined}\n className={cn(\n \"block rounded-md py-1.5 pr-2 text-sm\",\n indented ? \"pl-5\" : \"pl-2\",\n active ? \"bg-accent font-semibold text-primary\" : \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n )}\n >\n {label}\n </Link>\n );\n}\n\nexport function FlyoutSectionLabel({ children }: { children: React.ReactNode }) {\n return (\n <div className=\"px-2 pb-1 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground\">{children}</div>\n );\n}\n",
|
|
12
|
+
"type": "registry:block"
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"path": "src/components/app-shell/app-shell.tsx",
|
|
16
|
+
"content": "\"use client\";\n\nimport * as React from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { House, type LucideIcon } from \"lucide-react\";\nimport { cn } from \"cn\";\n\nimport { TooltipProvider } from \"@/components/ui/tooltip\";\nimport { SidebarCollapseToggle, SidebarNavLink, useSidebarCollapsed } from \"@/components/app-shell/sidebar-chrome\";\n\nexport interface AppShellNavItem {\n href: string;\n label: string;\n icon: LucideIcon;\n /** Render as a non-clickable placeholder for upcoming features. */\n disabled?: boolean;\n}\n\n// Placeholder navigation; replace with the project's own entries.\nconst NAV_ITEMS: AppShellNavItem[] = [{ href: \"/\", label: \"Home\", icon: House }];\n\ninterface AppShellProps {\n children: React.ReactNode;\n navItems?: AppShellNavItem[];\n}\n\n// Minimal collapsible app shell: a 240px sidebar that folds to a 64px icon\n// rail (preference persisted by useSidebarCollapsed) next to the page body.\nexport function AppShell({ children, navItems = NAV_ITEMS }: AppShellProps) {\n const pathname = usePathname();\n const [collapsed, setCollapsed] = useSidebarCollapsed();\n\n return (\n <TooltipProvider>\n <div className=\"flex min-h-screen\">\n <aside className={cn(\"flex shrink-0 flex-col border-r border-border\", collapsed ? \"w-16\" : \"w-60\")}>\n <nav className=\"flex-1 px-2 py-2\">\n {navItems.map((item) => (\n <SidebarNavLink\n key={item.href}\n href={item.href}\n label={item.label}\n icon={item.icon}\n active={pathname === item.href}\n collapsed={collapsed}\n disabled={item.disabled}\n />\n ))}\n </nav>\n <SidebarCollapseToggle\n collapsed={collapsed}\n onToggle={setCollapsed}\n collapseLabel=\"Collapse\"\n expandLabel=\"Expand sidebar\"\n />\n </aside>\n <main className=\"min-w-0 flex-1\">{children}</main>\n </div>\n </TooltipProvider>\n );\n}\n",
|
|
17
|
+
"type": "registry:block"
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
}
|
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
"name": "page-header",
|
|
4
4
|
"type": "registry:component",
|
|
5
5
|
"title": "Page header",
|
|
6
|
-
"description": "Standard page header with title,
|
|
6
|
+
"description": "Standard page header with title, optional subtitle, and a right-aligned actions slot.",
|
|
7
7
|
"files": [
|
|
8
8
|
{
|
|
9
9
|
"path": "src/components/page-header.tsx",
|
|
10
|
-
"content": "import type { ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface PageHeaderProps {\n title:
|
|
10
|
+
"content": "import type { ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface PageHeaderProps {\n /** Main page title, usually matching the sidebar entry label. */\n title: ReactNode;\n /** Optional short explanation rendered under the title. */\n subtitle?: ReactNode;\n /** Optional action area (buttons, filters) aligned to the right. */\n actions?: ReactNode;\n /** Augment the outer container (e.g. override the default mb-6 margin). */\n className?: string;\n}\n\n/**\n * Standard page header: title with optional subtitle on the left and an\n * actions slot on the right. Keeps title typography and spacing consistent\n * across feature modules so each page does not render its own header variant.\n */\nexport function PageHeader({ title, subtitle, actions, className }: PageHeaderProps) {\n return (\n <div className={cn(\"mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\", className)}>\n <div className=\"min-w-0\">\n <h1 className=\"text-xl font-semibold text-foreground\">{title}</h1>\n {subtitle ? <p className=\"mt-1 text-sm text-muted-foreground\">{subtitle}</p> : null}\n </div>\n {actions ? <div className=\"flex flex-shrink-0 flex-wrap items-center gap-2\">{actions}</div> : null}\n </div>\n );\n}\n",
|
|
11
11
|
"type": "registry:component"
|
|
12
12
|
}
|
|
13
13
|
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/r/registry-item.json",
|
|
3
|
+
"name": "password-checklist",
|
|
4
|
+
"type": "registry:block",
|
|
5
|
+
"title": "Password checklist",
|
|
6
|
+
"description": "Live password rule checklist with a reusable isStrongPassword predicate. Rules mirror the newbie account module's password policy (validator.isStrongPassword defaults: 8+ chars, lower/upper/number/symbol); when the backend policy changes, the rules here must be updated manually.",
|
|
7
|
+
"postInstall": "Render <PasswordChecklist password={...}> under password inputs (pairs with the login-form item in sign-up/change-password screens). The rules array is a manual mirror of the newbie account password policy - if the backend strategy changes, sync it here; there is no automatic linkage.",
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "src/components/password-checklist.tsx",
|
|
11
|
+
"content": "\"use client\";\n\nimport { Check, X } from \"lucide-react\";\n\n/**\n * Live password rule checklist. Rules mirror the backend IsStrongPassword\n * validator (validator.isStrongPassword defaults), so what the user sees is\n * exactly what the API enforces.\n *\n * NOTE: this is a manual mirror of the newbie account module's password\n * policy. When the backend strategy changes, update the rules array here.\n */\nconst rules: ReadonlyArray<{ key: string; label: string; test: (password: string) => boolean }> = [\n { key: \"length\", label: \"At least 8 characters\", test: (password) => password.length >= 8 },\n { key: \"lowercase\", label: \"One lowercase letter\", test: (password) => /[a-z]/.test(password) },\n { key: \"uppercase\", label: \"One uppercase letter\", test: (password) => /[A-Z]/.test(password) },\n { key: \"number\", label: \"One number\", test: (password) => /\\d/.test(password) },\n { key: \"symbol\", label: \"One symbol\", test: (password) => /[^\\w\\s]/.test(password) },\n];\n\nexport function isStrongPassword(password: string): boolean {\n return rules.every((rule) => rule.test(password));\n}\n\nexport function PasswordChecklist({ password }: { password: string }) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label=\"Password requirements\">\n {rules.map((rule) => {\n const met = rule.test(password);\n return (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"}`}\n >\n {met ? <Check className=\"h-3.5 w-3.5\" /> : <X className=\"h-3.5 w-3.5\" />}\n {rule.label}\n </li>\n );\n })}\n </ul>\n );\n}\n",
|
|
12
|
+
"type": "registry:block"
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/r/registry-item.json",
|
|
3
|
+
"name": "query-client",
|
|
4
|
+
"type": "registry:lib",
|
|
5
|
+
"title": "React Query client & provider",
|
|
6
|
+
"description": "TanStack Query singleton with safe Next.js App Router wiring (fresh client per server request, one shared client in the browser) plus the provider component.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"@tanstack/react-query@^5"
|
|
9
|
+
],
|
|
10
|
+
"postInstall": "Wrap the children of your root layout <body> with <QueryProvider> (src/components/query-provider.tsx). When consuming apits-generated clients, remember their ApiResponse<T> = [data?, res?] tuple: destructure with a null guard, e.g. `const [data] = await getProjects(); return data ?? [];`.",
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "src/lib/query-client.ts",
|
|
14
|
+
"content": "import { isServer, QueryClient } from \"@tanstack/react-query\";\n\n// Conservative defaults; tune per project. retry:1 tolerates transient\n// network blips without long stalls against a dead backend; staleTime:30s\n// avoids refetch storms when navigating between pages that share queries.\nfunction createQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n retry: 1,\n staleTime: 30_000,\n },\n mutations: {\n retry: false,\n },\n },\n });\n}\n\nlet browserQueryClient: QueryClient | undefined;\n\n// Official TanStack Query pattern for the App Router: the server must never\n// share a client across requests, while the browser reuses one singleton so\n// the cache survives navigations. Do NOT inline `new QueryClient()` in a\n// client component body — every re-render would discard the cache.\nexport function getQueryClient(): QueryClient {\n if (isServer) return createQueryClient();\n if (!browserQueryClient) browserQueryClient = createQueryClient();\n return browserQueryClient;\n}\n",
|
|
15
|
+
"type": "registry:lib"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "src/components/query-provider.tsx",
|
|
19
|
+
"content": "\"use client\";\n\nimport { QueryClientProvider } from \"@tanstack/react-query\";\n\nimport { getQueryClient } from \"@/lib/query-client\";\n\nexport function QueryProvider({ children }: { children: React.ReactNode }) {\n const queryClient = getQueryClient();\n return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;\n}\n",
|
|
20
|
+
"type": "registry:lib"
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
}
|
|
@@ -3,14 +3,11 @@
|
|
|
3
3
|
"name": "settings-required-state",
|
|
4
4
|
"type": "registry:block",
|
|
5
5
|
"title": "Settings required state",
|
|
6
|
-
"description": "Empty state shown when required configuration is missing, with a call-to-action to
|
|
7
|
-
"registryDependencies": [
|
|
8
|
-
"page-header"
|
|
9
|
-
],
|
|
6
|
+
"description": "Empty state shown when required configuration is missing, with a call-to-action linking to the settings page.",
|
|
10
7
|
"files": [
|
|
11
8
|
{
|
|
12
9
|
"path": "src/components/settings-required-state.tsx",
|
|
13
|
-
"content": "
|
|
10
|
+
"content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport Link from \"next/link\";\nimport { ArrowRight, Settings2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { cn } from \"@/lib/utils\";\n\ninterface SettingsRequiredStateProps {\n /** Short headline shown below the icon, e.g. \"AWS credential required\". */\n title: string;\n /** Explanation of which setting is missing and why it is needed. */\n description?: ReactNode;\n /** Destination of the settings call-to-action, usually the project settings page. */\n settingsHref: string;\n /** Label of the call-to-action button. */\n actionLabel?: string;\n /** Optional custom icon rendered inside the tinted badge. */\n icon?: ReactNode;\n /** Stretch the state to fill the parent height (used by full-screen panels). */\n fullHeight?: boolean;\n /** Allow callers to tweak the outer container when needed. */\n className?: string;\n}\n\n/**\n * Unified \"required settings are missing\" state. Feature modules render this\n * when their backing configuration has not been set up yet, so the\n * empty-state visuals and the settings entry point stay consistent.\n */\nexport function SettingsRequiredState({\n title,\n description,\n settingsHref,\n actionLabel = \"Open Settings\",\n icon,\n fullHeight = false,\n className,\n}: SettingsRequiredStateProps) {\n return (\n <div className={cn(\"flex w-full items-center justify-center\", fullHeight ? \"h-full\" : \"py-8 md:py-16\", className)}>\n <Card className=\"w-full max-w-xl text-center\">\n <CardContent className=\"flex flex-col items-center px-6 py-10 md:px-12\">\n {/* Tinted icon badge */}\n <div className=\"mb-4 flex size-16 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {icon ?? <Settings2 className=\"size-8\" />}\n </div>\n\n <h2 className=\"text-lg font-semibold text-foreground\">{title}</h2>\n\n {description ? <p className=\"mt-2 max-w-md text-sm leading-7 text-muted-foreground\">{description}</p> : null}\n\n {/* settingsHref may be a full in-app path; Link handles client-side navigation. */}\n <Button asChild className=\"mt-6\">\n <Link href={settingsHref}>\n {actionLabel}\n <ArrowRight className=\"size-4\" />\n </Link>\n </Button>\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
14
11
|
"type": "registry:block"
|
|
15
12
|
}
|
|
16
13
|
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/r/registry-item.json",
|
|
3
|
+
"name": "sse-stream",
|
|
4
|
+
"type": "registry:lib",
|
|
5
|
+
"title": "POST-based SSE transport",
|
|
6
|
+
"description": "Server-Sent Events decoder over a fetch ReadableStream with a POST-based request helper, for endpoints that EventSource cannot serve (POST bodies, custom headers). Transport-text only: frame decoding (event/data, keepalive comments, CRLF tolerance, chunk buffering) with abort support; JSON decoding of the data line is the caller's job.",
|
|
7
|
+
"postInstall": "Use postSse(url, { body, headers, signal, onFrame }) for POST-initiated streams (EventSource cannot POST or set headers); call consumeSseStream directly when you already hold a fetch Response. Throw semantics: SseStreamError carries the HTTP status for non-2xx responses.",
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "src/lib/sse-stream.ts",
|
|
11
|
+
"content": "/**\n * Minimal Server-Sent Events transport over fetch.\n *\n * `postSse` covers endpoints that EventSource cannot serve (POST bodies,\n * custom headers): it POSTs a JSON body, then decodes the response stream.\n * `consumeSseStream` is the lower-level decoder for callers that already\n * hold a fetch Response.\n *\n * The wire format handled is standard SSE:\n *\n * event: <name>\\n\n * data: <json>\\n\n * \\n\n *\n * with `: keepalive` comment lines during quiet periods. This layer is\n * transport-text only; JSON decoding of the data line is the caller's job.\n */\n\nexport interface SseFrame {\n event: string;\n data: string;\n}\n\n/** HTTP-level failure of a POST-initiated SSE request (non-2xx or no body). */\nexport class SseStreamError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"SseStreamError\";\n }\n}\n\nconst DECODER = new TextDecoder();\n\nconst NEVER_ABORTED = new AbortController().signal;\n\nexport interface PostSseOptions {\n /** JSON-encoded request body; omit to POST without a body. */\n body?: unknown;\n /** Extra request headers (e.g. Authorization). Content-Type and Accept are set automatically. */\n headers?: Record<string, string>;\n /** Aborting stops reading immediately; already received frames are retained by the caller. */\n signal?: AbortSignal;\n /** Called for every decoded frame, in arrival order. */\n onFrame: (frame: SseFrame) => void;\n}\n\n/**\n * POST-initiated SSE request: the standard workaround for EventSource's\n * inability to send POST bodies or custom headers. Resolves after the server\n * closes the stream; rejects with SseStreamError on HTTP-level failures.\n * Stream errors during reading propagate from the underlying reader.\n */\nexport async function postSse(url: string, options: PostSseOptions): Promise<void> {\n const { body, headers, signal = NEVER_ABORTED, onFrame } = options;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n\n if (!response.ok || !response.body) {\n const detail = await response.text().catch(() => \"\");\n throw new SseStreamError(response.status, `SSE request failed with ${response.status}${detail ? `: ${detail}` : \"\"}`);\n }\n\n await consumeSseStream(response.body, signal, onFrame);\n}\n\n/**\n * Consume a fetch Response.body stream until the server closes it.\n *\n * Partial multibyte sequences and frames split across chunks are buffered, so\n * callers may invoke this directly on response.body without any framing\n * assumptions. Aborting `signal` stops reading immediately; the already\n * received frames are retained by the caller.\n */\nexport async function consumeSseStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n onFrame: (frame: SseFrame) => void,\n): Promise<void> {\n const reader = body.getReader();\n let buffer = \"\";\n\n const onAbort = (): void => {\n reader.cancel(\"aborted\").catch(() => {});\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += DECODER.decode(value, { stream: true });\n\n let separatorIndex: number;\n // SSE dispatches on a blank line; tolerate CRLF.\n while ((separatorIndex = findFrameBoundary(buffer)) !== -1) {\n const rawFrame = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex).replace(/^(\\r?\\n){2}/, \"\");\n const frame = parseFrame(rawFrame);\n if (frame) onFrame(frame);\n }\n }\n\n const tail = buffer.trim();\n if (tail) {\n const frame = parseFrame(tail);\n if (frame) onFrame(frame);\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n try {\n reader.releaseLock();\n } catch {\n // A lock held by a racing cancel() releases on its own.\n }\n }\n}\n\n/** Normalize the two possible blank-line styles (\\n\\n and \\r\\n\\r\\n). */\nfunction findFrameBoundary(buffer: string): number {\n const lf = buffer.indexOf(\"\\n\\n\");\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\");\n if (lf === -1) return crlf;\n if (crlf === -1) return lf;\n return Math.min(lf, crlf);\n}\n\nfunction parseFrame(rawFrame: string): SseFrame | null {\n let event = \"message\";\n const dataLines: string[] = [];\n\n for (const rawLine of rawFrame.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\r$/, \"\");\n if (!line || line.startsWith(\":\")) continue; // comments / keepalive\n if (line.startsWith(\"event:\")) {\n event = line.slice(\"event:\".length).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(\"data:\".length).trimStart());\n }\n }\n\n if (dataLines.length === 0) return null;\n return { event, data: dataLines.join(\"\\n\") };\n}\n",
|
|
12
|
+
"type": "registry:lib"
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
@@ -7,11 +7,11 @@
|
|
|
7
7
|
"dependencies": [
|
|
8
8
|
"@devbie/web-monitor-sdk"
|
|
9
9
|
],
|
|
10
|
-
"postInstall": "Add <WebMonitor /> inside your root layout <body> (src/app/layout.tsx), then set
|
|
10
|
+
"postInstall": "Add <WebMonitor /> inside your root layout <body> (src/app/layout.tsx), then set NEXT_PUBLIC_WEB_MONITOR_ENDPOINT (report endpoint URL), NEXT_PUBLIC_WEB_MONITOR_APP_ID and NEXT_PUBLIC_WEB_MONITOR_TOKEN. The component is a no-op until all three env vars are present.",
|
|
11
11
|
"files": [
|
|
12
12
|
{
|
|
13
13
|
"path": "src/components/web-monitor.tsx",
|
|
14
|
-
"content": "\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Browser-side monitoring bootstrap.\n *\n * Dynamically imports @devbie/web-monitor-sdk on mount and initializes it\n * with
|
|
14
|
+
"content": "\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Browser-side monitoring bootstrap.\n *\n * Dynamically imports @devbie/web-monitor-sdk on mount and initializes it\n * with NEXT_PUBLIC_WEB_MONITOR_ENDPOINT (report endpoint),\n * NEXT_PUBLIC_WEB_MONITOR_APP_ID (public partition key) and\n * NEXT_PUBLIC_WEB_MONITOR_TOKEN (secret report token). Renders nothing; it is\n * a no-op until all three env vars are set. Heartbeat wiring is intentionally\n * NOT handled here — it lives in the template's instrumentation.ts (Node\n * process only).\n *\n * The dynamic import keeps the SDK out of SSR/Edge evaluation entirely:\n * the monitor bundle is only loaded in the browser when the component mounts.\n */\nexport function WebMonitor() {\n useEffect(() => {\n const api = process.env.NEXT_PUBLIC_WEB_MONITOR_ENDPOINT;\n const appId = process.env.NEXT_PUBLIC_WEB_MONITOR_APP_ID;\n const token = process.env.NEXT_PUBLIC_WEB_MONITOR_TOKEN;\n\n // Required configuration missing — stay silent in production, warn in dev.\n if (!api || !appId || !token) {\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n \"[WebMonitor] NEXT_PUBLIC_WEB_MONITOR_ENDPOINT / NEXT_PUBLIC_WEB_MONITOR_APP_ID / NEXT_PUBLIC_WEB_MONITOR_TOKEN not set; monitoring disabled.\",\n );\n }\n return;\n }\n\n let disposed = false;\n\n void import(\"@devbie/web-monitor-sdk\").then(({ default: init }) => {\n // StrictMode mounts effects twice in dev; guard against double init.\n if (disposed) return;\n init({\n appId,\n api,\n token,\n isPage: true,\n isAjax: true,\n isResource: true,\n isError: true,\n });\n });\n\n return () => {\n disposed = true;\n };\n }, []);\n\n return null;\n}\n",
|
|
15
15
|
"type": "registry:component"
|
|
16
16
|
}
|
|
17
17
|
]
|