@vite-hub/source 0.0.4 → 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 (48) hide show
  1. package/README.md +219 -82
  2. package/dist/{auth-Ddw55OUG.js → auth-B-tX_rp0.js} +255 -90
  3. package/dist/{client-CDfTmtQu.js → client-BwstxtdY.js} +584 -207
  4. package/dist/client.d.ts +27 -10
  5. package/dist/client.js +71 -13
  6. package/dist/collection-B_4w_J8h.d.ts +257 -0
  7. package/dist/{collection-B8pXGM2d.js → collection-cursor-WzV1Jd6v.js} +37 -54
  8. package/dist/collection-route-BplWPxHR.js +10 -0
  9. package/dist/drizzle.d.ts +41 -0
  10. package/dist/drizzle.js +89 -0
  11. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  12. package/dist/file-BX0FSvgE.js +60 -0
  13. package/dist/{file-EQ3AjVM6.d.ts → file-DadN9dbN.d.ts} +2 -3
  14. package/dist/file.d.ts +1 -1
  15. package/dist/file.js +1 -1
  16. package/dist/files.d.ts +15 -0
  17. package/dist/files.js +38 -0
  18. package/dist/github.d.ts +8 -5
  19. package/dist/github.js +725 -426
  20. package/dist/glob-BmFqTvJY.js +993 -0
  21. package/dist/glob.d.ts +12 -4
  22. package/dist/glob.js +1 -894
  23. package/dist/index.d.ts +118 -27
  24. package/dist/index.js +623 -14
  25. package/dist/markdown.d.ts +4 -6
  26. package/dist/markdown.js +2 -2
  27. package/dist/mcp.d.ts +3 -4
  28. package/dist/mcp.js +302 -5920
  29. package/dist/{file-BSWQg9Qv.js → mrmime-40h5OOIp.js} +1 -56
  30. package/dist/{path-CUhvUREm.js → path-BS8rYm0n.js} +60 -40
  31. package/dist/{path-BzmU4Eni.js → path-DOBpV8ol.js} +3 -7
  32. package/dist/server.d.ts +256 -6
  33. package/dist/server.js +90 -12
  34. package/dist/{sse-CE9Q2JqM.js → sse-D9gqqNPj.js} +50 -9
  35. package/dist/{streamableHttp-BszaXLmg.js → streamableHttp-BL-E7pl5.js} +40 -22
  36. package/dist/types-BigOktIj.d.ts +93 -0
  37. package/dist/{types-AIBmt_m6.js → types-CoWcW8oz.js} +2502 -1187
  38. package/dist/vite.d.ts +134 -13
  39. package/dist/vite.js +1734 -79
  40. package/package.json +55 -36
  41. package/dist/collection-CF2ON__k.d.ts +0 -92
  42. package/dist/collection-route-Dw7QLFyx.js +0 -6
  43. package/dist/content/client.d.ts +0 -3
  44. package/dist/content/client.js +0 -2
  45. package/dist/content.d.ts +0 -44
  46. package/dist/content.js +0 -157
  47. package/dist/registry-C8skfCSV.js +0 -120
  48. package/dist/types-Bu3WvNX9.d.ts +0 -71
package/dist/client.d.ts CHANGED
@@ -1,32 +1,49 @@
1
- import { f as CollectionQuery, r as CollectionClientItem, t as AnyCollection, u as CollectionPage } from "./collection-CF2ON__k.js";
1
+ import { f as CollectionPage, i as CollectionClientItem, m as CollectionQuery, s as CollectionFacets, t as AnyCollection } from "./collection-B_4w_J8h.js";
2
+ import { Diagnostic } from "nostics";
2
3
  import { ComputedRef, MaybeRefOrGetter, Ref } from "vue";
3
-
4
4
  //#region src/client.d.ts
