@vite-hub/source 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +267 -96
  2. package/dist/client.d.ts +27 -10
  3. package/dist/client.js +99 -15
  4. package/dist/collection-B8sgxw5-.d.ts +290 -0
  5. package/dist/collection-C0Rvrx3p.js +297 -0
  6. package/dist/collection-route-BplWPxHR.js +10 -0
  7. package/dist/drizzle.d.ts +48 -0
  8. package/dist/drizzle.js +87 -0
  9. package/dist/error-diagnostics-ClQKdi7c.js +194 -0
  10. package/dist/github-D5S0dEZe.js +1312 -0
  11. package/dist/{glob.js → glob-DmdMVqjx.js} +154 -57
  12. package/dist/index.d.ts +284 -62
  13. package/dist/index.js +583 -29
  14. package/dist/invariant-DolT9EEx.js +22 -0
  15. package/dist/mcp.d.ts +3 -4
  16. package/dist/mcp.js +184 -5917
  17. package/dist/object-CtSHeGQO.js +17 -0
  18. package/dist/{path-CUhvUREm.js → path-DFlSryRA.js} +90 -40
  19. package/dist/root-DJNmqCEW.js +11 -0
  20. package/dist/server.d.ts +24 -11
  21. package/dist/server.js +97 -26
  22. package/dist/types-Ln-FxVFn.d.ts +98 -0
  23. package/dist/vite.d.ts +202 -14
  24. package/dist/vite.js +1683 -122
  25. package/package.json +55 -58
  26. package/dist/auth-Ddw55OUG.js +0 -1261
  27. package/dist/client-CDfTmtQu.js +0 -7903
  28. package/dist/collection-B8pXGM2d.js +0 -141
  29. package/dist/collection-CF2ON__k.d.ts +0 -92
  30. package/dist/collection-route-Dw7QLFyx.js +0 -6
  31. package/dist/content/client.d.ts +0 -3
  32. package/dist/content/client.js +0 -2
  33. package/dist/content.d.ts +0 -44
  34. package/dist/content.js +0 -157
  35. package/dist/file-BSWQg9Qv.js +0 -503
  36. package/dist/file-EQ3AjVM6.d.ts +0 -20
  37. package/dist/file.d.ts +0 -2
  38. package/dist/file.js +0 -2
  39. package/dist/github.d.ts +0 -17
  40. package/dist/github.js +0 -1033
  41. package/dist/glob.d.ts +0 -15
  42. package/dist/markdown.d.ts +0 -7
  43. package/dist/markdown.js +0 -10
  44. package/dist/path-BzmU4Eni.js +0 -36
  45. package/dist/registry-C8skfCSV.js +0 -120
  46. package/dist/sse-CE9Q2JqM.js +0 -407
  47. package/dist/streamableHttp-BszaXLmg.js +0 -491
  48. package/dist/types-AIBmt_m6.js +0 -6275
  49. package/dist/types-Bu3WvNX9.d.ts +0 -71
  50. package/tsconfig.vite.json +0 -6
  51. package/types/source/fallback.d.ts +0 -1
  52. package/types/source/index.d.ts +0 -1
