@vite-hub/source 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +167 -1
  3. package/dist/auth-Ddw55OUG.js +1261 -0
  4. package/dist/client-CDfTmtQu.js +7903 -0
  5. package/dist/client.d.ts +32 -0
  6. package/dist/client.js +121 -0
  7. package/dist/collection-B8pXGM2d.js +141 -0
  8. package/dist/collection-CF2ON__k.d.ts +92 -0
  9. package/dist/collection-route-Dw7QLFyx.js +6 -0
  10. package/dist/content/client.d.ts +3 -0
  11. package/dist/content/client.js +2 -0
  12. package/dist/content.d.ts +44 -0
  13. package/dist/content.js +157 -0
  14. package/dist/file-BSWQg9Qv.js +503 -0
  15. package/dist/{file-slFAccIZ.d.ts → file-EQ3AjVM6.d.ts} +1 -1
  16. package/dist/file.d.ts +2 -0
  17. package/dist/file.js +2 -0
  18. package/dist/{index-CJpN2j6c.d.ts → github.d.ts} +4 -4
  19. package/dist/github.js +1033 -0
  20. package/dist/glob.d.ts +15 -0
  21. package/dist/glob.js +895 -0
  22. package/dist/index.d.ts +69 -10
  23. package/dist/index.js +70 -108
  24. package/dist/{markdown-Beo-0cqc.d.ts → markdown.d.ts} +3 -3
  25. package/dist/{sources/markdown.js → markdown.js} +1 -1
  26. package/dist/mcp.d.ts +152 -0
  27. package/dist/mcp.js +6115 -0
  28. package/dist/{path-B5QNI5sY.js → path-BzmU4Eni.js} +2 -10
  29. package/dist/path-CUhvUREm.js +1936 -0
  30. package/dist/registry-C8skfCSV.js +120 -0
  31. package/dist/server.d.ts +15 -0
  32. package/dist/server.js +71 -0
  33. package/dist/sse-CE9Q2JqM.js +407 -0
  34. package/dist/streamableHttp-BszaXLmg.js +491 -0
  35. package/dist/types-AIBmt_m6.js +6275 -0
  36. package/dist/types-Bu3WvNX9.d.ts +71 -0
  37. package/dist/vite.d.ts +41 -0
  38. package/dist/vite.js +629 -0
  39. package/package.json +68 -30
  40. package/tsconfig.vite.json +6 -0
  41. package/types/source/fallback.d.ts +1 -0
  42. package/types/source/index.d.ts +1 -0
  43. package/dist/chunk-D7D4PA-g.js +0 -13
  44. package/dist/custom-EnZvMLiy.d.ts +0 -6
  45. package/dist/github-B4lgrzXQ.js +0 -565
  46. package/dist/glob-CuxZwoC3.d.ts +0 -15
  47. package/dist/mcp-resources-C7-5Qeh4.d.ts +0 -41
  48. package/dist/mcp-resources-DSDqTfbK.js +0 -307
  49. package/dist/sources/custom.d.ts +0 -2
  50. package/dist/sources/custom.js +0 -6
  51. package/dist/sources/file.d.ts +0 -2
  52. package/dist/sources/file.js +0 -57
  53. package/dist/sources/github.d.ts +0 -2
  54. package/dist/sources/github.js +0 -2
  55. package/dist/sources/glob.d.ts +0 -2
  56. package/dist/sources/glob.js +0 -110
  57. package/dist/sources/index.d.ts +0 -13
  58. package/dist/sources/index.js +0 -18
  59. package/dist/sources/markdown.d.ts +0 -2
  60. package/dist/sources/mcp-resources.d.ts +0 -2
  61. package/dist/sources/mcp-resources.js +0 -2
  62. package/dist/types-f6Lyjq8g.d.ts +0 -73
