@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
@@ -0,0 +1,32 @@
1
+ import { ViteHubError } from "@vite-hub/runtime";
2
+ //#region src/core/errors.ts
3
+ function sourceError(message, options) {
4
+ return new ViteHubError("SOURCE_FAILED", message, options);
5
+ }
6
+ function sourceNotFoundError(name) {
7
+ return new ViteHubError("SOURCE_NOT_FOUND", `[vitehub] Source "${name}" is not registered.`, { details: { name } });
8
+ }
9
+ function sourcePathError(path) {
10
+ const publicPath = path.slice(0, 4096);
11
+ return new ViteHubError("SOURCE_PATH_INVALID", `[vitehub] Source path escapes the source root: ${JSON.stringify(publicPath)}.`, { details: { path: publicPath } });
12
+ }
13
+ //#endregion
14
+ //#region src/core/path.ts
15
+ function normalizeSourcePath(path = "") {
16
+ return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
17
+ }
18
+ function normalizeSafeSourcePath(path = "", options = {}) {
19
+ const raw = path.replace(/\\/g, "/");
20
+ const normalized = normalizeSourcePath(path);
21
+ const parts = normalized.split("/").filter(Boolean);
22
+ if (!options.allowEmpty && !normalized) throw sourcePathError(path);
23
+ if (raw.startsWith("/") || /^[a-z]:/i.test(raw) || raw.includes("\0") || parts.some((part) => part === "." || part === "..")) throw sourcePathError(path);
24
+ if (!options.allowReserved && (parts[0] === ".git" || parts[0] === ".vitehub")) throw sourcePathError(path);
25
+ return normalized;
26
+ }
27
+ function decodeSourceContent(content, options) {
28
+ if (options?.encoding === "binary") return typeof content === "string" ? new TextEncoder().encode(content) : content;
29
+ return typeof content === "string" ? content : new TextDecoder().decode(content);
30
+ }
31
+ //#endregion
32
+ export { sourceNotFoundError as a, sourceError as i, normalizeSafeSourcePath as n, sourcePathError as o, normalizeSourcePath as r, decodeSourceContent as t };
@@ -0,0 +1,265 @@
1
+ import { r as Collection } from "./collection-B_4w_J8h.js";
2
+ import { AccessAuthorizeOption } from "@vite-hub/runtime";
3
+ //#region ../../node_modules/.pnpm/ocache@0.3.0/node_modules/ocache/dist/index.d.mts
4
+ interface StorageInterface {
5
+ get<T = unknown>(key: string): T | null | Promise<T | null>;
6
+ set<T = unknown>(key: string, value: T, opts?: {
7
+ ttl?: number;
8
+ }): void | Promise<void>;
9
+ /**
10
+ * Largest byte charge one entry may have, when the backend enforces a ceiling.
11
+ *
12
+ * The HTTP layer derives its response-body limit from this value so that a body the
13
+ * backend could never store is refused before it is buffered.
14
+ */
15
+ maxEntryBytes?: number;
16
+ /**
17
+ * Whether stored values return byte views unchanged, including views nested in an object.
18
+ *
19
+ * Cached handlers store a binary response body as a `Uint8Array` when a backend declares
20
+ * this, and as base64 text otherwise. A backend that serializes entries must leave it unset:
21
+ * JSON renders a byte view as `{"0":255,...}`, which no reader can undo. A value read back
22
+ * in that shape is rejected as a miss rather than served.
23
+ *
24
+ * A declaring backend hands the same view to every hit, so nothing may mutate a stored body.
25
+ */
26
+ binary?: boolean;
27
+ }
28
+ /**
29
+ * A storage instance or a late-bound storage factory.
30
+ *
31
+ * The cache calls a factory once, on the first cache operation.
32
+ */
33
+ type StorageOption = StorageInterface | (() => StorageInterface);
34
+ /**
35
+ * Result of one cache call.
36
+ *
37
+ * - `"hit"`: returned a fresh stored value.
38
+ * - `"stale"`: returned stale data and started background revalidation.
39
+ * - `"revalidated"`: replaced an old value before returning.
40
+ * - `"miss"`: resolved a value when none existed.
41
+ */
42
+ type CacheStatus = "hit" | "stale" | "revalidated" | "miss";
43
+ /** Cached value and its metadata. */
44
+ interface CacheEntry<T = any> {
45
+ value?: T;
46
+ /** Expiry time in Unix milliseconds. */
47
+ expires?: number;
48
+ /** Last resolution time in Unix milliseconds. */
49
+ mtime?: number;
50
+ /** Hash of the cached function and computation options. */
51
+ integrity?: string;
52
+ /** Forces revalidation on the next access. */
53
+ stale?: boolean;
54
+ /** Per-entry fresh lifetime in seconds. */
55
+ maxAge?: number;
56
+ /** Per-entry stale lifetime in seconds. */
57
+ staleMaxAge?: number;
58
+ /**
59
+ * Stored form of a binary {@link value}.
60
+ *
61
+ * Set only for a value that is a byte view: `"bytes"` when the backend declares
62
+ * `StorageInterface.binary`, and `"base64"` when it does not.
63
+ * The field exists only between the storage write and the read that decodes it;
64
+ * hooks and callers always see a `Uint8Array`.
65
+ */
66
+ encoding?: "bytes" | "base64";
67
+ /**
68
+ * Where this entry's bulk payload sits.
69
+ *
70
+ * A storage codec reads this to move the payload as bytes, outside whatever document
71
+ * holds the metadata: `"value"` for a cached function whose value is the payload, and
72
+ * `"value.body"` for a cached handler's response body. See {@link createBlobStorage}.
73
+ *
74
+ * The producer of the stored shape declares it, so a codec never infers a payload from
75
+ * the value. Like {@link encoding} it describes storage, not the value: it exists only
76
+ * between the storage write and the read that consumes it, and is written again from the
77
+ * options in use.
78
+ */
79
+ payload?: "value" | "value.body";
80
+ /**
81
+ * Status for the current call.
82
+ * This field is available to `transform` and is not stored.
83
+ */
84
+ status?: CacheStatus;
85
+ }
86
+ /**
87
+ * Options for cached functions.
88
+ *
89
+ * Explicit `undefined` values use defaults.
90
+ * `null` values remain unchanged.
91
+ */
92
+ interface CacheOptions<T = any, ArgsT extends unknown[] = any[]> {
93
+ /**
94
+ * Cache-key name.
95
+ *
96
+ * Defaults to the function name or an anonymous function source hash.
97
+ * Pass an explicit name for equal-source closures created by factories or loops.
98
+ */
99
+ name?: string;
100
+ /** Returns a cache key from the function arguments. */
101
+ getKey?: (...args: ArgsT) => string | Promise<string>;
102
+ /** Transforms an entry before return. The return value replaces the cached value unless it is `undefined`. */
103
+ transform?: (entry: CacheEntry<T>, ...args: ArgsT) => any;
104
+ /**
105
+ * Converts a resolved value to its stored form.
106
+ *
107
+ * Runs once per resolution after `getMaxAge`.
108
+ * It may safely consume a one-use source shared by deduplicated callers.
109
+ * `validate` receives this stored form on writes and reads.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * serialize: async (entry) => ({ ...entry.value, body: await streamToString(entry.value.body) }),
114
+ * ```
115
+ */
116
+ serialize?: (entry: CacheEntry<T>, ctx: {
117
+ args: ArgsT;
118
+ }) => any;
119
+ /**
120
+ * Declares where the stored value's bulk payload sits, for a storage codec.
121
+ *
122
+ * `"value.body"` names the `body` member of an object value, as a `serialize` hook
123
+ * returning `{ body, ... }` produces. A value that is a byte view is its own payload and
124
+ * needs no declaration. Anything else stays inside the metadata document.
125
+ *
126
+ * Only {@link createBlobStorage} and other byte-payload backends read this; every other
127
+ * backend ignores it. See {@link CacheEntry.payload}.
128
+ */
129
+ payload?: "value.body";
130
+ /**
131
+ * Validates an entry for the current arguments.
132
+ * Return or resolve to `false` to revalidate it.
133
+ */
134
+ validate?: (entry: CacheEntry<T>, ctx: {
135
+ args: ArgsT;
136
+ }) => boolean | Promise<boolean>;
137
+ /** Return `true` to trigger revalidation. */
138
+ shouldInvalidateCache?: (...args: ArgsT) => boolean | Promise<boolean>;
139
+ /** Return `true` to call the function without cache processing. */
140
+ shouldBypassCache?: (...args: ArgsT) => boolean | Promise<boolean>;
141
+ /** Cache-key group. Defaults to `"functions"`. Escaped like `name`. */
142
+ group?: string;
143
+ /** Integrity value. Defaults to a hash of the function and options. */
144
+ integrity?: any;
145
+ /**
146
+ * Fresh lifetime in seconds. Defaults to `1`.
147
+ * A non-positive lifetime prevents storage.
148
+ */
149
+ maxAge?: number;
150
+ /**
151
+ * Enables stale-while-revalidate. Defaults to `false`.
152
+ *
153
+ * Without {@link staleMaxAge}, stale reuse is limited only by backend eviction.
154
+ */
155
+ swr?: boolean;
156
+ /**
157
+ * Stale lifetime in seconds.
158
+ *
159
+ * `0` requires foreground revalidation.
160
+ * An unset value allows stale reuse until backend eviction.
161
+ */
162
+ staleMaxAge?: number;
163
+ /**
164
+ * Returns per-entry lifetimes after resolution and before storage.
165
+ *
166
+ * A number sets `maxAge`.
167
+ * An object can set `maxAge` and `staleMaxAge`.
168
+ * Returned fields override static options for freshness, storage, and Cache-Control.
169
+ * Non-positive `maxAge` values prevent storage.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * getMaxAge: (entry) => entry.value?.expires_in,
174
+ * getMaxAge: () => ({ maxAge: 60, staleMaxAge: 300 }),
175
+ * ```
176
+ */
177
+ getMaxAge?: (entry: CacheEntry<T>) => number | {
178
+ maxAge?: number;
179
+ staleMaxAge?: number;
180
+ } | undefined | Promise<number | {
181
+ maxAge?: number;
182
+ staleMaxAge?: number;
183
+ } | undefined>;
184
+ /**
185
+ * Deadline for one shared resolution and its hooks, in seconds.
186
+ *
187
+ * Defaults to `30`.
188
+ * Set `Infinity` or `0` to disable the deadline.
189
+ * On timeout, all waiters reject with `TimeoutError` and the old entry is evicted.
190
+ * A handler's `event.req.signal` aborts with that error; a plain resolver receives no
191
+ * signal, so it continues but cannot write its late result.
192
+ */
193
+ maxResolveTime?: number;
194
+ /**
195
+ * Cache-key base prefixes. Defaults to `"/cache"`.
196
+ * Reads stop at the first hit. Misses write every prefix.
197
+ * Revalidation writes the hit prefix and every earlier prefix.
198
+ */
199
+ base?: string | string[];
200
+ /**
201
+ * Storage instance or late-bound factory.
202
+ *
203
+ * Defaults to one memory store per cached function or handler.
204
+ * Pass the same instance to share entries.
205
+ * A factory runs once on the first cache operation.
206
+ * The cache writes the resolved instance back to this options object.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * const storage = createMemoryStorage();
211
+ * const a = cachedFunction(fnA, { storage });
212
+ * const b = cachedFunction(fnB, { storage });
213
+ * ```
214
+ */
215
+ storage?: StorageOption;
216
+ /**
217
+ * Registers background work with the host: cache writes, SWR refreshes, and evictions.
218
+ *
219
+ * A cached function has no event to read `req.waitUntil` from, so a serverless host may
220
+ * freeze the process before an SWR refresh lands. Pass the platform hook here.
221
+ * Takes precedence over `event.req.waitUntil` when both are present, so one promise is
222
+ * never registered twice.
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * const cached = cachedFunction(fn, { swr: true, waitUntil: (p) => ctx.waitUntil(p) });
227
+ * ```
228
+ */
229
+ waitUntil?: (promise: Promise<any>) => void;
230
+ /** Receives handled cache, hook, and background errors. */
231
+ onError?: (error: unknown) => void;
232
+ }
233
+ //#endregion
234
+ //#region src/cached-source.d.ts
235
+ interface KeyedSourceReader {
236
+ get(key: never): Promise<unknown>;
237
+ }
238
+ type ValidCachedGet<TReader extends KeyedSourceReader> = (<T>() => T extends TReader["get"] ? 1 : 2) extends (<T>() => T extends ((key: Parameters<TReader["get"]>[0]) => ReturnType<TReader["get"]>) ? 1 : 2) ? unknown : never;
239
+ type SourceReaderCacheOptions<TKey, TValue> = Omit<CacheOptions<TValue, [key: TKey]>, "name"> & {
240
+ name: string;
241
+ };
242
+ /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
243
+ export declare function cachedSource<const TReader extends KeyedSourceReader>(reader: TReader & ValidCachedGet<TReader>, options: SourceReaderCacheOptions<Parameters<TReader["get"]>[0], Awaited<ReturnType<TReader["get"]>>>): TReader;
244
+ //#endregion
245
+ //#region src/server.d.ts
246
+ export interface CollectionHandler {
247
+ (event: unknown): Promise<unknown>;
248
+ fetch(input: Request | URL | string): Promise<Response>;
249
+ }
250
+ export interface CollectionHandlerEvent {
251
+ req: {
252
+ signal: AbortSignal;
253
+ };
254
+ }
255
+ /** Wraps a Collection handler so it runs only after the request is authorized. Return a `Response` to reject the request. */
256
+ export type CollectionAuthorizationGuard = <TEvent extends {
257
+ req: Request;
258
+ }, TResult>(authorize: AccessAuthorizeOption, handler: (event: TEvent) => Promise<TResult>) => (event: TEvent) => Promise<TResult | Response>;
259
+ export interface CollectionHandlerOptions {
260
+ /** Required when the Collection declares `authorize`. Generated routes pass Auth's `withAuthorization`. */
261
+ withAuthorization?: CollectionAuthorizationGuard;
262
+ }
263
+ export declare function defineCollectionHandler<TItem, TQuery extends object, TQueryInput extends object>(collection: Collection<TItem, TQuery, TQueryInput>, options?: CollectionHandlerOptions): CollectionHandler;
264
+ //#endregion
265
+ export type { SourceReaderCacheOptions };
package/dist/server.js ADDED
@@ -0,0 +1,149 @@
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
2
+ import { t as CollectionCursorError } from "./collection-cursor-WzV1Jd6v.js";
3
+ import { createError, defineEventHandler, getQuery } from "h3";
4
+ //#region src/cached-source.ts
5
+ function isRuntimeFunction(value) {
6
+ if (value === null || Object(value) !== value) return false;
7
+ try {
8
+ Function.prototype.toString.call(value);
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
15
+ function cachedSource(reader, options) {
16
+ let cachedGet;
17
+ const get = reader.get;
18
+ async function readCached(key) {
19
+ cachedGet ??= import("nitro/cache").then(({ defineCachedFunction }) => defineCachedFunction((value) => get.call(reader, value), {
20
+ swr: false,
21
+ ...options
22
+ }));
23
+ return await (await cachedGet)(key);
24
+ }
25
+ const facade = Object.create(reader);
26
+ return new Proxy(facade, {
27
+ get(_target, property) {
28
+ if (property === "get") return readCached;
29
+ const value = Reflect.get(reader, property, reader);
30
+ return isRuntimeFunction(value) ? value.bind(reader) : value;
31
+ },
32
+ set(_target, property, value) {
33
+ return Reflect.set(reader, property, value, reader);
34
+ },
35
+ ownKeys() {
36
+ return Reflect.ownKeys(reader);
37
+ },
38
+ getOwnPropertyDescriptor(_target, property) {
39
+ const descriptor = Reflect.getOwnPropertyDescriptor(reader, property);
40
+ return descriptor ? {
41
+ ...descriptor,
42
+ configurable: true
43
+ } : void 0;
44
+ }
45
+ });
46
+ }
47
+ //#endregion
48
+ //#region src/server.ts
49
+ function queryValue(query, key) {
50
+ const value = query[key];
51
+ if (Array.isArray(value)) throw sourceErrorDiagnostics.SOURCE_R0011({ message: `[vitehub] Collection query parameter ${JSON.stringify(key)} must have one value.` });
52
+ return value;
53
+ }
54
+ function queryLimit(query) {
55
+ const value = queryValue(query, "limit");
56
+ if (value === void 0) return;
57
+ if (!/^\d+$/.test(value)) throw sourceErrorDiagnostics.SOURCE_R0012({ message: "[vitehub] Collection limit must be a positive integer." });
58
+ const limit = Number(value);
59
+ if (!Number.isSafeInteger(limit) || limit < 1) throw sourceErrorDiagnostics.SOURCE_R0013({ message: "[vitehub] Collection limit must be a positive integer." });
60
+ return limit;
61
+ }
62
+ function collectionQuery(query) {
63
+ return Object.fromEntries(Object.entries(query).filter(([key]) => key !== "cursor" && key !== "limit"));
64
+ }
65
+ function invalidRequest(cause) {
66
+ throw createError({
67
+ cause,
68
+ statusCode: 400,
69
+ statusMessage: cause instanceof Error ? cause.message : "Invalid collection request."
70
+ });
71
+ }
72
+ function isJSONContainer(value) {
73
+ return Object(value) === value && !(value instanceof Function);
74
+ }
75
+ function serializeCollectionPage(value) {
76
+ const serialized = JSON.stringify(value, (_key, entry) => {
77
+ if (!isJSONContainer(entry) || Array.isArray(entry)) return entry;
78
+ const prototype = Object.getPrototypeOf(entry);
79
+ if (prototype !== null && Object.getPrototypeOf(prototype) !== null) throw sourceErrorDiagnostics.SOURCE_R0014({ message: "[vitehub] Collection pages may only contain plain objects, arrays, and toJSON() values. Use transform() for class instances and other object types." });
80
+ return entry;
81
+ });
82
+ if (serialized === void 0) throw sourceErrorDiagnostics.SOURCE_R0015({ message: "[vitehub] Collection page is not JSON-serializable." });
83
+ return JSON.parse(serialized);
84
+ }
85
+ function isCallable(value) {
86
+ try {
87
+ Reflect.apply(Function.prototype.toString, value, []);
88
+ return true;
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+ function hasDeclaredMethod(value, key) {
94
+ const object = Object(value);
95
+ if (Object.hasOwn(object, key)) return isCallable(Reflect.get(object, key));
96
+ let prototype = Object.getPrototypeOf(object);
97
+ while (prototype && prototype !== Object.prototype) {
98
+ if (Object.hasOwn(prototype, key)) {
99
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
100
+ return isCallable(constructor) && constructor !== Object && constructor.prototype === prototype && isCallable(Reflect.get(object, key));
101
+ }
102
+ prototype = Object.getPrototypeOf(prototype);
103
+ }
104
+ return false;
105
+ }
106
+ function assertCollection(value) {
107
+ if (Object(value) !== value || !hasDeclaredMethod(Object(value), "page") || !hasDeclaredMethod(Object(value), "parseQuery")) throw sourceErrorDiagnostics.SOURCE_R0016({ message: "[vitehub] defineCollectionHandler() requires a Collection." });
108
+ }
109
+ function defineCollectionHandler(collection, options = {}) {
110
+ assertCollection(collection);
111
+ if (collection.route === false) throw new TypeError("[vitehub] A server-only Collection cannot be exposed through defineCollectionHandler().");
112
+ const { authorize } = collection;
113
+ const { withAuthorization } = options;
114
+ if (authorize && !withAuthorization) throw sourceErrorDiagnostics.SOURCE_R0025({ message: "[vitehub] Collection authorize requires Auth. Enable Auth and add `server/auth.ts`." });
115
+ const handlePage = async (event) => {
116
+ const requestQuery = getQuery(event);
117
+ let cursor;
118
+ let limit;
119
+ let query;
120
+ try {
121
+ cursor = queryValue(requestQuery, "cursor");
122
+ limit = queryLimit(requestQuery);
123
+ query = await collection.parseQuery(collectionQuery(requestQuery));
124
+ } catch (cause) {
125
+ invalidRequest(cause);
126
+ }
127
+ try {
128
+ return serializeCollectionPage(await collection.page({
129
+ cursor,
130
+ limit,
131
+ query,
132
+ signal: event.req.signal
133
+ }));
134
+ } catch (cause) {
135
+ if (cause instanceof CollectionCursorError) {
136
+ if (cause.reason === "stale") throw createError({
137
+ cause,
138
+ statusCode: 409,
139
+ statusMessage: cause.message
140
+ });
141
+ invalidRequest(cause);
142
+ }
143
+ throw cause;
144
+ }
145
+ };
146
+ return defineEventHandler(authorize && withAuthorization ? withAuthorization(authorize, handlePage) : handlePage);
147
+ }
148
+ //#endregion
149
+ export { cachedSource, defineCollectionHandler };