@vite-hub/source 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,19 +1,125 @@
1
1
  import { t as collectionRoutePath } from "./collection-route-BplWPxHR.js";
2
- import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
2
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-DZdhDQpU.js";
3
3
  import { r as isRecordOrFunction } from "./object-CtSHeGQO.js";
4
- import { i as resolveGlobInput, r as globFilePath, t as collectGlobFiles } from "./glob-DmdMVqjx.js";
4
+ import { i as resolveGlobInput, r as globFilePath, t as collectGlobFiles } from "./glob-DT9HlkyK.js";
5
5
  import { t as invariant } from "./invariant-DolT9EEx.js";
6
6
  import { formatDiagnostic } from "nostics";
7
7
  import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
8
8
  import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve } from "node:path";
9
- import { pathToFileURL } from "node:url";
10
- import { mkdirSync, statSync, writeFileSync } from "node:fs";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
11
11
  import { tmpdir } from "node:os";
12
12
  import { parseSync } from "vite";
13
13
  import { randomUUID } from "node:crypto";
14
14
  import { once } from "node:events";
15
15
  import { createServer } from "node:http";
16
16
  import { gzipSync } from "node:zlib";
17
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
18
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
19
+ function normalizeWindowsPath(input = "") {
20
+ if (!input) return input;
21
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
22
+ }
23
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
24
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
25
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
26
+ function cwd() {
27
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
28
+ return "/";
29
+ }
30
+ const resolve$1 = function(...arguments_) {
31
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
32
+ let resolvedPath = "";
33
+ let resolvedAbsolute = false;
34
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
35
+ const path = index >= 0 ? arguments_[index] : cwd();
36
+ if (!path || path.length === 0) continue;
37
+ resolvedPath = `${path}/${resolvedPath}`;
38
+ resolvedAbsolute = isAbsolute$1(path);
39
+ }
40
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
41
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
42
+ return resolvedPath.length > 0 ? resolvedPath : ".";
43
+ };
44
+ function normalizeString(path, allowAboveRoot) {
45
+ let res = "";
46
+ let lastSegmentLength = 0;
47
+ let lastSlash = -1;
48
+ let dots = 0;
49
+ let char = null;
50
+ for (let index = 0; index <= path.length; ++index) {
51
+ if (index < path.length) char = path[index];
52
+ else if (char === "/") break;
53
+ else char = "/";
54
+ if (char === "/") {
55
+ if (lastSlash === index - 1 || dots === 1);
56
+ else if (dots === 2) {
57
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
58
+ if (res.length > 2) {
59
+ const lastSlashIndex = res.lastIndexOf("/");
60
+ if (lastSlashIndex === -1) {
61
+ res = "";
62
+ lastSegmentLength = 0;
63
+ } else {
64
+ res = res.slice(0, lastSlashIndex);
65
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
66
+ }
67
+ lastSlash = index;
68
+ dots = 0;
69
+ continue;
70
+ } else if (res.length > 0) {
71
+ res = "";
72
+ lastSegmentLength = 0;
73
+ lastSlash = index;
74
+ dots = 0;
75
+ continue;
76
+ }
77
+ }
78
+ if (allowAboveRoot) {
79
+ res += res.length > 0 ? "/.." : "..";
80
+ lastSegmentLength = 2;
81
+ }
82
+ } else {
83
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
84
+ else res = path.slice(lastSlash + 1, index);
85
+ lastSegmentLength = index - lastSlash - 1;
86
+ }
87
+ lastSlash = index;
88
+ dots = 0;
89
+ } else if (char === "." && dots !== -1) ++dots;
90
+ else dots = -1;
91
+ }
92
+ return res;
93
+ }
94
+ const isAbsolute$1 = function(p) {
95
+ return _IS_ABSOLUTE_RE.test(p);
96
+ };
97
+ const relative$1 = function(from, to) {
98
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
99
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
100
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
101
+ const _fromCopy = [..._from];
102
+ for (const segment of _fromCopy) {
103
+ if (_to[0] !== segment) break;
104
+ _from.shift();
105
+ _to.shift();
106
+ }
107
+ return [..._from.map(() => ".."), ..._to].join("/");
108
+ };
109
+ const dirname$1 = function(p) {
110
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
111
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
112
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
113
+ };
114
+ //#endregion
115
+ //#region ../internal/src/inspect.ts
116
+ function relativeDefinitionFile(projectRoot, file) {
117
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
118
+ }
119
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
120
+ 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");
121
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
122
+ //#endregion
17
123
  //#region ../internal/src/build/vite.ts
