@vite-hub/source 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +302 -31
  3. package/dist/auth-B-tX_rp0.js +1426 -0
  4. package/dist/client-BwstxtdY.js +8280 -0
  5. package/dist/client.d.ts +49 -0
  6. package/dist/client.js +179 -0
  7. package/dist/collection-B_4w_J8h.d.ts +257 -0
  8. package/dist/collection-cursor-WzV1Jd6v.js +124 -0
  9. package/dist/collection-route-BplWPxHR.js +10 -0
  10. package/dist/drizzle.d.ts +41 -0
  11. package/dist/drizzle.js +89 -0
  12. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  13. package/dist/file-BX0FSvgE.js +60 -0
  14. package/dist/file-DadN9dbN.d.ts +19 -0
  15. package/dist/file.d.ts +2 -0
  16. package/dist/file.js +2 -0
  17. package/dist/files.d.ts +15 -0
  18. package/dist/files.js +38 -0
  19. package/dist/github.d.ts +20 -0
  20. package/dist/github.js +1332 -0
  21. package/dist/glob-BmFqTvJY.js +993 -0
  22. package/dist/glob.d.ts +23 -0
  23. package/dist/glob.js +2 -0
  24. package/dist/index.d.ts +165 -172
  25. package/dist/index.js +600 -1113
  26. package/dist/markdown.d.ts +5 -0
  27. package/dist/markdown.js +10 -0
  28. package/dist/mcp.d.ts +151 -0
  29. package/dist/mcp.js +497 -0
  30. package/dist/mrmime-40h5OOIp.js +448 -0
  31. package/dist/path-BS8rYm0n.js +1956 -0
  32. package/dist/path-DOBpV8ol.js +32 -0
  33. package/dist/server.d.ts +265 -0
  34. package/dist/server.js +149 -0
  35. package/dist/sse-D9gqqNPj.js +448 -0
  36. package/dist/streamableHttp-BL-E7pl5.js +509 -0
  37. package/dist/types-BigOktIj.d.ts +93 -0
  38. package/dist/types-CoWcW8oz.js +7590 -0
  39. package/dist/vite.d.ts +162 -0
  40. package/dist/vite.js +2284 -0
  41. package/package.json +102 -17
  42. package/tsconfig.vite.json +6 -0
  43. package/types/source/fallback.d.ts +1 -0
  44. package/types/source/index.d.ts +1 -0
