@vite-hub/source 0.0.0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -1
- package/dist/chunk-D7D4PA-g.js +13 -0
- package/dist/custom-EnZvMLiy.d.ts +6 -0
- package/dist/file-slFAccIZ.d.ts +20 -0
- package/dist/github-B4lgrzXQ.js +565 -0
- package/dist/glob-CuxZwoC3.d.ts +15 -0
- package/dist/index-CJpN2j6c.d.ts +17 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +119 -0
- package/dist/markdown-Beo-0cqc.d.ts +7 -0
- package/dist/mcp-resources-C7-5Qeh4.d.ts +41 -0
- package/dist/mcp-resources-DSDqTfbK.js +307 -0
- package/dist/path-B5QNI5sY.js +44 -0
- package/dist/sources/custom.d.ts +2 -0
- package/dist/sources/custom.js +6 -0
- package/dist/sources/file.d.ts +2 -0
- package/dist/sources/file.js +57 -0
- package/dist/sources/github.d.ts +2 -0
- package/dist/sources/github.js +2 -0
- package/dist/sources/glob.d.ts +2 -0
- package/dist/sources/glob.js +110 -0
- package/dist/sources/index.d.ts +13 -0
- package/dist/sources/index.js +18 -0
- package/dist/sources/markdown.d.ts +2 -0
- package/dist/sources/markdown.js +10 -0
- package/dist/sources/mcp-resources.d.ts +2 -0
- package/dist/sources/mcp-resources.js +2 -0
- package/dist/types-f6Lyjq8g.d.ts +73 -0
- package/package.json +87 -5
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { a as SourceContent, c as SourceKey, d as SourceName, f as SourceReader, i as SourceCacheOptions, l as SourceListEntry, m as SourceSearchQuery, n as ReadSourceResult, o as SourceContext, p as SourceSearchHit, r as Source, s as SourceItem, t as ReadSourceOptions, u as SourceMap } from "./types-f6Lyjq8g.js";
|
|
2
|
+
import { t as custom } from "./custom-EnZvMLiy.js";
|
|
3
|
+
import { i as file, n as FileSourceOptions } from "./file-slFAccIZ.js";
|
|
4
|
+
import { n as GitHubSourceOptions, t as github } from "./index-CJpN2j6c.js";
|
|
5
|
+
import { n as glob, t as GlobSourceOptions } from "./glob-CuxZwoC3.js";
|
|
6
|
+
import { t as markdown } from "./markdown-Beo-0cqc.js";
|
|
7
|
+
import { a as McpResourcesRequestOptions, i as McpResourcesClientConfig, l as mcpResources, n as McpResourceDescriptor, o as McpResourcesServer, r as McpResourcesClient, s as McpResourcesSourceOptions, t as McpResourceContent } from "./mcp-resources-C7-5Qeh4.js";
|
|
8
|
+
import { t as index_d_exports } from "./sources/index.js";
|
|
9
|
+
import { ViteHubError } from "@vite-hub/runtime";
|
|
10
|
+
|
|
11
|
+
//#region src/core/define.d.ts
|
|
12
|
+
declare function defineSource<const TSource extends Source>(source: TSource): TSource;
|
|
13
|
+
declare function defineSources<const TSources extends Record<string, Source>>(sources: TSources): TSources;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/core/registry.d.ts
|
|
16
|
+
declare function registerSource<const TName extends string, const TSource extends Source>(name: TName, source: TSource): TSource;
|
|
17
|
+
declare function registerSources<const TSources extends Record<string, Source>>(sources: TSources): TSources;
|
|
18
|
+
declare function getRegisteredSource<TName extends SourceName>(name: TName): Source<SourceKey<TName>>;
|
|
19
|
+
declare function clearSources(): void;
|
|
20
|
+
declare function useSource<TName extends SourceName>(name: TName, context?: Partial<SourceContext>): SourceReader<TName>;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/core/errors.d.ts
|
|
23
|
+
type SourceErrorCode = "SOURCE_FAILED" | "SOURCE_NOT_FOUND" | "SOURCE_PATH_INVALID";
|
|
24
|
+
//#endregion
|
|
25
|
+
export { type FileSourceOptions, type GitHubSourceOptions, type GlobSourceOptions, type McpResourceContent, type McpResourceDescriptor, type McpResourcesClient, type McpResourcesClientConfig, type McpResourcesRequestOptions, type McpResourcesServer, type McpResourcesSourceOptions, type ReadSourceOptions, type ReadSourceResult, type Source, type SourceCacheOptions, type SourceContent, type SourceContext, type SourceErrorCode, type SourceItem, type SourceKey, type SourceListEntry, type SourceMap, type SourceName, type SourceReader, type SourceSearchHit, type SourceSearchQuery, clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, index_d_exports as source, useSource };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { i as normalizeSourcePath, o as sourceError, r as normalizeSafeSourcePath, s as sourceNotFoundError, t as decodeSourceContent } from "./path-B5QNI5sY.js";
|
|
2
|
+
import { custom } from "./sources/custom.js";
|
|
3
|
+
import { file } from "./sources/file.js";
|
|
4
|
+
import { t as github } from "./github-B4lgrzXQ.js";
|
|
5
|
+
import { glob } from "./sources/glob.js";
|
|
6
|
+
import { markdown } from "./sources/markdown.js";
|
|
7
|
+
import { t as mcpResources } from "./mcp-resources-DSDqTfbK.js";
|
|
8
|
+
import { t as sources_exports } from "./sources/index.js";
|
|
9
|
+
//#region src/core/define.ts
|
|
10
|
+
function defineSource(source) {
|
|
11
|
+
return source;
|
|
12
|
+
}
|
|
13
|
+
function defineSources(sources) {
|
|
14
|
+
return sources;
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/core/registry.ts
|
|
18
|
+
const sourceRegistry = /* @__PURE__ */ new Map();
|
|
19
|
+
function registerSource(name, source) {
|
|
20
|
+
sourceRegistry.set(name, source);
|
|
21
|
+
return source;
|
|
22
|
+
}
|
|
23
|
+
function registerSources(sources) {
|
|
24
|
+
for (const [name, source] of Object.entries(sources)) registerSource(name, source);
|
|
25
|
+
return sources;
|
|
26
|
+
}
|
|
27
|
+
function getRegisteredSource(name) {
|
|
28
|
+
const source = sourceRegistry.get(name);
|
|
29
|
+
if (!source) throw sourceNotFoundError(name);
|
|
30
|
+
return source;
|
|
31
|
+
}
|
|
32
|
+
function clearSources() {
|
|
33
|
+
sourceRegistry.clear();
|
|
34
|
+
}
|
|
35
|
+
function createSourceContext(name, context = {}) {
|
|
36
|
+
return {
|
|
37
|
+
abortSignal: context.abortSignal,
|
|
38
|
+
rootDir: context.rootDir || process.cwd(),
|
|
39
|
+
source: context.source || name,
|
|
40
|
+
sourceRootDir: context.sourceRootDir,
|
|
41
|
+
workspace: context.workspace
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function createMissingContentError(key) {
|
|
45
|
+
return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
|
|
46
|
+
}
|
|
47
|
+
function isNestedUnder(path, prefix) {
|
|
48
|
+
return !prefix || path === prefix || path.startsWith(`${prefix}/`);
|
|
49
|
+
}
|
|
50
|
+
function createDirectorySet(paths) {
|
|
51
|
+
const directories = /* @__PURE__ */ new Set();
|
|
52
|
+
for (const path of paths) {
|
|
53
|
+
const segments = normalizeSourcePath(path).split("/").filter(Boolean);
|
|
54
|
+
for (let index = 1; index < segments.length; index++) directories.add(segments.slice(0, index).join("/"));
|
|
55
|
+
}
|
|
56
|
+
return directories;
|
|
57
|
+
}
|
|
58
|
+
function useSource(name, context) {
|
|
59
|
+
const source = getRegisteredSource(name);
|
|
60
|
+
const ctx = createSourceContext(name, context);
|
|
61
|
+
let preparePromise;
|
|
62
|
+
async function ensurePrepared() {
|
|
63
|
+
if (!source.prepare) return;
|
|
64
|
+
preparePromise ||= source.prepare(ctx);
|
|
65
|
+
await preparePromise;
|
|
66
|
+
}
|
|
67
|
+
async function keys() {
|
|
68
|
+
await ensurePrepared();
|
|
69
|
+
return await source.getKeys(ctx);
|
|
70
|
+
}
|
|
71
|
+
async function get(key) {
|
|
72
|
+
await ensurePrepared();
|
|
73
|
+
return await source.getItem(key, ctx);
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
keys,
|
|
77
|
+
get,
|
|
78
|
+
async read(key, options) {
|
|
79
|
+
const item = await get(key);
|
|
80
|
+
if (typeof item.content === "undefined") throw createMissingContentError(key);
|
|
81
|
+
return decodeSourceContent(item.content, options);
|
|
82
|
+
},
|
|
83
|
+
async meta(key) {
|
|
84
|
+
await ensurePrepared();
|
|
85
|
+
return await source.getMeta?.(key, ctx);
|
|
86
|
+
},
|
|
87
|
+
async exists(key) {
|
|
88
|
+
return (await keys()).includes(key);
|
|
89
|
+
},
|
|
90
|
+
async list(prefix = "") {
|
|
91
|
+
await ensurePrepared();
|
|
92
|
+
const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }) : "";
|
|
93
|
+
const sourceKeys = await keys();
|
|
94
|
+
const directories = createDirectorySet(sourceKeys);
|
|
95
|
+
const result = /* @__PURE__ */ new Map();
|
|
96
|
+
for (const directory of directories) {
|
|
97
|
+
if (directory === normalizedPrefix) continue;
|
|
98
|
+
if (!isNestedUnder(directory, normalizedPrefix)) continue;
|
|
99
|
+
if (normalizeSourcePath(directory.slice(normalizedPrefix.length)).replace(/^\//, "").includes("/")) continue;
|
|
100
|
+
result.set(directory, {
|
|
101
|
+
key: directory,
|
|
102
|
+
type: "directory"
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
for (const key of sourceKeys) {
|
|
106
|
+
if (key === normalizedPrefix) continue;
|
|
107
|
+
if (!isNestedUnder(key, normalizedPrefix)) continue;
|
|
108
|
+
if (normalizeSourcePath(key.slice(normalizedPrefix.length)).replace(/^\//, "").includes("/")) continue;
|
|
109
|
+
result.set(key, {
|
|
110
|
+
key,
|
|
111
|
+
type: "file"
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
return [...result.values()].sort((left, right) => left.key.localeCompare(right.key));
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
export { clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, sources_exports as source, useSource };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { r as Source } from "./types-f6Lyjq8g.js";
|
|
2
|
+
import { n as FileSourceOptions } from "./file-slFAccIZ.js";
|
|
3
|
+
|
|
4
|
+
//#region src/sources/markdown.d.ts
|
|
5
|
+
declare function markdown<const TKey extends string = string>(options: FileSourceOptions<TKey>): Source<TKey>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { markdown as t };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { i as SourceCacheOptions, o as SourceContext, r as Source } from "./types-f6Lyjq8g.js";
|
|
2
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
4
|
+
import { StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
|
+
import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
6
|
+
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
7
|
+
import { BlobResourceContents, Resource, TextResourceContents } from "@modelcontextprotocol/sdk/types.js";
|
|
8
|
+
|
|
9
|
+
//#region src/sources/mcp-resources.d.ts
|
|
10
|
+
type McpResourcesRequestOptions = RequestOptions;
|
|
11
|
+
type McpResourceDescriptor = Resource;
|
|
12
|
+
type McpResourceContent = TextResourceContents | BlobResourceContents;
|
|
13
|
+
interface McpResourcesClient {
|
|
14
|
+
close?: () => void | Promise<void>;
|
|
15
|
+
getServerVersion?: Client["getServerVersion"];
|
|
16
|
+
listResources: Client["listResources"];
|
|
17
|
+
readResource: Client["readResource"];
|
|
18
|
+
serverInfo?: unknown;
|
|
19
|
+
}
|
|
20
|
+
type McpResourcesTransportConfig = Transport | ({
|
|
21
|
+
type?: "http";
|
|
22
|
+
url: string | URL;
|
|
23
|
+
} & StreamableHTTPClientTransportOptions) | ({
|
|
24
|
+
type: "sse";
|
|
25
|
+
url: string | URL;
|
|
26
|
+
} & SSEClientTransportOptions);
|
|
27
|
+
interface McpResourcesClientConfig {
|
|
28
|
+
transport: McpResourcesTransportConfig;
|
|
29
|
+
}
|
|
30
|
+
type McpResourcesServer = McpResourcesClient | McpResourcesClientConfig | ((ctx: SourceContext) => McpResourcesClient | McpResourcesClientConfig | Promise<McpResourcesClient | McpResourcesClientConfig>);
|
|
31
|
+
interface McpResourcesSourceOptions<TKey extends string = string> {
|
|
32
|
+
cache?: false | SourceCacheOptions;
|
|
33
|
+
exclude?: string | string[];
|
|
34
|
+
include?: string | string[];
|
|
35
|
+
path?: (resource: McpResourceDescriptor) => TKey | string | undefined;
|
|
36
|
+
request?: McpResourcesRequestOptions;
|
|
37
|
+
server: McpResourcesServer;
|
|
38
|
+
}
|
|
39
|
+
declare function mcpResources<const TKey extends string = string>(options: McpResourcesSourceOptions<TKey>): Source<TKey>;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { McpResourcesRequestOptions as a, McpResourcesTransportConfig as c, McpResourcesClientConfig as i, mcpResources as l, McpResourceDescriptor as n, McpResourcesServer as o, McpResourcesClient as r, McpResourcesSourceOptions as s, McpResourceContent as t };
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { i as normalizeSourcePath, n as matchesAny, o as sourceError, r as normalizeSafeSourcePath } from "./path-B5QNI5sY.js";
|
|
2
|
+
import { Cause, Data, Effect, Exit, Ref, Scope } from "effect";
|
|
3
|
+
//#region ../internal/src/effect.ts
|
|
4
|
+
var EffectBoundaryFailure = class extends Data.TaggedError("EffectBoundaryFailure") {};
|
|
5
|
+
function createEffectBoundary(options) {
|
|
6
|
+
function interruptionError(signal) {
|
|
7
|
+
if (signal?.aborted && signal.reason !== void 0) return signal.reason;
|
|
8
|
+
const error = new Error(options.interruptionMessage);
|
|
9
|
+
error.name = "AbortError";
|
|
10
|
+
return error;
|
|
11
|
+
}
|
|
12
|
+
function causeValues(cause, signal) {
|
|
13
|
+
return cause.reasons.map((reason) => {
|
|
14
|
+
if (Cause.isFailReason(reason)) return reason.error instanceof EffectBoundaryFailure ? reason.error.cause : reason.error;
|
|
15
|
+
if (Cause.isDieReason(reason)) return reason.defect;
|
|
16
|
+
return interruptionError(signal);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function tryPromise(evaluate) {
|
|
20
|
+
return Effect.tryPromise({
|
|
21
|
+
catch: (cause) => new EffectBoundaryFailure({ cause }),
|
|
22
|
+
try: (signal) => Promise.resolve(evaluate(signal))
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
async function run(effect, runOptions = {}) {
|
|
26
|
+
const exit = await Effect.runPromiseExit(effect, runOptions.signal ? { signal: runOptions.signal } : void 0);
|
|
27
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
28
|
+
const causes = causeValues(exit.cause, runOptions.signal);
|
|
29
|
+
if (causes.length === 1) throw causes[0];
|
|
30
|
+
throw new AggregateError(causes, options.aggregateMessage);
|
|
31
|
+
}
|
|
32
|
+
function acquireWithCapturedRelease(scope, failures, acquire, release) {
|
|
33
|
+
return Scope.provide(Effect.acquireRelease(acquire, (resource, exit) => Effect.matchCauseEffect(release(resource, exit), {
|
|
34
|
+
onFailure: (cause) => Ref.update(failures, (current) => [...current, ...causeValues(cause)]),
|
|
35
|
+
onSuccess: () => Effect.void
|
|
36
|
+
})), scope);
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
acquireWithCapturedRelease,
|
|
40
|
+
causeValues,
|
|
41
|
+
closeScopeWithCapturedReleases: Effect.fn("ViteHub.EffectBoundary.closeScope")(function* (scope, failures, closeOptions) {
|
|
42
|
+
yield* Scope.close(scope, closeOptions.exit ?? Exit.void);
|
|
43
|
+
const causes = yield* Ref.get(failures);
|
|
44
|
+
if (causes.length === 0) return;
|
|
45
|
+
const cause = causes.length === 1 ? causes[0] : new AggregateError(causes, closeOptions.aggregateMessage ?? options.aggregateMessage);
|
|
46
|
+
return yield* Effect.fail(new EffectBoundaryFailure({ cause }));
|
|
47
|
+
}),
|
|
48
|
+
run,
|
|
49
|
+
tryPromise
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/sources/mcp-resources.ts
|
|
54
|
+
const mcpEffectBoundary = createEffectBoundary({
|
|
55
|
+
aggregateMessage: "[vitehub] MCP Resource Source operation failed for multiple reasons.",
|
|
56
|
+
interruptionMessage: "[vitehub] MCP Resource Source operation was interrupted."
|
|
57
|
+
});
|
|
58
|
+
function isMcpResourcesClient(value) {
|
|
59
|
+
return typeof value === "object" && value !== null && typeof value.listResources === "function" && typeof value.readResource === "function";
|
|
60
|
+
}
|
|
61
|
+
function isMcpResourcesClientConfig(value) {
|
|
62
|
+
return typeof value === "object" && value !== null && "transport" in value;
|
|
63
|
+
}
|
|
64
|
+
function isMcpTransport(value) {
|
|
65
|
+
return typeof value === "object" && value !== null && typeof value.close === "function" && typeof value.send === "function" && typeof value.start === "function";
|
|
66
|
+
}
|
|
67
|
+
async function createMcpTransport(config) {
|
|
68
|
+
if (isMcpTransport(config)) return config;
|
|
69
|
+
const { type = "http", url, ...options } = config;
|
|
70
|
+
if (type === "sse") {
|
|
71
|
+
const { SSEClientTransport } = await import("@modelcontextprotocol/sdk/client/sse.js");
|
|
72
|
+
return new SSEClientTransport(new URL(url), options);
|
|
73
|
+
}
|
|
74
|
+
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
75
|
+
return new StreamableHTTPClientTransport(new URL(url), options);
|
|
76
|
+
}
|
|
77
|
+
async function createMcpClient(config) {
|
|
78
|
+
const [{ Client }, transport] = await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"), createMcpTransport(config.transport)]);
|
|
79
|
+
return {
|
|
80
|
+
client: new Client({
|
|
81
|
+
name: "vitehub-source",
|
|
82
|
+
version: "0.0.1"
|
|
83
|
+
}),
|
|
84
|
+
transport
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async function resolveMcpServer(server, ctx) {
|
|
88
|
+
const resolved = typeof server === "function" ? await server(ctx) : server;
|
|
89
|
+
if (isMcpResourcesClient(resolved) || isMcpResourcesClientConfig(resolved)) return resolved;
|
|
90
|
+
throw new TypeError("[vitehub] mcpResources({ server }) must resolve to an MCP client or MCP client config.");
|
|
91
|
+
}
|
|
92
|
+
function withRequestSignal(request, signal) {
|
|
93
|
+
return {
|
|
94
|
+
...request,
|
|
95
|
+
signal: request?.signal && request.signal !== signal ? AbortSignal.any([request.signal, signal]) : signal
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async function withMcpClient(server, ctx, request, callback) {
|
|
99
|
+
const effect = Effect.flatMap(mcpEffectBoundary.tryPromise(() => resolveMcpServer(server, ctx)), (resolved) => {
|
|
100
|
+
if (isMcpResourcesClient(resolved)) return mcpEffectBoundary.tryPromise((signal) => callback(resolved, withRequestSignal(request, signal)));
|
|
101
|
+
return Effect.acquireUseRelease(mcpEffectBoundary.tryPromise(() => createMcpClient(resolved)), ({ client, transport }) => mcpEffectBoundary.tryPromise((signal) => client.connect(transport, { signal })).pipe(Effect.andThen(mcpEffectBoundary.tryPromise((signal) => callback(client, withRequestSignal(request, signal))))), ({ client }) => mcpEffectBoundary.tryPromise(() => client.close?.()));
|
|
102
|
+
});
|
|
103
|
+
return await mcpEffectBoundary.run(effect, { signal: ctx.abortSignal });
|
|
104
|
+
}
|
|
105
|
+
function extensionForMimeType(mimeType) {
|
|
106
|
+
if (!mimeType) return;
|
|
107
|
+
if (mimeType === "application/json") return "json";
|
|
108
|
+
if (mimeType === "text/markdown") return "md";
|
|
109
|
+
if (mimeType === "text/plain") return "txt";
|
|
110
|
+
if (mimeType === "text/html") return "html";
|
|
111
|
+
if (mimeType === "application/xml" || mimeType === "text/xml") return "xml";
|
|
112
|
+
if (mimeType === "application/octet-stream") return "bin";
|
|
113
|
+
}
|
|
114
|
+
function normalizePathSegment(input) {
|
|
115
|
+
return input.normalize("NFKD").replace(/\\/g, "/").replace(/[^\w./-]+/g, "-").replace(/\/+/g, "/").replace(/(^|\/)\.+(?=\/|$)/g, "").replace(/^-+|-+$/g, "");
|
|
116
|
+
}
|
|
117
|
+
function defaultResourcePath(resource) {
|
|
118
|
+
let path = "";
|
|
119
|
+
try {
|
|
120
|
+
const url = new URL(resource.uri);
|
|
121
|
+
const protocol = url.protocol.replace(/:$/, "");
|
|
122
|
+
path = [url.hostname || url.host, decodeURIComponent(url.pathname).replace(/^\/+/, "") || resource.name || protocol].filter(Boolean).join("/");
|
|
123
|
+
} catch {
|
|
124
|
+
path = resource.name || resource.uri;
|
|
125
|
+
}
|
|
126
|
+
let normalized = normalizePathSegment(path);
|
|
127
|
+
if (!normalized) normalized = normalizePathSegment(resource.name || resource.uri);
|
|
128
|
+
const extension = extensionForMimeType(resource.mimeType);
|
|
129
|
+
if (extension && !normalized.split("/").at(-1)?.includes(".")) normalized = `${normalized}.${extension}`;
|
|
130
|
+
return normalizeSafeSourcePath(normalized);
|
|
131
|
+
}
|
|
132
|
+
function resourcePathNeedsContentMimeType(resource, options) {
|
|
133
|
+
if (options.path || resource.mimeType) return false;
|
|
134
|
+
return !defaultResourcePath(resource).split("/").at(-1)?.includes(".");
|
|
135
|
+
}
|
|
136
|
+
function resourceWithContentMimeType(resource, contents) {
|
|
137
|
+
if (resource.mimeType) return resource;
|
|
138
|
+
const content = contents.find((item) => item.uri === resource.uri) || contents[0];
|
|
139
|
+
const mimeType = contents.length > 1 ? "application/json" : content?.mimeType;
|
|
140
|
+
return mimeType ? {
|
|
141
|
+
...resource,
|
|
142
|
+
mimeType
|
|
143
|
+
} : resource;
|
|
144
|
+
}
|
|
145
|
+
function resourceKey(resource, options) {
|
|
146
|
+
return normalizeSafeSourcePath(options.path?.(resource) ?? defaultResourcePath(resource));
|
|
147
|
+
}
|
|
148
|
+
function shouldInclude(path, options) {
|
|
149
|
+
if (options.include && !matchesAny(path, options.include)) return false;
|
|
150
|
+
if (options.exclude && matchesAny(path, options.exclude)) return false;
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
async function listAllResources(client, request) {
|
|
154
|
+
const resources = [];
|
|
155
|
+
let cursor;
|
|
156
|
+
do {
|
|
157
|
+
const page = await client.listResources(cursor ? { cursor } : void 0, request);
|
|
158
|
+
resources.push(...page.resources);
|
|
159
|
+
cursor = page.nextCursor;
|
|
160
|
+
} while (cursor);
|
|
161
|
+
return resources;
|
|
162
|
+
}
|
|
163
|
+
async function readResourceContents(client, resource, request) {
|
|
164
|
+
return (await client.readResource({ uri: resource.uri }, request)).contents;
|
|
165
|
+
}
|
|
166
|
+
async function createEntries(resources, options, client) {
|
|
167
|
+
const entries = [];
|
|
168
|
+
const seen = /* @__PURE__ */ new Map();
|
|
169
|
+
for (const resource of resources) {
|
|
170
|
+
let contents;
|
|
171
|
+
let resolvedResource = resource;
|
|
172
|
+
if (client && resourcePathNeedsContentMimeType(resource, options)) {
|
|
173
|
+
contents = await readResourceContents(client, resource, options.request);
|
|
174
|
+
resolvedResource = resourceWithContentMimeType(resource, contents);
|
|
175
|
+
}
|
|
176
|
+
const key = resourceKey(resolvedResource, options);
|
|
177
|
+
if (!shouldInclude(key, options)) continue;
|
|
178
|
+
const existingUri = seen.get(key);
|
|
179
|
+
if (existingUri) throw sourceError(`[vitehub] mcpResources produced duplicate path ${JSON.stringify(key)} for ${JSON.stringify(existingUri)} and ${JSON.stringify(resource.uri)}.`);
|
|
180
|
+
seen.set(key, resource.uri);
|
|
181
|
+
entries.push({
|
|
182
|
+
contents,
|
|
183
|
+
key,
|
|
184
|
+
resource: resolvedResource
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return entries;
|
|
188
|
+
}
|
|
189
|
+
function decodeBase64(value) {
|
|
190
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(value, "base64"));
|
|
191
|
+
const binary = atob(value);
|
|
192
|
+
const bytes = new Uint8Array(binary.length);
|
|
193
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
194
|
+
return bytes;
|
|
195
|
+
}
|
|
196
|
+
function contentToSourceContent(content) {
|
|
197
|
+
if ("text" in content && typeof content.text === "string") return content.text;
|
|
198
|
+
if ("blob" in content && typeof content.blob === "string") return decodeBase64(content.blob);
|
|
199
|
+
return "";
|
|
200
|
+
}
|
|
201
|
+
function createResourceItem(key, resource, contents) {
|
|
202
|
+
const content = contents.find((item) => item.uri === resource.uri) || contents[0];
|
|
203
|
+
if (!content) throw sourceError(`[vitehub] mcpResources could not read resource ${JSON.stringify(resource.uri)}.`);
|
|
204
|
+
const multipleContents = contents.length > 1;
|
|
205
|
+
return {
|
|
206
|
+
key,
|
|
207
|
+
path: key,
|
|
208
|
+
content: multipleContents ? JSON.stringify(contents, null, 2) : contentToSourceContent(content),
|
|
209
|
+
mediaType: multipleContents ? "application/json" : content.mimeType || resource.mimeType,
|
|
210
|
+
metadata: {
|
|
211
|
+
description: resource.description,
|
|
212
|
+
name: resource.name,
|
|
213
|
+
serverResourceCount: contents.length,
|
|
214
|
+
size: resource.size,
|
|
215
|
+
title: resource.title,
|
|
216
|
+
uri: resource.uri
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function mcpResources(options) {
|
|
221
|
+
if (!options || typeof options !== "object" || !options.server) throw new TypeError("[vitehub] mcpResources({ server }) requires an MCP server.");
|
|
222
|
+
async function getEntries(ctx) {
|
|
223
|
+
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
224
|
+
return await createEntries(await listAllResources(client, request), {
|
|
225
|
+
...options,
|
|
226
|
+
request
|
|
227
|
+
}, client);
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
async function getItems(ctx) {
|
|
231
|
+
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
232
|
+
const scopedOptions = {
|
|
233
|
+
...options,
|
|
234
|
+
request
|
|
235
|
+
};
|
|
236
|
+
const entries = await createEntries(await listAllResources(client, request), scopedOptions, client);
|
|
237
|
+
return await Promise.all(entries.map(async ({ contents, key, resource }) => {
|
|
238
|
+
return createResourceItem(key, resource, contents ?? await readResourceContents(client, resource, request));
|
|
239
|
+
}));
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
cache: options.cache,
|
|
244
|
+
fingerprint: {
|
|
245
|
+
exclude: options.exclude,
|
|
246
|
+
include: options.include,
|
|
247
|
+
server: typeof options.server === "function" ? "[function]" : isMcpResourcesClient(options.server) ? {
|
|
248
|
+
client: true,
|
|
249
|
+
serverInfo: options.server.serverInfo
|
|
250
|
+
} : options.server
|
|
251
|
+
},
|
|
252
|
+
name: "mcpResources",
|
|
253
|
+
async getKeys(ctx) {
|
|
254
|
+
return (await getEntries(ctx)).map((entry) => entry.key);
|
|
255
|
+
},
|
|
256
|
+
async getItems(ctx) {
|
|
257
|
+
return await getItems(ctx);
|
|
258
|
+
},
|
|
259
|
+
async getMeta(key, ctx) {
|
|
260
|
+
const entry = (await getEntries(ctx)).find((entry) => entry.key === key);
|
|
261
|
+
if (!entry) return;
|
|
262
|
+
return {
|
|
263
|
+
description: entry.resource.description,
|
|
264
|
+
mimeType: entry.resource.mimeType,
|
|
265
|
+
name: entry.resource.name,
|
|
266
|
+
size: entry.resource.size,
|
|
267
|
+
title: entry.resource.title,
|
|
268
|
+
uri: entry.resource.uri
|
|
269
|
+
};
|
|
270
|
+
},
|
|
271
|
+
async getItem(key, ctx) {
|
|
272
|
+
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
273
|
+
const entry = (await createEntries(await listAllResources(client, request), {
|
|
274
|
+
...options,
|
|
275
|
+
request
|
|
276
|
+
}, client)).find((entry) => entry.key === key);
|
|
277
|
+
if (!entry) throw sourceError(`[vitehub] mcpResources could not find ${JSON.stringify(key)}.`);
|
|
278
|
+
const result = entry.contents ?? await readResourceContents(client, entry.resource, request);
|
|
279
|
+
return createResourceItem(key, entry.resource, result);
|
|
280
|
+
});
|
|
281
|
+
},
|
|
282
|
+
async search(query, ctx) {
|
|
283
|
+
const pattern = query.regex ? new RegExp(query.pattern, query.caseSensitive ? "g" : "gi") : void 0;
|
|
284
|
+
const search = query.caseSensitive ? query.pattern : query.pattern.toLowerCase();
|
|
285
|
+
const results = [];
|
|
286
|
+
for (const item of await getItems(ctx)) {
|
|
287
|
+
if (typeof item.content !== "string") continue;
|
|
288
|
+
if (query.paths?.length && !query.paths.some((path) => item.path && normalizeSourcePath(item.path).startsWith(normalizeSourcePath(path)))) continue;
|
|
289
|
+
const lines = item.content.split(/\r?\n/);
|
|
290
|
+
for (const [index, line] of lines.entries()) {
|
|
291
|
+
const matchIndex = pattern ? line.search(pattern) : (query.caseSensitive ? line : line.toLowerCase()).indexOf(search);
|
|
292
|
+
if (matchIndex === -1) continue;
|
|
293
|
+
results.push({
|
|
294
|
+
column: matchIndex + 1,
|
|
295
|
+
line: index + 1,
|
|
296
|
+
path: item.path || item.key,
|
|
297
|
+
text: line
|
|
298
|
+
});
|
|
299
|
+
if (query.limit && results.length >= query.limit) return results;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return results;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
//#endregion
|
|
307
|
+
export { mcpResources as t };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
|
|
2
|
+
import picomatch from "picomatch";
|
|
3
|
+
import { isAbsolute } from "pathe";
|
|
4
|
+
//#region src/core/errors.ts
|
|
5
|
+
function sourceError(message, options) {
|
|
6
|
+
return new ViteHubError("SOURCE_FAILED", message, options);
|
|
7
|
+
}
|
|
8
|
+
function sourceNotFoundError(name) {
|
|
9
|
+
return new ViteHubError("SOURCE_NOT_FOUND", `[vitehub] Source "${name}" is not registered.`, { details: { name } });
|
|
10
|
+
}
|
|
11
|
+
function sourcePathError(path) {
|
|
12
|
+
const publicPath = path.slice(0, 4096);
|
|
13
|
+
return new ViteHubError("SOURCE_PATH_INVALID", `[vitehub] Source path escapes the source root: ${JSON.stringify(publicPath)}.`, { details: { path: publicPath } });
|
|
14
|
+
}
|
|
15
|
+
function isSourceError(value) {
|
|
16
|
+
const code = getViteHubErrorShape(value)?.code;
|
|
17
|
+
return code === "SOURCE_FAILED" || code === "SOURCE_NOT_FOUND" || code === "SOURCE_PATH_INVALID";
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/core/path.ts
|
|
21
|
+
function normalizeSourcePath(path = "") {
|
|
22
|
+
return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
|
|
23
|
+
}
|
|
24
|
+
function normalizeSafeSourcePath(path = "", options = {}) {
|
|
25
|
+
const raw = path.replace(/\\/g, "/");
|
|
26
|
+
const normalized = normalizeSourcePath(path);
|
|
27
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
28
|
+
if (!options.allowEmpty && !normalized) throw sourcePathError(path);
|
|
29
|
+
if (isAbsolute(raw) || parts.some((part) => part === "." || part === "..")) throw sourcePathError(path);
|
|
30
|
+
if (!options.allowReserved && (parts[0] === ".git" || parts[0] === ".vitehub")) throw sourcePathError(path);
|
|
31
|
+
return normalized;
|
|
32
|
+
}
|
|
33
|
+
function matchesAny(path, patterns) {
|
|
34
|
+
if (!patterns) return true;
|
|
35
|
+
const list = Array.isArray(patterns) ? patterns : [patterns];
|
|
36
|
+
const normalizedPath = normalizeSourcePath(path);
|
|
37
|
+
return picomatch.isMatch(normalizedPath, list.map((pattern) => normalizeSourcePath(pattern)), { dot: true });
|
|
38
|
+
}
|
|
39
|
+
function decodeSourceContent(content, options) {
|
|
40
|
+
if (options?.encoding === "binary") return typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
41
|
+
return typeof content === "string" ? content : new TextDecoder().decode(content);
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { isSourceError as a, sourcePathError as c, normalizeSourcePath as i, matchesAny as n, sourceError as o, normalizeSafeSourcePath as r, sourceNotFoundError as s, decodeSourceContent as t };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { c as sourcePathError, i as normalizeSourcePath, o as sourceError, r as normalizeSafeSourcePath } from "../path-B5QNI5sY.js";
|
|
2
|
+
import { lookup } from "mrmime";
|
|
3
|
+
//#region src/sources/file.ts
|
|
4
|
+
function normalizeFileSourceOptions(input) {
|
|
5
|
+
return typeof input === "string" ? { path: input } : input;
|
|
6
|
+
}
|
|
7
|
+
function sourceKey(options) {
|
|
8
|
+
if (options.workspacePath) return normalizeSourcePath(options.workspacePath);
|
|
9
|
+
if ("path" in options && options.path) return normalizeSourcePath(normalizeSafeSourcePath(options.path));
|
|
10
|
+
throw new TypeError("[vitehub] file requires a path or workspacePath.");
|
|
11
|
+
}
|
|
12
|
+
function resolveSourceRoot(ctx) {
|
|
13
|
+
return ctx.sourceRootDir || ctx.rootDir;
|
|
14
|
+
}
|
|
15
|
+
async function readSourceFile(options, ctx) {
|
|
16
|
+
if (!("path" in options) || !options.path) throw new TypeError("[vitehub] file requires path when content is not provided.");
|
|
17
|
+
const { readFile } = await import("node:fs/promises");
|
|
18
|
+
return new Uint8Array(await readFile(await resolveSafeSourceFilePath(options.path, ctx)));
|
|
19
|
+
}
|
|
20
|
+
async function resolveSafeSourceFilePath(path, ctx) {
|
|
21
|
+
const { realpath } = await import("node:fs/promises");
|
|
22
|
+
const { relative, resolve, sep } = await import("node:path");
|
|
23
|
+
const root = await realpath(resolve(resolveSourceRoot(ctx)));
|
|
24
|
+
const target = await realpath(resolve(root, normalizeSafeSourcePath(path)));
|
|
25
|
+
const rel = relative(root, target);
|
|
26
|
+
if (rel === ".." || rel.startsWith(`..${sep}`)) throw sourcePathError(path);
|
|
27
|
+
return target;
|
|
28
|
+
}
|
|
29
|
+
function file(input) {
|
|
30
|
+
const options = normalizeFileSourceOptions(input);
|
|
31
|
+
const key = sourceKey(options);
|
|
32
|
+
const mediaType = options.mediaType || lookup(key);
|
|
33
|
+
return {
|
|
34
|
+
name: "file",
|
|
35
|
+
async getKeys() {
|
|
36
|
+
return [key];
|
|
37
|
+
},
|
|
38
|
+
async getMeta(requestedKey, ctx) {
|
|
39
|
+
if (requestedKey !== key) return;
|
|
40
|
+
if (!("path" in options) || !options.path) return;
|
|
41
|
+
const { stat } = await import("node:fs/promises");
|
|
42
|
+
const info = await stat(await resolveSafeSourceFilePath(options.path, ctx));
|
|
43
|
+
return { digest: `${info.size}:${info.mtimeMs}` };
|
|
44
|
+
},
|
|
45
|
+
async getItem(requestedKey, ctx) {
|
|
46
|
+
if (requestedKey !== key) throw sourceError(`[vitehub] file could not find ${JSON.stringify(requestedKey)}.`);
|
|
47
|
+
return {
|
|
48
|
+
key,
|
|
49
|
+
path: key,
|
|
50
|
+
content: typeof options.content === "undefined" ? await readSourceFile(options, ctx) : options.content,
|
|
51
|
+
mediaType
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { file };
|