@vite-hub/source 0.3.1 → 0.4.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.
@@ -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. Create server/sources/${name}.ts with the Source as its default export.`, { 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 };
@@ -1,4 +1,4 @@
1
- import { ViteHubError } from "@vite-hub/runtime";
1
+ import { r as normalizeSourcePath } from "./path-Cm7wV1Dk.js";
2
2
  //#region \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -22,36 +22,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  enumerable: true
23
23
  }) : target, mod));
24
24
  //#endregion
25
- //#region src/core/errors.ts
26
- function sourceError(message, options) {
27
- return new ViteHubError("SOURCE_FAILED", message, options);
28
- }
29
- function sourceNotFoundError(name) {
30
- return new ViteHubError("SOURCE_NOT_FOUND", `[vitehub] Source "${name}" is not registered.`, { details: { name } });
31
- }
32
- function sourcePathError(path) {
33
- const publicPath = path.slice(0, 4096);
34
- return new ViteHubError("SOURCE_PATH_INVALID", `[vitehub] Source path escapes the source root: ${JSON.stringify(publicPath)}.`, { details: { path: publicPath } });
35
- }
36
- //#endregion
37
- //#region src/core/path.ts
38
- function normalizeSourcePath(path = "") {
39
- return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
40
- }
41
- function normalizeSafeSourcePath(path = "", options = {}) {
42
- const raw = path.replace(/\\/g, "/");
43
- const normalized = normalizeSourcePath(path);
44
- const parts = normalized.split("/").filter(Boolean);
45
- if (!options.allowEmpty && !normalized) throw sourcePathError(path);
46
- if (raw.startsWith("/") || /^[a-z]:/i.test(raw) || raw.includes("\0") || parts.some((part) => part === "." || part === "..")) throw sourcePathError(path);
47
- if (!options.allowReserved && (parts[0] === ".git" || parts[0] === ".vitehub")) throw sourcePathError(path);
48
- return normalized;
49
- }
50
- function decodeSourceContent(content, options) {
51
- if (options?.encoding === "binary") return typeof content === "string" ? new TextEncoder().encode(content) : content;
52
- return typeof content === "string" ? content : new TextDecoder().decode(content);
53
- }
54
- //#endregion
55
25
  //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js
56
26
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
57
27
  const WIN_SLASH = "\\\\/";
@@ -1983,4 +1953,4 @@ function matchesAny(path, patterns) {
1983
1953
  return createPathMatcher(patterns)(path);
1984
1954
  }
1985
1955
  //#endregion
1986
- export { normalizeSafeSourcePath as a, sourceNotFoundError as c, decodeSourceContent as i, sourcePathError as l, matchesAny as n, normalizeSourcePath as o, require_picomatch as r, sourceError as s, createPathMatcher as t, __toESM as u };
1956
+ export { __toESM as i, matchesAny as n, require_picomatch as r, createPathMatcher as t };
@@ -0,0 +1,156 @@
1
+ import { a as sourceNotFoundError, i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath, t as decodeSourceContent } from "./path-Cm7wV1Dk.js";
2
+ //#region src/core/reader.ts
3
+ function createSourceContext(name, context = {}) {
4
+ return {
5
+ abortSignal: context.abortSignal,
6
+ revision: context.revision,
7
+ rootDir: context.rootDir || process.cwd(),
8
+ source: context.source || name,
9
+ sourceRootDir: context.sourceRootDir,
10
+ workspace: context.workspace
11
+ };
12
+ }
13
+ function createMissingContentError(key) {
14
+ return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
15
+ }
16
+ function isNestedUnder(path, prefix) {
17
+ return !prefix || path === prefix || path.startsWith(`${prefix}/`);
18
+ }
19
+ function createDirectorySet(paths, prefix) {
20
+ const directories = /* @__PURE__ */ new Set();
21
+ const start = prefix ? prefix.length + 1 : 0;
22
+ for (const path of paths) {
23
+ const normalized = normalizeSourcePath(path).split("/").filter(Boolean).join("/");
24
+ if (prefix && !normalized.startsWith(`${prefix}/`)) continue;
25
+ const end = normalized.indexOf("/", start);
26
+ if (end !== -1) directories.add(normalized.slice(0, end));
27
+ }
28
+ return directories;
29
+ }
30
+ function createSource(source, context) {
31
+ return openSource(() => source, source.name, context);
32
+ }
33
+ /** A reader whose Source loads on its first operation, such as the file of a Source name. */
34
+ function openSource(load, name, context) {
35
+ const ctx = createSourceContext(name, context);
36
+ let revisionPromise;
37
+ let preparePromise;
38
+ async function revision() {
39
+ if (ctx.revision) return ctx.revision;
40
+ revisionPromise ||= Promise.resolve(load()).then((source) => source.resolveRevision?.(ctx));
41
+ const resolved = await revisionPromise;
42
+ if (resolved) ctx.revision = resolved;
43
+ return resolved;
44
+ }
45
+ async function prepared() {
46
+ await revision();
47
+ const source = await load();
48
+ if (!source.prepare) return source;
49
+ preparePromise ||= source.prepare(ctx);
50
+ await preparePromise;
51
+ return source;
52
+ }
53
+ async function keys() {
54
+ return await (await prepared()).getKeys(ctx);
55
+ }
56
+ async function get(key) {
57
+ return await (await prepared()).getItem(key, ctx);
58
+ }
59
+ return {
60
+ revision,
61
+ keys,
62
+ get,
63
+ async items() {
64
+ const source = await prepared();
65
+ if (source.getItems) return await source.getItems(ctx);
66
+ return await Promise.all((await keys()).map(get));
67
+ },
68
+ async read(key, options) {
69
+ const item = await get(key);
70
+ if (item.content === void 0) throw createMissingContentError(key);
71
+ return decodeSourceContent(item.content, options);
72
+ },
73
+ async meta(key) {
74
+ return await (await prepared()).getMeta?.(key, ctx);
75
+ },
76
+ async exists(key) {
77
+ return (await keys()).includes(key);
78
+ },
79
+ async list(prefix = "") {
80
+ await prepared();
81
+ const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }).split("/").filter(Boolean).join("/") : "";
82
+ const sourceKeys = await keys();
83
+ const directories = createDirectorySet(sourceKeys, normalizedPrefix);
84
+ const result = /* @__PURE__ */ new Map();
85
+ for (const directory of directories) result.set(directory, {
86
+ key: directory,
87
+ type: "directory"
88
+ });
89
+ for (const key of sourceKeys) {
90
+ const normalizedKey = normalizeSourcePath(key).split("/").filter(Boolean).join("/");
91
+ if (normalizedKey === normalizedPrefix) continue;
92
+ if (!isNestedUnder(normalizedKey, normalizedPrefix)) continue;
93
+ if (normalizedKey.slice(normalizedPrefix.length).replace(/^\//, "").includes("/")) continue;
94
+ result.delete(normalizedKey);
95
+ result.set(key, {
96
+ key,
97
+ type: "file"
98
+ });
99
+ }
100
+ return [...result.values()].sort((left, right) => left.key.localeCompare(right.key));
101
+ }
102
+ };
103
+ }
104
+ //#endregion
105
+ //#region src/core/registry.ts
106
+ const registryKey = Symbol.for("vitehub.source.registry");
107
+ function sourceRegistry() {
108
+ const store = globalThis;
109
+ return store[registryKey] ??= /* @__PURE__ */ new Map();
110
+ }
111
+ /**
112
+ * Registers the Source files by name. Each module loads when a reader of its name needs it first, so a Source costs
113
+ * nothing at server start. The generated `server/sources/` registry plugin calls it.
114
+ */
115
+ function registerSourceLoaders(loaders) {
116
+ for (const [name, load] of Object.entries(loaders)) sourceRegistry().set(name, { load });
117
+ }
118
+ /** Registers a Source value by name. Tests call it. */
119
+ function registerSource(name, source) {
120
+ sourceRegistry().set(name, {
121
+ load: async () => ({ default: source }),
122
+ source: Promise.resolve(source)
123
+ });
124
+ return source;
125
+ }
126
+ function registerSources(sources) {
127
+ for (const [name, source] of Object.entries(sources)) registerSource(name, source);
128
+ return sources;
129
+ }
130
+ function clearSources() {
131
+ sourceRegistry().clear();
132
+ }
133
+ function loadRegistered(entry) {
134
+ if (!entry.source) {
135
+ const loading = entry.load().then((module) => module.default);
136
+ entry.source = loading;
137
+ loading.catch(() => {
138
+ if (entry.source === loading) entry.source = void 0;
139
+ });
140
+ }
141
+ return entry.source;
142
+ }
143
+ function useSource(input, context) {
144
+ if (typeof input !== "string") return createSource(input, context);
145
+ let entry;
146
+ return openSource(() => {
147
+ entry ??= sourceRegistry().get(input);
148
+ if (!entry) throw sourceNotFoundError(input);
149
+ return loadRegistered(entry);
150
+ }, input, {
151
+ ...context,
152
+ source: context?.source ?? input
153
+ });
154
+ }
155
+ //#endregion
156
+ export { useSource as a, registerSources as i, registerSource as n, registerSourceLoaders as r, clearSources as t };
@@ -0,0 +1,23 @@
1
+ import { i as RegisteredSource, l as SourceContext, o as Source, v as SourceName, y as SourceReader } from "./types-Ln-FxVFn.js";
2
+ //#region src/core/registry.d.ts
3
+ /** Imports the module of a Source file, such as `() => import("./server/sources/docs.ts")`. */
4
+ type SourceModuleLoader = () => Promise<{
5
+ default: Source;
6
+ }>;
7
+ /**
8
+ * Registers the Source files by name. Each module loads when a reader of its name needs it first, so a Source costs
9
+ * nothing at server start. The generated `server/sources/` registry plugin calls it.
10
+ */
11
+ declare function registerSourceLoaders(loaders: Record<string, SourceModuleLoader>): void;
12
+ /** Registers a Source value by name. Tests call it. */
13
+ declare function registerSource<const TSource extends Source>(name: string, source: TSource): TSource;
14
+ declare function registerSources<const TSources extends Record<string, Source>>(sources: TSources): TSources;
15
+ declare function clearSources(): void;
16
+ /**
17
+ * Opens a reader for the Source in `server/sources/<name>.ts`, or for a Source value such as `github({ repo })`.
18
+ * The generated `.vitehub` types give each name its Source type. The file loads on the first read.
19
+ */
20
+ declare function useSource<TName extends SourceName>(name: TName, context?: Partial<SourceContext>): SourceReader<RegisteredSource<TName>>;
21
+ declare function useSource<const TSource extends Source>(source: TSource, context?: Partial<SourceContext>): SourceReader<TSource>;
22
+ //#endregion
23
+ export { registerSources as a, registerSourceLoaders as i, clearSources as n, useSource as o, registerSource as r, SourceModuleLoader as t };
@@ -1,4 +1,4 @@
1
- import { a as normalizeSafeSourcePath } from "./path-DFlSryRA.js";
1
+ import { n as normalizeSafeSourcePath } from "./path-Cm7wV1Dk.js";
2
2
  //#region src/sources/github/root.ts
3
3
  function normalizeGitHubRoot(path = "") {
4
4
  const root = path.replace(/\\/g, "/").split("/").filter((part) => part !== ".").join("/");
package/dist/server.js CHANGED
@@ -1,5 +1,5 @@
1
- import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
2
- import { r as CollectionCursorError, t as assertCollectionAccess } from "./collection-C0Rvrx3p.js";
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-DZdhDQpU.js";
2
+ import { r as CollectionCursorError, t as assertCollectionAccess } from "./collection-C1TZnrRP.js";
3
3
  //#region src/cached-source.ts
4
4
  /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
5
5
  function cachedSource(reader, options) {
package/dist/vite.d.ts CHANGED
@@ -60,6 +60,17 @@ interface ViteHubInspectionPluginMetadata {
60
60
  inspect?: ViteHubInspectionContributor | ViteHubInspectionContributorFactory;
61
61
  }
62
62
  //#endregion
63
+ //#region ../internal/src/contributions.d.ts
64
+ /** Roots that ViteHub passes to every contribution factory. */
65
+ interface ContributionContext {
66
+ /** Vite root. */
67
+ root: string;
68
+ /** ViteHub project root. It can differ from the Vite root, for example in a Nuxt app with a `srcDir`. */
69
+ projectRoot: string;
70
+ /** Server directories that the host forwards, for example Nuxt's `serverDir` and the server directories of layers. */
71
+ serverDirs?: readonly string[];
72
+ }
73
+ //#endregion
63
74
  //#region src/inspect.d.ts
64
75
  interface CollectionInspectionOptions {
65
76
  projectRoot: string;
@@ -109,6 +120,13 @@ export interface SourceGenerationOptions {
109
120
  importBase?: string;
110
121
  projectRoot: string;
111
122
  serverDirs?: string[];
123
+ /**
124
+ * The app has ViteHub Queue: the GitHub push webhook of Content sends the pages that a push changed to the
125
+ * `vitehub-content-prewarm` Queue. Without it, the webhook prewarms them itself.
126
+ */
127
+ queue?: boolean;
128
+ /** The import of `defineQueue` and `dynamicQueue`, such as `vite-hub/queue`. */
129
+ queueImport?: string;
112
130
  }
113
131
  export interface SourceVitePluginOptions {
114
132
  /** Pass Auth's `withAuthorization` to generated Collection routes when the Auth Vite plugin has a Definition. */
@@ -123,6 +141,10 @@ export interface SourceVitePluginOptions {
123
141
  };
124
142
  contentImportBase?: string;
125
143
  importBase?: string;
144
+ /** The app has ViteHub Queue, so Content prewarms the pages of a GitHub push through it. */
145
+ queue?: boolean;
146
+ /** The import of `defineQueue` and `dynamicQueue`. Defaults to `@vite-hub/queue`. */
147
+ queueImport?: string;
126
148
  }
127
149
  /** The discovered `server/content.ts` file. Its default export is the Content runtime. */
128
150
  export interface ContentDefinitionFile {
@@ -217,13 +239,21 @@ export declare function hubSource(options?: SourceVitePluginOptions): Plugin & {
217
239
  /** The `server/content.ts` file found by the last preparation of `projectRoot` (default: the latest root). */
218
240
  getContentDefinition: (projectRoot?: string) => ContentDefinitionFile | undefined;
219
241
  onGeneratedHandlersChanged: (listener: GeneratedSourceHandlersListener, options?: GeneratedSourceHandlersListenerOptions) => () => void;
220
- prepareSources: (options: Omit<SourceGenerationOptions, "appSeo" | "auth" | "contentImportBase" | "importBase">) => Promise<GeneratedSourceHandler[]>;
242
+ prepareSources: (options: Omit<SourceGenerationOptions, "appSeo" | "auth" | "contentImportBase" | "importBase" | "queue" | "queueImport">) => Promise<GeneratedSourceHandler[]>;
221
243
  };
222
244
  nitro: {
223
245
  name: string;
224
246
  setup(nitro: SourceNitroHost): Promise<void>;
225
247
  };
226
- vitehub: ViteHubInspectionPluginMetadata;
248
+ vitehub: ViteHubInspectionPluginMetadata & {
249
+ queues: (context: ContributionContext) => Promise<Array<{
250
+ name: string;
251
+ definition: {
252
+ module: string;
253
+ };
254
+ reason: string;
255
+ }>>;
256
+ };
227
257
  };
228
258
  //#endregion
229
259
  export type { CollectionInspectionOptions };