@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/dist/vite.js
CHANGED
|
@@ -1,21 +1,43 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
1
|
+
import { t as collectionRoutePath } from "./collection-route-BplWPxHR.js";
|
|
2
|
+
import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
|
|
3
|
+
import { r as isRecordOrFunction } from "./object-CtSHeGQO.js";
|
|
4
|
+
import { i as resolveGlobInput, r as globFilePath, t as collectGlobFiles } from "./glob-DmdMVqjx.js";
|
|
5
|
+
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
6
|
+
import { formatDiagnostic } from "nostics";
|
|
3
7
|
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
8
|
import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve } from "node:path";
|
|
5
9
|
import { pathToFileURL } from "node:url";
|
|
6
|
-
import { statSync } from "node:fs";
|
|
7
|
-
import {
|
|
10
|
+
import { mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { parseSync } from "vite";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { once } from "node:events";
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { gzipSync } from "node:zlib";
|
|
8
17
|
//#region ../internal/src/build/vite.ts
|
|
9
18
|
const projectRootDirectoryMarkers = [
|
|
10
19
|
["server", "agents"],
|
|
11
20
|
["server", "channels"],
|
|
21
|
+
["server", "connections"],
|
|
12
22
|
["server", "browsers"],
|
|
13
23
|
["server", "emails"],
|
|
14
24
|
["server", "schedules"],
|
|
15
25
|
["server", "workspaces"]
|
|
16
26
|
];
|
|
17
|
-
const projectRootFileMarkers = [
|
|
27
|
+
const projectRootFileMarkers = [
|
|
28
|
+
["package.json"],
|
|
29
|
+
["nuxt.config.ts"],
|
|
30
|
+
["nuxt.config.mts"],
|
|
31
|
+
["nuxt.config.js"],
|
|
32
|
+
["nuxt.config.mjs"]
|
|
33
|
+
];
|
|
18
34
|
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
35
|
+
/** The application's mount path, which can differ from Nuxt's Vite asset base. */
|
|
36
|
+
const VITEHUB_APP_BASE_URL = "__vitehubAppBaseURL";
|
|
37
|
+
/**
|
|
38
|
+
* Server directories that ViteHub scans for Definitions. The first entry is the application.
|
|
39
|
+
* Later entries are Nuxt layers in Nuxt priority order.
|
|
40
|
+
*/
|
|
19
41
|
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
20
42
|
function resolveViteHubProjectRoot(root, options = {}) {
|
|
21
43
|
const resolvedRoot = resolve(root);
|
|
@@ -24,7 +46,12 @@ function resolveViteHubProjectRoot(root, options = {}) {
|
|
|
24
46
|
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
25
47
|
if (basename(resolvedRoot) === "app") {
|
|
26
48
|
const parent = dirname(resolvedRoot);
|
|
27
|
-
if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)
|
|
49
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
50
|
+
"nuxt.config.ts",
|
|
51
|
+
"nuxt.config.mts",
|
|
52
|
+
"nuxt.config.js",
|
|
53
|
+
"nuxt.config.mjs"
|
|
54
|
+
]))) return parent;
|
|
28
55
|
}
|
|
29
56
|
let current = resolvedRoot;
|
|
30
57
|
while (true) {
|
|
@@ -45,20 +72,1036 @@ function hasProjectRootDirectoryMarker(root) {
|
|
|
45
72
|
}
|
|
46
73
|
function hasProjectRootMarker(root) {
|
|
47
74
|
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
75
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
76
|
+
}
|
|
77
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
78
|
+
for (const marker of markers) {
|
|
79
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
80
|
+
try {
|
|
81
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code !== "ENOENT") throw error;
|
|
84
|
+
}
|
|
52
85
|
}
|
|
53
86
|
return false;
|
|
54
87
|
}
|
|
55
88
|
//#endregion
|
|
89
|
+
//#region ../internal/src/build/scan-module.ts
|
|
90
|
+
/**
|
|
91
|
+
* Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
|
|
92
|
+
* the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
|
|
93
|
+
* `dynamic`, so callers can report their own diagnostics.
|
|
94
|
+
*/
|
|
95
|
+
/** The value of an expression that the scanner cannot read without running the module. */
|
|
96
|
+
const dynamic$1 = Symbol("dynamic");
|
|
97
|
+
function languageOf(file) {
|
|
98
|
+
if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
|
|
99
|
+
if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
|
|
100
|
+
if (/\.(?:c|m)?js$/i.test(file)) return "js";
|
|
101
|
+
return "ts";
|
|
102
|
+
}
|
|
103
|
+
/** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
|
|
104
|
+
function scanModule(source, file = "module.ts") {
|
|
105
|
+
const result = parseSync(file, source, {
|
|
106
|
+
lang: languageOf(file),
|
|
107
|
+
preserveParens: false,
|
|
108
|
+
sourceType: "module"
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
comments: result.comments,
|
|
112
|
+
errors: result.errors,
|
|
113
|
+
file,
|
|
114
|
+
program: result.program,
|
|
115
|
+
source
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Lists the names that a module exports. A default export reads as `default`. Type-only exports are left out. */
|
|
119
|
+
function exportNames(source, file = "module.ts") {
|
|
120
|
+
const { module } = parseSync(file, source, {
|
|
121
|
+
lang: languageOf(file),
|
|
122
|
+
sourceType: "module"
|
|
123
|
+
});
|
|
124
|
+
return module.staticExports.flatMap((statement) => statement.entries).flatMap((entry) => {
|
|
125
|
+
if (entry.isType) return [];
|
|
126
|
+
if (entry.exportName.kind === "Default") return ["default"];
|
|
127
|
+
return entry.exportName.name === null ? [] : [entry.exportName.name];
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function isNode$1(value) {
|
|
131
|
+
return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
|
|
132
|
+
}
|
|
133
|
+
/** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
|
|
134
|
+
function walk$1(node, visit, parent) {
|
|
135
|
+
if (visit(node, parent) === false) return;
|
|
136
|
+
const fields = node;
|
|
137
|
+
for (const key in fields) {
|
|
138
|
+
const child = fields[key];
|
|
139
|
+
if (typeof child !== "object" || child === null || key === "parent") continue;
|
|
140
|
+
if (Array.isArray(child)) {
|
|
141
|
+
for (const item of child) if (isNode$1(item)) walk$1(item, visit, node);
|
|
142
|
+
} else if (isNode$1(child)) walk$1(child, visit, node);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
|
|
146
|
+
function unwrapExpression(node) {
|
|
147
|
+
while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
|
|
148
|
+
return node;
|
|
149
|
+
}
|
|
150
|
+
/** A call argument without assertions, or undefined for a spread or missing argument. */
|
|
151
|
+
function argumentExpression(argument) {
|
|
152
|
+
return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
|
|
153
|
+
}
|
|
154
|
+
/** Calls whose callee is a plain identifier in `names`, such as `defineCollection(...)`, in source order. */
|
|
155
|
+
function findCalls(module, names) {
|
|
156
|
+
const wanted = new Set(names);
|
|
157
|
+
const calls = [];
|
|
158
|
+
walk$1(module.program, (node) => {
|
|
159
|
+
if (node.type === "CallExpression" && node.callee.type === "Identifier" && wanted.has(node.callee.name)) calls.push(node);
|
|
160
|
+
});
|
|
161
|
+
return calls.sort((left, right) => left.start - right.start);
|
|
162
|
+
}
|
|
163
|
+
function staticKey(property) {
|
|
164
|
+
const key = property.key;
|
|
165
|
+
if (key.type === "Identifier" && !property.computed) return key.name;
|
|
166
|
+
if (key.type === "PrivateIdentifier") return;
|
|
167
|
+
const value = staticValue(key);
|
|
168
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
|
|
169
|
+
}
|
|
170
|
+
/** The members of an object literal in source order. */
|
|
171
|
+
function objectProperties(object) {
|
|
172
|
+
return object.properties.map((node) => node.type === "SpreadElement" ? {
|
|
173
|
+
computed: false,
|
|
174
|
+
key: void 0,
|
|
175
|
+
node,
|
|
176
|
+
value: void 0
|
|
177
|
+
} : {
|
|
178
|
+
computed: node.computed,
|
|
179
|
+
key: staticKey(node),
|
|
180
|
+
node,
|
|
181
|
+
value: unwrapExpression(node.value)
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** The last member named `name`, which is the one that the object keeps at runtime. */
|
|
185
|
+
function findProperty(object, name) {
|
|
186
|
+
return objectProperties(object).findLast((property) => property.key === name);
|
|
187
|
+
}
|
|
188
|
+
/** The value of a template literal without substitutions. */
|
|
189
|
+
function staticTemplate(node) {
|
|
190
|
+
if (node.expressions.length) return dynamic$1;
|
|
191
|
+
return node.quasis[0]?.value.cooked ?? dynamic$1;
|
|
192
|
+
}
|
|
193
|
+
const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
|
|
194
|
+
/**
|
|
195
|
+
* True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
|
|
196
|
+
* and accepts legacy octal escapes, so the scanner checks them again.
|
|
197
|
+
*/
|
|
198
|
+
function hasInvalidEscape(raw) {
|
|
199
|
+
for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
|
|
200
|
+
const code = escape.slice(2, -1);
|
|
201
|
+
if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
|
|
202
|
+
} else if (escape.startsWith("u")) {
|
|
203
|
+
if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
|
|
204
|
+
} else if (escape.startsWith("x")) {
|
|
205
|
+
if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
|
|
206
|
+
} else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
|
|
211
|
+
* and arrays and objects of these. Any other expression gives `dynamic`.
|
|
212
|
+
*/
|
|
213
|
+
function staticValue(node) {
|
|
214
|
+
node = unwrapExpression(node);
|
|
215
|
+
switch (node.type) {
|
|
216
|
+
case "Literal":
|
|
217
|
+
if ("regex" in node) return dynamic$1;
|
|
218
|
+
return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic$1 : node.value;
|
|
219
|
+
case "TemplateLiteral": return staticTemplate(node);
|
|
220
|
+
case "Identifier": return node.name === "undefined" ? void 0 : dynamic$1;
|
|
221
|
+
case "UnaryExpression": {
|
|
222
|
+
if (node.operator === "void") return staticValue(node.argument) === dynamic$1 ? dynamic$1 : void 0;
|
|
223
|
+
const value = staticValue(node.argument);
|
|
224
|
+
if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
|
|
225
|
+
return dynamic$1;
|
|
226
|
+
}
|
|
227
|
+
case "ArrayExpression": {
|
|
228
|
+
const values = [];
|
|
229
|
+
for (const element of node.elements) {
|
|
230
|
+
if (element === null || element.type === "SpreadElement") return dynamic$1;
|
|
231
|
+
const value = staticValue(element);
|
|
232
|
+
if (value === dynamic$1) return dynamic$1;
|
|
233
|
+
values.push(value);
|
|
234
|
+
}
|
|
235
|
+
return values;
|
|
236
|
+
}
|
|
237
|
+
case "ObjectExpression": {
|
|
238
|
+
const values = {};
|
|
239
|
+
for (const property of objectProperties(node)) {
|
|
240
|
+
if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic$1;
|
|
241
|
+
const value = staticValue(property.value);
|
|
242
|
+
if (value === dynamic$1) return dynamic$1;
|
|
243
|
+
Object.defineProperty(values, property.key, {
|
|
244
|
+
configurable: true,
|
|
245
|
+
enumerable: true,
|
|
246
|
+
value,
|
|
247
|
+
writable: true
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return values;
|
|
251
|
+
}
|
|
252
|
+
default: return dynamic$1;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** The static string value of an expression, or undefined when it is not a string literal. */
|
|
256
|
+
function staticString(node) {
|
|
257
|
+
if (node === void 0) return;
|
|
258
|
+
const value = staticValue(node);
|
|
259
|
+
return typeof value === "string" ? value : void 0;
|
|
260
|
+
}
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region ../internal/src/hints.ts
|
|
263
|
+
/**
|
|
264
|
+
* The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
|
|
265
|
+
* about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
|
|
266
|
+
* the file instead of the terminal.
|
|
267
|
+
*/
|
|
268
|
+
const viteHubHintsFile = ".vitehub/hints.json";
|
|
269
|
+
const runsKey = Symbol.for("vitehub.hints.runs");
|
|
270
|
+
const shared = globalThis;
|
|
271
|
+
const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
|
|
272
|
+
const startedKey = Symbol.for("vitehub.hints.started");
|
|
273
|
+
const startedShared = globalThis;
|
|
274
|
+
const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
|
|
275
|
+
/**
|
|
276
|
+
* The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
|
|
277
|
+
* Vite root in `app/`, one folder below.
|
|
278
|
+
*/
|
|
279
|
+
function hintsFile(config) {
|
|
280
|
+
const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
|
|
281
|
+
return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
|
|
282
|
+
}
|
|
283
|
+
function startRun(config) {
|
|
284
|
+
const file = hintsFile(config);
|
|
285
|
+
const run = {
|
|
286
|
+
file,
|
|
287
|
+
report: {
|
|
288
|
+
version: 1,
|
|
289
|
+
command: config.command,
|
|
290
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
291
|
+
hints: []
|
|
292
|
+
},
|
|
293
|
+
keys: /* @__PURE__ */ new Set()
|
|
294
|
+
};
|
|
295
|
+
runs.set(file, run);
|
|
296
|
+
return run;
|
|
297
|
+
}
|
|
298
|
+
function write(run) {
|
|
299
|
+
mkdirSync(dirname(run.file), { recursive: true });
|
|
300
|
+
writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Reports a hint from a Vite plugin hook: prints it once with its fix and docs link, and adds it to
|
|
304
|
+
* {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
|
|
305
|
+
*/
|
|
306
|
+
function reportViteHubHint(config, diagnostic) {
|
|
307
|
+
const run = runs.get(hintsFile(config)) ?? startRun(config);
|
|
308
|
+
const hint = {
|
|
309
|
+
code: diagnostic.code,
|
|
310
|
+
why: diagnostic.why,
|
|
311
|
+
...diagnostic.fix ? { fix: diagnostic.fix } : {},
|
|
312
|
+
...diagnostic.docs ? { docs: diagnostic.docs } : {},
|
|
313
|
+
...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
|
|
314
|
+
};
|
|
315
|
+
const key = JSON.stringify([hint.code, hint.sources ?? []]);
|
|
316
|
+
if (run.keys.has(key)) return;
|
|
317
|
+
run.keys.add(key);
|
|
318
|
+
run.report.hints.push(hint);
|
|
319
|
+
write(run);
|
|
320
|
+
config.logger.warn(formatDiagnostic(diagnostic));
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
|
|
324
|
+
* leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
|
|
325
|
+
* package used without `vitehub()` starts its own run. The first call for a resolved config starts the run, and the
|
|
326
|
+
* calls of other plugins of the same build keep it.
|
|
327
|
+
*/
|
|
328
|
+
function startViteHubHints(config) {
|
|
329
|
+
if (started.has(config)) return;
|
|
330
|
+
started.add(config);
|
|
331
|
+
write(startRun(config));
|
|
332
|
+
}
|
|
333
|
+
//#endregion
|
|
334
|
+
//#region ../internal/src/nitro-kit.ts
|
|
335
|
+
function cloneArray(value) {
|
|
336
|
+
return Array.isArray(value) ? [...value] : [];
|
|
337
|
+
}
|
|
338
|
+
function sameHandler(left, right) {
|
|
339
|
+
return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
|
|
340
|
+
}
|
|
341
|
+
/** Create a Nitro 3 configuration builder for generated ViteHub output. */
|
|
342
|
+
function createNitroServerKit(value = {}) {
|
|
343
|
+
const config = isRecordOrFunction(value) ? { ...value } : {};
|
|
344
|
+
const handlers = cloneArray(config.handlers);
|
|
345
|
+
const plugins = cloneArray(config.plugins);
|
|
346
|
+
config.handlers = handlers;
|
|
347
|
+
config.plugins = plugins;
|
|
348
|
+
return {
|
|
349
|
+
config,
|
|
350
|
+
addHandler(handler, position = "end") {
|
|
351
|
+
if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
|
|
352
|
+
if (position === "start") handlers.unshift({ ...handler });
|
|
353
|
+
else handlers.push({ ...handler });
|
|
354
|
+
},
|
|
355
|
+
addPlugin(plugin, position = "end") {
|
|
356
|
+
if (plugins.includes(plugin)) return;
|
|
357
|
+
if (position === "start") plugins.unshift(plugin);
|
|
358
|
+
else plugins.push(plugin);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
//#endregion
|
|
363
|
+
//#region src/internal/content-types-writer.ts
|
|
364
|
+
const installed = /* @__PURE__ */ new WeakMap();
|
|
365
|
+
/** Keep writes in the Nitro host, including when its runtime runs in workerd. */
|
|
366
|
+
function installContentTypesWriter(host, plugin) {
|
|
367
|
+
if (!host.options?.dev) return Promise.resolve();
|
|
368
|
+
const previous = installed.get(host);
|
|
369
|
+
if (previous) return previous;
|
|
370
|
+
const installation = startWriter(host, plugin);
|
|
371
|
+
installed.set(host, installation);
|
|
372
|
+
return installation;
|
|
373
|
+
}
|
|
374
|
+
async function startWriter(host, plugin) {
|
|
375
|
+
const file = resolve(dirname(plugin), "../types/content.d.ts");
|
|
376
|
+
const path = `/${randomUUID()}`;
|
|
377
|
+
const server = createServer((request, response) => {
|
|
378
|
+
if (request.method !== "POST" || request.url !== path || request.headers.origin) {
|
|
379
|
+
response.writeHead(403).end();
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
(async () => {
|
|
383
|
+
request.setEncoding("utf8");
|
|
384
|
+
let declarations = "";
|
|
385
|
+
for await (const chunk of request) {
|
|
386
|
+
declarations += String(chunk);
|
|
387
|
+
if (declarations.length > 16777216) {
|
|
388
|
+
response.writeHead(413).end();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (await readFile(file, "utf8").catch(() => void 0) !== declarations) {
|
|
393
|
+
await mkdir(dirname(file), { recursive: true });
|
|
394
|
+
await writeFile(file, declarations, "utf8");
|
|
395
|
+
}
|
|
396
|
+
response.writeHead(204).end();
|
|
397
|
+
})().catch(() => response.writeHead(500).end());
|
|
398
|
+
});
|
|
399
|
+
server.listen(0, "127.0.0.1");
|
|
400
|
+
await once(server, "listening");
|
|
401
|
+
server.unref();
|
|
402
|
+
let closing;
|
|
403
|
+
host.hooks.hook("close", () => closing ??= new Promise((resolve, reject) => {
|
|
404
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
405
|
+
server.closeAllConnections();
|
|
406
|
+
}));
|
|
407
|
+
const address = server.address();
|
|
408
|
+
invariant(address && typeof address !== "string", "the Content types writer listens on a TCP host and port, so it has a TCP address");
|
|
409
|
+
host.options.runtimeConfig ??= {};
|
|
410
|
+
host.options.runtimeConfig.vitehubContentTypesWriter = `http://127.0.0.1:${address.port}${path}`;
|
|
411
|
+
}
|
|
412
|
+
//#endregion
|
|
413
|
+
//#region src/internal/content-types-plugin.injected.ts
|
|
414
|
+
/**
|
|
415
|
+
* Source of the generated Nitro plugin that writes the types of `content.get()`, `content.list()`, and
|
|
416
|
+
* `content.query()` in development. `importBase` and `contentModule` are JSON string literals of import paths. The
|
|
417
|
+
* text runs in the app server, not here, so its error stays plain.
|
|
418
|
+
*/
|
|
419
|
+
function renderContentTypesPlugin(importBase, contentModule) {
|
|
420
|
+
return [
|
|
421
|
+
`import { defineContentTypesPlugin } from ${importBase}`,
|
|
422
|
+
"import { useRuntimeConfig } from \"nitro/runtime-config\"",
|
|
423
|
+
"",
|
|
424
|
+
"// A production build drops this branch, so the server does not load Content at startup.",
|
|
425
|
+
"const write = async (declarations) => {",
|
|
426
|
+
" const response = await fetch(useRuntimeConfig().vitehubContentTypesWriter, { method: \"POST\", body: declarations })",
|
|
427
|
+
" if (!response.ok) throw new Error(`Content types writer returned ${response.status}`)",
|
|
428
|
+
"}",
|
|
429
|
+
`export default import.meta.dev ? defineContentTypesPlugin(async () => (await import(${contentModule})).default, write, { moduleName: ${importBase} }) : () => {}`,
|
|
430
|
+
""
|
|
431
|
+
].join("\n");
|
|
432
|
+
}
|
|
433
|
+
//#endregion
|
|
434
|
+
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
435
|
+
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
436
|
+
function normalizeWindowsPath(input = "") {
|
|
437
|
+
if (!input) return input;
|
|
438
|
+
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
439
|
+
}
|
|
440
|
+
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
441
|
+
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
442
|
+
function cwd() {
|
|
443
|
+
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
444
|
+
return "/";
|
|
445
|
+
}
|
|
446
|
+
const resolve$1 = function(...arguments_) {
|
|
447
|
+
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
448
|
+
let resolvedPath = "";
|
|
449
|
+
let resolvedAbsolute = false;
|
|
450
|
+
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
451
|
+
const path = index >= 0 ? arguments_[index] : cwd();
|
|
452
|
+
if (!path || path.length === 0) continue;
|
|
453
|
+
resolvedPath = `${path}/${resolvedPath}`;
|
|
454
|
+
resolvedAbsolute = isAbsolute$1(path);
|
|
455
|
+
}
|
|
456
|
+
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
457
|
+
if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
|
|
458
|
+
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
459
|
+
};
|
|
460
|
+
function normalizeString(path, allowAboveRoot) {
|
|
461
|
+
let res = "";
|
|
462
|
+
let lastSegmentLength = 0;
|
|
463
|
+
let lastSlash = -1;
|
|
464
|
+
let dots = 0;
|
|
465
|
+
let char = null;
|
|
466
|
+
for (let index = 0; index <= path.length; ++index) {
|
|
467
|
+
if (index < path.length) char = path[index];
|
|
468
|
+
else if (char === "/") break;
|
|
469
|
+
else char = "/";
|
|
470
|
+
if (char === "/") {
|
|
471
|
+
if (lastSlash === index - 1 || dots === 1);
|
|
472
|
+
else if (dots === 2) {
|
|
473
|
+
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
474
|
+
if (res.length > 2) {
|
|
475
|
+
const lastSlashIndex = res.lastIndexOf("/");
|
|
476
|
+
if (lastSlashIndex === -1) {
|
|
477
|
+
res = "";
|
|
478
|
+
lastSegmentLength = 0;
|
|
479
|
+
} else {
|
|
480
|
+
res = res.slice(0, lastSlashIndex);
|
|
481
|
+
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
482
|
+
}
|
|
483
|
+
lastSlash = index;
|
|
484
|
+
dots = 0;
|
|
485
|
+
continue;
|
|
486
|
+
} else if (res.length > 0) {
|
|
487
|
+
res = "";
|
|
488
|
+
lastSegmentLength = 0;
|
|
489
|
+
lastSlash = index;
|
|
490
|
+
dots = 0;
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (allowAboveRoot) {
|
|
495
|
+
res += res.length > 0 ? "/.." : "..";
|
|
496
|
+
lastSegmentLength = 2;
|
|
497
|
+
}
|
|
498
|
+
} else {
|
|
499
|
+
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
500
|
+
else res = path.slice(lastSlash + 1, index);
|
|
501
|
+
lastSegmentLength = index - lastSlash - 1;
|
|
502
|
+
}
|
|
503
|
+
lastSlash = index;
|
|
504
|
+
dots = 0;
|
|
505
|
+
} else if (char === "." && dots !== -1) ++dots;
|
|
506
|
+
else dots = -1;
|
|
507
|
+
}
|
|
508
|
+
return res;
|
|
509
|
+
}
|
|
510
|
+
const isAbsolute$1 = function(p) {
|
|
511
|
+
return _IS_ABSOLUTE_RE.test(p);
|
|
512
|
+
};
|
|
513
|
+
const relative$1 = function(from, to) {
|
|
514
|
+
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
515
|
+
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
516
|
+
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
517
|
+
const _fromCopy = [..._from];
|
|
518
|
+
for (const segment of _fromCopy) {
|
|
519
|
+
if (_to[0] !== segment) break;
|
|
520
|
+
_from.shift();
|
|
521
|
+
_to.shift();
|
|
522
|
+
}
|
|
523
|
+
return [..._from.map(() => ".."), ..._to].join("/");
|
|
524
|
+
};
|
|
525
|
+
//#endregion
|
|
526
|
+
//#region ../internal/src/inspect.ts
|
|
527
|
+
function relativeDefinitionFile(projectRoot, file) {
|
|
528
|
+
return relative$1(projectRoot, file).replaceAll("\\", "/");
|
|
529
|
+
}
|
|
530
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
531
|
+
new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
532
|
+
new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
533
|
+
//#endregion
|
|
534
|
+
//#region src/internal/collection-discovery.ts
|
|
535
|
+
/** The initializers of top-level `const`, `let`, and `var` declarations named `name`, with their declaration kind. */
|
|
536
|
+
function declarationInitializers(module, name, exportedOnly) {
|
|
537
|
+
return module.program.body.flatMap((statement) => {
|
|
538
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : exportedOnly ? void 0 : statement;
|
|
539
|
+
if (declaration?.type !== "VariableDeclaration") return [];
|
|
540
|
+
return declaration.declarations.flatMap((declarator) => declarator.id.type === "Identifier" && declarator.id.name === name && declarator.init ? [{
|
|
541
|
+
init: declarator.init,
|
|
542
|
+
constant: declaration.kind === "const"
|
|
543
|
+
}] : []);
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
const viteHubSourceSpecifier = /^(?:@vite-hub\/source|vite-hub\/source)(?:\/|$)/;
|
|
547
|
+
/** Checks binding targets, including nested destructuring, without treating property keys or defaults as bindings. */
|
|
548
|
+
function bindsCollectionFactory(binding) {
|
|
549
|
+
switch (binding.type) {
|
|
550
|
+
case "Identifier": return binding.name === "defineCollection";
|
|
551
|
+
case "ObjectPattern": return binding.properties.some((property) => bindsCollectionFactory(property.type === "RestElement" ? property.argument : property.value));
|
|
552
|
+
case "ArrayPattern": return binding.elements.some((element) => element !== null && bindsCollectionFactory(element));
|
|
553
|
+
case "AssignmentPattern": return bindsCollectionFactory(binding.left);
|
|
554
|
+
case "RestElement": return bindsCollectionFactory(binding.argument);
|
|
555
|
+
default: return false;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* True when `defineCollection` in this module is ViteHub's factory: imported from a ViteHub Source entry, or not
|
|
560
|
+
* declared in the module at all (an auto-import). A local function or an import from elsewhere with that name can
|
|
561
|
+
* return any Collection, so its options say nothing about the route.
|
|
562
|
+
*/
|
|
563
|
+
function callsViteHubFactory(module) {
|
|
564
|
+
for (const statement of module.program.body) {
|
|
565
|
+
if (statement.type === "ImportDeclaration") {
|
|
566
|
+
if (statement.specifiers.some((specifier) => specifier.local.name === "defineCollection")) return statement.importKind !== "type" && viteHubSourceSpecifier.test(statement.source.value);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
|
|
570
|
+
if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id?.name === "defineCollection") return false;
|
|
571
|
+
if (declaration?.type === "VariableDeclaration" && declaration.declarations.some((declarator) => bindsCollectionFactory(declarator.id))) return false;
|
|
572
|
+
}
|
|
573
|
+
return true;
|
|
574
|
+
}
|
|
575
|
+
/** The local binding that `export { local as exportName }` exports, without a module source. */
|
|
576
|
+
function exportedLocalName(module, exportName) {
|
|
577
|
+
for (const statement of module.program.body) {
|
|
578
|
+
if (statement.type !== "ExportNamedDeclaration" || statement.source || statement.exportKind === "type") continue;
|
|
579
|
+
for (const specifier of statement.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === exportName && specifier.local.type === "Identifier") return specifier.local.name;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Finds the `defineCollection(...)` call that initializes the named export. An initializer with more than one call,
|
|
584
|
+
* such as a conditional, has no known call: the scanner cannot know which branch runs.
|
|
585
|
+
*/
|
|
586
|
+
function findCollectionDefinitionCall(source, exportName, file) {
|
|
587
|
+
const module = scanModule(source, `${file}.ts`);
|
|
588
|
+
const calls = findCalls(module, ["defineCollection"]);
|
|
589
|
+
const factory = callsViteHubFactory(module);
|
|
590
|
+
const callIn = ({ init, constant }) => {
|
|
591
|
+
const matches = calls.filter((call) => call.start >= init.start && call.end <= init.end);
|
|
592
|
+
const [call] = matches;
|
|
593
|
+
return matches.length === 1 && call ? {
|
|
594
|
+
call,
|
|
595
|
+
exported: factory && constant && unwrapExpression(init) === call
|
|
596
|
+
} : void 0;
|
|
597
|
+
};
|
|
598
|
+
for (const initializer of declarationInitializers(module, exportName, true)) {
|
|
599
|
+
const call = callIn(initializer);
|
|
600
|
+
if (call) return call;
|
|
601
|
+
}
|
|
602
|
+
const localName = exportedLocalName(module, exportName);
|
|
603
|
+
if (localName === void 0) return;
|
|
604
|
+
for (const initializer of declarationInitializers(module, localName, false)) {
|
|
605
|
+
const call = callIn(initializer);
|
|
606
|
+
if (call) return call;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* True only for a literal `route: false` in the options of the exported `defineCollection()` call. A spread or a
|
|
611
|
+
* computed key after it can set `route` again when the module runs, so the route stays. Any other form keeps the route,
|
|
612
|
+
* and `defineCollectionHandler()` answers 404 at request time when the Collection has `route: false`.
|
|
613
|
+
*/
|
|
614
|
+
function collectionRouteDisabled(definition) {
|
|
615
|
+
if (!definition?.exported) return false;
|
|
616
|
+
const options = argumentExpression(definition.call.arguments[1] ?? definition.call.arguments[0]);
|
|
617
|
+
if (options?.type !== "ObjectExpression") return false;
|
|
618
|
+
const properties = objectProperties(options);
|
|
619
|
+
const index = properties.findLastIndex((property) => property.key === "route");
|
|
620
|
+
const route = properties[index]?.value;
|
|
621
|
+
return route !== void 0 && staticValue(route) === false && properties.slice(index + 1).every((property) => property.key !== void 0);
|
|
622
|
+
}
|
|
623
|
+
/** Whether the module exports `exportName`, and whether that Collection gets a generated route. */
|
|
624
|
+
function inspectCollectionSource(file, source, exportName) {
|
|
625
|
+
const exported = exportNames(source, `${file}.ts`).includes(exportName);
|
|
626
|
+
return {
|
|
627
|
+
exported,
|
|
628
|
+
routeEnabled: exported && !collectionRouteDisabled(findCollectionDefinitionCall(source, exportName, file))
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
async function collectCollectionFiles(directory) {
|
|
632
|
+
let entries;
|
|
633
|
+
try {
|
|
634
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
635
|
+
} catch (error) {
|
|
636
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return [];
|
|
637
|
+
throw error;
|
|
638
|
+
}
|
|
639
|
+
const files = [];
|
|
640
|
+
for (const entry of entries) {
|
|
641
|
+
const path = join(directory, entry.name);
|
|
642
|
+
if (entry.isDirectory()) files.push(...await collectCollectionFiles(path));
|
|
643
|
+
else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) files.push(path);
|
|
644
|
+
}
|
|
645
|
+
return files;
|
|
646
|
+
}
|
|
647
|
+
/** Lists Collection modules under `<serverDir>/collections`. It reads the files and does not import them. */
|
|
648
|
+
async function discoverCollections(options) {
|
|
649
|
+
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
650
|
+
const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
|
|
651
|
+
const directory = resolve(serverDir, "collections");
|
|
652
|
+
return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
|
|
653
|
+
const extension = extname(file);
|
|
654
|
+
const exportName = basename(file, extension);
|
|
655
|
+
if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw sourceErrorDiagnostics.SOURCE_B0003({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.` });
|
|
656
|
+
const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
|
|
657
|
+
const source = await readFile(file, "utf8");
|
|
658
|
+
if (!exportNames(source, `${file}.ts`).includes(exportName)) throw sourceErrorDiagnostics.SOURCE_B0004({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.` });
|
|
659
|
+
const definition = findCollectionDefinitionCall(source, exportName, file);
|
|
660
|
+
return {
|
|
661
|
+
definition: definition?.call,
|
|
662
|
+
exportName,
|
|
663
|
+
file,
|
|
664
|
+
name,
|
|
665
|
+
route: !collectionRouteDisabled(definition)
|
|
666
|
+
};
|
|
667
|
+
}));
|
|
668
|
+
}))).flat().sort((left, right) => left.name.localeCompare(right.name));
|
|
669
|
+
const generatedPaths = /* @__PURE__ */ new Map();
|
|
670
|
+
for (const collection of collections) {
|
|
671
|
+
const generatedPath = `${collection.name}.mjs`.toLowerCase();
|
|
672
|
+
const previous = generatedPaths.get(generatedPath);
|
|
673
|
+
if (previous?.name === collection.name) throw sourceErrorDiagnostics.SOURCE_B0005({ message: `[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.` });
|
|
674
|
+
if (previous) {
|
|
675
|
+
const [firstName, secondName] = [previous.name, collection.name].sort();
|
|
676
|
+
throw sourceErrorDiagnostics.SOURCE_B0006({ message: `[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.` });
|
|
677
|
+
}
|
|
678
|
+
generatedPaths.set(generatedPath, collection);
|
|
679
|
+
}
|
|
680
|
+
return collections;
|
|
681
|
+
}
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/inspect.ts
|
|
684
|
+
const dynamic = "Dynamic";
|
|
685
|
+
function objectLiteral(value) {
|
|
686
|
+
return value?.type === "ObjectExpression" ? value : void 0;
|
|
687
|
+
}
|
|
688
|
+
function readMember(object, name) {
|
|
689
|
+
const property = object && findProperty(object, name);
|
|
690
|
+
if (property?.node.type !== "Property" || property.value === void 0) return;
|
|
691
|
+
return {
|
|
692
|
+
method: property.node.method || property.node.kind !== "init",
|
|
693
|
+
value: property.value
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
/** An identifier path such as `schema` or `tables.articles`, as written without whitespace. */
|
|
697
|
+
function identifierPath(value, optional) {
|
|
698
|
+
if (value.type === "Identifier") return value.name;
|
|
699
|
+
if (value.type !== "MemberExpression" || value.computed || value.property.type !== "Identifier" || value.optional && !optional) return;
|
|
700
|
+
const object = identifierPath(value.object, optional);
|
|
701
|
+
return object === void 0 ? void 0 : `${object}${value.optional ? "?." : "."}${value.property.name}`;
|
|
702
|
+
}
|
|
703
|
+
function callArguments(values) {
|
|
704
|
+
return values.flatMap((value) => argumentExpression(value) ?? []);
|
|
705
|
+
}
|
|
706
|
+
function readCall(value) {
|
|
707
|
+
if (value.type !== "CallExpression" || value.optional) return;
|
|
708
|
+
const callee = identifierPath(value.callee, false);
|
|
709
|
+
return callee === void 0 ? void 0 : {
|
|
710
|
+
arguments: callArguments(value.arguments),
|
|
711
|
+
callee
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
function describeString(member) {
|
|
715
|
+
return staticString(member.value) ?? dynamic;
|
|
716
|
+
}
|
|
717
|
+
function describeInteger(member) {
|
|
718
|
+
const value = member.value;
|
|
719
|
+
return value.type === "Literal" && typeof value.value === "number" && /^\d+(?:_\d+)*$/.test(value.raw ?? "") ? String(value.value) : dynamic;
|
|
720
|
+
}
|
|
721
|
+
function describeStringList(member) {
|
|
722
|
+
if (member.value.type !== "ArrayExpression") return dynamic;
|
|
723
|
+
const values = member.value.elements.map((element) => element === null || element.type === "SpreadElement" ? void 0 : staticString(element));
|
|
724
|
+
if (values.some((value) => value === void 0)) return dynamic;
|
|
725
|
+
return values.length ? values.join(", ") : "None";
|
|
726
|
+
}
|
|
727
|
+
/** Shows an identifier path as written and a call as `callee(...)`. Other expressions show as `Inline`. */
|
|
728
|
+
function describeExpression(member) {
|
|
729
|
+
if (member.method) return "Inline";
|
|
730
|
+
const path = identifierPath(member.value, true);
|
|
731
|
+
if (path !== void 0) return path;
|
|
732
|
+
const call = readCall(member.value);
|
|
733
|
+
return call ? `${call.callee}(...)` : "Inline";
|
|
734
|
+
}
|
|
735
|
+
function isFunction(member) {
|
|
736
|
+
return member.method || member.value.type === "ArrowFunctionExpression" || member.value.type === "FunctionExpression";
|
|
737
|
+
}
|
|
738
|
+
function pushSchema(fields, label, member) {
|
|
739
|
+
if (!member) return;
|
|
740
|
+
fields.push({
|
|
741
|
+
label,
|
|
742
|
+
value: describeExpression(member)
|
|
743
|
+
});
|
|
744
|
+
const call = member.method ? void 0 : readCall(member.value);
|
|
745
|
+
const shape = call && /(?:^|\.)(?:object|strictObject|looseObject)$/.test(call.callee) ? objectLiteral(call.arguments[0]) : void 0;
|
|
746
|
+
if (!shape) return;
|
|
747
|
+
const names = objectProperties(shape).map((property) => property.key);
|
|
748
|
+
fields.push({
|
|
749
|
+
label: `${label} fields`,
|
|
750
|
+
value: names.every((name) => name !== void 0) ? names.join(", ") || "None" : dynamic
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
function pushLimits(fields, options) {
|
|
754
|
+
const defaultLimit = readMember(options, "defaultLimit");
|
|
755
|
+
const maxLimit = readMember(options, "maxLimit");
|
|
756
|
+
if (defaultLimit) fields.push({
|
|
757
|
+
label: "Default limit",
|
|
758
|
+
value: describeInteger(defaultLimit)
|
|
759
|
+
});
|
|
760
|
+
if (maxLimit) fields.push({
|
|
761
|
+
label: "Max limit",
|
|
762
|
+
value: describeInteger(maxLimit)
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
function describeArraySort(member) {
|
|
766
|
+
const sort = objectLiteral(member.value);
|
|
767
|
+
const field = readMember(sort, "field");
|
|
768
|
+
const direction = readMember(sort, "direction");
|
|
769
|
+
const fieldName = field && staticString(field.value);
|
|
770
|
+
const directionName = direction ? staticString(direction.value) : "asc";
|
|
771
|
+
return fieldName && directionName ? `${fieldName} ${directionName}` : dynamic;
|
|
772
|
+
}
|
|
773
|
+
function describeTableSort(member) {
|
|
774
|
+
const orderBy = objectLiteral(member.value);
|
|
775
|
+
const column = readMember(orderBy, "column");
|
|
776
|
+
const direction = readMember(orderBy, "direction");
|
|
777
|
+
const tieBreaker = readMember(orderBy, "tieBreaker");
|
|
778
|
+
const directionName = direction && staticString(direction.value);
|
|
779
|
+
if (!column || !directionName) return dynamic;
|
|
780
|
+
const sort = `${describeExpression(column)} ${directionName}`;
|
|
781
|
+
return tieBreaker ? `${sort}, then ${describeExpression(tieBreaker)}` : sort;
|
|
782
|
+
}
|
|
783
|
+
function arrayFields(options) {
|
|
784
|
+
const fields = [];
|
|
785
|
+
pushSchema(fields, "Schema", readMember(options, "schema"));
|
|
786
|
+
const key = readMember(options, "key");
|
|
787
|
+
const sort = readMember(options, "sort");
|
|
788
|
+
if (key) fields.push({
|
|
789
|
+
label: "Key",
|
|
790
|
+
value: describeString(key)
|
|
791
|
+
});
|
|
792
|
+
if (sort) fields.push({
|
|
793
|
+
label: "Sort",
|
|
794
|
+
value: describeArraySort(sort)
|
|
795
|
+
});
|
|
796
|
+
for (const [property, label] of [
|
|
797
|
+
["filters", "Filters"],
|
|
798
|
+
["search", "Search"],
|
|
799
|
+
["facets", "Facets"]
|
|
800
|
+
]) {
|
|
801
|
+
const member = readMember(options, property);
|
|
802
|
+
if (member) fields.push({
|
|
803
|
+
label,
|
|
804
|
+
value: describeStringList(member)
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
pushLimits(fields, options);
|
|
808
|
+
return fields;
|
|
809
|
+
}
|
|
810
|
+
function tableFields(options) {
|
|
811
|
+
const fields = [];
|
|
812
|
+
const table = readMember(options, "table");
|
|
813
|
+
const orderBy = readMember(options, "orderBy");
|
|
814
|
+
const where = readMember(options, "where");
|
|
815
|
+
if (table) fields.push({
|
|
816
|
+
label: "Table",
|
|
817
|
+
value: describeExpression(table)
|
|
818
|
+
});
|
|
819
|
+
if (orderBy) fields.push({
|
|
820
|
+
label: "Sort",
|
|
821
|
+
value: describeTableSort(orderBy)
|
|
822
|
+
});
|
|
823
|
+
pushSchema(fields, "Query schema", readMember(options, "querySchema"));
|
|
824
|
+
if (where) fields.push({
|
|
825
|
+
label: "Where",
|
|
826
|
+
value: isFunction(where) ? "Callback" : dynamic
|
|
827
|
+
});
|
|
828
|
+
pushLimits(fields, options);
|
|
829
|
+
return fields;
|
|
830
|
+
}
|
|
831
|
+
/** Fields of a custom source object and of the options in `defineCollection(load, options)`. */
|
|
832
|
+
function loaderFields(options) {
|
|
833
|
+
const pagination = readMember(options, "pagination");
|
|
834
|
+
const fields = [{
|
|
835
|
+
label: "Pagination",
|
|
836
|
+
value: !pagination ? "Cursor" : staticString(pagination.value) === "provider" ? "Provider" : dynamic
|
|
837
|
+
}];
|
|
838
|
+
pushSchema(fields, "Cursor schema", readMember(options, "cursorSchema"));
|
|
839
|
+
pushSchema(fields, "Query schema", readMember(options, "querySchema"));
|
|
840
|
+
pushLimits(fields, options);
|
|
841
|
+
return fields;
|
|
842
|
+
}
|
|
843
|
+
function sourceFields(member) {
|
|
844
|
+
if (!member || member.method) return [{
|
|
845
|
+
label: "Source",
|
|
846
|
+
value: "unknown"
|
|
847
|
+
}];
|
|
848
|
+
const custom = objectLiteral(member.value);
|
|
849
|
+
if (custom) return [{
|
|
850
|
+
label: "Source",
|
|
851
|
+
value: "custom"
|
|
852
|
+
}, ...loaderFields(custom)];
|
|
853
|
+
const call = readCall(member.value);
|
|
854
|
+
if (!call) return [{
|
|
855
|
+
label: "Source",
|
|
856
|
+
value: "unknown"
|
|
857
|
+
}];
|
|
858
|
+
const fields = [{
|
|
859
|
+
label: "Source",
|
|
860
|
+
value: call.callee
|
|
861
|
+
}];
|
|
862
|
+
const helper = call.callee.split(".").at(-1);
|
|
863
|
+
const optionsValue = helper === "array" ? call.arguments[1] : helper === "table" ? call.arguments[0] : void 0;
|
|
864
|
+
if (optionsValue === void 0) return fields;
|
|
865
|
+
const options = objectLiteral(optionsValue);
|
|
866
|
+
if (!options) return [...fields, {
|
|
867
|
+
label: "Options",
|
|
868
|
+
value: dynamic
|
|
869
|
+
}];
|
|
870
|
+
return [...fields, ...helper === "array" ? arrayFields(options) : tableFields(options)];
|
|
871
|
+
}
|
|
872
|
+
function definitionFields(collection) {
|
|
873
|
+
const call = collection.definition;
|
|
874
|
+
if (!call) return [{
|
|
875
|
+
label: "Source",
|
|
876
|
+
value: "unknown"
|
|
877
|
+
}];
|
|
878
|
+
const [first, second] = callArguments(call.arguments);
|
|
879
|
+
const loaderForm = second !== void 0;
|
|
880
|
+
const options = objectLiteral(loaderForm ? second : first);
|
|
881
|
+
const fields = loaderForm ? [{
|
|
882
|
+
label: "Source",
|
|
883
|
+
value: "loader"
|
|
884
|
+
}, ...options ? loaderFields(options) : []] : sourceFields(readMember(options, "source"));
|
|
885
|
+
if (!options) return [...fields, {
|
|
886
|
+
label: "Options",
|
|
887
|
+
value: dynamic
|
|
888
|
+
}];
|
|
889
|
+
const authorize = readMember(options, "authorize");
|
|
890
|
+
const access = readMember(options, "access");
|
|
891
|
+
fields.push({
|
|
892
|
+
label: "Transform",
|
|
893
|
+
value: readMember(options, "transform") ? "Yes" : "No"
|
|
894
|
+
});
|
|
895
|
+
if (authorize) fields.push({
|
|
896
|
+
label: "Authorize",
|
|
897
|
+
value: !authorize.method && staticValue(authorize.value) === true ? "Signed-in session" : isFunction(authorize) ? "Callback" : dynamic
|
|
898
|
+
});
|
|
899
|
+
if (access) fields.push({
|
|
900
|
+
label: "Access",
|
|
901
|
+
value: staticValue(access.value) === "public" ? "Public" : dynamic
|
|
902
|
+
});
|
|
903
|
+
return fields;
|
|
904
|
+
}
|
|
905
|
+
function summarizeCollection(projectRoot, collection) {
|
|
906
|
+
return {
|
|
907
|
+
fields: [...definitionFields(collection), {
|
|
908
|
+
label: "Route",
|
|
909
|
+
value: collection.route ? `GET ${collectionRoutePath(collection.name)}` : "Disabled"
|
|
910
|
+
}],
|
|
911
|
+
file: relativeDefinitionFile(projectRoot, collection.file),
|
|
912
|
+
name: collection.name,
|
|
913
|
+
source: "server-collections"
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Lists Collections in `server/collections` with their source kind and static options. It reads the module text and
|
|
918
|
+
* does not import it, so values that are computed at runtime show as `Dynamic`.
|
|
919
|
+
*/
|
|
920
|
+
async function inspectCollectionDefinitions(options) {
|
|
921
|
+
return (await discoverCollections(options)).map((collection) => summarizeCollection(options.projectRoot, collection));
|
|
922
|
+
}
|
|
923
|
+
//#endregion
|
|
924
|
+
//#region src/internal/bundle-glob.ts
|
|
925
|
+
/**
|
|
926
|
+
* Bundling glob(): a ViteHub server build swaps each `glob()` call whose options are literals for a module that holds
|
|
927
|
+
* the files it matches, through files(). Hosts without a file system, such as Cloudflare Workers, then serve the same
|
|
928
|
+
* keys and bytes that glob() reads from disk. `vite dev` keeps glob() as it is.
|
|
929
|
+
*/
|
|
930
|
+
/** Prefix of the generated modules' ids. `\0` keeps other plugins from resolving or transforming them. */
|
|
931
|
+
const BUNDLED_GLOB_ID = "\0vitehub-source-glob:";
|
|
932
|
+
/** Matches those ids, for Rolldown's hook filters. */
|
|
933
|
+
const BUNDLED_GLOB_ID_PATTERN = /^\0vitehub-source-glob:/;
|
|
934
|
+
const GLOB_MODULE = /^(?:@vite-hub|vite-hub)\/source$/;
|
|
935
|
+
const OPTION_KEYS = /* @__PURE__ */ new Set([
|
|
936
|
+
"cwd",
|
|
937
|
+
"dot",
|
|
938
|
+
"followSymlinks",
|
|
939
|
+
"ignore",
|
|
940
|
+
"include",
|
|
941
|
+
"keyCache",
|
|
942
|
+
"prefix"
|
|
943
|
+
]);
|
|
944
|
+
function isNode(value) {
|
|
945
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
946
|
+
}
|
|
947
|
+
function walk(node, visit) {
|
|
948
|
+
visit(node);
|
|
949
|
+
for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach((child) => isNode(child) && walk(child, visit));
|
|
950
|
+
else if (isNode(value)) walk(value, visit);
|
|
951
|
+
}
|
|
952
|
+
/** A literal's value, or undefined for anything that is not one. */
|
|
953
|
+
function literal(node) {
|
|
954
|
+
if (!node) return void 0;
|
|
955
|
+
if (node.type === "Literal") return node.value;
|
|
956
|
+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
|
|
957
|
+
if (node.type === "ArrayExpression") {
|
|
958
|
+
const items = node.elements.map((element) => element ? literal(element) : void 0);
|
|
959
|
+
return items.every((item) => typeof item === "string") ? items : void 0;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function globInput(node) {
|
|
963
|
+
const value = literal(node);
|
|
964
|
+
if (typeof value === "string") return value;
|
|
965
|
+
if (node?.type !== "ObjectExpression") return void 0;
|
|
966
|
+
const options = {};
|
|
967
|
+
for (const property of node.properties) {
|
|
968
|
+
if (property.type !== "Property" || property.computed || property.kind !== "init") return void 0;
|
|
969
|
+
const key = property.key;
|
|
970
|
+
const name = key.type === "Identifier" ? key.name : key.value;
|
|
971
|
+
if (typeof name !== "string" || !OPTION_KEYS.has(name)) return void 0;
|
|
972
|
+
const option = literal(property.value);
|
|
973
|
+
if (option === void 0) return void 0;
|
|
974
|
+
options[name] = option;
|
|
975
|
+
}
|
|
976
|
+
return typeof options.include === "string" || Array.isArray(options.include) ? options : void 0;
|
|
977
|
+
}
|
|
978
|
+
/** Every `glob()` call in a module, by the names `glob` was imported under. */
|
|
979
|
+
function findGlobCalls(program) {
|
|
980
|
+
const imported = /* @__PURE__ */ new Map();
|
|
981
|
+
for (const statement of program.body) {
|
|
982
|
+
if (statement.type !== "ImportDeclaration") continue;
|
|
983
|
+
const source = statement.source.value;
|
|
984
|
+
if (typeof source !== "string" || !GLOB_MODULE.test(source)) continue;
|
|
985
|
+
for (const specifier of statement.specifiers) {
|
|
986
|
+
const name = specifier.imported?.name ?? specifier.imported?.value;
|
|
987
|
+
if (specifier.type === "ImportSpecifier" && name === "glob") imported.set(specifier.local.name, source);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
if (imported.size === 0) return [];
|
|
991
|
+
const calls = [];
|
|
992
|
+
walk(program, (node) => {
|
|
993
|
+
if (node.type !== "CallExpression") return;
|
|
994
|
+
const callee = node.callee;
|
|
995
|
+
const filesModule = callee.type === "Identifier" ? imported.get(callee.name) : void 0;
|
|
996
|
+
if (!filesModule) return;
|
|
997
|
+
const args = node.arguments;
|
|
998
|
+
calls.push({
|
|
999
|
+
start: node.start,
|
|
1000
|
+
end: node.end,
|
|
1001
|
+
input: args.length === 1 ? globInput(args[0]) : void 0,
|
|
1002
|
+
filesModule
|
|
1003
|
+
});
|
|
1004
|
+
});
|
|
1005
|
+
return calls;
|
|
1006
|
+
}
|
|
1007
|
+
/** The id of the module that holds what one call matches. */
|
|
1008
|
+
function bundledGlobId(call) {
|
|
1009
|
+
return BUNDLED_GLOB_ID + encodeURIComponent(JSON.stringify({
|
|
1010
|
+
filesModule: call.filesModule,
|
|
1011
|
+
input: call.input
|
|
1012
|
+
}));
|
|
1013
|
+
}
|
|
1014
|
+
/** The module with each call whose options are literals swapped for its bundled files. */
|
|
1015
|
+
function rewriteGlobCalls(code, calls) {
|
|
1016
|
+
let output = code;
|
|
1017
|
+
const imports = [];
|
|
1018
|
+
const bundled = calls.filter((call) => call.input !== void 0);
|
|
1019
|
+
bundled.forEach((call, index) => imports.push(`import __vitehubGlob${index} from ${JSON.stringify(bundledGlobId(call))};`));
|
|
1020
|
+
for (const [index, call] of [...bundled.entries()].reverse()) output = output.slice(0, call.start) + `__vitehubGlob${index}` + output.slice(call.end);
|
|
1021
|
+
return imports.length ? `${imports.join("\n")}\n${output}` : output;
|
|
1022
|
+
}
|
|
1023
|
+
/** The files a call matches, read as glob() reads them, and the paths to watch. */
|
|
1024
|
+
async function collectBundledGlob(input, rootDir) {
|
|
1025
|
+
const options = resolveGlobInput(input);
|
|
1026
|
+
const { paths, keys } = await collectGlobFiles(rootDir, options);
|
|
1027
|
+
const entries = {};
|
|
1028
|
+
const watched = [];
|
|
1029
|
+
for (const key of keys) {
|
|
1030
|
+
const path = await globFilePath(key, paths, options.followSymlinks === true);
|
|
1031
|
+
if (!path) continue;
|
|
1032
|
+
entries[key] = new Uint8Array(await readFile(path));
|
|
1033
|
+
watched.push(path);
|
|
1034
|
+
}
|
|
1035
|
+
return {
|
|
1036
|
+
entries,
|
|
1037
|
+
prefix: options.prefix,
|
|
1038
|
+
watched
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* The generated module: the matched files, served through files(). Their bytes are one gzip blob in base64, and each
|
|
1043
|
+
* key reads its range of the blob, which the server inflates on the first read. A host compiles a short string
|
|
1044
|
+
* instead of every file as JavaScript when the server starts. Cloudflare Workers compile every module of the bundle
|
|
1045
|
+
* when an isolate starts (https://github.com/cloudflare/workerd/issues/8442).
|
|
1046
|
+
*/
|
|
1047
|
+
function renderBundledGlob(filesModule, entries, prefix) {
|
|
1048
|
+
const lines = [];
|
|
1049
|
+
let offset = 0;
|
|
1050
|
+
for (const [key, bytes] of Object.entries(entries)) {
|
|
1051
|
+
lines.push(` ${JSON.stringify(key)}: file(${offset}, ${offset + bytes.length}),`);
|
|
1052
|
+
offset += bytes.length;
|
|
1053
|
+
}
|
|
1054
|
+
const packed = gzipSync(Buffer.concat(Object.values(entries)), { level: 9 }).toString("base64");
|
|
1055
|
+
return [
|
|
1056
|
+
`import { files } from ${JSON.stringify(filesModule)}`,
|
|
1057
|
+
`let unpacked`,
|
|
1058
|
+
`async function unpack(base64) {`,
|
|
1059
|
+
` const zlib = globalThis.process?.getBuiltinModule?.("node:zlib")`,
|
|
1060
|
+
` const buffer = globalThis.process?.getBuiltinModule?.("node:buffer")`,
|
|
1061
|
+
` if (zlib && buffer) {`,
|
|
1062
|
+
` const bytes = zlib.gunzipSync(buffer.Buffer.from(base64, "base64"))`,
|
|
1063
|
+
` return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)`,
|
|
1064
|
+
` }`,
|
|
1065
|
+
` const binary = atob(base64)`,
|
|
1066
|
+
` const gzip = new Uint8Array(binary.length)`,
|
|
1067
|
+
` for (let index = 0; index < binary.length; index++) gzip[index] = binary.charCodeAt(index)`,
|
|
1068
|
+
` return new Uint8Array(await new Response(new Response(gzip).body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer())`,
|
|
1069
|
+
`}`,
|
|
1070
|
+
`const file = (start, end) => async () => (await (unpacked ??= unpack(${JSON.stringify(packed)}))).slice(start, end)`,
|
|
1071
|
+
`export default files({`,
|
|
1072
|
+
...lines,
|
|
1073
|
+
`}${prefix ? `, { prefix: ${JSON.stringify(prefix)} }` : ""})`,
|
|
1074
|
+
``
|
|
1075
|
+
].join("\n");
|
|
1076
|
+
}
|
|
1077
|
+
/** Loads a generated module by its id. */
|
|
1078
|
+
async function loadBundledGlob(id, rootDir) {
|
|
1079
|
+
const { filesModule, input } = JSON.parse(decodeURIComponent(id.slice(21)));
|
|
1080
|
+
const { entries, prefix, watched } = await collectBundledGlob(input, rootDir);
|
|
1081
|
+
return {
|
|
1082
|
+
code: renderBundledGlob(filesModule, entries, prefix),
|
|
1083
|
+
watched
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
//#endregion
|
|
56
1087
|
//#region src/vite.ts
|
|
57
1088
|
const collectionTypesEntry = ".vitehub/types/source/collections.d.ts";
|
|
58
|
-
const
|
|
59
|
-
const legacyCollectionTypesEntry = ".vitehub/source/collections.d.ts";
|
|
1089
|
+
const retiredCollectionTypesWrapper = ".vitehub/types/source/vitehub-source-registry.d.ts";
|
|
60
1090
|
const collectionRoutesDirectory = ".vitehub/source/routes";
|
|
61
1091
|
const contentRouteEntry = ".vitehub/content/route.mjs";
|
|
1092
|
+
const contentPreviewEntry = ".vitehub/content/preview.mjs";
|
|
1093
|
+
const contentSitemapEntry = ".vitehub/content/sitemap.mjs";
|
|
1094
|
+
const contentRobotsEntry = ".vitehub/content/robots.mjs";
|
|
1095
|
+
const contentMarkdownEntry = ".vitehub/content/markdown.mjs";
|
|
1096
|
+
const contentRssEntry = ".vitehub/content/rss.mjs";
|
|
1097
|
+
const contentMcpEntry = ".vitehub/content/mcp.mjs";
|
|
1098
|
+
const contentLlmsEntry = ".vitehub/content/llms.mjs";
|
|
1099
|
+
const contentSqliteEntry = ".vitehub/content/sqlite.mjs";
|
|
1100
|
+
const contentGitHubWebhookEntry = ".vitehub/content/github-webhook.mjs";
|
|
1101
|
+
const contentPreviewRoutesEntry = ".vitehub/content/preview-routes.mjs";
|
|
1102
|
+
const contentTypesPluginEntry = ".vitehub/content/types.mjs";
|
|
1103
|
+
const contentTypesEntry = ".vitehub/types/content.d.ts";
|
|
1104
|
+
const authServerModuleId = "#vitehub/auth/server";
|
|
62
1105
|
const initialHostRefreshRetryDelay = 25;
|
|
63
1106
|
const maximumHostRefreshRetryDelay = 1e3;
|
|
64
1107
|
const hostRestartOwnerSettlementTimeout = 3e4;
|
|
@@ -73,9 +1116,16 @@ async function snapshotGeneratedSourceArtifacts(projectRoot) {
|
|
|
73
1116
|
const files = /* @__PURE__ */ new Map();
|
|
74
1117
|
const fixedEntries = [
|
|
75
1118
|
collectionTypesEntry,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
1119
|
+
contentRouteEntry,
|
|
1120
|
+
contentPreviewEntry,
|
|
1121
|
+
contentSitemapEntry,
|
|
1122
|
+
contentRobotsEntry,
|
|
1123
|
+
contentMarkdownEntry,
|
|
1124
|
+
contentRssEntry,
|
|
1125
|
+
contentLlmsEntry,
|
|
1126
|
+
contentSqliteEntry,
|
|
1127
|
+
contentTypesPluginEntry,
|
|
1128
|
+
contentTypesEntry
|
|
79
1129
|
];
|
|
80
1130
|
for (const entry of fixedEntries) {
|
|
81
1131
|
const path = resolve(projectRoot, entry);
|
|
@@ -94,15 +1144,23 @@ async function snapshotGeneratedSourceArtifacts(projectRoot) {
|
|
|
94
1144
|
return { files };
|
|
95
1145
|
}
|
|
96
1146
|
async function restoreGeneratedSourceArtifacts(projectRoot, snapshot) {
|
|
97
|
-
|
|
1147
|
+
const routesDirectory = resolve(projectRoot, collectionRoutesDirectory);
|
|
1148
|
+
await rm(routesDirectory, {
|
|
98
1149
|
force: true,
|
|
99
1150
|
recursive: true
|
|
100
1151
|
});
|
|
101
1152
|
for (const entry of [
|
|
102
1153
|
collectionTypesEntry,
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
1154
|
+
contentRouteEntry,
|
|
1155
|
+
contentPreviewEntry,
|
|
1156
|
+
contentSitemapEntry,
|
|
1157
|
+
contentRobotsEntry,
|
|
1158
|
+
contentMarkdownEntry,
|
|
1159
|
+
contentRssEntry,
|
|
1160
|
+
contentLlmsEntry,
|
|
1161
|
+
contentSqliteEntry,
|
|
1162
|
+
contentTypesPluginEntry,
|
|
1163
|
+
contentTypesEntry
|
|
106
1164
|
]) {
|
|
107
1165
|
const path = resolve(projectRoot, entry);
|
|
108
1166
|
if (!snapshot.files.has(path)) await rm(path, { force: true });
|
|
@@ -116,18 +1174,24 @@ function methodsOverlap(left, right) {
|
|
|
116
1174
|
return !left || !right || left.toLowerCase() === right.toLowerCase();
|
|
117
1175
|
}
|
|
118
1176
|
function generatedRouteOwner(handler) {
|
|
119
|
-
return handler.route === "/api/content/**" ? "Content" : "Collection";
|
|
1177
|
+
return handler.middleware || handler.route === "/api/content/**" || handler.route === "/_vitehub/content/github" || handler.route === "/sitemap.xml" || handler.route === "/robots.txt" || handler.route === "/rss.xml" || handler.route === "/mcp" ? "Content" : "Collection";
|
|
120
1178
|
}
|
|
121
1179
|
function generatedRouteDescription(handler) {
|
|
122
1180
|
return handler.method ? `${handler.method.toUpperCase()} handler` : "handler";
|
|
123
1181
|
}
|
|
1182
|
+
function assertGeneratedRoutes(nitro, generatedHandlers) {
|
|
1183
|
+
for (const generatedHandler of generatedHandlers) {
|
|
1184
|
+
if (generatedHandler.plugin || generatedHandler.middleware) continue;
|
|
1185
|
+
if (nitro.scannedHandlers.some((candidate) => !candidate.middleware && candidate.route === generatedHandler.route && methodsOverlap(candidate.method, generatedHandler.method))) throw sourceErrorDiagnostics.SOURCE_B0001({ message: `[vitehub] Generated ${generatedRouteOwner(generatedHandler)} route ${JSON.stringify(generatedHandler.route)} conflicts with an existing ${generatedRouteDescription(generatedHandler)}. Remove the matching server route.` });
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
124
1188
|
function generatedRouteGuard(generatedHandlers) {
|
|
125
1189
|
return {
|
|
126
1190
|
name: "vite-hub/generated-route-guard",
|
|
127
|
-
setup(nitro) {
|
|
128
|
-
nitro.hooks.hook("build:before", () =>
|
|
129
|
-
|
|
130
|
-
|
|
1191
|
+
async setup(nitro) {
|
|
1192
|
+
nitro.hooks.hook("build:before", () => assertGeneratedRoutes(nitro, generatedHandlers));
|
|
1193
|
+
const typesPlugin = generatedHandlers.find((handler) => handler.plugin && handler.handler.replaceAll("\\", "/").endsWith(`/${contentTypesPluginEntry}`));
|
|
1194
|
+
if (typesPlugin) await installContentTypesWriter(nitro, typesPlugin.handler);
|
|
131
1195
|
}
|
|
132
1196
|
};
|
|
133
1197
|
}
|
|
@@ -135,19 +1199,32 @@ function mergeGeneratedSourceNitroConfig(value, generatedHandlers) {
|
|
|
135
1199
|
const nitro = {};
|
|
136
1200
|
if (Object(value) === value && !Array.isArray(value)) Object.assign(nitro, value);
|
|
137
1201
|
if (generatedHandlers.length === 0) return nitro;
|
|
138
|
-
const
|
|
1202
|
+
const kit = createNitroServerKit(nitro);
|
|
1203
|
+
const handlers = kit.config.handlers;
|
|
139
1204
|
for (const handler of generatedHandlers) {
|
|
1205
|
+
if (handler.plugin) {
|
|
1206
|
+
kit.addPlugin(handler.handler, handler.position);
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
140
1209
|
if (handlers.some((candidate) => candidate.handler === handler.handler && candidate.route === handler.route && candidate.method?.toLowerCase() === handler.method?.toLowerCase())) continue;
|
|
141
|
-
|
|
142
|
-
|
|
1210
|
+
const duplicate = handler.middleware ? void 0 : handlers.find((candidate) => !candidate.middleware && candidate.route === handler.route && methodsOverlap(candidate.method, handler.method));
|
|
1211
|
+
if (duplicate && handler.route === "/mcp") {
|
|
1212
|
+
const other = duplicate.handler.replaceAll("\\", "/").includes("/.vitehub/nitro/mcp/") ? "the app MCP server of vitehub({ mcp })" : `the handler ${duplicate.handler}`;
|
|
1213
|
+
throw sourceErrorDiagnostics.SOURCE_B0010({
|
|
1214
|
+
route: handler.route,
|
|
1215
|
+
other
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
if (duplicate) throw sourceErrorDiagnostics.SOURCE_B0002({ message: `[vitehub] Generated ${generatedRouteOwner(handler)} route ${JSON.stringify(handler.route)} conflicts with an existing ${generatedRouteDescription(handler)}. Remove the matching server route.` });
|
|
1219
|
+
kit.addHandler({
|
|
1220
|
+
...handler,
|
|
1221
|
+
lazy: handler.lazy ?? true
|
|
1222
|
+
});
|
|
143
1223
|
}
|
|
144
1224
|
const modules = Array.isArray(nitro.modules) ? [...nitro.modules] : [];
|
|
145
1225
|
if (!modules.some((module) => Object(module) === module && Reflect.get(Object(module), "name") === "vite-hub/generated-route-guard")) modules.push(generatedRouteGuard(generatedHandlers));
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
handlers,
|
|
149
|
-
modules
|
|
150
|
-
};
|
|
1226
|
+
kit.config.modules = modules;
|
|
1227
|
+
return kit.config;
|
|
151
1228
|
}
|
|
152
1229
|
function toRuntimeModuleSpecifier(file) {
|
|
153
1230
|
return pathToFileURL(file, { windows: /^[A-Z]:[\\/]/i.test(file) }).href;
|
|
@@ -155,51 +1232,9 @@ function toRuntimeModuleSpecifier(file) {
|
|
|
155
1232
|
function toTypeModuleSpecifier(file) {
|
|
156
1233
|
return file.replaceAll("\\", "/");
|
|
157
1234
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
entries = await readdir(directory, { withFileTypes: true });
|
|
162
|
-
} catch (error) {
|
|
163
|
-
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return [];
|
|
164
|
-
throw error;
|
|
165
|
-
}
|
|
166
|
-
const files = [];
|
|
167
|
-
for (const entry of entries) {
|
|
168
|
-
const path = join(directory, entry.name);
|
|
169
|
-
if (entry.isDirectory()) files.push(...await collectCollectionFiles(path));
|
|
170
|
-
else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) files.push(path);
|
|
171
|
-
}
|
|
172
|
-
return files;
|
|
173
|
-
}
|
|
174
|
-
async function discoverCollections(options) {
|
|
175
|
-
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
176
|
-
const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
|
|
177
|
-
const directory = resolve(serverDir, "collections");
|
|
178
|
-
return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
|
|
179
|
-
const extension = extname(file);
|
|
180
|
-
const exportName = basename(file, extension);
|
|
181
|
-
if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.`);
|
|
182
|
-
const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
|
|
183
|
-
if (!findExportNames(await readFile(file, "utf8")).includes(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.`);
|
|
184
|
-
return {
|
|
185
|
-
exportName,
|
|
186
|
-
file,
|
|
187
|
-
name
|
|
188
|
-
};
|
|
189
|
-
}));
|
|
190
|
-
}))).flat().sort((left, right) => left.name.localeCompare(right.name));
|
|
191
|
-
const generatedPaths = /* @__PURE__ */ new Map();
|
|
192
|
-
for (const collection of collections) {
|
|
193
|
-
const generatedPath = `${collection.name}.mjs`.toLowerCase();
|
|
194
|
-
const previous = generatedPaths.get(generatedPath);
|
|
195
|
-
if (previous?.name === collection.name) throw new TypeError(`[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.`);
|
|
196
|
-
if (previous) {
|
|
197
|
-
const [firstName, secondName] = [previous.name, collection.name].sort();
|
|
198
|
-
throw new TypeError(`[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.`);
|
|
199
|
-
}
|
|
200
|
-
generatedPaths.set(generatedPath, collection);
|
|
201
|
-
}
|
|
202
|
-
return collections;
|
|
1235
|
+
/** Inspects the named Collection export without running application code. The docs snippet check calls it. */
|
|
1236
|
+
function inspectCollectionModule(file, source, exportName) {
|
|
1237
|
+
return inspectCollectionSource(file, source, exportName);
|
|
203
1238
|
}
|
|
204
1239
|
async function writeFileIfChanged(path, contents) {
|
|
205
1240
|
let current;
|
|
@@ -214,51 +1249,51 @@ async function writeFileIfChanged(path, contents) {
|
|
|
214
1249
|
}
|
|
215
1250
|
async function writeCollectionArtifacts(options, collections) {
|
|
216
1251
|
const output = resolve(options.projectRoot, collectionTypesEntry);
|
|
217
|
-
const packageOutput = resolve(options.projectRoot, collectionTypesPackageEntry);
|
|
218
|
-
await rm(resolve(options.projectRoot, legacyCollectionTypesEntry), { force: true });
|
|
219
1252
|
const routesDirectory = resolve(options.projectRoot, collectionRoutesDirectory);
|
|
1253
|
+
await rm(resolve(options.projectRoot, retiredCollectionTypesWrapper), { force: true });
|
|
220
1254
|
if (collections.length === 0) {
|
|
221
|
-
await Promise.all([
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
force: true,
|
|
226
|
-
recursive: true
|
|
227
|
-
})
|
|
228
|
-
]);
|
|
1255
|
+
await Promise.all([rm(output, { force: true }), rm(routesDirectory, {
|
|
1256
|
+
force: true,
|
|
1257
|
+
recursive: true
|
|
1258
|
+
})]);
|
|
229
1259
|
return [];
|
|
230
1260
|
}
|
|
1261
|
+
const routedCollections = collections.filter((collection) => collection.route);
|
|
231
1262
|
await writeFileIfChanged(output, [
|
|
232
1263
|
"declare global {",
|
|
233
1264
|
" interface ViteHubCollectionMap {",
|
|
234
|
-
...
|
|
1265
|
+
...routedCollections.map(({ exportName, file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})[${JSON.stringify(exportName)}]`),
|
|
235
1266
|
" }",
|
|
236
1267
|
"}",
|
|
237
1268
|
"",
|
|
238
1269
|
"export {}",
|
|
239
1270
|
""
|
|
240
1271
|
].join("\n"));
|
|
241
|
-
|
|
242
|
-
const expectedRoutes = new Set(collections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
|
|
1272
|
+
const expectedRoutes = new Set(routedCollections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
|
|
243
1273
|
const existingRoutes = await collectCollectionFiles(routesDirectory);
|
|
244
1274
|
await Promise.all(existingRoutes.filter((file) => !expectedRoutes.has(file)).map((file) => rm(file, { force: true })));
|
|
245
|
-
return await Promise.all(
|
|
1275
|
+
return await Promise.all(routedCollections.map(async ({ exportName, file, name }) => {
|
|
246
1276
|
const handler = resolve(routesDirectory, `${name}.mjs`);
|
|
247
1277
|
await writeFileIfChanged(handler, [
|
|
248
1278
|
`import { defineCollectionHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/server`)}`,
|
|
1279
|
+
...options.auth ? [`import { withAuthorization } from ${JSON.stringify(authServerModuleId)}`] : [],
|
|
249
1280
|
`import { ${exportName} as collection } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
|
|
250
1281
|
"",
|
|
251
|
-
"export default defineCollectionHandler(collection)",
|
|
1282
|
+
options.auth ? "export default defineCollectionHandler(collection, { withAuthorization })" : "export default defineCollectionHandler(collection)",
|
|
252
1283
|
""
|
|
253
1284
|
].join("\n"));
|
|
254
1285
|
return {
|
|
255
1286
|
handler,
|
|
256
1287
|
method: "get",
|
|
257
|
-
route:
|
|
1288
|
+
route: collectionRoutePath(name)
|
|
258
1289
|
};
|
|
259
1290
|
}));
|
|
260
1291
|
}
|
|
261
|
-
|
|
1292
|
+
/**
|
|
1293
|
+
* Find the `server/content.{ts,js}` file whose default export is the application Content runtime. Returns undefined when
|
|
1294
|
+
* the project has none. The generated `/api/content/**` route and the Console content editor import the same file.
|
|
1295
|
+
*/
|
|
1296
|
+
async function findContentEntry(options) {
|
|
262
1297
|
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
263
1298
|
const candidates = [];
|
|
264
1299
|
for (const serverDir of serverDirs) {
|
|
@@ -272,35 +1307,446 @@ async function discoverContent(options) {
|
|
|
272
1307
|
candidates.push(...entries.filter((entry) => entry.isFile() && /^content\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)).map((entry) => join(serverDir, entry.name)));
|
|
273
1308
|
}
|
|
274
1309
|
candidates.sort();
|
|
275
|
-
if (candidates.length > 1) throw
|
|
1310
|
+
if (candidates.length > 1) throw sourceErrorDiagnostics.SOURCE_B0007({ message: "[vitehub] Content is defined in more than one server directory." });
|
|
276
1311
|
const file = candidates[0];
|
|
277
1312
|
if (!file) return;
|
|
278
|
-
|
|
1313
|
+
const exports = exportNames(await readFile(file, "utf8"), file);
|
|
1314
|
+
if (!exports.includes("default")) {
|
|
1315
|
+
const name = JSON.stringify(relative(options.projectRoot, file));
|
|
1316
|
+
if (exports.includes("content")) throw sourceErrorDiagnostics.SOURCE_B0009({ message: `[vitehub] Content file ${name} exports \`content\` by name. Content is now the default export: \`export default defineContent({ ... })\`.` });
|
|
1317
|
+
throw sourceErrorDiagnostics.SOURCE_B0008({ message: `[vitehub] Content file ${name} must default-export the result of defineContent(): \`export default defineContent({ ... })\`.` });
|
|
1318
|
+
}
|
|
279
1319
|
return file;
|
|
280
1320
|
}
|
|
1321
|
+
const contentModules = /* @__PURE__ */ new Set(["vite-hub/content", "@vite-hub/content"]);
|
|
1322
|
+
function isAstNode(value) {
|
|
1323
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
1324
|
+
}
|
|
1325
|
+
function astNodes(value) {
|
|
1326
|
+
return Array.isArray(value) ? value.filter(isAstNode) : [];
|
|
1327
|
+
}
|
|
1328
|
+
function astName(node) {
|
|
1329
|
+
if (!isAstNode(node)) return;
|
|
1330
|
+
if (node.type === "Identifier" && String(node.name) === node.name) return node.name;
|
|
1331
|
+
if (node.type === "Literal" && String(node.value) === node.value) return node.value;
|
|
1332
|
+
}
|
|
1333
|
+
/** Drops `as`, `satisfies`, `!`, and parentheses around an expression. */
|
|
1334
|
+
function unwrapAst(node) {
|
|
1335
|
+
let current = node;
|
|
1336
|
+
while (isAstNode(current) && [
|
|
1337
|
+
"TSAsExpression",
|
|
1338
|
+
"TSSatisfiesExpression",
|
|
1339
|
+
"TSNonNullExpression",
|
|
1340
|
+
"ParenthesizedExpression"
|
|
1341
|
+
].includes(String(current.type))) current = current.expression;
|
|
1342
|
+
return current;
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Read the `defineContent()` call that the default export holds. Collections count as present unless the call
|
|
1346
|
+
* provably has no non-empty `collections` object. SEO routes count only when the call has a `seo` option: a literal
|
|
1347
|
+
* `sitemap`, `robots`, `markdown`, `rss`, `mcp`, or `llms` that is not `false`, or a `seo` value that discovery cannot follow.
|
|
1348
|
+
*/
|
|
1349
|
+
function inspectContentModule(program, contentImportBase) {
|
|
1350
|
+
return {
|
|
1351
|
+
...inspectContentOptions(program, contentImportBase),
|
|
1352
|
+
sqlite: importsContentSqlite(program, contentImportBase),
|
|
1353
|
+
github: importsGitHubSource(program)
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
const sourceModules = /* @__PURE__ */ new Set(["vite-hub/source", "@vite-hub/source"]);
|
|
1357
|
+
function importsGitHubSource(program) {
|
|
1358
|
+
return (isAstNode(program) ? astNodes(program.body) : []).some((statement) => statement.type === "ImportDeclaration" && isAstNode(statement.source) && sourceModules.has(String(statement.source.value)) && astNodes(statement.specifiers).some((specifier) => specifier.type === "ImportSpecifier" && astName(specifier.imported) === "github"));
|
|
1359
|
+
}
|
|
1360
|
+
function importsContentSqlite(program, contentImportBase) {
|
|
1361
|
+
const bases = contentImportBase ? /* @__PURE__ */ new Set([...contentModules, contentImportBase]) : contentModules;
|
|
1362
|
+
const modules = new Set([...bases].map((base) => `${base}/sqlite`));
|
|
1363
|
+
return (isAstNode(program) ? astNodes(program.body) : []).some((statement) => statement.type === "ImportDeclaration" && isAstNode(statement.source) && modules.has(String(statement.source.value)));
|
|
1364
|
+
}
|
|
1365
|
+
function inspectContentOptions(program, contentImportBase) {
|
|
1366
|
+
const maybe = {
|
|
1367
|
+
route: true,
|
|
1368
|
+
collections: true,
|
|
1369
|
+
sitemap: false,
|
|
1370
|
+
robots: false,
|
|
1371
|
+
markdown: false,
|
|
1372
|
+
rss: false,
|
|
1373
|
+
mcp: false,
|
|
1374
|
+
llms: false,
|
|
1375
|
+
live: true,
|
|
1376
|
+
previews: false
|
|
1377
|
+
};
|
|
1378
|
+
const body = isAstNode(program) ? astNodes(program.body) : [];
|
|
1379
|
+
const constants = /* @__PURE__ */ new Map();
|
|
1380
|
+
const defineContentNames = /* @__PURE__ */ new Set();
|
|
1381
|
+
const defineContentNamespaces = /* @__PURE__ */ new Set();
|
|
1382
|
+
const modules = contentImportBase ? /* @__PURE__ */ new Set([...contentModules, contentImportBase]) : contentModules;
|
|
1383
|
+
let contentInit;
|
|
1384
|
+
let contentLocal;
|
|
1385
|
+
for (const statement of body) {
|
|
1386
|
+
if (statement.type === "ImportDeclaration" && isAstNode(statement.source) && modules.has(String(statement.source.value))) for (const specifier of astNodes(statement.specifiers)) {
|
|
1387
|
+
if (specifier.type === "ImportSpecifier" && astName(specifier.imported) === "defineContent") {
|
|
1388
|
+
const local = astName(specifier.local);
|
|
1389
|
+
if (local) defineContentNames.add(local);
|
|
1390
|
+
}
|
|
1391
|
+
if (specifier.type === "ImportNamespaceSpecifier") {
|
|
1392
|
+
const local = astName(specifier.local);
|
|
1393
|
+
if (local) defineContentNamespaces.add(local);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
const exported = statement.type === "ExportNamedDeclaration";
|
|
1397
|
+
const declaration = exported ? statement.declaration : statement;
|
|
1398
|
+
if (isAstNode(declaration) && declaration.type === "VariableDeclaration") for (const declarator of astNodes(declaration.declarations)) {
|
|
1399
|
+
const local = astName(declarator.id);
|
|
1400
|
+
if (local && declaration.kind === "const") constants.set(local, declarator.init);
|
|
1401
|
+
}
|
|
1402
|
+
if (statement.type === "ExportDefaultDeclaration") {
|
|
1403
|
+
const value = unwrapAst(statement.declaration);
|
|
1404
|
+
if (isAstNode(value) && value.type === "Identifier") contentLocal = astName(value);
|
|
1405
|
+
else contentInit = statement.declaration;
|
|
1406
|
+
}
|
|
1407
|
+
if (exported && !statement.source) {
|
|
1408
|
+
for (const specifier of astNodes(statement.specifiers)) if (astName(specifier.exported) === "default") contentLocal = astName(specifier.local);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
if (contentInit === void 0 && contentLocal) contentInit = constants.get(contentLocal);
|
|
1412
|
+
const resolveNode = (node) => {
|
|
1413
|
+
const value = unwrapAst(node);
|
|
1414
|
+
const local = isAstNode(value) && value.type === "Identifier" ? astName(value) : void 0;
|
|
1415
|
+
return local && constants.has(local) ? unwrapAst(constants.get(local)) : value;
|
|
1416
|
+
};
|
|
1417
|
+
const properties = (node) => {
|
|
1418
|
+
if (!isAstNode(node) || node.type !== "ObjectExpression") return;
|
|
1419
|
+
const result = /* @__PURE__ */ new Map();
|
|
1420
|
+
for (const property of Array.isArray(node.properties) ? node.properties : []) {
|
|
1421
|
+
if (!isAstNode(property)) return;
|
|
1422
|
+
if (property.type === "SpreadElement") {
|
|
1423
|
+
const spread = properties(resolveNode(property.argument));
|
|
1424
|
+
if (!spread) return;
|
|
1425
|
+
for (const [key, value] of spread) result.set(key, value);
|
|
1426
|
+
continue;
|
|
1427
|
+
}
|
|
1428
|
+
if (property.type !== "Property" || property.computed) return;
|
|
1429
|
+
const key = astName(property.key);
|
|
1430
|
+
if (key) result.set(key, property.value);
|
|
1431
|
+
}
|
|
1432
|
+
return result;
|
|
1433
|
+
};
|
|
1434
|
+
const call = unwrapAst(contentInit);
|
|
1435
|
+
if (!isAstNode(call) || call.type !== "CallExpression") return maybe;
|
|
1436
|
+
const calleeNode = unwrapAst(call.callee);
|
|
1437
|
+
const callee = astName(calleeNode);
|
|
1438
|
+
const namespaceCall = isAstNode(calleeNode) && calleeNode.type === "MemberExpression" && !calleeNode.computed && defineContentNamespaces.has(astName(calleeNode.object) ?? "") && astName(calleeNode.property) === "defineContent";
|
|
1439
|
+
if ((!callee || !defineContentNames.has(callee)) && !namespaceCall) return maybe;
|
|
1440
|
+
const [argument, ...rest] = Array.isArray(call.arguments) ? call.arguments : [];
|
|
1441
|
+
if (argument === void 0) return {
|
|
1442
|
+
route: true,
|
|
1443
|
+
collections: false,
|
|
1444
|
+
sitemap: false,
|
|
1445
|
+
robots: false,
|
|
1446
|
+
markdown: false,
|
|
1447
|
+
rss: false,
|
|
1448
|
+
mcp: false,
|
|
1449
|
+
llms: false,
|
|
1450
|
+
live: true,
|
|
1451
|
+
previews: false
|
|
1452
|
+
};
|
|
1453
|
+
const options = rest.length ? void 0 : properties(resolveNode(argument));
|
|
1454
|
+
if (!options) return {
|
|
1455
|
+
route: true,
|
|
1456
|
+
collections: true,
|
|
1457
|
+
sitemap: true,
|
|
1458
|
+
robots: true,
|
|
1459
|
+
markdown: true,
|
|
1460
|
+
rss: true,
|
|
1461
|
+
mcp: "unknown",
|
|
1462
|
+
llms: true,
|
|
1463
|
+
live: true,
|
|
1464
|
+
previews: true
|
|
1465
|
+
};
|
|
1466
|
+
const route = resolveNode(options.get("route"));
|
|
1467
|
+
const live = unwrapAst(options.get("live"));
|
|
1468
|
+
const previews = resolveNode(options.get("previews"));
|
|
1469
|
+
const features = {
|
|
1470
|
+
route: !(isAstNode(route) && route.type === "Literal" && route.value === false),
|
|
1471
|
+
collections: false,
|
|
1472
|
+
sitemap: false,
|
|
1473
|
+
robots: false,
|
|
1474
|
+
markdown: false,
|
|
1475
|
+
rss: false,
|
|
1476
|
+
mcp: false,
|
|
1477
|
+
llms: false,
|
|
1478
|
+
live: !(isAstNode(live) && live.type === "Literal" && live.value === false),
|
|
1479
|
+
previews: options.has("previews") && !(isAstNode(previews) && previews.type === "Literal" && previews.value === false)
|
|
1480
|
+
};
|
|
1481
|
+
if (options.has("collections")) {
|
|
1482
|
+
const value = resolveNode(options.get("collections"));
|
|
1483
|
+
features.collections = !isAstNode(value) || value.type !== "ObjectExpression" || Array.isArray(value.properties) && value.properties.length > 0;
|
|
1484
|
+
}
|
|
1485
|
+
if (options.has("seo")) {
|
|
1486
|
+
const seo = properties(resolveNode(options.get("seo")));
|
|
1487
|
+
if (!seo) return {
|
|
1488
|
+
...features,
|
|
1489
|
+
sitemap: true,
|
|
1490
|
+
robots: true,
|
|
1491
|
+
markdown: true,
|
|
1492
|
+
rss: true,
|
|
1493
|
+
mcp: "unknown",
|
|
1494
|
+
llms: true
|
|
1495
|
+
};
|
|
1496
|
+
for (const key of [
|
|
1497
|
+
"sitemap",
|
|
1498
|
+
"robots",
|
|
1499
|
+
"markdown",
|
|
1500
|
+
"rss",
|
|
1501
|
+
"mcp",
|
|
1502
|
+
"llms"
|
|
1503
|
+
]) {
|
|
1504
|
+
if (!seo.has(key)) continue;
|
|
1505
|
+
const value = key === "mcp" ? resolveNode(seo.get(key)) : unwrapAst(seo.get(key));
|
|
1506
|
+
if (key === "mcp" && (!isAstNode(value) || value.type !== "Literal" && value.type !== "ObjectExpression")) features.mcp = "unknown";
|
|
1507
|
+
else features[key] = !(isAstNode(value) && value.type === "Literal" && value.value === false);
|
|
1508
|
+
}
|
|
1509
|
+
if (features.llms) features.markdown = true;
|
|
1510
|
+
}
|
|
1511
|
+
return features;
|
|
1512
|
+
}
|
|
1513
|
+
/** Read what the Content module defines without running it. A file that does not parse counts as defining everything. */
|
|
1514
|
+
async function inspectContentEntry(file, contentImportBase) {
|
|
1515
|
+
const { parseAst } = await import("vite");
|
|
1516
|
+
try {
|
|
1517
|
+
return inspectContentModule(parseAst(await readFile(file, "utf8"), { lang: /\.[cm]?ts$/.test(file) ? "ts" : "js" }), contentImportBase);
|
|
1518
|
+
} catch {
|
|
1519
|
+
return {
|
|
1520
|
+
route: true,
|
|
1521
|
+
collections: true,
|
|
1522
|
+
sitemap: false,
|
|
1523
|
+
robots: false,
|
|
1524
|
+
markdown: false,
|
|
1525
|
+
rss: false,
|
|
1526
|
+
mcp: false,
|
|
1527
|
+
llms: false,
|
|
1528
|
+
live: true,
|
|
1529
|
+
previews: false,
|
|
1530
|
+
sqlite: false,
|
|
1531
|
+
github: false
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
281
1535
|
async function writeContentArtifact(options, file) {
|
|
282
1536
|
const output = resolve(options.projectRoot, contentRouteEntry);
|
|
1537
|
+
const preview = resolve(options.projectRoot, contentPreviewEntry);
|
|
1538
|
+
const sitemap = resolve(options.projectRoot, contentSitemapEntry);
|
|
1539
|
+
const robots = resolve(options.projectRoot, contentRobotsEntry);
|
|
1540
|
+
const markdown = resolve(options.projectRoot, contentMarkdownEntry);
|
|
1541
|
+
const rss = resolve(options.projectRoot, contentRssEntry);
|
|
1542
|
+
const mcp = resolve(options.projectRoot, contentMcpEntry);
|
|
1543
|
+
const llms = resolve(options.projectRoot, contentLlmsEntry);
|
|
1544
|
+
const sqlite = resolve(options.projectRoot, contentSqliteEntry);
|
|
1545
|
+
const githubWebhook = resolve(options.projectRoot, contentGitHubWebhookEntry);
|
|
1546
|
+
const previewRoutes = resolve(options.projectRoot, contentPreviewRoutesEntry);
|
|
1547
|
+
const typesPlugin = resolve(options.projectRoot, contentTypesPluginEntry);
|
|
1548
|
+
const types = resolve(options.projectRoot, contentTypesEntry);
|
|
283
1549
|
if (!file) {
|
|
284
|
-
await
|
|
1550
|
+
await Promise.all([
|
|
1551
|
+
output,
|
|
1552
|
+
preview,
|
|
1553
|
+
sitemap,
|
|
1554
|
+
robots,
|
|
1555
|
+
markdown,
|
|
1556
|
+
rss,
|
|
1557
|
+
mcp,
|
|
1558
|
+
llms,
|
|
1559
|
+
sqlite,
|
|
1560
|
+
githubWebhook,
|
|
1561
|
+
previewRoutes,
|
|
1562
|
+
typesPlugin,
|
|
1563
|
+
types
|
|
1564
|
+
].map((path) => rm(path, { force: true })));
|
|
285
1565
|
return [];
|
|
286
1566
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
1567
|
+
const importBase = JSON.stringify(options.contentImportBase ?? "@vite-hub/content");
|
|
1568
|
+
const contentModule = JSON.stringify(toRuntimeModuleSpecifier(file));
|
|
1569
|
+
const features = {
|
|
1570
|
+
...await inspectContentEntry(file, options.contentImportBase ?? "@vite-hub/content"),
|
|
1571
|
+
...options.appSeo?.sitemap ? { sitemap: false } : {},
|
|
1572
|
+
...options.appSeo?.robots ? { robots: false } : {}
|
|
1573
|
+
};
|
|
1574
|
+
const sessionUser = (useAuth) => `async request => (await ${useAuth}(request).api.getSession({ headers: request.headers }))?.user ?? null`;
|
|
1575
|
+
const authImport = options.auth ? [`import { useAuth } from ${JSON.stringify(authServerModuleId)}`] : [];
|
|
1576
|
+
const readerOptions = options.auth ? `, { user: ${sessionUser("useAuth")} }` : "";
|
|
1577
|
+
const lazyUser = options.auth ? `user: ${sessionUser(`(await import(${JSON.stringify(authServerModuleId)})).useAuth`)}` : "";
|
|
1578
|
+
if (features.route) await writeFileIfChanged(output, [
|
|
1579
|
+
`import { defineContentHandler } from ${importBase}`,
|
|
1580
|
+
...authImport,
|
|
1581
|
+
`import content from ${contentModule}`,
|
|
290
1582
|
"",
|
|
291
|
-
|
|
1583
|
+
`export default defineContentHandler(content${readerOptions})`,
|
|
292
1584
|
""
|
|
293
1585
|
].join("\n"));
|
|
294
|
-
|
|
1586
|
+
else await rm(output, { force: true });
|
|
1587
|
+
const handlers = [];
|
|
1588
|
+
await writeFileIfChanged(preview, [
|
|
1589
|
+
`import { defineContentPreviewPlugin } from ${JSON.stringify(`${options.contentImportBase ?? "@vite-hub/content"}/preview`)}`,
|
|
1590
|
+
"",
|
|
1591
|
+
`export default defineContentPreviewPlugin(() => import(${contentModule}).then(module => module.default))`,
|
|
1592
|
+
""
|
|
1593
|
+
].join("\n"));
|
|
1594
|
+
handlers.push({
|
|
1595
|
+
handler: preview,
|
|
1596
|
+
plugin: true
|
|
1597
|
+
});
|
|
1598
|
+
if (features.sqlite) {
|
|
1599
|
+
await writeFileIfChanged(sqlite, [
|
|
1600
|
+
`import { sqlite } from ${JSON.stringify(`${options.contentImportBase ?? "@vite-hub/content"}/sqlite`)}`,
|
|
1601
|
+
"",
|
|
1602
|
+
"// Returning the import keeps it in the bundle. A bare import is dropped, because the packages have no side effects.",
|
|
1603
|
+
"export default () => sqlite",
|
|
1604
|
+
""
|
|
1605
|
+
].join("\n"));
|
|
1606
|
+
handlers.push({
|
|
1607
|
+
handler: sqlite,
|
|
1608
|
+
plugin: true
|
|
1609
|
+
});
|
|
1610
|
+
} else await rm(sqlite, { force: true });
|
|
1611
|
+
await writeFileIfChanged(typesPlugin, renderContentTypesPlugin(importBase, contentModule));
|
|
1612
|
+
handlers.push({
|
|
1613
|
+
handler: typesPlugin,
|
|
1614
|
+
plugin: true
|
|
1615
|
+
});
|
|
1616
|
+
if (!await readFile(types, "utf8").then(() => true, () => false)) await writeFileIfChanged(types, "export {}\n");
|
|
1617
|
+
if (features.route) handlers.push({
|
|
295
1618
|
handler: output,
|
|
296
1619
|
route: "/api/content/**"
|
|
297
|
-
}
|
|
1620
|
+
});
|
|
1621
|
+
if (features.github) {
|
|
1622
|
+
await writeFileIfChanged(githubWebhook, [
|
|
1623
|
+
`import { defineContentGitHubWebhookHandler } from ${importBase}`,
|
|
1624
|
+
`import content from ${contentModule}`,
|
|
1625
|
+
"",
|
|
1626
|
+
"export default defineContentGitHubWebhookHandler(content)",
|
|
1627
|
+
""
|
|
1628
|
+
].join("\n"));
|
|
1629
|
+
handlers.push({
|
|
1630
|
+
handler: githubWebhook,
|
|
1631
|
+
method: "post",
|
|
1632
|
+
route: "/_vitehub/content/github"
|
|
1633
|
+
});
|
|
1634
|
+
} else await rm(githubWebhook, { force: true });
|
|
1635
|
+
if (features.previews) {
|
|
1636
|
+
await writeFileIfChanged(previewRoutes, [
|
|
1637
|
+
`import { defineContentPreviewRoutesPlugin } from ${JSON.stringify(`${options.contentImportBase ?? "@vite-hub/content"}/preview`)}`,
|
|
1638
|
+
"import { useRuntimeConfig } from \"nitro/runtime-config\"",
|
|
1639
|
+
"",
|
|
1640
|
+
`export default defineContentPreviewRoutesPlugin(() => import(${contentModule}).then(module => module.default), { app: useRuntimeConfig().app${lazyUser ? `, ${lazyUser}` : ""} })`,
|
|
1641
|
+
""
|
|
1642
|
+
].join("\n"));
|
|
1643
|
+
handlers.push({
|
|
1644
|
+
handler: previewRoutes,
|
|
1645
|
+
plugin: true,
|
|
1646
|
+
position: "start"
|
|
1647
|
+
});
|
|
1648
|
+
} else await rm(previewRoutes, { force: true });
|
|
1649
|
+
for (const [enabled, path, helper, routes] of [
|
|
1650
|
+
[
|
|
1651
|
+
features.sitemap,
|
|
1652
|
+
sitemap,
|
|
1653
|
+
"defineContentSitemapHandler",
|
|
1654
|
+
["/sitemap.xml"]
|
|
1655
|
+
],
|
|
1656
|
+
[
|
|
1657
|
+
features.robots,
|
|
1658
|
+
robots,
|
|
1659
|
+
"defineContentRobotsHandler",
|
|
1660
|
+
["/robots.txt"]
|
|
1661
|
+
],
|
|
1662
|
+
[
|
|
1663
|
+
features.rss,
|
|
1664
|
+
rss,
|
|
1665
|
+
"defineContentRssHandler",
|
|
1666
|
+
["/rss.xml"]
|
|
1667
|
+
],
|
|
1668
|
+
[
|
|
1669
|
+
features.mcp,
|
|
1670
|
+
mcp,
|
|
1671
|
+
"defineContentMcpHandler",
|
|
1672
|
+
["/mcp"]
|
|
1673
|
+
],
|
|
1674
|
+
[
|
|
1675
|
+
features.llms,
|
|
1676
|
+
llms,
|
|
1677
|
+
"defineContentLlmsHandler",
|
|
1678
|
+
[
|
|
1679
|
+
"/llms.txt",
|
|
1680
|
+
"/llms-full.txt",
|
|
1681
|
+
"/:locale/llms-full.txt",
|
|
1682
|
+
"/sitemap.md"
|
|
1683
|
+
]
|
|
1684
|
+
]
|
|
1685
|
+
]) {
|
|
1686
|
+
if (!enabled) {
|
|
1687
|
+
await rm(path, { force: true });
|
|
1688
|
+
continue;
|
|
1689
|
+
}
|
|
1690
|
+
const conditionalMcp = routes[0] === "/mcp" && enabled === "unknown";
|
|
1691
|
+
const helperOptions = helper === "defineContentRobotsHandler" ? "" : readerOptions;
|
|
1692
|
+
await writeFileIfChanged(path, [
|
|
1693
|
+
`import { ${helper} } from ${importBase}`,
|
|
1694
|
+
...helperOptions ? authImport : [],
|
|
1695
|
+
`import content from ${contentModule}`,
|
|
1696
|
+
"",
|
|
1697
|
+
...conditionalMcp ? [
|
|
1698
|
+
`const handler = ${helper}(content${helperOptions})`,
|
|
1699
|
+
"export default async event => {",
|
|
1700
|
+
" if (!content.seo?.mcp) return",
|
|
1701
|
+
" return await handler.fetch(event.req)",
|
|
1702
|
+
"}"
|
|
1703
|
+
] : [`export default ${helper}(content${helperOptions})`],
|
|
1704
|
+
""
|
|
1705
|
+
].join("\n"));
|
|
1706
|
+
for (const route of routes) handlers.push(conditionalMcp ? {
|
|
1707
|
+
handler: path,
|
|
1708
|
+
middleware: true,
|
|
1709
|
+
route
|
|
1710
|
+
} : route === "/mcp" ? {
|
|
1711
|
+
handler: path,
|
|
1712
|
+
route
|
|
1713
|
+
} : {
|
|
1714
|
+
handler: path,
|
|
1715
|
+
method: "get",
|
|
1716
|
+
route
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
if (features.markdown) {
|
|
1720
|
+
await writeFileIfChanged(markdown, [
|
|
1721
|
+
`import { defineContentMarkdownHandler } from ${JSON.stringify(`${options.contentImportBase ?? "@vite-hub/content"}/markdown`)}`,
|
|
1722
|
+
`import { serverFetch } from "nitro"`,
|
|
1723
|
+
"",
|
|
1724
|
+
`export default defineContentMarkdownHandler(() => import(${contentModule}).then(module => module.default), { render: request => serverFetch(request)${lazyUser ? `, ${lazyUser}` : ""} })`,
|
|
1725
|
+
""
|
|
1726
|
+
].join("\n"));
|
|
1727
|
+
handlers.push({
|
|
1728
|
+
handler: markdown,
|
|
1729
|
+
middleware: true,
|
|
1730
|
+
lazy: false,
|
|
1731
|
+
route: "/**"
|
|
1732
|
+
});
|
|
1733
|
+
} else await rm(markdown, { force: true });
|
|
1734
|
+
return handlers;
|
|
1735
|
+
}
|
|
1736
|
+
async function prepareSourceArtifacts(options) {
|
|
1737
|
+
const [collections, content] = await Promise.all([discoverCollections(options), findContentEntry(options)]);
|
|
1738
|
+
return {
|
|
1739
|
+
handlers: [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => (left.route ?? "").localeCompare(right.route ?? "")),
|
|
1740
|
+
...content ? { content: { handler: content } } : {}
|
|
1741
|
+
};
|
|
298
1742
|
}
|
|
299
1743
|
async function prepareSourceGeneration(options) {
|
|
300
|
-
|
|
301
|
-
return [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => left.route.localeCompare(right.route));
|
|
1744
|
+
return (await prepareSourceArtifacts(options)).handlers;
|
|
302
1745
|
}
|
|
303
|
-
|
|
1746
|
+
/** Nuxt serves Vite assets from `/_nuxt/`, so its Vite `base` is not the app base. `vite-hub/nuxt` passes the app base. */
|
|
1747
|
+
function applicationBaseURL(config) {
|
|
1748
|
+
const configured = Reflect.get(config, VITEHUB_APP_BASE_URL);
|
|
1749
|
+
const base = typeof configured === "string" ? configured : config.base;
|
|
304
1750
|
return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
|
|
305
1751
|
}
|
|
306
1752
|
async function generatedHandlerKey(handlers) {
|
|
@@ -315,36 +1761,63 @@ function generatedSourceNitroContribution(value, generatedHandlers) {
|
|
|
315
1761
|
const merged = mergeGeneratedSourceNitroConfig(existing, generatedHandlers);
|
|
316
1762
|
const handlers = merged.handlers?.slice(Array.isArray(existing.handlers) ? existing.handlers.length : 0);
|
|
317
1763
|
const modules = merged.modules?.slice(Array.isArray(existing.modules) ? existing.modules.length : 0);
|
|
318
|
-
|
|
319
|
-
return
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
1764
|
+
const plugins = merged.plugins?.filter((plugin) => !existing.plugins?.includes(plugin));
|
|
1765
|
+
if (!handlers?.length && !modules?.length && !plugins?.length) return;
|
|
1766
|
+
const contribution = {};
|
|
1767
|
+
if (handlers?.length) contribution.handlers = handlers;
|
|
1768
|
+
if (modules?.length) contribution.modules = modules;
|
|
1769
|
+
if (plugins?.length) contribution.plugins = plugins;
|
|
1770
|
+
return contribution;
|
|
323
1771
|
}
|
|
324
1772
|
function sourceDefinitionPath(file, projectRoot, serverDirs) {
|
|
1773
|
+
const projectRelativePath = relative(resolve(projectRoot), resolve(file)).replaceAll("\\", "/");
|
|
1774
|
+
if (/^server\.auth\.(?:[cm]?[jt]s)$/.test(projectRelativePath)) return true;
|
|
325
1775
|
return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs).some((directory) => {
|
|
326
1776
|
const path = relative(resolve(projectRoot, directory), resolve(file)).replaceAll("\\", "/");
|
|
327
1777
|
if (path.startsWith("../") || isAbsolute(path)) return false;
|
|
328
|
-
return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^collections\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
|
|
1778
|
+
return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^auth\.(?:[cm]?[jt]s)$/.test(path) || /^collections\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
|
|
329
1779
|
});
|
|
330
1780
|
}
|
|
331
1781
|
function hubSource(options = {}) {
|
|
1782
|
+
const refreshAuthByRoot = /* @__PURE__ */ new Map();
|
|
1783
|
+
let nitroHost;
|
|
1784
|
+
let nitroHostContribution;
|
|
1785
|
+
const nitroHandlers = [];
|
|
332
1786
|
let latestProjectRoot;
|
|
333
1787
|
const configuredStateByRoot = /* @__PURE__ */ new Map();
|
|
334
1788
|
const closeHostRefreshByEnvironment = /* @__PURE__ */ new WeakMap();
|
|
335
1789
|
const hostRefreshLifecycleByRoot = /* @__PURE__ */ new Map();
|
|
336
1790
|
const sourcePreparationByRoot = /* @__PURE__ */ new Map();
|
|
1791
|
+
const contentDefinitionByRoot = /* @__PURE__ */ new Map();
|
|
1792
|
+
const getContentDefinition = (projectRoot) => {
|
|
1793
|
+
const root = projectRoot ? resolve(projectRoot) : latestProjectRoot;
|
|
1794
|
+
return root ? contentDefinitionByRoot.get(root) : void 0;
|
|
1795
|
+
};
|
|
337
1796
|
const configurationTransitionByRoot = /* @__PURE__ */ new Map();
|
|
1797
|
+
let legacyServerBuild = false;
|
|
1798
|
+
let resolvedConfig;
|
|
338
1799
|
const generatedHandlersListeners = /* @__PURE__ */ new Set();
|
|
339
1800
|
const prepareSources = (input) => {
|
|
340
1801
|
const root = resolve(input.projectRoot);
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
1802
|
+
const previousPreparation = sourcePreparationByRoot.get(root) ?? Promise.resolve();
|
|
1803
|
+
const runPreparation = () => {
|
|
1804
|
+
const auth = typeof options.auth === "function" ? options.auth({
|
|
1805
|
+
projectRoot: root,
|
|
1806
|
+
serverDirs: input.serverDirs
|
|
1807
|
+
}) : options.auth && Boolean(refreshAuthByRoot.get(root)?.());
|
|
1808
|
+
return prepareSourceArtifacts({
|
|
1809
|
+
...input,
|
|
1810
|
+
auth,
|
|
1811
|
+
...options.appSeo ? { appSeo: options.appSeo } : {},
|
|
1812
|
+
importBase: options.importBase,
|
|
1813
|
+
contentImportBase: options.contentImportBase
|
|
1814
|
+
}).then(({ content, handlers }) => {
|
|
1815
|
+
if (content) contentDefinitionByRoot.set(root, content);
|
|
1816
|
+
else contentDefinitionByRoot.delete(root);
|
|
1817
|
+
return handlers;
|
|
1818
|
+
});
|
|
1819
|
+
};
|
|
1820
|
+
const preparation = previousPreparation.then(runPreparation, runPreparation);
|
|
348
1821
|
sourcePreparationByRoot.set(root, preparation);
|
|
349
1822
|
preparation.finally(() => {
|
|
350
1823
|
if (sourcePreparationByRoot.get(root) === preparation) sourcePreparationByRoot.delete(root);
|
|
@@ -378,18 +1851,84 @@ function hubSource(options = {}) {
|
|
|
378
1851
|
if (Array.isArray(nitro.handlers) && contributedHandlers.length > 0) nitro.handlers = nitro.handlers.filter((handler) => !contributedHandlers.includes(handler));
|
|
379
1852
|
const contributedModules = configuredNitroContribution?.modules ?? [];
|
|
380
1853
|
if (Array.isArray(nitro.modules) && contributedModules.length > 0) nitro.modules = nitro.modules.filter((module) => !contributedModules.includes(module));
|
|
1854
|
+
const contributedPlugins = configuredNitroContribution?.plugins ?? [];
|
|
1855
|
+
if (Array.isArray(nitro.plugins) && contributedPlugins.length > 0) nitro.plugins = nitro.plugins.filter((plugin) => !contributedPlugins.includes(plugin));
|
|
381
1856
|
return mergeGeneratedSourceNitroConfig(nitro, handlers);
|
|
382
1857
|
};
|
|
383
1858
|
return {
|
|
384
1859
|
name: "@vite-hub/source/vite",
|
|
385
1860
|
enforce: "post",
|
|
386
1861
|
api: {
|
|
1862
|
+
getContentDefinition,
|
|
387
1863
|
onGeneratedHandlersChanged,
|
|
388
1864
|
prepareSources
|
|
389
1865
|
},
|
|
390
|
-
|
|
1866
|
+
resolveId: {
|
|
1867
|
+
filter: { id: BUNDLED_GLOB_ID_PATTERN },
|
|
1868
|
+
handler(id) {
|
|
1869
|
+
return id;
|
|
1870
|
+
}
|
|
1871
|
+
},
|
|
1872
|
+
load: {
|
|
1873
|
+
filter: { id: BUNDLED_GLOB_ID_PATTERN },
|
|
1874
|
+
async handler(id) {
|
|
1875
|
+
const { code, watched } = await loadBundledGlob(id, latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd()));
|
|
1876
|
+
for (const file of watched) this.addWatchFile(file);
|
|
1877
|
+
return code;
|
|
1878
|
+
}
|
|
1879
|
+
},
|
|
1880
|
+
transform: {
|
|
1881
|
+
filter: {
|
|
1882
|
+
id: { exclude: /\/node_modules\// },
|
|
1883
|
+
code: /\bvite-hub\/source["'`]/
|
|
1884
|
+
},
|
|
1885
|
+
handler(code, id, options) {
|
|
1886
|
+
const environment = this.environment?.config;
|
|
1887
|
+
if (!(environment ? environment.consumer === "server" : options?.ssr === true && legacyServerBuild) || environment && environment.command !== "build") return;
|
|
1888
|
+
const calls = findGlobCalls(this.parse(code));
|
|
1889
|
+
for (const call of calls.filter((call) => call.input === void 0)) {
|
|
1890
|
+
const hint = sourceErrorDiagnostics.SOURCE_GLOB_OPTIONS_NOT_LITERAL();
|
|
1891
|
+
const config = environment ?? resolvedConfig;
|
|
1892
|
+
if (!config) {
|
|
1893
|
+
this.warn({
|
|
1894
|
+
message: `[vitehub] ${hint.why}`,
|
|
1895
|
+
pos: call.start
|
|
1896
|
+
});
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
const lines = code.slice(0, call.start).split("\n");
|
|
1900
|
+
hint.sources = [`${relative(config.root, id)}:${lines.length}:${lines.at(-1).length + 1}`];
|
|
1901
|
+
reportViteHubHint(config, hint);
|
|
1902
|
+
}
|
|
1903
|
+
if (calls.some((call) => call.input !== void 0)) return {
|
|
1904
|
+
code: rewriteGlobCalls(code, calls),
|
|
1905
|
+
map: null
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
},
|
|
1909
|
+
vitehub: { inspect: () => ({ definitions: [{
|
|
1910
|
+
kind: "collection",
|
|
1911
|
+
label: "Collections",
|
|
1912
|
+
list: () => {
|
|
1913
|
+
const projectRoot = latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd());
|
|
1914
|
+
return inspectCollectionDefinitions({
|
|
1915
|
+
projectRoot,
|
|
1916
|
+
serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
}] }) },
|
|
1920
|
+
nitro: {
|
|
1921
|
+
name: "@vite-hub/source/generated-routes",
|
|
1922
|
+
async setup(nitro) {
|
|
1923
|
+
nitroHost = nitro;
|
|
1924
|
+
nitroHostContribution = void 0;
|
|
1925
|
+
await generatedRouteGuard(nitroHandlers).setup(nitro);
|
|
1926
|
+
}
|
|
1927
|
+
},
|
|
1928
|
+
async config(config, env) {
|
|
391
1929
|
const viteConfig = config;
|
|
392
1930
|
if (viteConfig["__vitehubNitroConfigContext"]) return;
|
|
1931
|
+
legacyServerBuild = env.command === "build" && config.build?.ssr === true;
|
|
393
1932
|
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
|
|
394
1933
|
latestProjectRoot = projectRoot;
|
|
395
1934
|
bindUnresolvedListenerRoots(projectRoot);
|
|
@@ -412,7 +1951,7 @@ function hubSource(options = {}) {
|
|
|
412
1951
|
serverDirs: serverDirs?.slice()
|
|
413
1952
|
});
|
|
414
1953
|
const contribution = {
|
|
415
|
-
define: { __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(viteConfig
|
|
1954
|
+
define: { __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(viteConfig)) },
|
|
416
1955
|
...nitro ? { nitro } : {}
|
|
417
1956
|
};
|
|
418
1957
|
previousLifecycle?.close();
|
|
@@ -437,10 +1976,18 @@ function hubSource(options = {}) {
|
|
|
437
1976
|
return transition;
|
|
438
1977
|
},
|
|
439
1978
|
async configResolved(config) {
|
|
1979
|
+
startViteHubHints(config);
|
|
1980
|
+
resolvedConfig = config;
|
|
440
1981
|
const viteConfig = config;
|
|
441
1982
|
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
|
|
442
1983
|
latestProjectRoot = projectRoot;
|
|
443
1984
|
bindUnresolvedListenerRoots(projectRoot);
|
|
1985
|
+
const authPlugin = (config.plugins ?? []).flat(Infinity).find((plugin) => plugin.name === "@vite-hub/auth/vite");
|
|
1986
|
+
const refreshAuth = Reflect.get(Object(Reflect.get(Object(authPlugin), "api")), "refresh");
|
|
1987
|
+
if (refreshAuth instanceof Function) refreshAuthByRoot.set(projectRoot, () => refreshAuth());
|
|
1988
|
+
else refreshAuthByRoot.delete(projectRoot);
|
|
1989
|
+
viteConfig.define ??= {};
|
|
1990
|
+
viteConfig.define.__VITEHUB_APP_BASE_URL__ = JSON.stringify(applicationBaseURL(config));
|
|
444
1991
|
const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
|
|
445
1992
|
const runTransition = async () => {
|
|
446
1993
|
const configuredState = configuredStateByRoot.get(projectRoot);
|
|
@@ -450,6 +1997,20 @@ function hubSource(options = {}) {
|
|
|
450
1997
|
serverDirs
|
|
451
1998
|
});
|
|
452
1999
|
const handlerKey = await generatedHandlerKey(handlers);
|
|
2000
|
+
if (nitroHost && !viteConfig["__vitehubNitroConfigContext"]) {
|
|
2001
|
+
assertGeneratedRoutes(nitroHost, handlers);
|
|
2002
|
+
const nitro = replaceConfiguredNitroContribution(nitroHost.options, handlers, nitroHostContribution);
|
|
2003
|
+
nitroHostContribution = {
|
|
2004
|
+
handlers: nitro.handlers?.filter((handler) => handlers.some((generated) => !generated.plugin && handler.handler === generated.handler && handler.route === generated.route && handler.method === generated.method)),
|
|
2005
|
+
plugins: handlers.flatMap((generated) => generated.plugin ? [generated.handler] : [])
|
|
2006
|
+
};
|
|
2007
|
+
nitroHost.options.handlers = nitro.handlers;
|
|
2008
|
+
nitroHost.options.plugins = nitro.plugins;
|
|
2009
|
+
nitroHandlers.splice(0, nitroHandlers.length, ...handlers);
|
|
2010
|
+
const typesPlugin = handlers.find((handler) => handler.plugin && handler.handler.replaceAll("\\", "/").endsWith(`/${contentTypesPluginEntry}`));
|
|
2011
|
+
if (typesPlugin) await installContentTypesWriter(nitroHost, typesPlugin.handler);
|
|
2012
|
+
nitroHost.routing.sync();
|
|
2013
|
+
}
|
|
453
2014
|
configuredStateByRoot.set(projectRoot, {
|
|
454
2015
|
handlerKey,
|
|
455
2016
|
nitroContribution: configuredState?.nitroContribution,
|
|
@@ -626,4 +2187,4 @@ function hubSource(options = {}) {
|
|
|
626
2187
|
};
|
|
627
2188
|
}
|
|
628
2189
|
//#endregion
|
|
629
|
-
export { hubSource, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };
|
|
2190
|
+
export { findContentEntry, hubSource, inspectCollectionDefinitions, inspectCollectionModule, inspectContentEntry, inspectContentModule, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };
|