5
- interface CollectionRequestOptions {
5
+ export interface CollectionRequestOptions {
6
6
  query?: Record<string, unknown>;
7
7
  signal: AbortSignal;
8
8
  }
9
- type CollectionRequester = (endpoint: string, options: CollectionRequestOptions) => Promise<unknown>;
9
+ export type CollectionRequester = (endpoint: string, options: CollectionRequestOptions) => Promise<unknown>;
10
10
  declare global {
11
11
  interface ViteHubCollectionMap {}
12
12
  }
13
- type CollectionName = Extract<keyof ViteHubCollectionMap, string>;
13
+ export type CollectionName = Extract<keyof ViteHubCollectionMap, string>;
14
14
  type RegisteredCollection<TName extends CollectionName> = Extract<ViteHubCollectionMap[TName], AnyCollection>;
15
- interface UseCollectionOptions<TCollection extends AnyCollection> {
15
+ export interface UseCollectionOptions<TCollection extends AnyCollection> {
16
16
  all?: boolean;
17
17
  filter?: MaybeRefOrGetter<CollectionQuery<TCollection>>;
18
18
  immediate?: boolean;
19
19
  limit?: number;
20
20
  request?: CollectionRequester;
21
21
  }
22
- interface UseCollectionReturn<TCollection extends AnyCollection> {
22
+ export interface UseCollectionReturn<TCollection extends AnyCollection> {
23
23
  error: Ref<unknown>;
24
+ /** Facet counts from the latest page, when the Collection declares facets. */
25
+ facets: Ref<CollectionFacets | undefined>;
24
26
  hasMore: ComputedRef<boolean>;
25
27
  items: Ref<Array<CollectionClientItem<TCollection>>>;
28
+ /** Matching items across every page, when the Collection counts them. */
29
+ total: Ref<number | undefined>;
26
30
  loadMore: () => Promise<CollectionPage<CollectionClientItem<TCollection>> | undefined>;
27
31
  pending: Ref<boolean>;
28
32
  refresh: () => Promise<CollectionPage<CollectionClientItem<TCollection>> | undefined>;
29
33
  }
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 };
34
+ /** A Collection route rejected the request: `401` without a session, `403` when `authorize` denied it. */
35
+ export declare class CollectionAccessError extends Diagnostic {
36
+ readonly status: 401 | 403;
37
+ constructor(status: 401 | 403, options?: ErrorOptions);
38
+ override toJSON(): {
39
+ code: string;
40
+ data: undefined;
41
+ docs: string | undefined;
42
+ fix: string | undefined;
43
+ name: string;
44
+ status: 401 | 403;
45
+ why: string;
46
+ };
47
+ }
48
+ export declare function useCollection<TName extends CollectionName>(name: TName, options?: UseCollectionOptions<RegisteredCollection<TName>>): UseCollectionReturn<RegisteredCollection<TName>>;
49
+ //#endregion
package/dist/client.js CHANGED
@@ -1,22 +1,68 @@
1
- import { t as encodeCollectionRouteSegment } from "./collection-route-Dw7QLFyx.js";
1
+ import { n as encodeCollectionRouteSegment } from "./collection-route-BplWPxHR.js";
2
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
3
+ import { Diagnostic } from "nostics";
2
4
  import { $fetch } from "ofetch";
3
5
  import { computed, onScopeDispose, ref, toValue, watch } from "vue";
4
6
  //#region src/client.ts
5
7
  const defaultRequester = async (endpoint, options) => {
6
8
  return await $fetch(endpoint, options);
7
9
  };
10
+ /** A Collection route rejected the request: `401` without a session, `403` when `authorize` denied it. */
11
+ var CollectionAccessError = class CollectionAccessError extends Diagnostic {
12
+ status;
13
+ constructor(status, options) {
14
+ super({
15
+ cause: options?.cause,
16
+ code: "SOURCE_R0026",
17
+ docs: "https://vitehub.dev/docs/reference/diagnostics",
18
+ why: status === 401 ? "[vitehub] Collection requires a signed-in session." : "[vitehub] Collection access is forbidden."
19
+ }, CollectionAccessError);
20
+ this.name = "CollectionAccessError";
21
+ this.status = status;
22
+ }
23
+ toJSON() {
24
+ return {
25
+ code: this.code,
26
+ data: void 0,
27
+ docs: this.docs,
28
+ fix: this.fix,
29
+ name: this.name,
30
+ status: this.status,
31
+ why: this.why
32
+ };
33
+ }
34
+ };
35
+ function accessError(error) {
36
+ if (Object(error) !== error) return;
37
+ const status = Reflect.get(Object(error), "status") ?? Reflect.get(Object(error), "statusCode");
38
+ if (status === 401 || status === 403) return new CollectionAccessError(status, { cause: error });
39
+ }
8
40
  function isAbortError(error) {
9
41
  return Object(error) === error && Reflect.get(Object(error), "name") === "AbortError";
10
42
  }
11
43
  function parseCollectionPage(value) {
12
- if (Object(value) !== value) throw new TypeError("[vitehub] Collection response must be an object.");
44
+ if (Object(value) !== value) throw sourceErrorDiagnostics.SOURCE_R0001({ message: "[vitehub] Collection response must be an object." });
13
45
  const items = Reflect.get(Object(value), "items");
14
46
  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 {
47
+ if (!Array.isArray(items) || !(nextCursor === null || String(nextCursor) === nextCursor)) throw sourceErrorDiagnostics.SOURCE_R0002({ message: "[vitehub] Collection response must contain items and nextCursor." });
48
+ const page = {
17
49
  items,
18
50
  nextCursor
19
51
  };
52
+ const total = Reflect.get(Object(value), "total");
53
+ if (total !== void 0) {
54
+ if (!Number.isSafeInteger(total) || Number(total) < 0) throw sourceErrorDiagnostics.SOURCE_R0002({ message: "[vitehub] Collection response total must be a non-negative integer." });
55
+ page.total = Number(total);
56
+ }
57
+ const facets = Reflect.get(Object(value), "facets");
58
+ if (facets !== void 0) {
59
+ if (!isFacets(facets)) throw sourceErrorDiagnostics.SOURCE_R0002({ message: "[vitehub] Collection response facets must map fields to { value, count } lists." });
60
+ page.facets = facets;
61
+ }
62
+ return page;
63
+ }
64
+ function isFacets(value) {
65
+ 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));
20
66
  }
21
67
  function appBaseURL() {
22
68
  try {
@@ -34,6 +80,8 @@ function useCollection(name, options = {}) {
34
80
  const endpoint = collectionEndpoint(name);
35
81
  const items = ref([]);
36
82
  const nextCursor = ref(null);
83
+ const total = ref();
84
+ const facets = ref();
37
85
  const pending = ref(false);
38
86
  const error = ref(null);
39
87
  const request = options.request || defaultRequester;
@@ -55,7 +103,9 @@ function useCollection(name, options = {}) {
55
103
  try {
56
104
  const filter = options.filter ? toValue(options.filter) : {};
57
105
  let cursor = reset ? void 0 : nextCursor.value || void 0;
58
- let loadedItems = reset ? [] : [...items.value];
106
+ const loadedItems = reset ? [] : [...items.value];
107
+ let loadedTotal = reset ? void 0 : total.value;
108
+ let loadedFacets = reset ? void 0 : facets.value;
59
109
  let response;
60
110
  const seenCursors = new Set(cursors);
61
111
  if (cursor) seenCursors.add(cursor);
@@ -69,26 +119,32 @@ function useCollection(name, options = {}) {
69
119
  signal: controller.signal
70
120
  }));
71
121
  response = {
72
- items: parsed.items,
73
- nextCursor: parsed.nextCursor
122
+ ...parsed,
123
+ items: parsed.items
74
124
  };
75
125
  if (active !== controller) return;
76
- loadedItems = [...loadedItems, ...response.items];
126
+ if (response.total !== void 0) loadedTotal = response.total;
127
+ if (response.facets !== void 0) loadedFacets = response.facets;
128
+ for (const item of response.items) loadedItems.push(item);
77
129
  cursor = response.nextCursor || void 0;
78
- if (cursor && seenCursors.has(cursor)) throw new TypeError("[vitehub] Collection returned the same cursor twice.");
130
+ if (cursor && seenCursors.has(cursor)) throw sourceErrorDiagnostics.SOURCE_R0003({ message: "[vitehub] Collection returned the same cursor twice." });
79
131
  if (cursor) seenCursors.add(cursor);
80
132
  } while (options.all === true && cursor);
81
133
  items.value = loadedItems;
82
134
  cursors = seenCursors;
83
135
  nextCursor.value = response.nextCursor;
136
+ total.value = loadedTotal;
137
+ facets.value = loadedFacets;
84
138
  loaded = true;
85
139
  return {
140
+ ...response,
86
141
  items: loadedItems,
87
- nextCursor: response.nextCursor
142
+ total: loadedTotal,
143
+ facets: loadedFacets
88
144
  };
89
145
  } catch (cause) {
90
146
  if (active !== controller || isAbortError(cause)) return;
91
- error.value = cause;
147
+ error.value = accessError(cause) ?? cause;
92
148
  } finally {
93
149
  if (active === controller) {
94
150
  active = void 0;
@@ -110,12 +166,14 @@ function useCollection(name, options = {}) {
110
166
  });
111
167
  return {
112
168
  error,
169
+ facets,
113
170
  hasMore: computed(() => Boolean(nextCursor.value)),
114
171
  items,
115
172
  loadMore: () => load(false),
116
173
  pending,
117
- refresh: () => load(true)
174
+ refresh: () => load(true),
175
+ total
118
176
  };
119
177
  }
120
178
  //#endregion
121
- export { useCollection };
179
+ export { CollectionAccessError, useCollection };
@@ -0,0 +1,257 @@
1
+ import { Diagnostic } from "nostics";
2
+ import { AccessAuthorizeOption } from "@vite-hub/runtime";
3
+ import { StandardSchemaV1 } from "@standard-schema/spec";
4
+ //#region src/core/collection-cursor.d.ts
5
+ /** Why a Collection rejected a cursor: it cannot be decoded, or it belongs to other data or another query. */
6
+ type CollectionCursorErrorReason = "malformed" | "stale";
7
+ interface CollectionCursorErrorOptions extends ErrorOptions {
8
+ reason?: CollectionCursorErrorReason;
9
+ }
10
+ /** A Collection cursor was rejected. Routes answer `400` for `malformed` and `409` for `stale`. */
11
+ declare class CollectionCursorError extends Diagnostic {
12
+ readonly reason: CollectionCursorErrorReason;
13
+ constructor(message?: string, options?: CollectionCursorErrorOptions);
14
+ }
15
+ //#endregion
16
+ //#region src/core/collection.d.ts
17
+ declare const collectionQueryInput: unique symbol;
18
+ type CollectionRequestQuery = Record<string, string | readonly string[] | undefined>;
19
+ type CollectionCursorValue = boolean | null | number | string | readonly CollectionCursorValue[] | {
20
+ readonly [key: string]: CollectionCursorValue;
21
+ };
22
+ interface CollectionLoadOptions<TQuery extends object, TCursor extends CollectionCursorValue> {
23
+ cursor?: TCursor;
24
+ limit: number;
25
+ query: TQuery;
26
+ signal?: AbortSignal;
27
+ }
28
+ interface CollectionPageOptions<TQuery extends object> {
29
+ cursor?: string;
30
+ limit?: number;
31
+ query: TQuery;
32
+ signal?: AbortSignal;
33
+ }
34
+ /** One distinct value of a faceted field and how many matching items carry it. */
35
+ interface CollectionFacetValue {
36
+ count: number;
37
+ value: string;
38
+ }
39
+ /** Facet counts keyed by field path, computed over every item that matches the query. */
40
+ type CollectionFacets = Record<string, CollectionFacetValue[]>;
41
+ interface CollectionPage<TItem> {
42
+ items: TItem[];
43
+ nextCursor: string | null;
44
+ /** Number of items that match the query across every page, when the Collection can count them. */
45
+ total?: number;
46
+ /** Facet counts over every item that matches the query, when the Collection declares facets. */
47
+ facets?: CollectionFacets;
48
+ }
49
+ interface Collection<TItem, TQuery extends object = CollectionRequestQuery, TQueryInput extends object = TQuery> {
50
+ readonly [collectionQueryInput]?: TQueryInput;
51
+ /** Access rule for the generated route. Omit it for a public Collection. */
52
+ readonly authorize?: AccessAuthorizeOption;
53
+ readonly route?: false;
54
+ readonly get?: (key: string, options?: {
55
+ signal?: AbortSignal;
56
+ }) => Promise<TItem | null | undefined>;
57
+ page(options: CollectionPageOptions<TQuery>): Promise<CollectionPage<TItem>>;
58
+ parseQuery(input: TQueryInput | CollectionRequestQuery): Promise<TQuery>;
59
+ query(input?: TQueryInput): CollectionQueryBuilder<TItem>;
60
+ all(options?: CollectionReadOptions & {
61
+ query?: TQueryInput;
62
+ limit?: number;
63
+ }): Promise<TItem[]>;
64
+ /** The query schema, when the Collection has one. Tools read it to describe accepted query keys. */
65
+ readonly querySchema?: StandardSchemaV1<unknown, TQuery>;
66
+ }
67
+ interface CollectionReadOptions {
68
+ signal?: AbortSignal;
69
+ }
70
+ interface CollectionQueryBuilder<TItem> {
71
+ select<TKey extends Extract<keyof TItem, string>>(...keys: TKey[]): CollectionQueryBuilder<Pick<TItem, TKey>>;
72
+ page(options?: CollectionReadOptions & {
73
+ cursor?: string;
74
+ limit?: number;
75
+ }): Promise<CollectionPage<TItem>>;
76
+ all(options?: CollectionReadOptions & {
77
+ limit?: number;
78
+ }): Promise<TItem[]>;
79
+ }
80
+ type AnyCollection = Collection<any, any, any>;
81
+ type CollectionItem<TCollection extends AnyCollection> = TCollection extends Collection<infer TItem, any, any> ? TItem : never;
82
+ type JSONOmitted = undefined | ((...args: any[]) => any) | symbol;
83
+ type JSONUnsupportedObject = ArrayBuffer | ArrayBufferView | Date | Error | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | RegExp | SharedArrayBuffer | URL | WeakMap<object, unknown> | WeakSet<object>;
84
+ type JSONOmittedBranch<T> = T extends {
85
+ toJSON(): infer TJSON;
86
+ } ? TJSON extends JSONOmitted ? TJSON : never : T extends JSONOmitted ? T : never;
87
+ type JSONSerializedValue<T> = T extends {
88
+ toJSON(): infer TJSON;
89
+ } ? JSONSerializedPostToJSON<TJSON> : JSONSerializedPostToJSON<T>;
90
+ 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;
91
+ type JSONSerialized<T> = T extends unknown ? JSONSerializedValue<T> : never;
92
+ type JSONSerializedArrayItem<T> = T extends {
93
+ toJSON(): infer TJSON;
94
+ } ? JSONSerializedArrayValue<TJSON> : JSONSerializedArrayValue<T>;
95
+ type JSONSerializedArrayValue<T> = T extends JSONOmitted ? null : JSONSerializedPostToJSON<T>;
96
+ type Simplify<T> = { [TKey in keyof T]: T[TKey]; };
97
+ 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]>; }>;
98
+ type CollectionClientItem<TCollection extends AnyCollection> = JSONSerializedArrayItem<CollectionItem<TCollection>>;
99
+ type CollectionQuery<TCollection extends AnyCollection> = TCollection extends Collection<any, any, infer TQueryInput> ? TQueryInput : never;
100
+ type CollectionLoader<TSourceItem, TQuery extends object, TCursor extends CollectionCursorValue> = (options: CollectionLoadOptions<TQuery, TCursor>) => Promise<readonly TSourceItem[]>;
101
+ /** Result of a provider-paginated loader. `total` and `facets` reach the page unchanged. */
102
+ interface ProviderCollectionPage<TSourceItem> {
103
+ items: readonly TSourceItem[];
104
+ nextCursor: string | null;
105
+ total?: number;
106
+ facets?: CollectionFacets;
107
+ }
108
+ type ProviderCollectionLoader<TSourceItem, TQuery extends object> = (options: {
109
+ cursor?: string;
110
+ limit: number;
111
+ query: TQuery;
112
+ signal?: AbortSignal;
113
+ }) => Promise<ProviderCollectionPage<TSourceItem>>;
114
+ type CollectionTransform<TSourceItem> = (item: NoInfer<TSourceItem>) => unknown;
115
+ /**
116
+ * A cursor the loader must not mutate. Only object cursors become readonly, so `AnyCollectionSource` keeps `any`
117
+ * instead of `Readonly<any>`, an index-signature object that rejects string and number cursors.
118
+ */
119
+ type ReadonlyCursor<TCursorInput> = TCursorInput extends object ? Readonly<TCursorInput> : TCursorInput;
120
+ interface CollectionOptions<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue, TCursorOutput extends CollectionCursorValue = TCursorInput> {
121
+ /** `true` requires a signed-in Auth session. A callback also decides each request after sign-in. */
122
+ authorize?: AccessAuthorizeOption;
123
+ cursor(item: NoInfer<TSourceItem>): ReadonlyCursor<TCursorInput>;
124
+ cursorSchema: StandardSchemaV1<TCursorInput, TCursorOutput>;
125
+ defaultLimit?: number;
126
+ maxLimit?: number;
127
+ querySchema?: StandardSchemaV1<unknown, TQuery>;
128
+ transform?: CollectionTransform<TSourceItem>;
129
+ get?: (key: string, options: {
130
+ signal?: AbortSignal;
131
+ }) => Promise<TSourceItem | null | undefined>;
132
+ route?: false;
133
+ }
134
+ interface ProviderCollectionOptions<TSourceItem, TQuery extends object = CollectionRequestQuery, TItem = unknown> {
135
+ authorize?: AccessAuthorizeOption;
136
+ route?: false;
137
+ pagination: "provider";
138
+ get?: (key: string, options: {
139
+ signal?: AbortSignal;
140
+ }) => Promise<TSourceItem | null | undefined>;
141
+ defaultLimit?: number;
142
+ maxLimit?: number;
143
+ querySchema?: StandardSchemaV1<unknown, TQuery>;
144
+ transform?: (item: NoInfer<TSourceItem>) => Promise<TItem> | TItem;
145
+ }
146
+ interface CollectionSourceBase<TSourceItem, TQueryInput extends object, TQuery extends object> {
147
+ get?: (key: string, options: {
148
+ signal?: AbortSignal;
149
+ }) => Promise<TSourceItem | null | undefined>;
150
+ defaultLimit?: number;
151
+ maxLimit?: number;
152
+ querySchema?: StandardSchemaV1<TQueryInput, TQuery>;
153
+ }
154
+ /** A loader whose rows carry their own cursor. The Collection requests one extra row to detect the next page. */
155
+ interface CursorCollectionSource<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue, TCursorOutput extends CollectionCursorValue = TCursorInput, TQueryInput extends object = TQuery> extends CollectionSourceBase<TSourceItem, TQueryInput, TQuery> {
156
+ cursor(item: NoInfer<TSourceItem>): ReadonlyCursor<TCursorInput>;
157
+ cursorSchema: StandardSchemaV1<TCursorInput, TCursorOutput>;
158
+ load: CollectionLoader<TSourceItem, TQuery, TCursorOutput>;
159
+ pagination?: undefined;
160
+ }
161
+ /** A loader that returns whole pages with its own opaque `nextCursor`, and optionally `total` and `facets`. */
162
+ interface ProviderCollectionSource<TSourceItem, TQuery extends object, TQueryInput extends object = TQuery> extends CollectionSourceBase<TSourceItem, TQueryInput, TQuery> {
163
+ load: ProviderCollectionLoader<TSourceItem, TQuery>;
164
+ pagination: "provider";
165
+ cursor?: undefined;
166
+ cursorSchema?: undefined;
167
+ }
168
+ /** Where a Collection reads rows from: `array()`, `table()`, `workspaceFile()`, or your own object. */
169
+ type CollectionSource<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue, TCursorOutput extends CollectionCursorValue = TCursorInput, TQueryInput extends object = TQuery> = CursorCollectionSource<TSourceItem, TQuery, TCursorInput, TCursorOutput, TQueryInput> | ProviderCollectionSource<TSourceItem, TQuery, TQueryInput>;
170
+ type AnyCollectionSource = CollectionSource<any, any, any, any, any>;
171
+ type SourceItemOf<TSource extends AnyCollectionSource> = TSource extends CollectionSource<infer TItem, any, any, any, any> ? TItem : never;
172
+ type SourceQueryOf<TSource extends AnyCollectionSource> = TSource extends CollectionSource<any, infer TQuery, any, any, any> ? TQuery : never;
173
+ type SourceQueryInputOf<TSource extends AnyCollectionSource> = TSource extends CollectionSource<any, any, any, any, infer TQueryInput> ? TQueryInput : never;
174
+ type LoadedItemOf<TSource> = TSource extends {
175
+ load: (...args: any[]) => infer TResult;
176
+ } ? Awaited<TResult> extends readonly (infer TItem)[] ? TItem : Awaited<TResult> extends {
177
+ items: readonly (infer TItem)[];
178
+ } ? TItem : never : never;
179
+ type LoadOptionsOf<TSource> = TSource extends {
180
+ load: (options: infer TOptions) => unknown;
181
+ } ? TOptions : never;
182
+ /**
183
+ * Ties a source's own parts to its loader. `AnyCollectionSource` only bounds each part, so without this a cursor,
184
+ * `get`, or query schema written for other rows or another query would pass.
185
+ */
186
+ type SourceContract<TSource> = (TSource extends {
187
+ cursor: (item: never) => unknown;
188
+ } ? {
189
+ cursor: (item: LoadedItemOf<TSource>) => unknown;
190
+ } : unknown) & (TSource extends {
191
+ get: (key: string, options: never) => unknown;
192
+ } ? {
193
+ get: (key: string, options: {
194
+ signal?: AbortSignal;
195
+ }) => Promise<LoadedItemOf<TSource> | null | undefined>;
196
+ } : unknown) & (TSource extends {
197
+ querySchema: StandardSchemaV1<any, infer TQuery>;
198
+ } ? [LoadOptionsOf<TSource>] extends [never] ? unknown : {
199
+ load: (options: Omit<LoadOptionsOf<TSource>, "query"> & {
200
+ query: TQuery;
201
+ }) => unknown;
202
+ } : unknown);
203
+ interface SourceCollectionOptions<TSource extends AnyCollectionSource> {
204
+ /** `true` requires a signed-in Auth session. A callback also decides each request after sign-in. */
205
+ authorize?: AccessAuthorizeOption;
206
+ route?: false;
207
+ source: TSource & SourceContract<TSource>;
208
+ }
209
+ type CollectionDefinition<TSourceItem, TQuery extends object, TCursorInput extends CollectionCursorValue> = Omit<CollectionOptions<TSourceItem, TQuery, TCursorInput>, "cursorSchema" | "querySchema" | "transform">;
210
+ type CursorInput<TSchema extends StandardSchemaV1> = [StandardSchemaV1.InferInput<TSchema>] extends [CollectionCursorValue] ? StandardSchemaV1.InferInput<TSchema> : never;
211
+ type CursorOutput<TSchema extends StandardSchemaV1> = [StandardSchemaV1.InferOutput<TSchema>] extends [CollectionCursorValue] ? StandardSchemaV1.InferOutput<TSchema> : never;
212
+ type RepeatedQueryValues = [string, string, ...string[]];
213
+ 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];
214
+ type ReservedCollectionQueryKey = "cursor" | "limit";
215
+ 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;
216
+ type QueryInput<TSchema extends StandardSchemaV1> = CollectionQueryInput<StandardSchemaV1.InferInput<TSchema>>;
217
+ declare function defineCollection<TSource extends AnyCollectionSource, TTransform extends (item: NoInfer<SourceItemOf<TSource>>) => unknown>(options: SourceCollectionOptions<TSource> & {
218
+ transform: TTransform;
219
+ }): Collection<Awaited<ReturnType<TTransform>>, SourceQueryOf<TSource>, SourceQueryInputOf<TSource>>;
220
+ declare function defineCollection<TSource extends AnyCollectionSource>(options: SourceCollectionOptions<TSource> & {
221
+ transform?: undefined;
222
+ }): Collection<SourceItemOf<TSource>, SourceQueryOf<TSource>, SourceQueryInputOf<TSource>>;
223
+ 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>> & {
224
+ cursorSchema: TCursorSchema;
225
+ querySchema: TQuerySchema;
226
+ transform: TTransform;
227
+ }): Collection<Awaited<ReturnType<TTransform>>, StandardSchemaV1.InferOutput<TQuerySchema>, QueryInput<TQuerySchema>>;
228
+ 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>> & {
229
+ cursorSchema: TCursorSchema;
230
+ querySchema: TQuerySchema;
231
+ transform?: undefined;
232
+ }): Collection<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, QueryInput<TQuerySchema>>;
233
+ declare function defineCollection<TSourceItem, TQuerySchema extends StandardSchemaV1<unknown, object>, TItem = TSourceItem>(load: ProviderCollectionLoader<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>>, options: ProviderCollectionOptions<TSourceItem, StandardSchemaV1.InferOutput<TQuerySchema>, TItem> & {
234
+ querySchema: TQuerySchema;
235
+ }): Collection<TItem, StandardSchemaV1.InferOutput<TQuerySchema>, QueryInput<TQuerySchema>>;
236
+ declare function defineCollection<TSourceItem, TTransform extends CollectionTransform<TSourceItem>>(load: ProviderCollectionLoader<TSourceItem, CollectionRequestQuery>, options: ProviderCollectionOptions<TSourceItem, CollectionRequestQuery, Awaited<ReturnType<TTransform>>> & {
237
+ get: NonNullable<ProviderCollectionOptions<TSourceItem>["get"]>;
238
+ querySchema?: undefined;
239
+ transform: TTransform;
240
+ }): Collection<Awaited<ReturnType<TTransform>>, CollectionRequestQuery, CollectionRequestQuery> & {
241
+ get: (key: string, options?: CollectionReadOptions) => Promise<Awaited<ReturnType<TTransform>> | null | undefined>;
242
+ };
243
+ declare function defineCollection<TSourceItem, TItem = TSourceItem>(load: ProviderCollectionLoader<TSourceItem, CollectionRequestQuery>, options: ProviderCollectionOptions<TSourceItem, CollectionRequestQuery, TItem> & {
244
+ querySchema?: undefined;
245
+ }): Collection<TItem, CollectionRequestQuery, CollectionRequestQuery>;
246
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1, TTransform extends CollectionTransform<TSourceItem>>(load: CollectionLoader<TSourceItem, CollectionRequestQuery, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, CollectionRequestQuery, CursorInput<TCursorSchema>> & {
247
+ cursorSchema: TCursorSchema;
248
+ querySchema?: undefined;
249
+ transform: TTransform;
250
+ }): Collection<Awaited<ReturnType<TTransform>>, CollectionRequestQuery, CollectionRequestQuery>;
251
+ declare function defineCollection<TSourceItem, TCursorSchema extends StandardSchemaV1>(load: CollectionLoader<TSourceItem, CollectionRequestQuery, CursorOutput<TCursorSchema>>, options: CollectionDefinition<TSourceItem, CollectionRequestQuery, CursorInput<TCursorSchema>> & {
252
+ cursorSchema: TCursorSchema;
253
+ querySchema?: undefined;
254
+ transform?: undefined;
255
+ }): Collection<TSourceItem, CollectionRequestQuery, CollectionRequestQuery>;
256
+ //#endregion
257
+ export { ProviderCollectionPage as C, CollectionCursorError as D, defineCollection as E, CollectionCursorErrorOptions as O, ProviderCollectionOptions as S, SourceCollectionOptions as T, CollectionReadOptions as _, CollectionCursorValue as a, CursorCollectionSource as b, CollectionItem as c, CollectionOptions as d, CollectionPage as f, CollectionQueryInput as g, CollectionQueryBuilder as h, CollectionClientItem as i, CollectionCursorErrorReason as k, CollectionLoadOptions as l, CollectionQuery as m, AnyCollectionSource as n, CollectionFacetValue as o, CollectionPageOptions as p, Collection as r, CollectionFacets as s, AnyCollection as t, CollectionLoader as u, CollectionRequestQuery as v, ProviderCollectionSource as w, ProviderCollectionLoader as x, CollectionSource as y };
@@ -1,12 +1,9 @@
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
2
+ import { Diagnostic } from "nostics";
1
3
  //#region ../internal/src/object.ts