package/dist/index.js CHANGED
@@ -1,82 +1,534 @@
1
- import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
2
- import picomatch from "picomatch";
3
- import { isAbsolute } from "pathe";
4
- import { lookup } from "mrmime";
5
- import { Buffer as Buffer$1 } from "node:buffer";
6
- import { defineCachedFunction } from "ocache";
7
- import { gunzipSync } from "node:zlib";
8
- import { devNull } from "node:os";
9
- import { glob as glob$1 } from "tinyglobby";
10
- import { Cause, Data, Effect, Exit, Ref, Scope } from "effect";
11
- //#region src/core/define.ts
12
- function defineSource(source) {
13
- return source;
14
- }
15
- function defineSources(sources) {
16
- return sources;
17
- }
18
- //#endregion
19
- //#region src/core/errors.ts
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 } });
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
2
+ import { n as createCollectionCursorCodec, r as parseCollectionSchema, t as CollectionCursorError } from "./collection-cursor-WzV1Jd6v.js";
3
+ import { a as sourceNotFoundError, i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath, t as decodeSourceContent } from "./path-DOBpV8ol.js";
4
+ //#region src/core/array-collection.ts
5
+ const defaultMaxLimit$1 = 100;
6
+ const reservedQueryKeys = /* @__PURE__ */ new Set([
7
+ "cursor",
8
+ "empty",
9
+ "limit",
10
+ "search"
11
+ ]);
12
+ function compareProtocolStrings(left, right) {
13
+ return left < right ? -1 : left > right ? 1 : 0;
14
+ }
15
+ const cursorCodec = createCollectionCursorCodec({ "~standard": {
16
+ version: 1,
17
+ vendor: "vite-hub",
18
+ validate(value) {
19
+ const cursor = Object(value);
20
+ const digest = Reflect.get(cursor, "digest");
21
+ const offset = Reflect.get(cursor, "offset");
22
+ const query = Reflect.get(cursor, "query");
23
+ if (Object(value) !== value || String(digest) !== digest || String(query) !== query || !Number.isSafeInteger(offset) || Number(offset) < 0 || Reflect.ownKeys(cursor).length !== 3) return { issues: [{ message: "Array Collection cursor is malformed." }] };
24
+ return { value: {
25
+ digest: String(digest),
26
+ offset: Number(offset),
27
+ query: String(query)
28
+ } };
29
+ }
30
+ } });
31
+ function isRecord(value) {
32
+ return Object(value) === value && !Array.isArray(value);
33
+ }
34
+ /** Read a dot path through own properties. Arrays fan out to every element. */
35
+ function collectionValueAt(value, path) {
36
+ const segments = path.split(".").filter(Boolean);
37
+ function visit(current, remaining) {
38
+ if (!remaining.length) return current;
39
+ if (Array.isArray(current)) return current.map((item) => visit(item, remaining)).filter((item) => item !== void 0);
40
+ if (!isRecord(current)) return;
41
+ const segment = remaining[0];
42
+ if (!Object.hasOwn(current, segment)) return;
43
+ return visit(current[segment], remaining.slice(1));
44
+ }
45
+ return visit(value, segments);
46
+ }
47
+ function dateTime(value) {
48
+ if (Object.prototype.toString.call(value) !== "[object Date]") return;
49
+ const time = Date.prototype.getTime.call(value);
50
+ return Number.isNaN(time) ? void 0 : time;
51
+ }
52
+ function scalarValues(value) {
53
+ if (Array.isArray(value)) return value.flatMap(scalarValues);
54
+ const time = dateTime(value);
55
+ if (time !== void 0) return [new Date(time).toISOString()];
56
+ if (value === null || value === void 0 || Object(value) === value) return [];
57
+ return [String(value)];
58
+ }
59
+ function firstScalar(value) {
60
+ const entry = Array.isArray(value) ? value.flat(Infinity).find((item) => item !== null && item !== void 0 && (Object(item) !== item || dateTime(item) !== void 0)) : value;
61
+ return dateTime(entry) ?? entry;
62
+ }
63
+ function isString(value) {
64
+ return String(value) === value;
65
+ }
66
+ function stringList(value) {
67
+ return (Array.isArray(value) ? value : [value]).filter((entry) => String(entry) === entry);
68
+ }
69
+ async function sha256(value) {
70
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
71
+ return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ }
73
+ function assertFieldList(label, fields) {
74
+ if (fields === void 0) return;
75
+ if (!Array.isArray(fields) || fields.some((field) => String(field) !== field || !field)) throw sourceErrorDiagnostics.SOURCE_R0028({ message: `[vitehub] array() ${label} must be a list of field paths.` });
76
+ }
77
+ function normalizeQuery(query) {
78
+ const normalized = {
79
+ empty: [],
80
+ filters: Object.create(null),
81
+ search: ""
82
+ };
83
+ for (const [key, value] of Object.entries(query).sort(([a], [b]) => compareProtocolStrings(a, b))) {
84
+ if (value === void 0 || value === null) continue;
85
+ if (key === "search") {
86
+ normalized.search = String(value).trim().toLocaleLowerCase();
87
+ continue;
88
+ }
89
+ if (key === "empty") {
90
+ normalized.empty = [...new Set(stringList(value))].sort();
91
+ continue;
92
+ }
93
+ const values = stringList(value).map((entry) => entry.toLocaleLowerCase());
94
+ if (values.length) normalized.filters[key] = [...new Set(values)].sort();
95
+ }
96
+ return normalized;
25
97
  }
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 } });
98
+ function matches(item, query, searchFields) {
99
+ for (const [field, expected] of Object.entries(query.filters)) {
100
+ const values = scalarValues(collectionValueAt(item, field)).map((value) => value.toLocaleLowerCase());
101
+ if (!expected.some((candidate) => values.includes(candidate))) return false;
102
+ }
103
+ for (const field of query.empty) if (scalarValues(collectionValueAt(item, field)).length) return false;
104
+ if (query.search) return searchFields.some((field) => scalarValues(collectionValueAt(item, field)).some((value) => value.toLocaleLowerCase().includes(query.search)));
105
+ return true;
29
106
  }