package/dist/index.js CHANGED
@@ -1,39 +1,459 @@
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();
1
+ import { a as normalizeSafeSourcePath, c as sourceNotFoundError, i as decodeSourceContent, l as sourcePathError, o as normalizeSourcePath, s as sourceError } from "./path-DFlSryRA.js";
2
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
3
+ import { r as isRecordOrFunction } from "./object-CtSHeGQO.js";
4
+ import { a as parseCollectionSchema, i as createCollectionCursorCodec, n as defineCollection, r as CollectionCursorError } from "./collection-C0Rvrx3p.js";
5
+ import { t as normalizeGitHubRoot } from "./root-DJNmqCEW.js";
6
+ import { n as glob } from "./glob-DmdMVqjx.js";
7
+ import { lookup } from "mrmime";
8
+ //#region src/core/array-collection.ts
9
+ const defaultMaxLimit = 100;
10
+ const reservedQueryKeys = /* @__PURE__ */ new Set([
11
+ "cursor",
12
+ "empty",
13
+ "limit",
14
+ "search"
15
+ ]);
16
+ function compareProtocolStrings(left, right) {
17
+ return left < right ? -1 : left > right ? 1 : 0;
18
+ }
19
+ const cursorCodec = createCollectionCursorCodec({ "~standard": {
20
+ version: 1,
21
+ vendor: "vite-hub",
22
+ validate(value) {
23
+ const cursor = Object(value);
24
+ const digest = Reflect.get(cursor, "digest");
25
+ const offset = Reflect.get(cursor, "offset");
26
+ const query = Reflect.get(cursor, "query");
27
+ 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." }] };
28
+ return { value: {
29
+ digest: String(digest),
30
+ offset: Number(offset),
31
+ query: String(query)
32
+ } };
33
+ }
34
+ } });
35
+ /** Read a dot path through own properties. Arrays fan out to every element. */
36
+ function collectionValueAt(value, path) {
37
+ const segments = path.split(".").filter(Boolean);
38
+ function visit(current, remaining) {
39
+ if (!remaining.length) return current;
40
+ if (Array.isArray(current)) return current.map((item) => visit(item, remaining)).filter((item) => item !== void 0);
41
+ if (!isRecordOrFunction(current)) return;
42
+ const segment = remaining[0];
43
+ if (!Object.hasOwn(current, segment)) return;
44
+ return visit(current[segment], remaining.slice(1));
45
+ }
46
+ return visit(value, segments);
47
+ }
48
+ function dateTime(value) {
49
+ if (Object.prototype.toString.call(value) !== "[object Date]") return;
50
+ const time = Date.prototype.getTime.call(value);
51
+ return Number.isNaN(time) ? void 0 : time;
52
+ }
53
+ function scalarValues(value) {
54
+ if (Array.isArray(value)) return value.flatMap(scalarValues);
55
+ const time = dateTime(value);
56
+ if (time !== void 0) return [new Date(time).toISOString()];
57
+ if (value === null || value === void 0 || Object(value) === value) return [];
58
+ return [String(value)];
59
+ }
60
+ function firstScalar(value) {
61
+ const entry = Array.isArray(value) ? value.flat(Infinity).find((item) => item !== null && item !== void 0 && (Object(item) !== item || dateTime(item) !== void 0)) : value;
62
+ return dateTime(entry) ?? entry;
63
+ }
64
+ function isString(value) {
65
+ return String(value) === value;
66
+ }
67
+ function stringList(value) {
68
+ return (Array.isArray(value) ? value : [value]).filter((entry) => String(entry) === entry);
69
+ }
70
+ async function sha256(value) {
71
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
72
+ return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
73
+ }
74
+ function assertFieldList(label, fields) {
75
+ if (fields === void 0) return;
76
+ 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.` });
77
+ }
78
+ function normalizeQuery(query) {
79
+ const normalized = {
80
+ empty: [],
81
+ filters: Object.create(null),
82
+ search: ""
83
+ };
84
+ for (const [key, value] of Object.entries(query).sort(([a], [b]) => compareProtocolStrings(a, b))) {
85
+ if (value === void 0 || value === null) continue;
86
+ if (key === "search") {
87
+ normalized.search = String(value).trim().toLocaleLowerCase();
88
+ continue;
89
+ }
90
+ if (key === "empty") {
91
+ normalized.empty = [...new Set(stringList(value))].sort();
92
+ continue;
93
+ }
94
+ const values = stringList(value).map((entry) => entry.toLocaleLowerCase());
95
+ if (values.length) normalized.filters[key] = [...new Set(values)].sort();
96
+ }
97
+ return normalized;
98
+ }
99
+ function matches(item, query, searchFields) {
100
+ for (const [field, expected] of Object.entries(query.filters)) {
101
+ const values = scalarValues(collectionValueAt(item, field)).map((value) => value.toLocaleLowerCase());
102
+ if (!expected.some((candidate) => values.includes(candidate))) return false;
103
+ }
104
+ for (const field of query.empty) if (scalarValues(collectionValueAt(item, field)).length) return false;
105
+ if (query.search) return searchFields.some((field) => scalarValues(collectionValueAt(item, field)).some((value) => value.toLocaleLowerCase().includes(query.search)));
106
+ return true;
107
+ }
108
+ function sortItems(items, sort) {
109
+ if (!sort) return items;
110
+ const direction = sort.direction === "desc" ? -1 : 1;
111
+ return items.map((item) => ({
112
+ item,
113
+ value: firstScalar(collectionValueAt(item, sort.field))
114
+ })).sort(({ value: leftValue }, { value: rightValue }) => {
115
+ if (Number(leftValue) === leftValue && Number(rightValue) === rightValue) return (leftValue - rightValue) * direction;
116
+ return String(leftValue ?? "").localeCompare(String(rightValue ?? "")) * direction;
117
+ }).map(({ item }) => item);
118
+ }
119
+ function buildFacets(items, fields, maxValues) {
120
+ return Object.fromEntries(fields.map((field) => {
121
+ const counts = /* @__PURE__ */ new Map();
122
+ for (const item of items) for (const value of new Set(scalarValues(collectionValueAt(item, field)))) counts.set(value, (counts.get(value) ?? 0) + 1);
123
+ return [field, [...counts].map(([value, count]) => ({
124
+ count,
125
+ value
126
+ })).sort((left, right) => right.count - left.count || left.value.localeCompare(right.value)).slice(0, maxValues)];
127
+ }));
128
+ }
129
+ function array(load, options = {}) {
130
+ assertFieldList("filters", options.filters);
131
+ assertFieldList("search", options.search);
132
+ assertFieldList("facets", options.facets);
133
+ const reserved = options.filters?.find((field) => reservedQueryKeys.has(field));
134
+ if (reserved) throw sourceErrorDiagnostics.SOURCE_R0028({ message: `[vitehub] array() filter ${JSON.stringify(reserved)} collides with a reserved query key.` });
135
+ if (options.sort !== void 0 && (!isRecordOrFunction(options.sort) || String(options.sort.field) !== options.sort.field || !options.sort.field)) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() sort must name a field." });
136
+ const filters = new Set(options.filters ?? []);
137
+ const isFilter = (key) => filters.has(key);
138
+ const searchFields = options.search ?? [];
139
+ const facetFields = options.facets ?? [];
140
+ const maxValues = options.maxLimit ?? defaultMaxLimit;
141
+ const signatureFields = JSON.stringify({
142
+ search: [...searchFields].sort(),
143
+ sort: options.sort ? {
144
+ direction: options.sort.direction ?? "asc",
145
+ field: options.sort.field
146
+ } : null
147
+ });
148
+ async function snapshot(signal, includeDigest) {
149
+ const result = typeof load === "function" ? await load({ signal }) : load;
150
+ signal?.throwIfAborted();
151
+ const items = Array.isArray(result) ? result : Reflect.get(Object(result), "items");
152
+ if (!Array.isArray(items)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() load must return an array or { items, digest }." });
153
+ const digest = Array.isArray(result) ? void 0 : Reflect.get(Object(result), "digest");
154
+ if (digest !== void 0 && (String(digest) !== digest || !digest)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() digest must be a non-empty string." });
155
+ const contentDigest = includeDigest ? String(digest ?? await sha256(JSON.stringify(items))) : "";
156
+ const schema = options.schema;
157
+ if (schema) return {
158
+ digest: contentDigest,
159
+ items: await Promise.all(items.map(async (item, index) => {
160
+ try {
161
+ return await parseCollectionSchema(schema, item);
162
+ } catch (cause) {
163
+ throw sourceErrorDiagnostics.SOURCE_R0006({
164
+ cause,
165
+ message: `[vitehub] array() item ${index} does not match its schema: ${cause instanceof Error ? cause.message : String(cause)}`
166
+ });
167
+ }
168
+ }))
169
+ };
170
+ return {
171
+ digest: contentDigest,
172
+ items
173
+ };
174
+ }
175
+ const source = {
176
+ defaultLimit: options.defaultLimit,
177
+ maxLimit: options.maxLimit,
178
+ pagination: "provider",
179
+ querySchema: { "~standard": {
180
+ version: 1,
181
+ vendor: "vite-hub",
182
+ validate(value) {
183
+ if (!isRecordOrFunction(value)) return { issues: [{ message: "Collection query must be an object." }] };
184
+ const filterValues = Object.create(null);
185
+ let empty;
186
+ let search;
187
+ for (const [key, raw] of Object.entries(value)) {
188
+ if (raw === void 0 || raw === null) continue;
189
+ const values = Array.isArray(raw) ? raw : [raw];
190
+ if (!values.every(isString)) return { issues: [{ message: `Collection query ${JSON.stringify(key)} must be a string.` }] };
191
+ if (key === "search") {
192
+ if (values.length !== 1) return { issues: [{ message: "Collection search must have one value." }] };
193
+ if (values[0] && !searchFields.length) return { issues: [{ message: "Collection search is not enabled." }] };
194
+ search = values[0];
195
+ continue;
196
+ }
197
+ if (key === "empty") {
198
+ const unknown = values.find((field) => !isFilter(field));
199
+ if (unknown !== void 0) return { issues: [{ message: `Collection filter ${JSON.stringify(unknown)} is not allowed.` }] };
200
+ empty = values.filter(isFilter);
201
+ continue;
202
+ }
203
+ if (!isFilter(key)) return { issues: [{ message: `Collection query parameter ${JSON.stringify(key)} is not allowed.` }] };
204
+ filterValues[key] = values.map((entry) => entry.trim());
205
+ }
206
+ const parsed = { ...filterValues };
207
+ if (empty) parsed.empty = empty;
208
+ if (search !== void 0) parsed.search = search;
209
+ return { value: parsed };
210
+ }
211
+ } },
212
+ async load({ cursor, limit, query, signal }) {
213
+ const { digest, items } = await snapshot(signal, true);
214
+ const normalized = normalizeQuery(query);
215
+ const matching = sortItems(items.filter((item) => matches(item, normalized, searchFields)), options.sort);
216
+ const signature = await sha256(`${signatureFields}\n${JSON.stringify(normalized)}`);
217
+ const decoded = await cursorCodec.decode(cursor);
218
+ if (decoded && (decoded.digest !== digest || decoded.query !== signature)) throw new CollectionCursorError(void 0, { reason: "stale" });
219
+ const offset = decoded?.offset ?? 0;
220
+ if (offset > matching.length) throw new CollectionCursorError();
221
+ const pageItems = matching.slice(offset, offset + limit);
222
+ const nextOffset = offset + pageItems.length;
223
+ const page = {
224
+ items: pageItems,
225
+ nextCursor: nextOffset < matching.length ? cursorCodec.encode({
226
+ digest,
227
+ offset: nextOffset,
228
+ query: signature
229
+ }) : null,
230
+ total: matching.length
231
+ };
232
+ if (facetFields.length) page.facets = buildFacets(matching, facetFields, maxValues);
233
+ return page;
234
+ }
235
+ };
236
+ const key = options.key;
237
+ if (key !== void 0) {
238
+ if (String(key) !== key || !key) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() key must be a field path." });
239
+ source.get = async (value, { signal }) => {
240
+ const { items } = await snapshot(signal, false);
241
+ return items.find((item) => scalarValues(collectionValueAt(item, key)).includes(value)) ?? null;
242
+ };
243
+ }
244
+ return source;
245
+ }
246
+ //#endregion
247
+ //#region src/core/split-source.ts
248
+ /** Split each item of a Source into parts, such as the sections of a Markdown file. Each part is an item. */
249
+ function splitSource(options) {
250
+ const parent = options.source;
251
+ const splitCaches = /* @__PURE__ */ new WeakMap();
252
+ async function partsOf(item) {
253
+ const parts = await options.split(item);
254
+ if (!Array.isArray(parts)) throw sourceError(`[vitehub] splitSource() split() must return an array for ${JSON.stringify(item.key)}.`);
255
+ const seen = /* @__PURE__ */ new Set();
256
+ return parts.map((part) => {
257
+ 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 "#".`);
258
+ if (seen.has(part.key)) throw sourceError(`[vitehub] splitSource() returned the part key ${JSON.stringify(part.key)} twice for ${JSON.stringify(item.key)}.`);
259
+ seen.add(part.key);
260
+ const key = `${item.key}#${part.key}`;
261
+ const path = part.path ?? item.path;
262
+ const metadata = item.metadata === void 0 ? part.metadata : part.metadata === void 0 ? item.metadata : {
263
+ ...item.metadata,
264
+ ...part.metadata
265
+ };
266
+ return {
267
+ ...part,
268
+ key,
269
+ ...path === void 0 ? {} : { path },
270
+ ...metadata === void 0 ? {} : { metadata }
271
+ };
272
+ });
273
+ }
274
+ function cachedPartsOf(item, ctx) {
275
+ let splitCache = splitCaches.get(ctx);
276
+ if (!splitCache) {
277
+ splitCache = /* @__PURE__ */ new Map();
278
+ splitCaches.set(ctx, splitCache);
279
+ }
280
+ const cached = splitCache.get(item.key);
281
+ if (cached) return cached;
282
+ const result = partsOf(item);
283
+ splitCache.set(item.key, result);
284
+ return result;
285
+ }
286
+ async function parentItems(ctx) {
287
+ if (parent.getItems) return await parent.getItems(ctx);
288
+ const keys = await parent.getKeys(ctx);
289
+ return await Promise.all(keys.map((key) => parent.getItem(key, ctx)));
290
+ }
291
+ async function getItems(ctx) {
292
+ return (await Promise.all((await parentItems(ctx)).map((item) => cachedPartsOf(item, ctx)))).flat();
21
293
  }