2
4
  function isPlainObject(value) {
3
5
  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
- }
6
+ return typeof value === "object";
10
7
  }
11
8
  function isPlainRecord(value) {
12
9
  if (!isPlainObject(value)) return false;
@@ -15,21 +12,29 @@ function isPlainRecord(value) {
15
12
  return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
16
13
  }
17
14
  //#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);
15
+ //#region src/core/schema.ts
16
+ async function parseCollectionSchema(schema, value) {
17
+ const result = await schema["~standard"].validate(value);
18
+ if (result.issues) throw sourceErrorDiagnostics.SOURCE_R0006({ message: result.issues[0]?.message ?? "Collection value is invalid." });
19
+ return result.value;
20
+ }
21
+ //#endregion
22
+ //#region src/core/collection-cursor.ts
23
+ /** A Collection cursor was rejected. Routes answer `400` for `malformed` and `409` for `stale`. */
24
+ var CollectionCursorError = class CollectionCursorError extends Diagnostic {
25
+ reason;
26
+ constructor(message, options) {
27
+ const reason = options?.reason ?? "malformed";
28
+ super({
29
+ cause: options?.cause,
30
+ code: reason === "stale" ? "SOURCE_R0027" : "SOURCE_R0023",
31
+ docs: "https://vitehub.dev/docs/reference/diagnostics",
32
+ why: message ?? (reason === "stale" ? "[vitehub] Collection cursor is stale. Its data or query changed; reload from the first page." : "[vitehub] Collection cursor is malformed.")
33
+ }, CollectionCursorError);
34
+ this.name = "CollectionCursorError";
35
+ this.reason = reason;
24
36
  }
25
37
  };
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
38
  function encodeBase64Url(value) {
34
39
  const bytes = new TextEncoder().encode(value);
35
40
  let binary = "";
@@ -37,9 +42,11 @@ function encodeBase64Url(value) {
37
42
  return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
38
43
  }
39
44
  function decodeBase64Url(value) {
45
+ if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) throw new TypeError("Malformed base64url cursor");
40
46
  const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
41
47
  const binary = atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="));
42
- return new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
48
+ if (btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "") !== value) throw new TypeError("Noncanonical base64url cursor");
49
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
43
50
  }