30
- function isSourceError(value) {
31
- const code = getViteHubErrorShape(value)?.code;
32
- return code === "SOURCE_FAILED" || code === "SOURCE_NOT_FOUND" || code === "SOURCE_PATH_INVALID";
107
+ function sortItems(items, sort) {
108
+ if (!sort) return items;
109
+ const direction = sort.direction === "desc" ? -1 : 1;
110
+ return items.map((item) => ({
111
+ item,
112
+ value: firstScalar(collectionValueAt(item, sort.field))
113
+ })).sort(({ value: leftValue }, { value: rightValue }) => {
114
+ if (Number(leftValue) === leftValue && Number(rightValue) === rightValue) return (leftValue - rightValue) * direction;
115
+ return String(leftValue ?? "").localeCompare(String(rightValue ?? "")) * direction;
116
+ }).map(({ item }) => item);
117
+ }
118
+ function buildFacets(items, fields, maxValues) {
119
+ return Object.fromEntries(fields.map((field) => {
120
+ const counts = /* @__PURE__ */ new Map();
121
+ for (const item of items) for (const value of new Set(scalarValues(collectionValueAt(item, field)))) counts.set(value, (counts.get(value) ?? 0) + 1);
122
+ return [field, [...counts].map(([value, count]) => ({
123
+ count,
124
+ value
125
+ })).sort((left, right) => right.count - left.count || left.value.localeCompare(right.value)).slice(0, maxValues)];
126
+ }));
127
+ }
128
+ function array(load, options = {}) {
129
+ assertFieldList("filters", options.filters);
130
+ assertFieldList("search", options.search);
131
+ assertFieldList("facets", options.facets);
132
+ const reserved = options.filters?.find((field) => reservedQueryKeys.has(field));
133
+ if (reserved) throw sourceErrorDiagnostics.SOURCE_R0028({ message: `[vitehub] array() filter ${JSON.stringify(reserved)} collides with a reserved query key.` });
134
+ if (options.sort !== void 0 && (!isRecord(options.sort) || String(options.sort.field) !== options.sort.field || !options.sort.field)) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() sort must name a field." });
135
+ const filters = new Set(options.filters ?? []);
136
+ const isFilter = (key) => filters.has(key);
137
+ const searchFields = options.search ?? [];
138
+ const facetFields = options.facets ?? [];
139
+ const maxValues = options.maxLimit ?? defaultMaxLimit$1;
140
+ const signatureFields = JSON.stringify({
141
+ search: [...searchFields].sort(),
142
+ sort: options.sort ? {
143
+ direction: options.sort.direction ?? "asc",
144
+ field: options.sort.field
145
+ } : null
146
+ });
147
+ async function snapshot(signal, includeDigest) {
148
+ const result = typeof load === "function" ? await load({ signal }) : load;
149
+ signal?.throwIfAborted();
150
+ const items = Array.isArray(result) ? result : Reflect.get(Object(result), "items");
151
+ if (!Array.isArray(items)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() load must return an array or { items, digest }." });
152
+ const digest = Array.isArray(result) ? void 0 : Reflect.get(Object(result), "digest");
153
+ if (digest !== void 0 && (String(digest) !== digest || !digest)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() digest must be a non-empty string." });
154
+ const contentDigest = includeDigest ? String(digest ?? await sha256(JSON.stringify(items))) : "";
155
+ const schema = options.schema;
156
+ if (schema) return {
157
+ digest: contentDigest,
158
+ items: await Promise.all(items.map(async (item, index) => {
159
+ try {
160
+ return await parseCollectionSchema(schema, item);
161
+ } catch (cause) {
162
+ throw sourceErrorDiagnostics.SOURCE_R0006({
163
+ cause,
164
+ message: `[vitehub] array() item ${index} does not match its schema: ${cause instanceof Error ? cause.message : String(cause)}`
165
+ });
166
+ }
167
+ }))
168
+ };
169
+ return {
170
+ digest: contentDigest,
171
+ items
172
+ };
173
+ }
174
+ const source = {
175
+ defaultLimit: options.defaultLimit,
176
+ maxLimit: options.maxLimit,
177
+ pagination: "provider",
178
+ querySchema: { "~standard": {
179
+ version: 1,
180
+ vendor: "vite-hub",
181
+ validate(value) {
182
+ if (!isRecord(value)) return { issues: [{ message: "Collection query must be an object." }] };
183
+ const filterValues = Object.create(null);
184
+ let empty;
185
+ let search;
186
+ for (const [key, raw] of Object.entries(value)) {
187
+ if (raw === void 0 || raw === null) continue;
188
+ const values = Array.isArray(raw) ? raw : [raw];
189
+ if (!values.every(isString)) return { issues: [{ message: `Collection query ${JSON.stringify(key)} must be a string.` }] };
190
+ if (key === "search") {
191
+ if (values.length !== 1) return { issues: [{ message: "Collection search must have one value." }] };
192
+ if (values[0] && !searchFields.length) return { issues: [{ message: "Collection search is not enabled." }] };
193
+ search = values[0];
194
+ continue;
195
+ }
196
+ if (key === "empty") {
197
+ const unknown = values.find((field) => !isFilter(field));
198
+ if (unknown !== void 0) return { issues: [{ message: `Collection filter ${JSON.stringify(unknown)} is not allowed.` }] };
199
+ empty = values.filter(isFilter);
200
+ continue;
201
+ }
202
+ if (!isFilter(key)) return { issues: [{ message: `Collection query parameter ${JSON.stringify(key)} is not allowed.` }] };
203
+ filterValues[key] = values.map((entry) => entry.trim());
204
+ }
205
+ const parsed = { ...filterValues };
206
+ if (empty) parsed.empty = empty;
207
+ if (search !== void 0) parsed.search = search;
208
+ return { value: parsed };
209
+ }
210
+ } },
211
+ async load({ cursor, limit, query, signal }) {
212
+ const { digest, items } = await snapshot(signal, true);
213
+ const normalized = normalizeQuery(query);
214
+ const matching = sortItems(items.filter((item) => matches(item, normalized, searchFields)), options.sort);
215
+ const signature = await sha256(`${signatureFields}\n${JSON.stringify(normalized)}`);
216
+ const decoded = await cursorCodec.decode(cursor);
217
+ if (decoded && (decoded.digest !== digest || decoded.query !== signature)) throw new CollectionCursorError(void 0, { reason: "stale" });
218
+ const offset = decoded?.offset ?? 0;
219
+ if (offset > matching.length) throw new CollectionCursorError();
220
+ const pageItems = matching.slice(offset, offset + limit);
221
+ const nextOffset = offset + pageItems.length;
222
+ const page = {
223
+ items: pageItems,
224
+ nextCursor: nextOffset < matching.length ? cursorCodec.encode({
225
+ digest,
226
+ offset: nextOffset,
227
+ query: signature
228
+ }) : null,
229
+ total: matching.length
230
+ };
231
+ if (facetFields.length) page.facets = buildFacets(matching, facetFields, maxValues);
232
+ return page;
233
+ }
234
+ };
235
+ const key = options.key;
236
+ if (key !== void 0) {
237
+ if (String(key) !== key || !key) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() key must be a field path." });
238
+ source.get = async (value, { signal }) => {
239
+ const { items } = await snapshot(signal, false);
240
+ return items.find((item) => scalarValues(collectionValueAt(item, key)).includes(value)) ?? null;
241
+ };
242
+ }
243
+ return source;
33
244
  }
34
245
  //#endregion
35
- //#region src/core/path.ts
36
- function normalizeSourcePath(path = "") {
37
- return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
38
- }
39
- function normalizeSafeSourcePath(path = "", options = {}) {
40
- const raw = path.replace(/\\/g, "/");
41
- const normalized = normalizeSourcePath(path);
42
- const parts = normalized.split("/").filter(Boolean);
43
- if (!options.allowEmpty && !normalized) throw sourcePathError(path);
44
- if (isAbsolute(raw) || parts.some((part) => part === "." || part === "..")) throw sourcePathError(path);
45
- if (!options.allowReserved && (parts[0] === ".git" || parts[0] === ".vitehub")) throw sourcePathError(path);
46
- return normalized;
246
+ //#region src/core/collection.ts
247
+ const defaultPageLimit = 50;
248
+ const defaultMaxLimit = 100;
249
+ function isCollectionFacets(value) {
250
+ return Object(value) === value && !Array.isArray(value) && Object.values(Object(value)).every((entries) => Array.isArray(entries) && entries.every((entry) => Object(entry) === entry && String(Reflect.get(entry, "value")) === Reflect.get(entry, "value") && Number.isSafeInteger(Reflect.get(entry, "count")) && Number(Reflect.get(entry, "count")) >= 0));
251
+ }
252
+ function assertPositiveInteger(value, label) {
253
+ if (!Number.isSafeInteger(value) || value < 1) throw sourceErrorDiagnostics.SOURCE_R0004({ message: `[vitehub] Collection ${label} must be a positive integer.` });
254
+ }
255
+ function resolveLimit(limit, defaultLimit, maxLimit) {
256
+ if (limit !== void 0) assertPositiveInteger(limit, "limit");
257
+ return Math.min(limit ?? defaultLimit, maxLimit);
258
+ }
259
+ function defineCollection(input, options) {
260
+ const [load, definition] = typeof input === "function" ? [input, options] : sourceDefinition(input);
261
+ if (!definition) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] defineCollection() requires a loader with options, or { source }." });
262
+ const defaultLimit = definition.defaultLimit ?? defaultPageLimit;
263
+ const maxLimit = definition.maxLimit ?? defaultMaxLimit;
264
+ assertPositiveInteger(defaultLimit, "defaultLimit");
265
+ assertPositiveInteger(maxLimit, "maxLimit");
266
+ if (defaultLimit > maxLimit) throw sourceErrorDiagnostics.SOURCE_R0008({ message: "[vitehub] Collection defaultLimit cannot exceed maxLimit." });
267
+ const cursorDefinition = "cursorSchema" in definition ? definition : void 0;
268
+ const cursorCodec = cursorDefinition ? createCollectionCursorCodec(cursorDefinition.cursorSchema) : void 0;
269
+ const authorize = definition.authorize;
270
+ if (authorize !== void 0 && authorize !== true && typeof authorize !== "function") throw sourceErrorDiagnostics.SOURCE_R0024({ message: "[vitehub] Collection authorize must be true or a function." });
271
+ const collection = {
272
+ ...authorize ? { authorize } : {},
273
+ route: definition.route,
274
+ async page(request) {
275
+ request.signal?.throwIfAborted();
276
+ const limit = resolveLimit(request.limit, defaultLimit, maxLimit);
277
+ if (!cursorDefinition || !cursorCodec) {
278
+ const result = await load({
279
+ cursor: request.cursor,
280
+ limit,
281
+ query: request.query,
282
+ signal: request.signal
283
+ });
284
+ request.signal?.throwIfAborted();
285
+ if (!result || !Array.isArray(result.items) || result.nextCursor !== null && !isProviderCursor(result.nextCursor)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection load() must return items and nextCursor." });
286
+ const transformedItems = definition.transform ? await Promise.all(result.items.map(definition.transform)) : result.items;
287
+ request.signal?.throwIfAborted();
288
+ const page = {
289
+ items: transformedItems,
290
+ nextCursor: result.nextCursor
291
+ };
292
+ if (result.total !== void 0) {
293
+ if (!Number.isSafeInteger(result.total) || result.total < 0) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection total must be a non-negative integer." });
294
+ page.total = result.total;
295
+ }
296
+ if (result.facets !== void 0) {
297
+ if (!isCollectionFacets(result.facets)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection facets must map fields to { value, count } lists." });
298
+ page.facets = result.facets;
299
+ }
300
+ return page;
301
+ }
302
+ const decodedCursor = await cursorCodec.decode(request.cursor);
303
+ request.signal?.throwIfAborted();
304
+ const sourceItems = await load({
305
+ cursor: decodedCursor,
306
+ limit: limit + 1,
307
+ query: request.query,
308
+ signal: request.signal
309
+ });
310
+ request.signal?.throwIfAborted();
311
+ if (!Array.isArray(sourceItems)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Collection load() must return an array." });
312
+ const hasMore = sourceItems.length > limit;
313
+ const pageItems = sourceItems.slice(0, limit);
314
+ const nextCursor = hasMore && pageItems.length ? cursorCodec.encode(cursorDefinition.cursor(pageItems[pageItems.length - 1])) : null;
315
+ const transformedItems = definition.transform ? await Promise.all(pageItems.map(definition.transform)) : pageItems;
316
+ request.signal?.throwIfAborted();
317
+ return {
318
+ items: transformedItems,
319
+ nextCursor
320
+ };
321
+ },
322
+ async parseQuery(input) {
323
+ if (definition.querySchema) return await parseCollectionSchema(definition.querySchema, input);
324
+ return input;
325
+ },
326
+ query(input = {}) {
327
+ const project = (item, keys) => keys ? Object.fromEntries(keys.map((key) => [key, item[key]])) : item;
328
+ const build = (keys) => ({
329
+ select(...selected) {
330
+ return build(selected);
331
+ },
332
+ async page(options = {}) {
333
+ options.signal?.throwIfAborted();
334
+ const query = await collection.parseQuery(input);
335
+ const result = await collection.page({
336
+ ...options,
337
+ query
338
+ });
339
+ return {
340
+ ...result,
341
+ items: result.items.map((item) => project(item, keys))
342
+ };
343
+ },
344
+ async all(options = {}) {
345
+ options.signal?.throwIfAborted();
346
+ const items = [];
347
+ const query = await collection.parseQuery(input);
348
+ let cursor;
349
+ const seen = /* @__PURE__ */ new Set();
350
+ do {
351
+ options.signal?.throwIfAborted();
352
+ const result = await collection.page({
353
+ ...options,
354
+ cursor,
355
+ query
356
+ });
357
+ for (const item of result.items) items.push(project(item, keys));
358
+ cursor = result.nextCursor ?? void 0;
359
+ if (cursor !== void 0) {
360
+ if (seen.has(cursor)) throw new CollectionCursorError("[vitehub] Collection loader repeated a pagination cursor.");
361
+ seen.add(cursor);
362
+ }
363
+ } while (cursor !== void 0);
364
+ return items;
365
+ }
366
+ });
367
+ return build();
368
+ },
369
+ async all(options = {}) {
370
+ return collection.query(options.query).all(options);
371
+ },
372
+ ...definition.querySchema ? { querySchema: definition.querySchema } : {}
373
+ };
374
+ const get = definition.get;
375
+ if (get) {
376
+ const lookup = async (key, options) => {
377
+ options?.signal?.throwIfAborted();
378
+ const item = await get(key, options ?? {});
379
+ options?.signal?.throwIfAborted();
380
+ if (item === null || item === void 0) return item;
381
+ const result = definition.transform ? await definition.transform(item) : item;
382
+ options?.signal?.throwIfAborted();
383
+ return result;
384
+ };
385
+ Object.assign(collection, { get: lookup });
386
+ }
387
+ return collection;
388
+ }
389
+ function sourceDefinition(input) {
390
+ const { authorize, route, source, transform } = input;
391
+ if (Object(source) !== source || typeof source.load !== "function") throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] defineCollection({ source }) requires a Collection source with load()." });
392
+ const shared = {
393
+ authorize,
394
+ route,
395
+ get: source.get,
396
+ defaultLimit: source.defaultLimit,
397
+ maxLimit: source.maxLimit,
398
+ querySchema: source.querySchema,
399
+ transform
400
+ };
401
+ return source.pagination === "provider" ? [source.load, {
402
+ ...shared,
403
+ pagination: "provider"
404
+ }] : [source.load, {
405
+ ...shared,
406
+ cursor: source.cursor,
407
+ cursorSchema: source.cursorSchema
408
+ }];
409
+ }
410
+ function isProviderCursor(value) {
411
+ return value === String(value);
47
412
  }
48
- function matchesAny(path, patterns) {
49
- if (!patterns) return true;
50
- const list = Array.isArray(patterns) ? patterns : [patterns];
51
- const normalizedPath = normalizeSourcePath(path);
52
- return picomatch.isMatch(normalizedPath, list.map((pattern) => normalizeSourcePath(pattern)), { dot: true });
413
+ //#endregion
414
+ //#region src/core/combine-sources.ts
415
+ function combineSources(definition) {
416
+ const sources = definition.sources;
417
+ async function get(identity) {
418
+ if (!Array.isArray(identity) || identity.length !== 2 || String(identity[0]) !== identity[0] || String(identity[1]) !== identity[1]) throw sourceErrorDiagnostics.SOURCE_R0010({ message: "[vitehub] Combined Source identity must be a [source, key] string tuple." });
419
+ const [source, key] = identity;
420
+ if (!Object.hasOwn(sources, source)) throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not defined.`);
421
+ return await sources[source].get(key);
422
+ }
423
+ async function items() {
424
+ const entries = Object.entries(sources);
425
+ for (const [source, reader] of entries) if (typeof reader.items !== "function") throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not enumerable.`);
426
+ return (await Promise.all(entries.map(async ([source, reader]) => (await reader.items()).map((item) => ({
427
+ ...item,
428
+ identity: [source, item.key],
429
+ source
430
+ }))))).flat();
431
+ }
432
+ return Object.values(sources).every((source) => typeof source.items === "function") ? {
433
+ get,
434
+ items
435
+ } : { get };
53
436
  }
54
- function decodeSourceContent(content, options) {
55
- if (options?.encoding === "binary") return typeof content === "string" ? new TextEncoder().encode(content) : content;
56
- return typeof content === "string" ? content : new TextDecoder().decode(content);
437
+ //#endregion
438
+ //#region src/core/split-source.ts
439
+ /** Split each item of a Source into parts, such as the sections of a Markdown file. Each part is an item. */
440
+ function splitSource(options) {
441
+ const parent = options.source;
442
+ const splitCaches = /* @__PURE__ */ new WeakMap();
443
+ async function partsOf(item) {
444
+ const parts = await options.split(item);
445
+ if (!Array.isArray(parts)) throw sourceError(`[vitehub] splitSource() split() must return an array for ${JSON.stringify(item.key)}.`);
446
+ const seen = /* @__PURE__ */ new Set();
447
+ return parts.map((part) => {
448
+ if (!part.key || part.key.includes("#")) throw sourceError(`[vitehub] splitSource() part key ${JSON.stringify(part.key)} in ${JSON.stringify(item.key)} must be a non-empty string without "#".`);
449
+ if (seen.has(part.key)) throw sourceError(`[vitehub] splitSource() returned the part key ${JSON.stringify(part.key)} twice for ${JSON.stringify(item.key)}.`);
450
+ seen.add(part.key);
451
+ const key = `${item.key}#${part.key}`;
452
+ const path = part.path ?? item.path;
453
+ const metadata = item.metadata === void 0 ? part.metadata : part.metadata === void 0 ? item.metadata : {
454
+ ...item.metadata,
455
+ ...part.metadata
456
+ };
457
+ return {
458
+ ...part,
459
+ key,
460
+ ...path === void 0 ? {} : { path },
461
+ ...metadata === void 0 ? {} : { metadata }
462
+ };
463
+ });
464
+ }
465
+ function cachedPartsOf(item, ctx) {
466
+ let splitCache = splitCaches.get(ctx);
467
+ if (!splitCache) {
468
+ splitCache = /* @__PURE__ */ new Map();
469
+ splitCaches.set(ctx, splitCache);
470
+ }
471
+ const cached = splitCache.get(item.key);
472
+ if (cached) return cached;
473
+ const result = partsOf(item);
474
+ splitCache.set(item.key, result);
475
+ return result;
476
+ }
477
+ async function parentItems(ctx) {
478
+ if (parent.getItems) return await parent.getItems(ctx);
479
+ const keys = await parent.getKeys(ctx);
480
+ return await Promise.all(keys.map((key) => parent.getItem(key, ctx)));
481
+ }
482
+ async function getItems(ctx) {
483
+ return (await Promise.all((await parentItems(ctx)).map((item) => cachedPartsOf(item, ctx)))).flat();
484
+ }
485
+ return {
486
+ name: options.name ?? parent.name,
487
+ ...parent.cache === void 0 ? {} : { cache: parent.cache },
488
+ ...parent.fingerprint === void 0 ? {} : { fingerprint: parent.fingerprint },
489
+ ...parent.resolveRevision ? { resolveRevision: (ctx) => parent.resolveRevision(ctx) } : {},
490
+ ...parent.prepare ? { prepare: (ctx) => parent.prepare(ctx) } : {},
491
+ async getKeys(ctx) {
492
+ return (await getItems(ctx)).map((part) => part.key);
493
+ },
494
+ async getItem(key, ctx) {
495
+ const id = String(key);
496
+ const at = id.lastIndexOf("#");
497
+ if (at < 1) throw sourceError(`[vitehub] splitSource() key ${JSON.stringify(id)} has no "#" between the item and the part.`);
498
+ const part = (await cachedPartsOf(await parent.getItem(id.slice(0, at), ctx), ctx)).find((candidate) => candidate.key === key);
499
+ if (!part) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
500
+ return part;
501
+ },
502
+ getMeta(key, ctx) {
503
+ return (async () => {
504
+ const id = String(key);
505
+ const at = id.lastIndexOf("#");
506
+ if (at < 1) return void 0;
507
+ const parentKey = id.slice(0, at);
508
+ const cached = splitCaches.get(ctx)?.get(parentKey);
509
+ if (!cached) return await parent.getMeta?.(parentKey, ctx);
510
+ if (!(await cached).some((part) => part.key === key)) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
511
+ return await parent.getMeta?.(parentKey, ctx);
512
+ })();
513
+ },
514
+ getItems
515
+ };
57
516
  }
58
517
  //#endregion
59
- //#region src/core/registry.ts
60
- const sourceRegistry = /* @__PURE__ */ new Map();
61
- function registerSource(name, source) {
62
- sourceRegistry.set(name, source);
518
+ //#region src/core/define.ts
519
+ /** Define a loader. Open it with createSource() to bind its runtime context. */
520
+ function defineSource(source) {
63
521
  return source;
64
522
  }
65
- function registerSources(sources) {
66
- for (const [name, source] of Object.entries(sources)) registerSource(name, source);
523
+ function defineSources(sources) {
67
524
  return sources;
68
525
  }
69
- function getRegisteredSource(name) {
70
- const source = sourceRegistry.get(name);
71
- if (!source) throw sourceNotFoundError(name);
72
- return source;
73
- }
74
- function clearSources() {
75
- sourceRegistry.clear();
76
- }
526
+ //#endregion
527
+ //#region src/core/reader.ts
77
528
  function createSourceContext(name, context = {}) {
78
529
  return {
79
530
  abortSignal: context.abortSignal,
531
+ revision: context.revision,
80
532
  rootDir: context.rootDir || process.cwd(),
81
533
  source: context.source || name,
82
534
  sourceRootDir: context.sourceRootDir,
@@ -89,19 +541,30 @@ function createMissingContentError(key) {
89
541
  function isNestedUnder(path, prefix) {
90
542
  return !prefix || path === prefix || path.startsWith(`${prefix}/`);
91
543
  }
92
- function createDirectorySet(paths) {
544
+ function createDirectorySet(paths, prefix) {
93
545
  const directories = /* @__PURE__ */ new Set();
546
+ const start = prefix ? prefix.length + 1 : 0;
94
547
  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("/"));
548
+ const normalized = normalizeSourcePath(path).split("/").filter(Boolean).join("/");
549
+ if (prefix && !normalized.startsWith(`${prefix}/`)) continue;
550
+ const end = normalized.indexOf("/", start);
551
+ if (end !== -1) directories.add(normalized.slice(0, end));
97
552
  }
98
553
  return directories;
99
554
  }
100
- function useSource(name, context) {
101
- const source = getRegisteredSource(name);
102
- const ctx = createSourceContext(name, context);
555
+ function createSource(source, context) {
556
+ const ctx = createSourceContext(source.name, context);
557
+ let revisionPromise;
103
558
  let preparePromise;
559
+ async function revision() {
560
+ if (ctx.revision) return ctx.revision;
561
+ revisionPromise ||= source.resolveRevision?.(ctx) ?? Promise.resolve(void 0);
562
+ const resolved = await revisionPromise;
563
+ if (resolved) ctx.revision = resolved;
564
+ return resolved;
565
+ }
104
566
  async function ensurePrepared() {
567
+ await revision();
105
568
  if (!source.prepare) return;
106
569
  preparePromise ||= source.prepare(ctx);
107
570
  await preparePromise;
@@ -115,6 +578,7 @@ function useSource(name, context) {
115
578
  return await source.getItem(key, ctx);
116
579
  }
117
580
  return {
581
+ revision,
118
582
  keys,
119
583
  get,
120
584
  async items() {
@@ -124,7 +588,7 @@ function useSource(name, context) {
124
588
  },
125
589
  async read(key, options) {
126
590
  const item = await get(key);
127
- if (typeof item.content === "undefined") throw createMissingContentError(key);
591
+ if (item.content === void 0) throw createMissingContentError(key);
128
592
  return decodeSourceContent(item.content, options);
129
593
  },
130
594
  async meta(key) {
@@ -136,23 +600,20 @@ function useSource(name, context) {
136
600
  },
137
601
  async list(prefix = "") {
138
602
  await ensurePrepared();
139
- const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }) : "";
603
+ const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }).split("/").filter(Boolean).join("/") : "";
140
604
  const sourceKeys = await keys();
141
- const directories = createDirectorySet(sourceKeys);
605
+ const directories = createDirectorySet(sourceKeys, normalizedPrefix);
142
606
  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
- }
607
+ for (const directory of directories) result.set(directory, {
608
+ key: directory,
609
+ type: "directory"
610
+ });
152
611
  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;
612
+ const normalizedKey = normalizeSourcePath(key).split("/").filter(Boolean).join("/");
613
+ if (normalizedKey === normalizedPrefix) continue;
614
+ if (!isNestedUnder(normalizedKey, normalizedPrefix)) continue;
615
+ if (normalizedKey.slice(normalizedPrefix.length).replace(/^\//, "").includes("/")) continue;
616
+ result.delete(normalizedKey);
156
617
  result.set(key, {
157
618
  key,
158
619
  type: "file"
@@ -163,1041 +624,67 @@ function useSource(name, context) {
163
624
  };
164
625
  }
165
626
  //#endregion
166
- //#region src/sources/custom.ts
167
- function custom(source) {
627
+ //#region src/core/registry.ts
628
+ const sourceRegistry = /* @__PURE__ */ new Map();
629
+ function registerSource(name, source) {
630
+ sourceRegistry.set(name, source);
168
631
  return source;
169
632
  }
170
- //#endregion
171
- //#region src/sources/file.ts
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] : [];
633
+ function registerSources(sources) {
634
+ for (const [name, source] of Object.entries(sources)) registerSource(name, source);
635
+ return sources;
877
636
  }
878
- function resolveSourceRoot(ctx) {
879
- return ctx.sourceRootDir || ctx.rootDir;
637
+ function getRegisteredSource(name) {
638
+ const source = sourceRegistry.get(name);
639
+ if (!source) throw sourceNotFoundError(name);
640
+ return source;
880
641
  }
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;
642
+ function clearSources() {
643
+ sourceRegistry.clear();
889
644
  }
890
- //#endregion
891
- //#region src/sources/markdown.ts
892
- function markdown(options) {
893
- return file({
894
- ...options,
895
- mediaType: options.mediaType || "text/markdown"
645
+ /** Open a registered definition with the same lifecycle as direct Source readers. */
646
+ function useSource(name, context) {
647
+ return createSource(getRegisteredSource(name), {
648
+ ...context,
649
+ source: context?.source ?? name
896
650
  });
897
651
  }
898
652
  //#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."
653
+ //#region src/ignores.ts
654
+ const dependencies = Object.freeze([
655
+ "**/node_modules/**",
656
+ "**/.pnpm-store/**",
657
+ "**/.venv/**",
658
+ "**/dbt_packages/**"
659
+ ]);
660
+ const generated = Object.freeze([
661
+ "**/.nuxt/**",
662
+ "**/.output/**",
663
+ "**/coverage/**",
664
+ "**/playwright-report/**",
665
+ "**/target/**",
666
+ "**/test-results/**"
667
+ ]);
668
+ const media = Object.freeze(["**/*.{gif,ico,jpeg,jpg,png,webp}"]);
669
+ const secrets = Object.freeze(["**/.env", "**/.env.*"]);
670
+ const system = Object.freeze([
671
+ "**/.DS_Store",
672
+ "**/__pycache__/**",
673
+ "**/*.pyc"
674
+ ]);
675
+ const sourceIgnores = Object.freeze({
676
+ defaults: Object.freeze([
677
+ ...dependencies,
678
+ ...generated,
679
+ ...media,
680
+ ...secrets,
681
+ ...system
682
+ ]),
683
+ dependencies,
684
+ generated,
685
+ media,
686
+ secrets,
687
+ system
953
688
  });
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
689
  //#endregion
1203
- export { clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, useSource };
690
+ export { CollectionCursorError, array, clearSources, combineSources, createSource, defineCollection, defineSource, defineSources, getRegisteredSource, registerSource, registerSources, sourceIgnores, splitSource, useSource };