@vite-hub/source 0.0.3 → 0.0.4
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/LICENSE +201 -0
- package/README.md +135 -1
- package/dist/auth-Ddw55OUG.js +1261 -0
- package/dist/client-CDfTmtQu.js +7903 -0
- package/dist/client.d.ts +32 -0
- package/dist/client.js +121 -0
- package/dist/collection-B8pXGM2d.js +141 -0
- package/dist/collection-CF2ON__k.d.ts +92 -0
- package/dist/collection-route-Dw7QLFyx.js +6 -0
- package/dist/content/client.d.ts +3 -0
- package/dist/content/client.js +2 -0
- package/dist/content.d.ts +44 -0
- package/dist/content.js +157 -0
- package/dist/file-BSWQg9Qv.js +503 -0
- package/dist/file-EQ3AjVM6.d.ts +20 -0
- package/dist/file.d.ts +2 -0
- package/dist/file.js +2 -0
- package/dist/github.d.ts +17 -0
- package/dist/github.js +1033 -0
- package/dist/glob.d.ts +15 -0
- package/dist/glob.js +895 -0
- package/dist/index.d.ts +64 -162
- package/dist/index.js +66 -1188
- package/dist/markdown.d.ts +7 -0
- package/dist/markdown.js +10 -0
- package/dist/mcp.d.ts +152 -0
- package/dist/mcp.js +6115 -0
- package/dist/path-BzmU4Eni.js +36 -0
- package/dist/path-CUhvUREm.js +1936 -0
- package/dist/registry-C8skfCSV.js +120 -0
- package/dist/server.d.ts +15 -0
- package/dist/server.js +71 -0
- package/dist/sse-CE9Q2JqM.js +407 -0
- package/dist/streamableHttp-BszaXLmg.js +491 -0
- package/dist/types-AIBmt_m6.js +6275 -0
- package/dist/types-Bu3WvNX9.d.ts +71 -0
- package/dist/vite.d.ts +41 -0
- package/dist/vite.js +629 -0
- package/package.json +75 -9
- package/tsconfig.vite.json +6 -0
- package/types/source/fallback.d.ts +1 -0
- package/types/source/index.d.ts +1 -0
package/dist/index.js
CHANGED
|
@@ -1,13 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
import { a as sourceError } from "./path-BzmU4Eni.js";
|
|
2
|
+
import { a as useSource, i as registerSources, n as getRegisteredSource, r as registerSource, t as clearSources } from "./registry-C8skfCSV.js";
|
|
3
|
+
import { n as defineCollection, t as CollectionCursorError } from "./collection-B8pXGM2d.js";
|
|
4
|
+
//#region src/core/combine-sources.ts
|
|
5
|
+
function combineSources(definition) {
|
|
6
|
+
const sources = definition.sources;
|
|
7
|
+
async function get(identity) {
|
|
8
|
+
if (!Array.isArray(identity) || identity.length !== 2 || String(identity[0]) !== identity[0] || String(identity[1]) !== identity[1]) throw new TypeError("[vitehub] Combined Source identity must be a [source, key] string tuple.");
|
|
9
|
+
const [source, key] = identity;
|
|
10
|
+
if (!Object.hasOwn(sources, source)) throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not defined.`);
|
|
11
|
+
return await sources[source].get(key);
|
|
12
|
+
}
|
|
13
|
+
async function items() {
|
|
14
|
+
const entries = Object.entries(sources);
|
|
15
|
+
for (const [source, reader] of entries) if (!(reader.items instanceof Function)) throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not enumerable.`);
|
|
16
|
+
return (await Promise.all(entries.map(async ([source, reader]) => (await reader.items()).map((item) => ({
|
|
17
|
+
...item,
|
|
18
|
+
identity: [source, item.key],
|
|
19
|
+
source
|
|
20
|
+
}))))).flat();
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
get,
|
|
24
|
+
items
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
11
28
|
//#region src/core/define.ts
|
|
12
29
|
function defineSource(source) {
|
|
13
30
|
return source;
|
|
@@ -15,1189 +32,50 @@ function defineSource(source) {
|
|
|
15
32
|
function defineSources(sources) {
|
|
16
33
|
return sources;
|
|
17
34
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
function sourceError(message, options) {
|
|
21
|
-
return new ViteHubError("SOURCE_FAILED", message, options);
|
|
22
|
-
}
|
|
23
|
-
function sourceNotFoundError(name) {
|
|
24
|
-
return new ViteHubError("SOURCE_NOT_FOUND", `[vitehub] Source "${name}" is not registered.`, { details: { name } });
|
|
25
|
-
}
|
|
26
|
-
function sourcePathError(path) {
|
|
27
|
-
const publicPath = path.slice(0, 4096);
|
|
28
|
-
return new ViteHubError("SOURCE_PATH_INVALID", `[vitehub] Source path escapes the source root: ${JSON.stringify(publicPath)}.`, { details: { path: publicPath } });
|
|
29
|
-
}
|
|
30
|
-
function isSourceError(value) {
|
|
31
|
-
const code = getViteHubErrorShape(value)?.code;
|
|
32
|
-
return code === "SOURCE_FAILED" || code === "SOURCE_NOT_FOUND" || code === "SOURCE_PATH_INVALID";
|
|
35
|
+
function createSource(definition, context) {
|
|
36
|
+
return definition(context);
|
|
33
37
|
}
|
|
34
38
|
//#endregion
|
|
35
|
-
//#region src/
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (!source) throw sourceNotFoundError(name);
|
|
72
|
-
return source;
|
|
73
|
-
}
|
|
74
|
-
function clearSources() {
|
|
75
|
-
sourceRegistry.clear();
|
|
76
|
-
}
|
|
77
|
-
function createSourceContext(name, context = {}) {
|
|
78
|
-
return {
|
|
79
|
-
abortSignal: context.abortSignal,
|
|
80
|
-
rootDir: context.rootDir || process.cwd(),
|
|
81
|
-
source: context.source || name,
|
|
82
|
-
sourceRootDir: context.sourceRootDir,
|
|
83
|
-
workspace: context.workspace
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
function createMissingContentError(key) {
|
|
87
|
-
return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
|
|
88
|
-
}
|
|
89
|
-
function isNestedUnder(path, prefix) {
|
|
90
|
-
return !prefix || path === prefix || path.startsWith(`${prefix}/`);
|
|
91
|
-
}
|
|
92
|
-
function createDirectorySet(paths) {
|
|
93
|
-
const directories = /* @__PURE__ */ new Set();
|
|
94
|
-
for (const path of paths) {
|
|
95
|
-
const segments = normalizeSourcePath(path).split("/").filter(Boolean);
|
|
96
|
-
for (let index = 1; index < segments.length; index++) directories.add(segments.slice(0, index).join("/"));
|
|
97
|
-
}
|
|
98
|
-
return directories;
|
|
99
|
-
}
|
|
100
|
-
function useSource(name, context) {
|
|
101
|
-
const source = getRegisteredSource(name);
|
|
102
|
-
const ctx = createSourceContext(name, context);
|
|
103
|
-
let preparePromise;
|
|
104
|
-
async function ensurePrepared() {
|
|
105
|
-
if (!source.prepare) return;
|
|
106
|
-
preparePromise ||= source.prepare(ctx);
|
|
107
|
-
await preparePromise;
|
|
108
|
-
}
|
|
109
|
-
async function keys() {
|
|
110
|
-
await ensurePrepared();
|
|
111
|
-
return await source.getKeys(ctx);
|
|
112
|
-
}
|
|
113
|
-
async function get(key) {
|
|
114
|
-
await ensurePrepared();
|
|
115
|
-
return await source.getItem(key, ctx);
|
|
116
|
-
}
|
|
117
|
-
return {
|
|
118
|
-
keys,
|
|
119
|
-
get,
|
|
120
|
-
async items() {
|
|
121
|
-
await ensurePrepared();
|
|
122
|
-
if (source.getItems) return await source.getItems(ctx);
|
|
123
|
-
return await Promise.all((await keys()).map(get));
|
|
124
|
-
},
|
|
125
|
-
async read(key, options) {
|
|
126
|
-
const item = await get(key);
|
|
127
|
-
if (typeof item.content === "undefined") throw createMissingContentError(key);
|
|
128
|
-
return decodeSourceContent(item.content, options);
|
|
129
|
-
},
|
|
130
|
-
async meta(key) {
|
|
131
|
-
await ensurePrepared();
|
|
132
|
-
return await source.getMeta?.(key, ctx);
|
|
133
|
-
},
|
|
134
|
-
async exists(key) {
|
|
135
|
-
return (await keys()).includes(key);
|
|
136
|
-
},
|
|
137
|
-
async list(prefix = "") {
|
|
138
|
-
await ensurePrepared();
|
|
139
|
-
const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }) : "";
|
|
140
|
-
const sourceKeys = await keys();
|
|
141
|
-
const directories = createDirectorySet(sourceKeys);
|
|
142
|
-
const result = /* @__PURE__ */ new Map();
|
|
143
|
-
for (const directory of directories) {
|
|
144
|
-
if (directory === normalizedPrefix) continue;
|
|
145
|
-
if (!isNestedUnder(directory, normalizedPrefix)) continue;
|
|
146
|
-
if (normalizeSourcePath(directory.slice(normalizedPrefix.length)).replace(/^\//, "").includes("/")) continue;
|
|
147
|
-
result.set(directory, {
|
|
148
|
-
key: directory,
|
|
149
|
-
type: "directory"
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
for (const key of sourceKeys) {
|
|
153
|
-
if (key === normalizedPrefix) continue;
|
|
154
|
-
if (!isNestedUnder(key, normalizedPrefix)) continue;
|
|
155
|
-
if (normalizeSourcePath(key.slice(normalizedPrefix.length)).replace(/^\//, "").includes("/")) continue;
|
|
156
|
-
result.set(key, {
|
|
157
|
-
key,
|
|
158
|
-
type: "file"
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
return [...result.values()].sort((left, right) => left.key.localeCompare(right.key));
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
}
|
|
39
|
+
//#region src/ignores.ts
|
|
40
|
+
const dependencies = Object.freeze([
|
|
41
|
+
"**/node_modules/**",
|
|
42
|
+
"**/.pnpm-store/**",
|
|
43
|
+
"**/.venv/**",
|
|
44
|
+
"**/dbt_packages/**"
|
|
45
|
+
]);
|
|
46
|
+
const generated = Object.freeze([
|
|
47
|
+
"**/.nuxt/**",
|
|
48
|
+
"**/.output/**",
|
|
49
|
+
"**/coverage/**",
|
|
50
|
+
"**/playwright-report/**",
|
|
51
|
+
"**/target/**",
|
|
52
|
+
"**/test-results/**"
|
|
53
|
+
]);
|
|
54
|
+
const media = Object.freeze(["**/*.{gif,ico,jpeg,jpg,png,webp}"]);
|
|
55
|
+
const secrets = Object.freeze(["**/.env", "**/.env.*"]);
|
|
56
|
+
const system = Object.freeze([
|
|
57
|
+
"**/.DS_Store",
|
|
58
|
+
"**/__pycache__/**",
|
|
59
|
+
"**/*.pyc"
|
|
60
|
+
]);
|
|
61
|
+
const sourceIgnores = Object.freeze({
|
|
62
|
+
defaults: Object.freeze([
|
|
63
|
+
...dependencies,
|
|
64
|
+
...generated,
|
|
65
|
+
...media,
|
|
66
|
+
...secrets,
|
|
67
|
+
...system
|
|
68
|
+
]),
|
|
69
|
+
dependencies,
|
|
70
|
+
generated,
|
|
71
|
+
media,
|
|
72
|
+
secrets,
|
|
73
|
+
system
|
|
74
|
+
});
|
|
165
75
|
//#endregion
|
|
166
76
|
//#region src/sources/custom.ts
|
|
167
77
|
function custom(source) {
|
|
168
78
|
return source;
|
|
169
79
|
}
|
|
170
80
|
//#endregion
|
|
171
|
-
|
|
172
|
-
function normalizeFileSourceOptions(input) {
|
|
173
|
-
return typeof input === "string" ? { path: input } : input;
|
|
174
|
-
}
|
|
175
|
-
function sourceKey(options) {
|
|
176
|
-
if (options.workspacePath) return normalizeSourcePath(options.workspacePath);
|
|
177
|
-
if ("path" in options && options.path) return normalizeSourcePath(normalizeSafeSourcePath(options.path));
|
|
178
|
-
throw new TypeError("[vitehub] file requires a path or workspacePath.");
|
|
179
|
-
}
|
|
180
|
-
function resolveSourceRoot$1(ctx) {
|
|
181
|
-
return ctx.sourceRootDir || ctx.rootDir;
|
|
182
|
-
}
|
|
183
|
-
async function readSourceFile(options, ctx) {
|
|
184
|
-
if (!("path" in options) || !options.path) throw new TypeError("[vitehub] file requires path when content is not provided.");
|
|
185
|
-
const { readFile } = await import("node:fs/promises");
|
|
186
|
-
return new Uint8Array(await readFile(await resolveSafeSourceFilePath(options.path, ctx)));
|
|
187
|
-
}
|
|
188
|
-
async function resolveSafeSourceFilePath(path, ctx) {
|
|
189
|
-
const { realpath } = await import("node:fs/promises");
|
|
190
|
-
const { relative, resolve, sep } = await import("node:path");
|
|
191
|
-
const root = await realpath(resolve(resolveSourceRoot$1(ctx)));
|
|
192
|
-
const target = await realpath(resolve(root, normalizeSafeSourcePath(path)));
|
|
193
|
-
const rel = relative(root, target);
|
|
194
|
-
if (rel === ".." || rel.startsWith(`..${sep}`)) throw sourcePathError(path);
|
|
195
|
-
return target;
|
|
196
|
-
}
|
|
197
|
-
function file(input) {
|
|
198
|
-
const options = normalizeFileSourceOptions(input);
|
|
199
|
-
const key = sourceKey(options);
|
|
200
|
-
const mediaType = options.mediaType || lookup(key);
|
|
201
|
-
return {
|
|
202
|
-
name: "file",
|
|
203
|
-
async getKeys() {
|
|
204
|
-
return [key];
|
|
205
|
-
},
|
|
206
|
-
async getMeta(requestedKey, ctx) {
|
|
207
|
-
if (requestedKey !== key) return;
|
|
208
|
-
if (!("path" in options) || !options.path) return;
|
|
209
|
-
const { stat } = await import("node:fs/promises");
|
|
210
|
-
const info = await stat(await resolveSafeSourceFilePath(options.path, ctx));
|
|
211
|
-
return { digest: `${info.size}:${info.mtimeMs}` };
|
|
212
|
-
},
|
|
213
|
-
async getItem(requestedKey, ctx) {
|
|
214
|
-
if (requestedKey !== key) throw sourceError(`[vitehub] file could not find ${JSON.stringify(requestedKey)}.`);
|
|
215
|
-
return {
|
|
216
|
-
key,
|
|
217
|
-
path: key,
|
|
218
|
-
content: typeof options.content === "undefined" ? await readSourceFile(options, ctx) : options.content,
|
|
219
|
-
mediaType
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
//#endregion
|
|
225
|
-
//#region src/sources/github/archive.ts
|
|
226
|
-
function parseGitHubArchive(bytes) {
|
|
227
|
-
const tar = gunzipSync(bytes);
|
|
228
|
-
const files = [];
|
|
229
|
-
let offset = 0;
|
|
230
|
-
let paxPath;
|
|
231
|
-
while (offset + 512 <= tar.length) {
|
|
232
|
-
const header = tar.subarray(offset, offset + 512);
|
|
233
|
-
if (header.every((byte) => byte === 0)) break;
|
|
234
|
-
const name = readTarString(header, 0, 100);
|
|
235
|
-
const prefix = readTarString(header, 345, 155);
|
|
236
|
-
const path = paxPath || [prefix, name].filter(Boolean).join("/");
|
|
237
|
-
const size = Number.parseInt(readTarString(header, 124, 12).trim() || "0", 8) || 0;
|
|
238
|
-
const type = String.fromCharCode(header[156] || 0);
|
|
239
|
-
const contentStart = offset + 512;
|
|
240
|
-
const contentEnd = contentStart + size;
|
|
241
|
-
const content = tar.subarray(contentStart, contentEnd);
|
|
242
|
-
if (type === "x") paxPath = readPaxPath(content);
|
|
243
|
-
else {
|
|
244
|
-
if (type === "0" || type === "\0") {
|
|
245
|
-
const entryPath = stripArchiveRoot(path);
|
|
246
|
-
if (entryPath) files.push({
|
|
247
|
-
content: new Uint8Array(content),
|
|
248
|
-
path: entryPath
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
paxPath = void 0;
|
|
252
|
-
}
|
|
253
|
-
offset = contentStart + Math.ceil(size / 512) * 512;
|
|
254
|
-
}
|
|
255
|
-
return files;
|
|
256
|
-
}
|
|
257
|
-
function readTarString(buffer, offset, length) {
|
|
258
|
-
const slice = buffer.subarray(offset, offset + length);
|
|
259
|
-
const end = slice.indexOf(0);
|
|
260
|
-
return Buffer$1.from(end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
|
|
261
|
-
}
|
|
262
|
-
function readPaxPath(content) {
|
|
263
|
-
let index = 0;
|
|
264
|
-
while (index < content.length) {
|
|
265
|
-
let space = index;
|
|
266
|
-
while (space < content.length && content[space] !== 32) space++;
|
|
267
|
-
if (space >= content.length) return;
|
|
268
|
-
const length = Number.parseInt(Buffer$1.from(content.subarray(index, space)).toString("ascii"), 10);
|
|
269
|
-
if (!Number.isFinite(length) || length <= 0 || index + length > content.length) return;
|
|
270
|
-
const record = content.subarray(space + 1, index + length - 1);
|
|
271
|
-
const equals = record.indexOf(61);
|
|
272
|
-
if (equals !== -1 && Buffer$1.from(record.subarray(0, equals)).toString("utf8") === "path") return Buffer$1.from(record.subarray(equals + 1)).toString("utf8");
|
|
273
|
-
index += length;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
function stripArchiveRoot(path) {
|
|
277
|
-
const slash = path.indexOf("/");
|
|
278
|
-
if (slash === -1) return;
|
|
279
|
-
return normalizeSourcePath(path.slice(slash + 1));
|
|
280
|
-
}
|
|
281
|
-
//#endregion
|
|
282
|
-
//#region src/sources/github/cache.ts
|
|
283
|
-
function normalizeGitHubCache(options) {
|
|
284
|
-
if (options.cache === false) return;
|
|
285
|
-
if (options.cache && typeof options.cache === "object") return { maxAge: options.cache.maxAge };
|
|
286
|
-
}
|
|
287
|
-
function createGitHubCacheKey(input) {
|
|
288
|
-
return [
|
|
289
|
-
input.kind,
|
|
290
|
-
input.repo,
|
|
291
|
-
input.ref,
|
|
292
|
-
input.root,
|
|
293
|
-
normalizePatternCacheKey(input.include),
|
|
294
|
-
normalizePatternCacheKey(input.exclude),
|
|
295
|
-
input.token,
|
|
296
|
-
input.key || ""
|
|
297
|
-
].join(":");
|
|
298
|
-
}
|
|
299
|
-
function normalizePatternCacheKey(value) {
|
|
300
|
-
if (!value) return "";
|
|
301
|
-
return Array.isArray(value) ? value.join(",") : value;
|
|
302
|
-
}
|
|
303
|
-
//#endregion
|
|
304
|
-
//#region src/sources/github/client.ts
|
|
305
|
-
async function requestGitHubJson(input) {
|
|
306
|
-
const response = await fetch(input.url, {
|
|
307
|
-
headers: {
|
|
308
|
-
accept: "application/vnd.github+json",
|
|
309
|
-
...input.token ? { authorization: `Bearer ${input.token}` } : {},
|
|
310
|
-
"user-agent": "vitehub-source",
|
|
311
|
-
"x-github-api-version": "2022-11-28"
|
|
312
|
-
},
|
|
313
|
-
signal: input.signal
|
|
314
|
-
});
|
|
315
|
-
if (!response.ok) {
|
|
316
|
-
if (response.status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) could not access the repository or ref ${JSON.stringify(input.ref)}. Check that the repo exists, the ref exists, and auth can access it.`);
|
|
317
|
-
throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) request failed with ${response.status} for ${input.url}.`);
|
|
318
|
-
}
|
|
319
|
-
return await response.json();
|
|
320
|
-
}
|
|
321
|
-
async function fetchGitHubArchive(input) {
|
|
322
|
-
const response = await fetch(`https://codeload.github.com/${input.repo}/tar.gz/${encodeURIComponent(input.ref)}`, {
|
|
323
|
-
headers: {
|
|
324
|
-
...input.token ? { authorization: `Bearer ${input.token}` } : {},
|
|
325
|
-
"user-agent": "vitehub-source"
|
|
326
|
-
},
|
|
327
|
-
signal: input.signal
|
|
328
|
-
});
|
|
329
|
-
if (!response.ok) {
|
|
330
|
-
if (response.status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) could not access the repository or ref ${JSON.stringify(input.ref)}. Check that the repo exists and the ref exists.`);
|
|
331
|
-
throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) archive request failed with ${response.status}.`);
|
|
332
|
-
}
|
|
333
|
-
return new Uint8Array(await response.arrayBuffer());
|
|
334
|
-
}
|
|
335
|
-
//#endregion
|
|
336
|
-
//#region src/sources/github/git.ts
|
|
337
|
-
function createGitEnv(home, token, baseEnv = process.env) {
|
|
338
|
-
const env = { ...baseEnv };
|
|
339
|
-
for (const key of [
|
|
340
|
-
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
341
|
-
"GIT_COMMON_DIR",
|
|
342
|
-
"GIT_CONFIG",
|
|
343
|
-
"GIT_CONFIG_COUNT",
|
|
344
|
-
"GIT_CONFIG_PARAMETERS",
|
|
345
|
-
"GIT_DIR",
|
|
346
|
-
"GIT_GRAFT_FILE",
|
|
347
|
-
"GIT_IMPLICIT_WORK_TREE",
|
|
348
|
-
"GIT_INDEX_FILE",
|
|
349
|
-
"GIT_NO_REPLACE_OBJECTS",
|
|
350
|
-
"GIT_OBJECT_DIRECTORY",
|
|
351
|
-
"GIT_PREFIX",
|
|
352
|
-
"GIT_REPLACE_REF_BASE",
|
|
353
|
-
"GIT_SHALLOW_FILE",
|
|
354
|
-
"GIT_WORK_TREE"
|
|
355
|
-
]) delete env[key];
|
|
356
|
-
for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) delete env[key];
|
|
357
|
-
Object.assign(env, {
|
|
358
|
-
GCM_INTERACTIVE: "Never",
|
|
359
|
-
GIT_ASKPASS: "",
|
|
360
|
-
GIT_CONFIG_COUNT: token ? "1" : "0",
|
|
361
|
-
GIT_CONFIG_GLOBAL: devNull,
|
|
362
|
-
GIT_CONFIG_NOSYSTEM: "1",
|
|
363
|
-
GIT_TERMINAL_PROMPT: "0",
|
|
364
|
-
HOME: home,
|
|
365
|
-
SSH_ASKPASS: "",
|
|
366
|
-
USERPROFILE: home,
|
|
367
|
-
XDG_CONFIG_HOME: home
|
|
368
|
-
});
|
|
369
|
-
if (!token) return env;
|
|
370
|
-
const credential = Buffer$1.from(`x-access-token:${token}`).toString("base64");
|
|
371
|
-
env.GIT_CONFIG_KEY_0 = "http.https://github.com/.extraheader";
|
|
372
|
-
env.GIT_CONFIG_VALUE_0 = `AUTHORIZATION: basic ${credential}`;
|
|
373
|
-
return env;
|
|
374
|
-
}
|
|
375
|
-
async function runGit(args, options = {}) {
|
|
376
|
-
const { spawn } = await import("node:child_process");
|
|
377
|
-
return await new Promise((resolve, reject) => {
|
|
378
|
-
const child = spawn("git", args, {
|
|
379
|
-
env: options.env,
|
|
380
|
-
signal: options.signal,
|
|
381
|
-
stdio: [
|
|
382
|
-
"pipe",
|
|
383
|
-
"pipe",
|
|
384
|
-
"pipe"
|
|
385
|
-
]
|
|
386
|
-
});
|
|
387
|
-
const stdout = [];
|
|
388
|
-
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
389
|
-
child.stderr.resume();
|
|
390
|
-
child.stdin.on("error", () => {});
|
|
391
|
-
child.stdin.end();
|
|
392
|
-
child.on("error", reject);
|
|
393
|
-
child.on("close", (code) => {
|
|
394
|
-
if (code === 0) {
|
|
395
|
-
resolve(Buffer$1.concat(stdout));
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
const command = args[0] === "-C" ? args[2] : args[0];
|
|
399
|
-
reject(/* @__PURE__ */ new Error(`git ${command || "command"} exited with ${code ?? "an unknown status"}.`));
|
|
400
|
-
});
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
function isGitSparsePattern(pattern) {
|
|
404
|
-
if (pattern.includes("\0") || pattern.includes("\r") || pattern.includes("\n")) return false;
|
|
405
|
-
if (pattern.split("/").some((segment) => segment === "." || segment === "..")) return false;
|
|
406
|
-
if (!pattern.includes("*")) return !/[?[\]{}()!+@]/.test(pattern);
|
|
407
|
-
if (!pattern.endsWith("/**")) return false;
|
|
408
|
-
return !/[*?[\]{}()!+@]/.test(pattern.slice(0, -3));
|
|
409
|
-
}
|
|
410
|
-
function getGitSparsePatterns(root, include) {
|
|
411
|
-
const patterns = (include ? Array.isArray(include) ? include : [include] : []).map((pattern) => [root, normalizeSourcePath(pattern)].filter(Boolean).join("/")).filter(Boolean);
|
|
412
|
-
if (patterns.some((pattern) => !isGitSparsePattern(pattern))) return;
|
|
413
|
-
if (patterns.length) return [...new Set(patterns)];
|
|
414
|
-
return root && isGitSparsePattern(root) ? [`${root}/**`] : void 0;
|
|
415
|
-
}
|
|
416
|
-
function isGitLfsPointer(content) {
|
|
417
|
-
if (content.byteLength > 64 * 1024) return false;
|
|
418
|
-
const lines = Buffer$1.from(content).toString("utf8").split(/\r?\n/);
|
|
419
|
-
return lines[0] === "version https://git-lfs.github.com/spec/v1" && lines.some((line) => /^oid sha256:[0-9a-f]{64}$/.test(line)) && lines.some((line) => /^size \d+$/.test(line));
|
|
420
|
-
}
|
|
421
|
-
async function readGitArchiveFiles(dir, input, executeGit, options) {
|
|
422
|
-
input.signal?.throwIfAborted();
|
|
423
|
-
const archive = await executeGit([
|
|
424
|
-
"-C",
|
|
425
|
-
dir,
|
|
426
|
-
"archive",
|
|
427
|
-
"--format=tar.gz",
|
|
428
|
-
"--prefix=archive/",
|
|
429
|
-
input.sha,
|
|
430
|
-
"--",
|
|
431
|
-
...input.sparsePatterns.map((pattern) => {
|
|
432
|
-
return `:(literal)${pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern}`;
|
|
433
|
-
})
|
|
434
|
-
], options);
|
|
435
|
-
return parseGitHubArchive(Buffer$1.from(archive)).map((entry) => {
|
|
436
|
-
const key = input.keyForRepoPath(entry.path);
|
|
437
|
-
if (!key || !input.shouldInclude(key)) return;
|
|
438
|
-
if (isGitLfsPointer(entry.content)) throw new Error("git archive contained a Git LFS pointer; use the GitHub archive instead.");
|
|
439
|
-
return {
|
|
440
|
-
content: entry.content,
|
|
441
|
-
key,
|
|
442
|
-
path: key,
|
|
443
|
-
ref: input.ref,
|
|
444
|
-
sha: input.sha
|
|
445
|
-
};
|
|
446
|
-
}).filter((file) => Boolean(file));
|
|
447
|
-
}
|
|
448
|
-
async function loadGitArchiveFiles(input, executeGit = runGit) {
|
|
449
|
-
const [{ mkdtemp, rm }, { tmpdir }, { join }] = await Promise.all([
|
|
450
|
-
import("node:fs/promises"),
|
|
451
|
-
import("node:os"),
|
|
452
|
-
import("node:path")
|
|
453
|
-
]);
|
|
454
|
-
const dir = await mkdtemp(join(tmpdir(), "vitehub-github-"));
|
|
455
|
-
try {
|
|
456
|
-
const options = {
|
|
457
|
-
env: createGitEnv(dir, input.token, input.env),
|
|
458
|
-
signal: input.signal
|
|
459
|
-
};
|
|
460
|
-
await executeGit([
|
|
461
|
-
"init",
|
|
462
|
-
"--quiet",
|
|
463
|
-
dir
|
|
464
|
-
], options);
|
|
465
|
-
await executeGit([
|
|
466
|
-
"-C",
|
|
467
|
-
dir,
|
|
468
|
-
"remote",
|
|
469
|
-
"add",
|
|
470
|
-
"origin",
|
|
471
|
-
input.repositoryUrl || `https://github.com/${input.repo}.git`
|
|
472
|
-
], options);
|
|
473
|
-
await executeGit([
|
|
474
|
-
"-C",
|
|
475
|
-
dir,
|
|
476
|
-
"config",
|
|
477
|
-
"remote.origin.promisor",
|
|
478
|
-
"true"
|
|
479
|
-
], options);
|
|
480
|
-
await executeGit([
|
|
481
|
-
"-C",
|
|
482
|
-
dir,
|
|
483
|
-
"config",
|
|
484
|
-
"remote.origin.partialclonefilter",
|
|
485
|
-
"blob:none"
|
|
486
|
-
], options);
|
|
487
|
-
await executeGit([
|
|
488
|
-
"-C",
|
|
489
|
-
dir,
|
|
490
|
-
"fetch",
|
|
491
|
-
"--depth=1",
|
|
492
|
-
"--filter=blob:none",
|
|
493
|
-
"--no-tags",
|
|
494
|
-
"--",
|
|
495
|
-
"origin",
|
|
496
|
-
`+${input.ref}`
|
|
497
|
-
], options);
|
|
498
|
-
const sha = Buffer$1.from(await executeGit([
|
|
499
|
-
"-C",
|
|
500
|
-
dir,
|
|
501
|
-
"rev-parse",
|
|
502
|
-
"FETCH_HEAD"
|
|
503
|
-
], options)).toString("utf8").trim();
|
|
504
|
-
return await readGitArchiveFiles(dir, {
|
|
505
|
-
...input,
|
|
506
|
-
sha
|
|
507
|
-
}, executeGit, options);
|
|
508
|
-
} finally {
|
|
509
|
-
await rm(dir, {
|
|
510
|
-
force: true,
|
|
511
|
-
recursive: true
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
//#endregion
|
|
516
|
-
//#region src/sources/github/index.ts
|
|
517
|
-
function normalizeGitHubRoot(path = "") {
|
|
518
|
-
return normalizeSourcePath(path).split("/").filter((part) => part && part !== ".").join("/");
|
|
519
|
-
}
|
|
520
|
-
function dedupeProviderPromise(promises, key, load) {
|
|
521
|
-
const promise = promises.get(key);
|
|
522
|
-
if (promise) return promise;
|
|
523
|
-
const nextPromise = load().finally(() => {
|
|
524
|
-
promises.delete(key);
|
|
525
|
-
});
|
|
526
|
-
promises.set(key, nextPromise);
|
|
527
|
-
return nextPromise;
|
|
528
|
-
}
|
|
529
|
-
function github(options) {
|
|
530
|
-
const configuredRef = options.ref;
|
|
531
|
-
const root = normalizeGitHubRoot(options.root || "");
|
|
532
|
-
const sparsePatterns = getGitSparsePatterns(root, options.include);
|
|
533
|
-
let auth;
|
|
534
|
-
const providerCache = normalizeGitHubCache(options);
|
|
535
|
-
function resolveAuth() {
|
|
536
|
-
const token = typeof options.auth === "function" ? options.auth() : options.auth;
|
|
537
|
-
return typeof token === "string" && token.length > 0 ? token : void 0;
|
|
538
|
-
}
|
|
539
|
-
function refreshAuth() {
|
|
540
|
-
const nextAuth = resolveAuth();
|
|
541
|
-
if (nextAuth !== auth) auth = nextAuth;
|
|
542
|
-
return auth;
|
|
543
|
-
}
|
|
544
|
-
function keyForRepoPath(path) {
|
|
545
|
-
const normalized = normalizeSourcePath(path);
|
|
546
|
-
if (!root) return normalized;
|
|
547
|
-
if (!normalized.startsWith(`${root}/`)) return void 0;
|
|
548
|
-
return normalized.slice(root.length + 1);
|
|
549
|
-
}
|
|
550
|
-
function repoPathForKey(key) {
|
|
551
|
-
const normalized = normalizeSourcePath(key);
|
|
552
|
-
return root ? `${root}/${normalized}` : normalized;
|
|
553
|
-
}
|
|
554
|
-
function contentsUrl(repoPath, ref) {
|
|
555
|
-
return `https://api.github.com/repos/${options.repo}/contents/${encodeURIComponent(repoPath).replace(/%2F/g, "/")}?ref=${encodeURIComponent(ref)}`;
|
|
556
|
-
}
|
|
557
|
-
function shouldInclude(key) {
|
|
558
|
-
if (options.include && !matchesAny(key, options.include)) return false;
|
|
559
|
-
if (options.exclude && matchesAny(key, options.exclude)) return false;
|
|
560
|
-
return true;
|
|
561
|
-
}
|
|
562
|
-
async function resolveRef(token = auth, signal) {
|
|
563
|
-
if (configuredRef) return configuredRef;
|
|
564
|
-
try {
|
|
565
|
-
const defaultBranch = (await requestGitHubJson({
|
|
566
|
-
ref: "default",
|
|
567
|
-
repo: options.repo,
|
|
568
|
-
signal,
|
|
569
|
-
token,
|
|
570
|
-
url: `https://api.github.com/repos/${options.repo}`
|
|
571
|
-
})).default_branch || "main";
|
|
572
|
-
return (await requestGitHubJson({
|
|
573
|
-
ref: defaultBranch,
|
|
574
|
-
repo: options.repo,
|
|
575
|
-
signal,
|
|
576
|
-
token,
|
|
577
|
-
url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(defaultBranch)}`
|
|
578
|
-
})).sha || defaultBranch;
|
|
579
|
-
} catch (error) {
|
|
580
|
-
if (shouldResolveMainFallback(error)) return "main";
|
|
581
|
-
throw error;
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
function shouldResolveMainFallback(error) {
|
|
585
|
-
return isSourceError(error) && error instanceof Error && error.message.includes(" request failed with 403 ");
|
|
586
|
-
}
|
|
587
|
-
const resolvedRefs = /* @__PURE__ */ new Map();
|
|
588
|
-
const cachedResolveRef = providerCache ? defineCachedFunction(async (token) => await resolveRef(token), {
|
|
589
|
-
...providerCache,
|
|
590
|
-
getKey: (token) => cacheKey("ref", token || ""),
|
|
591
|
-
name: "github-source-ref"
|
|
592
|
-
}) : (token) => dedupeProviderPromise(resolvedRefs, cacheKey("ref", token || ""), () => resolveRef(token));
|
|
593
|
-
async function getRef(token = refreshAuth(), signal) {
|
|
594
|
-
return signal ? await resolveRef(token, signal) : await cachedResolveRef(token);
|
|
595
|
-
}
|
|
596
|
-
async function validateConfiguredRef(token = auth, signal) {
|
|
597
|
-
if (!configuredRef) return;
|
|
598
|
-
await requestGitHubJson({
|
|
599
|
-
ref: configuredRef,
|
|
600
|
-
repo: options.repo,
|
|
601
|
-
signal,
|
|
602
|
-
token,
|
|
603
|
-
url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(configuredRef)}`
|
|
604
|
-
});
|
|
605
|
-
}
|
|
606
|
-
async function loadArchiveFiles(token = auth, signal, resolvedRef) {
|
|
607
|
-
const ref = resolvedRef ?? await getRef(token, signal);
|
|
608
|
-
return parseGitHubArchive(await fetchGitHubArchive({
|
|
609
|
-
ref,
|
|
610
|
-
repo: options.repo,
|
|
611
|
-
signal,
|
|
612
|
-
token
|
|
613
|
-
})).map((entry) => {
|
|
614
|
-
const key = keyForRepoPath(entry.path);
|
|
615
|
-
if (!key || !shouldInclude(key)) return void 0;
|
|
616
|
-
return {
|
|
617
|
-
content: entry.content,
|
|
618
|
-
key,
|
|
619
|
-
path: key,
|
|
620
|
-
ref,
|
|
621
|
-
sha: ref
|
|
622
|
-
};
|
|
623
|
-
}).filter((file) => Boolean(file));
|
|
624
|
-
}
|
|
625
|
-
async function loadFiles(token = auth, signal) {
|
|
626
|
-
const ref = await getRef(token, signal);
|
|
627
|
-
if (sparsePatterns) try {
|
|
628
|
-
return await loadGitArchiveFiles({
|
|
629
|
-
keyForRepoPath,
|
|
630
|
-
ref,
|
|
631
|
-
repo: options.repo,
|
|
632
|
-
shouldInclude,
|
|
633
|
-
signal,
|
|
634
|
-
sparsePatterns,
|
|
635
|
-
token
|
|
636
|
-
});
|
|
637
|
-
} catch (error) {
|
|
638
|
-
if (signal?.aborted) throw error;
|
|
639
|
-
}
|
|
640
|
-
return await loadArchiveFiles(token, signal, ref);
|
|
641
|
-
}
|
|
642
|
-
const loadedFiles = /* @__PURE__ */ new Map();
|
|
643
|
-
const cachedLoadFiles = providerCache ? defineCachedFunction(async (token) => await loadFiles(token), {
|
|
644
|
-
...providerCache,
|
|
645
|
-
getKey: (token) => cacheKey("archive", token || ""),
|
|
646
|
-
name: "github-source-archive"
|
|
647
|
-
}) : (token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token || ""), () => loadFiles(token));
|
|
648
|
-
function getFiles(token = refreshAuth(), signal) {
|
|
649
|
-
return signal ? loadFiles(token, signal) : cachedLoadFiles(token);
|
|
650
|
-
}
|
|
651
|
-
async function loadFileMetadata(key, token = auth, signal) {
|
|
652
|
-
const normalizedKey = normalizeSourcePath(key);
|
|
653
|
-
if (!normalizedKey || !shouldInclude(normalizedKey)) return;
|
|
654
|
-
const ref = await getRef(token, signal);
|
|
655
|
-
const repoPath = repoPathForKey(normalizedKey);
|
|
656
|
-
let file;
|
|
657
|
-
try {
|
|
658
|
-
file = await requestGitHubJson({
|
|
659
|
-
ref,
|
|
660
|
-
repo: options.repo,
|
|
661
|
-
signal,
|
|
662
|
-
token,
|
|
663
|
-
url: contentsUrl(repoPath, ref)
|
|
664
|
-
});
|
|
665
|
-
} catch (error) {
|
|
666
|
-
if (isGitHubAccessError(error)) {
|
|
667
|
-
await validateConfiguredRef(token, signal);
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
if (shouldResolveMainFallback(error)) return (signal ? await loadArchiveFiles(token, signal, ref) : await getFiles(token)).find((file) => file.key === normalizedKey);
|
|
671
|
-
throw error;
|
|
672
|
-
}
|
|
673
|
-
if (!file || Array.isArray(file)) return;
|
|
674
|
-
if (file.type === "dir") return;
|
|
675
|
-
return {
|
|
676
|
-
key: normalizedKey,
|
|
677
|
-
path: normalizedKey,
|
|
678
|
-
ref,
|
|
679
|
-
sha: file.sha || ref
|
|
680
|
-
};
|
|
681
|
-
}
|
|
682
|
-
const loadedFileMetadata = /* @__PURE__ */ new Map();
|
|
683
|
-
const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, token) => await loadFileMetadata(key, token), {
|
|
684
|
-
...providerCache,
|
|
685
|
-
getKey: (key, token) => cacheKey("metadata", token || "", key),
|
|
686
|
-
name: "github-source-metadata"
|
|
687
|
-
}) : (key, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token || "", key), () => loadFileMetadata(key, token));
|
|
688
|
-
function isGitHubAccessError(error) {
|
|
689
|
-
return isSourceError(error) && error instanceof Error && error.message.includes(" could not access the repository or ref ");
|
|
690
|
-
}
|
|
691
|
-
async function loadFile(key, token = auth, signal) {
|
|
692
|
-
const normalizedKey = normalizeSourcePath(key);
|
|
693
|
-
if (!normalizedKey || !shouldInclude(normalizedKey)) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
694
|
-
const ref = await getRef(token, signal);
|
|
695
|
-
const repoPath = repoPathForKey(normalizedKey);
|
|
696
|
-
const file = await requestGitHubJson({
|
|
697
|
-
ref,
|
|
698
|
-
repo: options.repo,
|
|
699
|
-
signal,
|
|
700
|
-
token,
|
|
701
|
-
url: contentsUrl(repoPath, ref)
|
|
702
|
-
});
|
|
703
|
-
if (Array.isArray(file) || file.type === "dir") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) expected ${JSON.stringify(key)} to be a file, but it is a directory.`);
|
|
704
|
-
if (file.encoding !== "base64" || typeof file.content !== "string") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include file content for ${JSON.stringify(key)}.`);
|
|
705
|
-
return {
|
|
706
|
-
content: new Uint8Array(Buffer$1.from(file.content.replace(/\s/g, ""), "base64")),
|
|
707
|
-
key: normalizedKey,
|
|
708
|
-
path: normalizedKey,
|
|
709
|
-
ref,
|
|
710
|
-
sha: file.sha || ref
|
|
711
|
-
};
|
|
712
|
-
}
|
|
713
|
-
async function getFile(key, ctx, token = refreshAuth()) {
|
|
714
|
-
if (ctx?.abortSignal) return await loadFile(key, token, ctx.abortSignal);
|
|
715
|
-
const file = (await getFiles(token)).find((file) => file.key === key);
|
|
716
|
-
if (!file) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
|
|
717
|
-
return file;
|
|
718
|
-
}
|
|
719
|
-
function fetchContent(key, file) {
|
|
720
|
-
if (file.content) return Promise.resolve(file.content);
|
|
721
|
-
throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include archive content for ${JSON.stringify(key)}.`);
|
|
722
|
-
}
|
|
723
|
-
function cacheKey(kind, token, key = "") {
|
|
724
|
-
return createGitHubCacheKey({
|
|
725
|
-
exclude: options.exclude,
|
|
726
|
-
include: options.include,
|
|
727
|
-
key,
|
|
728
|
-
kind,
|
|
729
|
-
ref: configuredRef || "default",
|
|
730
|
-
repo: options.repo,
|
|
731
|
-
root,
|
|
732
|
-
token
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
return {
|
|
736
|
-
cache: options.cache,
|
|
737
|
-
fingerprint: {
|
|
738
|
-
exclude: options.exclude,
|
|
739
|
-
include: options.include,
|
|
740
|
-
ref: configuredRef || "default",
|
|
741
|
-
repo: options.repo,
|
|
742
|
-
root
|
|
743
|
-
},
|
|
744
|
-
name: "github",
|
|
745
|
-
async getKeys(ctx) {
|
|
746
|
-
return (await getFiles(refreshAuth(), ctx.abortSignal)).map((file) => file.key);
|
|
747
|
-
},
|
|
748
|
-
async getItems(ctx) {
|
|
749
|
-
const token = refreshAuth();
|
|
750
|
-
return await Promise.all((await getFiles(token, ctx.abortSignal)).map(async (file) => ({
|
|
751
|
-
key: file.key,
|
|
752
|
-
path: file.path,
|
|
753
|
-
content: await fetchContent(file.key, file),
|
|
754
|
-
metadata: {
|
|
755
|
-
ref: file.ref,
|
|
756
|
-
sha: file.sha
|
|
757
|
-
}
|
|
758
|
-
})));
|
|
759
|
-
},
|
|
760
|
-
async getMeta(key, ctx) {
|
|
761
|
-
const token = refreshAuth();
|
|
762
|
-
const file = ctx?.abortSignal ? await loadFileMetadata(key, token, ctx.abortSignal) : await cachedLoadFileMetadata(key, token);
|
|
763
|
-
if (!file) return;
|
|
764
|
-
return {
|
|
765
|
-
ref: file.ref,
|
|
766
|
-
sha: file.sha
|
|
767
|
-
};
|
|
768
|
-
},
|
|
769
|
-
async getItem(key, ctx) {
|
|
770
|
-
const file = await getFile(key, ctx, refreshAuth());
|
|
771
|
-
return {
|
|
772
|
-
key: file.key,
|
|
773
|
-
path: file.path,
|
|
774
|
-
content: await fetchContent(key, file),
|
|
775
|
-
metadata: {
|
|
776
|
-
ref: file.ref,
|
|
777
|
-
sha: file.sha
|
|
778
|
-
}
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
//#endregion
|
|
784
|
-
//#region src/sources/glob.ts
|
|
785
|
-
function glob(options) {
|
|
786
|
-
let snapshot;
|
|
787
|
-
let latest;
|
|
788
|
-
async function getContextKey(ctx) {
|
|
789
|
-
return resolveCwd(resolveSourceRoot(ctx), options.cwd);
|
|
790
|
-
}
|
|
791
|
-
async function loadKeys(ctx) {
|
|
792
|
-
const cwd = await resolveCwd(resolveSourceRoot(ctx), options.cwd);
|
|
793
|
-
const ignore = normalizePatterns(options.ignore);
|
|
794
|
-
return (await glob$1(options.include, {
|
|
795
|
-
cwd,
|
|
796
|
-
dot: options.dot ?? false,
|
|
797
|
-
followSymbolicLinks: options.followSymlinks ?? false,
|
|
798
|
-
ignore: [
|
|
799
|
-
"**/.git/**",
|
|
800
|
-
"**/node_modules/**",
|
|
801
|
-
...ignore
|
|
802
|
-
],
|
|
803
|
-
onlyFiles: true
|
|
804
|
-
})).map((file) => normalizeSourcePath(file)).filter((file) => matchesAny(file, options.include) && !matchesAny(file, ignore)).sort((left, right) => left.localeCompare(right));
|
|
805
|
-
}
|
|
806
|
-
async function refreshKeys(ctx) {
|
|
807
|
-
const key = await getContextKey(ctx);
|
|
808
|
-
const keys = await loadKeys(ctx);
|
|
809
|
-
latest = {
|
|
810
|
-
key,
|
|
811
|
-
keys
|
|
812
|
-
};
|
|
813
|
-
return keys;
|
|
814
|
-
}
|
|
815
|
-
async function getCachedKeys(ctx) {
|
|
816
|
-
if (options.keyCache === false) return await refreshKeys(ctx);
|
|
817
|
-
const key = await getContextKey(ctx);
|
|
818
|
-
if (!snapshot || snapshot.key !== key) {
|
|
819
|
-
const keys = refreshKeys(ctx);
|
|
820
|
-
const entry = {
|
|
821
|
-
key,
|
|
822
|
-
keys
|
|
823
|
-
};
|
|
824
|
-
snapshot = entry;
|
|
825
|
-
keys.catch(() => {
|
|
826
|
-
if (snapshot === entry) snapshot = void 0;
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
return await snapshot.keys;
|
|
830
|
-
}
|
|
831
|
-
async function getKnownKeys(ctx) {
|
|
832
|
-
const key = await getContextKey(ctx);
|
|
833
|
-
if (latest?.key === key) return latest.keys;
|
|
834
|
-
return await getCachedKeys(ctx);
|
|
835
|
-
}
|
|
836
|
-
async function assertKey(key, ctx) {
|
|
837
|
-
if ((await getKnownKeys(ctx)).includes(key)) return;
|
|
838
|
-
if (options.keyCache !== false) throw sourceError(`[vitehub] glob could not find ${JSON.stringify(key)}.`);
|
|
839
|
-
if ((await refreshKeys(ctx)).includes(key)) return;
|
|
840
|
-
throw sourceError(`[vitehub] glob could not find ${JSON.stringify(key)}.`);
|
|
841
|
-
}
|
|
842
|
-
return {
|
|
843
|
-
name: "glob",
|
|
844
|
-
async prepare(ctx) {
|
|
845
|
-
snapshot = void 0;
|
|
846
|
-
await getCachedKeys(ctx);
|
|
847
|
-
},
|
|
848
|
-
getKeys(ctx) {
|
|
849
|
-
return getCachedKeys(ctx);
|
|
850
|
-
},
|
|
851
|
-
async getMeta(key, ctx) {
|
|
852
|
-
await assertKey(key, ctx);
|
|
853
|
-
const { stat } = await import("node:fs/promises");
|
|
854
|
-
const { resolve } = await import("node:path");
|
|
855
|
-
const info = await stat(resolve(await resolveCwd(resolveSourceRoot(ctx), options.cwd), key));
|
|
856
|
-
return { digest: `${info.size}:${info.mtimeMs}` };
|
|
857
|
-
},
|
|
858
|
-
async getItem(key, ctx) {
|
|
859
|
-
await assertKey(key, ctx);
|
|
860
|
-
const { readFile, stat } = await import("node:fs/promises");
|
|
861
|
-
const { resolve } = await import("node:path");
|
|
862
|
-
const cwd = await resolveCwd(resolveSourceRoot(ctx), options.cwd);
|
|
863
|
-
const prefix = normalizeSafeSourcePath(options.prefix || "", { allowEmpty: true });
|
|
864
|
-
const bytes = await readFile(resolve(cwd, key));
|
|
865
|
-
const info = await stat(resolve(cwd, key));
|
|
866
|
-
return {
|
|
867
|
-
key,
|
|
868
|
-
path: normalizeSourcePath(prefix ? `${prefix}/${key}` : key),
|
|
869
|
-
content: new Uint8Array(bytes),
|
|
870
|
-
metadata: { mtime: info.mtimeMs }
|
|
871
|
-
};
|
|
872
|
-
}
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
function normalizePatterns(patterns) {
|
|
876
|
-
return Array.isArray(patterns) ? patterns : patterns ? [patterns] : [];
|
|
877
|
-
}
|
|
878
|
-
function resolveSourceRoot(ctx) {
|
|
879
|
-
return ctx.sourceRootDir || ctx.rootDir;
|
|
880
|
-
}
|
|
881
|
-
async function resolveCwd(rootDir, cwd = ".") {
|
|
882
|
-
const { realpath } = await import("node:fs/promises");
|
|
883
|
-
const { isAbsolute, relative, resolve } = await import("node:path");
|
|
884
|
-
const resolvedRoot = await realpath(resolve(rootDir));
|
|
885
|
-
const resolvedCwd = await realpath(isAbsolute(cwd) ? resolve(cwd) : resolve(resolvedRoot, cwd));
|
|
886
|
-
const rel = relative(resolvedRoot, resolvedCwd);
|
|
887
|
-
if (rel && (rel.startsWith("..") || isAbsolute(rel))) throw sourceError(`[vitehub] glob cwd escapes the source root: ${JSON.stringify(cwd)}.`);
|
|
888
|
-
return resolvedCwd;
|
|
889
|
-
}
|
|
890
|
-
//#endregion
|
|
891
|
-
//#region src/sources/markdown.ts
|
|
892
|
-
function markdown(options) {
|
|
893
|
-
return file({
|
|
894
|
-
...options,
|
|
895
|
-
mediaType: options.mediaType || "text/markdown"
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
//#endregion
|
|
899
|
-
//#region ../internal/src/effect.ts
|
|
900
|
-
var EffectBoundaryFailure = class extends Data.TaggedError("EffectBoundaryFailure") {};
|
|
901
|
-
function createEffectBoundary(options) {
|
|
902
|
-
function interruptionError(signal) {
|
|
903
|
-
if (signal?.aborted && signal.reason !== void 0) return signal.reason;
|
|
904
|
-
const error = new Error(options.interruptionMessage);
|
|
905
|
-
error.name = "AbortError";
|
|
906
|
-
return error;
|
|
907
|
-
}
|
|
908
|
-
function causeValues(cause, signal) {
|
|
909
|
-
return cause.reasons.map((reason) => {
|
|
910
|
-
if (Cause.isFailReason(reason)) return reason.error instanceof EffectBoundaryFailure ? reason.error.cause : reason.error;
|
|
911
|
-
if (Cause.isDieReason(reason)) return reason.defect;
|
|
912
|
-
return interruptionError(signal);
|
|
913
|
-
});
|
|
914
|
-
}
|
|
915
|
-
function tryPromise(evaluate) {
|
|
916
|
-
return Effect.tryPromise({
|
|
917
|
-
catch: (cause) => new EffectBoundaryFailure({ cause }),
|
|
918
|
-
try: (signal) => Promise.resolve(evaluate(signal))
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
async function run(effect, runOptions = {}) {
|
|
922
|
-
const exit = await Effect.runPromiseExit(effect, runOptions.signal ? { signal: runOptions.signal } : void 0);
|
|
923
|
-
if (Exit.isSuccess(exit)) return exit.value;
|
|
924
|
-
const causes = causeValues(exit.cause, runOptions.signal);
|
|
925
|
-
if (causes.length === 1) throw causes[0];
|
|
926
|
-
throw new AggregateError(causes, options.aggregateMessage);
|
|
927
|
-
}
|
|
928
|
-
function acquireWithCapturedRelease(scope, failures, acquire, release) {
|
|
929
|
-
return Scope.provide(Effect.acquireRelease(acquire, (resource, exit) => Effect.matchCauseEffect(release(resource, exit), {
|
|
930
|
-
onFailure: (cause) => Ref.update(failures, (current) => [...current, ...causeValues(cause)]),
|
|
931
|
-
onSuccess: () => Effect.void
|
|
932
|
-
})), scope);
|
|
933
|
-
}
|
|
934
|
-
return {
|
|
935
|
-
acquireWithCapturedRelease,
|
|
936
|
-
causeValues,
|
|
937
|
-
closeScopeWithCapturedReleases: Effect.fn("ViteHub.EffectBoundary.closeScope")(function* (scope, failures, closeOptions) {
|
|
938
|
-
yield* Scope.close(scope, closeOptions.exit ?? Exit.void);
|
|
939
|
-
const causes = yield* Ref.get(failures);
|
|
940
|
-
if (causes.length === 0) return;
|
|
941
|
-
const cause = causes.length === 1 ? causes[0] : new AggregateError(causes, closeOptions.aggregateMessage ?? options.aggregateMessage);
|
|
942
|
-
return yield* Effect.fail(new EffectBoundaryFailure({ cause }));
|
|
943
|
-
}),
|
|
944
|
-
run,
|
|
945
|
-
tryPromise
|
|
946
|
-
};
|
|
947
|
-
}
|
|
948
|
-
//#endregion
|
|
949
|
-
//#region src/sources/mcp-resources.ts
|
|
950
|
-
const mcpEffectBoundary = createEffectBoundary({
|
|
951
|
-
aggregateMessage: "[vitehub] MCP Resource Source operation failed for multiple reasons.",
|
|
952
|
-
interruptionMessage: "[vitehub] MCP Resource Source operation was interrupted."
|
|
953
|
-
});
|
|
954
|
-
function isMcpResourcesClient(value) {
|
|
955
|
-
return typeof value === "object" && value !== null && typeof value.listResources === "function" && typeof value.readResource === "function";
|
|
956
|
-
}
|
|
957
|
-
function isMcpResourcesClientConfig(value) {
|
|
958
|
-
return typeof value === "object" && value !== null && "transport" in value;
|
|
959
|
-
}
|
|
960
|
-
function isMcpTransport(value) {
|
|
961
|
-
return typeof value === "object" && value !== null && typeof value.close === "function" && typeof value.send === "function" && typeof value.start === "function";
|
|
962
|
-
}
|
|
963
|
-
async function createMcpTransport(config) {
|
|
964
|
-
if (isMcpTransport(config)) return config;
|
|
965
|
-
const { type = "http", url, ...options } = config;
|
|
966
|
-
if (type === "sse") {
|
|
967
|
-
const { SSEClientTransport } = await import("@modelcontextprotocol/sdk/client/sse.js");
|
|
968
|
-
return new SSEClientTransport(new URL(url), options);
|
|
969
|
-
}
|
|
970
|
-
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
971
|
-
return new StreamableHTTPClientTransport(new URL(url), options);
|
|
972
|
-
}
|
|
973
|
-
async function createMcpClient(config) {
|
|
974
|
-
const [{ Client }, transport] = await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"), createMcpTransport(config.transport)]);
|
|
975
|
-
return {
|
|
976
|
-
client: new Client({
|
|
977
|
-
name: "vitehub-source",
|
|
978
|
-
version: "0.0.1"
|
|
979
|
-
}),
|
|
980
|
-
transport
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
async function resolveMcpServer(server, ctx) {
|
|
984
|
-
const resolved = typeof server === "function" ? await server(ctx) : server;
|
|
985
|
-
if (isMcpResourcesClient(resolved) || isMcpResourcesClientConfig(resolved)) return resolved;
|
|
986
|
-
throw new TypeError("[vitehub] mcpResources({ server }) must resolve to an MCP client or MCP client config.");
|
|
987
|
-
}
|
|
988
|
-
function withRequestSignal(request, signal) {
|
|
989
|
-
return {
|
|
990
|
-
...request,
|
|
991
|
-
signal: request?.signal && request.signal !== signal ? AbortSignal.any([request.signal, signal]) : signal
|
|
992
|
-
};
|
|
993
|
-
}
|
|
994
|
-
async function withMcpClient(server, ctx, request, callback) {
|
|
995
|
-
const effect = Effect.flatMap(mcpEffectBoundary.tryPromise(() => resolveMcpServer(server, ctx)), (resolved) => {
|
|
996
|
-
if (isMcpResourcesClient(resolved)) return mcpEffectBoundary.tryPromise((signal) => callback(resolved, withRequestSignal(request, signal)));
|
|
997
|
-
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?.()));
|
|
998
|
-
});
|
|
999
|
-
return await mcpEffectBoundary.run(effect, { signal: ctx.abortSignal });
|
|
1000
|
-
}
|
|
1001
|
-
function extensionForMimeType(mimeType) {
|
|
1002
|
-
if (!mimeType) return;
|
|
1003
|
-
if (mimeType === "application/json") return "json";
|
|
1004
|
-
if (mimeType === "text/markdown") return "md";
|
|
1005
|
-
if (mimeType === "text/plain") return "txt";
|
|
1006
|
-
if (mimeType === "text/html") return "html";
|
|
1007
|
-
if (mimeType === "application/xml" || mimeType === "text/xml") return "xml";
|
|
1008
|
-
if (mimeType === "application/octet-stream") return "bin";
|
|
1009
|
-
}
|
|
1010
|
-
function normalizePathSegment(input) {
|
|
1011
|
-
return input.normalize("NFKD").replace(/\\/g, "/").replace(/[^\w./-]+/g, "-").replace(/\/+/g, "/").replace(/(^|\/)\.+(?=\/|$)/g, "").replace(/^-+|-+$/g, "");
|
|
1012
|
-
}
|
|
1013
|
-
function defaultResourcePath(resource) {
|
|
1014
|
-
let path = "";
|
|
1015
|
-
try {
|
|
1016
|
-
const url = new URL(resource.uri);
|
|
1017
|
-
const protocol = url.protocol.replace(/:$/, "");
|
|
1018
|
-
path = [url.hostname || url.host, decodeURIComponent(url.pathname).replace(/^\/+/, "") || resource.name || protocol].filter(Boolean).join("/");
|
|
1019
|
-
} catch {
|
|
1020
|
-
path = resource.name || resource.uri;
|
|
1021
|
-
}
|
|
1022
|
-
let normalized = normalizePathSegment(path);
|
|
1023
|
-
if (!normalized) normalized = normalizePathSegment(resource.name || resource.uri);
|
|
1024
|
-
const extension = extensionForMimeType(resource.mimeType);
|
|
1025
|
-
if (extension && !normalized.split("/").at(-1)?.includes(".")) normalized = `${normalized}.${extension}`;
|
|
1026
|
-
return normalizeSafeSourcePath(normalized);
|
|
1027
|
-
}
|
|
1028
|
-
function resourcePathNeedsContentMimeType(resource, options) {
|
|
1029
|
-
if (options.path || resource.mimeType) return false;
|
|
1030
|
-
return !defaultResourcePath(resource).split("/").at(-1)?.includes(".");
|
|
1031
|
-
}
|
|
1032
|
-
function resourceWithContentMimeType(resource, contents) {
|
|
1033
|
-
if (resource.mimeType) return resource;
|
|
1034
|
-
const content = contents.find((item) => item.uri === resource.uri) || contents[0];
|
|
1035
|
-
const mimeType = contents.length > 1 ? "application/json" : content?.mimeType;
|
|
1036
|
-
return mimeType ? {
|
|
1037
|
-
...resource,
|
|
1038
|
-
mimeType
|
|
1039
|
-
} : resource;
|
|
1040
|
-
}
|
|
1041
|
-
function resourceKey(resource, options) {
|
|
1042
|
-
return normalizeSafeSourcePath(options.path?.(resource) ?? defaultResourcePath(resource));
|
|
1043
|
-
}
|
|
1044
|
-
function shouldInclude(path, options) {
|
|
1045
|
-
if (options.include && !matchesAny(path, options.include)) return false;
|
|
1046
|
-
if (options.exclude && matchesAny(path, options.exclude)) return false;
|
|
1047
|
-
return true;
|
|
1048
|
-
}
|
|
1049
|
-
async function listAllResources(client, request) {
|
|
1050
|
-
const resources = [];
|
|
1051
|
-
let cursor;
|
|
1052
|
-
do {
|
|
1053
|
-
const page = await client.listResources(cursor ? { cursor } : void 0, request);
|
|
1054
|
-
resources.push(...page.resources);
|
|
1055
|
-
cursor = page.nextCursor;
|
|
1056
|
-
} while (cursor);
|
|
1057
|
-
return resources;
|
|
1058
|
-
}
|
|
1059
|
-
async function readResourceContents(client, resource, request) {
|
|
1060
|
-
return (await client.readResource({ uri: resource.uri }, request)).contents;
|
|
1061
|
-
}
|
|
1062
|
-
async function createEntries(resources, options, client) {
|
|
1063
|
-
const entries = [];
|
|
1064
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1065
|
-
for (const resource of resources) {
|
|
1066
|
-
let contents;
|
|
1067
|
-
let resolvedResource = resource;
|
|
1068
|
-
if (client && resourcePathNeedsContentMimeType(resource, options)) {
|
|
1069
|
-
contents = await readResourceContents(client, resource, options.request);
|
|
1070
|
-
resolvedResource = resourceWithContentMimeType(resource, contents);
|
|
1071
|
-
}
|
|
1072
|
-
const key = resourceKey(resolvedResource, options);
|
|
1073
|
-
if (!shouldInclude(key, options)) continue;
|
|
1074
|
-
const existingUri = seen.get(key);
|
|
1075
|
-
if (existingUri) throw sourceError(`[vitehub] mcpResources produced duplicate path ${JSON.stringify(key)} for ${JSON.stringify(existingUri)} and ${JSON.stringify(resource.uri)}.`);
|
|
1076
|
-
seen.set(key, resource.uri);
|
|
1077
|
-
entries.push({
|
|
1078
|
-
contents,
|
|
1079
|
-
key,
|
|
1080
|
-
resource: resolvedResource
|
|
1081
|
-
});
|
|
1082
|
-
}
|
|
1083
|
-
return entries;
|
|
1084
|
-
}
|
|
1085
|
-
function decodeBase64(value) {
|
|
1086
|
-
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(value, "base64"));
|
|
1087
|
-
const binary = atob(value);
|
|
1088
|
-
const bytes = new Uint8Array(binary.length);
|
|
1089
|
-
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
1090
|
-
return bytes;
|
|
1091
|
-
}
|
|
1092
|
-
function contentToSourceContent(content) {
|
|
1093
|
-
if ("text" in content && typeof content.text === "string") return content.text;
|
|
1094
|
-
if ("blob" in content && typeof content.blob === "string") return decodeBase64(content.blob);
|
|
1095
|
-
return "";
|
|
1096
|
-
}
|
|
1097
|
-
function createResourceItem(key, resource, contents) {
|
|
1098
|
-
const content = contents.find((item) => item.uri === resource.uri) || contents[0];
|
|
1099
|
-
if (!content) throw sourceError(`[vitehub] mcpResources could not read resource ${JSON.stringify(resource.uri)}.`);
|
|
1100
|
-
const multipleContents = contents.length > 1;
|
|
1101
|
-
return {
|
|
1102
|
-
key,
|
|
1103
|
-
path: key,
|
|
1104
|
-
content: multipleContents ? JSON.stringify(contents, null, 2) : contentToSourceContent(content),
|
|
1105
|
-
mediaType: multipleContents ? "application/json" : content.mimeType || resource.mimeType,
|
|
1106
|
-
metadata: {
|
|
1107
|
-
description: resource.description,
|
|
1108
|
-
name: resource.name,
|
|
1109
|
-
serverResourceCount: contents.length,
|
|
1110
|
-
size: resource.size,
|
|
1111
|
-
title: resource.title,
|
|
1112
|
-
uri: resource.uri
|
|
1113
|
-
}
|
|
1114
|
-
};
|
|
1115
|
-
}
|
|
1116
|
-
function mcpResources(options) {
|
|
1117
|
-
if (!options || typeof options !== "object" || !options.server) throw new TypeError("[vitehub] mcpResources({ server }) requires an MCP server.");
|
|
1118
|
-
async function getEntries(ctx) {
|
|
1119
|
-
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
1120
|
-
return await createEntries(await listAllResources(client, request), {
|
|
1121
|
-
...options,
|
|
1122
|
-
request
|
|
1123
|
-
}, client);
|
|
1124
|
-
});
|
|
1125
|
-
}
|
|
1126
|
-
async function getItems(ctx) {
|
|
1127
|
-
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
1128
|
-
const scopedOptions = {
|
|
1129
|
-
...options,
|
|
1130
|
-
request
|
|
1131
|
-
};
|
|
1132
|
-
const entries = await createEntries(await listAllResources(client, request), scopedOptions, client);
|
|
1133
|
-
return await Promise.all(entries.map(async ({ contents, key, resource }) => {
|
|
1134
|
-
return createResourceItem(key, resource, contents ?? await readResourceContents(client, resource, request));
|
|
1135
|
-
}));
|
|
1136
|
-
});
|
|
1137
|
-
}
|
|
1138
|
-
return {
|
|
1139
|
-
cache: options.cache,
|
|
1140
|
-
fingerprint: {
|
|
1141
|
-
exclude: options.exclude,
|
|
1142
|
-
include: options.include,
|
|
1143
|
-
server: typeof options.server === "function" ? "[function]" : isMcpResourcesClient(options.server) ? {
|
|
1144
|
-
client: true,
|
|
1145
|
-
serverInfo: options.server.serverInfo
|
|
1146
|
-
} : options.server
|
|
1147
|
-
},
|
|
1148
|
-
name: "mcpResources",
|
|
1149
|
-
async getKeys(ctx) {
|
|
1150
|
-
return (await getEntries(ctx)).map((entry) => entry.key);
|
|
1151
|
-
},
|
|
1152
|
-
async getItems(ctx) {
|
|
1153
|
-
return await getItems(ctx);
|
|
1154
|
-
},
|
|
1155
|
-
async getMeta(key, ctx) {
|
|
1156
|
-
const entry = (await getEntries(ctx)).find((entry) => entry.key === key);
|
|
1157
|
-
if (!entry) return;
|
|
1158
|
-
return {
|
|
1159
|
-
description: entry.resource.description,
|
|
1160
|
-
mimeType: entry.resource.mimeType,
|
|
1161
|
-
name: entry.resource.name,
|
|
1162
|
-
size: entry.resource.size,
|
|
1163
|
-
title: entry.resource.title,
|
|
1164
|
-
uri: entry.resource.uri
|
|
1165
|
-
};
|
|
1166
|
-
},
|
|
1167
|
-
async getItem(key, ctx) {
|
|
1168
|
-
return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
|
|
1169
|
-
const entry = (await createEntries(await listAllResources(client, request), {
|
|
1170
|
-
...options,
|
|
1171
|
-
request
|
|
1172
|
-
}, client)).find((entry) => entry.key === key);
|
|
1173
|
-
if (!entry) throw sourceError(`[vitehub] mcpResources could not find ${JSON.stringify(key)}.`);
|
|
1174
|
-
const result = entry.contents ?? await readResourceContents(client, entry.resource, request);
|
|
1175
|
-
return createResourceItem(key, entry.resource, result);
|
|
1176
|
-
});
|
|
1177
|
-
},
|
|
1178
|
-
async search(query, ctx) {
|
|
1179
|
-
const pattern = query.regex ? new RegExp(query.pattern, query.caseSensitive ? "g" : "gi") : void 0;
|
|
1180
|
-
const search = query.caseSensitive ? query.pattern : query.pattern.toLowerCase();
|
|
1181
|
-
const results = [];
|
|
1182
|
-
for (const item of await getItems(ctx)) {
|
|
1183
|
-
if (typeof item.content !== "string") continue;
|
|
1184
|
-
if (query.paths?.length && !query.paths.some((path) => item.path && normalizeSourcePath(item.path).startsWith(normalizeSourcePath(path)))) continue;
|
|
1185
|
-
const lines = item.content.split(/\r?\n/);
|
|
1186
|
-
for (const [index, line] of lines.entries()) {
|
|
1187
|
-
const matchIndex = pattern ? line.search(pattern) : (query.caseSensitive ? line : line.toLowerCase()).indexOf(search);
|
|
1188
|
-
if (matchIndex === -1) continue;
|
|
1189
|
-
results.push({
|
|
1190
|
-
column: matchIndex + 1,
|
|
1191
|
-
line: index + 1,
|
|
1192
|
-
path: item.path || item.key,
|
|
1193
|
-
text: line
|
|
1194
|
-
});
|
|
1195
|
-
if (query.limit && results.length >= query.limit) return results;
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
return results;
|
|
1199
|
-
}
|
|
1200
|
-
};
|
|
1201
|
-
}
|
|
1202
|
-
//#endregion
|
|
1203
|
-
export { clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, useSource };
|
|
81
|
+
export { CollectionCursorError, clearSources, combineSources, createSource, custom, defineCollection, defineSource, defineSources, getRegisteredSource, registerSource, registerSources, sourceIgnores, useSource };
|