@devbie/fewbie-cli 0.2.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.
@@ -3,7 +3,7 @@
3
3
  "name": "api-client",
4
4
  "type": "registry:lib",
5
5
  "title": "API client",
6
- "description": "Axios instance with bearer-token auth, httpOnly refresh-cookie rotation, single-flight 401 retry and proactive token refresh.",
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
  ]
@@ -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 NEXT_PUBLIC_WEB_MONITOR_API (report endpoint URL) and NEXT_PUBLIC_WEB_MONITOR_APP_ID. The component is a no-op until both env vars are present.",
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 NEXT_PUBLIC_WEB_MONITOR_API (report endpoint) and\n * NEXT_PUBLIC_WEB_MONITOR_APP_ID. Renders nothing; it is a no-op until both\n * env vars are set. Heartbeat wiring is intentionally NOT handled here —\n * it lives in the template's instrumentation.ts (Node 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_API;\n const appId = process.env.NEXT_PUBLIC_WEB_MONITOR_APP_ID;\n\n // Required configuration missing — stay silent in production, warn in dev.\n if (!api || !appId) {\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n \"[WebMonitor] NEXT_PUBLIC_WEB_MONITOR_API / NEXT_PUBLIC_WEB_MONITOR_APP_ID 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 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",
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
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devbie/fewbie-cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "fewbie frontend framework CLI",
5
5
  "license": "MIT",
6
6
  "author": "worldzhy",