22
294
  return {
23
- get,
24
- items
295
+ name: options.name ?? parent.name,
296
+ ...parent.cache === void 0 ? {} : { cache: parent.cache },
297
+ ...parent.fingerprint === void 0 ? {} : { fingerprint: parent.fingerprint },
298
+ ...parent.resolveRevision ? { resolveRevision: (ctx) => parent.resolveRevision(ctx) } : {},
299
+ ...parent.prepare ? { prepare: (ctx) => parent.prepare(ctx) } : {},
300
+ async getKeys(ctx) {
301
+ return (await getItems(ctx)).map((part) => part.key);
302
+ },
303
+ async getItem(key, ctx) {
304
+ const id = String(key);
305
+ const at = id.lastIndexOf("#");
306
+ if (at < 1) throw sourceError(`[vitehub] splitSource() key ${JSON.stringify(id)} has no "#" between the item and the part.`);
307
+ const part = (await cachedPartsOf(await parent.getItem(id.slice(0, at), ctx), ctx)).find((candidate) => candidate.key === key);
308
+ if (!part) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
309
+ return part;
310
+ },
311
+ getMeta(key, ctx) {
312
+ return (async () => {
313
+ const id = String(key);
314
+ const at = id.lastIndexOf("#");
315
+ if (at < 1) return void 0;
316
+ const parentKey = id.slice(0, at);
317
+ const cached = splitCaches.get(ctx)?.get(parentKey);
318
+ if (!cached) return await parent.getMeta?.(parentKey, ctx);
319
+ if (!(await cached).some((part) => part.key === key)) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
320
+ return await parent.getMeta?.(parentKey, ctx);
321
+ })();
322
+ },
323
+ getItems
25
324
  };
