@lobehub/market-sdk 0.22.13-beta.0 → 0.22.14-beta.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/index.d.mts +7 -5
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -75,7 +75,7 @@ interface AdminPluginParams {
|
|
|
75
75
|
/** Sort direction */
|
|
76
76
|
order?: 'asc' | 'desc';
|
|
77
77
|
/** Field to sort by */
|
|
78
|
-
orderBy?: 'createdAt' | 'updatedAt' | 'installCount' | 'ratingAverage';
|
|
78
|
+
orderBy?: 'createdAt' | 'updatedAt' | 'installCount' | 'ratingAverage' | 'githubUpdateAt';
|
|
79
79
|
/** Filter by owner ID */
|
|
80
80
|
ownerId?: number;
|
|
81
81
|
/** Search query string */
|
|
@@ -167,6 +167,8 @@ interface PluginVersionUpdateParams {
|
|
|
167
167
|
* Parameters for updating plugin basic metadata (non-version specific)
|
|
168
168
|
*/
|
|
169
169
|
interface PluginUpdateParams {
|
|
170
|
+
/** GitHub last update timestamp */
|
|
171
|
+
githubUpdateAt?: string;
|
|
170
172
|
/** Unique identifier for the plugin */
|
|
171
173
|
identifier?: string;
|
|
172
174
|
/** Whether this plugin has been claimed by its original author */
|
|
@@ -287,11 +289,11 @@ interface AgentItemDetail extends AgentItem {
|
|
|
287
289
|
/** Author (may come from marketplace base but ensure presence) */
|
|
288
290
|
author?: string;
|
|
289
291
|
/** Avatar URL for the agent, can be a emoji */
|
|
290
|
-
avatar
|
|
292
|
+
avatar: string;
|
|
291
293
|
/** Total comment count */
|
|
292
294
|
commentCount?: number;
|
|
293
295
|
/** Agent configuration JSON */
|
|
294
|
-
config
|
|
296
|
+
config: any;
|
|
295
297
|
/** Current version id */
|
|
296
298
|
currentVersionId?: number;
|
|
297
299
|
/** URL to human-readable documentation */
|
|
@@ -343,11 +345,11 @@ interface AgentItemDetail extends AgentItem {
|
|
|
343
345
|
/** Token usage */
|
|
344
346
|
tokenUsage?: number;
|
|
345
347
|
/** Agent or A2A implementation version string */
|
|
346
|
-
version
|
|
348
|
+
version: string;
|
|
347
349
|
/** Version display name */
|
|
348
350
|
versionName?: string;
|
|
349
351
|
/** Incremental version number */
|
|
350
|
-
versionNumber
|
|
352
|
+
versionNumber: number;
|
|
351
353
|
/** Version list summary */
|
|
352
354
|
versions?: Array<{
|
|
353
355
|
isLatest: boolean;
|
package/dist/index.mjs
CHANGED
|
@@ -1631,7 +1631,7 @@ var _AuthService = class _AuthService extends BaseSDK {
|
|
|
1631
1631
|
throw new Error(`Unsupported grant type: ${grantType}`);
|
|
1632
1632
|
}
|
|
1633
1633
|
log10("Exchanging OAuth token using grant_type=%s", grantType);
|
|
1634
|
-
const tokenUrl = urlJoin2(this.baseUrl, "
|
|
1634
|
+
const tokenUrl = urlJoin2(this.baseUrl, "lobehub-oidc/token");
|
|
1635
1635
|
const params = new URLSearchParams();
|
|
1636
1636
|
params.set("grant_type", grantType);
|
|
1637
1637
|
if (grantType === "authorization_code") {
|
|
@@ -1695,7 +1695,7 @@ var _AuthService = class _AuthService extends BaseSDK {
|
|
|
1695
1695
|
*/
|
|
1696
1696
|
async getUserInfo(accessToken, options) {
|
|
1697
1697
|
log10("Getting user info");
|
|
1698
|
-
const userInfoUrl = urlJoin2(this.baseUrl, "
|
|
1698
|
+
const userInfoUrl = urlJoin2(this.baseUrl, "lobehub-oidc/userinfo");
|
|
1699
1699
|
const response = await fetch(userInfoUrl, {
|
|
1700
1700
|
headers: {
|
|
1701
1701
|
"Authorization": `Bearer ${accessToken}`,
|
|
@@ -1774,7 +1774,7 @@ var _AuthService = class _AuthService extends BaseSDK {
|
|
|
1774
1774
|
var _a, _b;
|
|
1775
1775
|
if (!id) throw new Error("id is required");
|
|
1776
1776
|
log10("Getting OAuth handoff: %s", id);
|
|
1777
|
-
const handoffUrl = `${urlJoin2(this.baseUrl, "
|
|
1777
|
+
const handoffUrl = `${urlJoin2(this.baseUrl, "lobehub-oidc/handoff")}?id=${encodeURIComponent(id)}`;
|
|
1778
1778
|
const response = await fetch(handoffUrl, {
|
|
1779
1779
|
headers: {
|
|
1780
1780
|
"Content-Type": "application/json"
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/admin/MarketAdmin.ts","../src/core/BaseSDK.ts","../src/admin/services/AnalysisService.ts","../src/admin/services/PluginService.ts","../src/admin/services/SystemDependencyService.ts","../src/admin/services/SettingsService.ts","../src/admin/services/ReviewService.ts","../src/admin/services/PluginEnvService.ts","../src/market/market-sdk.ts","../src/market/services/AgentService.ts","../src/market/services/AuthService.ts","../src/market/services/DiscoveryService.ts","../src/market/services/PluginsService.ts","../src/types/admin.ts","../src/index.ts"],"sourcesContent":["import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport { MarketSDKOptions } from '@/types';\n\nimport {\n AnalysisService,\n PluginEnvService,\n PluginService,\n ReviewService,\n SettingsService,\n SystemDependencyService,\n} from './services';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin');\n\n/**\n * LobeHub Market Admin SDK Client\n *\n * Client for accessing administrative functionality of the LobeHub Marketplace.\n * This SDK provides privileged operations for managing plugins, reviews,\n * system settings, and dependencies. It requires admin-level authentication.\n */\nexport class MarketAdmin extends BaseSDK {\n /**\n * Market analysis service\n * Provides methods for accessing market analytics and statistics\n */\n readonly analysis: AnalysisService;\n\n /**\n * Plugin management service\n * Provides methods for creating, updating, and managing plugins\n */\n readonly plugins: PluginService;\n\n readonly env: PluginEnvService;\n\n /**\n * Review management service\n * Provides methods for moderating and managing user reviews\n */\n readonly reviews: ReviewService;\n\n /**\n * System settings management service\n * Provides methods for configuring marketplace settings\n */\n readonly settings: SettingsService;\n\n /**\n * System dependency management service\n * Provides methods for managing system dependencies required by plugins\n */\n readonly dependencies: SystemDependencyService;\n\n /**\n * Creates a new MarketAdmin instance\n *\n * @param options - Configuration options for the SDK\n */\n constructor(options: MarketSDKOptions = {}) {\n // Use admin-specific API key if available\n const apiKey = options.apiKey || process.env.MARKET_ADMIN_API_KEY;\n\n // Create shared token state object for all services\n const sharedTokenState = {\n accessToken: undefined,\n tokenExpiry: undefined,\n };\n\n super({ ...options, apiKey }, undefined, sharedTokenState);\n log('MarketAdmin instance created');\n\n // Initialize admin services with shared headers and token state for efficient reuse\n this.analysis = new AnalysisService(options, this.headers, sharedTokenState);\n this.plugins = new PluginService(options, this.headers, sharedTokenState);\n this.reviews = new ReviewService(options, this.headers, sharedTokenState);\n this.settings = new SettingsService(options, this.headers, sharedTokenState);\n this.dependencies = new SystemDependencyService(options, this.headers, sharedTokenState);\n this.env = new PluginEnvService(options, this.headers, sharedTokenState);\n }\n}\n","import debug from 'debug';\nimport { SignJWT } from 'jose';\nimport urlJoin from 'url-join';\n\nimport type { MarketSDKOptions, SharedTokenState } from '../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:core');\n\n/**\n * Base SDK class\n *\n * Provides shared request handling and authentication functionality that is used\n * by both the Market SDK and Admin SDK. This class handles the common concerns:\n * - API endpoint configuration\n * - Authentication header management\n * - HTTP request handling\n * - Error handling\n * - Query string building\n */\nexport class BaseSDK {\n /** Base API URL */\n protected apiBaseUrl: string;\n /** Base URL */\n protected baseUrl: string;\n /** OAuth URL */\n protected oauthBaseUrl: string;\n\n /** Default locale for requests that require localization */\n protected defaultLocale: string;\n\n /** HTTP headers to include with all requests */\n protected headers: Record<string, string>;\n\n private clientId?: string;\n private clientSecret?: string;\n private readonly initialAccessToken?: string;\n private accessToken?: string;\n private tokenExpiry?: number;\n\n // Shared token state for all instances\n private sharedTokenState?: SharedTokenState;\n\n /**\n * Creates a new BaseSDK instance\n *\n * @param options - Configuration options for the SDK\n * @param sharedHeaders - Optional shared headers object for reuse across services\n * @param sharedTokenState - Optional shared token state object for reuse across services\n */\n constructor(\n options: MarketSDKOptions = {},\n sharedHeaders?: Record<string, string>,\n sharedTokenState?: SharedTokenState,\n ) {\n // Set base URL from options, environment variable, or default to production URL\n this.baseUrl = options.baseURL || process.env.MARKET_BASE_URL || 'https://market.lobehub.com';\n this.apiBaseUrl = urlJoin(this.baseUrl, 'api');\n this.oauthBaseUrl = urlJoin(this.baseUrl, 'oauth');\n\n // Set default locale from options or use English as default\n this.defaultLocale = options.defaultLocale || 'en-US';\n\n this.initialAccessToken = options.accessToken;\n this.clientId = options.clientId;\n this.clientSecret = options.clientSecret;\n\n // Share token state across instances if provided\n this.sharedTokenState = sharedTokenState;\n\n // Get API key from options or environment variable\n const apiKey = options.apiKey || process.env.MARKET_API_KEY;\n\n // Either use shared headers or create new headers object\n if (sharedHeaders) {\n this.headers = sharedHeaders;\n log('Using shared headers object');\n } else {\n this.headers = {\n 'Content-Type': 'application/json',\n };\n log('Created new headers object');\n }\n\n // If an apiKey is provided, use it for authorization.\n // This will be overridden by M2M auth if credentials are also provided.\n if (apiKey) {\n this.headers.Authorization = `Bearer ${apiKey}`;\n }\n\n // If an accessToken is provided on init, it takes precedence.\n if (this.initialAccessToken) {\n this.headers.Authorization = `Bearer ${this.initialAccessToken}`;\n }\n\n log('BaseSDK instance created: %O', {\n baseUrl: this.baseUrl,\n defaultLocale: this.defaultLocale,\n hasApiKey: !!apiKey,\n hasInitialAccessToken: !!this.initialAccessToken,\n hasM2MCredentials: !!this.clientId,\n hasSharedTokenState: !!this.sharedTokenState,\n });\n }\n\n /**\n * Sends an HTTP request to the API and handles the response\n *\n * @param url - Request URL path (will be appended to baseUrl)\n * @param options - Fetch API request options\n * @returns Promise resolving to the parsed JSON response\n * @throws Error if the request fails\n */\n // eslint-disable-next-line no-undef\n protected async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const requestUrl = urlJoin(this.apiBaseUrl, url);\n log('Sending request: %s', requestUrl);\n\n // If no access token was provided on init, and we have M2M creds, run the auth flow.\n if (!this.initialAccessToken && this.clientId && this.clientSecret) {\n await this.setM2MAuthToken();\n }\n\n const response = await fetch(requestUrl, {\n ...options,\n headers: {\n ...this.headers,\n ...options.headers,\n },\n });\n\n if (!response.ok) {\n const errorMsg = `Request failed: ${response.status} ${response.statusText}`;\n try {\n const errorBody = await response.json();\n\n console.error('Request error: %s', JSON.stringify(errorBody));\n\n throw new Error(`${errorMsg} - ${JSON.stringify(errorBody)}`);\n } catch {\n throw new Error(errorMsg);\n }\n }\n\n log('Request successful: %s', url);\n return response.json() as Promise<T>;\n }\n\n /**\n * Builds a URL query string from a parameters object\n *\n * @param params - Object containing query parameters\n * @returns Formatted query string (including leading ? if params exist)\n */\n protected buildQueryString(params: Record<string, any>): string {\n const query = Object.entries(params)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n .filter(([_, value]) => value !== undefined && value !== null)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\n return query ? `?${query}` : '';\n }\n\n /**\n * Sets an authentication token for API requests\n *\n * @param token - API authentication token\n */\n setAuthToken(token: string): void {\n log('Setting authentication token');\n this.accessToken = undefined;\n this.tokenExpiry = undefined;\n\n // Clear shared token state if it exists\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = undefined;\n this.sharedTokenState.tokenExpiry = undefined;\n }\n\n this.headers.Authorization = `Bearer ${token}`;\n }\n\n /**\n * Clears the authentication token\n */\n clearAuthToken(): void {\n log('Clearing authentication token');\n this.accessToken = undefined;\n this.tokenExpiry = undefined;\n\n // Clear shared token state if it exists\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = undefined;\n this.sharedTokenState.tokenExpiry = undefined;\n }\n\n delete this.headers.Authorization;\n }\n\n /**\n * Fetches an M2M access token.\n * This method is designed for server-side use cases where you need to manage the token lifecycle\n * (e.g., storing it in a cookie).\n *\n * @returns A promise that resolves to an object containing the access token and its expiry time.\n */\n public async fetchM2MToken(): Promise<{ accessToken: string; expiresIn: number }> {\n if (!this.clientId || !this.clientSecret) {\n throw new Error('clientId and clientSecret are required to fetch an M2M token.');\n }\n\n log('Fetching M2M token for server-side use');\n\n const assertion = await this.createClientAssertion();\n const tokenData = await this.exchangeTokenForServer(assertion);\n\n log('M2M token fetched successfully');\n\n return {\n accessToken: tokenData.access_token,\n expiresIn: tokenData.expires_in || 3600,\n };\n }\n\n private async createClientAssertion(): Promise<string> {\n if (!this.clientId || !this.clientSecret) {\n throw new Error('Missing clientId or clientSecret for M2M authentication.');\n }\n\n const secret = new TextEncoder().encode(this.clientSecret);\n\n const tokenEndpoint = `${this.oauthBaseUrl}/token`;\n\n return await new SignJWT({})\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.clientId)\n .setSubject(this.clientId)\n .setAudience(tokenEndpoint)\n .setJti(crypto.randomUUID())\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(secret);\n }\n\n private async exchangeToken(clientAssertion: string): Promise<string> {\n const tokenData = await this.exchangeTokenForServer(clientAssertion);\n\n // Calculate token expiry time (current time + expires_in seconds - 60 seconds buffer)\n const expiresInSeconds = tokenData.expires_in || 3600; // Default to 1 hour if not provided\n this.tokenExpiry = Date.now() + (expiresInSeconds - 60) * 1000; // 60 seconds buffer\n\n return tokenData.access_token;\n }\n\n private async exchangeTokenForServer(clientAssertion: string): Promise<any> {\n const tokenEndpoint = urlJoin(this.oauthBaseUrl, 'token');\n log('Exchanging token at endpoint: %s', tokenEndpoint);\n\n const params = new URLSearchParams();\n params.append('grant_type', 'client_credentials');\n params.append(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n );\n params.append('client_assertion', clientAssertion);\n\n const response = await fetch(tokenEndpoint, {\n body: params,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n });\n\n const tokenData = await response.json();\n\n if (!response.ok) {\n throw new Error(`Token exchange failed: ${JSON.stringify(tokenData)}`);\n }\n\n return tokenData;\n }\n\n private async setM2MAuthToken(): Promise<void> {\n // Use shared token state if available\n const currentAccessToken = this.sharedTokenState?.accessToken || this.accessToken;\n const currentTokenExpiry = this.sharedTokenState?.tokenExpiry || this.tokenExpiry;\n\n log(\n 'Token check: hasSharedState=%s, hasCurrentToken=%s, tokenExpiry=%d, currentTime=%d',\n !!this.sharedTokenState,\n !!currentAccessToken,\n currentTokenExpiry || 0,\n Date.now(),\n );\n\n // Check if we have a valid token that hasn't expired\n if (currentAccessToken && currentTokenExpiry && Date.now() < currentTokenExpiry) {\n log(\n 'Using existing M2M access token (expires in %d seconds)',\n Math.floor((currentTokenExpiry - Date.now()) / 1000),\n );\n this.headers.Authorization = `Bearer ${currentAccessToken}`;\n return;\n }\n\n // Check if there's already a token request in progress (for shared state)\n if (this.sharedTokenState?.tokenPromise) {\n log('Token request already in progress, waiting for completion...');\n const token = await this.sharedTokenState.tokenPromise;\n this.headers.Authorization = `Bearer ${token}`;\n log('Using token from concurrent request');\n return;\n }\n\n log('Fetching new M2M access token...');\n\n // Create token request promise and store it in shared state\n const tokenPromise = this.fetchNewToken();\n if (this.sharedTokenState) {\n this.sharedTokenState.tokenPromise = tokenPromise;\n }\n\n try {\n const newAccessToken = await tokenPromise;\n\n // Update both local and shared token state\n this.accessToken = newAccessToken;\n this.headers.Authorization = `Bearer ${newAccessToken}`;\n\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = newAccessToken;\n this.sharedTokenState.tokenExpiry = this.tokenExpiry;\n // Clear the promise since we're done\n this.sharedTokenState.tokenPromise = undefined;\n log(\n 'Updated shared token state (expires in %d seconds)',\n Math.floor(((this.tokenExpiry || 0) - Date.now()) / 1000),\n );\n }\n\n log('Successfully set new M2M access token');\n } catch (error) {\n // Clear the promise on error\n if (this.sharedTokenState) {\n this.sharedTokenState.tokenPromise = undefined;\n }\n throw error;\n }\n }\n\n private async fetchNewToken(): Promise<string> {\n const assertion = await this.createClientAssertion();\n return await this.exchangeToken(assertion);\n }\n}\n","import {\n InstallFailureAnalysis,\n InstallFailureAnalysisQuery,\n RangeQuery,\n RangeStats,\n TopPlugin,\n TopPluginsQuery,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:analysis');\n\n/**\n * Market Overview Statistics Interface\n * Defines the structure for market overview data\n */\nexport interface MarketOverviewStats {\n devices: {\n count: number;\n prevCount: number;\n };\n installs: {\n count: number;\n prevCount: number;\n };\n period: string;\n pluginCalls: {\n count: number;\n prevCount: number;\n };\n plugins: {\n count: number;\n prevCount: number;\n };\n}\n\n/**\n * Period type for analysis queries\n */\nexport type AnalysisPeriod = '1d' | '7d' | '30d' | '1mo' | '3mo' | '1y';\n\n/**\n * Market overview query parameters\n */\nexport interface MarketOverviewQuery {\n /** Analysis period: 1d, 7d, 30d (rolling periods) or 1mo, 3mo, 1y (natural periods) */\n period?: AnalysisPeriod;\n}\n\n/**\n * Standard API response wrapper\n */\ninterface ApiResponse<T> {\n data: T;\n success: boolean;\n}\n\n/**\n * Analysis Management Service\n *\n * Provides administrative functionality for accessing market analysis and statistics.\n * This service handles retrieving various analytics reports including market overview,\n * plugin trends, and installation analytics for administrative dashboards.\n */\nexport class AnalysisService extends BaseSDK {\n /**\n * Retrieves market overview statistics\n *\n * Returns comprehensive market statistics including plugin counts,\n * installation metrics, new plugin trends, and rating averages\n * with comparison to previous periods.\n *\n * @param params - Query parameters for the analysis\n * @returns Promise resolving to market overview statistics\n */\n async getMarketOverview(params: MarketOverviewQuery = {}): Promise<MarketOverviewStats> {\n const { period = '30d' } = params;\n\n log('Getting market overview statistics for period: %s', period);\n\n const searchParams = new URLSearchParams();\n if (period) {\n searchParams.append('period', period);\n }\n\n const url = `/admin/analysis/plugin/overview${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;\n\n const result = await this.request<ApiResponse<MarketOverviewStats>>(url);\n\n log('Market overview statistics retrieved successfully: %s', result.data);\n\n return result.data;\n }\n\n /**\n * Retrieves market overview statistics for 1 day period\n *\n * Convenience method for getting daily market statistics.\n *\n * @returns Promise resolving to market overview statistics for 1 day\n */\n async getDailyOverview(): Promise<MarketOverviewStats> {\n log('Getting daily market overview');\n return this.getMarketOverview({ period: '1d' });\n }\n\n /**\n * Retrieves market overview statistics for 7 days period\n *\n * Convenience method for getting weekly market statistics.\n *\n * @returns Promise resolving to market overview statistics for 7 days\n */\n async getWeeklyOverview(): Promise<MarketOverviewStats> {\n log('Getting weekly market overview');\n return this.getMarketOverview({ period: '7d' });\n }\n\n /**\n * Retrieves market overview statistics for 30 days period\n *\n * Convenience method for getting monthly market statistics.\n *\n * @returns Promise resolving to market overview statistics for 30 days\n */\n async getMonthlyOverview(): Promise<MarketOverviewStats> {\n log('Getting monthly market overview');\n return this.getMarketOverview({ period: '30d' });\n }\n\n /**\n * Retrieves market overview statistics for current natural month\n *\n * Convenience method for getting current month vs previous month statistics.\n *\n * @returns Promise resolving to market overview statistics for current month\n */\n async getThisMonthOverview(): Promise<MarketOverviewStats> {\n log('Getting this month market overview');\n return this.getMarketOverview({ period: '1mo' });\n }\n\n /**\n * Retrieves market overview statistics for current quarter\n *\n * Convenience method for getting current quarter vs previous quarter statistics.\n *\n * @returns Promise resolving to market overview statistics for current quarter\n */\n async getQuarterlyOverview(): Promise<MarketOverviewStats> {\n log('Getting quarterly market overview');\n return this.getMarketOverview({ period: '3mo' });\n }\n\n /**\n * Retrieves market overview statistics for current year\n *\n * Convenience method for getting current year vs previous year statistics.\n *\n * @returns Promise resolving to market overview statistics for current year\n */\n async getYearlyOverview(): Promise<MarketOverviewStats> {\n log('Getting yearly market overview');\n return this.getMarketOverview({ period: '1y' });\n }\n\n /**\n * Retrieves install failure analysis for plugins within a date range\n *\n * Returns detailed analysis of plugin installation failures including failure counts,\n * failure rates, and most common error messages for each plugin with failures.\n *\n * @param params - Query parameters for the failure analysis\n * @returns Promise resolving to install failure analysis data\n */\n async getInstallFailureAnalysis(\n params: InstallFailureAnalysisQuery,\n ): Promise<InstallFailureAnalysis[]> {\n const { range, limit = 15 } = params;\n\n log('Getting install failure analysis for range: %o, limit: %d', range, limit);\n\n const searchParams = new URLSearchParams();\n searchParams.append('range', JSON.stringify(range));\n if (limit !== 15) {\n searchParams.append('limit', limit.toString());\n }\n\n const url = `/admin/analysis/plugin/install-failure?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<InstallFailureAnalysis[]>>(url);\n\n log('Install failure analysis retrieved successfully for %d plugins', result.data.length);\n\n return result.data;\n }\n\n /**\n * Calculates growth rate between current and previous values\n *\n * Utility method for calculating percentage growth rates from the statistics.\n *\n * @param current - Current period value\n * @param previous - Previous period value\n * @returns Growth rate as percentage (e.g., 15.5 for 15.5% growth)\n */\n static calculateGrowthRate(current: number, previous: number): number {\n if (previous === 0) return current > 0 ? 100 : 0;\n return Math.round(((current - previous) / previous) * 100 * 10) / 10;\n }\n\n /**\n * Formats market overview statistics with calculated growth rates\n *\n * Utility method that enhances the raw statistics with calculated growth rates\n * for easier consumption in dashboards and reports.\n *\n * @param stats - Raw market overview statistics\n * @returns Enhanced statistics with growth rate calculations\n */\n static formatMarketOverview(stats: MarketOverviewStats) {\n return {\n ...stats,\n growth: {\n devices: this.calculateGrowthRate(stats.devices.count, stats.devices.prevCount),\n installs: this.calculateGrowthRate(stats.installs.count, stats.installs.prevCount),\n pluginCalls: this.calculateGrowthRate(stats.pluginCalls.count, stats.pluginCalls.prevCount),\n plugins: this.calculateGrowthRate(stats.plugins.count, stats.plugins.prevCount),\n },\n };\n }\n\n /**\n * Retrieves installation trend statistics for a specified date range\n *\n * Returns daily installation counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to installation trend statistics\n */\n async getRangeInstalls(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting installation trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-installs?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Installation trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves plugin growth trend statistics for a specified date range\n *\n * Returns daily plugin creation counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to plugin growth trend statistics\n */\n async getRangePlugins(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting plugin growth trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-plugins?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Plugin growth trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves device growth trend statistics for a specified date range\n *\n * Note: This is a system-level statistic that tracks device registrations,\n * not plugin-specific metrics. It provides daily device registration counts\n * and trends for the specified period with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to device growth trend statistics\n */\n async getRangeDevices(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting device growth trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/system/range-devices?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Device growth trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves plugin call trend statistics for a specified date range\n *\n * Returns daily plugin call counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to plugin call trend statistics\n */\n async getRangeCalls(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting plugin call trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-calls?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Plugin call trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Calculates trend growth rate between current and previous period totals\n *\n * Utility method for calculating percentage growth rates from range statistics.\n *\n * @param stats - Range statistics with sum and prevSum\n * @returns Growth rate as percentage (e.g., 15.5 for 15.5% growth)\n */\n static calculateTrendGrowthRate(stats: RangeStats): number {\n return this.calculateGrowthRate(stats.sum, stats.prevSum);\n }\n\n /**\n * Retrieves top plugins sorted by specified criteria within a date range\n *\n * Returns list of plugins sorted by the specified criteria (installs or calls)\n * in descending order for the specified date range.\n *\n * @param params - Query parameters including date range, sort criteria, and limit\n * @returns Promise resolving to list of top plugins\n */\n async getTopPlugins(params: TopPluginsQuery): Promise<TopPlugin[]> {\n const { range, sortBy = 'installs', limit = 10 } = params;\n\n const searchParams = new URLSearchParams();\n searchParams.append('range', range.join(','));\n searchParams.append('sortBy', sortBy);\n searchParams.append('limit', limit.toString());\n\n const url = `/admin/analysis/plugin/top-plugins?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<TopPlugin[]>>(url);\n\n return result.data;\n }\n}\n","import type {\n AdminDeploymentOption,\n AdminPluginItem,\n AdminPluginItemDetail,\n IncompleteI18nPlugin,\n InstallationDetails,\n PluginManifest,\n PluginVersion,\n PluginVersionLocalization,\n SystemDependency,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport {\n AdminListQueryParams,\n AdminListResponse,\n PluginI18nImportParams,\n PluginI18nImportResponse,\n PluginUpdateParams,\n PluginVersionCreateParams,\n PluginVersionUpdateParams,\n UnclaimedPluginItem,\n} from '@/types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:plugins');\n\n/**\n * Plugin Management Service\n *\n * Provides administrative functionality for managing plugins in the marketplace.\n * This service handles CRUD operations for plugins, plugin versions, and deployment options.\n */\nexport class PluginService extends BaseSDK {\n /**\n * Batch imports plugin manifests using the dedicated import endpoint\n *\n * This method is intended for use with scripts and bulk import operations.\n *\n * @param manifests - Array of plugin manifests to import\n * @param ownerId - Optional owner ID to associate with the imported plugins\n * @returns Promise resolving to the import results with counts of success, skipped, failed, and a list of failed IDs\n */\n async importPlugins(\n manifests: PluginManifest[],\n ownerId?: number,\n ): Promise<{ failed: number; failedIds: string[]; skipped: number; success: number }> {\n log(`Starting batch plugin import of ${manifests.length} manifests`);\n if (ownerId) {\n log(`Using specified owner ID for import: ${ownerId}`);\n }\n\n const response = await this.request<{\n data: { failed: number; failedIds: string[]; skipped: number; success: number };\n }>('/admin/plugins/import', {\n body: JSON.stringify({\n manifests,\n ownerId,\n }),\n method: 'POST',\n });\n\n log(\n `Plugin import completed: ${response.data.success} succeeded, ${response.data.skipped} skipped, ${response.data.failed} failed`,\n );\n return response.data;\n }\n\n /**\n * Imports plugin internationalization (i18n) data\n *\n * Allows importing localized content for a specific plugin version.\n * This method creates or updates localizations for the specified plugin.\n *\n * @param params - Plugin i18n import parameters containing identifier, version, and localizations\n * @returns Promise resolving to the import results with counts of success and failure\n */\n async importPluginI18n(params: PluginI18nImportParams): Promise<PluginI18nImportResponse> {\n log(\n `Starting i18n import for plugin ${params.identifier} v${params.version} with ${params.localizations.length} localizations`,\n );\n\n const response = await this.request<{\n data: PluginI18nImportResponse;\n message: string;\n }>('/admin/plugins/import/i18n', {\n body: JSON.stringify(params),\n method: 'POST',\n });\n\n log(\n `Plugin i18n import completed: ${response.data.success} succeeded, ${response.data.failed} failed, ${response.data.totalLocalizations} total`,\n );\n return response.data;\n }\n\n /**\n * Retrieves a list of plugins with admin details\n *\n * Supports filtering, pagination, and sorting of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the plugin list response with admin details\n */\n async getPlugins(params: AdminListQueryParams = {}): Promise<AdminListResponse<AdminPluginItem>> {\n log('Getting plugins with params: %O', params);\n\n const queryString = this.buildQueryString(params);\n const url = `/admin/plugins${queryString}`;\n\n const result = await this.request<AdminListResponse<AdminPluginItem>>(url);\n\n log('Retrieved %d plugins', result.data.length);\n return result;\n }\n\n /**\n * Retrieves all published plugin identifiers\n *\n * Returns a lightweight list of all published plugin identifiers without\n * full plugin metadata. This is useful for admin operations that need to know\n * which plugins are currently published and available to users.\n *\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(): Promise<{ identifier: string; lastModified: string }[]> {\n log('Getting published plugin identifiers (admin)');\n\n const result =\n await this.request<{ identifier: string; lastModified: string }[]>('/v1/plugins/identifiers');\n log('Retrieved %d published plugin identifiers (admin)', result.length);\n return result;\n }\n\n /**\n * Retrieves a single plugin with full admin details\n *\n * @param id - Plugin ID or identifier\n * @returns Promise resolving to the detailed plugin information with version history\n */\n async getPlugin(id: number | string): Promise<AdminPluginItemDetail> {\n log('Getting plugin details (admin): %d', id);\n\n const result = await this.request<AdminPluginItemDetail>(`/admin/plugins/${id}`);\n log('Retrieved plugin with %d versions', result.versions.length);\n return result;\n }\n\n /**\n * Retrieves a plugin by its GitHub repository URL\n *\n * @param githubUrl - The GitHub repository URL to search for\n * @returns Promise resolving to the detailed plugin information with version history\n */\n async getPluginByGithubUrl(githubUrl: string): Promise<AdminPluginItemDetail> {\n log('Getting plugin by GitHub URL: %s', githubUrl);\n\n const queryString = this.buildQueryString({ url: githubUrl });\n const result = await this.request<AdminPluginItemDetail>(\n `/admin/plugins/by-github-url${queryString}`,\n );\n log('Retrieved plugin with %d versions', result.versions.length);\n return result;\n }\n\n /**\n * Updates plugin information\n *\n * @param id - Plugin ID\n * @param data - Plugin update data containing fields to update\n * @returns Promise resolving to the updated plugin\n */\n async updatePlugin(id: number, data: PluginUpdateParams): Promise<AdminPluginItem> {\n log('Updating plugin: %d, data: %O', id, data);\n\n const result = await this.request<AdminPluginItem>(`/admin/plugins/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Plugin updated successfully');\n return result;\n }\n\n /**\n * Updates plugin publication status\n *\n * @param id - Plugin ID\n * @param status - New status to set\n * @returns Promise resolving to success response\n */\n async updatePluginStatus(\n id: number,\n status: 'published' | 'draft' | 'review' | 'rejected',\n ): Promise<{ message: string; success: boolean }> {\n log('Updating plugin status: %d to %s', id, status);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}/status`,\n {\n body: JSON.stringify({ status }),\n method: 'PATCH',\n },\n );\n log('Plugin status updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin\n *\n * @param id - Plugin ID\n * @returns Promise resolving to success response\n */\n async deletePlugin(id: number): Promise<{ message: string; success: boolean }> {\n log('Deleting plugin: %d', id);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}`,\n { method: 'DELETE' },\n );\n log('Plugin deleted successfully');\n return result;\n }\n\n /**\n * Retrieves the version history for a plugin\n *\n * @param pluginId - Plugin ID\n * @returns Promise resolving to an array of plugin versions\n */\n async getPluginVersions(pluginId: number): Promise<PluginVersion[]> {\n log('Getting plugin versions: pluginId=%d', pluginId);\n\n const result = await this.request<PluginVersion[]>(`/admin/plugins/${pluginId}/versions`);\n\n log('Retrieved %d versions', result.length);\n return result;\n }\n\n /**\n * Retrieves a specific plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to the plugin version details\n */\n async getPluginVersion(pluginId: number, versionId: number): Promise<PluginVersion> {\n log('Getting version details: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<PluginVersion>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n );\n log('Version details retrieved');\n return result;\n }\n\n /**\n * Retrieves all localizations for a specific plugin version\n *\n * @param pluginId - Plugin ID or identifier\n * @param versionId - Version ID\n * @returns Promise resolving to an array of plugin version localizations\n */\n async getPluginLocalizations(\n pluginId: number | string,\n versionId: number,\n ): Promise<PluginVersionLocalization[]> {\n log('Getting localizations: pluginId=%s, versionId=%d', pluginId, versionId);\n\n const result = await this.request<PluginVersionLocalization[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/localizations`,\n );\n log('Retrieved %d localizations for plugin %s, version %d', result.length, pluginId, versionId);\n return result;\n }\n\n /**\n * Creates a new plugin version with all version-specific data\n *\n * @param pluginId - Plugin ID\n * @param data - Version creation data including all version-specific fields\n * @returns Promise resolving to the created plugin version\n */\n async createPluginVersion(\n pluginId: number,\n data: PluginVersionCreateParams,\n ): Promise<PluginVersion> {\n log('Creating new plugin version: pluginId=%d, data: %O', pluginId, data);\n\n const result = await this.request<PluginVersion>(`/admin/plugins/${pluginId}/versions`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Plugin version created successfully: version=%s', data.version);\n return result;\n }\n\n /**\n * Creates a new plugin version from a manifest\n * Extracts version data from the manifest for easier creation\n *\n * @param pluginId - Plugin ID\n * @param manifest - Plugin manifest containing all version data\n * @param options - Additional options for version creation\n * @returns Promise resolving to the created plugin version\n */\n async createPluginVersionFromManifest(\n pluginId: number,\n manifest: PluginManifest,\n options: {\n isLatest?: boolean;\n isValidated?: boolean;\n } = {},\n ): Promise<PluginVersion> {\n log(\n 'Creating plugin version from manifest: pluginId=%d, version=%s',\n pluginId,\n manifest.version,\n );\n\n const versionData: PluginVersionCreateParams = {\n author: manifest.author?.name,\n authorUrl: manifest.author?.url,\n capabilitiesPrompts: manifest.capabilities?.prompts,\n capabilitiesResources: manifest.capabilities?.resources,\n capabilitiesTools: manifest.capabilities?.tools,\n category: manifest.category,\n description: manifest.description,\n icon: manifest.icon,\n isLatest: options.isLatest,\n isValidated: options.isValidated,\n name: manifest.name,\n prompts: manifest.prompts,\n readme: manifest.overview?.readme,\n resources: manifest.resources,\n summary: manifest.overview?.summary,\n tags: manifest.tags,\n tools: manifest.tools,\n version: manifest.version,\n };\n\n return this.createPluginVersion(pluginId, versionData);\n }\n\n /**\n * Updates a plugin version with comprehensive version-specific data\n *\n * @param idOrIdentifier - Plugin ID\n * @param versionId - Version ID\n * @param data - Version update data including all version-specific fields\n * @returns Promise resolving to the updated plugin version\n */\n async updatePluginVersion(\n idOrIdentifier: number | string,\n versionId: number,\n data: PluginVersionUpdateParams,\n ): Promise<PluginVersion> {\n log(\n 'Updating plugin version: pluginId=%d, versionId=%d, data: %O',\n idOrIdentifier,\n versionId,\n data,\n );\n\n const result = await this.request<PluginVersion>(\n `/admin/plugins/${idOrIdentifier}/versions/${versionId}`,\n {\n body: JSON.stringify(data),\n method: 'PUT',\n },\n );\n\n log('Plugin version updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to success response\n */\n async deletePluginVersion(\n pluginId: number,\n versionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log('Deleting version: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n { method: 'DELETE' },\n );\n log('Plugin version deleted successfully');\n return result;\n }\n\n /**\n * Sets a specific version as the latest version of a plugin\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID to set as latest\n * @returns Promise resolving to success response\n */\n async setPluginVersionAsLatest(\n pluginId: number,\n versionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log('Setting version as latest: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}/latest`,\n { method: 'POST' },\n );\n log('Version set as latest successfully');\n return result;\n }\n\n /**\n * Updates plugin visibility\n *\n * @param id - Plugin ID\n * @param visibility - New visibility setting\n * @returns Promise resolving to success response\n */\n async updatePluginVisibility(\n id: number,\n visibility: 'public' | 'private' | 'unlisted',\n ): Promise<{ message: string; success: boolean }> {\n log('Updating plugin visibility: %d to %s', id, visibility);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}/visibility`,\n {\n body: JSON.stringify({ visibility }),\n method: 'PATCH',\n },\n );\n log('Plugin visibility updated successfully');\n return result;\n }\n\n /**\n * Updates status for multiple plugins in a single operation\n *\n * @param ids - Array of plugin IDs to update\n * @param status - New status to set for all specified plugins\n * @returns Promise resolving to success response\n */\n async batchUpdatePluginStatus(\n ids: number[],\n status: 'published' | 'draft' | 'review' | 'rejected',\n ): Promise<{ message: string; success: boolean }> {\n log('Batch updating plugin status: %O to %s', ids, status);\n\n const result = await this.request<{ message: string; success: boolean }>(\n '/admin/plugins/batch/status',\n {\n body: JSON.stringify({ ids, status }),\n method: 'PATCH',\n },\n );\n log('Batch plugin status update completed');\n return result;\n }\n\n /**\n * Deletes multiple plugins in a single operation\n *\n * @param ids - Array of plugin IDs to delete\n * @returns Promise resolving to success response\n */\n async batchDeletePlugins(ids: number[]): Promise<{ message: string; success: boolean }> {\n log('Batch deleting plugins: %O', ids);\n\n const result = await this.request<{ message: string; success: boolean }>(\n '/admin/plugins/batch/delete',\n {\n body: JSON.stringify({ ids }),\n method: 'DELETE',\n },\n );\n log('Batch plugin deletion completed');\n return result;\n }\n\n /**\n * Retrieves detailed information about a plugin version including deployment options\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to version details with deployment options\n */\n async getPluginVersionDetails(\n pluginId: number,\n versionId: number,\n ): Promise<PluginVersion & { deploymentOptions: any }> {\n log(\n 'Getting version details with deployment options: pluginId=%d, versionId=%d',\n pluginId,\n versionId,\n );\n\n const result = await this.request<PluginVersion & { deploymentOptions: any }>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n );\n log('Version details with deployment options retrieved');\n return result;\n }\n\n /**\n * Retrieves deployment options for a specific plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to an array of deployment options\n */\n async getDeploymentOptions(\n pluginId: number,\n versionId: number,\n ): Promise<AdminDeploymentOption[]> {\n log('Getting deployment options: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<AdminDeploymentOption[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options`,\n );\n log('Retrieved %d deployment options', result.length);\n return result;\n }\n\n /**\n * Creates a new deployment option for a plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param data - Deployment option configuration data\n * @returns Promise resolving to the created deployment option\n */\n async createDeploymentOption(\n pluginId: number,\n versionId: number,\n data: {\n connectionArgs?: string[];\n connectionCommand?: string;\n connectionType: string;\n description?: string;\n installationDetails?: InstallationDetails;\n installationMethod: string;\n isRecommended?: boolean;\n },\n ): Promise<AdminDeploymentOption> {\n log('Creating deployment option: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<AdminDeploymentOption>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options`,\n {\n body: JSON.stringify(data),\n method: 'POST',\n },\n );\n log('Deployment option created successfully');\n return result;\n }\n\n /**\n * Updates an existing deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @param data - Updated deployment option configuration\n * @returns Promise resolving to the updated deployment option\n */\n async updateDeploymentOption(\n pluginId: number,\n versionId: number,\n optionId: number,\n data: {\n connectionArgs?: string[];\n connectionCommand?: string;\n connectionType?: string;\n description?: string;\n installationDetails?: Record<string, any>;\n installationMethod?: string;\n isRecommended?: boolean;\n },\n ): Promise<AdminDeploymentOption> {\n log(\n 'Updating deployment option: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<AdminDeploymentOption>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}`,\n {\n body: JSON.stringify(data),\n method: 'PUT',\n },\n );\n log('Deployment option updated successfully');\n return result;\n }\n\n /**\n * Deletes a deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @returns Promise resolving to success response\n */\n async deleteDeploymentOption(\n pluginId: number,\n versionId: number,\n optionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log(\n 'Deleting deployment option: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}`,\n { method: 'DELETE' },\n );\n log('Deployment option deleted successfully');\n return result;\n }\n\n /**\n * Retrieves system dependencies for a deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @returns Promise resolving to an array of system dependencies\n */\n async getDeploymentOptionSystemDependencies(\n pluginId: number,\n versionId: number,\n optionId: number,\n ): Promise<SystemDependency[]> {\n log(\n 'Getting system dependencies: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<SystemDependency[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}/system-dependencies`,\n );\n log('Retrieved %d system dependencies', result.length);\n return result;\n }\n\n /**\n * Retrieves verified plugins without summary information\n *\n * Returns plugins that are validated but missing summary data.\n *\n * @returns Promise resolving to array of plugins with incomplete summary data\n */\n async getVerifiedPluginsWithoutSummary(): Promise<\n { identifier: string; manifest: PluginManifest; versionId: number }[]\n > {\n log('Getting verified plugins without summary');\n\n const result = await this.request<\n { identifier: string; manifest: PluginManifest; versionId: number }[]\n >('/admin/plugins/verified-without-summary');\n\n log('Retrieved %d verified plugins without summary', result.length);\n return result;\n }\n\n /**\n * Retrieves plugins with incomplete internationalization\n *\n * Returns plugins where pluginVersionLocalizations has only 1 entry.\n *\n * @returns Promise resolving to an array of plugins with incomplete i18n\n */\n async getIncompleteI18nPlugins(): Promise<IncompleteI18nPlugin[]> {\n log('Getting plugins with incomplete i18n');\n\n const result = await this.request<IncompleteI18nPlugin[]>('/admin/plugins/incomplete-i18n');\n log('Retrieved %d plugins with incomplete i18n', result.length);\n return result;\n }\n\n /**\n * Retrieves unclaimed plugins\n *\n * Returns plugins where isClaimed is false, containing only ID and identifier.\n *\n * @returns Promise resolving to an array of unclaimed plugins with basic info\n */\n async getUnclaimedPlugins(): Promise<UnclaimedPluginItem[]> {\n log('Getting unclaimed plugins');\n\n const result = await this.request<UnclaimedPluginItem[]>('/admin/plugins/unclaimed');\n log('Retrieved %d unclaimed plugins', result.length);\n return result;\n }\n}\n","import type { SystemDependency } from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:dependency');\n\n/**\n * System Dependency Management Service\n *\n * Provides administrative functionality for managing system dependencies\n * required by plugins. This service handles creating, updating, deleting,\n * and listing system dependencies that plugins may require.\n */\nexport class SystemDependencyService extends BaseSDK {\n /**\n * Retrieves all system dependencies\n *\n * Gets a list of all defined system dependencies that plugins may require.\n *\n * @returns Promise resolving to an array of system dependencies\n */\n async getSystemDependencies(): Promise<SystemDependency[]> {\n log('Getting all system dependencies');\n\n const result = await this.request<SystemDependency[]>(`/admin/plugins/dependencies`);\n log('Retrieved %d system dependencies', result.length);\n return result;\n }\n\n /**\n * Retrieves a specific system dependency by ID\n *\n * @param id - System dependency ID\n * @returns Promise resolving to the system dependency details\n */\n async getSystemDependency(id: number): Promise<SystemDependency> {\n log('Getting system dependency details: %d', id);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies/${id}`);\n log('System dependency details retrieved');\n return result;\n }\n\n /**\n * Creates a new system dependency\n *\n * @param data - System dependency creation data\n * @returns Promise resolving to the created system dependency\n */\n async createSystemDependency(data: Omit<SystemDependency, 'id'>): Promise<SystemDependency> {\n log('Creating system dependency: %O', data);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('System dependency created successfully');\n return result;\n }\n\n /**\n * Updates an existing system dependency\n *\n * @param id - System dependency ID\n * @param data - System dependency update data\n * @returns Promise resolving to the updated system dependency\n */\n async updateSystemDependency(\n id: number,\n data: Partial<SystemDependency>,\n ): Promise<SystemDependency> {\n log('Updating system dependency: %d, data: %O', id, data);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('System dependency updated successfully');\n return result;\n }\n\n /**\n * Deletes a system dependency\n *\n * @param id - System dependency ID\n * @returns Promise resolving to success response\n */\n async deleteSystemDependency(id: number): Promise<{ message: string; success: boolean }> {\n log('Deleting system dependency: %d', id);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/dependencies/${id}`,\n { method: 'DELETE' },\n );\n log('System dependency deleted successfully');\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:settings');\n\n/**\n * Settings entity representing a system setting\n */\nexport interface Settings {\n /** Creation timestamp (ISO 8601 format) */\n createdAt: string;\n /** Optional description of the setting's purpose */\n description?: string;\n /** Unique identifier for the setting */\n id: number;\n /** Setting key name used for retrieving the setting */\n key: string;\n /** Last update timestamp (ISO 8601 format) */\n updatedAt: string;\n /** Setting value (stored as string) */\n value: string;\n}\n\n/**\n * Configuration for enabled resource types\n */\nexport interface EnabledResources {\n /** Whether agent resources are enabled */\n agents: boolean;\n /** Whether plugin resources are enabled */\n plugins: boolean;\n}\n\n/**\n * Authentication configuration\n */\nexport interface AuthenticationConfig {\n /** Whether authentication is required */\n enabled: boolean;\n /** Supported authentication schemes */\n schemes: string[];\n}\n\n/**\n * Documentation URL configuration\n */\nexport interface DocumentationConfig {\n /** URL to API documentation */\n apiUrl?: string;\n /** URL to privacy policy */\n policyUrl?: string;\n /** URL to terms of service */\n termsOfServiceUrl?: string;\n}\n\n/**\n * Map of all system settings with typed properties\n */\nexport interface SettingsMap {\n /** Additional settings (dynamically added) */\n [key: string]: any;\n /** Authentication configuration */\n authentication: AuthenticationConfig;\n /** Base URL for the marketplace */\n baseURL: string;\n /** Documentation URL configuration */\n documentation: DocumentationConfig;\n /** Configuration for enabled resource types */\n enabledResources: EnabledResources;\n /** Supported locales */\n locales: string[];\n}\n\n/**\n * Parameters for creating a new setting\n */\nexport interface CreateSettingsParams {\n /** Optional description of the setting's purpose */\n description?: string;\n /** Setting key name */\n key: string;\n /** Setting value (will be stored as string) */\n value: string;\n}\n\n/**\n * Parameters for updating an existing setting\n */\nexport interface UpdateSettingsParams {\n /** Optional new description */\n description?: string;\n /** New setting value */\n value: string;\n}\n\n/**\n * Settings Management Service\n *\n * Provides administrative functionality for managing system settings.\n * This service handles getting, creating, updating, and deleting\n * configuration settings for the marketplace.\n */\nexport class SettingsService extends BaseSDK {\n /**\n * Retrieves all system settings\n *\n * Returns a consolidated map of all settings with typed values\n * for known setting keys.\n *\n * @returns Promise resolving to the settings map\n */\n async getSettings(): Promise<SettingsMap> {\n return await this.request<SettingsMap>('/admin/settings');\n }\n\n /**\n * Retrieves a specific setting by key\n *\n * @param key - Setting key name\n * @returns Promise resolving to the setting details\n */\n async getSettingByKey(key: string): Promise<{ data: Settings }> {\n log('Getting setting: %s', key);\n\n const result = await this.request<{ data: Settings }>(`/admin/settings/${key}`);\n log('Setting retrieved');\n return result;\n }\n\n /**\n * Creates a new system setting\n *\n * @param data - Setting creation parameters\n * @returns Promise resolving to the created setting\n */\n async createSetting(data: CreateSettingsParams): Promise<{ data: Settings }> {\n log('Creating setting: %O', data);\n\n const result = await this.request<{ data: Settings }>('/admin/settings', {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Setting created successfully');\n return result;\n }\n\n /**\n * Updates an existing setting\n *\n * @param key - Setting key name\n * @param data - Setting update parameters\n * @returns Promise resolving to the updated setting\n */\n async updateSetting(key: string, data: UpdateSettingsParams): Promise<{ data: Settings }> {\n log('Updating setting: %s, data: %O', key, data);\n\n const result = await this.request<{ data: Settings }>(`/admin/settings/${key}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Setting updated successfully');\n return result;\n }\n\n /**\n * Deletes a setting\n *\n * @param key - Setting key name\n * @returns Promise resolving to success message\n */\n async deleteSetting(key: string): Promise<{ message: string }> {\n log('Deleting setting: %s', key);\n\n const result = await this.request<{ message: string }>(`/admin/settings/${key}`, {\n method: 'DELETE',\n });\n log('Setting deleted successfully');\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport type { AdminListQueryParams, AdminListResponse, ReviewStatus } from '@/types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:review');\n\n/**\n * Review entity representing a plugin review\n */\nexport interface Review {\n /** Optional comment providing feedback */\n comment?: string;\n /** Creation timestamp (ISO 8601 format) */\n createdAt: string;\n /** Unique identifier for the review */\n id: number;\n /** ID of the plugin being reviewed */\n pluginId: number;\n /** ID of the reviewer (if available) */\n reviewerId?: number;\n /** Current status of the review */\n status: ReviewStatus;\n /** Last update timestamp (ISO 8601 format) */\n updatedAt: string;\n}\n\n/**\n * Extended review information with related entities\n */\nexport interface PluginReviewWithRelations extends Review {\n /** Related plugin information */\n plugin?: any;\n /** Related version information */\n version?: any;\n}\n\n/**\n * Parameters for updating a review\n */\nexport interface UpdateReviewParams {\n /** Optional comment or feedback */\n comment?: string;\n /** New status to set for the review */\n status: ReviewStatus;\n}\n\n/**\n * Review Management Service\n *\n * Provides administrative functionality for managing plugin reviews.\n * This service handles listing, fetching, and updating review statuses\n * for plugins in the marketplace.\n */\nexport class ReviewService extends BaseSDK {\n /**\n * Retrieves a list of reviews with filtering options\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the review list response\n */\n async getReviews(\n params: AdminListQueryParams = {},\n ): Promise<AdminListResponse<PluginReviewWithRelations>> {\n log('Getting reviews with params: %O', params);\n\n const queryString = this.buildQueryString(params);\n const url = `/admin/reviews${queryString ? `?${queryString}` : ''}`;\n\n const result = await this.request<AdminListResponse<PluginReviewWithRelations>>(url);\n\n log('Retrieved %d reviews', result.data.length);\n return result;\n }\n\n /**\n * Retrieves a specific review by ID\n *\n * @param id - Review ID\n * @returns Promise resolving to the review details\n */\n async getReviewById(id: number): Promise<Review> {\n log('Getting review details: %d', id);\n\n const result = await this.request<Review>(`/admin/reviews/${id}`);\n log('Review details retrieved');\n return result;\n }\n\n /**\n * Updates a review's status and comment\n *\n * @param id - Review ID\n * @param data - Update parameters containing new status and optional comment\n * @returns Promise resolving to the updated review\n */\n async updateReview(id: number, data: UpdateReviewParams): Promise<Review> {\n log('Updating review: %d, data: %O', id, data);\n\n const result = await this.request<Review>(`/admin/reviews/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Review updated successfully');\n return result;\n }\n\n /**\n * Retrieves the review history for a specific plugin\n *\n * @param pluginId - Plugin ID\n * @returns Promise resolving to an array of reviews for the plugin\n */\n async getPluginReviews(pluginId: number): Promise<{ data: Review[] }> {\n log('Getting plugin reviews: pluginId=%d', pluginId);\n\n const result = await this.request<{ data: Review[] }>(`/admin/reviews/plugin/${pluginId}`);\n log('Retrieved %d reviews for plugin', result.data.length);\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport type { AdminListResponse } from '@/types/admin';\n\ntype AdminPluginEnvListQuery = any;\ntype PluginEnv = any;\n\nconst log = debug('lobe-market-sdk:admin:plugin-env');\n\nexport interface AdminPluginEnvCreateParams {\n description?: string;\n identifier: string;\n key: string;\n value: string;\n}\n\nexport interface AdminPluginEnvUpdateParams {\n description?: string;\n value?: string;\n}\n\n/**\n * Plugin Environment Variable Management Service\n *\n * Provides administrative functionality for managing plugin environment variables.\n */\nexport class PluginEnvService extends BaseSDK {\n /**\n * Retrieves a paginated list of plugin environment variables\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the env list response\n */\n async getPluginEnvs(params: AdminPluginEnvListQuery = {}): Promise<AdminListResponse<PluginEnv>> {\n log('Getting plugin envs with params: %O', params);\n const queryString = this.buildQueryString(params);\n const url = `/admin/plugins/env${queryString}`;\n const result = await this.request<AdminListResponse<PluginEnv>>(url);\n log('Retrieved %d plugin envs', result.data.length);\n return result;\n }\n\n /**\n * Retrieves a single plugin environment variable by ID\n *\n * @param id - Env ID\n * @returns Promise resolving to the env item\n */\n async getPluginEnv(id: number): Promise<PluginEnv> {\n log('Getting plugin env: %d', id);\n const result = await this.request<PluginEnv>(`/admin/plugins/env/${id}`);\n log('Retrieved plugin env: %d', id);\n return result;\n }\n\n /**\n * Creates a new plugin environment variable\n *\n * @param data - Env creation data\n * @returns Promise resolving to the created env item\n */\n async createPluginEnv(data: AdminPluginEnvCreateParams): Promise<PluginEnv> {\n log('Creating plugin env: %O', data);\n const result = await this.request<PluginEnv>(`/admin/plugins/env`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Plugin env created successfully');\n return result;\n }\n\n /**\n * Updates a plugin environment variable\n *\n * @param id - Env ID\n * @param data - Env update data\n * @returns Promise resolving to the updated env item\n */\n async updatePluginEnv(id: number, data: AdminPluginEnvUpdateParams): Promise<PluginEnv> {\n log('Updating plugin env: %d, data: %O', id, data);\n const result = await this.request<PluginEnv>(`/admin/plugins/env/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Plugin env updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin environment variable\n *\n * @param id - Env ID\n * @returns Promise resolving to success response\n */\n async deletePluginEnv(id: number): Promise<{ success: boolean }> {\n log('Deleting plugin env: %d', id);\n const result = await this.request<{ success: boolean }>(`/admin/plugins/env/${id}`, {\n method: 'DELETE',\n });\n log('Plugin env deleted successfully');\n return result;\n }\n\n /**\n * Batch import plugin environment variables\n *\n * @param data - Batch import data, format: { [plugin: string]: { [envKey: string]: string } }\n * @returns Promise resolving to import result\n */\n async importPluginEnvs(\n data: Record<string, Record<string, string>>,\n ): Promise<{ success: number }> {\n log('Batch importing plugin envs: %O', data);\n const result = await this.request<{ success: number }>(`/admin/plugins/env/import`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Batch import completed: %d envs imported', result.success);\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '../core/BaseSDK';\nimport type {\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n DiscoveryDocument,\n MarketSDKOptions,\n} from '../types';\nimport { AgentService, AuthService, DiscoveryService, PluginsService } from './services';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk');\n\n/**\n * LobeHub Market SDK Client\n *\n * Main client for accessing the LobeHub Marketplace API.\n * This class provides access to marketplace resources like plugins, agents,\n * and service discovery information. It follows a composition pattern\n * by combining specialized domain services.\n */\nexport class MarketSDK extends BaseSDK {\n /**\n * Agents service for accessing agent-related functionality\n * Provides methods to list, search, retrieve agent information, and upload agents\n */\n readonly agents: AgentService;\n\n /**\n * Auth service for authentication and authorization\n * Provides methods for OIDC user authentication, client registration, and M2M token management\n */\n readonly auth: AuthService;\n\n /**\n * Plugins service for accessing plugin-related functionality\n * Provides methods to list, search, retrieve plugin information, and report installation attempts\n */\n readonly plugins: PluginsService;\n\n /**\n * Discovery service for retrieving API service information\n * Used to get information about available endpoints and services\n */\n private readonly discovery: DiscoveryService;\n\n /**\n * Creates a new MarketSDK instance\n *\n * @param options - Configuration options for the SDK\n */\n constructor(options: MarketSDKOptions = {}) {\n // Create shared token state object for all services\n const sharedTokenState = {\n accessToken: undefined,\n tokenExpiry: undefined,\n };\n\n super(options, undefined, sharedTokenState);\n log('MarketSDK instance created');\n\n // Initialize domain services with shared headers and token state for efficient reuse\n this.agents = new AgentService(options, this.headers, sharedTokenState);\n this.auth = new AuthService(options, this.headers, sharedTokenState);\n this.plugins = new PluginsService(options, this.headers, sharedTokenState);\n this.discovery = new DiscoveryService(options, this.headers, sharedTokenState);\n }\n\n /**\n * Retrieves the service discovery document\n *\n * The discovery document provides information about available API endpoints,\n * versions, and capabilities of the Market API.\n *\n * @returns Promise resolving to the service discovery document\n */\n async getDiscoveryDocument(): Promise<DiscoveryDocument> {\n return this.discovery.getDiscoveryDocument();\n }\n\n /**\n * Registers a new client for M2M authentication\n *\n * This method registers a client application with the Market API and returns\n * unique credentials (client_id and client_secret) that can be used for M2M authentication.\n * These credentials should be stored securely and used to initialize the SDK.\n *\n * @param request - Client registration request data\n * @returns Promise resolving to the client registration response with credentials\n * @throws Error if registration fails\n * @deprecated Use auth.registerClient() instead\n */\n async registerClient(request: ClientRegistrationRequest): Promise<ClientRegistrationResponse> {\n log('Registering client (deprecated method, use auth.registerClient): %s', request.clientName);\n return this.auth.registerClient(request);\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n AgentCreateRequest,\n AgentCreateResponse,\n AgentDetailQuery,\n AgentItemDetail,\n AgentListQuery,\n AgentListResponse,\n AgentModifyRequest,\n AgentModifyResponse,\n AgentUploadRequest,\n AgentUploadResponse,\n AgentVersionCreateRequest,\n AgentVersionCreateResponse,\n AgentVersionModifyRequest,\n AgentVersionModifyResponse,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:agents');\n\n/**\n * Agents Service\n *\n * Provides access to agent-related functionality in the LobeHub Marketplace.\n * This service handles listing, searching, and retrieving detailed information\n * about agents available in the marketplace.\n */\nexport class AgentService extends BaseSDK {\n /**\n * Retrieves a list of agents from the marketplace\n *\n * Supports filtering, pagination, and localization of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @param options - Optional request options\n * @returns Promise resolving to the agent list response containing items and pagination info\n */\n async getAgentList(\n params: AgentListQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<AgentListResponse> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent list: %O', queryParams);\n\n const result = await this.request<AgentListResponse>(`/v1/agents${queryString}`, options);\n log('Retrieved %d agents', result.items.length);\n return result;\n }\n\n /**\n * Retrieves detailed information about a specific agent\n *\n * Returns complete agent information including A2A AgentCard data,\n * configuration, skills, and localized content.\n *\n * @param id - Unique identifier of the agent\n * @param params - Query parameters for locale and version\n * @param options - Optional request options\n * @returns Promise resolving to the agent detail information\n */\n async getAgentDetail(\n id: string,\n params: AgentDetailQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<AgentItemDetail> {\n const locale = params.locale || this.defaultLocale;\n const queryParams: Record<string, string> = { locale };\n if (params.version !== undefined) {\n queryParams.version = params.version.toString();\n }\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent detail: %O', { id, ...params });\n\n const result = await this.request<AgentItemDetail>(\n `/v1/agents/detail/${id}${queryString}`,\n options,\n );\n\n log('Agent detail successfully retrieved: %s', id);\n return result;\n }\n\n /**\n * Retrieves all published agent identifiers\n *\n * Returns a lightweight list of all published agent identifiers without\n * full agent metadata. This is useful for clients that need to know which\n * agents are available without fetching complete agent information.\n *\n * @param options - Optional request options\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(\n options?: globalThis.RequestInit,\n ): Promise<{ id: string; lastModified: string }[]> {\n log('Getting published agent identifiers');\n\n const result = await this.request<{ id: string; lastModified: string }[]>(\n '/v1/agents/identifiers',\n options,\n );\n log('Retrieved %d published agent identifiers', result.length);\n return result;\n }\n\n /**\n * Retrieves agent categories and their counts\n *\n * Returns a list of categories along with the number of agents in each category.\n * Useful for building category filters in a UI. Supports optional search filtering\n * via 'q' parameter and locale specification.\n *\n * @param params - Query parameters for filtering categories\n * @param options - Optional request options\n * @returns Promise resolving to an array of category items with counts\n */\n async getCategories(\n params: { locale?: string; q?: string } = {},\n options?: globalThis.RequestInit,\n ): Promise<{ category: string; count: number }[]> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent categories: %O', queryParams);\n\n const result = await this.request<{ category: string; count: number }[]>(\n `/v1/agents/categories${queryString}`,\n options,\n );\n log('Retrieved %d categories', result.length);\n return result;\n }\n\n /**\n * Uploads an agent to the marketplace\n *\n * Allows users to upload new agents or update existing ones.\n * The agent data should conform to the A2A AgentCard specification.\n *\n * @param agentData - The agent data to upload\n * @param options - Optional request options\n * @returns Promise resolving to the upload response\n */\n async uploadAgent(\n agentData: AgentUploadRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentUploadResponse> {\n log('Uploading agent: %s@%s', agentData.agentIdentifier, agentData.version.version);\n\n const result = await this.request<AgentUploadResponse>('/v1/agents/upload', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent uploaded successfully: %O', result);\n return result;\n }\n\n /**\n * Creates a new agent in the marketplace\n *\n * @param agentData - The agent data to create\n * @param options - Optional request options\n * @returns Promise resolving to the created agent response\n */\n async createAgent(\n agentData: AgentCreateRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentCreateResponse> {\n log('Creating agent: %s', agentData.identifier);\n\n const result = await this.request<AgentCreateResponse>('/v1/agents/create', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent created successfully: %O', result);\n return result;\n }\n\n /**\n * Creates a new version for an existing agent\n *\n * @param versionData - The version data to create\n * @param options - Optional request options\n * @returns Promise resolving to the created version response\n */\n async createAgentVersion(\n versionData: AgentVersionCreateRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentVersionCreateResponse> {\n log('Creating agent version: %s', versionData.identifier);\n\n const result = await this.request<AgentVersionCreateResponse>('/v1/agents/version/create', {\n body: JSON.stringify(versionData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent version created successfully: %O', result);\n return result;\n }\n\n /**\n * Modifies an existing agent\n *\n * @param agentData - The agent data to modify\n * @param options - Optional request options\n * @returns Promise resolving to the modified agent response\n */\n async modifyAgent(\n agentData: AgentModifyRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentModifyResponse> {\n log('Modifying agent: %s', agentData.identifier);\n\n const result = await this.request<AgentModifyResponse>('/v1/agents/modify', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent modified successfully: %O', result);\n return result;\n }\n\n /**\n * Modifies a specific version of an existing agent\n *\n * @param versionData - The version data to modify\n * @param options - Optional request options\n * @returns Promise resolving to the modified version response\n */\n async modifyAgentVersion(\n versionData: AgentVersionModifyRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentVersionModifyResponse> {\n log('Modifying agent version: %s@%s', versionData.identifier, versionData.version);\n\n const result = await this.request<AgentVersionModifyResponse>('/v1/agents/version/modify', {\n body: JSON.stringify(versionData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent version modified successfully: %O', result);\n return result;\n }\n\n /**\n * Checks if an agent exists in the marketplace\n *\n * @param identifier - Unique identifier of the agent\n * @param options - Optional request options\n * @returns Promise resolving to true if agent exists, false otherwise\n */\n async checkAgentExists(identifier: string, options?: globalThis.RequestInit): Promise<boolean> {\n log('Checking if agent exists: %s', identifier);\n\n try {\n await this.getAgentDetail(identifier, {}, options);\n log('Agent exists: %s', identifier);\n return true;\n } catch {\n log('Agent does not exist: %s', identifier);\n return false;\n }\n }\n}\n","import debug from 'debug';\nimport urlJoin from 'url-join';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n AuthorizationCodeTokenRequest,\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n OAuthTokenResponse,\n RefreshTokenRequest,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:auth');\n\n/**\n * Auth Service\n *\n * Provides authentication and authorization functionality for the LobeHub Marketplace.\n * This service handles OIDC user authentication, client registration, and M2M token management.\n */\nexport class AuthService extends BaseSDK {\n // ===== OAuth Handoff Types =====\n /** Successful handoff payload */\n private static readonly HANDOFF_SUCCESS_STATUS = 'success' as const;\n /** Pending handoff status */\n private static readonly HANDOFF_PENDING_STATUS = 'pending' as const;\n /** Consumed handoff status */\n private static readonly HANDOFF_CONSUMED_STATUS = 'consumed' as const;\n /** Expired handoff status */\n private static readonly HANDOFF_EXPIRED_STATUS = 'expired' as const;\n\n /** Normalize token response from snake_case to camelCase fields */\n private static normalizeTokenResponse(data: any): OAuthTokenResponse {\n if (!data?.access_token || !data?.token_type) {\n throw new Error('Invalid token response payload');\n }\n\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n idToken: data.id_token,\n refreshToken: data.refresh_token,\n scope: data.scope,\n tokenType: data.token_type,\n };\n }\n\n /**\n * Exchanges an authorization code or refresh token for access credentials\n *\n * Supports both the authorization_code and refresh_token grant types.\n * The method normalizes the response to camelCase field names.\n *\n * @param request - Token exchange parameters\n * @param options - Optional fetch options (e.g., custom headers)\n * @returns Promise resolving to the OAuth token payload\n */\n async exchangeOAuthToken(\n request: AuthorizationCodeTokenRequest | RefreshTokenRequest,\n options?: globalThis.RequestInit,\n ): Promise<OAuthTokenResponse> {\n const grantType = request.grantType ?? 'authorization_code';\n\n if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {\n throw new Error(`Unsupported grant type: ${grantType}`);\n }\n\n log('Exchanging OAuth token using grant_type=%s', grantType);\n\n const tokenUrl = urlJoin(this.baseUrl, 'market-oidc/token');\n const params = new URLSearchParams();\n params.set('grant_type', grantType);\n\n if (grantType === 'authorization_code') {\n const { clientId, code, codeVerifier, redirectUri } =\n request as AuthorizationCodeTokenRequest;\n\n if (!clientId || !code || !codeVerifier || !redirectUri) {\n throw new Error(\n 'clientId, code, codeVerifier, and redirectUri are required for authorization_code',\n );\n }\n\n params.set('client_id', clientId);\n params.set('code', code);\n params.set('code_verifier', codeVerifier);\n params.set('redirect_uri', redirectUri);\n } else {\n const { refreshToken, clientId } = request as RefreshTokenRequest;\n\n if (!refreshToken) {\n throw new Error('refreshToken is required for refresh_token grant');\n }\n\n params.set('refresh_token', refreshToken);\n if (clientId) params.set('client_id', clientId);\n }\n\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n if (options?.headers) {\n new Headers(options.headers).forEach((value, key) => {\n headers.set(key, value);\n });\n }\n\n const requestInit: globalThis.RequestInit = {\n ...options,\n body: params,\n headers,\n method: 'POST',\n };\n\n const response = await fetch(tokenUrl, requestInit);\n\n let payload: any;\n try {\n payload = await response.json();\n } catch (error) {\n log('Failed to parse token response: %O', error);\n throw new Error(`Failed to parse token response: ${response.status} ${response.statusText}`);\n }\n\n if (!response.ok) {\n const errorDescription = payload?.error_description || payload?.error || response.statusText;\n const errorMsg = `Token exchange failed: ${response.status} ${errorDescription}`;\n log('Error: %s', errorMsg);\n throw new Error(errorMsg);\n }\n\n log('Token exchange successful');\n return AuthService.normalizeTokenResponse(payload);\n }\n\n /**\n * Retrieves user information from the OIDC userinfo endpoint\n *\n * Requires a valid access token in the Authorization header.\n *\n * @param accessToken - The access token to use for authentication\n * @param options - Optional request options\n * @returns Promise resolving to the user information\n */\n async getUserInfo(\n accessToken: string,\n options?: globalThis.RequestInit,\n ): Promise<{\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n sub: string;\n }> {\n log('Getting user info');\n\n const userInfoUrl = urlJoin(this.baseUrl, 'market-oidc/userinfo');\n\n const response = await fetch(userInfoUrl, {\n headers: {\n 'Authorization': `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n ...options,\n });\n\n if (!response.ok) {\n const errorMsg = `Failed to fetch user info: ${response.status} ${response.statusText}`;\n log('Error: %s', errorMsg);\n throw new Error(errorMsg);\n }\n\n const userInfo = await response.json();\n log('User info retrieved successfully');\n return userInfo;\n }\n\n /**\n * Registers a new OAuth client with the marketplace\n *\n * This is typically used for device registration or application setup.\n * Returns client credentials that can be used for M2M authentication.\n *\n * @param clientData - The client registration data\n * @param options - Optional request options\n * @returns Promise resolving to the client credentials\n */\n async registerClient(\n clientData: ClientRegistrationRequest,\n options?: globalThis.RequestInit,\n ): Promise<ClientRegistrationResponse> {\n log('Registering client: %s (%s)', clientData.clientName, clientData.clientType);\n\n const result = await this.request<ClientRegistrationResponse>('/v1/clients/register', {\n body: JSON.stringify(clientData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Client registered successfully: %s', result.client_id);\n return result;\n }\n\n /**\n * Fetches an M2M (Machine-to-Machine) access token\n *\n * Uses client credentials to obtain an access token for server-to-server communication.\n * This method requires clientId and clientSecret to be set in the SDK options.\n *\n * @returns Promise resolving to the access token and expiration time\n */\n async getM2MToken(): Promise<{\n accessToken: string;\n expiresIn: number;\n }> {\n log('Fetching M2M token');\n\n const tokenInfo = await this.fetchM2MToken();\n\n log('M2M token fetched successfully');\n return tokenInfo;\n }\n\n /** OAuth handoff response shapes */\n // Using inline type aliases inside the class for better encapsulation\n // success: 200\n private static typeHandoffSuccess(data: { clientId: string; code: string; redirectUri: string }) {\n return {\n clientId: data.clientId,\n code: data.code,\n redirectUri: data.redirectUri,\n status: AuthService.HANDOFF_SUCCESS_STATUS,\n } as const;\n }\n\n /**\n * Get OAuth handoff status and data by id.\n * Maps server HTTP statuses to a typed status union:\n * - 200: success\n * - 202: pending\n * - 404: consumed\n * - 410: expired\n * - others: error (throws)\n */\n async getOAuthHandoff(\n id: string,\n options?: globalThis.RequestInit,\n ): Promise<\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'pending' }\n | { status: 'consumed' }\n | { status: 'expired' }\n > {\n if (!id) throw new Error('id is required');\n\n log('Getting OAuth handoff: %s', id);\n\n const handoffUrl = `${urlJoin(this.baseUrl, 'market-oidc/handoff')}?id=${encodeURIComponent(id)}`;\n const response = await fetch(handoffUrl, {\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n ...options,\n });\n\n // Map known statuses\n if (response.status === 200) {\n const json = await response.json();\n const result = AuthService.typeHandoffSuccess({\n clientId: json.clientId,\n code: json.code,\n redirectUri: json.redirectUri,\n });\n log('OAuth handoff success for id: %s', id);\n return result;\n }\n if (response.status === 202) {\n log('OAuth handoff pending for id: %s', id);\n return { status: AuthService.HANDOFF_PENDING_STATUS };\n }\n if (response.status === 404) {\n log('OAuth handoff consumed for id: %s', id);\n return { status: AuthService.HANDOFF_CONSUMED_STATUS };\n }\n if (response.status === 410) {\n log('OAuth handoff expired for id: %s', id);\n return { status: AuthService.HANDOFF_EXPIRED_STATUS };\n }\n\n // Attempt to parse error for diagnostics\n let errorMessage = `Failed to fetch OAuth handoff (status ${response.status} ${response.statusText})`;\n try {\n const errJson = await response.json();\n if (errJson && (errJson.message || errJson.error)) {\n errorMessage = `${errorMessage}: ${errJson.error ?? ''} ${errJson.message ?? ''}`.trim();\n }\n } catch {\n // ignore json parse error\n }\n log('Error: %s', errorMessage);\n throw new Error(errorMessage);\n }\n\n /**\n * Poll OAuth handoff result until it becomes terminal.\n * Terminal statuses: success, expired, consumed.\n * Non-terminal: pending → continue polling.\n */\n async pollOAuthHandoff(\n id: string,\n params: {\n intervalMs?: number;\n requestInit?: globalThis.RequestInit;\n signal?: AbortSignal;\n timeoutMs?: number;\n } = {},\n ): Promise<\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'expired' }\n | { status: 'consumed' }\n > {\n const intervalMs = params.intervalMs ?? 1500;\n const timeoutMs = params.timeoutMs ?? 60_000;\n const startedAt = Date.now();\n const { signal, requestInit } = params;\n\n log('Start polling OAuth handoff: %s', id);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (signal?.aborted) {\n const err = new Error('Polling aborted');\n log('Error: %s', err.message);\n throw err;\n }\n if (Date.now() - startedAt > timeoutMs) {\n const err = new Error('Polling timeout');\n log('Error: %s', err.message);\n throw err;\n }\n\n const result = await this.getOAuthHandoff(id, requestInit);\n\n if (\n result.status === 'success' ||\n result.status === 'expired' ||\n result.status === 'consumed'\n ) {\n log('Stop polling OAuth handoff (terminal): %s -> %s', id, result.status);\n return result as\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'expired' }\n | { status: 'consumed' };\n }\n\n // pending → wait and retry\n await new Promise<void>((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n }\n }\n}\n","import debug from 'debug';\nimport urlJoin from 'url-join';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type { DiscoveryDocument } from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:discovery');\n\n/**\n * Discovery Service\n *\n * Provides functionality for retrieving service discovery information\n * from the LobeHub Marketplace API. The discovery document contains\n * metadata about available endpoints, authentication methods, and\n * other capabilities of the API.\n */\nexport class DiscoveryService extends BaseSDK {\n /** Cached discovery document to avoid repeated requests */\n private discoveryDoc?: DiscoveryDocument;\n\n /**\n * Retrieves the service discovery document\n *\n * This document contains information about available API endpoints,\n * authentication methods, and other capabilities of the Market API.\n * The result is cached after the first request to improve performance.\n *\n * @returns Promise resolving to the service discovery document\n */\n async getDiscoveryDocument(): Promise<DiscoveryDocument> {\n log('Fetching discovery document');\n if (this.discoveryDoc) {\n log('Returning cached discovery document');\n return this.discoveryDoc;\n }\n\n const res = await fetch(urlJoin(this.baseUrl, '/.well-known/discovery'));\n if (!res.ok) {\n throw new Error(await res.text());\n }\n\n this.discoveryDoc = (await res.json()) as DiscoveryDocument;\n log('Discovery document successfully fetched');\n return this.discoveryDoc;\n }\n}\n","import type {\n CallReportRequest,\n CallReportResponse,\n InstallReportRequest,\n InstallReportResponse,\n PluginItemDetail,\n PluginManifest,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n CategoryItem,\n CategoryListQuery,\n PluginListResponse,\n PluginQueryParams,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:plugins');\n\n/**\n * Plugins Service\n *\n * Provides access to plugin-related functionality in the LobeHub Marketplace.\n * This service handles listing, searching, and retrieving detailed information\n * about plugins available in the marketplace.\n */\nexport class PluginsService extends BaseSDK {\n /**\n * Retrieves a list of plugins from the marketplace\n *\n * Supports filtering, pagination, and localization of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @param options\n * @returns Promise resolving to the plugin list response containing items and pagination info\n */\n async getPluginList(\n params: PluginQueryParams = {},\n options?: globalThis.RequestInit,\n ): Promise<PluginListResponse> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting plugin list: %O', queryParams);\n\n const result = await this.request<PluginListResponse>(`/v1/plugins${queryString}`, options);\n log('Retrieved %d plugins', result.items.length);\n return result;\n }\n\n /**\n * Retrieves all plugin categories and their counts\n *\n * Returns a list of categories along with the number of plugins in each category.\n * Useful for building category filters in a UI. Supports optional search filtering\n * via 'q' parameter and locale specification.\n *\n * @param params - Query parameters for filtering categories\n * @param options - Optional request options\n * @returns Promise resolving to an array of category items with counts\n */\n async getCategories(\n params: CategoryListQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<CategoryItem[]> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting plugin categories: %O', queryParams);\n\n const result = await this.request<CategoryItem[]>(\n `/v1/plugins/categories${queryString}`,\n options,\n );\n log('Retrieved %d categories', result.length);\n return result;\n }\n\n /**\n * Retrieves all published plugin identifiers\n *\n * Returns a lightweight list of all published plugin identifiers without\n * full plugin metadata. This is useful for clients that need to know which\n * plugins are available without fetching complete plugin information.\n *\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(\n options?: globalThis.RequestInit,\n ): Promise<{ identifier: string; lastModified: string }[]> {\n log('Getting published plugin identifiers');\n\n const result = await this.request<{ identifier: string; lastModified: string }[]>(\n '/v1/plugins/identifiers',\n options,\n );\n log('Retrieved %d published plugin identifiers', result.length);\n return result;\n }\n\n /**\n * Retrieves the manifest for a specific plugin\n *\n * The manifest contains detailed information about a plugin, including\n * its capabilities, tools, prompts, and resources.\n *\n * @param identifier - Unique identifier of the plugin\n * @param locale - Optional locale for localized content (defaults to SDK default locale)\n * @param version - Optional specific version to retrieve (defaults to latest)\n * @param options\n * @returns Promise resolving to the plugin manifest\n */\n async getPluginManifest(\n {\n locale,\n version,\n identifier,\n }: {\n identifier: string;\n locale?: string;\n version?: string;\n },\n options?: globalThis.RequestInit,\n ): Promise<PluginManifest> {\n log('Getting plugin manifest: %O', { identifier, locale, version });\n const localeParam = locale || this.defaultLocale;\n const params: Record<string, string> = { locale: localeParam };\n if (version) {\n params.version = version;\n }\n const queryString = this.buildQueryString(params);\n\n const manifest = await this.request<PluginManifest>(\n `/v1/plugins/${identifier}/manifest${queryString}`,\n options,\n );\n\n log('Plugin manifest successfully retrieved: %s', identifier);\n return manifest;\n }\n\n /**\n * Retrieves the plugin detailed information about a plugin, including\n * its capabilities, tools, prompts, and resources.\n *\n * @param identifier - Unique identifier of the plugin\n * @param locale - Optional locale for localized content (defaults to SDK default locale)\n * @param version - Optional specific version to retrieve (defaults to latest)\n * @returns Promise resolving to the plugin manifest\n */\n async getPluginDetail(\n {\n locale,\n version,\n identifier,\n }: {\n identifier: string;\n locale?: string;\n version?: string;\n },\n options?: globalThis.RequestInit,\n ): Promise<PluginItemDetail> {\n log('Getting plugin detail: %O', { identifier, locale, version });\n const localeParam = locale || this.defaultLocale;\n const params: Record<string, string> = { locale: localeParam };\n if (version) {\n params.version = version;\n }\n const queryString = this.buildQueryString(params);\n\n const manifest = await this.request<PluginItemDetail>(\n `/v1/plugins/${identifier}${queryString}`,\n options,\n );\n\n log('Plugin manifest successfully retrieved: %s', identifier);\n return manifest;\n }\n\n /**\n * Report a plugin installation attempt\n *\n * Reports the outcome of a plugin installation attempt, including timing,\n * success status, manifest information, and error details if applicable.\n * This helps improve plugin validation and provides analytics about installation success rates.\n *\n * @param reportData - The installation report data\n * @returns Promise resolving to the report submission response\n *\n */\n async reportInstallation(reportData: InstallReportRequest): Promise<InstallReportResponse> {\n log('Reporting installation for %s@%s', reportData.identifier, reportData.version);\n\n const result = await this.request<InstallReportResponse>('/v1/plugins/report/installation', {\n body: JSON.stringify(reportData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n log('Installation report submitted successfully: %O', result);\n return result;\n }\n\n /**\n * Report a plugin method call attempt\n *\n * Reports the outcome of a plugin method call, including timing,\n * success status, method information, and error details if applicable.\n * This helps improve plugin performance monitoring and provides usage analytics.\n *\n * @param reportData - The call report data\n * @returns Promise resolving to the report submission response\n */\n async reportCall(reportData: CallReportRequest): Promise<CallReportResponse> {\n log(\n 'Reporting call for %s@%s - %s:%s',\n reportData.identifier,\n reportData.version,\n reportData.methodType,\n reportData.methodName,\n );\n\n const result = await this.request<CallReportResponse>('/v1/plugins/report/call', {\n body: JSON.stringify(reportData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n log('Call report submitted successfully: %O', result);\n return result;\n }\n}\n","import { z } from 'zod';\n\n/**\n * Visibility levels for plugins in the marketplace\n * - public: Visible to all users\n * - private: Visible only to the owner and authorized users\n * - internal: Visible only within the organization\n */\nexport const VisibilityEnumSchema = z.enum(['public', 'private', 'internal']);\n\n/**\n * Publication status options for plugins\n * - published: Publicly available in the marketplace\n * - unpublished: Not publicly visible\n * - archived: Marked as no longer maintained\n * - deprecated: Marked as deprecated, but still available\n */\nexport const StatusEnumSchema = z.enum(['published', 'unpublished', 'archived', 'deprecated']);\n\n/**\n * Common query parameters for admin list endpoints\n * These parameters are used for pagination, filtering, and sorting.\n */\nexport interface AdminListQueryParams {\n /** Current page number (1-based) */\n current?: number;\n /** Search keyword for filtering results */\n keyword?: string;\n /** Number of items per page */\n pageSize?: number;\n /** Field to sort results by */\n sortField?: string;\n /** Sort direction */\n sortOrder?: 'ascend' | 'descend';\n}\n\n/**\n * Common response format for paginated admin list endpoints\n * This structure provides both the data and pagination information.\n */\nexport interface AdminListResponse<T> {\n /** Current page number (1-based) */\n current: number;\n /** Array of items for the current page */\n data: T[];\n /** Number of items per page */\n pageSize: number;\n /** Total number of items across all pages */\n total: number;\n /** Total number of pages */\n totalPages: number;\n}\n\n/**\n * Review status options\n * - pending: Awaiting review\n * - approved: Review approved\n * - rejected: Review rejected\n */\nexport type ReviewStatus = 'pending' | 'approved' | 'rejected';\n\n/**\n * Review status schema for validation\n */\nexport const ReviewStatusEnumSchema = z.enum(['published', 'draft', 'review', 'rejected']);\n\n/**\n * Parameters for admin plugin listing\n * Extends the common query parameters with plugin-specific filters.\n */\nexport interface AdminPluginParams {\n /** Filter for featured plugins */\n featured?: boolean;\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Sort direction */\n order?: 'asc' | 'desc';\n /** Field to sort by */\n orderBy?: 'createdAt' | 'updatedAt' | 'installCount' | 'ratingAverage';\n /** Filter by owner ID */\n ownerId?: number;\n /** Search query string */\n query?: string;\n /** Filter by plugin status */\n status?: 'published' | 'draft' | 'review' | 'rejected';\n /** Filter by visibility level */\n visibility?: 'public' | 'private' | 'unlisted';\n}\n\n/**\n * Parameters for creating a new plugin version\n */\nexport interface PluginVersionCreateParams {\n /** Author or organization name for this version */\n author?: string;\n /** URL to the author's website or profile */\n authorUrl?: string;\n /** Capability flag: whether this plugin provides prompts */\n capabilitiesPrompts?: boolean;\n /** Capability flag: whether this plugin manages resources (MCP) */\n capabilitiesResources?: boolean;\n /** Capability flag: whether this plugin provides tools */\n capabilitiesTools?: boolean;\n /** Category key for the plugin */\n category?: string;\n /** Description of the plugin version */\n description?: string;\n /** Icon URL or emoji for the plugin */\n icon?: string;\n /** Whether this is the latest version */\n isLatest?: boolean;\n /** Whether this version has been validated */\n isValidated?: boolean;\n /** Name of the plugin version */\n name?: string;\n /** Array of prompt definitions */\n prompts?: any[];\n /** README content */\n readme?: string;\n /** Array of resource definitions */\n resources?: any[];\n /** Summary of the plugin version */\n summary?: string;\n /** Array of tags for categorization */\n tags?: string[];\n /** Array of tool definitions */\n tools?: any[];\n /** Semantic version string (e.g., \"1.0.0\") */\n version: string;\n}\n\n/**\n * Parameters for updating an existing plugin version\n */\nexport interface PluginVersionUpdateParams {\n /** Author or organization name for this version */\n author?: string;\n /** URL to the author's website or profile */\n authorUrl?: string;\n /** Capability flag: whether this plugin provides prompts */\n capabilitiesPrompts?: boolean;\n /** Capability flag: whether this plugin manages resources (MCP) */\n capabilitiesResources?: boolean;\n /** Capability flag: whether this plugin provides tools */\n capabilitiesTools?: boolean;\n /** Category key for the plugin */\n category?: string;\n /** Description of the plugin version */\n description?: string;\n /** Icon URL or emoji for the plugin */\n icon?: string;\n /** Whether this version has been validated */\n isValidated?: boolean;\n /** Name of the plugin version */\n name?: string;\n /** Array of prompt definitions */\n prompts?: any[];\n /** README content */\n readme?: string;\n /** Array of resource definitions */\n resources?: any[];\n /** Summary of the plugin version */\n summary?: string;\n /** Array of tags for categorization */\n tags?: string[];\n /** Array of tool definitions */\n tools?: any[];\n}\n\n/**\n * Parameters for updating plugin basic metadata (non-version specific)\n */\nexport interface PluginUpdateParams {\n /** Unique identifier for the plugin */\n identifier?: string;\n /** Whether this plugin has been claimed by its original author */\n isClaimed?: boolean;\n /** Whether this plugin is featured */\n isFeatured?: boolean;\n /** Whether this plugin is officially maintained by LobeHub */\n isOfficial?: boolean;\n /** Publication status */\n status?: 'published' | 'draft' | 'review' | 'rejected';\n /** Visibility level */\n visibility?: 'public' | 'private' | 'unlisted';\n}\n\n/**\n * Plugin localization data\n */\nexport interface PluginLocalization {\n /** Plugin description in specific locale */\n description: string;\n /** Locale identifier (e.g., 'en-US', 'zh-CN') */\n locale: string;\n /** Plugin name in specific locale */\n name: string;\n /** Summary in specific locale */\n summary?: string;\n /** Plugin tags in specific locale */\n tags?: string[];\n}\n\n/**\n * Parameters for importing plugin i18n data\n */\nexport interface PluginI18nImportParams {\n /** Plugin identifier */\n identifier: string;\n /** Array of localizations for this plugin version */\n localizations: PluginLocalization[];\n /** Plugin version */\n version: string;\n}\n\n/**\n * Response from plugin i18n import operation\n */\nexport interface PluginI18nImportResponse {\n /** Number of failed localizations */\n failed: number;\n /** Number of successful localizations */\n success: number;\n /** Total number of processed localizations */\n totalLocalizations: number;\n}\n\n/**\n * Unclaimed plugin item data structure\n * Represents a plugin that has not been claimed by its author\n */\nexport interface UnclaimedPluginItem {\n /** Plugin ID */\n id: number;\n /** Plugin identifier */\n identifier: string;\n}\n","/**\n * LobeHub Market JavaScript SDK\n *\n * This is the main entry point for the LobeHub Market SDK.\n * It exports the primary client classes and all type definitions.\n */\n\n// Export admin-related functionality\nexport { MarketAdmin } from './admin';\n\n// Export market-related functionality\nexport { MarketSDK } from './market';\n\n// Export SDK-specific types\nexport * from './types';\n\n// Re-export all type definitions from the types package\nexport * from '@lobehub/market-types';\n"],"mappings":";AAAA,OAAOA,YAAW;;;ACAlB,OAAO,WAAW;AAClB,SAAS,eAAe;AACxB,OAAO,aAAa;AAKpB,IAAM,MAAM,MAAM,sBAAsB;AAajC,IAAM,UAAN,MAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BnB,YACE,UAA4B,CAAC,GAC7B,eACA,kBACA;AAEA,SAAK,UAAU,QAAQ,WAAW,QAAQ,IAAI,mBAAmB;AACjE,SAAK,aAAa,QAAQ,KAAK,SAAS,KAAK;AAC7C,SAAK,eAAe,QAAQ,KAAK,SAAS,OAAO;AAGjD,SAAK,gBAAgB,QAAQ,iBAAiB;AAE9C,SAAK,qBAAqB,QAAQ;AAClC,SAAK,WAAW,QAAQ;AACxB,SAAK,eAAe,QAAQ;AAG5B,SAAK,mBAAmB;AAGxB,UAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;AAG7C,QAAI,eAAe;AACjB,WAAK,UAAU;AACf,UAAI,6BAA6B;AAAA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AAAA;AAAA,EA8BrC,YAAY,UAA4B,CAAC,GAAG;AAE1C,UAAM,mBAAmB;AAAA,MACvB,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAEA,UAAM,SAAS,QAAW,gBAAgB;AAC1C,IAAAD,MAAI,4BAA4B;AAGhC,SAAK,SAAS,IAAI,aAAa,SAAS,KAAK,SAAS,gBAAgB;AACtE,SAAK,OAAO,IAAI,YAAY,SAAS,KAAK,SAAS,gBAAgB;AACnE,SAAK,UAAU,IAAI,eAAe,SAAS,KAAK,SAAS,gBAAgB;AACzE,SAAK,YAAY,IAAI,iBAAiB,SAAS,KAAK,SAAS,gBAAgB;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,uBAAmD;AACvD,WAAO,KAAK,UAAU,qBAAqB;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,MAAM,eAAe,SAAyE;AAC5F,IAAAA,MAAI,uEAAuE,QAAQ,UAAU;AAC7F,WAAO,KAAK,KAAK,eAAe,OAAO;AAAA,EACzC;AACF;;;AKjGA,SAAS,SAAS;AAQX,IAAM,uBAAuB,EAAE,KAAK,CAAC,UAAU,WAAW,UAAU,CAAC;AASrE,IAAM,mBAAmB,EAAE,KAAK,CAAC,aAAa,eAAe,YAAY,YAAY,CAAC;AA+CtF,IAAM,yBAAyB,EAAE,KAAK,CAAC,aAAa,SAAS,UAAU,UAAU,CAAC;;;AC/CzF,cAAc;","names":["debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","log","debug","debug","debug","log","debug","debug","urlJoin","log","debug","urlJoin","debug","urlJoin","log","debug","urlJoin","debug","log","debug","log","debug"]}
|
|
1
|
+
{"version":3,"sources":["../src/admin/MarketAdmin.ts","../src/core/BaseSDK.ts","../src/admin/services/AnalysisService.ts","../src/admin/services/PluginService.ts","../src/admin/services/SystemDependencyService.ts","../src/admin/services/SettingsService.ts","../src/admin/services/ReviewService.ts","../src/admin/services/PluginEnvService.ts","../src/market/market-sdk.ts","../src/market/services/AgentService.ts","../src/market/services/AuthService.ts","../src/market/services/DiscoveryService.ts","../src/market/services/PluginsService.ts","../src/types/admin.ts","../src/index.ts"],"sourcesContent":["import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport { MarketSDKOptions } from '@/types';\n\nimport {\n AnalysisService,\n PluginEnvService,\n PluginService,\n ReviewService,\n SettingsService,\n SystemDependencyService,\n} from './services';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin');\n\n/**\n * LobeHub Market Admin SDK Client\n *\n * Client for accessing administrative functionality of the LobeHub Marketplace.\n * This SDK provides privileged operations for managing plugins, reviews,\n * system settings, and dependencies. It requires admin-level authentication.\n */\nexport class MarketAdmin extends BaseSDK {\n /**\n * Market analysis service\n * Provides methods for accessing market analytics and statistics\n */\n readonly analysis: AnalysisService;\n\n /**\n * Plugin management service\n * Provides methods for creating, updating, and managing plugins\n */\n readonly plugins: PluginService;\n\n readonly env: PluginEnvService;\n\n /**\n * Review management service\n * Provides methods for moderating and managing user reviews\n */\n readonly reviews: ReviewService;\n\n /**\n * System settings management service\n * Provides methods for configuring marketplace settings\n */\n readonly settings: SettingsService;\n\n /**\n * System dependency management service\n * Provides methods for managing system dependencies required by plugins\n */\n readonly dependencies: SystemDependencyService;\n\n /**\n * Creates a new MarketAdmin instance\n *\n * @param options - Configuration options for the SDK\n */\n constructor(options: MarketSDKOptions = {}) {\n // Use admin-specific API key if available\n const apiKey = options.apiKey || process.env.MARKET_ADMIN_API_KEY;\n\n // Create shared token state object for all services\n const sharedTokenState = {\n accessToken: undefined,\n tokenExpiry: undefined,\n };\n\n super({ ...options, apiKey }, undefined, sharedTokenState);\n log('MarketAdmin instance created');\n\n // Initialize admin services with shared headers and token state for efficient reuse\n this.analysis = new AnalysisService(options, this.headers, sharedTokenState);\n this.plugins = new PluginService(options, this.headers, sharedTokenState);\n this.reviews = new ReviewService(options, this.headers, sharedTokenState);\n this.settings = new SettingsService(options, this.headers, sharedTokenState);\n this.dependencies = new SystemDependencyService(options, this.headers, sharedTokenState);\n this.env = new PluginEnvService(options, this.headers, sharedTokenState);\n }\n}\n","import debug from 'debug';\nimport { SignJWT } from 'jose';\nimport urlJoin from 'url-join';\n\nimport type { MarketSDKOptions, SharedTokenState } from '../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:core');\n\n/**\n * Base SDK class\n *\n * Provides shared request handling and authentication functionality that is used\n * by both the Market SDK and Admin SDK. This class handles the common concerns:\n * - API endpoint configuration\n * - Authentication header management\n * - HTTP request handling\n * - Error handling\n * - Query string building\n */\nexport class BaseSDK {\n /** Base API URL */\n protected apiBaseUrl: string;\n /** Base URL */\n protected baseUrl: string;\n /** OAuth URL */\n protected oauthBaseUrl: string;\n\n /** Default locale for requests that require localization */\n protected defaultLocale: string;\n\n /** HTTP headers to include with all requests */\n protected headers: Record<string, string>;\n\n private clientId?: string;\n private clientSecret?: string;\n private readonly initialAccessToken?: string;\n private accessToken?: string;\n private tokenExpiry?: number;\n\n // Shared token state for all instances\n private sharedTokenState?: SharedTokenState;\n\n /**\n * Creates a new BaseSDK instance\n *\n * @param options - Configuration options for the SDK\n * @param sharedHeaders - Optional shared headers object for reuse across services\n * @param sharedTokenState - Optional shared token state object for reuse across services\n */\n constructor(\n options: MarketSDKOptions = {},\n sharedHeaders?: Record<string, string>,\n sharedTokenState?: SharedTokenState,\n ) {\n // Set base URL from options, environment variable, or default to production URL\n this.baseUrl = options.baseURL || process.env.MARKET_BASE_URL || 'https://market.lobehub.com';\n this.apiBaseUrl = urlJoin(this.baseUrl, 'api');\n this.oauthBaseUrl = urlJoin(this.baseUrl, 'oauth');\n\n // Set default locale from options or use English as default\n this.defaultLocale = options.defaultLocale || 'en-US';\n\n this.initialAccessToken = options.accessToken;\n this.clientId = options.clientId;\n this.clientSecret = options.clientSecret;\n\n // Share token state across instances if provided\n this.sharedTokenState = sharedTokenState;\n\n // Get API key from options or environment variable\n const apiKey = options.apiKey || process.env.MARKET_API_KEY;\n\n // Either use shared headers or create new headers object\n if (sharedHeaders) {\n this.headers = sharedHeaders;\n log('Using shared headers object');\n } else {\n this.headers = {\n 'Content-Type': 'application/json',\n };\n log('Created new headers object');\n }\n\n // If an apiKey is provided, use it for authorization.\n // This will be overridden by M2M auth if credentials are also provided.\n if (apiKey) {\n this.headers.Authorization = `Bearer ${apiKey}`;\n }\n\n // If an accessToken is provided on init, it takes precedence.\n if (this.initialAccessToken) {\n this.headers.Authorization = `Bearer ${this.initialAccessToken}`;\n }\n\n log('BaseSDK instance created: %O', {\n baseUrl: this.baseUrl,\n defaultLocale: this.defaultLocale,\n hasApiKey: !!apiKey,\n hasInitialAccessToken: !!this.initialAccessToken,\n hasM2MCredentials: !!this.clientId,\n hasSharedTokenState: !!this.sharedTokenState,\n });\n }\n\n /**\n * Sends an HTTP request to the API and handles the response\n *\n * @param url - Request URL path (will be appended to baseUrl)\n * @param options - Fetch API request options\n * @returns Promise resolving to the parsed JSON response\n * @throws Error if the request fails\n */\n // eslint-disable-next-line no-undef\n protected async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const requestUrl = urlJoin(this.apiBaseUrl, url);\n log('Sending request: %s', requestUrl);\n\n // If no access token was provided on init, and we have M2M creds, run the auth flow.\n if (!this.initialAccessToken && this.clientId && this.clientSecret) {\n await this.setM2MAuthToken();\n }\n\n const response = await fetch(requestUrl, {\n ...options,\n headers: {\n ...this.headers,\n ...options.headers,\n },\n });\n\n if (!response.ok) {\n const errorMsg = `Request failed: ${response.status} ${response.statusText}`;\n try {\n const errorBody = await response.json();\n\n console.error('Request error: %s', JSON.stringify(errorBody));\n\n throw new Error(`${errorMsg} - ${JSON.stringify(errorBody)}`);\n } catch {\n throw new Error(errorMsg);\n }\n }\n\n log('Request successful: %s', url);\n return response.json() as Promise<T>;\n }\n\n /**\n * Builds a URL query string from a parameters object\n *\n * @param params - Object containing query parameters\n * @returns Formatted query string (including leading ? if params exist)\n */\n protected buildQueryString(params: Record<string, any>): string {\n const query = Object.entries(params)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n .filter(([_, value]) => value !== undefined && value !== null)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)\n .join('&');\n\n return query ? `?${query}` : '';\n }\n\n /**\n * Sets an authentication token for API requests\n *\n * @param token - API authentication token\n */\n setAuthToken(token: string): void {\n log('Setting authentication token');\n this.accessToken = undefined;\n this.tokenExpiry = undefined;\n\n // Clear shared token state if it exists\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = undefined;\n this.sharedTokenState.tokenExpiry = undefined;\n }\n\n this.headers.Authorization = `Bearer ${token}`;\n }\n\n /**\n * Clears the authentication token\n */\n clearAuthToken(): void {\n log('Clearing authentication token');\n this.accessToken = undefined;\n this.tokenExpiry = undefined;\n\n // Clear shared token state if it exists\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = undefined;\n this.sharedTokenState.tokenExpiry = undefined;\n }\n\n delete this.headers.Authorization;\n }\n\n /**\n * Fetches an M2M access token.\n * This method is designed for server-side use cases where you need to manage the token lifecycle\n * (e.g., storing it in a cookie).\n *\n * @returns A promise that resolves to an object containing the access token and its expiry time.\n */\n public async fetchM2MToken(): Promise<{ accessToken: string; expiresIn: number }> {\n if (!this.clientId || !this.clientSecret) {\n throw new Error('clientId and clientSecret are required to fetch an M2M token.');\n }\n\n log('Fetching M2M token for server-side use');\n\n const assertion = await this.createClientAssertion();\n const tokenData = await this.exchangeTokenForServer(assertion);\n\n log('M2M token fetched successfully');\n\n return {\n accessToken: tokenData.access_token,\n expiresIn: tokenData.expires_in || 3600,\n };\n }\n\n private async createClientAssertion(): Promise<string> {\n if (!this.clientId || !this.clientSecret) {\n throw new Error('Missing clientId or clientSecret for M2M authentication.');\n }\n\n const secret = new TextEncoder().encode(this.clientSecret);\n\n const tokenEndpoint = `${this.oauthBaseUrl}/token`;\n\n return await new SignJWT({})\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuer(this.clientId)\n .setSubject(this.clientId)\n .setAudience(tokenEndpoint)\n .setJti(crypto.randomUUID())\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(secret);\n }\n\n private async exchangeToken(clientAssertion: string): Promise<string> {\n const tokenData = await this.exchangeTokenForServer(clientAssertion);\n\n // Calculate token expiry time (current time + expires_in seconds - 60 seconds buffer)\n const expiresInSeconds = tokenData.expires_in || 3600; // Default to 1 hour if not provided\n this.tokenExpiry = Date.now() + (expiresInSeconds - 60) * 1000; // 60 seconds buffer\n\n return tokenData.access_token;\n }\n\n private async exchangeTokenForServer(clientAssertion: string): Promise<any> {\n const tokenEndpoint = urlJoin(this.oauthBaseUrl, 'token');\n log('Exchanging token at endpoint: %s', tokenEndpoint);\n\n const params = new URLSearchParams();\n params.append('grant_type', 'client_credentials');\n params.append(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n );\n params.append('client_assertion', clientAssertion);\n\n const response = await fetch(tokenEndpoint, {\n body: params,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n });\n\n const tokenData = await response.json();\n\n if (!response.ok) {\n throw new Error(`Token exchange failed: ${JSON.stringify(tokenData)}`);\n }\n\n return tokenData;\n }\n\n private async setM2MAuthToken(): Promise<void> {\n // Use shared token state if available\n const currentAccessToken = this.sharedTokenState?.accessToken || this.accessToken;\n const currentTokenExpiry = this.sharedTokenState?.tokenExpiry || this.tokenExpiry;\n\n log(\n 'Token check: hasSharedState=%s, hasCurrentToken=%s, tokenExpiry=%d, currentTime=%d',\n !!this.sharedTokenState,\n !!currentAccessToken,\n currentTokenExpiry || 0,\n Date.now(),\n );\n\n // Check if we have a valid token that hasn't expired\n if (currentAccessToken && currentTokenExpiry && Date.now() < currentTokenExpiry) {\n log(\n 'Using existing M2M access token (expires in %d seconds)',\n Math.floor((currentTokenExpiry - Date.now()) / 1000),\n );\n this.headers.Authorization = `Bearer ${currentAccessToken}`;\n return;\n }\n\n // Check if there's already a token request in progress (for shared state)\n if (this.sharedTokenState?.tokenPromise) {\n log('Token request already in progress, waiting for completion...');\n const token = await this.sharedTokenState.tokenPromise;\n this.headers.Authorization = `Bearer ${token}`;\n log('Using token from concurrent request');\n return;\n }\n\n log('Fetching new M2M access token...');\n\n // Create token request promise and store it in shared state\n const tokenPromise = this.fetchNewToken();\n if (this.sharedTokenState) {\n this.sharedTokenState.tokenPromise = tokenPromise;\n }\n\n try {\n const newAccessToken = await tokenPromise;\n\n // Update both local and shared token state\n this.accessToken = newAccessToken;\n this.headers.Authorization = `Bearer ${newAccessToken}`;\n\n if (this.sharedTokenState) {\n this.sharedTokenState.accessToken = newAccessToken;\n this.sharedTokenState.tokenExpiry = this.tokenExpiry;\n // Clear the promise since we're done\n this.sharedTokenState.tokenPromise = undefined;\n log(\n 'Updated shared token state (expires in %d seconds)',\n Math.floor(((this.tokenExpiry || 0) - Date.now()) / 1000),\n );\n }\n\n log('Successfully set new M2M access token');\n } catch (error) {\n // Clear the promise on error\n if (this.sharedTokenState) {\n this.sharedTokenState.tokenPromise = undefined;\n }\n throw error;\n }\n }\n\n private async fetchNewToken(): Promise<string> {\n const assertion = await this.createClientAssertion();\n return await this.exchangeToken(assertion);\n }\n}\n","import {\n InstallFailureAnalysis,\n InstallFailureAnalysisQuery,\n RangeQuery,\n RangeStats,\n TopPlugin,\n TopPluginsQuery,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:analysis');\n\n/**\n * Market Overview Statistics Interface\n * Defines the structure for market overview data\n */\nexport interface MarketOverviewStats {\n devices: {\n count: number;\n prevCount: number;\n };\n installs: {\n count: number;\n prevCount: number;\n };\n period: string;\n pluginCalls: {\n count: number;\n prevCount: number;\n };\n plugins: {\n count: number;\n prevCount: number;\n };\n}\n\n/**\n * Period type for analysis queries\n */\nexport type AnalysisPeriod = '1d' | '7d' | '30d' | '1mo' | '3mo' | '1y';\n\n/**\n * Market overview query parameters\n */\nexport interface MarketOverviewQuery {\n /** Analysis period: 1d, 7d, 30d (rolling periods) or 1mo, 3mo, 1y (natural periods) */\n period?: AnalysisPeriod;\n}\n\n/**\n * Standard API response wrapper\n */\ninterface ApiResponse<T> {\n data: T;\n success: boolean;\n}\n\n/**\n * Analysis Management Service\n *\n * Provides administrative functionality for accessing market analysis and statistics.\n * This service handles retrieving various analytics reports including market overview,\n * plugin trends, and installation analytics for administrative dashboards.\n */\nexport class AnalysisService extends BaseSDK {\n /**\n * Retrieves market overview statistics\n *\n * Returns comprehensive market statistics including plugin counts,\n * installation metrics, new plugin trends, and rating averages\n * with comparison to previous periods.\n *\n * @param params - Query parameters for the analysis\n * @returns Promise resolving to market overview statistics\n */\n async getMarketOverview(params: MarketOverviewQuery = {}): Promise<MarketOverviewStats> {\n const { period = '30d' } = params;\n\n log('Getting market overview statistics for period: %s', period);\n\n const searchParams = new URLSearchParams();\n if (period) {\n searchParams.append('period', period);\n }\n\n const url = `/admin/analysis/plugin/overview${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;\n\n const result = await this.request<ApiResponse<MarketOverviewStats>>(url);\n\n log('Market overview statistics retrieved successfully: %s', result.data);\n\n return result.data;\n }\n\n /**\n * Retrieves market overview statistics for 1 day period\n *\n * Convenience method for getting daily market statistics.\n *\n * @returns Promise resolving to market overview statistics for 1 day\n */\n async getDailyOverview(): Promise<MarketOverviewStats> {\n log('Getting daily market overview');\n return this.getMarketOverview({ period: '1d' });\n }\n\n /**\n * Retrieves market overview statistics for 7 days period\n *\n * Convenience method for getting weekly market statistics.\n *\n * @returns Promise resolving to market overview statistics for 7 days\n */\n async getWeeklyOverview(): Promise<MarketOverviewStats> {\n log('Getting weekly market overview');\n return this.getMarketOverview({ period: '7d' });\n }\n\n /**\n * Retrieves market overview statistics for 30 days period\n *\n * Convenience method for getting monthly market statistics.\n *\n * @returns Promise resolving to market overview statistics for 30 days\n */\n async getMonthlyOverview(): Promise<MarketOverviewStats> {\n log('Getting monthly market overview');\n return this.getMarketOverview({ period: '30d' });\n }\n\n /**\n * Retrieves market overview statistics for current natural month\n *\n * Convenience method for getting current month vs previous month statistics.\n *\n * @returns Promise resolving to market overview statistics for current month\n */\n async getThisMonthOverview(): Promise<MarketOverviewStats> {\n log('Getting this month market overview');\n return this.getMarketOverview({ period: '1mo' });\n }\n\n /**\n * Retrieves market overview statistics for current quarter\n *\n * Convenience method for getting current quarter vs previous quarter statistics.\n *\n * @returns Promise resolving to market overview statistics for current quarter\n */\n async getQuarterlyOverview(): Promise<MarketOverviewStats> {\n log('Getting quarterly market overview');\n return this.getMarketOverview({ period: '3mo' });\n }\n\n /**\n * Retrieves market overview statistics for current year\n *\n * Convenience method for getting current year vs previous year statistics.\n *\n * @returns Promise resolving to market overview statistics for current year\n */\n async getYearlyOverview(): Promise<MarketOverviewStats> {\n log('Getting yearly market overview');\n return this.getMarketOverview({ period: '1y' });\n }\n\n /**\n * Retrieves install failure analysis for plugins within a date range\n *\n * Returns detailed analysis of plugin installation failures including failure counts,\n * failure rates, and most common error messages for each plugin with failures.\n *\n * @param params - Query parameters for the failure analysis\n * @returns Promise resolving to install failure analysis data\n */\n async getInstallFailureAnalysis(\n params: InstallFailureAnalysisQuery,\n ): Promise<InstallFailureAnalysis[]> {\n const { range, limit = 15 } = params;\n\n log('Getting install failure analysis for range: %o, limit: %d', range, limit);\n\n const searchParams = new URLSearchParams();\n searchParams.append('range', JSON.stringify(range));\n if (limit !== 15) {\n searchParams.append('limit', limit.toString());\n }\n\n const url = `/admin/analysis/plugin/install-failure?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<InstallFailureAnalysis[]>>(url);\n\n log('Install failure analysis retrieved successfully for %d plugins', result.data.length);\n\n return result.data;\n }\n\n /**\n * Calculates growth rate between current and previous values\n *\n * Utility method for calculating percentage growth rates from the statistics.\n *\n * @param current - Current period value\n * @param previous - Previous period value\n * @returns Growth rate as percentage (e.g., 15.5 for 15.5% growth)\n */\n static calculateGrowthRate(current: number, previous: number): number {\n if (previous === 0) return current > 0 ? 100 : 0;\n return Math.round(((current - previous) / previous) * 100 * 10) / 10;\n }\n\n /**\n * Formats market overview statistics with calculated growth rates\n *\n * Utility method that enhances the raw statistics with calculated growth rates\n * for easier consumption in dashboards and reports.\n *\n * @param stats - Raw market overview statistics\n * @returns Enhanced statistics with growth rate calculations\n */\n static formatMarketOverview(stats: MarketOverviewStats) {\n return {\n ...stats,\n growth: {\n devices: this.calculateGrowthRate(stats.devices.count, stats.devices.prevCount),\n installs: this.calculateGrowthRate(stats.installs.count, stats.installs.prevCount),\n pluginCalls: this.calculateGrowthRate(stats.pluginCalls.count, stats.pluginCalls.prevCount),\n plugins: this.calculateGrowthRate(stats.plugins.count, stats.plugins.prevCount),\n },\n };\n }\n\n /**\n * Retrieves installation trend statistics for a specified date range\n *\n * Returns daily installation counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to installation trend statistics\n */\n async getRangeInstalls(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting installation trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-installs?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Installation trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves plugin growth trend statistics for a specified date range\n *\n * Returns daily plugin creation counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to plugin growth trend statistics\n */\n async getRangePlugins(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting plugin growth trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-plugins?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Plugin growth trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves device growth trend statistics for a specified date range\n *\n * Note: This is a system-level statistic that tracks device registrations,\n * not plugin-specific metrics. It provides daily device registration counts\n * and trends for the specified period with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to device growth trend statistics\n */\n async getRangeDevices(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting device growth trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/system/range-devices?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Device growth trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Retrieves plugin call trend statistics for a specified date range\n *\n * Returns daily plugin call counts and trends for the specified period\n * with optional comparison to a previous period.\n *\n * @param params - Query parameters including date range and display config\n * @returns Promise resolving to plugin call trend statistics\n */\n async getRangeCalls(params: RangeQuery): Promise<RangeStats> {\n const { display, range, prevRange } = params;\n\n log('Getting plugin call trend statistics for range: %s to %s', range[0], range[1]);\n\n const searchParams = new URLSearchParams();\n searchParams.append('display', display);\n searchParams.append('range', range.join(','));\n if (prevRange) {\n searchParams.append('prevRange', prevRange.join(','));\n }\n\n const url = `/admin/analysis/plugin/range-calls?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<RangeStats>>(url);\n\n log(\n 'Plugin call trend statistics retrieved successfully: %d data points',\n result.data.data.length,\n );\n\n return result.data;\n }\n\n /**\n * Calculates trend growth rate between current and previous period totals\n *\n * Utility method for calculating percentage growth rates from range statistics.\n *\n * @param stats - Range statistics with sum and prevSum\n * @returns Growth rate as percentage (e.g., 15.5 for 15.5% growth)\n */\n static calculateTrendGrowthRate(stats: RangeStats): number {\n return this.calculateGrowthRate(stats.sum, stats.prevSum);\n }\n\n /**\n * Retrieves top plugins sorted by specified criteria within a date range\n *\n * Returns list of plugins sorted by the specified criteria (installs or calls)\n * in descending order for the specified date range.\n *\n * @param params - Query parameters including date range, sort criteria, and limit\n * @returns Promise resolving to list of top plugins\n */\n async getTopPlugins(params: TopPluginsQuery): Promise<TopPlugin[]> {\n const { range, sortBy = 'installs', limit = 10 } = params;\n\n const searchParams = new URLSearchParams();\n searchParams.append('range', range.join(','));\n searchParams.append('sortBy', sortBy);\n searchParams.append('limit', limit.toString());\n\n const url = `/admin/analysis/plugin/top-plugins?${searchParams.toString()}`;\n\n const result = await this.request<ApiResponse<TopPlugin[]>>(url);\n\n return result.data;\n }\n}\n","import type {\n AdminDeploymentOption,\n AdminPluginItem,\n AdminPluginItemDetail,\n IncompleteI18nPlugin,\n InstallationDetails,\n PluginManifest,\n PluginVersion,\n PluginVersionLocalization,\n SystemDependency,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport {\n AdminListQueryParams,\n AdminListResponse,\n PluginI18nImportParams,\n PluginI18nImportResponse,\n PluginUpdateParams,\n PluginVersionCreateParams,\n PluginVersionUpdateParams,\n UnclaimedPluginItem,\n} from '@/types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:plugins');\n\n/**\n * Plugin Management Service\n *\n * Provides administrative functionality for managing plugins in the marketplace.\n * This service handles CRUD operations for plugins, plugin versions, and deployment options.\n */\nexport class PluginService extends BaseSDK {\n /**\n * Batch imports plugin manifests using the dedicated import endpoint\n *\n * This method is intended for use with scripts and bulk import operations.\n *\n * @param manifests - Array of plugin manifests to import\n * @param ownerId - Optional owner ID to associate with the imported plugins\n * @returns Promise resolving to the import results with counts of success, skipped, failed, and a list of failed IDs\n */\n async importPlugins(\n manifests: PluginManifest[],\n ownerId?: number,\n ): Promise<{ failed: number; failedIds: string[]; skipped: number; success: number }> {\n log(`Starting batch plugin import of ${manifests.length} manifests`);\n if (ownerId) {\n log(`Using specified owner ID for import: ${ownerId}`);\n }\n\n const response = await this.request<{\n data: { failed: number; failedIds: string[]; skipped: number; success: number };\n }>('/admin/plugins/import', {\n body: JSON.stringify({\n manifests,\n ownerId,\n }),\n method: 'POST',\n });\n\n log(\n `Plugin import completed: ${response.data.success} succeeded, ${response.data.skipped} skipped, ${response.data.failed} failed`,\n );\n return response.data;\n }\n\n /**\n * Imports plugin internationalization (i18n) data\n *\n * Allows importing localized content for a specific plugin version.\n * This method creates or updates localizations for the specified plugin.\n *\n * @param params - Plugin i18n import parameters containing identifier, version, and localizations\n * @returns Promise resolving to the import results with counts of success and failure\n */\n async importPluginI18n(params: PluginI18nImportParams): Promise<PluginI18nImportResponse> {\n log(\n `Starting i18n import for plugin ${params.identifier} v${params.version} with ${params.localizations.length} localizations`,\n );\n\n const response = await this.request<{\n data: PluginI18nImportResponse;\n message: string;\n }>('/admin/plugins/import/i18n', {\n body: JSON.stringify(params),\n method: 'POST',\n });\n\n log(\n `Plugin i18n import completed: ${response.data.success} succeeded, ${response.data.failed} failed, ${response.data.totalLocalizations} total`,\n );\n return response.data;\n }\n\n /**\n * Retrieves a list of plugins with admin details\n *\n * Supports filtering, pagination, and sorting of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the plugin list response with admin details\n */\n async getPlugins(params: AdminListQueryParams = {}): Promise<AdminListResponse<AdminPluginItem>> {\n log('Getting plugins with params: %O', params);\n\n const queryString = this.buildQueryString(params);\n const url = `/admin/plugins${queryString}`;\n\n const result = await this.request<AdminListResponse<AdminPluginItem>>(url);\n\n log('Retrieved %d plugins', result.data.length);\n return result;\n }\n\n /**\n * Retrieves all published plugin identifiers\n *\n * Returns a lightweight list of all published plugin identifiers without\n * full plugin metadata. This is useful for admin operations that need to know\n * which plugins are currently published and available to users.\n *\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(): Promise<{ identifier: string; lastModified: string }[]> {\n log('Getting published plugin identifiers (admin)');\n\n const result =\n await this.request<{ identifier: string; lastModified: string }[]>('/v1/plugins/identifiers');\n log('Retrieved %d published plugin identifiers (admin)', result.length);\n return result;\n }\n\n /**\n * Retrieves a single plugin with full admin details\n *\n * @param id - Plugin ID or identifier\n * @returns Promise resolving to the detailed plugin information with version history\n */\n async getPlugin(id: number | string): Promise<AdminPluginItemDetail> {\n log('Getting plugin details (admin): %d', id);\n\n const result = await this.request<AdminPluginItemDetail>(`/admin/plugins/${id}`);\n log('Retrieved plugin with %d versions', result.versions.length);\n return result;\n }\n\n /**\n * Retrieves a plugin by its GitHub repository URL\n *\n * @param githubUrl - The GitHub repository URL to search for\n * @returns Promise resolving to the detailed plugin information with version history\n */\n async getPluginByGithubUrl(githubUrl: string): Promise<AdminPluginItemDetail> {\n log('Getting plugin by GitHub URL: %s', githubUrl);\n\n const queryString = this.buildQueryString({ url: githubUrl });\n const result = await this.request<AdminPluginItemDetail>(\n `/admin/plugins/by-github-url${queryString}`,\n );\n log('Retrieved plugin with %d versions', result.versions.length);\n return result;\n }\n\n /**\n * Updates plugin information\n *\n * @param id - Plugin ID\n * @param data - Plugin update data containing fields to update\n * @returns Promise resolving to the updated plugin\n */\n async updatePlugin(id: number, data: PluginUpdateParams): Promise<AdminPluginItem> {\n log('Updating plugin: %d, data: %O', id, data);\n\n const result = await this.request<AdminPluginItem>(`/admin/plugins/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Plugin updated successfully');\n return result;\n }\n\n /**\n * Updates plugin publication status\n *\n * @param id - Plugin ID\n * @param status - New status to set\n * @returns Promise resolving to success response\n */\n async updatePluginStatus(\n id: number,\n status: 'published' | 'draft' | 'review' | 'rejected',\n ): Promise<{ message: string; success: boolean }> {\n log('Updating plugin status: %d to %s', id, status);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}/status`,\n {\n body: JSON.stringify({ status }),\n method: 'PATCH',\n },\n );\n log('Plugin status updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin\n *\n * @param id - Plugin ID\n * @returns Promise resolving to success response\n */\n async deletePlugin(id: number): Promise<{ message: string; success: boolean }> {\n log('Deleting plugin: %d', id);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}`,\n { method: 'DELETE' },\n );\n log('Plugin deleted successfully');\n return result;\n }\n\n /**\n * Retrieves the version history for a plugin\n *\n * @param pluginId - Plugin ID\n * @returns Promise resolving to an array of plugin versions\n */\n async getPluginVersions(pluginId: number): Promise<PluginVersion[]> {\n log('Getting plugin versions: pluginId=%d', pluginId);\n\n const result = await this.request<PluginVersion[]>(`/admin/plugins/${pluginId}/versions`);\n\n log('Retrieved %d versions', result.length);\n return result;\n }\n\n /**\n * Retrieves a specific plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to the plugin version details\n */\n async getPluginVersion(pluginId: number, versionId: number): Promise<PluginVersion> {\n log('Getting version details: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<PluginVersion>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n );\n log('Version details retrieved');\n return result;\n }\n\n /**\n * Retrieves all localizations for a specific plugin version\n *\n * @param pluginId - Plugin ID or identifier\n * @param versionId - Version ID\n * @returns Promise resolving to an array of plugin version localizations\n */\n async getPluginLocalizations(\n pluginId: number | string,\n versionId: number,\n ): Promise<PluginVersionLocalization[]> {\n log('Getting localizations: pluginId=%s, versionId=%d', pluginId, versionId);\n\n const result = await this.request<PluginVersionLocalization[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/localizations`,\n );\n log('Retrieved %d localizations for plugin %s, version %d', result.length, pluginId, versionId);\n return result;\n }\n\n /**\n * Creates a new plugin version with all version-specific data\n *\n * @param pluginId - Plugin ID\n * @param data - Version creation data including all version-specific fields\n * @returns Promise resolving to the created plugin version\n */\n async createPluginVersion(\n pluginId: number,\n data: PluginVersionCreateParams,\n ): Promise<PluginVersion> {\n log('Creating new plugin version: pluginId=%d, data: %O', pluginId, data);\n\n const result = await this.request<PluginVersion>(`/admin/plugins/${pluginId}/versions`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Plugin version created successfully: version=%s', data.version);\n return result;\n }\n\n /**\n * Creates a new plugin version from a manifest\n * Extracts version data from the manifest for easier creation\n *\n * @param pluginId - Plugin ID\n * @param manifest - Plugin manifest containing all version data\n * @param options - Additional options for version creation\n * @returns Promise resolving to the created plugin version\n */\n async createPluginVersionFromManifest(\n pluginId: number,\n manifest: PluginManifest,\n options: {\n isLatest?: boolean;\n isValidated?: boolean;\n } = {},\n ): Promise<PluginVersion> {\n log(\n 'Creating plugin version from manifest: pluginId=%d, version=%s',\n pluginId,\n manifest.version,\n );\n\n const versionData: PluginVersionCreateParams = {\n author: manifest.author?.name,\n authorUrl: manifest.author?.url,\n capabilitiesPrompts: manifest.capabilities?.prompts,\n capabilitiesResources: manifest.capabilities?.resources,\n capabilitiesTools: manifest.capabilities?.tools,\n category: manifest.category,\n description: manifest.description,\n icon: manifest.icon,\n isLatest: options.isLatest,\n isValidated: options.isValidated,\n name: manifest.name,\n prompts: manifest.prompts,\n readme: manifest.overview?.readme,\n resources: manifest.resources,\n summary: manifest.overview?.summary,\n tags: manifest.tags,\n tools: manifest.tools,\n version: manifest.version,\n };\n\n return this.createPluginVersion(pluginId, versionData);\n }\n\n /**\n * Updates a plugin version with comprehensive version-specific data\n *\n * @param idOrIdentifier - Plugin ID\n * @param versionId - Version ID\n * @param data - Version update data including all version-specific fields\n * @returns Promise resolving to the updated plugin version\n */\n async updatePluginVersion(\n idOrIdentifier: number | string,\n versionId: number,\n data: PluginVersionUpdateParams,\n ): Promise<PluginVersion> {\n log(\n 'Updating plugin version: pluginId=%d, versionId=%d, data: %O',\n idOrIdentifier,\n versionId,\n data,\n );\n\n const result = await this.request<PluginVersion>(\n `/admin/plugins/${idOrIdentifier}/versions/${versionId}`,\n {\n body: JSON.stringify(data),\n method: 'PUT',\n },\n );\n\n log('Plugin version updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to success response\n */\n async deletePluginVersion(\n pluginId: number,\n versionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log('Deleting version: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n { method: 'DELETE' },\n );\n log('Plugin version deleted successfully');\n return result;\n }\n\n /**\n * Sets a specific version as the latest version of a plugin\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID to set as latest\n * @returns Promise resolving to success response\n */\n async setPluginVersionAsLatest(\n pluginId: number,\n versionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log('Setting version as latest: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}/latest`,\n { method: 'POST' },\n );\n log('Version set as latest successfully');\n return result;\n }\n\n /**\n * Updates plugin visibility\n *\n * @param id - Plugin ID\n * @param visibility - New visibility setting\n * @returns Promise resolving to success response\n */\n async updatePluginVisibility(\n id: number,\n visibility: 'public' | 'private' | 'unlisted',\n ): Promise<{ message: string; success: boolean }> {\n log('Updating plugin visibility: %d to %s', id, visibility);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${id}/visibility`,\n {\n body: JSON.stringify({ visibility }),\n method: 'PATCH',\n },\n );\n log('Plugin visibility updated successfully');\n return result;\n }\n\n /**\n * Updates status for multiple plugins in a single operation\n *\n * @param ids - Array of plugin IDs to update\n * @param status - New status to set for all specified plugins\n * @returns Promise resolving to success response\n */\n async batchUpdatePluginStatus(\n ids: number[],\n status: 'published' | 'draft' | 'review' | 'rejected',\n ): Promise<{ message: string; success: boolean }> {\n log('Batch updating plugin status: %O to %s', ids, status);\n\n const result = await this.request<{ message: string; success: boolean }>(\n '/admin/plugins/batch/status',\n {\n body: JSON.stringify({ ids, status }),\n method: 'PATCH',\n },\n );\n log('Batch plugin status update completed');\n return result;\n }\n\n /**\n * Deletes multiple plugins in a single operation\n *\n * @param ids - Array of plugin IDs to delete\n * @returns Promise resolving to success response\n */\n async batchDeletePlugins(ids: number[]): Promise<{ message: string; success: boolean }> {\n log('Batch deleting plugins: %O', ids);\n\n const result = await this.request<{ message: string; success: boolean }>(\n '/admin/plugins/batch/delete',\n {\n body: JSON.stringify({ ids }),\n method: 'DELETE',\n },\n );\n log('Batch plugin deletion completed');\n return result;\n }\n\n /**\n * Retrieves detailed information about a plugin version including deployment options\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to version details with deployment options\n */\n async getPluginVersionDetails(\n pluginId: number,\n versionId: number,\n ): Promise<PluginVersion & { deploymentOptions: any }> {\n log(\n 'Getting version details with deployment options: pluginId=%d, versionId=%d',\n pluginId,\n versionId,\n );\n\n const result = await this.request<PluginVersion & { deploymentOptions: any }>(\n `/admin/plugins/${pluginId}/versions/${versionId}`,\n );\n log('Version details with deployment options retrieved');\n return result;\n }\n\n /**\n * Retrieves deployment options for a specific plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @returns Promise resolving to an array of deployment options\n */\n async getDeploymentOptions(\n pluginId: number,\n versionId: number,\n ): Promise<AdminDeploymentOption[]> {\n log('Getting deployment options: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<AdminDeploymentOption[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options`,\n );\n log('Retrieved %d deployment options', result.length);\n return result;\n }\n\n /**\n * Creates a new deployment option for a plugin version\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param data - Deployment option configuration data\n * @returns Promise resolving to the created deployment option\n */\n async createDeploymentOption(\n pluginId: number,\n versionId: number,\n data: {\n connectionArgs?: string[];\n connectionCommand?: string;\n connectionType: string;\n description?: string;\n installationDetails?: InstallationDetails;\n installationMethod: string;\n isRecommended?: boolean;\n },\n ): Promise<AdminDeploymentOption> {\n log('Creating deployment option: pluginId=%d, versionId=%d', pluginId, versionId);\n\n const result = await this.request<AdminDeploymentOption>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options`,\n {\n body: JSON.stringify(data),\n method: 'POST',\n },\n );\n log('Deployment option created successfully');\n return result;\n }\n\n /**\n * Updates an existing deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @param data - Updated deployment option configuration\n * @returns Promise resolving to the updated deployment option\n */\n async updateDeploymentOption(\n pluginId: number,\n versionId: number,\n optionId: number,\n data: {\n connectionArgs?: string[];\n connectionCommand?: string;\n connectionType?: string;\n description?: string;\n installationDetails?: Record<string, any>;\n installationMethod?: string;\n isRecommended?: boolean;\n },\n ): Promise<AdminDeploymentOption> {\n log(\n 'Updating deployment option: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<AdminDeploymentOption>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}`,\n {\n body: JSON.stringify(data),\n method: 'PUT',\n },\n );\n log('Deployment option updated successfully');\n return result;\n }\n\n /**\n * Deletes a deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @returns Promise resolving to success response\n */\n async deleteDeploymentOption(\n pluginId: number,\n versionId: number,\n optionId: number,\n ): Promise<{ message: string; success: boolean }> {\n log(\n 'Deleting deployment option: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}`,\n { method: 'DELETE' },\n );\n log('Deployment option deleted successfully');\n return result;\n }\n\n /**\n * Retrieves system dependencies for a deployment option\n *\n * @param pluginId - Plugin ID\n * @param versionId - Version ID\n * @param optionId - Deployment option ID\n * @returns Promise resolving to an array of system dependencies\n */\n async getDeploymentOptionSystemDependencies(\n pluginId: number,\n versionId: number,\n optionId: number,\n ): Promise<SystemDependency[]> {\n log(\n 'Getting system dependencies: pluginId=%d, versionId=%d, optionId=%d',\n pluginId,\n versionId,\n optionId,\n );\n\n const result = await this.request<SystemDependency[]>(\n `/admin/plugins/${pluginId}/versions/${versionId}/deployment-options/${optionId}/system-dependencies`,\n );\n log('Retrieved %d system dependencies', result.length);\n return result;\n }\n\n /**\n * Retrieves verified plugins without summary information\n *\n * Returns plugins that are validated but missing summary data.\n *\n * @returns Promise resolving to array of plugins with incomplete summary data\n */\n async getVerifiedPluginsWithoutSummary(): Promise<\n { identifier: string; manifest: PluginManifest; versionId: number }[]\n > {\n log('Getting verified plugins without summary');\n\n const result = await this.request<\n { identifier: string; manifest: PluginManifest; versionId: number }[]\n >('/admin/plugins/verified-without-summary');\n\n log('Retrieved %d verified plugins without summary', result.length);\n return result;\n }\n\n /**\n * Retrieves plugins with incomplete internationalization\n *\n * Returns plugins where pluginVersionLocalizations has only 1 entry.\n *\n * @returns Promise resolving to an array of plugins with incomplete i18n\n */\n async getIncompleteI18nPlugins(): Promise<IncompleteI18nPlugin[]> {\n log('Getting plugins with incomplete i18n');\n\n const result = await this.request<IncompleteI18nPlugin[]>('/admin/plugins/incomplete-i18n');\n log('Retrieved %d plugins with incomplete i18n', result.length);\n return result;\n }\n\n /**\n * Retrieves unclaimed plugins\n *\n * Returns plugins where isClaimed is false, containing only ID and identifier.\n *\n * @returns Promise resolving to an array of unclaimed plugins with basic info\n */\n async getUnclaimedPlugins(): Promise<UnclaimedPluginItem[]> {\n log('Getting unclaimed plugins');\n\n const result = await this.request<UnclaimedPluginItem[]>('/admin/plugins/unclaimed');\n log('Retrieved %d unclaimed plugins', result.length);\n return result;\n }\n}\n","import type { SystemDependency } from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:dependency');\n\n/**\n * System Dependency Management Service\n *\n * Provides administrative functionality for managing system dependencies\n * required by plugins. This service handles creating, updating, deleting,\n * and listing system dependencies that plugins may require.\n */\nexport class SystemDependencyService extends BaseSDK {\n /**\n * Retrieves all system dependencies\n *\n * Gets a list of all defined system dependencies that plugins may require.\n *\n * @returns Promise resolving to an array of system dependencies\n */\n async getSystemDependencies(): Promise<SystemDependency[]> {\n log('Getting all system dependencies');\n\n const result = await this.request<SystemDependency[]>(`/admin/plugins/dependencies`);\n log('Retrieved %d system dependencies', result.length);\n return result;\n }\n\n /**\n * Retrieves a specific system dependency by ID\n *\n * @param id - System dependency ID\n * @returns Promise resolving to the system dependency details\n */\n async getSystemDependency(id: number): Promise<SystemDependency> {\n log('Getting system dependency details: %d', id);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies/${id}`);\n log('System dependency details retrieved');\n return result;\n }\n\n /**\n * Creates a new system dependency\n *\n * @param data - System dependency creation data\n * @returns Promise resolving to the created system dependency\n */\n async createSystemDependency(data: Omit<SystemDependency, 'id'>): Promise<SystemDependency> {\n log('Creating system dependency: %O', data);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('System dependency created successfully');\n return result;\n }\n\n /**\n * Updates an existing system dependency\n *\n * @param id - System dependency ID\n * @param data - System dependency update data\n * @returns Promise resolving to the updated system dependency\n */\n async updateSystemDependency(\n id: number,\n data: Partial<SystemDependency>,\n ): Promise<SystemDependency> {\n log('Updating system dependency: %d, data: %O', id, data);\n\n const result = await this.request<SystemDependency>(`/admin/plugins/dependencies/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('System dependency updated successfully');\n return result;\n }\n\n /**\n * Deletes a system dependency\n *\n * @param id - System dependency ID\n * @returns Promise resolving to success response\n */\n async deleteSystemDependency(id: number): Promise<{ message: string; success: boolean }> {\n log('Deleting system dependency: %d', id);\n\n const result = await this.request<{ message: string; success: boolean }>(\n `/admin/plugins/dependencies/${id}`,\n { method: 'DELETE' },\n );\n log('System dependency deleted successfully');\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:settings');\n\n/**\n * Settings entity representing a system setting\n */\nexport interface Settings {\n /** Creation timestamp (ISO 8601 format) */\n createdAt: string;\n /** Optional description of the setting's purpose */\n description?: string;\n /** Unique identifier for the setting */\n id: number;\n /** Setting key name used for retrieving the setting */\n key: string;\n /** Last update timestamp (ISO 8601 format) */\n updatedAt: string;\n /** Setting value (stored as string) */\n value: string;\n}\n\n/**\n * Configuration for enabled resource types\n */\nexport interface EnabledResources {\n /** Whether agent resources are enabled */\n agents: boolean;\n /** Whether plugin resources are enabled */\n plugins: boolean;\n}\n\n/**\n * Authentication configuration\n */\nexport interface AuthenticationConfig {\n /** Whether authentication is required */\n enabled: boolean;\n /** Supported authentication schemes */\n schemes: string[];\n}\n\n/**\n * Documentation URL configuration\n */\nexport interface DocumentationConfig {\n /** URL to API documentation */\n apiUrl?: string;\n /** URL to privacy policy */\n policyUrl?: string;\n /** URL to terms of service */\n termsOfServiceUrl?: string;\n}\n\n/**\n * Map of all system settings with typed properties\n */\nexport interface SettingsMap {\n /** Additional settings (dynamically added) */\n [key: string]: any;\n /** Authentication configuration */\n authentication: AuthenticationConfig;\n /** Base URL for the marketplace */\n baseURL: string;\n /** Documentation URL configuration */\n documentation: DocumentationConfig;\n /** Configuration for enabled resource types */\n enabledResources: EnabledResources;\n /** Supported locales */\n locales: string[];\n}\n\n/**\n * Parameters for creating a new setting\n */\nexport interface CreateSettingsParams {\n /** Optional description of the setting's purpose */\n description?: string;\n /** Setting key name */\n key: string;\n /** Setting value (will be stored as string) */\n value: string;\n}\n\n/**\n * Parameters for updating an existing setting\n */\nexport interface UpdateSettingsParams {\n /** Optional new description */\n description?: string;\n /** New setting value */\n value: string;\n}\n\n/**\n * Settings Management Service\n *\n * Provides administrative functionality for managing system settings.\n * This service handles getting, creating, updating, and deleting\n * configuration settings for the marketplace.\n */\nexport class SettingsService extends BaseSDK {\n /**\n * Retrieves all system settings\n *\n * Returns a consolidated map of all settings with typed values\n * for known setting keys.\n *\n * @returns Promise resolving to the settings map\n */\n async getSettings(): Promise<SettingsMap> {\n return await this.request<SettingsMap>('/admin/settings');\n }\n\n /**\n * Retrieves a specific setting by key\n *\n * @param key - Setting key name\n * @returns Promise resolving to the setting details\n */\n async getSettingByKey(key: string): Promise<{ data: Settings }> {\n log('Getting setting: %s', key);\n\n const result = await this.request<{ data: Settings }>(`/admin/settings/${key}`);\n log('Setting retrieved');\n return result;\n }\n\n /**\n * Creates a new system setting\n *\n * @param data - Setting creation parameters\n * @returns Promise resolving to the created setting\n */\n async createSetting(data: CreateSettingsParams): Promise<{ data: Settings }> {\n log('Creating setting: %O', data);\n\n const result = await this.request<{ data: Settings }>('/admin/settings', {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Setting created successfully');\n return result;\n }\n\n /**\n * Updates an existing setting\n *\n * @param key - Setting key name\n * @param data - Setting update parameters\n * @returns Promise resolving to the updated setting\n */\n async updateSetting(key: string, data: UpdateSettingsParams): Promise<{ data: Settings }> {\n log('Updating setting: %s, data: %O', key, data);\n\n const result = await this.request<{ data: Settings }>(`/admin/settings/${key}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Setting updated successfully');\n return result;\n }\n\n /**\n * Deletes a setting\n *\n * @param key - Setting key name\n * @returns Promise resolving to success message\n */\n async deleteSetting(key: string): Promise<{ message: string }> {\n log('Deleting setting: %s', key);\n\n const result = await this.request<{ message: string }>(`/admin/settings/${key}`, {\n method: 'DELETE',\n });\n log('Setting deleted successfully');\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport type { AdminListQueryParams, AdminListResponse, ReviewStatus } from '@/types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:admin:review');\n\n/**\n * Review entity representing a plugin review\n */\nexport interface Review {\n /** Optional comment providing feedback */\n comment?: string;\n /** Creation timestamp (ISO 8601 format) */\n createdAt: string;\n /** Unique identifier for the review */\n id: number;\n /** ID of the plugin being reviewed */\n pluginId: number;\n /** ID of the reviewer (if available) */\n reviewerId?: number;\n /** Current status of the review */\n status: ReviewStatus;\n /** Last update timestamp (ISO 8601 format) */\n updatedAt: string;\n}\n\n/**\n * Extended review information with related entities\n */\nexport interface PluginReviewWithRelations extends Review {\n /** Related plugin information */\n plugin?: any;\n /** Related version information */\n version?: any;\n}\n\n/**\n * Parameters for updating a review\n */\nexport interface UpdateReviewParams {\n /** Optional comment or feedback */\n comment?: string;\n /** New status to set for the review */\n status: ReviewStatus;\n}\n\n/**\n * Review Management Service\n *\n * Provides administrative functionality for managing plugin reviews.\n * This service handles listing, fetching, and updating review statuses\n * for plugins in the marketplace.\n */\nexport class ReviewService extends BaseSDK {\n /**\n * Retrieves a list of reviews with filtering options\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the review list response\n */\n async getReviews(\n params: AdminListQueryParams = {},\n ): Promise<AdminListResponse<PluginReviewWithRelations>> {\n log('Getting reviews with params: %O', params);\n\n const queryString = this.buildQueryString(params);\n const url = `/admin/reviews${queryString ? `?${queryString}` : ''}`;\n\n const result = await this.request<AdminListResponse<PluginReviewWithRelations>>(url);\n\n log('Retrieved %d reviews', result.data.length);\n return result;\n }\n\n /**\n * Retrieves a specific review by ID\n *\n * @param id - Review ID\n * @returns Promise resolving to the review details\n */\n async getReviewById(id: number): Promise<Review> {\n log('Getting review details: %d', id);\n\n const result = await this.request<Review>(`/admin/reviews/${id}`);\n log('Review details retrieved');\n return result;\n }\n\n /**\n * Updates a review's status and comment\n *\n * @param id - Review ID\n * @param data - Update parameters containing new status and optional comment\n * @returns Promise resolving to the updated review\n */\n async updateReview(id: number, data: UpdateReviewParams): Promise<Review> {\n log('Updating review: %d, data: %O', id, data);\n\n const result = await this.request<Review>(`/admin/reviews/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Review updated successfully');\n return result;\n }\n\n /**\n * Retrieves the review history for a specific plugin\n *\n * @param pluginId - Plugin ID\n * @returns Promise resolving to an array of reviews for the plugin\n */\n async getPluginReviews(pluginId: number): Promise<{ data: Review[] }> {\n log('Getting plugin reviews: pluginId=%d', pluginId);\n\n const result = await this.request<{ data: Review[] }>(`/admin/reviews/plugin/${pluginId}`);\n log('Retrieved %d reviews for plugin', result.data.length);\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '@/core/BaseSDK';\nimport type { AdminListResponse } from '@/types/admin';\n\ntype AdminPluginEnvListQuery = any;\ntype PluginEnv = any;\n\nconst log = debug('lobe-market-sdk:admin:plugin-env');\n\nexport interface AdminPluginEnvCreateParams {\n description?: string;\n identifier: string;\n key: string;\n value: string;\n}\n\nexport interface AdminPluginEnvUpdateParams {\n description?: string;\n value?: string;\n}\n\n/**\n * Plugin Environment Variable Management Service\n *\n * Provides administrative functionality for managing plugin environment variables.\n */\nexport class PluginEnvService extends BaseSDK {\n /**\n * Retrieves a paginated list of plugin environment variables\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise resolving to the env list response\n */\n async getPluginEnvs(params: AdminPluginEnvListQuery = {}): Promise<AdminListResponse<PluginEnv>> {\n log('Getting plugin envs with params: %O', params);\n const queryString = this.buildQueryString(params);\n const url = `/admin/plugins/env${queryString}`;\n const result = await this.request<AdminListResponse<PluginEnv>>(url);\n log('Retrieved %d plugin envs', result.data.length);\n return result;\n }\n\n /**\n * Retrieves a single plugin environment variable by ID\n *\n * @param id - Env ID\n * @returns Promise resolving to the env item\n */\n async getPluginEnv(id: number): Promise<PluginEnv> {\n log('Getting plugin env: %d', id);\n const result = await this.request<PluginEnv>(`/admin/plugins/env/${id}`);\n log('Retrieved plugin env: %d', id);\n return result;\n }\n\n /**\n * Creates a new plugin environment variable\n *\n * @param data - Env creation data\n * @returns Promise resolving to the created env item\n */\n async createPluginEnv(data: AdminPluginEnvCreateParams): Promise<PluginEnv> {\n log('Creating plugin env: %O', data);\n const result = await this.request<PluginEnv>(`/admin/plugins/env`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Plugin env created successfully');\n return result;\n }\n\n /**\n * Updates a plugin environment variable\n *\n * @param id - Env ID\n * @param data - Env update data\n * @returns Promise resolving to the updated env item\n */\n async updatePluginEnv(id: number, data: AdminPluginEnvUpdateParams): Promise<PluginEnv> {\n log('Updating plugin env: %d, data: %O', id, data);\n const result = await this.request<PluginEnv>(`/admin/plugins/env/${id}`, {\n body: JSON.stringify(data),\n method: 'PUT',\n });\n log('Plugin env updated successfully');\n return result;\n }\n\n /**\n * Deletes a plugin environment variable\n *\n * @param id - Env ID\n * @returns Promise resolving to success response\n */\n async deletePluginEnv(id: number): Promise<{ success: boolean }> {\n log('Deleting plugin env: %d', id);\n const result = await this.request<{ success: boolean }>(`/admin/plugins/env/${id}`, {\n method: 'DELETE',\n });\n log('Plugin env deleted successfully');\n return result;\n }\n\n /**\n * Batch import plugin environment variables\n *\n * @param data - Batch import data, format: { [plugin: string]: { [envKey: string]: string } }\n * @returns Promise resolving to import result\n */\n async importPluginEnvs(\n data: Record<string, Record<string, string>>,\n ): Promise<{ success: number }> {\n log('Batch importing plugin envs: %O', data);\n const result = await this.request<{ success: number }>(`/admin/plugins/env/import`, {\n body: JSON.stringify(data),\n method: 'POST',\n });\n log('Batch import completed: %d envs imported', result.success);\n return result;\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '../core/BaseSDK';\nimport type {\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n DiscoveryDocument,\n MarketSDKOptions,\n} from '../types';\nimport { AgentService, AuthService, DiscoveryService, PluginsService } from './services';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk');\n\n/**\n * LobeHub Market SDK Client\n *\n * Main client for accessing the LobeHub Marketplace API.\n * This class provides access to marketplace resources like plugins, agents,\n * and service discovery information. It follows a composition pattern\n * by combining specialized domain services.\n */\nexport class MarketSDK extends BaseSDK {\n /**\n * Agents service for accessing agent-related functionality\n * Provides methods to list, search, retrieve agent information, and upload agents\n */\n readonly agents: AgentService;\n\n /**\n * Auth service for authentication and authorization\n * Provides methods for OIDC user authentication, client registration, and M2M token management\n */\n readonly auth: AuthService;\n\n /**\n * Plugins service for accessing plugin-related functionality\n * Provides methods to list, search, retrieve plugin information, and report installation attempts\n */\n readonly plugins: PluginsService;\n\n /**\n * Discovery service for retrieving API service information\n * Used to get information about available endpoints and services\n */\n private readonly discovery: DiscoveryService;\n\n /**\n * Creates a new MarketSDK instance\n *\n * @param options - Configuration options for the SDK\n */\n constructor(options: MarketSDKOptions = {}) {\n // Create shared token state object for all services\n const sharedTokenState = {\n accessToken: undefined,\n tokenExpiry: undefined,\n };\n\n super(options, undefined, sharedTokenState);\n log('MarketSDK instance created');\n\n // Initialize domain services with shared headers and token state for efficient reuse\n this.agents = new AgentService(options, this.headers, sharedTokenState);\n this.auth = new AuthService(options, this.headers, sharedTokenState);\n this.plugins = new PluginsService(options, this.headers, sharedTokenState);\n this.discovery = new DiscoveryService(options, this.headers, sharedTokenState);\n }\n\n /**\n * Retrieves the service discovery document\n *\n * The discovery document provides information about available API endpoints,\n * versions, and capabilities of the Market API.\n *\n * @returns Promise resolving to the service discovery document\n */\n async getDiscoveryDocument(): Promise<DiscoveryDocument> {\n return this.discovery.getDiscoveryDocument();\n }\n\n /**\n * Registers a new client for M2M authentication\n *\n * This method registers a client application with the Market API and returns\n * unique credentials (client_id and client_secret) that can be used for M2M authentication.\n * These credentials should be stored securely and used to initialize the SDK.\n *\n * @param request - Client registration request data\n * @returns Promise resolving to the client registration response with credentials\n * @throws Error if registration fails\n * @deprecated Use auth.registerClient() instead\n */\n async registerClient(request: ClientRegistrationRequest): Promise<ClientRegistrationResponse> {\n log('Registering client (deprecated method, use auth.registerClient): %s', request.clientName);\n return this.auth.registerClient(request);\n }\n}\n","import debug from 'debug';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n AgentCreateRequest,\n AgentCreateResponse,\n AgentDetailQuery,\n AgentItemDetail,\n AgentListQuery,\n AgentListResponse,\n AgentModifyRequest,\n AgentModifyResponse,\n AgentUploadRequest,\n AgentUploadResponse,\n AgentVersionCreateRequest,\n AgentVersionCreateResponse,\n AgentVersionModifyRequest,\n AgentVersionModifyResponse,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:agents');\n\n/**\n * Agents Service\n *\n * Provides access to agent-related functionality in the LobeHub Marketplace.\n * This service handles listing, searching, and retrieving detailed information\n * about agents available in the marketplace.\n */\nexport class AgentService extends BaseSDK {\n /**\n * Retrieves a list of agents from the marketplace\n *\n * Supports filtering, pagination, and localization of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @param options - Optional request options\n * @returns Promise resolving to the agent list response containing items and pagination info\n */\n async getAgentList(\n params: AgentListQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<AgentListResponse> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent list: %O', queryParams);\n\n const result = await this.request<AgentListResponse>(`/v1/agents${queryString}`, options);\n log('Retrieved %d agents', result.items.length);\n return result;\n }\n\n /**\n * Retrieves detailed information about a specific agent\n *\n * Returns complete agent information including A2A AgentCard data,\n * configuration, skills, and localized content.\n *\n * @param id - Unique identifier of the agent\n * @param params - Query parameters for locale and version\n * @param options - Optional request options\n * @returns Promise resolving to the agent detail information\n */\n async getAgentDetail(\n id: string,\n params: AgentDetailQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<AgentItemDetail> {\n const locale = params.locale || this.defaultLocale;\n const queryParams: Record<string, string> = { locale };\n if (params.version !== undefined) {\n queryParams.version = params.version.toString();\n }\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent detail: %O', { id, ...params });\n\n const result = await this.request<AgentItemDetail>(\n `/v1/agents/detail/${id}${queryString}`,\n options,\n );\n\n log('Agent detail successfully retrieved: %s', id);\n return result;\n }\n\n /**\n * Retrieves all published agent identifiers\n *\n * Returns a lightweight list of all published agent identifiers without\n * full agent metadata. This is useful for clients that need to know which\n * agents are available without fetching complete agent information.\n *\n * @param options - Optional request options\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(\n options?: globalThis.RequestInit,\n ): Promise<{ id: string; lastModified: string }[]> {\n log('Getting published agent identifiers');\n\n const result = await this.request<{ id: string; lastModified: string }[]>(\n '/v1/agents/identifiers',\n options,\n );\n log('Retrieved %d published agent identifiers', result.length);\n return result;\n }\n\n /**\n * Retrieves agent categories and their counts\n *\n * Returns a list of categories along with the number of agents in each category.\n * Useful for building category filters in a UI. Supports optional search filtering\n * via 'q' parameter and locale specification.\n *\n * @param params - Query parameters for filtering categories\n * @param options - Optional request options\n * @returns Promise resolving to an array of category items with counts\n */\n async getCategories(\n params: { locale?: string; q?: string } = {},\n options?: globalThis.RequestInit,\n ): Promise<{ category: string; count: number }[]> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting agent categories: %O', queryParams);\n\n const result = await this.request<{ category: string; count: number }[]>(\n `/v1/agents/categories${queryString}`,\n options,\n );\n log('Retrieved %d categories', result.length);\n return result;\n }\n\n /**\n * Uploads an agent to the marketplace\n *\n * Allows users to upload new agents or update existing ones.\n * The agent data should conform to the A2A AgentCard specification.\n *\n * @param agentData - The agent data to upload\n * @param options - Optional request options\n * @returns Promise resolving to the upload response\n */\n async uploadAgent(\n agentData: AgentUploadRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentUploadResponse> {\n log('Uploading agent: %s@%s', agentData.agentIdentifier, agentData.version.version);\n\n const result = await this.request<AgentUploadResponse>('/v1/agents/upload', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent uploaded successfully: %O', result);\n return result;\n }\n\n /**\n * Creates a new agent in the marketplace\n *\n * @param agentData - The agent data to create\n * @param options - Optional request options\n * @returns Promise resolving to the created agent response\n */\n async createAgent(\n agentData: AgentCreateRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentCreateResponse> {\n log('Creating agent: %s', agentData.identifier);\n\n const result = await this.request<AgentCreateResponse>('/v1/agents/create', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent created successfully: %O', result);\n return result;\n }\n\n /**\n * Creates a new version for an existing agent\n *\n * @param versionData - The version data to create\n * @param options - Optional request options\n * @returns Promise resolving to the created version response\n */\n async createAgentVersion(\n versionData: AgentVersionCreateRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentVersionCreateResponse> {\n log('Creating agent version: %s', versionData.identifier);\n\n const result = await this.request<AgentVersionCreateResponse>('/v1/agents/version/create', {\n body: JSON.stringify(versionData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent version created successfully: %O', result);\n return result;\n }\n\n /**\n * Modifies an existing agent\n *\n * @param agentData - The agent data to modify\n * @param options - Optional request options\n * @returns Promise resolving to the modified agent response\n */\n async modifyAgent(\n agentData: AgentModifyRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentModifyResponse> {\n log('Modifying agent: %s', agentData.identifier);\n\n const result = await this.request<AgentModifyResponse>('/v1/agents/modify', {\n body: JSON.stringify(agentData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent modified successfully: %O', result);\n return result;\n }\n\n /**\n * Modifies a specific version of an existing agent\n *\n * @param versionData - The version data to modify\n * @param options - Optional request options\n * @returns Promise resolving to the modified version response\n */\n async modifyAgentVersion(\n versionData: AgentVersionModifyRequest,\n options?: globalThis.RequestInit,\n ): Promise<AgentVersionModifyResponse> {\n log('Modifying agent version: %s@%s', versionData.identifier, versionData.version);\n\n const result = await this.request<AgentVersionModifyResponse>('/v1/agents/version/modify', {\n body: JSON.stringify(versionData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Agent version modified successfully: %O', result);\n return result;\n }\n\n /**\n * Checks if an agent exists in the marketplace\n *\n * @param identifier - Unique identifier of the agent\n * @param options - Optional request options\n * @returns Promise resolving to true if agent exists, false otherwise\n */\n async checkAgentExists(identifier: string, options?: globalThis.RequestInit): Promise<boolean> {\n log('Checking if agent exists: %s', identifier);\n\n try {\n await this.getAgentDetail(identifier, {}, options);\n log('Agent exists: %s', identifier);\n return true;\n } catch {\n log('Agent does not exist: %s', identifier);\n return false;\n }\n }\n}\n","import debug from 'debug';\nimport urlJoin from 'url-join';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n AuthorizationCodeTokenRequest,\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n OAuthTokenResponse,\n RefreshTokenRequest,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:auth');\n\n/**\n * Auth Service\n *\n * Provides authentication and authorization functionality for the LobeHub Marketplace.\n * This service handles OIDC user authentication, client registration, and M2M token management.\n */\nexport class AuthService extends BaseSDK {\n // ===== OAuth Handoff Types =====\n /** Successful handoff payload */\n private static readonly HANDOFF_SUCCESS_STATUS = 'success' as const;\n /** Pending handoff status */\n private static readonly HANDOFF_PENDING_STATUS = 'pending' as const;\n /** Consumed handoff status */\n private static readonly HANDOFF_CONSUMED_STATUS = 'consumed' as const;\n /** Expired handoff status */\n private static readonly HANDOFF_EXPIRED_STATUS = 'expired' as const;\n\n /** Normalize token response from snake_case to camelCase fields */\n private static normalizeTokenResponse(data: any): OAuthTokenResponse {\n if (!data?.access_token || !data?.token_type) {\n throw new Error('Invalid token response payload');\n }\n\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n idToken: data.id_token,\n refreshToken: data.refresh_token,\n scope: data.scope,\n tokenType: data.token_type,\n };\n }\n\n /**\n * Exchanges an authorization code or refresh token for access credentials\n *\n * Supports both the authorization_code and refresh_token grant types.\n * The method normalizes the response to camelCase field names.\n *\n * @param request - Token exchange parameters\n * @param options - Optional fetch options (e.g., custom headers)\n * @returns Promise resolving to the OAuth token payload\n */\n async exchangeOAuthToken(\n request: AuthorizationCodeTokenRequest | RefreshTokenRequest,\n options?: globalThis.RequestInit,\n ): Promise<OAuthTokenResponse> {\n const grantType = request.grantType ?? 'authorization_code';\n\n if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {\n throw new Error(`Unsupported grant type: ${grantType}`);\n }\n\n log('Exchanging OAuth token using grant_type=%s', grantType);\n\n const tokenUrl = urlJoin(this.baseUrl, 'lobehub-oidc/token');\n const params = new URLSearchParams();\n params.set('grant_type', grantType);\n\n if (grantType === 'authorization_code') {\n const { clientId, code, codeVerifier, redirectUri } =\n request as AuthorizationCodeTokenRequest;\n\n if (!clientId || !code || !codeVerifier || !redirectUri) {\n throw new Error(\n 'clientId, code, codeVerifier, and redirectUri are required for authorization_code',\n );\n }\n\n params.set('client_id', clientId);\n params.set('code', code);\n params.set('code_verifier', codeVerifier);\n params.set('redirect_uri', redirectUri);\n } else {\n const { refreshToken, clientId } = request as RefreshTokenRequest;\n\n if (!refreshToken) {\n throw new Error('refreshToken is required for refresh_token grant');\n }\n\n params.set('refresh_token', refreshToken);\n if (clientId) params.set('client_id', clientId);\n }\n\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n if (options?.headers) {\n new Headers(options.headers).forEach((value, key) => {\n headers.set(key, value);\n });\n }\n\n const requestInit: globalThis.RequestInit = {\n ...options,\n body: params,\n headers,\n method: 'POST',\n };\n\n const response = await fetch(tokenUrl, requestInit);\n\n let payload: any;\n try {\n payload = await response.json();\n } catch (error) {\n log('Failed to parse token response: %O', error);\n throw new Error(`Failed to parse token response: ${response.status} ${response.statusText}`);\n }\n\n if (!response.ok) {\n const errorDescription = payload?.error_description || payload?.error || response.statusText;\n const errorMsg = `Token exchange failed: ${response.status} ${errorDescription}`;\n log('Error: %s', errorMsg);\n throw new Error(errorMsg);\n }\n\n log('Token exchange successful');\n return AuthService.normalizeTokenResponse(payload);\n }\n\n /**\n * Retrieves user information from the OIDC userinfo endpoint\n *\n * Requires a valid access token in the Authorization header.\n *\n * @param accessToken - The access token to use for authentication\n * @param options - Optional request options\n * @returns Promise resolving to the user information\n */\n async getUserInfo(\n accessToken: string,\n options?: globalThis.RequestInit,\n ): Promise<{\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n sub: string;\n }> {\n log('Getting user info');\n\n const userInfoUrl = urlJoin(this.baseUrl, 'lobehub-oidc/userinfo');\n\n const response = await fetch(userInfoUrl, {\n headers: {\n 'Authorization': `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n ...options,\n });\n\n if (!response.ok) {\n const errorMsg = `Failed to fetch user info: ${response.status} ${response.statusText}`;\n log('Error: %s', errorMsg);\n throw new Error(errorMsg);\n }\n\n const userInfo = await response.json();\n log('User info retrieved successfully');\n return userInfo;\n }\n\n /**\n * Registers a new OAuth client with the marketplace\n *\n * This is typically used for device registration or application setup.\n * Returns client credentials that can be used for M2M authentication.\n *\n * @param clientData - The client registration data\n * @param options - Optional request options\n * @returns Promise resolving to the client credentials\n */\n async registerClient(\n clientData: ClientRegistrationRequest,\n options?: globalThis.RequestInit,\n ): Promise<ClientRegistrationResponse> {\n log('Registering client: %s (%s)', clientData.clientName, clientData.clientType);\n\n const result = await this.request<ClientRegistrationResponse>('/v1/clients/register', {\n body: JSON.stringify(clientData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n ...options,\n });\n\n log('Client registered successfully: %s', result.client_id);\n return result;\n }\n\n /**\n * Fetches an M2M (Machine-to-Machine) access token\n *\n * Uses client credentials to obtain an access token for server-to-server communication.\n * This method requires clientId and clientSecret to be set in the SDK options.\n *\n * @returns Promise resolving to the access token and expiration time\n */\n async getM2MToken(): Promise<{\n accessToken: string;\n expiresIn: number;\n }> {\n log('Fetching M2M token');\n\n const tokenInfo = await this.fetchM2MToken();\n\n log('M2M token fetched successfully');\n return tokenInfo;\n }\n\n /** OAuth handoff response shapes */\n // Using inline type aliases inside the class for better encapsulation\n // success: 200\n private static typeHandoffSuccess(data: { clientId: string; code: string; redirectUri: string }) {\n return {\n clientId: data.clientId,\n code: data.code,\n redirectUri: data.redirectUri,\n status: AuthService.HANDOFF_SUCCESS_STATUS,\n } as const;\n }\n\n /**\n * Get OAuth handoff status and data by id.\n * Maps server HTTP statuses to a typed status union:\n * - 200: success\n * - 202: pending\n * - 404: consumed\n * - 410: expired\n * - others: error (throws)\n */\n async getOAuthHandoff(\n id: string,\n options?: globalThis.RequestInit,\n ): Promise<\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'pending' }\n | { status: 'consumed' }\n | { status: 'expired' }\n > {\n if (!id) throw new Error('id is required');\n\n log('Getting OAuth handoff: %s', id);\n\n const handoffUrl = `${urlJoin(this.baseUrl, 'lobehub-oidc/handoff')}?id=${encodeURIComponent(id)}`;\n const response = await fetch(handoffUrl, {\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n ...options,\n });\n\n // Map known statuses\n if (response.status === 200) {\n const json = await response.json();\n const result = AuthService.typeHandoffSuccess({\n clientId: json.clientId,\n code: json.code,\n redirectUri: json.redirectUri,\n });\n log('OAuth handoff success for id: %s', id);\n return result;\n }\n if (response.status === 202) {\n log('OAuth handoff pending for id: %s', id);\n return { status: AuthService.HANDOFF_PENDING_STATUS };\n }\n if (response.status === 404) {\n log('OAuth handoff consumed for id: %s', id);\n return { status: AuthService.HANDOFF_CONSUMED_STATUS };\n }\n if (response.status === 410) {\n log('OAuth handoff expired for id: %s', id);\n return { status: AuthService.HANDOFF_EXPIRED_STATUS };\n }\n\n // Attempt to parse error for diagnostics\n let errorMessage = `Failed to fetch OAuth handoff (status ${response.status} ${response.statusText})`;\n try {\n const errJson = await response.json();\n if (errJson && (errJson.message || errJson.error)) {\n errorMessage = `${errorMessage}: ${errJson.error ?? ''} ${errJson.message ?? ''}`.trim();\n }\n } catch {\n // ignore json parse error\n }\n log('Error: %s', errorMessage);\n throw new Error(errorMessage);\n }\n\n /**\n * Poll OAuth handoff result until it becomes terminal.\n * Terminal statuses: success, expired, consumed.\n * Non-terminal: pending → continue polling.\n */\n async pollOAuthHandoff(\n id: string,\n params: {\n intervalMs?: number;\n requestInit?: globalThis.RequestInit;\n signal?: AbortSignal;\n timeoutMs?: number;\n } = {},\n ): Promise<\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'expired' }\n | { status: 'consumed' }\n > {\n const intervalMs = params.intervalMs ?? 1500;\n const timeoutMs = params.timeoutMs ?? 60_000;\n const startedAt = Date.now();\n const { signal, requestInit } = params;\n\n log('Start polling OAuth handoff: %s', id);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (signal?.aborted) {\n const err = new Error('Polling aborted');\n log('Error: %s', err.message);\n throw err;\n }\n if (Date.now() - startedAt > timeoutMs) {\n const err = new Error('Polling timeout');\n log('Error: %s', err.message);\n throw err;\n }\n\n const result = await this.getOAuthHandoff(id, requestInit);\n\n if (\n result.status === 'success' ||\n result.status === 'expired' ||\n result.status === 'consumed'\n ) {\n log('Stop polling OAuth handoff (terminal): %s -> %s', id, result.status);\n return result as\n | { clientId: string; code: string; redirectUri: string; status: 'success' }\n | { status: 'expired' }\n | { status: 'consumed' };\n }\n\n // pending → wait and retry\n await new Promise<void>((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n }\n }\n}\n","import debug from 'debug';\nimport urlJoin from 'url-join';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type { DiscoveryDocument } from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:discovery');\n\n/**\n * Discovery Service\n *\n * Provides functionality for retrieving service discovery information\n * from the LobeHub Marketplace API. The discovery document contains\n * metadata about available endpoints, authentication methods, and\n * other capabilities of the API.\n */\nexport class DiscoveryService extends BaseSDK {\n /** Cached discovery document to avoid repeated requests */\n private discoveryDoc?: DiscoveryDocument;\n\n /**\n * Retrieves the service discovery document\n *\n * This document contains information about available API endpoints,\n * authentication methods, and other capabilities of the Market API.\n * The result is cached after the first request to improve performance.\n *\n * @returns Promise resolving to the service discovery document\n */\n async getDiscoveryDocument(): Promise<DiscoveryDocument> {\n log('Fetching discovery document');\n if (this.discoveryDoc) {\n log('Returning cached discovery document');\n return this.discoveryDoc;\n }\n\n const res = await fetch(urlJoin(this.baseUrl, '/.well-known/discovery'));\n if (!res.ok) {\n throw new Error(await res.text());\n }\n\n this.discoveryDoc = (await res.json()) as DiscoveryDocument;\n log('Discovery document successfully fetched');\n return this.discoveryDoc;\n }\n}\n","import type {\n CallReportRequest,\n CallReportResponse,\n InstallReportRequest,\n InstallReportResponse,\n PluginItemDetail,\n PluginManifest,\n} from '@lobehub/market-types';\nimport debug from 'debug';\n\nimport { BaseSDK } from '../../core/BaseSDK';\nimport type {\n CategoryItem,\n CategoryListQuery,\n PluginListResponse,\n PluginQueryParams,\n} from '../../types';\n\n// Create debug instance for logging\nconst log = debug('lobe-market-sdk:plugins');\n\n/**\n * Plugins Service\n *\n * Provides access to plugin-related functionality in the LobeHub Marketplace.\n * This service handles listing, searching, and retrieving detailed information\n * about plugins available in the marketplace.\n */\nexport class PluginsService extends BaseSDK {\n /**\n * Retrieves a list of plugins from the marketplace\n *\n * Supports filtering, pagination, and localization of results.\n *\n * @param params - Query parameters for filtering and pagination\n * @param options\n * @returns Promise resolving to the plugin list response containing items and pagination info\n */\n async getPluginList(\n params: PluginQueryParams = {},\n options?: globalThis.RequestInit,\n ): Promise<PluginListResponse> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting plugin list: %O', queryParams);\n\n const result = await this.request<PluginListResponse>(`/v1/plugins${queryString}`, options);\n log('Retrieved %d plugins', result.items.length);\n return result;\n }\n\n /**\n * Retrieves all plugin categories and their counts\n *\n * Returns a list of categories along with the number of plugins in each category.\n * Useful for building category filters in a UI. Supports optional search filtering\n * via 'q' parameter and locale specification.\n *\n * @param params - Query parameters for filtering categories\n * @param options - Optional request options\n * @returns Promise resolving to an array of category items with counts\n */\n async getCategories(\n params: CategoryListQuery = {},\n options?: globalThis.RequestInit,\n ): Promise<CategoryItem[]> {\n const locale = params.locale || this.defaultLocale;\n const queryParams = { ...params, locale };\n const queryString = this.buildQueryString(queryParams);\n\n log('Getting plugin categories: %O', queryParams);\n\n const result = await this.request<CategoryItem[]>(\n `/v1/plugins/categories${queryString}`,\n options,\n );\n log('Retrieved %d categories', result.length);\n return result;\n }\n\n /**\n * Retrieves all published plugin identifiers\n *\n * Returns a lightweight list of all published plugin identifiers without\n * full plugin metadata. This is useful for clients that need to know which\n * plugins are available without fetching complete plugin information.\n *\n * @returns Promise resolving to an array containing identifiers array and last modified time\n */\n async getPublishedIdentifiers(\n options?: globalThis.RequestInit,\n ): Promise<{ identifier: string; lastModified: string }[]> {\n log('Getting published plugin identifiers');\n\n const result = await this.request<{ identifier: string; lastModified: string }[]>(\n '/v1/plugins/identifiers',\n options,\n );\n log('Retrieved %d published plugin identifiers', result.length);\n return result;\n }\n\n /**\n * Retrieves the manifest for a specific plugin\n *\n * The manifest contains detailed information about a plugin, including\n * its capabilities, tools, prompts, and resources.\n *\n * @param identifier - Unique identifier of the plugin\n * @param locale - Optional locale for localized content (defaults to SDK default locale)\n * @param version - Optional specific version to retrieve (defaults to latest)\n * @param options\n * @returns Promise resolving to the plugin manifest\n */\n async getPluginManifest(\n {\n locale,\n version,\n identifier,\n }: {\n identifier: string;\n locale?: string;\n version?: string;\n },\n options?: globalThis.RequestInit,\n ): Promise<PluginManifest> {\n log('Getting plugin manifest: %O', { identifier, locale, version });\n const localeParam = locale || this.defaultLocale;\n const params: Record<string, string> = { locale: localeParam };\n if (version) {\n params.version = version;\n }\n const queryString = this.buildQueryString(params);\n\n const manifest = await this.request<PluginManifest>(\n `/v1/plugins/${identifier}/manifest${queryString}`,\n options,\n );\n\n log('Plugin manifest successfully retrieved: %s', identifier);\n return manifest;\n }\n\n /**\n * Retrieves the plugin detailed information about a plugin, including\n * its capabilities, tools, prompts, and resources.\n *\n * @param identifier - Unique identifier of the plugin\n * @param locale - Optional locale for localized content (defaults to SDK default locale)\n * @param version - Optional specific version to retrieve (defaults to latest)\n * @returns Promise resolving to the plugin manifest\n */\n async getPluginDetail(\n {\n locale,\n version,\n identifier,\n }: {\n identifier: string;\n locale?: string;\n version?: string;\n },\n options?: globalThis.RequestInit,\n ): Promise<PluginItemDetail> {\n log('Getting plugin detail: %O', { identifier, locale, version });\n const localeParam = locale || this.defaultLocale;\n const params: Record<string, string> = { locale: localeParam };\n if (version) {\n params.version = version;\n }\n const queryString = this.buildQueryString(params);\n\n const manifest = await this.request<PluginItemDetail>(\n `/v1/plugins/${identifier}${queryString}`,\n options,\n );\n\n log('Plugin manifest successfully retrieved: %s', identifier);\n return manifest;\n }\n\n /**\n * Report a plugin installation attempt\n *\n * Reports the outcome of a plugin installation attempt, including timing,\n * success status, manifest information, and error details if applicable.\n * This helps improve plugin validation and provides analytics about installation success rates.\n *\n * @param reportData - The installation report data\n * @returns Promise resolving to the report submission response\n *\n */\n async reportInstallation(reportData: InstallReportRequest): Promise<InstallReportResponse> {\n log('Reporting installation for %s@%s', reportData.identifier, reportData.version);\n\n const result = await this.request<InstallReportResponse>('/v1/plugins/report/installation', {\n body: JSON.stringify(reportData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n log('Installation report submitted successfully: %O', result);\n return result;\n }\n\n /**\n * Report a plugin method call attempt\n *\n * Reports the outcome of a plugin method call, including timing,\n * success status, method information, and error details if applicable.\n * This helps improve plugin performance monitoring and provides usage analytics.\n *\n * @param reportData - The call report data\n * @returns Promise resolving to the report submission response\n */\n async reportCall(reportData: CallReportRequest): Promise<CallReportResponse> {\n log(\n 'Reporting call for %s@%s - %s:%s',\n reportData.identifier,\n reportData.version,\n reportData.methodType,\n reportData.methodName,\n );\n\n const result = await this.request<CallReportResponse>('/v1/plugins/report/call', {\n body: JSON.stringify(reportData),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n log('Call report submitted successfully: %O', result);\n return result;\n }\n}\n","import { z } from 'zod';\n\n/**\n * Visibility levels for plugins in the marketplace\n * - public: Visible to all users\n * - private: Visible only to the owner and authorized users\n * - internal: Visible only within the organization\n */\nexport const VisibilityEnumSchema = z.enum(['public', 'private', 'internal']);\n\n/**\n * Publication status options for plugins\n * - published: Publicly available in the marketplace\n * - unpublished: Not publicly visible\n * - archived: Marked as no longer maintained\n * - deprecated: Marked as deprecated, but still available\n */\nexport const StatusEnumSchema = z.enum(['published', 'unpublished', 'archived', 'deprecated']);\n\n/**\n * Common query parameters for admin list endpoints\n * These parameters are used for pagination, filtering, and sorting.\n */\nexport interface AdminListQueryParams {\n /** Current page number (1-based) */\n current?: number;\n /** Search keyword for filtering results */\n keyword?: string;\n /** Number of items per page */\n pageSize?: number;\n /** Field to sort results by */\n sortField?: string;\n /** Sort direction */\n sortOrder?: 'ascend' | 'descend';\n}\n\n/**\n * Common response format for paginated admin list endpoints\n * This structure provides both the data and pagination information.\n */\nexport interface AdminListResponse<T> {\n /** Current page number (1-based) */\n current: number;\n /** Array of items for the current page */\n data: T[];\n /** Number of items per page */\n pageSize: number;\n /** Total number of items across all pages */\n total: number;\n /** Total number of pages */\n totalPages: number;\n}\n\n/**\n * Review status options\n * - pending: Awaiting review\n * - approved: Review approved\n * - rejected: Review rejected\n */\nexport type ReviewStatus = 'pending' | 'approved' | 'rejected';\n\n/**\n * Review status schema for validation\n */\nexport const ReviewStatusEnumSchema = z.enum(['published', 'draft', 'review', 'rejected']);\n\n/**\n * Parameters for admin plugin listing\n * Extends the common query parameters with plugin-specific filters.\n */\nexport interface AdminPluginParams {\n /** Filter for featured plugins */\n featured?: boolean;\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Sort direction */\n order?: 'asc' | 'desc';\n /** Field to sort by */\n orderBy?: 'createdAt' | 'updatedAt' | 'installCount' | 'ratingAverage' | 'githubUpdateAt';\n /** Filter by owner ID */\n ownerId?: number;\n /** Search query string */\n query?: string;\n /** Filter by plugin status */\n status?: 'published' | 'draft' | 'review' | 'rejected';\n /** Filter by visibility level */\n visibility?: 'public' | 'private' | 'unlisted';\n}\n\n/**\n * Parameters for creating a new plugin version\n */\nexport interface PluginVersionCreateParams {\n /** Author or organization name for this version */\n author?: string;\n /** URL to the author's website or profile */\n authorUrl?: string;\n /** Capability flag: whether this plugin provides prompts */\n capabilitiesPrompts?: boolean;\n /** Capability flag: whether this plugin manages resources (MCP) */\n capabilitiesResources?: boolean;\n /** Capability flag: whether this plugin provides tools */\n capabilitiesTools?: boolean;\n /** Category key for the plugin */\n category?: string;\n /** Description of the plugin version */\n description?: string;\n /** Icon URL or emoji for the plugin */\n icon?: string;\n /** Whether this is the latest version */\n isLatest?: boolean;\n /** Whether this version has been validated */\n isValidated?: boolean;\n /** Name of the plugin version */\n name?: string;\n /** Array of prompt definitions */\n prompts?: any[];\n /** README content */\n readme?: string;\n /** Array of resource definitions */\n resources?: any[];\n /** Summary of the plugin version */\n summary?: string;\n /** Array of tags for categorization */\n tags?: string[];\n /** Array of tool definitions */\n tools?: any[];\n /** Semantic version string (e.g., \"1.0.0\") */\n version: string;\n}\n\n/**\n * Parameters for updating an existing plugin version\n */\nexport interface PluginVersionUpdateParams {\n /** Author or organization name for this version */\n author?: string;\n /** URL to the author's website or profile */\n authorUrl?: string;\n /** Capability flag: whether this plugin provides prompts */\n capabilitiesPrompts?: boolean;\n /** Capability flag: whether this plugin manages resources (MCP) */\n capabilitiesResources?: boolean;\n /** Capability flag: whether this plugin provides tools */\n capabilitiesTools?: boolean;\n /** Category key for the plugin */\n category?: string;\n /** Description of the plugin version */\n description?: string;\n /** Icon URL or emoji for the plugin */\n icon?: string;\n /** Whether this version has been validated */\n isValidated?: boolean;\n /** Name of the plugin version */\n name?: string;\n /** Array of prompt definitions */\n prompts?: any[];\n /** README content */\n readme?: string;\n /** Array of resource definitions */\n resources?: any[];\n /** Summary of the plugin version */\n summary?: string;\n /** Array of tags for categorization */\n tags?: string[];\n /** Array of tool definitions */\n tools?: any[];\n}\n\n/**\n * Parameters for updating plugin basic metadata (non-version specific)\n */\nexport interface PluginUpdateParams {\n /** GitHub last update timestamp */\n githubUpdateAt?: string;\n /** Unique identifier for the plugin */\n identifier?: string;\n /** Whether this plugin has been claimed by its original author */\n isClaimed?: boolean;\n /** Whether this plugin is featured */\n isFeatured?: boolean;\n /** Whether this plugin is officially maintained by LobeHub */\n isOfficial?: boolean;\n /** Publication status */\n status?: 'published' | 'draft' | 'review' | 'rejected';\n /** Visibility level */\n visibility?: 'public' | 'private' | 'unlisted';\n}\n\n/**\n * Plugin localization data\n */\nexport interface PluginLocalization {\n /** Plugin description in specific locale */\n description: string;\n /** Locale identifier (e.g., 'en-US', 'zh-CN') */\n locale: string;\n /** Plugin name in specific locale */\n name: string;\n /** Summary in specific locale */\n summary?: string;\n /** Plugin tags in specific locale */\n tags?: string[];\n}\n\n/**\n * Parameters for importing plugin i18n data\n */\nexport interface PluginI18nImportParams {\n /** Plugin identifier */\n identifier: string;\n /** Array of localizations for this plugin version */\n localizations: PluginLocalization[];\n /** Plugin version */\n version: string;\n}\n\n/**\n * Response from plugin i18n import operation\n */\nexport interface PluginI18nImportResponse {\n /** Number of failed localizations */\n failed: number;\n /** Number of successful localizations */\n success: number;\n /** Total number of processed localizations */\n totalLocalizations: number;\n}\n\n/**\n * Unclaimed plugin item data structure\n * Represents a plugin that has not been claimed by its author\n */\nexport interface UnclaimedPluginItem {\n /** Plugin ID */\n id: number;\n /** Plugin identifier */\n identifier: string;\n}\n","/**\n * LobeHub Market JavaScript SDK\n *\n * This is the main entry point for the LobeHub Market SDK.\n * It exports the primary client classes and all type definitions.\n */\n\n// Export admin-related functionality\nexport { MarketAdmin } from './admin';\n\n// Export market-related functionality\nexport { MarketSDK } from './market';\n\n// Export SDK-specific types\nexport * from './types';\n\n// Re-export all type definitions from the types package\nexport * from '@lobehub/market-types';\n"],"mappings":";AAAA,OAAOA,YAAW;;;ACAlB,OAAO,WAAW;AAClB,SAAS,eAAe;AACxB,OAAO,aAAa;AAKpB,IAAM,MAAM,MAAM,sBAAsB;AAajC,IAAM,UAAN,MAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BnB,YACE,UAA4B,CAAC,GAC7B,eACA,kBACA;AAEA,SAAK,UAAU,QAAQ,WAAW,QAAQ,IAAI,mBAAmB;AACjE,SAAK,aAAa,QAAQ,KAAK,SAAS,KAAK;AAC7C,SAAK,eAAe,QAAQ,KAAK,SAAS,OAAO;AAGjD,SAAK,gBAAgB,QAAQ,iBAAiB;AAE9C,SAAK,qBAAqB,QAAQ;AAClC,SAAK,WAAW,QAAQ;AACxB,SAAK,eAAe,QAAQ;AAG5B,SAAK,mBAAmB;AAGxB,UAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;AAG7C,QAAI,eAAe;AACjB,WAAK,UAAU;AACf,UAAI,6BAA6B;AAAA,IACnC,OAAO;AACL,WAAK,UAAU;AAAA,QACb,gBAAgB;AAAA,MAClB;AACA,UAAI,4BAA4B;AAAA,IAClC;AAIA,QAAI,QAAQ;AACV,WAAK,QAAQ,gBAAgB,UAAU,MAAM;AAAA,IAC/C;AAGA,QAAI,KAAK,oBAAoB;AAC3B,WAAK,QAAQ,gBAAgB,UAAU,KAAK,k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ACtE,SAAK,OAAO,IAAI,YAAY,SAAS,KAAK,SAAS,gBAAgB;AACnE,SAAK,UAAU,IAAI,eAAe,SAAS,KAAK,SAAS,gBAAgB;AACzE,SAAK,YAAY,IAAI,iBAAiB,SAAS,KAAK,SAAS,gBAAgB;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,uBAAmD;AACvD,WAAO,KAAK,UAAU,qBAAqB;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,MAAM,eAAe,SAAyE;AAC5F,IAAAA,MAAI,uEAAuE,QAAQ,UAAU;AAC7F,WAAO,KAAK,KAAK,eAAe,OAAO;AAAA,EACzC;AACF;;;AKjGA,SAAS,SAAS;AAQX,IAAM,uBAAuB,EAAE,KAAK,CAAC,UAAU,WAAW,UAAU,CAAC;AASrE,IAAM,mBAAmB,EAAE,KAAK,CAAC,aAAa,eAAe,YAAY,YAAY,CAAC;AA+CtF,IAAM,yBAAyB,EAAE,KAAK,CAAC,aAAa,SAAS,UAAU,UAAU,CAAC;;;AC/CzF,cAAc;","names":["debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","debug","log","debug","log","debug","debug","debug","log","debug","debug","urlJoin","log","debug","urlJoin","debug","urlJoin","log","debug","urlJoin","debug","log","debug","log","debug"]}
|