44
51
  function hasPrimitiveRuntimeTag(value, tag) {
45
52
  return value !== null && value !== void 0 && Object(value) !== value && Object.prototype.toString.call(value) === tag;
@@ -82,14 +89,9 @@ function isCursorValue(value, ancestors = /* @__PURE__ */ new Set()) {
82
89
  }
83
90
  }
84
91
  function encodeCursor(value) {
85
- if (!isCursorValue(value)) throw new TypeError("[vitehub] Collection cursor() must return a JSON-serializable value.");
92
+ if (!isCursorValue(value)) throw sourceErrorDiagnostics.SOURCE_R0005({ message: "[vitehub] Collection cursor() must return a JSON-serializable value." });
86
93
  return encodeBase64Url(JSON.stringify(value));
87
94
  }
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
95
  async function decodeCursor(value, schema) {
94
96
  if (value === void 0) return;
95
97
  let decoded;
@@ -100,42 +102,23 @@ async function decodeCursor(value, schema) {
100
102
  }
101
103
  if (!isCursorValue(decoded)) throw new CollectionCursorError();
102
104
  try {
103
- const cursor = await parseSchema(schema, decoded);
104
- if (!isCursorValue(cursor)) throw new TypeError("Collection cursor schema returned an invalid value.");
105
+ const cursor = await parseCollectionSchema(schema, decoded);
106
+ if (!isCursorValue(cursor)) throw sourceErrorDiagnostics.SOURCE_R0007({ message: "Collection cursor schema returned an invalid value." });
105
107
  return cursor;
106
108
  } catch (cause) {
107
109
  throw new CollectionCursorError(void 0, { cause });
108
110
  }
109
111
  }
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.");
112
+ /** Bind cursor transport and validation to the Collection's schema once. */
113
+ function createCollectionCursorCodec(schema) {
116
114
  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
- };
115
+ encode(value) {
116
+ return encodeCursor(value);
133
117
  },
134
- async parseQuery(input) {
135
- if (definition.querySchema) return await parseSchema(definition.querySchema, input);
136
- return input;
118
+ decode(value) {
119
+ return decodeCursor(value, schema);
137
120
  }
138
121
  };
139
122
  }
140
123
  //#endregion
141
- export { defineCollection as n, CollectionCursorError as t };
124
+ export { createCollectionCursorCodec as n, parseCollectionSchema as r, CollectionCursorError as t };
@@ -0,0 +1,10 @@
1
+ //#region src/internal/collection-route.ts
2
+ function encodeCollectionRouteSegment(segment) {
3
+ return encodeURIComponent(segment).replaceAll("*", "%2A");
4
+ }
5
+ /** Generated GET route of a discovered Collection, for example `/api/articles`. */
6
+ function collectionRoutePath(name) {
7
+ return `/api/${name.split("/").map(encodeCollectionRouteSegment).join("/")}`;
8
+ }
9
+ //#endregion
10
+ export { encodeCollectionRouteSegment as n, collectionRoutePath as t };