26
325
  }
27
326
  //#endregion
28
327
  //#region src/core/define.ts
328
+ /** Define a loader. Open it with createSource() to bind its runtime context. */
29
329
  function defineSource(source) {
30
330
  return source;
31
331
  }
32
- function defineSources(sources) {
332
+ //#endregion
333
+ //#region src/core/reader.ts
334
+ function createSourceContext(name, context = {}) {
335
+ return {
336
+ abortSignal: context.abortSignal,
337
+ revision: context.revision,
338
+ rootDir: context.rootDir || process.cwd(),
339
+ source: context.source || name,
340
+ sourceRootDir: context.sourceRootDir,
341
+ workspace: context.workspace
342
+ };
343
+ }
344
+ function createMissingContentError(key) {
345
+ return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
346
+ }
347
+ function isNestedUnder(path, prefix) {
348
+ return !prefix || path === prefix || path.startsWith(`${prefix}/`);
349
+ }
350
+ function createDirectorySet(paths, prefix) {
351
+ const directories = /* @__PURE__ */ new Set();
352
+ const start = prefix ? prefix.length + 1 : 0;
353
+ for (const path of paths) {
354
+ const normalized = normalizeSourcePath(path).split("/").filter(Boolean).join("/");
355
+ if (prefix && !normalized.startsWith(`${prefix}/`)) continue;
356
+ const end = normalized.indexOf("/", start);
357
+ if (end !== -1) directories.add(normalized.slice(0, end));
358
+ }
359
+ return directories;
360
+ }
361
+ function createSource(source, context) {
362
+ const ctx = createSourceContext(source.name, context);
363
+ let revisionPromise;
364
+ let preparePromise;
365
+ async function revision() {
366
+ if (ctx.revision) return ctx.revision;
367
+ revisionPromise ||= source.resolveRevision?.(ctx) ?? Promise.resolve(void 0);
368
+ const resolved = await revisionPromise;
369
+ if (resolved) ctx.revision = resolved;
370
+ return resolved;
371
+ }
372
+ async function ensurePrepared() {
373
+ await revision();
374
+ if (!source.prepare) return;
375
+ preparePromise ||= source.prepare(ctx);
376
+ await preparePromise;
377
+ }
378
+ async function keys() {
379
+ await ensurePrepared();
380
+ return await source.getKeys(ctx);
381
+ }
382
+ async function get(key) {
383
+ await ensurePrepared();
384
+ return await source.getItem(key, ctx);
385
+ }
386
+ return {
387
+ revision,
388
+ keys,
389
+ get,
390
+ async items() {
391
+ await ensurePrepared();
392
+ if (source.getItems) return await source.getItems(ctx);
393
+ return await Promise.all((await keys()).map(get));
394
+ },
395
+ async read(key, options) {
396
+ const item = await get(key);
397
+ if (item.content === void 0) throw createMissingContentError(key);
398
+ return decodeSourceContent(item.content, options);
399
+ },
400
+ async meta(key) {
401
+ await ensurePrepared();
402
+ return await source.getMeta?.(key, ctx);
403
+ },
404
+ async exists(key) {
405
+ return (await keys()).includes(key);
406
+ },
407
+ async list(prefix = "") {
408
+ await ensurePrepared();
409
+ const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }).split("/").filter(Boolean).join("/") : "";
410
+ const sourceKeys = await keys();
411
+ const directories = createDirectorySet(sourceKeys, normalizedPrefix);
412
+ const result = /* @__PURE__ */ new Map();
413
+ for (const directory of directories) result.set(directory, {
414
+ key: directory,
415
+ type: "directory"
416
+ });
417
+ for (const key of sourceKeys) {
418
+ const normalizedKey = normalizeSourcePath(key).split("/").filter(Boolean).join("/");
419
+ if (normalizedKey === normalizedPrefix) continue;
420
+ if (!isNestedUnder(normalizedKey, normalizedPrefix)) continue;
421
+ if (normalizedKey.slice(normalizedPrefix.length).replace(/^\//, "").includes("/")) continue;
422
+ result.delete(normalizedKey);
423
+ result.set(key, {
424
+ key,
425
+ type: "file"
426
+ });
427
+ }
428
+ return [...result.values()].sort((left, right) => left.key.localeCompare(right.key));
429
+ }
430
+ };
431
+ }
432
+ //#endregion
433
+ //#region src/core/registry.ts
434
+ const sourceRegistry = /* @__PURE__ */ new Map();
435
+ function registerSource(name, source) {
436
+ sourceRegistry.set(name, source);
437
+ return source;
438
+ }
439
+ function registerSources(sources) {
440
+ for (const [name, source] of Object.entries(sources)) registerSource(name, source);
33
441
  return sources;
34
442
  }
35
- function createSource(definition, context) {
36
- return definition(context);
443
+ function getRegisteredSource(name) {
444
+ const source = sourceRegistry.get(name);
445
+ if (!source) throw sourceNotFoundError(name);
446
+ return source;
447
+ }
448
+ function clearSources() {
449
+ sourceRegistry.clear();
450
+ }
451
+ /** Open a registered definition with the same lifecycle as direct Source readers. */
452
+ function useSource(name, context) {
453
+ return createSource(getRegisteredSource(name), {
454
+ ...context,
455
+ source: context?.source ?? name
456
+ });
37
457
  }
38
458
  //#endregion
39
459
  //#region src/ignores.ts
@@ -73,9 +493,143 @@ const sourceIgnores = Object.freeze({
73
493
  system
74
494
  });
75
495
  //#endregion
76
- //#region src/sources/custom.ts
77
- function custom(source) {
78
- return source;
496
+ //#region src/sources/file.ts
497
+ function normalizeFileSourceOptions(input) {
498
+ return typeof input === "string" ? { path: input } : input;
499
+ }
500
+ function sourceKey(options) {
501
+ if (Object.hasOwn(options, "workspacePath") && options.workspacePath) return normalizeSafeSourcePath(options.workspacePath);
502
+ if (Object.hasOwn(options, "path") && options.path) return normalizeSourcePath(normalizeSafeSourcePath(options.path));
503
+ throw sourceErrorDiagnostics.SOURCE_R0017({ message: "[vitehub] file requires a path or workspacePath." });
504
+ }
505
+ function resolveSourceRoot(ctx) {
506
+ return ctx.sourceRootDir || ctx.rootDir;
507
+ }
508
+ async function readSourceFile(options, ctx) {
509
+ if (!Object.hasOwn(options, "path") || !options.path) throw sourceErrorDiagnostics.SOURCE_R0018({ message: "[vitehub] file requires path when content is not provided." });
510
+ const { readFile } = await import("node:fs/promises");
511
+ const content = await readFile(await resolveSafeSourceFilePath(options.path, ctx));
512
+ return content.byteOffset === 0 && content.byteLength === content.buffer.byteLength ? new Uint8Array(content.buffer) : new Uint8Array(content);
513
+ }
514
+ async function resolveSafeSourceFilePath(path, ctx) {
515
+ const { realpath } = await import("node:fs/promises");
516
+ const { isAbsolute, relative, resolve, sep } = await import("node:path");
517
+ const root = await realpath(resolve(resolveSourceRoot(ctx)));
518
+ const target = await realpath(resolve(root, normalizeSafeSourcePath(path)));
519
+ const rel = relative(root, target);
520
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw sourcePathError(path);
521
+ return target;
522
+ }
523
+ function file(input) {
524
+ const options = normalizeFileSourceOptions(input);
525
+ const key = sourceKey(options);
526
+ const mediaType = Object.hasOwn(options, "mediaType") && options.mediaType ? options.mediaType : lookup(key);
527
+ return {
528
+ name: "file",
529
+ key,
530
+ async getKeys() {
531
+ return [key];
532
+ },
533
+ async getMeta(requestedKey, ctx) {
534
+ if (requestedKey !== key) return;
535
+ if (!Object.hasOwn(options, "path") || !options.path) return;
536
+ const { stat } = await import("node:fs/promises");
537
+ const info = await stat(await resolveSafeSourceFilePath(options.path, ctx));
538
+ return { digest: `${info.size}:${info.mtimeMs}` };
539
+ },
540
+ async getItem(requestedKey, ctx) {
541
+ if (requestedKey !== key) throw sourceError(`[vitehub] file could not find ${JSON.stringify(requestedKey)}.`);
542
+ const content = Object.hasOwn(options, "content") && options.content !== void 0 ? options.content : await readSourceFile(options, ctx);
543
+ return {
544
+ key,
545
+ path: key,
546
+ content,
547
+ mediaType
548
+ };
549
+ }
550
+ };
551
+ }
552
+ //#endregion
553
+ //#region src/sources/files.ts
554
+ /**
555
+ * A Source of files that the server already holds, keyed by path. A ViteHub build turns `glob()` into this, with the
556
+ * matched files in the server bundle. Call it yourself for files you hold another way.
557
+ */
558
+ function files(entries, options = {}) {
559
+ const base = options.base ? `${options.base.replace(/\\/g, "/").replace(/\/+$/, "")}/` : "";
560
+ const items = /* @__PURE__ */ new Map();
561
+ for (const [path, content] of Object.entries(entries)) {
562
+ const portable = path.replace(/\\/g, "/");
563
+ if (base && !portable.startsWith(base)) throw sourceError(`[vitehub] files() path ${JSON.stringify(path)} does not start with base ${JSON.stringify(options.base)}.`);
564
+ const key = normalizeSafeSourcePath(portable.slice(base.length).replace(/^\.\//, ""));
565
+ if (items.has(key)) throw sourceError(`[vitehub] files() has two files at ${JSON.stringify(key)}.`);
566
+ items.set(key, content);
567
+ }
568
+ const keys = [...items.keys()].sort((left, right) => left.localeCompare(right));
569
+ const prefix = normalizeSafeSourcePath(options.prefix || "", { allowEmpty: true });
570
+ return {
571
+ name: "files",
572
+ async getKeys() {
573
+ return keys.slice();
574
+ },
575
+ async getItem(key) {
576
+ const entry = items.get(key);
577
+ if (entry === void 0) throw sourceError(`[vitehub] files() could not find ${JSON.stringify(key)}.`);
578
+ const content = typeof entry === "function" ? await entry() : entry;
579
+ return {
580
+ key,
581
+ path: normalizeSourcePath(prefix ? `${prefix}/${key}` : key),
582
+ content,
583
+ mediaType: lookup(key)
584
+ };
585
+ }
586
+ };
587
+ }
588
+ //#endregion
589
+ //#region src/sources/github/lazy.ts
590
+ /**
591
+ * github() as the Source root exports it. The loader imports Node built-ins, ocache, and the forge client, so it loads
592
+ * on the first read. A bundle that imports the root and never calls github() keeps none of them.
593
+ */
594
+ function github(options) {
595
+ const root = normalizeGitHubRoot(options.root || "");
596
+ let loader;
597
+ const load = () => loader ??= import("./github-D5S0dEZe.js").then((module) => module.github(options)).catch((error) => {
598
+ loader = void 0;
599
+ throw error;
600
+ });
601
+ return {
602
+ cache: options.cache,
603
+ fingerprint: {
604
+ ignore: options.ignore,
605
+ include: options.include,
606
+ ref: options.ref || "default",
607
+ repo: options.repo,
608
+ root
609
+ },
610
+ name: "github",
611
+ authenticated: async () => await (await load()).authenticated(),
612
+ history: async (key, historyOptions) => await (await load()).history(key, historyOptions),
613
+ latest: async (keys, latestOptions) => await (await load()).latest(keys, latestOptions),
614
+ changes: async (base, head) => await (await load()).changes(base, head),
615
+ pullChanges: async (number) => await (await load()).pullChanges(number),
616
+ resolveRef: async (ref, refOptions) => await (await load()).resolveRef(ref, refOptions),
617
+ contains: async (sha, refOptions) => await (await load()).contains(sha, refOptions),
618
+ pullsAt: async (sha, refOptions) => await (await load()).pullsAt(sha, refOptions),
619
+ resolveRevision: async (ctx) => await (await load()).resolveRevision(ctx),
620
+ getKeys: async (ctx) => await (await load()).getKeys(ctx),
621
+ getItems: async (ctx) => await (await load()).getItems(ctx),
622
+ getMeta: async (key, ctx) => await (await load()).getMeta(key, ctx),
623
+ getItem: async (key, ctx) => await (await load()).getItem(key, ctx)
624
+ };
625
+ }
626
+ //#endregion
627
+ //#region src/sources/markdown.ts
628
+ function markdown(options) {
629
+ return file({
630
+ ...options,
631
+ mediaType: Object.hasOwn(options, "mediaType") && options.mediaType ? options.mediaType : "text/markdown"
632
+ });
79
633
  }
80
634
  //#endregion
81
- export { CollectionCursorError, clearSources, combineSources, createSource, custom, defineCollection, defineSource, defineSources, getRegisteredSource, registerSource, registerSources, sourceIgnores, useSource };
635
+ export { CollectionCursorError, array, clearSources, createSource, defineCollection, defineSource, file, files, github, glob, markdown, registerSource, registerSources, sourceIgnores, splitSource, useSource };
@@ -0,0 +1,22 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ export { invariantError as n, invariant as t };
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { i as SourceCacheOptions, o as SourceContext, r as Source } from "./types-Bu3WvNX9.js";
2
-
1
+ import { l as SourceContext, s as SourceCacheOptions, t as FileSource } from "./types-Ln-FxVFn.js";
3
2
  //#region src/sources/mcp-resources.d.ts
4
3
  interface McpResourcesRequestOptions {
5
4
  maxTotalTimeout?: number;
@@ -147,6 +146,6 @@ interface McpResourcesSourceOptions<TKey extends string = string> {
147
146
  request?: McpResourcesRequestOptions;
148
147
  server: McpResourcesServer;
149
148
  }
150
- declare function mcpResources<const TKey extends string = string>(options: McpResourcesSourceOptions<TKey>): Source<TKey>;
149
+ export declare function mcpResources<const TKey extends string = string>(options: McpResourcesSourceOptions<TKey>): FileSource<TKey>;
151
150
  //#endregion
152
- export { type McpResourceContent, type McpResourceDescriptor, type McpResourcesClient, type McpResourcesClientConfig, type McpResourcesRequestOptions, type McpResourcesServer, type McpResourcesSourceOptions, type McpResourcesTransport, type McpResourcesTransportConfig, mcpResources };
151
+ export type { McpResourceContent, McpResourceDescriptor, McpResourcesClient, McpResourcesClientConfig, McpResourcesRequestOptions, McpResourcesServer, McpResourcesSourceOptions, McpResourcesTransport, McpResourcesTransportConfig };