@vite-hub/source 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +267 -96
- package/dist/client.d.ts +27 -10
- package/dist/client.js +99 -15
- package/dist/collection-B8sgxw5-.d.ts +290 -0
- package/dist/collection-C0Rvrx3p.js +297 -0
- package/dist/collection-route-BplWPxHR.js +10 -0
- package/dist/drizzle.d.ts +48 -0
- package/dist/drizzle.js +87 -0
- package/dist/error-diagnostics-ClQKdi7c.js +194 -0
- package/dist/github-D5S0dEZe.js +1312 -0
- package/dist/{glob.js → glob-DmdMVqjx.js} +154 -57
- package/dist/index.d.ts +284 -62
- package/dist/index.js +583 -29
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/mcp.d.ts +3 -4
- package/dist/mcp.js +184 -5917
- package/dist/object-CtSHeGQO.js +17 -0
- package/dist/{path-CUhvUREm.js → path-DFlSryRA.js} +90 -40
- package/dist/root-DJNmqCEW.js +11 -0
- package/dist/server.d.ts +24 -11
- package/dist/server.js +97 -26
- package/dist/types-Ln-FxVFn.d.ts +98 -0
- package/dist/vite.d.ts +202 -14
- package/dist/vite.js +1683 -122
- package/package.json +55 -58
- package/dist/auth-Ddw55OUG.js +0 -1261
- package/dist/client-CDfTmtQu.js +0 -7903
- package/dist/collection-B8pXGM2d.js +0 -141
- package/dist/collection-CF2ON__k.d.ts +0 -92
- package/dist/collection-route-Dw7QLFyx.js +0 -6
- package/dist/content/client.d.ts +0 -3
- package/dist/content/client.js +0 -2
- package/dist/content.d.ts +0 -44
- package/dist/content.js +0 -157
- package/dist/file-BSWQg9Qv.js +0 -503
- package/dist/file-EQ3AjVM6.d.ts +0 -20
- package/dist/file.d.ts +0 -2
- package/dist/file.js +0 -2
- package/dist/github.d.ts +0 -17
- package/dist/github.js +0 -1033
- package/dist/glob.d.ts +0 -15
- package/dist/markdown.d.ts +0 -7
- package/dist/markdown.js +0 -10
- package/dist/path-BzmU4Eni.js +0 -36
- package/dist/registry-C8skfCSV.js +0 -120
- package/dist/sse-CE9Q2JqM.js +0 -407
- package/dist/streamableHttp-BszaXLmg.js +0 -491
- package/dist/types-AIBmt_m6.js +0 -6275
- package/dist/types-Bu3WvNX9.d.ts +0 -71
- package/tsconfig.vite.json +0 -6
- package/types/source/fallback.d.ts +0 -1
- package/types/source/index.d.ts +0 -1
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# @vite-hub/source
|
|
2
2
|
|
|
3
3
|
<p>
|
|
4
|
-
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://
|
|
5
|
-
<img alt="TypeScript" src="https://
|
|
6
|
-
<img alt="Sources" src="https://
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&value=vitehub.dev"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&value=ready">
|
|
6
|
+
<img alt="Sources" src="https://comark-ui.onmax.me/badge.svg?label=Source&value=typed+retrieval">
|
|
7
7
|
</p>
|
|
8
8
|
|
|
9
9
|
`@vite-hub/source` loads files, globs, markdown, GitHub content, or custom data before something else places it in a workspace.
|
|
@@ -14,139 +14,213 @@
|
|
|
14
14
|
pnpm add @vite-hub/source
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
##
|
|
17
|
+
## Open a Source
|
|
18
18
|
|
|
19
19
|
```ts
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
readme: file("README.md"),
|
|
29
|
-
upstream: github({ repo: "vite-hub/vitehub" }),
|
|
30
|
-
}))
|
|
31
|
-
|
|
32
|
-
const docs = useSource("docs", { rootDir: process.cwd() })
|
|
33
|
-
const revision = await docs.revision()
|
|
34
|
-
const keys = await docs.keys()
|
|
35
|
-
const first = await docs.read(keys[0]!)
|
|
20
|
+
import { createSource, glob } from "@vite-hub/source"
|
|
21
|
+
|
|
22
|
+
export const docs = glob({ cwd: "docs", include: "**/*.md" })
|
|
23
|
+
|
|
24
|
+
const reader = createSource(docs, { rootDir: process.cwd() })
|
|
25
|
+
const revision = await reader.revision()
|
|
26
|
+
const keys = await reader.keys()
|
|
27
|
+
const first = await reader.read(keys[0]!)
|
|
36
28
|
```
|
|
37
29
|
|
|
38
|
-
`
|
|
39
|
-
|
|
30
|
+
`createSource(definition, context?)` infers keys, items, and metadata from the
|
|
31
|
+
Source definition. It resolves a revision and prepares the Source once per
|
|
32
|
+
reader. Revision-aware loaders receive the same pinned revision on every
|
|
33
|
+
operation. Loaders without revision support can observe origin changes. Create
|
|
34
|
+
another reader to resolve a new revision. No registration or global type map is needed.
|
|
40
35
|
|
|
41
|
-
|
|
36
|
+
`glob()` treats both `/` and `\` as path separators in `include` and `ignore`,
|
|
37
|
+
including before wildcards: the JavaScript string `"docs\\*.md"` means
|
|
38
|
+
`"docs/*.md"`. Backslashes never escape glob metacharacters. To match literal
|
|
39
|
+
characters, use bracket expressions: `[*]` for `*`, `[?]` for `?`, and `[[]`
|
|
40
|
+
for `[`. For example, `"docs/file[[]1].md"` matches `docs/file[1].md`.
|
|
41
|
+
The same normalized patterns are used for discovery and final filtering.
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
features in its loader:
|
|
43
|
+
`glob()` keeps its cached key listing in each reader. Opening another reader
|
|
44
|
+
refreshes that reader's listing without changing existing readers. File content
|
|
45
|
+
and metadata are read from the current file system. Set `keyCache: false` to
|
|
46
|
+
refresh keys on each listing and when an item is missing from the latest listing.
|
|
48
47
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
`file()` follows a symbolic link only when its resolved target stays inside the Source root. `glob()` is also confined to the Source root. It does not follow symbolic links by default, and it checks each file path again before it reads content or metadata. Set `followSymlinks: true` to follow links when their resolved targets stay inside the Source root. This option controls file selection. It does not isolate the process from concurrent file system changes.
|
|
49
|
+
|
|
50
|
+
File paths are relative to the Source root. Absolute paths, Windows drive paths such as `C:notes.md`, parent traversal, and null bytes are rejected on every host.
|
|
51
|
+
|
|
52
|
+
Use `defineSource()` for custom loaders:
|
|
52
53
|
|
|
53
54
|
```ts
|
|
54
|
-
import
|
|
55
|
-
import sqliteFullTextSearch from "comark-content/plugins/sqlite-full-text-search"
|
|
56
|
-
import { defineContent } from "@vite-hub/source/content"
|
|
55
|
+
import { createSource, defineSource } from "@vite-hub/source"
|
|
57
56
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
const articles = defineSource({
|
|
58
|
+
name: "articles",
|
|
59
|
+
async getKeys() {
|
|
60
|
+
return ["article_123" as const]
|
|
61
|
+
},
|
|
62
|
+
async getItem(key: `article_${string}`) {
|
|
63
|
+
return { key, data: { title: "Source API" }, metadata: { version: 1 } }
|
|
62
64
|
},
|
|
63
65
|
})
|
|
64
66
|
|
|
65
|
-
await
|
|
66
|
-
|
|
67
|
-
|
|
67
|
+
const article = await createSource(articles).get("article_123")
|
|
68
|
+
article.data.title
|
|
69
|
+
article.metadata.version
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Every loader has `name`, `getKeys()`, and `getItem()`. Optional hooks include
|
|
73
|
+
`resolveRevision()`, `prepare()`, `getItems()`, and `getMeta()`.
|
|
74
|
+
`SourceReader<typeof articles>`, `SourceKey<typeof articles>`,
|
|
75
|
+
`SourceData<typeof articles>`, and `SourceMetadata<typeof articles>` use the
|
|
76
|
+
definition type.
|
|
77
|
+
|
|
78
|
+
All managed readers expose `revision()`, `keys()`, `get()`, `items()`, `meta()`,
|
|
79
|
+
and `exists()`. File readers also expose `read()` and `list()`. Built-in `file`,
|
|
80
|
+
`glob`, `github`, `markdown`, and `mcpResources` loaders return `FileSource`.
|
|
81
|
+
Their `SourceFile` items guarantee `content`. Custom loaders that guarantee
|
|
82
|
+
content receive file methods too. Record readers use `get()` and `items()`.
|
|
83
|
+
|
|
84
|
+
`github()` reads GitHub through `@vite-hub/forge`, an optional peer that it loads on the first read. Install it with
|
|
85
|
+
`pnpm add @vite-hub/forge`. `auth` is a token or a trusted
|
|
86
|
+
callback. Without `auth`, it reads Server Env `VITEHUB_GITHUB_TOKEN`, then
|
|
87
|
+
`FORGES_GITHUB_TOKEN`. It does not read `GH_TOKEN` or `GITHUB_TOKEN`.
|
|
88
|
+
`auth: false` reads without a token. `authenticated()` tells whether reads send a
|
|
89
|
+
token. Content serves a `github()` Source from a validated head commit only when
|
|
90
|
+
it does.
|
|
91
|
+
|
|
92
|
+
`history(key, { sha, page, perPage })` lists the commits that changed one file,
|
|
93
|
+
newest first, from the commit `sha` back. It reads GitHub's commits endpoint with
|
|
94
|
+
`path`, so it does not follow renames. Each commit has `sha`, `date`, `author`,
|
|
95
|
+
the first line of `message`, and `url`. `content.history()` uses it.
|
|
96
|
+
|
|
97
|
+
`latest(keys, { sha })` returns the latest commit of many files at once, as a
|
|
98
|
+
`Map` from key to commit. It sends one GitHub GraphQL request per 150 files, 4
|
|
99
|
+
at a time, so 2,600 files cost 18 requests. When GitHub stops a request after 10
|
|
100
|
+
seconds (502), it asks again with half the files. `changes(base, head)` returns
|
|
101
|
+
the keys that a commit from one commit to a later one changed, with a file that
|
|
102
|
+
one commit edits and a later one reverts. It sends one compare request, plus one
|
|
103
|
+
commit request per commit when there is more than one. It returns undefined when
|
|
104
|
+
GitHub cannot list them all or more than 20 commits lie between them. The Content sitemap and RSS feed
|
|
105
|
+
use both to date Source pages. `pullChanges(number)` returns the keys that a pull
|
|
106
|
+
request adds or changes, from its file list, with the new key of a renamed file
|
|
107
|
+
and without removed files. GitHub lists at most 3,000 files of a pull request.
|
|
108
|
+
`vitehub content previews comment` uses it.
|
|
109
|
+
|
|
110
|
+
`resolveRef()` returns the commit that a ref of the repository points to now:
|
|
111
|
+
`{ sha }` for `{ sha }` or `{ branch }`, and `{ sha, pull }` for `{ pull: 12 }`.
|
|
112
|
+
`pull` has the state, the head and base branches, `fork`, and the label names. A
|
|
113
|
+
branch must match its full name, and a SHA must be a full commit SHA. It returns
|
|
114
|
+
undefined when the repository has no such ref. Content uses it for
|
|
115
|
+
`content.sources.at()`.
|
|
116
|
+
|
|
117
|
+
`glob()` takes a pattern or options. In a pattern, the folders before the first
|
|
118
|
+
wildcard are `cwd`, so keys are the paths below them:
|
|
68
119
|
|
|
120
|
+
```ts
|
|
121
|
+
import { glob } from "@vite-hub/source"
|
|
122
|
+
|
|
123
|
+
export const docs = glob("content/docs/**/*.md") // keys like "guide/setup.md"
|
|
69
124
|
```
|
|
70
125
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
126
|
+
Under `vite dev` it reads the files from disk. A server build with `hubSource()`
|
|
127
|
+
bundles the files of a call whose options are literals, through `files()`, so
|
|
128
|
+
hosts without a runtime file system, such as Cloudflare Workers, serve them.
|
|
129
|
+
`files(entries, { base, prefix })` serves files the server already holds. An
|
|
130
|
+
entry can be the content or a function that loads it, such as an
|
|
131
|
+
`import.meta.glob()` loader. After removing `base`, a leading `./` is removed
|
|
132
|
+
from each key: `./content/a.md` becomes `content/a.md`, or `a.md` with
|
|
133
|
+
`base: "./content"`.
|
|
77
134
|
|
|
78
|
-
|
|
79
|
-
module. Comark's cache accepts an unstorage driver and exposes
|
|
80
|
-
`refresh(source)`, `invalidate(key)`, and `expire(key)`, so applications do not
|
|
81
|
-
need a second parsed-content cache in ViteHub.
|
|
135
|
+
## Reuse a definition
|
|
82
136
|
|
|
83
|
-
|
|
137
|
+
Content accepts Source definitions directly. It opens a new reader on each
|
|
138
|
+
refresh, so overlapping loads keep separate revisions:
|
|
84
139
|
|
|
85
|
-
```ts
|
|
86
|
-
import
|
|
87
|
-
import { defineContent } from "@vite-hub/source/content"
|
|
140
|
+
```ts fragment
|
|
141
|
+
import { defineContent } from "@vite-hub/content"
|
|
88
142
|
|
|
89
|
-
export
|
|
143
|
+
export default defineContent({ source: docs })
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Workspace binds the same definition to a persistent file tree:
|
|
147
|
+
|
|
148
|
+
```ts fragment
|
|
149
|
+
import { defineWorkspace } from "@vite-hub/workspace"
|
|
150
|
+
|
|
151
|
+
export default defineWorkspace({
|
|
90
152
|
sources: {
|
|
91
|
-
|
|
153
|
+
docs: { source: docs, mount: "docs", materialize: "lazy" },
|
|
92
154
|
},
|
|
93
155
|
})
|
|
94
156
|
```
|
|
95
157
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
client plugin to call the same plugin methods over the generated endpoint.
|
|
99
|
-
|
|
100
|
-
Workspace search remains filesystem search over the visible Workspace tree.
|
|
101
|
-
Comark search is semantic content search over parsed documents. They deliberately
|
|
102
|
-
have different owners and result contracts.
|
|
103
|
-
|
|
104
|
-
Structured sources preserve record and metadata types through `useSource()`:
|
|
158
|
+
Workspace owns paths, materialization, sync, and access rules. Source owns
|
|
159
|
+
retrieval. Content owns parsed documents, navigation, queries, and search.
|
|
105
160
|
|
|
106
|
-
|
|
107
|
-
import type { Source } from "@vite-hub/source"
|
|
161
|
+
## Optional name lookup
|
|
108
162
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
cover: { key: string, mediaType: string }
|
|
112
|
-
title: string
|
|
113
|
-
}
|
|
163
|
+
```ts fragment
|
|
164
|
+
import { registerSources, useSource } from "@vite-hub/source"
|
|
114
165
|
|
|
115
|
-
|
|
116
|
-
revision: string
|
|
117
|
-
}
|
|
166
|
+
registerSources({ docs })
|
|
118
167
|
|
|
119
168
|
declare global {
|
|
120
169
|
interface ViteHubSourceMap {
|
|
121
|
-
|
|
170
|
+
docs: typeof docs
|
|
122
171
|
}
|
|
123
172
|
}
|
|
124
173
|
|
|
125
|
-
|
|
126
|
-
article.data?.title
|
|
127
|
-
article.metadata?.revision
|
|
128
|
-
|
|
129
|
-
const articles = await useSource("articles").items()
|
|
174
|
+
await useSource("docs").read("intro.md")
|
|
130
175
|
```
|
|
131
176
|
|
|
132
|
-
|
|
177
|
+
`useSource(name, context?)` opens the same managed reader through a process-local
|
|
178
|
+
registry. Import the registration module before lookup. The Vite integration
|
|
179
|
+
for Collections and Content does not generate `ViteHubSourceMap`.
|
|
180
|
+
`RegisteredSource<"docs">` resolves a registered name to its definition type.
|
|
181
|
+
|
|
182
|
+
## Split items into parts
|
|
183
|
+
|
|
184
|
+
`splitSource()` turns each item of a Source into several items, such as the
|
|
185
|
+
sections of a Markdown file. Each part key is `<parent key>#<part key>`:
|
|
133
186
|
|
|
134
187
|
```ts
|
|
135
|
-
import {
|
|
188
|
+
import { createSource, splitSource, glob } from "@vite-hub/source"
|
|
136
189
|
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
items: async () => [{ key: "2026-07" as const }],
|
|
142
|
-
}),
|
|
143
|
-
},
|
|
190
|
+
const sections = splitSource({
|
|
191
|
+
source: glob({ cwd: "docs", include: "**/*.md" }),
|
|
192
|
+
split: file => String(file.content).split(/^## /m).slice(1)
|
|
193
|
+
.map(section => ({ key: section.slice(0, section.indexOf("\n")), content: section })),
|
|
144
194
|
})
|
|
145
195
|
|
|
146
|
-
await
|
|
147
|
-
|
|
196
|
+
await createSource(sections).read("guide.md#Usage")
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The result is a Source definition. `get()` reads only the parent item of the
|
|
200
|
+
part, and a part without a `path` keeps the parent's path. Part keys must be
|
|
201
|
+
unique in their parent item and must not contain `#`.
|
|
202
|
+
|
|
203
|
+
## Cache keyed readers
|
|
204
|
+
|
|
205
|
+
Use `cachedSource()` to add Nitro caching to a keyed reader. It loads
|
|
206
|
+
`nitro/cache` on the first `get()`, so the app must run on Nitro:
|
|
207
|
+
|
|
208
|
+
```ts fragment
|
|
209
|
+
import { cachedSource } from "@vite-hub/source/server"
|
|
210
|
+
|
|
211
|
+
const cachedDocs = cachedSource(createSource(docs), { name: "docs", maxAge: 60 })
|
|
212
|
+
await cachedDocs.get("intro.md")
|
|
148
213
|
```
|
|
149
214
|
|
|
215
|
+
Use a different cache name for each origin and access scope.
|
|
216
|
+
|
|
217
|
+
The `cache` option of a loader, such as `github({ cache: { maxAge } })`, is a
|
|
218
|
+
hint for the consumer of the Source. The Workspace reads it to decide when its
|
|
219
|
+
copy of the Source content is stale. A reader from `createSource()` alone does
|
|
220
|
+
not read `cache` and does not cache.
|
|
221
|
+
|
|
222
|
+
## Collections
|
|
223
|
+
|
|
150
224
|
Define a Collection when a database or other origin should become a typed,
|
|
151
225
|
paginated client read model:
|
|
152
226
|
|
|
@@ -155,9 +229,19 @@ paginated client read model:
|
|
|
155
229
|
import { defineCollection } from "@vite-hub/source"
|
|
156
230
|
import * as v from "valibot"
|
|
157
231
|
|
|
232
|
+
interface Article { id: string, title: string, createdAt: number }
|
|
233
|
+
|
|
158
234
|
export const articles = defineCollection(async ({ cursor, limit, query }) => {
|
|
159
|
-
|
|
235
|
+
// A CMS API that pages by the last (createdAt, id) it returned
|
|
236
|
+
const url = new URL("https://cms.example.com/api/articles")
|
|
237
|
+
url.searchParams.set("limit", String(limit))
|
|
238
|
+
if (cursor) url.searchParams.set("after", cursor.join(","))
|
|
239
|
+
if (query.author) url.searchParams.set("author", query.author)
|
|
240
|
+
const response = await fetch(url)
|
|
241
|
+
if (!response.ok) throw new Error(`The CMS answered ${response.status}`)
|
|
242
|
+
return await response.json() as Article[]
|
|
160
243
|
}, {
|
|
244
|
+
access: 'public',
|
|
161
245
|
cursor: article => [article.createdAt, article.id] as const,
|
|
162
246
|
cursorSchema: v.tuple([v.number(), v.string()]),
|
|
163
247
|
querySchema: v.object({ author: v.optional(v.string()) }),
|
|
@@ -167,6 +251,8 @@ export const articles = defineCollection(async ({ cursor, limit, query }) => {
|
|
|
167
251
|
|
|
168
252
|
`cursorSchema` and `querySchema` accept any Standard Schema validator. Their
|
|
169
253
|
output types flow into the loader, so the loader needs no manual generic types.
|
|
254
|
+
The Collection exposes `querySchema` so tools such as `vitehub channels replay`
|
|
255
|
+
can describe the accepted query keys.
|
|
170
256
|
|
|
171
257
|
```ts
|
|
172
258
|
// app/composables/articles.ts
|
|
@@ -181,8 +267,20 @@ export const useArticles = () => useCollection("articles", {
|
|
|
181
267
|
ViteHub discovers modules in `server/collections` and generates the collection
|
|
182
268
|
registry and GET handler. The module must export a Collection with the same name
|
|
183
269
|
as its filename, so `articles.ts` exports `articles` and maps to `/api/articles`.
|
|
184
|
-
|
|
185
|
-
|
|
270
|
+
Each routed Collection must set `authorize` or `access: "public"`, or
|
|
271
|
+
`defineCollection()` throws `SOURCE_COLLECTION_ACCESS_REQUIRED`. `access: "public"` makes the route
|
|
272
|
+
public. `authorize: false` throws `SOURCE_COLLECTION_AUTHORIZE_FALSE`, and `access: "public"` with
|
|
273
|
+
`authorize` throws `SOURCE_COLLECTION_ACCESS_CONFLICT`. `authorize: true`
|
|
274
|
+
requires a signed-in `@vite-hub/auth` session, and a callback receives
|
|
275
|
+
`{ request, session, user }` and returns `true`, `false` for `403`, or a
|
|
276
|
+
`Response`. The route checks access before it parses the query. Without a session
|
|
277
|
+
it returns `401`, and `useCollection()` sets `error` to a `CollectionAccessError`
|
|
278
|
+
with that `status`. Generated routes wrap the page with Auth's `withAuthorization` when the host
|
|
279
|
+
enables Auth with a discovered Auth Definition (`hubSource({ auth: true })`
|
|
280
|
+
alongside `hubAuth()` outside `vite-hub`); otherwise a
|
|
281
|
+
Collection with `authorize: true` or a callback fails closed. Set `route: false`
|
|
282
|
+
to keep a Collection server-only. Then neither is needed. Do not repeat the route under
|
|
283
|
+
`server/api`. Restart Nuxt after
|
|
186
284
|
adding, removing, or renaming a Collection module so Nitro rebuilds its handler
|
|
187
285
|
manifest.
|
|
188
286
|
Callers do not repeat URL strings or generic imports. `filter` is validated by
|
|
@@ -193,10 +291,83 @@ origin-specific query. Collection owns limit enforcement, opaque cursor
|
|
|
193
291
|
transport, response shaping, and the exact item and filter types consumed by
|
|
194
292
|
`useCollection()`.
|
|
195
293
|
|
|
294
|
+
### Collections over an array
|
|
295
|
+
|
|
296
|
+
When the whole data set fits in memory, pass `array()` as the Collection source.
|
|
297
|
+
It filters, searches, sorts, counts, and pages the array, and returns `total` and
|
|
298
|
+
`facets` with each page:
|
|
299
|
+
|
|
300
|
+
```ts fragment
|
|
301
|
+
// server/collections/articles.ts
|
|
302
|
+
import { array, defineCollection } from "@vite-hub/source"
|
|
303
|
+
|
|
304
|
+
export const articles = defineCollection({
|
|
305
|
+
access: 'public',
|
|
306
|
+
source: array(() => loadArticles(), {
|
|
307
|
+
facets: ["category"],
|
|
308
|
+
filters: ["category", "authors.name"],
|
|
309
|
+
key: "slug",
|
|
310
|
+
search: ["title", "summary"],
|
|
311
|
+
sort: { field: "title" },
|
|
312
|
+
}),
|
|
313
|
+
transform: article => ({ slug: article.slug, title: article.title }),
|
|
314
|
+
})
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Clients filter with the declared field paths: `?category=guide` matches without
|
|
318
|
+
case, a repeated key matches any of its values, `?empty=category` matches items
|
|
319
|
+
with no value, and `?search=` matches the `search` fields. Any other key returns
|
|
320
|
+
`400`. Cursors are bound to the data and the query. A cursor from changed data or
|
|
321
|
+
another query returns `409`. `load` runs on every request; return
|
|
322
|
+
`{ items, digest }` when the origin already has a content digest, or ViteHub
|
|
323
|
+
hashes the items for pagination. Keyed lookups do not compute a digest.
|
|
324
|
+
`useCollection()` exposes `total` and `facets` from the latest
|
|
325
|
+
page. `key` adds `collection.get(key)` for server code, and `schema` validates
|
|
326
|
+
every item and types it from the schema output. Use a database `table()`
|
|
327
|
+
from `@vite-hub/source/drizzle` when the data set should not be loaded per
|
|
328
|
+
request. `table()` needs the optional `drizzle-orm` peer. Apps import it from
|
|
329
|
+
`vite-hub/source/drizzle`. `table()` selects every column. A public Collection
|
|
330
|
+
over it must set `transform` to return only the public fields, or
|
|
331
|
+
`defineCollection()` throws `SOURCE_COLLECTION_PUBLIC_TRANSFORM_REQUIRED`:
|
|
332
|
+
|
|
333
|
+
```ts fragment
|
|
334
|
+
export const authors = defineCollection({
|
|
335
|
+
access: 'public',
|
|
336
|
+
source: table({ db, orderBy: { column: users.id, direction: "asc", tieBreaker: users.id }, table: users }),
|
|
337
|
+
transform: ({ id, name }) => ({ id, name }),
|
|
338
|
+
})
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Pass `{ signal }` to `collection.get(key, { signal })` to cancel a direct read.
|
|
342
|
+
Cancelled reads reject with the signal's reason, including when a loader or
|
|
343
|
+
transform returns after cancellation.
|
|
344
|
+
|
|
196
345
|
Keep binary assets behind the Blob boundary and store a serializable reference in
|
|
197
346
|
the record. This keeps ordinary record reads lazy while treating the structured
|
|
198
347
|
data and its assets as one logical item.
|
|
199
348
|
|
|
349
|
+
### Inspect Collections
|
|
350
|
+
|
|
351
|
+
`vitehub inspect definitions --kind collection` lists each discovered Collection
|
|
352
|
+
with its file, source kind, and the options that it sets: schema, key, sort,
|
|
353
|
+
filters, search, facets, limits, transform, authorize, and route. The
|
|
354
|
+
`hubSource()` plugin contributes this list through `vitehub.inspect`, and
|
|
355
|
+
`inspectCollectionDefinitions({ projectRoot, serverDirs })` from
|
|
356
|
+
`@vite-hub/source/vite` returns the same summaries. Inspection reads the module
|
|
357
|
+
text and does not run it, so a value that is computed at runtime shows as
|
|
358
|
+
`Dynamic`.
|
|
359
|
+
|
|
360
|
+
```txt
|
|
361
|
+
Collections (collection): 1
|
|
362
|
+
articles server/collections/articles.ts [server-collections]
|
|
363
|
+
Source: array
|
|
364
|
+
Key: slug
|
|
365
|
+
Sort: publishedAt desc
|
|
366
|
+
Filters: category, authors.name
|
|
367
|
+
Transform: Yes
|
|
368
|
+
Route: GET /api/articles
|
|
369
|
+
```
|
|
370
|
+
|
|
200
371
|
## Used by
|
|
201
372
|
|
|
202
373
|
[`@vite-hub/workspace`](../workspace/README.md) materializes Source output into workspace files. Use this package directly when you only need typed source loading and not a workspace file tree.
|
package/dist/client.d.ts
CHANGED
|
@@ -1,32 +1,49 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as CollectionClientItem, c as CollectionFacets, h as CollectionQuery, p as CollectionPage, t as AnyCollection } from "./collection-B8sgxw5-.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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|