@@ -0,0 +1,32 @@
1
+ import { f as CollectionQuery, r as CollectionClientItem, t as AnyCollection, u as CollectionPage } from "./collection-CF2ON__k.js";
2
+ import { ComputedRef, MaybeRefOrGetter, Ref } from "vue";
3
+
4
+ //#region src/client.d.ts
5
+ interface CollectionRequestOptions {
6
+ query?: Record<string, unknown>;
7
+ signal: AbortSignal;
8
+ }
9
+ type CollectionRequester = (endpoint: string, options: CollectionRequestOptions) => Promise<unknown>;
10
+ declare global {
11
+ interface ViteHubCollectionMap {}
12
+ }
13
+ type CollectionName = Extract<keyof ViteHubCollectionMap, string>;
14
+ type RegisteredCollection<TName extends CollectionName> = Extract<ViteHubCollectionMap[TName], AnyCollection>;
15
+ interface UseCollectionOptions<TCollection extends AnyCollection> {
16
+ all?: boolean;
17
+ filter?: MaybeRefOrGetter<CollectionQuery<TCollection>>;
18
+ immediate?: boolean;
19
+ limit?: number;
20
+ request?: CollectionRequester;
21
+ }
22
+ interface UseCollectionReturn<TCollection extends AnyCollection> {
23
+ error: Ref<unknown>;
24
+ hasMore: ComputedRef<boolean>;
25
+ items: Ref<Array<CollectionClientItem<TCollection>>>;
26
+ loadMore: () => Promise<CollectionPage<CollectionClientItem<TCollection>> | undefined>;
27
+ pending: Ref<boolean>;
28
+ refresh: () => Promise<CollectionPage<CollectionClientItem<TCollection>> | undefined>;
29
+ }
30
+ declare function useCollection<TName extends CollectionName>(name: TName, options?: UseCollectionOptions<RegisteredCollection<TName>>): UseCollectionReturn<RegisteredCollection<TName>>;
31
+ //#endregion
32
+ export { CollectionName, CollectionRequestOptions, CollectionRequester, UseCollectionOptions, UseCollectionReturn, useCollection };
package/dist/client.js ADDED
@@ -0,0 +1,121 @@
1
+ import { t as encodeCollectionRouteSegment } from "./collection-route-Dw7QLFyx.js";
2
+ import { $fetch } from "ofetch";
3
+ import { computed, onScopeDispose, ref, toValue, watch } from "vue";
4
+ //#region src/client.ts
5
+ const defaultRequester = async (endpoint, options) => {
6
+ return await $fetch(endpoint, options);
7
+ };
8
+ function isAbortError(error) {
9
+ return Object(error) === error && Reflect.get(Object(error), "name") === "AbortError";
10
+ }
11
+ function parseCollectionPage(value) {
12
+ if (Object(value) !== value) throw new TypeError("[vitehub] Collection response must be an object.");
13
+ const items = Reflect.get(Object(value), "items");
14
+ const nextCursor = Reflect.get(Object(value), "nextCursor");
15
+ if (!Array.isArray(items) || !(nextCursor === null || String(nextCursor) === nextCursor)) throw new TypeError("[vitehub] Collection response must contain items and nextCursor.");
16
+ return {
17
+ items,
18
+ nextCursor
19
+ };
20
+ }
21
+ function appBaseURL() {
22
+ try {
23
+ return __VITEHUB_APP_BASE_URL__;
24
+ } catch {
25
+ return "/";
26
+ }
27
+ }
28
+ function collectionEndpoint(name) {
29
+ const path = `/api/${String(name).split("/").map(encodeCollectionRouteSegment).join("/")}`;
30
+ const baseURL = appBaseURL();
31
+ return baseURL.startsWith("/") && !baseURL.startsWith("//") && baseURL !== "/" ? `${baseURL.replace(/\/+$/, "")}${path}` : path;
32
+ }
33
+ function useCollection(name, options = {}) {
34
+ const endpoint = collectionEndpoint(name);
35
+ const items = ref([]);
36
+ const nextCursor = ref(null);
37
+ const pending = ref(false);
38
+ const error = ref(null);
39
+ const request = options.request || defaultRequester;
40
+ let active;
41
+ let cursors = /* @__PURE__ */ new Set();
42
+ let loaded = false;
43
+ async function load(reset) {
44
+ if (!reset && (pending.value || loaded && !nextCursor.value)) return;
45
+ if (reset) {
46
+ cursors = /* @__PURE__ */ new Set();
47
+ nextCursor.value = null;
48
+ loaded = true;
49
+ }
50
+ active?.abort();
51
+ const controller = new AbortController();
52
+ active = controller;
53
+ pending.value = true;
54
+ error.value = null;
55
+ try {
56
+ const filter = options.filter ? toValue(options.filter) : {};
57
+ let cursor = reset ? void 0 : nextCursor.value || void 0;
58
+ let loadedItems = reset ? [] : [...items.value];
59
+ let response;
60
+ const seenCursors = new Set(cursors);
61
+ if (cursor) seenCursors.add(cursor);
62
+ do {
63
+ const parsed = parseCollectionPage(await request(endpoint, {
64
+ query: {
65
+ ...filter,
66
+ cursor,
67
+ limit: options.limit
68
+ },
69
+ signal: controller.signal
70
+ }));
71
+ response = {
72
+ items: parsed.items,
73
+ nextCursor: parsed.nextCursor
74
+ };
75
+ if (active !== controller) return;
76
+ loadedItems = [...loadedItems, ...response.items];
77
+ cursor = response.nextCursor || void 0;
78
+ if (cursor && seenCursors.has(cursor)) throw new TypeError("[vitehub] Collection returned the same cursor twice.");
79
+ if (cursor) seenCursors.add(cursor);
80
+ } while (options.all === true && cursor);
81
+ items.value = loadedItems;
82
+ cursors = seenCursors;
83
+ nextCursor.value = response.nextCursor;
84
+ loaded = true;
85
+ return {
86
+ items: loadedItems,
87
+ nextCursor: response.nextCursor
88
+ };
89
+ } catch (cause) {
90
+ if (active !== controller || isAbortError(cause)) return;
91
+ error.value = cause;
92
+ } finally {
93
+ if (active === controller) {
94
+ active = void 0;
95
+ pending.value = false;
96
+ }
97
+ }
98
+ }
99
+ const stop = watch(() => options.filter ? toValue(options.filter) : void 0, () => {
100
+ load(true);
101
+ }, {
102
+ deep: true,
103
+ immediate: options.immediate !== false && (options.request !== void 0 || "window" in globalThis)
104
+ });
105
+ onScopeDispose(() => {
106
+ stop();
107
+ active?.abort();
108
+ active = void 0;
109
+ pending.value = false;
110
+ });
111
+ return {
112
+ error,
113
+ hasMore: computed(() => Boolean(nextCursor.value)),
114
+ items,
115
+ loadMore: () => load(false),
116
+ pending,
117
+ refresh: () => load(true)
118
+ };
119
+ }
120
+ //#endregion
121
+ export { useCollection };
@@ -0,0 +1,141 @@
1
+ //#region ../internal/src/object.ts
2
+ function isPlainObject(value) {
3
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
4
+ try {
5
+ Function.prototype.toString.call(value);
6
+ return false;
7
+ } catch {
8
+ return true;
9
+ }
10
+ }
11
+ function isPlainRecord(value) {
12
+ if (!isPlainObject(value)) return false;
13
+ const prototype = Object.getPrototypeOf(value);
14
+ if (prototype === null) return true;
15
+ return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
16
+ }
17
+ //#endregion
18
+ //#region src/core/collection.ts
19
+ const defaultPageLimit = 50;
20
+ const defaultMaxLimit = 100;
21
+ var CollectionCursorError = class extends TypeError {
22
+ constructor(message = "[vitehub] Collection cursor is malformed.", options) {
23
+ super(message, options);
24
+ }
25
+ };
26
+ function assertPositiveInteger(value, label) {
27
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`[vitehub] Collection ${label} must be a positive integer.`);
28
+ }
29
+ function resolveLimit(limit, defaultLimit, maxLimit) {
30
+ if (limit !== void 0) assertPositiveInteger(limit, "limit");
31
+ return Math.min(limit ?? defaultLimit, maxLimit);
32
+ }
33
+ function encodeBase64Url(value) {
34
+ const bytes = new TextEncoder().encode(value);
35
+ let binary = "";
36
+ for (const byte of bytes) binary += String.fromCharCode(byte);
37
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
38
+ }
39
+ function decodeBase64Url(value) {
40
+ const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
41
+ const binary = atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="));
42
+ return new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
43
+ }
44
+ function hasPrimitiveRuntimeTag(value, tag) {
45
+ return value !== null && value !== void 0 && Object(value) !== value && Object.prototype.toString.call(value) === tag;
46
+ }
47
+ function isRuntimeNumber(value) {
48
+ return hasPrimitiveRuntimeTag(value, "[object Number]");
49
+ }
50
+ function isRuntimeObject(value) {
51
+ return value !== null && Object(value) === value;
52
+ }
53
+ function isRuntimeString(value) {
54
+ return hasPrimitiveRuntimeTag(value, "[object String]");
55
+ }
56
+ function isCursorValue(value, ancestors = /* @__PURE__ */ new Set()) {
57
+ if (isRuntimeNumber(value)) return Number.isFinite(value) && !Object.is(value, -0);
58
+ if (value === null || value === true || value === false || isRuntimeString(value)) return true;
59
+ if (!isRuntimeObject(value) || ancestors.has(value)) return false;
60
+ ancestors.add(value);
61
+ try {
62
+ if (Array.isArray(value)) {
63
+ const keys = Reflect.ownKeys(value);
64
+ if (keys.length !== value.length + 1 || keys.some((key) => key !== "length" && !isRuntimeString(key))) return false;
65
+ for (let index = 0; index < value.length; index += 1) {
66
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
67
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isCursorValue(descriptor.value, ancestors)) return false;
68
+ }
69
+ return true;
70
+ }
71
+ if (!isPlainRecord(value)) return false;
72
+ for (const key of Reflect.ownKeys(value)) {
73
+ if (!isRuntimeString(key)) return false;
74
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
75
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isCursorValue(descriptor.value, ancestors)) return false;
76
+ }
77
+ return true;
78
+ } catch {
79
+ return false;
80
+ } finally {
81
+ ancestors.delete(value);
82
+ }
83
+ }
84
+ function encodeCursor(value) {
85
+ if (!isCursorValue(value)) throw new TypeError("[vitehub] Collection cursor() must return a JSON-serializable value.");
86
+ return encodeBase64Url(JSON.stringify(value));
87
+ }
88
+ async function parseSchema(schema, value) {
89
+ const result = await schema["~standard"].validate(value);
90
+ if (result.issues) throw new TypeError(result.issues[0]?.message ?? "Collection value is invalid.");
91
+ return result.value;
92
+ }
93
+ async function decodeCursor(value, schema) {
94
+ if (value === void 0) return;
95
+ let decoded;
96
+ try {
97
+ decoded = JSON.parse(decodeBase64Url(value));
98
+ } catch (cause) {
99
+ throw new CollectionCursorError(void 0, { cause });
100
+ }
101
+ if (!isCursorValue(decoded)) throw new CollectionCursorError();
102
+ try {
103
+ const cursor = await parseSchema(schema, decoded);
104
+ if (!isCursorValue(cursor)) throw new TypeError("Collection cursor schema returned an invalid value.");
105
+ return cursor;
106
+ } catch (cause) {
107
+ throw new CollectionCursorError(void 0, { cause });
108
+ }
109
+ }
110
+ function defineCollection(load, definition) {
111
+ const defaultLimit = definition.defaultLimit ?? defaultPageLimit;
112
+ const maxLimit = definition.maxLimit ?? defaultMaxLimit;
113
+ assertPositiveInteger(defaultLimit, "defaultLimit");
114
+ assertPositiveInteger(maxLimit, "maxLimit");
115
+ if (defaultLimit > maxLimit) throw new TypeError("[vitehub] Collection defaultLimit cannot exceed maxLimit.");
116
+ return {
117
+ async page(request) {
118
+ const limit = resolveLimit(request.limit, defaultLimit, maxLimit);
119
+ const sourceItems = await load({
120
+ cursor: await decodeCursor(request.cursor, definition.cursorSchema),
121
+ limit: limit + 1,
122
+ query: request.query,
123
+ signal: request.signal
124
+ });
125
+ if (!Array.isArray(sourceItems)) throw new TypeError("[vitehub] Collection load() must return an array.");
126
+ const hasMore = sourceItems.length > limit;
127
+ const pageItems = sourceItems.slice(0, limit);
128
+ const nextCursor = hasMore && pageItems.length ? encodeCursor(definition.cursor(pageItems[pageItems.length - 1])) : null;
129
+ return {
130
+ items: definition.transform ? await Promise.all(pageItems.map(definition.transform)) : pageItems,
131
+ nextCursor
132
+ };
133
+ },
134
+ async parseQuery(input) {
135
+ if (definition.querySchema) return await parseSchema(definition.querySchema, input);
136
+ return input;
137
+ }
138
+ };
139
+ }
140
+ //#endregion
141
+ export { defineCollection as n, CollectionCursorError as t };
@@ -0,0 +1,92 @@
1
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
+
3
+ //#region src/core/collection.d.ts
4
+ declare const collectionQueryInput: unique symbol;
5
+ type CollectionRequestQuery = Record<string, string | readonly string[] | undefined>;
6
+ type CollectionCursorValue = boolean | null | number | string | readonly CollectionCursorValue[] | {
7
+ readonly [key: string]: CollectionCursorValue;
8
+ };
9
+ interface CollectionLoadOptions<TQuery extends object, TCursor extends CollectionCursorValue> {
10
+ cursor?: TCursor;
11
+ limit: number;
12
+ query: TQuery;
13
+ signal?: AbortSignal;
14
+ }
15
+ interface CollectionPageOptions<TQuery extends object> {
16
+ cursor?: string;
17
+ limit?: number;
18
+ query: TQuery;
19
+ signal?: AbortSignal;
20
+ }
21
+ interface CollectionPage<TItem> {
22
+ items: TItem[];
23
+ nextCursor: string | null;
24
+ }
25
+ interface Collection<TItem, TQuery extends object = CollectionRequestQuery, TQueryInput extends object = TQuery> {
26
+ readonly [collectionQueryInput]?: TQueryInput;
27
+ page(options: CollectionPageOptions<TQuery>): Promise<CollectionPage<TItem>>;
28
+ parseQuery(input: CollectionRequestQuery): Promise<TQuery>;
29
+ }
30
+ type AnyCollection = Collection<any, any, any>;
31
+ type CollectionItem<TCollection extends AnyCollection> = TCollection extends Collection<infer TItem, any, any> ? TItem : never;
32
+ type JSONOmitted = undefined | ((...args: any[]) => any) | symbol;
33
+ type JSONUnsupportedObject = ArrayBuffer | ArrayBufferView | Date | Error | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | RegExp | SharedArrayBuffer | URL | WeakMap<object, unknown> | WeakSet<object>;
34
+ type JSONOmittedBranch<T> = T extends {
35
+ toJSON(): infer TJSON;
36
+ } ? TJSON extends JSONOmitted ? TJSON : never : T extends JSONOmitted ? T : never;
37
+ type JSONSerializedValue<T> = T extends {
38
+ toJSON(): infer TJSON;
39
+ } ? JSONSerializedPostToJSON<TJSON> : JSONSerializedPostToJSON<T>;
40
+ type JSONSerializedPostToJSON<T> = T extends bigint | JSONUnsupportedObject ? never : T extends number ? number | null : T extends boolean | null | string ? T : T extends readonly (infer TItem)[] ? Array<JSONSerializedArrayItem<TItem>> : T extends object ? JSONSerializedObject<T> : never;
41
+ type JSONSerialized<T> = T extends unknown ? JSONSerializedValue<T> : never;
42
+ type JSONSerializedArrayItem<T> = T extends {
43
+ toJSON(): infer TJSON;
44
+ } ? JSONSerializedArrayValue<TJSON> : JSONSerializedArrayValue<T>;
45
+ type JSONSerializedArrayValue<T> = T extends JSONOmitted ? null : JSONSerializedPostToJSON<T>;
46
+ type Simplify<T> = { [TKey in keyof T]: T[TKey] };
47
+ type JSONSerializedObject<T extends object> = Simplify<{ [TKey in keyof T as TKey extends symbol ? never : [JSONOmittedBranch<T[TKey]>] extends [never] ? TKey : never]: JSONSerialized<T[TKey]> } & { [TKey in keyof T as TKey extends symbol ? never : [JSONOmittedBranch<T[TKey]>] extends [never] ? never : [JSONSerialized<T[TKey]>] extends [never] ? never : TKey]?: JSONSerialized<T[TKey]> }>;
48
+ type CollectionClientItem<TCollection extends AnyCollection> = JSONSerializedArrayItem<CollectionItem<TCollection>>;
49
+ type CollectionQuery<TCollection extends AnyCollection> = TCollection extends Collection<any, any, infer TQueryInput> ? TQueryInput : never;
50
+ type CollectionLoader<TSourceItem, TQuery extends object, TCursor extends CollectionCursorValue> = (options: CollectionLoadOptions<TQuery, TCursor>) => Promise<readonly TSourceItem[]>;
51
+ type CollectionTransform<TSourceItem> = (item: NoInfer<TSourceItem>) => unknown;
52
+ interface CollectionOptions<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue, TCursorOutput extends CollectionCursorValue = TCursorInput> {
53
+ cursor(item: NoInfer<TSourceItem>): Readonly<TCursorInput>;
54
+ cursorSchema: StandardSchemaV1<TCursorInput, TCursorOutput>;
55
+ defaultLimit?: number;
56
+ maxLimit?: number;
57
+ querySchema?: StandardSchemaV1<unknown, TQuery>;
58
+ transform?: CollectionTransform<TSourceItem>;
59
+ }
60
+ type CollectionDefinition<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue> = Omit<CollectionOptions<TSourceItem, TQuery, TCursorInput>, "cursorSchema" | "querySchema" | "transform">;
61
+ type CursorInput<TSchema extends StandardSchemaV1> = [StandardSchemaV1.InferInput<TSchema>] extends [CollectionCursorValue] ? StandardSchemaV1.InferInput<TSchema> : never;
62
+ type CursorOutput<TSchema extends StandardSchemaV1> = [StandardSchemaV1.InferOutput<TSchema>] extends [CollectionCursorValue] ? StandardSchemaV1.InferOutput<TSchema> : never;
63
+ type RepeatedQueryValues = [string, string, ...string[]];
64
+ type AmbiguousArrayQueryKey<TInput extends object> = { [TKey in keyof TInput]-?: [Extract<TInput[TKey], readonly string[]>] extends [never] ? never : RepeatedQueryValues extends TInput[TKey] ? string extends TInput[TKey] ? undefined extends TInput[TKey] ? never : TKey : TKey : TKey }[keyof TInput];
65
+ type ReservedCollectionQueryKey = "cursor" | "limit";
66
+ type CollectionQueryInput<TInput> = TInput extends object ? [Exclude<keyof TInput, string>] extends [never] ? [Extract<ReservedCollectionQueryKey, keyof TInput>] extends [never] ? [TInput[keyof TInput]] extends [CollectionRequestQuery[string]] ? [AmbiguousArrayQueryKey<TInput>] extends [never] ? TInput : never : never : never : never : never;
67
+ type QueryInput<TSchema extends StandardSchemaV1> = CollectionQueryInput<StandardSchemaV1.InferInput<TSchema>>;
68
+ declare class CollectionCursorError extends TypeError {
69
+ constructor(message?: string, options?: ErrorOptions);
70
+ }
71
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1, TQuerySchema extends StandardSchemaV1<unknown, object>, TTransform extends CollectionTransform<TSourceItem>>(load: CollectionLoader<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, CursorInput<TCursorSchema>> & {
72
+ cursorSchema: TCursorSchema;
73
+ querySchema: TQuerySchema;
74
+ transform: TTransform;
75
+ }): Collection<Awaited<ReturnType<TTransform>>, StandardSchemaV1.InferOutput<TQuerySchema>, QueryInput<TQuerySchema>>;
76
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1, TQuerySchema extends StandardSchemaV1<unknown, object>>(load: CollectionLoader<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, CursorInput<TCursorSchema>> & {
77
+ cursorSchema: TCursorSchema;
78
+ querySchema: TQuerySchema;
79
+ transform?: undefined;
80
+ }): Collection<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, QueryInput<TQuerySchema>>;
81
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1, TTransform extends CollectionTransform<TSourceItem>>(load: CollectionLoader<TSourceItem, CollectionRequestQuery, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, CollectionRequestQuery, CursorInput<TCursorSchema>> & {
82
+ cursorSchema: TCursorSchema;
83
+ querySchema?: undefined;
84
+ transform: TTransform;
85
+ }): Collection<Awaited<ReturnType<TTransform>>, CollectionRequestQuery, CollectionRequestQuery>;
86
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1>(load: CollectionLoader<TSourceItem, CollectionRequestQuery, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, CollectionRequestQuery, CursorInput<TCursorSchema>> & {
87
+ cursorSchema: TCursorSchema;
88
+ querySchema?: undefined;
89
+ transform?: undefined;
90
+ }): Collection<TSourceItem, CollectionRequestQuery, CollectionRequestQuery>;
91
+ //#endregion
92
+ export { CollectionCursorValue as a, CollectionLoader as c, CollectionPageOptions as d, CollectionQuery as f, defineCollection as h, CollectionCursorError as i, CollectionOptions as l, CollectionRequestQuery as m, Collection as n, CollectionItem as o, CollectionQueryInput as p, CollectionClientItem as r, CollectionLoadOptions as s, AnyCollection as t, CollectionPage as u };
@@ -0,0 +1,6 @@
1
+ //#region src/internal/collection-route.ts
2
+ function encodeCollectionRouteSegment(segment) {
3
+ return encodeURIComponent(segment).replaceAll("*", "%2A");
4
+ }
5
+ //#endregion
6
+ export { encodeCollectionRouteSegment as t };
@@ -0,0 +1,3 @@
1
+ import { createContentClient, defineContentClientPlugin } from "comark-content/client";
2
+ export type * from "comark-content/client";
3
+ export { createContentClient, defineContentClientPlugin };
@@ -0,0 +1,2 @@
1
+ import { createContentClient, defineContentClientPlugin } from "comark-content/client";
2
+ export { createContentClient, defineContentClientPlugin };
@@ -0,0 +1,44 @@
1
+ import { m as SourceReader, p as SourceName } from "./types-Bu3WvNX9.js";
2
+ import { ComarkContent, ContentOptions, ContentPlugin, JsonSchema, Source } from "comark-content";
3
+
4
+ //#region src/content.d.ts
5
+ interface ContentHandler {
6
+ (event: unknown): Promise<unknown>;
7
+ fetch(input: Request | URL | string): Promise<Response>;
8
+ }
9
+ interface ContentHandlerEvent {
10
+ method?: string;
11
+ node?: {
12
+ req: NodeContentRequest;
13
+ };
14
+ req: Request | NodeContentRequest;
15
+ }
16
+ interface ContentSourceOptions {
17
+ prefix?: string;
18
+ schema?: JsonSchema;
19
+ }
20
+ type NodeContentRequest = {
21
+ aborted: boolean;
22
+ headers: Record<string, string | string[] | undefined>;
23
+ method?: string;
24
+ url?: string;
25
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
26
+ once(event: "aborted", listener: () => void): unknown;
27
+ };
28
+ type ContentSourceInput = SourceName | SourceReader | (() => SourceReader) | Source;
29
+ type PluginMethods<TPlugin> = TPlugin extends ContentPlugin<infer TMethods, any> ? TMethods : unknown;
30
+ type UnionToIntersection<T> = (T extends unknown ? (value: T) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
31
+ type ContentMethods<TPlugins extends ReadonlyArray<ContentPlugin<any, any>>> = TPlugins["length"] extends 0 ? unknown : UnionToIntersection<PluginMethods<TPlugins[number]>>;
32
+ type DefineContentOptions<TPlugins extends ReadonlyArray<ContentPlugin<any, any>> = ReadonlyArray<ContentPlugin<any, any>>> = Omit<ContentOptions, "basePath" | "plugins" | "source" | "sources"> & {
33
+ plugins?: TPlugins;
34
+ source?: ContentSourceInput;
35
+ sources?: Record<string, ContentSourceInput>;
36
+ };
37
+ /** Adapt a registered ViteHub Source or Source Reader to the interface consumed by Comark Content. */
38
+ declare function contentSource(input: ContentSourceInput, options?: ContentSourceOptions): Source;
39
+ /** Define the Comark Content runtime served by ViteHub from `server/content.ts`. */
40
+ declare function defineContent<const TPlugins extends ReadonlyArray<ContentPlugin<any, any>> = []>(options?: DefineContentOptions<TPlugins>): ComarkContent & ContentMethods<TPlugins>;
41
+ /** Adapt a Comark Content Web handler to an H3/Nitro route. */
42
+ declare function defineContentHandler(content: Pick<ComarkContent, "handler">): ContentHandler;
43
+ //#endregion
44
+ export { ContentHandler, ContentHandlerEvent, ContentSourceInput, ContentSourceOptions, DefineContentOptions, contentSource, defineContent, defineContentHandler };
@@ -0,0 +1,157 @@
1
+ import { n as normalizeSafeSourcePath } from "./path-BzmU4Eni.js";
2
+ import { a as useSource } from "./registry-C8skfCSV.js";
3
+ import { comarkContent } from "comark-content";
4
+ import { defineEventHandler } from "h3";
5
+ //#region src/content.ts
6
+ function contentPath(item) {
7
+ return normalizeSafeSourcePath(item.path || item.key);
8
+ }
9
+ function textContent(item) {
10
+ if (item.content instanceof Uint8Array) return new TextDecoder().decode(item.content);
11
+ if (item.content !== void 0) return item.content;
12
+ if (item.data !== void 0) {
13
+ const serialized = JSON.stringify(item.data);
14
+ if (serialized !== void 0) return serialized;
15
+ }
16
+ throw new TypeError(`[vitehub] contentSource() cannot read ${JSON.stringify(item.key)} as content.`);
17
+ }
18
+ function isRuntimeFunction(value) {
19
+ if (value === null || Object(value) !== value) return false;
20
+ try {
21
+ Function.prototype.toString.call(value);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+ function isRuntimeObject(value) {
28
+ return value !== null && Object(value) === value && !isRuntimeFunction(value);
29
+ }
30
+ function isComarkContentSource(input) {
31
+ return isRuntimeObject(input) && "getItem" in input && isRuntimeFunction(input.getItem) && "getItemRaw" in input && isRuntimeFunction(input.getItemRaw) && "keys" in input && isRuntimeFunction(input.keys);
32
+ }
33
+ function isSourceReaderFactory(input) {
34
+ return input instanceof Function;
35
+ }
36
+ function isSourceName(input) {
37
+ return !(input instanceof Object);
38
+ }
39
+ function configuredContentSource(input, options) {
40
+ const source = {
41
+ getItem: input.getItem.bind(input),
42
+ getItemRaw: input.getItemRaw.bind(input),
43
+ keys: input.keys.bind(input),
44
+ prefix: options.prefix ?? input.prefix,
45
+ schema: options.schema ?? input.schema
46
+ };
47
+ if (input.watch) source.watch = input.watch.bind(input);
48
+ return source;
49
+ }
50
+ /** Adapt a registered ViteHub Source or Source Reader to the interface consumed by Comark Content. */
51
+ function contentSource(input, options = {}) {
52
+ if (isComarkContentSource(input)) return options.prefix === void 0 && options.schema === void 0 ? input : configuredContentSource(input, options);
53
+ const sourceInput = input;
54
+ const pendingLoads = [];
55
+ let latestItems;
56
+ async function loadItems() {
57
+ const nextItems = /* @__PURE__ */ new Map();
58
+ const currentReader = isSourceName(sourceInput) ? useSource(sourceInput) : isSourceReaderFactory(sourceInput) ? sourceInput() : sourceInput;
59
+ for (const item of await currentReader.items()) {
60
+ const path = contentPath(item);
61
+ if (nextItems.has(path)) throw new TypeError(`[vitehub] contentSource() received duplicate content path ${JSON.stringify(path)}.`);
62
+ nextItems.set(path, item);
63
+ }
64
+ return nextItems;
65
+ }
66
+ async function findItem(key) {
67
+ const path = normalizeSafeSourcePath(key);
68
+ const loadIndex = pendingLoads.findIndex((items) => items.has(path));
69
+ if (loadIndex !== -1) {
70
+ const items = pendingLoads[loadIndex];
71
+ const item = items.get(path);
72
+ items.delete(path);
73
+ if (items.size === 0) pendingLoads.splice(loadIndex, 1);
74
+ return item;
75
+ }
76
+ return (await loadItems()).get(path);
77
+ }
78
+ const source = {
79
+ async keys() {
80
+ const items = await loadItems();
81
+ latestItems = items;
82
+ const pendingItems = new Map(items);
83
+ pendingLoads.push(pendingItems);
84
+ setTimeout(() => {
85
+ const loadIndex = pendingLoads.indexOf(pendingItems);
86
+ if (loadIndex !== -1) pendingLoads.splice(loadIndex, 1);
87
+ }, 0);
88
+ return [...items.keys()];
89
+ },
90
+ async getItem(key) {
91
+ const item = await findItem(key);
92
+ if (!item) throw new TypeError(`[vitehub] contentSource() could not find ${JSON.stringify(key)}.`);
93
+ return textContent(item);
94
+ },
95
+ async getItemRaw(key) {
96
+ const path = normalizeSafeSourcePath(key);
97
+ const item = (latestItems ?? await loadItems()).get(path);
98
+ if (!item) return;
99
+ return item.data ?? item.content;
100
+ }
101
+ };
102
+ if (options.prefix !== void 0) source.prefix = options.prefix;
103
+ if (options.schema !== void 0) source.schema = options.schema;
104
+ return source;
105
+ }
106
+ /** Define the Comark Content runtime served by ViteHub from `server/content.ts`. */
107
+ function defineContent(options = {}) {
108
+ const source = options.source ? contentSource(options.source) : void 0;
109
+ const sources = options.sources ? Object.fromEntries(Object.entries(options.sources).map(([name, input]) => [name, contentSource(input)])) : void 0;
110
+ return comarkContent({
111
+ ...options,
112
+ basePath: "/api/content",
113
+ source,
114
+ sources
115
+ });
116
+ }
117
+ /** Adapt a Comark Content Web handler to an H3/Nitro route. */
118
+ function defineContentHandler(content) {
119
+ return defineEventHandler(async (event) => {
120
+ if (event.req instanceof Request) return await content.handler(event.req);
121
+ if (!event.node) throw new TypeError("[vitehub] Content received an unsupported non-Web request.");
122
+ const nodeRequest = event.node.req;
123
+ const method = event.method || nodeRequest.method || "GET";
124
+ const headers = new Headers();
125
+ for (const [name, value] of Object.entries(nodeRequest.headers)) {
126
+ if (value === void 0) continue;
127
+ if (value instanceof Array) for (const entry of value) headers.append(name, entry);
128
+ else headers.set(name, value);
129
+ }
130
+ const protocol = headers.get("x-forwarded-proto")?.split(",", 1)[0]?.trim() || "http";
131
+ const host = headers.get("x-forwarded-host")?.split(",", 1)[0]?.trim() || headers.get("host") || "localhost";
132
+ const url = new URL(nodeRequest.url || "/", `${protocol}://${host}`);
133
+ let body;
134
+ if (method !== "GET" && method !== "HEAD") {
135
+ const chunks = [];
136
+ for await (const chunk of nodeRequest) chunks.push(chunk);
137
+ const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
138
+ body = new Uint8Array(length);
139
+ let offset = 0;
140
+ for (const chunk of chunks) {
141
+ body.set(chunk, offset);
142
+ offset += chunk.byteLength;
143
+ }
144
+ }
145
+ const abort = new AbortController();
146
+ if (nodeRequest.aborted) abort.abort();
147
+ else nodeRequest.once("aborted", () => abort.abort());
148
+ return await content.handler(new Request(url, {
149
+ body,
150
+ headers,
151
+ method,
152
+ signal: abort.signal
153
+ }));
154
+ });
155
+ }
156
+ //#endregion
157
+ export { contentSource, defineContent, defineContentHandler };