18
124
  const projectRootDirectoryMarkers = [
19
125
  ["server", "agents"],
@@ -86,6 +192,30 @@ function hasProjectRootFileMarker(root, markers) {
86
192
  return false;
87
193
  }
88
194
  //#endregion
195
+ //#region ../internal/src/build/ast-walk.ts
196
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
197
+ function moduleLanguage(file) {
198
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
199
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
200
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
201
+ return "ts";
202
+ }
203
+ function isNode$1(value) {
204
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
205
+ }
206
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
207
+ function walk$1(node, visit, parent) {
208
+ if (visit(node, parent) === false) return;
209
+ const fields = node;
210
+ for (const key in fields) {
211
+ const child = fields[key];
212
+ if (typeof child !== "object" || child === null || key === "parent") continue;
213
+ if (Array.isArray(child)) {
214
+ for (const item of child) if (isNode$1(item)) walk$1(item, visit, node);
215
+ } else if (isNode$1(child)) walk$1(child, visit, node);
216
+ }
217
+ }
218
+ //#endregion
89
219
  //#region ../internal/src/build/scan-module.ts
90
220
  /**
91
221
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -94,16 +224,10 @@ function hasProjectRootFileMarker(root, markers) {
94
224
  */
95
225
  /** The value of an expression that the scanner cannot read without running the module. */
96
226
  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
227
  /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
104
228
  function scanModule(source, file = "module.ts") {
105
229
  const result = parseSync(file, source, {
106
- lang: languageOf(file),
230
+ lang: moduleLanguage(file),
107
231
  preserveParens: false,
108
232
  sourceType: "module"
109
233
  });
@@ -118,7 +242,7 @@ function scanModule(source, file = "module.ts") {
118
242
  /** Lists the names that a module exports. A default export reads as `default`. Type-only exports are left out. */
119
243
  function exportNames(source, file = "module.ts") {
120
244
  const { module } = parseSync(file, source, {
121
- lang: languageOf(file),
245
+ lang: moduleLanguage(file),
122
246
  sourceType: "module"
123
247
  });
124
248
  return module.staticExports.flatMap((statement) => statement.entries).flatMap((entry) => {
@@ -127,21 +251,6 @@ function exportNames(source, file = "module.ts") {
127
251
  return entry.exportName.name === null ? [] : [entry.exportName.name];
128
252
  });
129
253
  }
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
254
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
146
255
  function unwrapExpression(node) {
147
256
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -266,6 +375,7 @@ function staticString(node) {
266
375
  * the file instead of the terminal.
267
376
  */
268
377
  const viteHubHintsFile = ".vitehub/hints.json";
378
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
269
379
  const runsKey = Symbol.for("vitehub.hints.runs");
270
380
  const shared = globalThis;
271
381
  const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
@@ -300,10 +410,13 @@ function write(run) {
300
410
  writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
301
411
  }
302
412
  /**
303
- * Reports a hint from a Vite plugin hook: prints it once with its fix and docs link, and adds it to
413
+ * Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
304
414
  * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
305
415
  */
306
416
  function reportViteHubHint(config, diagnostic) {
417
+ if (skipHints(config)) return;
418
+ const nuxt = config[VITEHUB_NUXT_HINTS];
419
+ if (typeof nuxt === "function") return nuxt(diagnostic);
307
420
  const run = runs.get(hintsFile(config)) ?? startRun(config);
308
421
  const hint = {
309
422
  code: diagnostic.code,
@@ -317,17 +430,20 @@ function reportViteHubHint(config, diagnostic) {
317
430
  run.keys.add(key);
318
431
  run.report.hints.push(hint);
319
432
  write(run);
320
- config.logger.warn(formatDiagnostic(diagnostic));
433
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
434
+ }
435
+ function skipHints(config) {
436
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
321
437
  }
322
438
  /**
323
439
  * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
324
440
  * 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.
441
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
442
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
327
443
  */
328
- function startViteHubHints(config) {
329
- if (started.has(config)) return;
330
- started.add(config);
444
+ function startViteHubHints(config, owner = config) {
445
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
446
+ started.add(owner);
331
447
  write(startRun(config));
332
448
  }
333
449
  //#endregion
@@ -360,6 +476,34 @@ function createNitroServerKit(value = {}) {
360
476
  };
361
477
  }
362
478
  //#endregion
479
+ //#region ../internal/src/build/paths.ts
480
+ function resolveRuntimeModule(packageDir, modulePath) {
481
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
482
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
483
+ }
484
+ const packageDirs = /* @__PURE__ */ new Map();
485
+ function findPackageDir(file) {
486
+ const start = dirname$1(file);
487
+ const cached = packageDirs.get(start);
488
+ if (cached) return cached;
489
+ let dir = start;
490
+ while (!existsSync(resolve$1(dir, "package.json"))) {
491
+ const parent = dirname$1(dir);
492
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
493
+ dir = parent;
494
+ }
495
+ packageDirs.set(start, dir);
496
+ return dir;
497
+ }
498
+ /**
499
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
500
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
501
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
502
+ */
503
+ function ownModule(importMetaUrl, modulePath) {
504
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
505
+ }
506
+ //#endregion
363
507
  //#region src/internal/content-types-writer.ts
364
508
  const installed = /* @__PURE__ */ new WeakMap();
365
509
  /** Keep writes in the Nitro host, including when its runtime runs in workerd. */
@@ -431,106 +575,6 @@ function renderContentTypesPlugin(importBase, contentModule) {
431
575
  ].join("\n");
432
576
  }
433
577
  //#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
578
  //#region src/internal/collection-discovery.ts
535
579
  /** The initializers of top-level `const`, `let`, and `var` declarations named `name`, with their declaration kind. */
536
580
  function declarationInitializers(module, name, exportedOnly) {
@@ -1084,8 +1128,37 @@ async function loadBundledGlob(id, rootDir) {
1084
1128
  };
1085
1129
  }
1086
1130
  //#endregion
1131
+ //#region src/internal/source-discovery.ts
1132
+ /** Lists the Source files under `<serverDir>/sources`. Each default export is one Source. It reads the files and does not import them. */
1133
+ async function discoverSources(options) {
1134
+ const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
1135
+ const sources = (await Promise.all(serverDirs.map(async (serverDir) => {
1136
+ const directory = resolve(serverDir, "sources");
1137
+ return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
1138
+ const path = relative(options.projectRoot, file).replaceAll("\\", "/");
1139
+ if (!exportNames(await readFile(file, "utf8"), `${file}.ts`).includes("default")) throw sourceErrorDiagnostics.SOURCE_FILE_DEFAULT_EXPORT_MISSING({ path });
1140
+ return {
1141
+ file,
1142
+ name: relative(directory, file).slice(0, -extname(file).length).replaceAll("\\", "/")
1143
+ };
1144
+ }));
1145
+ }))).flat().sort((left, right) => left.name.localeCompare(right.name));
1146
+ const files = /* @__PURE__ */ new Map();
1147
+ for (const source of sources) {
1148
+ const previous = files.get(source.name);
1149
+ if (previous) throw sourceErrorDiagnostics.SOURCE_FILE_NAME_DUPLICATE({
1150
+ files: [previous, source.file].map((file) => relative(options.projectRoot, file).replaceAll("\\", "/")).join(" and "),
1151
+ name: source.name
1152
+ });
1153
+ files.set(source.name, source.file);
1154
+ }
1155
+ return sources;
1156
+ }
1157
+ //#endregion
1087
1158
  //#region src/vite.ts
1088
1159
  const collectionTypesEntry = ".vitehub/types/source/collections.d.ts";
1160
+ const sourceTypesEntry = ".vitehub/types/source/sources.d.ts";
1161
+ const sourceRegistryEntry = ".vitehub/source/registry.mjs";
1089
1162
  const retiredCollectionTypesWrapper = ".vitehub/types/source/vitehub-source-registry.d.ts";
1090
1163
  const collectionRoutesDirectory = ".vitehub/source/routes";
1091
1164
  const contentRouteEntry = ".vitehub/content/route.mjs";
@@ -1098,6 +1171,8 @@ const contentMcpEntry = ".vitehub/content/mcp.mjs";
1098
1171
  const contentLlmsEntry = ".vitehub/content/llms.mjs";
1099
1172
  const contentSqliteEntry = ".vitehub/content/sqlite.mjs";
1100
1173
  const contentGitHubWebhookEntry = ".vitehub/content/github-webhook.mjs";
1174
+ const contentPrewarmQueueEntry = ".vitehub/content/prewarm-queue.mjs";
1175
+ const contentPrewarmQueue = "vitehub-content-prewarm";
1101
1176
  const contentPreviewRoutesEntry = ".vitehub/content/preview-routes.mjs";
1102
1177
  const contentTypesPluginEntry = ".vitehub/content/types.mjs";
1103
1178
  const contentTypesEntry = ".vitehub/types/content.d.ts";
@@ -1116,6 +1191,8 @@ async function snapshotGeneratedSourceArtifacts(projectRoot) {
1116
1191
  const files = /* @__PURE__ */ new Map();
1117
1192
  const fixedEntries = [
1118
1193
  collectionTypesEntry,
1194
+ sourceTypesEntry,
1195
+ sourceRegistryEntry,
1119
1196
  contentRouteEntry,
1120
1197
  contentPreviewEntry,
1121
1198
  contentSitemapEntry,
@@ -1151,6 +1228,8 @@ async function restoreGeneratedSourceArtifacts(projectRoot, snapshot) {
1151
1228
  });
1152
1229
  for (const entry of [
1153
1230
  collectionTypesEntry,
1231
+ sourceTypesEntry,
1232
+ sourceRegistryEntry,
1154
1233
  contentRouteEntry,
1155
1234
  contentPreviewEntry,
1156
1235
  contentSitemapEntry,
@@ -1290,6 +1369,43 @@ async function writeCollectionArtifacts(options, collections) {
1290
1369
  }));
1291
1370
  }
1292
1371
  /**
1372
+ * Writes the `ViteHubSourceMap` types and a Nitro plugin that registers a loader for each file in `server/sources/`
1373
+ * by its name, so `useSource("docs")` opens the default export of `server/sources/docs.ts`.
1374
+ */
1375
+ async function writeSourceArtifacts(options, sources) {
1376
+ const types = resolve(options.projectRoot, sourceTypesEntry);
1377
+ const registry = resolve(options.projectRoot, sourceRegistryEntry);
1378
+ if (sources.length === 0) {
1379
+ await Promise.all([types, registry].map((path) => rm(path, { force: true })));
1380
+ return [];
1381
+ }
1382
+ await writeFileIfChanged(types, [
1383
+ "declare global {",
1384
+ " interface ViteHubSourceMap {",
1385
+ ...sources.map(({ file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})["default"]`),
1386
+ " }",
1387
+ "}",
1388
+ "",
1389
+ "export {}",
1390
+ ""
1391
+ ].join("\n"));
1392
+ await writeFileIfChanged(registry, [
1393
+ `import { registerSourceLoaders } from ${JSON.stringify(toRuntimeModuleSpecifier(ownModule(import.meta.url, "internal/registry")))}`,
1394
+ "",
1395
+ "registerSourceLoaders({",
1396
+ ...sources.map(({ file, name }) => ` [${JSON.stringify(name)}]: () => import(${JSON.stringify(toRuntimeModuleSpecifier(file))}),`),
1397
+ "})",
1398
+ "",
1399
+ "export default () => {}",
1400
+ ""
1401
+ ].join("\n"));
1402
+ return [{
1403
+ handler: registry,
1404
+ plugin: true,
1405
+ position: "start"
1406
+ }];
1407
+ }
1408
+ /**
1293
1409
  * Find the `server/content.{ts,js}` file whose default export is the application Content runtime. Returns undefined when
1294
1410
  * the project has none. The generated `/api/content/**` route and the Console content editor import the same file.
1295
1411
  */
@@ -1543,6 +1659,7 @@ async function writeContentArtifact(options, file) {
1543
1659
  const llms = resolve(options.projectRoot, contentLlmsEntry);
1544
1660
  const sqlite = resolve(options.projectRoot, contentSqliteEntry);
1545
1661
  const githubWebhook = resolve(options.projectRoot, contentGitHubWebhookEntry);
1662
+ const prewarmQueue = resolve(options.projectRoot, contentPrewarmQueueEntry);
1546
1663
  const previewRoutes = resolve(options.projectRoot, contentPreviewRoutesEntry);
1547
1664
  const typesPlugin = resolve(options.projectRoot, contentTypesPluginEntry);
1548
1665
  const types = resolve(options.projectRoot, contentTypesEntry);
@@ -1558,6 +1675,7 @@ async function writeContentArtifact(options, file) {
1558
1675
  llms,
1559
1676
  sqlite,
1560
1677
  githubWebhook,
1678
+ prewarmQueue,
1561
1679
  previewRoutes,
1562
1680
  typesPlugin,
1563
1681
  types
@@ -1619,7 +1737,15 @@ async function writeContentArtifact(options, file) {
1619
1737
  route: "/api/content/**"
1620
1738
  });
1621
1739
  if (features.github) {
1622
- await writeFileIfChanged(githubWebhook, [
1740
+ const queueImport = JSON.stringify(options.queueImport ?? "@vite-hub/queue");
1741
+ await writeFileIfChanged(githubWebhook, options.queue ? [
1742
+ `import { defineContentGitHubWebhookHandler } from ${importBase}`,
1743
+ `import { dynamicQueue } from ${queueImport}`,
1744
+ `import content from ${contentModule}`,
1745
+ "",
1746
+ `export default defineContentGitHubWebhookHandler(content, { prewarm: job => dynamicQueue.send(${JSON.stringify(contentPrewarmQueue)}, job) })`,
1747
+ ""
1748
+ ].join("\n") : [
1623
1749
  `import { defineContentGitHubWebhookHandler } from ${importBase}`,
1624
1750
  `import content from ${contentModule}`,
1625
1751
  "",
@@ -1632,6 +1758,7 @@ async function writeContentArtifact(options, file) {
1632
1758
  route: "/_vitehub/content/github"
1633
1759
  });
1634
1760
  } else await rm(githubWebhook, { force: true });
1761
+ if (!features.github || !options.queue) await rm(prewarmQueue, { force: true });
1635
1762
  if (features.previews) {
1636
1763
  await writeFileIfChanged(previewRoutes, [
1637
1764
  `import { defineContentPreviewRoutesPlugin } from ${JSON.stringify(`${options.contentImportBase ?? "@vite-hub/content"}/preview`)}`,
@@ -1734,9 +1861,17 @@ async function writeContentArtifact(options, file) {
1734
1861
  return handlers;
1735
1862
  }
1736
1863
  async function prepareSourceArtifacts(options) {
1737
- const [collections, content] = await Promise.all([discoverCollections(options), findContentEntry(options)]);
1864
+ const [collections, content, sources] = await Promise.all([
1865
+ discoverCollections(options),
1866
+ findContentEntry(options),
1867
+ discoverSources(options)
1868
+ ]);
1738
1869
  return {
1739
- handlers: [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => (left.route ?? "").localeCompare(right.route ?? "")),
1870
+ handlers: [
1871
+ ...await writeSourceArtifacts(options, sources),
1872
+ ...await writeCollectionArtifacts(options, collections),
1873
+ ...await writeContentArtifact(options, content)
1874
+ ].sort((left, right) => (left.route ?? "").localeCompare(right.route ?? "")),
1740
1875
  ...content ? { content: { handler: content } } : {}
1741
1876
  };
1742
1877
  }
@@ -1775,7 +1910,7 @@ function sourceDefinitionPath(file, projectRoot, serverDirs) {
1775
1910
  return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs).some((directory) => {
1776
1911
  const path = relative(resolve(projectRoot, directory), resolve(file)).replaceAll("\\", "/");
1777
1912
  if (path.startsWith("../") || isAbsolute(path)) return false;
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);
1913
+ return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^auth\.(?:[cm]?[jt]s)$/.test(path) || /^(?:collections|sources)\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
1779
1914
  });
1780
1915
  }
1781
1916
  function hubSource(options = {}) {
@@ -1810,7 +1945,11 @@ function hubSource(options = {}) {
1810
1945
  auth,
1811
1946
  ...options.appSeo ? { appSeo: options.appSeo } : {},
1812
1947
  importBase: options.importBase,
1813
- contentImportBase: options.contentImportBase
1948
+ contentImportBase: options.contentImportBase,
1949
+ ...options.queue ? {
1950
+ queue: true,
1951
+ ...options.queueImport ? { queueImport: options.queueImport } : {}
1952
+ } : {}
1814
1953
  }).then(({ content, handlers }) => {
1815
1954
  if (content) contentDefinitionByRoot.set(root, content);
1816
1955
  else contentDefinitionByRoot.delete(root);
@@ -1906,17 +2045,42 @@ function hubSource(options = {}) {
1906
2045
  };
1907
2046
  }
1908
2047
  },
1909
- vitehub: { inspect: () => ({ definitions: [{
1910
- kind: "collection",
1911
- label: "Collections",
1912
- list: () => {
1913
- const projectRoot = latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd());
1914
- return inspectCollectionDefinitions({
2048
+ vitehub: {
2049
+ async queues(context) {
2050
+ if (!options.queue) return [];
2051
+ const projectRoot = resolve(context.projectRoot);
2052
+ const file = await findContentEntry({
1915
2053
  projectRoot,
1916
- serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
2054
+ ...context.serverDirs ? { serverDirs: [...context.serverDirs] } : {}
1917
2055
  });
1918
- }
1919
- }] }) },
2056
+ if (!file || !(await inspectContentEntry(file, options.contentImportBase)).github) return [];
2057
+ const module = resolve(projectRoot, contentPrewarmQueueEntry);
2058
+ await writeFileIfChanged(module, [
2059
+ `import { defineQueue } from ${JSON.stringify(options.queueImport ?? "@vite-hub/queue")}`,
2060
+ `import { prewarmContentPage } from ${JSON.stringify(options.contentImportBase ?? "@vite-hub/content")}`,
2061
+ `import content from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
2062
+ "",
2063
+ "export default defineQueue(job => prewarmContentPage(content, job.payload))",
2064
+ ""
2065
+ ].join("\n"));
2066
+ return [{
2067
+ name: contentPrewarmQueue,
2068
+ definition: { module },
2069
+ reason: "Prewarms the pages that a GitHub push changed, for the `github()` Sources of `server/content.ts`."
2070
+ }];
2071
+ },
2072
+ inspect: () => ({ definitions: [{
2073
+ kind: "collection",
2074
+ label: "Collections",
2075
+ list: () => {
2076
+ const projectRoot = latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd());
2077
+ return inspectCollectionDefinitions({
2078
+ projectRoot,
2079
+ serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
2080
+ });
2081
+ }
2082
+ }] })
2083
+ },
1920
2084
  nitro: {
1921
2085
  name: "@vite-hub/source/generated-routes",
1922
2086
  async setup(nitro) {