@vite-hub/docs 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +167 -7
  2. package/dist/{agent-copy-xPaWye_g.js → agent-copy-CY9_RkHN.js} +2 -3
  3. package/dist/{assistant-pages-BN7hNsSZ.js → assistant-pages-BbWfd69g.js} +3 -4
  4. package/dist/{assistant-shared-CWIKRtBv.d.ts → assistant-shared-BWeRcmVS.d.ts} +0 -2
  5. package/dist/{assistant-shared-WzButktj.js → assistant-shared-JcfjK-qg.js} +3 -4
  6. package/dist/assistant-worker.d.ts +1 -3
  7. package/dist/assistant-worker.js +2 -3
  8. package/dist/assistant.d.ts +1 -3
  9. package/dist/assistant.js +2 -3
  10. package/dist/{content-CPZGnn3S.js → content-C_WXjV3y.js} +60 -28
  11. package/dist/{draft-BjWmaiLn.js → draft-rOGhtXch.js} +3 -4
  12. package/dist/{error-diagnostics-B_ZOy7kF.js → error-diagnostics-Daz9oBJS.js} +65 -2
  13. package/dist/{files-UY4h1_36.js → files-BBoAGhhM.js} +1 -2
  14. package/dist/index.d.ts +7 -8
  15. package/dist/index.js +5 -6
  16. package/dist/link-checker-redirects.d.ts +0 -2
  17. package/dist/link-checker-redirects.js +2 -3
  18. package/dist/{manifest-ZdxLrcvt.js → manifest-Bti_WxDZ.js} +64 -30
  19. package/dist/{manifest-CMoxcwPm.d.ts → manifest-DJ2DyNue.d.ts} +1 -5
  20. package/dist/{page-Dx2JD3y1.d.ts → markdown-B97RuMXs.d.ts} +2 -27
  21. package/dist/{markdown-DUWnEMPp.js → markdown-BzZkYb24.js} +2 -3
  22. package/dist/navigation.d.ts +10 -6
  23. package/dist/navigation.js +23 -10
  24. package/dist/{nuxt-CAGpKl_-.d.ts → nuxt-CYAIBEHE.d.ts} +74 -8
  25. package/dist/nuxt.d.ts +3 -3
  26. package/dist/nuxt.js +1286 -89
  27. package/dist/page-B8_70-5D.d.ts +24 -0
  28. package/dist/{page-GPt09oex.js → page-DWsretqk.js} +20 -5
  29. package/dist/primitive-rail.d.ts +1 -10
  30. package/dist/primitive-rail.js +4 -10
  31. package/dist/{raw-BChwipz_.js → raw-CQukuLuj.js} +1 -2
  32. package/dist/{redirects-CmR1yu5A.js → redirects-BEFu4KLR.js} +35 -23
  33. package/dist/runnable.d.ts +33 -0
  34. package/dist/runnable.js +104 -0
  35. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  36. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  37. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  38. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  39. package/dist/runtime/app/components/DocsPage.vue +11 -5
  40. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  41. package/dist/runtime/app/components/content/Example.vue +18 -49
  42. package/dist/runtime/app/components/content/PageList.vue +1 -5
  43. package/dist/runtime/app/layouts/docs.vue +36 -8
  44. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  45. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  46. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  47. package/dist/runtime/server/llms.d.ts +0 -2
  48. package/dist/runtime/server/llms.js +2 -3
  49. package/dist/runtime/server/markdown.d.ts +0 -7
  50. package/dist/runtime/server/markdown.js +11 -3
  51. package/dist/runtime/server/mcp.d.ts +0 -2
  52. package/dist/runtime/server/mcp.js +2 -3
  53. package/dist/runtime/server/page.d.ts +1 -3
  54. package/dist/runtime/server/page.js +4 -5
  55. package/dist/runtime/server/raw.d.ts +0 -2
  56. package/dist/runtime/server/raw.js +3 -11
  57. package/dist/runtime/server/search.d.ts +1 -3
  58. package/dist/runtime/server/search.js +4 -4
  59. package/dist/runtime/server/sitemap.d.ts +0 -2
  60. package/dist/runtime/server/sitemap.js +3 -5
  61. package/dist/runtime/server/trailing-slash.d.ts +0 -2
  62. package/dist/runtime/server/trailing-slash.js +1 -2
  63. package/dist/schema-CmSiwC4t.js +189 -0
  64. package/dist/server.d.ts +3 -4
  65. package/dist/server.js +4 -4
  66. package/dist/snapshot-worker.mjs +40 -0
  67. package/dist/steps-C3tGwhNK.d.ts +103 -0
  68. package/dist/steps-muDP1nYT.js +31 -0
  69. package/dist/{theme-BXyu4uFL.d.ts → theme-CgJRnVdT.d.ts} +0 -4
  70. package/dist/{theme-DzC8LtMH.js → theme-CxBzPBZ9.js} +2 -4
  71. package/dist/theme.d.ts +1 -1
  72. package/dist/theme.js +1 -2
  73. package/dist/{types-BhG6vGfG.d.ts → types-B6YlHil4.d.ts} +69 -8
  74. package/package.json +40 -32
  75. package/dist/schema-DwpXW0VZ.js +0 -98
package/dist/nuxt.js CHANGED
@@ -1,28 +1,162 @@
1
- import { docsAppPath, docsIndexedPages, docsManifestPages, docsPageIcon, docsPageIndexed, docsRailIcon, docsRawPath, docsSectionIcon, isDocsPath, normalizeDocsBase, normalizeDocsPath } from "./navigation.js";
2
- import { a as replacesDocsPage, o as routePaths, t as docsMount } from "./page-GPt09oex.js";
3
- import { t as docsErrorDiagnostics } from "./error-diagnostics-B_ZOy7kF.js";
4
- import { i as docsServerRoutes, n as docsRedirectProblems, r as docsRedirects, t as docsRedirectError } from "./redirects-CmR1yu5A.js";
5
- import { a as docsAppManifestSource, c as resolveDocsSources, d as docsLinkExclusion, f as docsOutputFile, i as docsAppManifest, l as checkDocsLinks, n as createDocsContent, o as docsAppPanelSource, s as readDocsContent, t as contentName, u as docsLinkError } from "./manifest-ZdxLrcvt.js";
6
- import { r as docsContentSource } from "./agent-copy-xPaWye_g.js";
7
- import { i as docsThemeScope, n as docsThemeAdditions, r as docsUi, t as docsAppConfigUi } from "./theme-DzC8LtMH.js";
1
+ import { t as docsErrorDiagnostics } from "./error-diagnostics-Daz9oBJS.js";
2
+ import { t as dependencyKey } from "./steps-muDP1nYT.js";
3
+ import { a as docsAppManifestSource, c as resolveDocsSources, d as docsLinkExclusion, f as docsOutputFile, i as docsAppManifest, l as checkDocsLinks, n as createDocsContent, o as docsAppPanelSource, s as readDocsContent, t as contentName, u as docsLinkError } from "./manifest-Bti_WxDZ.js";
4
+ import { docsAppPath, docsIndexedPages, docsManifestPages, docsPageIcon, docsPageIndexed, docsRailIcon, docsRawPath, docsSectionIcon, isDocsPath, isDocsWorkspaceLayout, normalizeDocsBase, normalizeDocsPath } from "./navigation.js";
5
+ import { a as replacesDocsPage, o as routePaths, t as docsMount } from "./page-DWsretqk.js";
6
+ import { r as docsContentSource } from "./agent-copy-CY9_RkHN.js";
7
+ import { i as docsServerRoutes, n as docsRedirectProblems, r as docsRedirects, t as docsRedirectError } from "./redirects-BEFu4KLR.js";
8
+ import { i as docsThemeScope, n as docsThemeAdditions, r as docsUi, t as docsAppConfigUi } from "./theme-CxBzPBZ9.js";
8
9
  import { createRequire } from "node:module";
9
10
  import { addComponent, addComponentsDir, addImportsDir, addPlugin, addRouteMiddleware, addServerHandler, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, extendPages, updateTemplates, useLogger } from "@nuxt/kit";
10
11
  import { addRoute, createRouter, findAllRoutes, routeToRegExp } from "rou3";
11
12
  import { defineDiagnostics, formatDiagnostic } from "nostics";
12
13
  import { createHash } from "node:crypto";
13
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
14
- import { readFile, readdir } from "node:fs/promises";
15
- import { basename, dirname, join, parse, posix, relative, resolve, sep } from "node:path";
14
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
15
+ import { copyFile, glob, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
16
16
  import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { basename, dirname, isAbsolute, join, matchesGlob, parse, posix, relative, resolve, sep } from "node:path";
17
18
  import { tmpdir } from "node:os";
18
19
  import { findContentEntry } from "@vite-hub/source/vite";
19
20
  import { vitehubTheme } from "@vite-hub/ui/theme";
20
21
  import { sizeOf } from "comark-zoom/size";
21
22
  import { defu } from "defu";
22
- import { ELEMENT_NODE, parse as parse$1, walkSync } from "ultrahtml";
23
+ import { Buffer as Buffer$1 } from "node:buffer";
24
+ import { parse as parse$1 } from "yaml";
25
+ import { execFileSync, spawn } from "node:child_process";
26
+ import { ELEMENT_NODE, parse as parse$2, walkSync } from "ultrahtml";
23
27
  import { gzipSync } from "node:zlib";
24
28
  import postcss from "postcss";
25
- //#region ../internal/dist/build/vite.js
29
+ // ../internal/dist/invariant.js
30
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
31
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
32
+ codes: { INTERNAL_INVARIANT_FAILED: {
33
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
34
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
35
+ } }
36
+ });
37
+ /**
38
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
39
+ * Use a code from the package catalog when a developer can cause the error or fix it.
40
+ */
41
+ function invariantError(what) {
42
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
43
+ }
44
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
45
+ function invariant(condition, what) {
46
+ if (!condition) throw invariantError(what);
47
+ }
48
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
49
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
50
+ function normalizeWindowsPath(input = "") {
51
+ if (!input) return input;
52
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
53
+ }
54
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
55
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
56
+ function cwd() {
57
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
58
+ return "/";
59
+ }
60
+ const resolve$1 = function(...arguments_) {
61
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
62
+ let resolvedPath = "";
63
+ let resolvedAbsolute = false;
64
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
65
+ const path = index >= 0 ? arguments_[index] : cwd();
66
+ if (!path || path.length === 0) continue;
67
+ resolvedPath = `${path}/${resolvedPath}`;
68
+ resolvedAbsolute = isAbsolute$1(path);
69
+ }
70
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
71
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
72
+ return resolvedPath.length > 0 ? resolvedPath : ".";
73
+ };
74
+ function normalizeString(path, allowAboveRoot) {
75
+ let res = "";
76
+ let lastSegmentLength = 0;
77
+ let lastSlash = -1;
78
+ let dots = 0;
79
+ let char = null;
80
+ for (let index = 0; index <= path.length; ++index) {
81
+ if (index < path.length) char = path[index];
82
+ else if (char === "/") break;
83
+ else char = "/";
84
+ if (char === "/") {
85
+ if (lastSlash === index - 1 || dots === 1);
86
+ else if (dots === 2) {
87
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
88
+ if (res.length > 2) {
89
+ const lastSlashIndex = res.lastIndexOf("/");
90
+ if (lastSlashIndex === -1) {
91
+ res = "";
92
+ lastSegmentLength = 0;
93
+ } else {
94
+ res = res.slice(0, lastSlashIndex);
95
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
96
+ }
97
+ lastSlash = index;
98
+ dots = 0;
99
+ continue;
100
+ } else if (res.length > 0) {
101
+ res = "";
102
+ lastSegmentLength = 0;
103
+ lastSlash = index;
104
+ dots = 0;
105
+ continue;
106
+ }
107
+ }
108
+ if (allowAboveRoot) {
109
+ res += res.length > 0 ? "/.." : "..";
110
+ lastSegmentLength = 2;
111
+ }
112
+ } else {
113
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
114
+ else res = path.slice(lastSlash + 1, index);
115
+ lastSegmentLength = index - lastSlash - 1;
116
+ }
117
+ lastSlash = index;
118
+ dots = 0;
119
+ } else if (char === "." && dots !== -1) ++dots;
120
+ else dots = -1;
121
+ }
122
+ return res;
123
+ }
124
+ const isAbsolute$1 = function(p) {
125
+ return _IS_ABSOLUTE_RE.test(p);
126
+ };
127
+ const dirname$1 = function(p) {
128
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
129
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
130
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
131
+ };
132
+ // ../internal/dist/build/paths.js
133
+ function resolveRuntimeModule(packageDir, modulePath) {
134
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
135
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
136
+ }
137
+ const packageDirs = /* @__PURE__ */ new Map();
138
+ function findPackageDir(file) {
139
+ const start = dirname$1(file);
140
+ const cached = packageDirs.get(start);
141
+ if (cached) return cached;
142
+ let dir = start;
143
+ while (!existsSync(resolve$1(dir, "package.json"))) {
144
+ const parent = dirname$1(dir);
145
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
146
+ dir = parent;
147
+ }
148
+ packageDirs.set(start, dir);
149
+ return dir;
150
+ }
151
+ /**
152
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
153
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
154
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
155
+ */
156
+ function ownModule(importMetaUrl, modulePath) {
157
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
158
+ }
159
+ // ../internal/dist/vite-CELQZdD3.js
26
160
  const projectRootDirectoryMarkers = [
27
161
  ["server", "agents"],
28
162
  ["server", "channels"],
@@ -67,7 +201,7 @@ function hasProjectRootDirectoryMarker(root) {
67
201
  for (const marker of projectRootDirectoryMarkers) try {
68
202
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
69
203
  } catch (error) {
70
- if (error.code !== "ENOENT") throw error;
204
+ if (!isMissingProjectMarker(error)) throw error;
71
205
  }
72
206
  return false;
73
207
  }
@@ -81,13 +215,16 @@ function hasProjectRootFileMarker(root, markers) {
81
215
  try {
82
216
  if (statSync(resolve(root, ...path)).isFile()) return true;
83
217
  } catch (error) {
84
- if (error.code !== "ENOENT") throw error;
218
+ if (!isMissingProjectMarker(error)) throw error;
85
219
  }
86
220
  }
87
221
  return false;
88
222
  }
89
- //#endregion
90
- //#region ../internal/dist/hints.js
223
+ function isMissingProjectMarker(error) {
224
+ const code = error.code;
225
+ return code === "ENOENT" || code === "ENOTDIR";
226
+ }
227
+ // ../internal/dist/hints.js
91
228
  /**
92
229
  * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
93
230
  * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
@@ -165,24 +302,7 @@ function startViteHubHints(config, owner = config) {
165
302
  started.add(owner);
166
303
  write(startRun(config));
167
304
  }
168
- //#endregion
169
- //#region ../internal/dist/invariant.js
170
- const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
171
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
172
- codes: { INTERNAL_INVARIANT_FAILED: {
173
- why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
174
- fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
175
- } }
176
- });
177
- /**
178
- * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
179
- * Use a code from the package catalog when a developer can cause the error or fix it.
180
- */
181
- function invariantError(what) {
182
- return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
183
- }
184
- //#endregion
185
- //#region src/module-options.ts
305
+ // src/module-options.ts
186
306
  /** The module name: a string entry, or the `getMeta()` name of an imported module function. */
187
307
  async function moduleName(module) {
188
308
  if (typeof module !== "function") return module;
@@ -220,8 +340,7 @@ async function readModuleOptions(nuxt, names, configKey, requireInstalled = fals
220
340
  async function viteHubModuleOptions(nuxt) {
221
341
  return await readModuleOptions(nuxt, ["vite-hub/nuxt"], "vitehub", true);
222
342
  }
223
- //#endregion
224
- //#region src/assistant-nuxt.ts
343
+ // src/assistant-nuxt.ts
225
344
  /**
226
345
  * Checks what the docs assistant needs, when `docs.assistant` is on. The docs module calls it from its setup.
227
346
  *
@@ -239,8 +358,7 @@ function setupDocsAssistant(nuxt, config) {
239
358
  if (!(await viteHubModuleOptions(nuxt))?.agent) throw docsErrorDiagnostics.DOCS_ASSISTANT_AGENTS_MISSING({ agent: assistant.agent });
240
359
  });
241
360
  }
242
- //#endregion
243
- //#region src/comark-blocks.ts
361
+ // src/comark-blocks.ts
244
362
  /**
245
363
  * The source of a module whose default export is comark-ui's block components by tag, each one loaded on first use.
246
364
  * `comark-ui/vue` imports every block package, so a page that rendered with it downloaded all of them. Each tag imports
@@ -278,8 +396,7 @@ async function comarkBlocksSource() {
278
396
  return ` ${JSON.stringify(tag)}: defineAsyncComponent(() => import(${file}).then(module => ${map}[${JSON.stringify(tag)}])),`;
279
397
  }).join("\n")}\n}\n`;
280
398
  }
281
- //#endregion
282
- //#region src/comments-nuxt.ts
399
+ // src/comments-nuxt.ts
283
400
  /** Whether the app can import `name`, as `vite-hub` resolves its optional peers. */
284
401
  function installed(name, rootDir) {
285
402
  try {
@@ -292,10 +409,11 @@ function installed(name, rootDir) {
292
409
  /**
293
410
  * The module dependency that turns Comments on in `vite-hub/nuxt`. Comments keeps threads in a ViteHub Database, so a
294
411
  * site without `vite-hub/nuxt` has none unless it asks for them, which fails the build. `false` sets `comments: false`.
295
- * The dependency only sets defaults: the app's own `vitehub.comments` wins.
412
+ * The dependency only sets defaults: the app's own `vitehub.comments` wins, so `false` with Comments on in `vitehub` warns.
296
413
  */
297
414
  async function docsCommentsDependencies(nuxt, comments) {
298
415
  const vitehub = await viteHubModuleOptions(nuxt);
416
+ if (comments === false && vitehub?.comments !== void 0 && vitehub.comments !== false) useLogger("@vite-hub/docs").warn(formatDiagnostic(docsErrorDiagnostics.DOCS_COMMENTS_OFF_IGNORED()));
299
417
  if (comments === false) return vitehub ? { "vite-hub/nuxt": {
300
418
  optional: true,
301
419
  defaults: { comments: false }
@@ -312,8 +430,1029 @@ async function docsCommentsDependencies(nuxt, comments) {
312
430
  defaults: { comments: comments === void 0 || comments === true ? true : comments }
313
431
  } };
314
432
  }
315
- //#endregion
316
- //#region src/content-check.ts
433
+ // src/runnable/build.ts
434
+ const ignoredEntries = /* @__PURE__ */ new Set([
435
+ "node_modules",
436
+ ".output",
437
+ ".vitehub",
438
+ ".nitro",
439
+ ".data",
440
+ "dist"
441
+ ]);
442
+ /**
443
+ * Local files with secrets, in any folder: `.env` and `.env.*` but not `.env.example`, `.dev.vars*`, npm and netrc
444
+ * credentials, and keys. Workspace modules ship to the browser, so they never hold these.
445
+ */
446
+ function isPrivateFile(name) {
447
+ if (name === ".env.example") return false;
448
+ return name === ".env" || name.startsWith(".env.") || name.startsWith(".dev.vars") || name === ".npmrc" || name === ".netrc" || /\.(?:pem|key|p12|pfx)$/.test(name);
449
+ }
450
+ /** Labels of code blocks that are not files of the app, such as `commands/dev` and `output/response.json`. */
451
+ function isTutorialFileLabel(label) {
452
+ return !label.startsWith("commands/") && !label.startsWith("output/");
453
+ }
454
+ function codeBlockLabels(markdown) {
455
+ return [...markdown.matchAll(/^```[^\n[]*\[([^\]]+)\]/gm)].map((match) => match[1]);
456
+ }
457
+ function frontmatterField(markdown, field) {
458
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(markdown)?.[1] ?? "";
459
+ const value = parse$1(frontmatter)?.[field];
460
+ return typeof value === "string" ? value : "";
461
+ }
462
+ /**
463
+ * A page as a reader of one framework sees it: the content of that framework's tab stays, and the other tabs of every
464
+ * `::tabs{sync="framework"}` block go away. Runnable lessons run a Vite fixture, so they read the Vite view. A page
465
+ * without framework tabs stays as it is.
466
+ */
467
+ function frameworkView(markdown, framework) {
468
+ const lines = markdown.replaceAll("\r\n", "\n").split("\n");
469
+ const out = [];
470
+ for (let index = 0; index < lines.length; index++) {
471
+ const panel = /^(:{2,})framework\{name="([^"]+)"\}\s*$/.exec(lines[index]);
472
+ if (panel) {
473
+ for (index++; index < lines.length && lines[index].trim() !== panel[1]; index++) if (panel[2] === framework) out.push(lines[index]);
474
+ continue;
475
+ }
476
+ const tabs = /^(:{2,})tabs\{[^}]*sync="framework"[^}]*\}\s*$/.exec(lines[index]);
477
+ if (!tabs) {
478
+ out.push(lines[index]);
479
+ continue;
480
+ }
481
+ const colons = tabs[1];
482
+ let keep = false;
483
+ for (index++; index < lines.length && lines[index].trim() !== colons; index++) {
484
+ const line = lines[index];
485
+ const item = new RegExp(`^${colons}:tabs-item\\{[^}]*label="([^"]*)"`).exec(line);
486
+ if (item) keep = item[1] === framework;
487
+ else if (line.trim() === `${colons}:`) keep = false;
488
+ else if (keep) out.push(line);
489
+ }
490
+ }
491
+ return out.join("\n");
492
+ }
493
+ /** The `::tutorial-step` blocks of a page, in order, with the file labels of their code blocks. */
494
+ function parseTutorialSteps(markdown) {
495
+ const steps = [];
496
+ markdown = frameworkView(markdown, "Vite");
497
+ for (const match of markdown.matchAll(/^::tutorial-step\{([^}]*)\}\n([\s\S]*?)^::$/gm)) {
498
+ const title = /title="([^"]*)"/.exec(match[1])?.[1];
499
+ if (!title) throw docsErrorDiagnostics.DOCS_RUNNABLE_TITLE_MISSING({ block: `::tutorial-step{${match[1]}}` });
500
+ steps.push({
501
+ title,
502
+ labels: codeBlockLabels(match[2]).filter(isTutorialFileLabel)
503
+ });
504
+ }
505
+ return steps;
506
+ }
507
+ /** The code block of `label` in a page, without its fences. */
508
+ function codeBlock(markdown, label) {
509
+ markdown = frameworkView(markdown, "Vite");
510
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
511
+ const match = new RegExp("^```[^\\n]*\\[" + escaped + "\\]\\n([\\s\\S]*?)\\n```", "m").exec(markdown);
512
+ return match ? `${match[1]}\n` : void 0;
513
+ }
514
+ /** Whether `entry`, a name in a fixture folder, is a generated or installed file that the workspace makes itself. */
515
+ function isIgnoredEntry(entry) {
516
+ return ignoredEntries.has(entry);
517
+ }
518
+ /**
519
+ * The text of a file, with its BOM, or `undefined` for a binary file: bytes that are not valid UTF-8, or that hold a
520
+ * NUL byte, such as WebAssembly modules and model weights.
521
+ */
522
+ function decodeText(bytes) {
523
+ if (bytes.includes(0)) return void 0;
524
+ try {
525
+ return new TextDecoder("utf-8", {
526
+ fatal: true,
527
+ ignoreBOM: true
528
+ }).decode(bytes);
529
+ } catch {
530
+ return;
531
+ }
532
+ }
533
+ /**
534
+ * The files of a fixture folder, without generated, installed or private files: the text files in `files`, and the files
535
+ * that are not valid UTF-8, such as model weights, in `assets`.
536
+ */
537
+ async function readTree(root) {
538
+ const files = {};
539
+ const assets = {};
540
+ async function walk(directory) {
541
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
542
+ if (ignoredEntries.has(entry.name) || entry.isFile() && isPrivateFile(entry.name)) continue;
543
+ const path = join(directory, entry.name);
544
+ if (entry.isDirectory()) await walk(path);
545
+ else if (entry.isFile()) {
546
+ const name = relative(root, path).replaceAll("\\", "/");
547
+ const bytes = new Uint8Array(await readFile(path));
548
+ const text = decodeText(bytes);
549
+ if (text === void 0) assets[name] = bytes;
550
+ else files[name] = text;
551
+ }
552
+ }
553
+ }
554
+ await walk(root);
555
+ return {
556
+ files,
557
+ assets
558
+ };
559
+ }
560
+ /** No pnpm workspace: `catalog:` and `workspace:` specifiers fail, and every dependency installs from npm. */
561
+ const noWorkspaceVersions = {
562
+ catalogs: {},
563
+ packages: {}
564
+ };
565
+ async function readPnpmWorkspace(root) {
566
+ const workspace = parse$1(await readFile(resolve(root, "pnpm-workspace.yaml"), "utf8"));
567
+ return workspace && typeof workspace === "object" ? workspace : {};
568
+ }
569
+ const isNodeModules = (path) => path.split(/[\\/]/).includes("node_modules");
570
+ /**
571
+ * The folders of the workspace packages, sorted, as pnpm finds them: the root and each folder with a `package.json`
572
+ * that a `packages` pattern of `pnpm-workspace.yaml` matches and no `!` pattern excludes.
573
+ */
574
+ async function workspacePackageDirs(root) {
575
+ const { packages } = await readPnpmWorkspace(root);
576
+ const patterns = Array.isArray(packages) ? packages.filter((pattern) => typeof pattern === "string").map((pattern) => pattern.replace(/\/+$/, "")) : [];
577
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
578
+ const included = patterns.filter((pattern) => !pattern.startsWith("!")).map((pattern) => `${pattern}/package.json`);
579
+ const dirs = /* @__PURE__ */ new Set();
580
+ for await (const file of glob(["package.json", ...included], {
581
+ cwd: root,
582
+ exclude: isNodeModules
583
+ })) {
584
+ const dir = file.replaceAll("\\", "/").replace(/\/?package\.json$/, "");
585
+ if (!excluded.some((pattern) => matchesGlob(dir, pattern))) dirs.add(resolve(root, dir));
586
+ }
587
+ return [...dirs].sort();
588
+ }
589
+ /** Reads the pnpm catalogs and the versions of the workspace packages that fixtures depend on. */
590
+ async function readWorkspaceVersions(root) {
591
+ const record = await readPnpmWorkspace(root);
592
+ const catalogs = {};
593
+ if (record.catalog && typeof record.catalog === "object") catalogs.default = record.catalog;
594
+ if (record.catalogs && typeof record.catalogs === "object") Object.assign(catalogs, record.catalogs);
595
+ const packages = {};
596
+ for (const dir of await workspacePackageDirs(root)) {
597
+ const manifest = await readFile(resolve(dir, "package.json"), "utf8").then(JSON.parse, () => void 0);
598
+ if (!manifest || typeof manifest !== "object") continue;
599
+ const { name, version } = manifest;
600
+ if (typeof name === "string" && typeof version === "string") packages[name] = version;
601
+ }
602
+ return {
603
+ catalogs,
604
+ packages
605
+ };
606
+ }
607
+ const isStringRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
608
+ /**
609
+ * Rewrites `catalog:` and `workspace:` specifiers to npm versions, so `npm install` works outside the pnpm workspace.
610
+ * A workspace package resolves to the published range of its current version.
611
+ */
612
+ function resolveDependencies(dependencies, versions) {
613
+ const resolved = {};
614
+ for (const [name, specifier] of Object.entries(dependencies)) if (specifier.startsWith("catalog:")) {
615
+ const catalog = specifier.slice(8) || "default";
616
+ const version = versions.catalogs[catalog]?.[name];
617
+ if (!version) throw docsErrorDiagnostics.DOCS_RUNNABLE_CATALOG_VERSION_MISSING({
618
+ catalog,
619
+ name
620
+ });
621
+ resolved[name] = version;
622
+ } else if (specifier.startsWith("workspace:")) {
623
+ const version = versions.packages[name];
624
+ if (!version) throw docsErrorDiagnostics.DOCS_RUNNABLE_WORKSPACE_PACKAGE_MISSING({ name });
625
+ resolved[name] = `^${version}`;
626
+ } else resolved[name] = specifier;
627
+ return resolved;
628
+ }
629
+ /** A `package.json` with the `dependencies` and `devDependencies` of `resolveDependencies()`. Other JSON stays as it is. */
630
+ function resolveManifest(source, versions) {
631
+ const manifest = JSON.parse(source);
632
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) return source;
633
+ const resolved = { ...manifest };
634
+ for (const field of ["dependencies", "devDependencies"]) {
635
+ const dependencies = resolved[field];
636
+ if (isStringRecord(dependencies)) resolved[field] = resolveDependencies(dependencies, versions);
637
+ }
638
+ return `${JSON.stringify(resolved, null, 2)}\n`;
639
+ }
640
+ /**
641
+ * Builds the workspace files of one lesson.
642
+ *
643
+ * The fixture is the app after the last step, and every file code block in the lesson equals a fixture file. So step N
644
+ * writes the fixture version of the files that its code blocks name. Before step 1 the app is the fixture without those
645
+ * files, except where the `start` page already shows a version, such as `vite.config.ts`.
646
+ */
647
+ async function buildRunnableTutorial(input) {
648
+ const { source, fixturesDir, versions } = input;
649
+ const readPage = (page) => {
650
+ const markdown = input.readPage(page);
651
+ if (markdown === void 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_PAGE_MISSING({ page });
652
+ return markdown.replaceAll("\r\n", "\n");
653
+ };
654
+ const lesson = readPage(source.page);
655
+ const start = input.start ? readPage(input.start) : "";
656
+ const { files: fixture } = await readTree(resolve(fixturesDir, source.fixture));
657
+ if (fixture["package.json"]) fixture["package.json"] = resolveManifest(fixture["package.json"], versions);
658
+ const parsed = parseTutorialSteps(lesson);
659
+ if (parsed.length === 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_STEPS_MISSING({ page: source.page });
660
+ const files = { ...fixture };
661
+ const steps = parsed.map(({ title, labels }) => {
662
+ const stepFiles = {};
663
+ for (const label of labels) {
664
+ const contents = fixture[label];
665
+ if (contents === void 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_FIXTURE_FILE_MISSING({
666
+ fixture: source.fixture,
667
+ label,
668
+ page: source.page
669
+ });
670
+ stepFiles[label] = contents;
671
+ }
672
+ return {
673
+ title,
674
+ files: stepFiles
675
+ };
676
+ });
677
+ for (const step of steps) for (const path of Object.keys(step.files)) {
678
+ const before = codeBlock(start, path);
679
+ if (before === void 0) delete files[path];
680
+ else files[path] = before;
681
+ }
682
+ return {
683
+ slug: source.slug,
684
+ page: source.page,
685
+ title: frontmatterField(lesson, "title"),
686
+ description: frontmatterField(lesson, "description"),
687
+ files,
688
+ steps
689
+ };
690
+ }
691
+ // src/runnable/workspaces.ts
692
+ /** The `playground` and `learn` pages of the site. */
693
+ function workspacePages(pages) {
694
+ return pages.filter((page) => (page.layout === "playground" || page.layout === "learn") && !!page.workspace);
695
+ }
696
+ /**
697
+ * The paths that must be cross-origin isolated: each `learn` page, and each `playground` page without `render`. A
698
+ * WebContainer runs only there. A `render` page runs in the page, so it stays a plain page.
699
+ */
700
+ function webContainerRoutes(pages) {
701
+ return workspacePages(pages).filter((page) => page.layout === "learn" || !page.workspace.render).map((page) => page.path);
702
+ }
703
+ /**
704
+ * The id of a page in file names, snapshot names, and zip names: `/learn/first-kv` is `learn-first-kv`. It has no
705
+ * `--`, so the ids of a page's examples, `<page id>--<example id>`, never start with the id of another page.
706
+ */
707
+ function workspacePageSlug(path) {
708
+ return path.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "index";
709
+ }
710
+ /** Fails the build when two pages get one id, such as `/docs/a/b` and `/docs/a-b`. */
711
+ function checkWorkspacePageIds(pages) {
712
+ const seen = /* @__PURE__ */ new Map();
713
+ for (const page of pages) {
714
+ const id = workspacePageSlug(page.path);
715
+ const other = seen.get(id);
716
+ if (other !== void 0) throw docsErrorDiagnostics.DOCS_WORKSPACE_ID_COLLISION({
717
+ id,
718
+ owners: [`the page ${other}`, `the page ${page.path}`]
719
+ });
720
+ seen.set(id, page.path);
721
+ }
722
+ }
723
+ /**
724
+ * Fails the build when two lessons, two examples, or two snapshots get one id, configured or from a page. A configured
725
+ * lesson `learn-first-kv` and the page `/learn/first-kv` collide, and so do the lesson of `/playground/kv` and the
726
+ * snapshot `playground-kv` of an example `kv`.
727
+ */
728
+ function checkRunnableIds(lessons, examples) {
729
+ const seen = /* @__PURE__ */ new Map();
730
+ const claim = (kind, id, owner) => {
731
+ const key = `${kind} ${id.toLowerCase()}`;
732
+ const other = seen.get(key);
733
+ if (other !== void 0) throw docsErrorDiagnostics.DOCS_WORKSPACE_ID_COLLISION({
734
+ id,
735
+ owners: [other, owner]
736
+ });
737
+ seen.set(key, owner);
738
+ };
739
+ for (const lesson of lessons) claim("snapshot", lesson.slug, `the lesson ${lesson.slug} of ${lesson.page}`);
740
+ for (const example of examples) {
741
+ claim("example", example.id, `the example ${example.id}`);
742
+ claim("snapshot", `playground-${example.id}`, `the example ${example.id}`);
743
+ }
744
+ }
745
+ /** The lesson of a `learn` page: its steps come from `lesson`, or from the page itself. */
746
+ function learnLessonSource(page) {
747
+ return {
748
+ slug: workspacePageSlug(page.path),
749
+ page: page.workspace.lesson ?? page.path,
750
+ fixture: page.workspace.fixture ?? ""
751
+ };
752
+ }
753
+ const exampleSeparator = "--";
754
+ /**
755
+ * The examples of a `playground` page that runs a WebContainer, as playground sources. They share the snapshot of a
756
+ * lesson or of another example with the same dependencies. The id names the page, so two pages can use one example id.
757
+ */
758
+ function playgroundExampleSources(page, rootDir) {
759
+ return (page.workspace.examples ?? []).map((example) => ({
760
+ id: `${workspacePageSlug(page.path)}${exampleSeparator}${example.id}`,
761
+ label: example.label,
762
+ description: example.description,
763
+ group: example.group,
764
+ fixture: resolve(rootDir, example.dir),
765
+ open: example.open,
766
+ preview: example.preview,
767
+ readonly: example.readonly
768
+ }));
769
+ }
770
+ function isTextFileOf(dir, path) {
771
+ const parts = path.split("/");
772
+ if (isAbsolute(path) || path.includes("\\") || parts.some((part) => part === "" || part === "." || part === ".." || isIgnoredEntry(part)) || isPrivateFile(parts.at(-1))) return false;
773
+ if (parts.map((_, index) => lstatSync(resolve(dir, ...parts.slice(0, index + 1)), { throwIfNoEntry: false })).some((stat, index) => !(index === parts.length - 1 ? stat?.isFile() : stat?.isDirectory()))) return false;
774
+ return decodeText(readFileSync(resolve(dir, path))) !== void 0;
775
+ }
776
+ /**
777
+ * Fails the build for a folder, a `render` module, or a tab component that a page names and that does not exist, and
778
+ * for a `readonly` path that is not a text file of its example.
779
+ */
780
+ function checkWorkspacePage(page, input) {
781
+ const { workspace } = page;
782
+ const dirs = page.layout === "learn" ? [resolve(input.fixturesDir, workspace.fixture ?? "")] : (workspace.examples ?? []).map((example) => resolve(input.rootDir, example.dir));
783
+ for (const dir of dirs) if (!existsSync(dir)) throw docsErrorDiagnostics.DOCS_WORKSPACE_DIR_MISSING({
784
+ page: page.path,
785
+ dir
786
+ });
787
+ for (const example of workspace.examples ?? []) {
788
+ const dir = resolve(input.rootDir, example.dir);
789
+ for (const path of example.readonly ?? []) if (!isTextFileOf(dir, path)) throw docsErrorDiagnostics.DOCS_WORKSPACE_READONLY_MISSING({
790
+ page: page.path,
791
+ example: example.id,
792
+ path,
793
+ dir: example.dir
794
+ });
795
+ }
796
+ if (workspace.render && !existsSync(resolve(input.rootDir, workspace.render))) throw docsErrorDiagnostics.DOCS_WORKSPACE_RENDER_MISSING({
797
+ page: page.path,
798
+ file: workspace.render
799
+ });
800
+ for (const tab of workspace.tabs ?? []) {
801
+ const file = workspaceTabComponent(input.srcDir, tab.value);
802
+ if (!existsSync(file)) throw docsErrorDiagnostics.DOCS_WORKSPACE_TAB_MISSING({
803
+ page: page.path,
804
+ tab: tab.value,
805
+ file
806
+ });
807
+ }
808
+ }
809
+ /** The component of a tab: `messages` is `<srcDir>/components/playground/PlaygroundTabMessages.vue`. */
810
+ function workspaceTabComponent(srcDir, value) {
811
+ const name = value.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
812
+ return resolve(srcDir, "components/playground", `PlaygroundTab${name}.vue`);
813
+ }
814
+ /** The examples of a `render` page, with their files and binary files. They need no snapshot. */
815
+ async function renderExamples(page, rootDir) {
816
+ return Promise.all((page.workspace.examples ?? []).map(async (example) => {
817
+ const { files, assets } = await readTree(resolve(rootDir, example.dir));
818
+ const { id, label, description, group, open, preview, readonly } = example;
819
+ return {
820
+ id,
821
+ label,
822
+ description,
823
+ group,
824
+ open,
825
+ preview,
826
+ readonly,
827
+ files,
828
+ ...Object.keys(assets).length ? { assets } : {}
829
+ };
830
+ }));
831
+ }
832
+ /** The examples of a WebContainer page from the built templates, with their own ids again. */
833
+ function pageExamples(page, templates) {
834
+ const prefix = `${workspacePageSlug(page.path)}${exampleSeparator}`;
835
+ return templates.filter((template) => template.id.startsWith(prefix)).map((template) => ({
836
+ ...template,
837
+ id: template.id.slice(prefix.length)
838
+ }));
839
+ }
840
+ const decodeAssets = [
841
+ `const bytes = text => Uint8Array.from(atob(text), char => char.charCodeAt(0))`,
842
+ `for (const example of data.examples) {`,
843
+ ` const encoded = Object.hasOwn(assets, example.id) ? assets[example.id] : undefined`,
844
+ ` if (encoded) example.assets = Object.fromEntries(Object.entries(encoded).map(([path, text]) => [path, bytes(text)]))`,
845
+ `}`
846
+ ];
847
+ /**
848
+ * The JavaScript of a page module. `render` and the tab components are imports, so the page loads them with its data
849
+ * and Vite bundles them with the app. JSON has no bytes, so the binary files of the examples are base64 in the module,
850
+ * and the module decodes them when it loads.
851
+ */
852
+ function workspacePageModule(data, loaders = {}) {
853
+ if (data.layout === "learn") return pageModule(data, loaders);
854
+ const assets = {};
855
+ const examples = data.examples.map(({ assets: bytes, ...example }) => {
856
+ if (bytes) assets[example.id] = Object.fromEntries(Object.entries(bytes).map(([path, contents]) => [path, Buffer$1.from(contents).toString("base64")]));
857
+ return example;
858
+ });
859
+ return pageModule({
860
+ ...data,
861
+ examples
862
+ }, loaders, Object.keys(assets).length ? [`const assets = ${JSON.stringify(assets)}`, ...decodeAssets] : []);
863
+ }
864
+ function pageModule(data, loaders, decode = []) {
865
+ const lines = [`const data = ${JSON.stringify(data)}`, ...decode];
866
+ if (loaders.render) lines.push(`data.render = () => import(${JSON.stringify(loaders.render)})`);
867
+ if (loaders.tabs?.length) lines.push(`data.tabs = [`, ...loaders.tabs.map((tab) => ` { value: ${JSON.stringify(tab.value)}, label: ${JSON.stringify(tab.label)}, component: () => import(${JSON.stringify(tab.file)}) },`), `]`);
868
+ lines.push("export default data", "");
869
+ return lines.join("\n");
870
+ }
871
+ // src/workspace-nuxt.ts
872
+ /**
873
+ * The `webContainer` defaults of `vite-hub/nuxt` for the pages that run a WebContainer. `vite-hub/nuxt` sends the
874
+ * cross-origin isolation headers on these routes only. The defaults merge with the app's own `vitehub.webContainer.routes`,
875
+ * and they reach `vite-hub/nuxt` in either module order. Without such pages there are none.
876
+ */
877
+ async function docsWebContainerDefaults(nuxt, routes) {
878
+ if (routes.length === 0) return void 0;
879
+ if (!await viteHubModuleOptions(nuxt)) throw docsErrorDiagnostics.DOCS_WORKSPACE_VITEHUB_MISSING({ pages: routes });
880
+ return { webContainer: { routes: [...routes] } };
881
+ }
882
+ // src/runnable/learn.ts
883
+ /**
884
+ * Reading at 200 words a minute, plus 2 minutes to do each step, rounded up to 5 minutes.
885
+ * Code blocks do not count as reading, because the reader copies or opens them.
886
+ */
887
+ function tutorialMinutes(markdown) {
888
+ const words = markdown.replace(/^```[\s\S]*?^```/gm, "").replace(/^---[\s\S]*?^---/m, "").split(/\s+/).filter(Boolean).length;
889
+ const steps = tutorialSteps(markdown);
890
+ return Math.max(5, Math.ceil((words / 200 + steps * 2) / 5) * 5);
891
+ }
892
+ function tutorialSteps(markdown) {
893
+ return markdown.match(/^::tutorial-step\b/gm)?.length ?? 0;
894
+ }
895
+ /** The facts of a page with `layout: tutorial`, from its Markdown. */
896
+ function tutorialPageFacts(markdown) {
897
+ markdown = markdown.replaceAll("\r\n", "\n");
898
+ return {
899
+ steps: tutorialSteps(markdown),
900
+ minutes: tutorialMinutes(markdown)
901
+ };
902
+ }
903
+ // src/runnable/playground.ts
904
+ /**
905
+ * Reads the files of each example from its fixture.
906
+ *
907
+ * A snapshot holds the `dependencies` of a fixture. An example whose fixture has the same dependencies as the fixture
908
+ * of a lesson names that lesson in `snapshotOf`, so the playground mounts the same snapshot and the browser keeps one
909
+ * copy. Any other example names `playground-<id>` of the first example with its dependencies, and `snapshotSources`
910
+ * adds a snapshot for it.
911
+ */
912
+ async function buildPlaygroundTemplates(input) {
913
+ const manifest = (fixture) => readFile(resolve(input.fixturesDir, fixture, "package.json"), "utf8").catch(() => void 0);
914
+ const tutorialKeys = await Promise.all(input.tutorials.map(async (tutorial) => ({
915
+ slug: tutorial.slug,
916
+ key: dependencyKey(await manifest(tutorial.fixture))
917
+ })));
918
+ const read = await Promise.all(input.examples.map(async (source) => {
919
+ const { files, assets } = await readTree(resolve(input.fixturesDir, source.fixture));
920
+ if (files["package.json"]) files["package.json"] = resolveManifest(files["package.json"], input.versions);
921
+ return {
922
+ source,
923
+ files,
924
+ assets,
925
+ key: dependencyKey(await manifest(source.fixture))
926
+ };
927
+ }));
928
+ const shared = new Map(tutorialKeys.toReversed().map((tutorial) => [tutorial.key, tutorial.slug]));
929
+ return read.map(({ source, files, assets, key }) => {
930
+ const snapshotOf = shared.get(key) ?? `playground-${source.id}`;
931
+ shared.set(key, snapshotOf);
932
+ const { id, label, description, group, open, preview, readonly } = source;
933
+ return {
934
+ id,
935
+ label,
936
+ description,
937
+ group,
938
+ open,
939
+ preview,
940
+ readonly,
941
+ files,
942
+ ...Object.keys(assets).length ? { assets } : {},
943
+ snapshotOf
944
+ };
945
+ });
946
+ }
947
+ /** The lessons, and a source for each example that shares no snapshot with a lesson. */
948
+ function snapshotSources(tutorials, examples, templates) {
949
+ const own = templates.filter((template) => template.snapshotOf === `playground-${template.id}`);
950
+ return [...tutorials, ...own.map((template) => {
951
+ const example = examples.find((source) => source.id === template.id);
952
+ if (!example) throw invariantError(`a playground template comes from an example (${template.id})`);
953
+ return {
954
+ slug: template.snapshotOf,
955
+ page: "/playground",
956
+ fixture: example.fixture
957
+ };
958
+ })];
959
+ }
960
+ // src/runnable/snapshots.ts
961
+ const SNAPSHOT_CONCURRENCY = 3;
962
+ /** Runs `snapshot-worker.mjs` and returns its stdout. Its warnings, such as an updated lockfile, go to stderr. */
963
+ function runSnapshotWorker(args) {
964
+ return new Promise((resolvePromise, reject) => {
965
+ const child = spawn(process.execPath, [resolve(import.meta.dirname, "snapshot-worker.mjs"), ...args], { stdio: [
966
+ "ignore",
967
+ "pipe",
968
+ "inherit"
969
+ ] });
970
+ let stdout = "";
971
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
972
+ stdout += chunk;
973
+ });
974
+ child.once("error", reject);
975
+ child.once("close", (code) => code === 0 ? resolvePromise(stdout) : reject(/* @__PURE__ */ new Error(`snapshot-worker.mjs exited with code ${code} for ${args[2]}.`)));
976
+ });
977
+ }
978
+ /** The npm lockfile that pins the install of a fixture: `<fixture>.package-lock.json` beside the fixture folder. */
979
+ function tutorialLockfile(fixturesDir, fixture) {
980
+ return resolve(fixturesDir, `${fixture}.package-lock.json`);
981
+ }
982
+ const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
983
+ const stringRecord = (value) => isRecord(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : {};
984
+ /** The fields of a `package.json` that a snapshot reads. Other values, and invalid JSON, read as empty. */
985
+ function readManifest(source) {
986
+ let json;
987
+ try {
988
+ json = source === void 0 ? void 0 : JSON.parse(source);
989
+ } catch {
990
+ json = void 0;
991
+ }
992
+ const record = isRecord(json) ? json : {};
993
+ const meta = isRecord(record.peerDependenciesMeta) ? record.peerDependenciesMeta : {};
994
+ return {
995
+ name: typeof record.name === "string" ? record.name : void 0,
996
+ private: record.private === true,
997
+ scripts: stringRecord(record.scripts),
998
+ dependencies: stringRecord(record.dependencies),
999
+ devDependencies: stringRecord(record.devDependencies),
1000
+ peerDependencies: stringRecord(record.peerDependencies),
1001
+ optionalPeers: new Set(Object.entries(meta).filter(([, value]) => isRecord(value) && value.optional === true).map(([name]) => name))
1002
+ };
1003
+ }
1004
+ /**
1005
+ * The package that the `dev` script of a fixture runs, when it is in `devDependencies`. A snapshot installs
1006
+ * `dependencies` only, so the workspace could not start that dev server.
1007
+ */
1008
+ function devServerInDevDependencies(manifest) {
1009
+ const command = manifest.scripts.dev?.trim().split(/\s+/)[0];
1010
+ return command && command in manifest.devDependencies && !(command in manifest.dependencies) ? command : void 0;
1011
+ }
1012
+ /** The output line of `snapshot-worker.mjs`. */
1013
+ function readWorkerResult(stdout) {
1014
+ const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "");
1015
+ if (isRecord(result) && Array.isArray(result.files) && result.files.every((file) => typeof file === "string") && typeof result.sha256 === "string" && typeof result.bytes === "number" && typeof result.compressed === "number") return {
1016
+ files: result.files,
1017
+ sha256: result.sha256,
1018
+ bytes: result.bytes,
1019
+ compressed: result.compressed
1020
+ };
1021
+ throw invariantError(`snapshot-worker.mjs prints its files, hash, and sizes as its last line (${stdout.slice(-200)})`);
1022
+ }
1023
+ const dependencyFields = [
1024
+ "dependencies",
1025
+ "devDependencies",
1026
+ "optionalDependencies",
1027
+ "peerDependencies",
1028
+ "peerDependenciesMeta"
1029
+ ];
1030
+ /**
1031
+ * `pnpm pack` writes the dependencies that had `workspace:` specifiers in a different order on each run. The installed
1032
+ * `package.json` would then change the snapshot bytes, so sort those fields and pack the tarball again.
1033
+ */
1034
+ async function sortPackedManifest(tarball, scratch) {
1035
+ await rm(scratch, {
1036
+ recursive: true,
1037
+ force: true
1038
+ });
1039
+ await mkdir(scratch, { recursive: true });
1040
+ execFileSync("tar", [
1041
+ "-xzf",
1042
+ tarball,
1043
+ "-C",
1044
+ scratch
1045
+ ]);
1046
+ const path = resolve(scratch, "package/package.json");
1047
+ const manifest = JSON.parse(await readFile(path, "utf8"));
1048
+ for (const field of dependencyFields) {
1049
+ const value = manifest[field];
1050
+ if (value && typeof value === "object") manifest[field] = Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
1051
+ }
1052
+ await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`);
1053
+ execFileSync("tar", [
1054
+ "-czf",
1055
+ tarball,
1056
+ "-C",
1057
+ scratch,
1058
+ "package"
1059
+ ]);
1060
+ await rm(scratch, {
1061
+ recursive: true,
1062
+ force: true
1063
+ });
1064
+ }
1065
+ /**
1066
+ * A hash of everything that decides what a snapshot installs: the fixture manifests, the npm lockfiles of the
1067
+ * fixtures, and with a pnpm workspace its catalogs, its lockfile, and the manifest of every workspace package. Source
1068
+ * code is not in it: a dev server reuses a snapshot with older package code until `TUTORIAL_SNAPSHOTS=1` rebuilds it.
1069
+ */
1070
+ async function tutorialSnapshotInputs(input) {
1071
+ const hash = createHash("sha256");
1072
+ const add = (label, contents) => hash.update(`${label}\0${contents}\0`);
1073
+ const read = (path) => readFile(path, "utf8").catch(() => "");
1074
+ add("versions", JSON.stringify(input.versions));
1075
+ for (const tutorial of input.tutorials) {
1076
+ add(`${tutorial.slug} fixture`, await read(resolve(input.fixturesDir, tutorial.fixture, "package.json")));
1077
+ add(`${tutorial.slug} lockfile`, await read(tutorialLockfile(input.fixturesDir, tutorial.fixture)));
1078
+ }
1079
+ if (input.workspaceRoot) {
1080
+ add("pnpm-lock.yaml", await read(resolve(input.workspaceRoot, "pnpm-lock.yaml")));
1081
+ for (const dir of await workspacePackageDirs(input.workspaceRoot)) add(relative(input.workspaceRoot, dir).replaceAll("\\", "/"), await read(resolve(dir, "package.json")));
1082
+ }
1083
+ return hash.digest("hex");
1084
+ }
1085
+ /**
1086
+ * Reads the snapshots of the last build when they were built from `inputs`. Removes them, and returns nothing, when
1087
+ * snapshots are disabled.
1088
+ */
1089
+ async function readTutorialSnapshots(outDir, options) {
1090
+ if (options.disabled) {
1091
+ await rm(resolve(outDir, "snapshots"), {
1092
+ recursive: true,
1093
+ force: true
1094
+ });
1095
+ await rm(resolve(outDir, "snapshots.json"), { force: true });
1096
+ return;
1097
+ }
1098
+ const file = await readFile(resolve(outDir, "snapshots.json"), "utf8").then(JSON.parse, () => void 0);
1099
+ return file?.inputs === options.inputs ? file.tutorials : void 0;
1100
+ }
1101
+ /**
1102
+ * Builds the `node_modules` snapshot of each tutorial, so its workspace skips `npm install` in the browser.
1103
+ *
1104
+ * With a pnpm workspace, this builds and packs the workspace packages that each fixture uses, so the snapshot holds
1105
+ * the code that the docs describe. It installs them with the other dependencies of the fixture through
1106
+ * `createNodeModulesSnapshot` in `snapshot-worker.mjs`, pinned by the npm lockfile beside the fixture, and writes the
1107
+ * gzip parts to `<outDir>/snapshots/` with `snapshots.json` beside them. A build that resolves new versions writes the
1108
+ * lockfile.
1109
+ */
1110
+ async function buildTutorialSnapshots(input) {
1111
+ const { workspaceRoot, outDir, workDir } = input;
1112
+ const workspace = /* @__PURE__ */ new Map();
1113
+ for (const dir of workspaceRoot ? await workspacePackageDirs(workspaceRoot) : []) {
1114
+ const manifest = readManifest(await readFile(resolve(dir, "package.json"), "utf8").catch(() => void 0));
1115
+ if (manifest.name) workspace.set(manifest.name, {
1116
+ dir,
1117
+ manifest
1118
+ });
1119
+ }
1120
+ const closure = (names) => {
1121
+ const seen = /* @__PURE__ */ new Set();
1122
+ const visit = (name) => {
1123
+ const found = workspace.get(name);
1124
+ if (!found || found.manifest.private || seen.has(name)) return;
1125
+ seen.add(name);
1126
+ for (const dependency of Object.keys(found.manifest.dependencies)) visit(dependency);
1127
+ };
1128
+ names.forEach(visit);
1129
+ return [...seen];
1130
+ };
1131
+ const run = (command, args, cwd) => execFileSync(command, args, {
1132
+ cwd,
1133
+ stdio: [
1134
+ "ignore",
1135
+ "ignore",
1136
+ "inherit"
1137
+ ]
1138
+ });
1139
+ const snapshotsDir = resolve(outDir, "snapshots");
1140
+ await rm(snapshotsDir, {
1141
+ recursive: true,
1142
+ force: true
1143
+ });
1144
+ await mkdir(snapshotsDir, { recursive: true });
1145
+ await rm(workDir, {
1146
+ recursive: true,
1147
+ force: true
1148
+ });
1149
+ const plans = (await Promise.all(input.tutorials.map(async (tutorial) => {
1150
+ const source = readManifest(await readFile(resolve(input.fixturesDir, tutorial.fixture, "package.json"), "utf8"));
1151
+ const devServer = devServerInDevDependencies(source);
1152
+ if (devServer) throw docsErrorDiagnostics.DOCS_RUNNABLE_DEV_SERVER_MISSING({
1153
+ fixture: tutorial.fixture,
1154
+ name: devServer
1155
+ });
1156
+ const local = Object.entries(source.dependencies).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name);
1157
+ return {
1158
+ tutorial,
1159
+ source,
1160
+ local,
1161
+ packages: closure(local)
1162
+ };
1163
+ }))).filter((plan) => Object.keys(plan.source.dependencies).length > 0);
1164
+ const packed = [...new Set(plans.flatMap((plan) => plan.packages))];
1165
+ if (workspaceRoot && packed.length > 0) {
1166
+ const filters = packed.flatMap((name) => ["--filter", `${name}...`]);
1167
+ const vp = resolve(workspaceRoot, "node_modules/.bin/vp");
1168
+ if (existsSync(vp)) run(vp, [
1169
+ "run",
1170
+ "--cache",
1171
+ ...filters,
1172
+ "build"
1173
+ ], workspaceRoot);
1174
+ else run("pnpm", [
1175
+ "--recursive",
1176
+ ...filters,
1177
+ "run",
1178
+ "--if-present",
1179
+ "build"
1180
+ ], workspaceRoot);
1181
+ }
1182
+ const tarballDir = resolve(workDir, "tarballs");
1183
+ await mkdir(tarballDir, { recursive: true });
1184
+ const tarballFiles = /* @__PURE__ */ new Map();
1185
+ for (const name of packed) {
1186
+ const before = new Set(await readdir(tarballDir));
1187
+ run("pnpm", [
1188
+ "pack",
1189
+ "--pack-destination",
1190
+ tarballDir
1191
+ ], workspace.get(name).dir);
1192
+ const file = (await readdir(tarballDir)).find((candidate) => !before.has(candidate));
1193
+ if (!file) throw docsErrorDiagnostics.DOCS_RUNNABLE_PACK_FAILED({ name });
1194
+ await sortPackedManifest(resolve(tarballDir, file), resolve(workDir, "unpacked"));
1195
+ tarballFiles.set(name, file);
1196
+ }
1197
+ const buildSnapshot = async ({ tutorial, source, local, packages }) => {
1198
+ const started = performance.now();
1199
+ const work = resolve(workDir, tutorial.slug);
1200
+ await mkdir(resolve(work, "tarballs"), { recursive: true });
1201
+ const tarballs = {};
1202
+ for (const name of packages) {
1203
+ const file = tarballFiles.get(name);
1204
+ await copyFile(resolve(tarballDir, file), resolve(work, "tarballs", file));
1205
+ tarballs[name] = `file:./tarballs/${file}`;
1206
+ }
1207
+ const peers = {};
1208
+ for (const name of packages) {
1209
+ const { peerDependencies, optionalPeers } = workspace.get(name).manifest;
1210
+ for (const [peer, specifier] of Object.entries(peerDependencies)) if (!optionalPeers.has(peer) && !tarballs[peer] && !peer.startsWith("@types/")) peers[peer] = specifier;
1211
+ }
1212
+ const dependencies = resolveDependencies({
1213
+ ...peers,
1214
+ ...source.dependencies
1215
+ }, input.versions);
1216
+ for (const name of local) dependencies[name] = tarballs[name];
1217
+ await writeFile(resolve(work, "package.json"), `${JSON.stringify({
1218
+ name: source.name,
1219
+ private: true,
1220
+ dependencies,
1221
+ overrides: tarballs
1222
+ }, null, 2)}\n`);
1223
+ await writeFile(resolve(work, ".npmrc"), "legacy-peer-deps=true\n");
1224
+ const lockfile = tutorialLockfile(input.fixturesDir, tutorial.fixture);
1225
+ const written = readWorkerResult(await runSnapshotWorker([
1226
+ work,
1227
+ snapshotsDir,
1228
+ tutorial.slug,
1229
+ lockfile
1230
+ ]));
1231
+ await rm(work, {
1232
+ recursive: true,
1233
+ force: true
1234
+ });
1235
+ console.info(`[docs] ${tutorial.slug}: ${(written.bytes / 2 ** 20).toFixed(1)} MiB of node_modules, ${(written.compressed / 2 ** 20).toFixed(1)} MiB in ${written.files.length} parts, sha256 ${written.sha256.slice(0, 12)}, built in ${((performance.now() - started) / 1e3).toFixed(0)} s`);
1236
+ return {
1237
+ parts: written.files,
1238
+ sha256: written.sha256
1239
+ };
1240
+ };
1241
+ const results = /* @__PURE__ */ new Map();
1242
+ const queue = [...plans];
1243
+ await Promise.all(Array.from({ length: SNAPSHOT_CONCURRENCY }, async () => {
1244
+ for (let plan = queue.shift(); plan; plan = queue.shift()) results.set(plan.tutorial.slug, await buildSnapshot(plan));
1245
+ }));
1246
+ await rm(workDir, {
1247
+ recursive: true,
1248
+ force: true
1249
+ });
1250
+ const snapshots = Object.fromEntries(plans.map((plan) => [plan.tutorial.slug, results.get(plan.tutorial.slug)]));
1251
+ const file = {
1252
+ inputs: await tutorialSnapshotInputs(input),
1253
+ tutorials: snapshots
1254
+ };
1255
+ await writeFile(resolve(outDir, "snapshots.json"), `${JSON.stringify(file, null, 2)}\n`);
1256
+ return snapshots;
1257
+ }
1258
+ // src/runnable/nuxt.ts
1259
+ /** Where Nitro serves the snapshot parts, under the app base. */
1260
+ const baseURL = "/_tutorials";
1261
+ /**
1262
+ * Runnable lessons and playground examples.
1263
+ *
1264
+ * The pages with `layout: learn` and `layout: playground` are the lessons and the examples. Their frontmatter is the
1265
+ * only list. `lessons` and `examples` of the options add more, for app pages that render a workspace themselves. Both
1266
+ * share one snapshot build, so a lesson and an example with the same dependencies share one snapshot.
1267
+ *
1268
+ * At build time this reads each lesson and its fixture, and writes:
1269
+ * - `#build/docs/workspaces/<page>.mjs`: the workspace data of each `learn` and `playground` page. The result's
1270
+ * `workspaces` is the source of `#docs/workspaces`, which loads them by page path.
1271
+ * - `#build/runnable-tutorials.mjs`: the files before step 1 and the files that each step writes, for `lessons`.
1272
+ * - `#build/playground-templates.mjs`: the files of each example of `examples`, read from its fixture.
1273
+ * - `#build/learn-facts.mjs`: the step count and reading time of each page with `layout: tutorial` or `layout: learn`.
1274
+ * - `/_tutorials/snapshots/<slug>.<hash>.<part>.bin`: the `node_modules` of the workspace, so the browser skips
1275
+ * `npm install`. An example with the dependencies of a lesson mounts the snapshot of that lesson. `nuxt build` writes
1276
+ * them, pinned by the lockfile beside each fixture. `nuxt dev` reuses the last ones while their dependencies match
1277
+ * (`tutorialSnapshotInputs`). Set `TUTORIAL_SNAPSHOTS=1` to build them in development, or `TUTORIAL_SNAPSHOTS=0` to
1278
+ * skip them in a build. Without them the workspace installs. `nuxi prepare` never builds them.
1279
+ */
1280
+ async function setupDocsRunnable(options, input) {
1281
+ const { nuxt, content } = input;
1282
+ const rootDir = nuxt.options.rootDir;
1283
+ const fixturesDir = resolve(rootDir, options.fixtures ?? "fixtures");
1284
+ const pages = workspacePages(content.pages());
1285
+ checkWorkspacePageIds(pages);
1286
+ for (const page of pages) checkWorkspacePage(page, {
1287
+ rootDir,
1288
+ srcDir: nuxt.options.srcDir,
1289
+ fixturesDir
1290
+ });
1291
+ const learnPages = pages.filter((page) => page.layout === "learn");
1292
+ const containerPages = pages.filter((page) => page.layout === "playground" && !page.workspace.render);
1293
+ const renderPages = pages.filter((page) => page.layout === "playground" && page.workspace.render);
1294
+ const pageLessons = learnPages.map(learnLessonSource);
1295
+ const lessons = [...options.lessons ?? [], ...pageLessons];
1296
+ const examples = [...options.examples ?? [], ...containerPages.flatMap((page) => playgroundExampleSources(page, rootDir))];
1297
+ checkRunnableIds(lessons, examples);
1298
+ const workspaceRoot = options.pnpmWorkspace === void 0 ? void 0 : resolve(rootDir, options.pnpmWorkspace);
1299
+ const versions = workspaceRoot ? await readWorkspaceVersions(workspaceRoot) : noWorkspaceVersions;
1300
+ nuxt.options.routeRules = {
1301
+ ...nuxt.options.routeRules,
1302
+ [`${baseURL}/snapshots/**`]: { headers: { "cache-control": "public, max-age=31536000, immutable" } }
1303
+ };
1304
+ const build = () => Promise.all(lessons.map((source) => buildRunnableTutorial({
1305
+ source,
1306
+ readPage: content.read,
1307
+ fixturesDir,
1308
+ versions,
1309
+ start: options.start
1310
+ })));
1311
+ const buildTemplates = () => buildPlaygroundTemplates({
1312
+ fixturesDir,
1313
+ versions,
1314
+ tutorials: lessons,
1315
+ examples
1316
+ });
1317
+ const tutorials = await build();
1318
+ const templates = await buildTemplates();
1319
+ const assetsDir = resolve(rootDir, "node_modules/.cache/runnable-tutorials");
1320
+ await mkdir(assetsDir, { recursive: true });
1321
+ const sources = snapshotSources(lessons, examples, templates);
1322
+ let snapshots = await readTutorialSnapshots(assetsDir, {
1323
+ inputs: await tutorialSnapshotInputs({
1324
+ tutorials: sources,
1325
+ workspaceRoot,
1326
+ fixturesDir,
1327
+ versions
1328
+ }),
1329
+ disabled: process.env.TUTORIAL_SNAPSHOTS === "0"
1330
+ });
1331
+ if (!snapshots && sources.length > 0 && nuxt.options.dev && process.env.TUTORIAL_SNAPSHOTS !== "1" && process.env.TUTORIAL_SNAPSHOTS !== "0") console.info("[docs] No snapshots of the runnable lessons for the current dependencies, so the workspace runs npm install. Start with TUTORIAL_SNAPSHOTS=1 to build them.");
1332
+ const buildSnapshots = sources.length > 0 && !Reflect.get(nuxt.options, "_prepare") && (process.env.TUTORIAL_SNAPSHOTS ?? (nuxt.options.dev ? "0" : "1")) === "1";
1333
+ let built;
1334
+ nuxt.hook("app:templates", () => {
1335
+ if (!buildSnapshots) return;
1336
+ built ??= buildTutorialSnapshots({
1337
+ tutorials: sources,
1338
+ workspaceRoot,
1339
+ fixturesDir,
1340
+ versions,
1341
+ outDir: assetsDir,
1342
+ workDir: resolve(rootDir, "node_modules/.cache/runnable-tutorials-work")
1343
+ }).then((result) => {
1344
+ snapshots = result;
1345
+ });
1346
+ return built;
1347
+ });
1348
+ const partsBase = `${nuxt.options.app.baseURL.replace(/\/+$/, "")}${baseURL}/snapshots/`;
1349
+ const served = (snapshot) => snapshot && {
1350
+ ...snapshot,
1351
+ parts: snapshot.parts.map((part) => `${partsBase}${basename(part)}`)
1352
+ };
1353
+ const snapshotOf = (slug, all) => served(all && Object.hasOwn(all, slug) ? all[slug] : void 0);
1354
+ const currentTutorials = async () => (nuxt.options.dev ? await build() : tutorials).map((tutorial) => ({
1355
+ ...tutorial,
1356
+ snapshot: snapshotOf(tutorial.slug, snapshots)
1357
+ }));
1358
+ const currentTemplates = async () => (nuxt.options.dev ? await buildTemplates() : templates).map((template) => ({
1359
+ ...template,
1360
+ snapshot: snapshotOf(template.snapshotOf, snapshots)
1361
+ }));
1362
+ const configLessons = new Set((options.lessons ?? []).map((lesson) => lesson.slug));
1363
+ const configExamples = new Set((options.examples ?? []).map((example) => example.id));
1364
+ addTemplate({
1365
+ filename: "runnable-tutorials.mjs",
1366
+ write: true,
1367
+ getContents: async () => `export const runnableTutorials = ${JSON.stringify((await currentTutorials()).filter((tutorial) => configLessons.has(tutorial.slug)))}\n`
1368
+ });
1369
+ addTemplate({
1370
+ filename: "playground-templates.mjs",
1371
+ write: true,
1372
+ getContents: async () => `export const playgroundTemplates = ${JSON.stringify((await currentTemplates()).filter((template) => configExamples.has(template.id)).map(({ assets: _assets, ...template }) => template))}\n`
1373
+ });
1374
+ const pageModule = async (page) => {
1375
+ const port = page.workspace.port ?? 3e3;
1376
+ if (page.layout === "learn") {
1377
+ const slug = workspacePageSlug(page.path);
1378
+ const tutorial = (await currentTutorials()).find((candidate) => candidate.slug === slug);
1379
+ if (!tutorial) throw invariantError(`the lesson of ${page.path} was built`);
1380
+ return workspacePageModule({
1381
+ layout: "learn",
1382
+ tutorial,
1383
+ guide: page.workspace.guide ?? "side",
1384
+ port,
1385
+ preview: page.workspace.preview
1386
+ });
1387
+ }
1388
+ const tabs = (page.workspace.tabs ?? []).map((tab) => ({
1389
+ ...tab,
1390
+ file: workspaceTabComponent(nuxt.options.srcDir, tab.value)
1391
+ }));
1392
+ if (page.workspace.render) return workspacePageModule({
1393
+ layout: "playground",
1394
+ examples: await renderExamples(page, rootDir),
1395
+ port
1396
+ }, {
1397
+ render: resolve(rootDir, page.workspace.render),
1398
+ tabs
1399
+ });
1400
+ return workspacePageModule({
1401
+ layout: "playground",
1402
+ examples: pageExamples(page, await currentTemplates()),
1403
+ port,
1404
+ connect: page.workspace.connect
1405
+ }, { tabs });
1406
+ };
1407
+ const pageFile = (page) => `docs/workspaces/${workspacePageSlug(page.path)}.mjs`;
1408
+ for (const page of [
1409
+ ...learnPages,
1410
+ ...containerPages,
1411
+ ...renderPages
1412
+ ]) addTemplate({
1413
+ filename: pageFile(page),
1414
+ write: true,
1415
+ getContents: () => pageModule(page)
1416
+ });
1417
+ addTemplate({
1418
+ filename: "learn-facts.mjs",
1419
+ write: true,
1420
+ getContents: () => {
1421
+ const facts = Object.fromEntries(content.pages().filter((page) => page.layout === "tutorial" || page.layout === "learn").flatMap((page) => {
1422
+ const markdown = content.read(page.layout === "learn" ? page.workspace?.lesson ?? page.path : page.path);
1423
+ return markdown === void 0 ? [] : [[page.path, tutorialPageFacts(markdown)]];
1424
+ }));
1425
+ return `export const learnFacts = ${JSON.stringify(facts)}\n`;
1426
+ }
1427
+ });
1428
+ const types = JSON.stringify(ownModule(import.meta.url, "runnable"));
1429
+ addTypeTemplate({
1430
+ filename: "types/runnable-tutorials.d.ts",
1431
+ getContents: () => [
1432
+ `declare module "#build/runnable-tutorials.mjs" {`,
1433
+ ` export const runnableTutorials: import(${types}).RunnableTutorialData[]`,
1434
+ `}`,
1435
+ `declare module "#build/playground-templates.mjs" {`,
1436
+ ` export const playgroundTemplates: import(${types}).PlaygroundTemplate[]`,
1437
+ `}`,
1438
+ `declare module "#build/learn-facts.mjs" {`,
1439
+ ` export const learnFacts: Record<string, import(${types}).LearnPageFacts>`,
1440
+ `}`
1441
+ ].join("\n")
1442
+ });
1443
+ Reflect.apply(nuxt.hook, nuxt, ["nitro:config", (nitro) => {
1444
+ nitro.publicAssets = [...nitro.publicAssets ?? [], {
1445
+ baseURL,
1446
+ dir: assetsDir
1447
+ }];
1448
+ }]);
1449
+ return { workspaces: docsWorkspacesSource(pages) };
1450
+ }
1451
+ /** The source of `#docs/workspaces`: a loader of the page module of each workspace page, by page path. */
1452
+ function docsWorkspacesSource(pages) {
1453
+ return `export default {\n${pages.map((page) => ` ${JSON.stringify(page.path)}: () => import(${JSON.stringify(`./workspaces/${workspacePageSlug(page.path)}.mjs`)}),`).join("\n")}\n}\n`;
1454
+ }
1455
+ // src/content-check.ts
317
1456
  /**
318
1457
  * `content.check()` over the docs pages, as `vitehub content check` runs it: links to missing pages, and the title and
319
1458
  * description rules of `seoAudit`, from the Markdown and without built HTML. Each page has its URL from the manifest.
@@ -369,8 +1508,7 @@ function problem(finding) {
369
1508
  function docsAppPageLinks(routes) {
370
1509
  return [...new Set(routePaths(routes).filter((path) => !/\(\.\*\)\*?|\*$/.test(path)).map((path) => path.replace(/:\w+(?:\([^)]*\))?\??/g, "*") || "/"))];
371
1510
  }
372
- //#endregion
373
- //#region src/files.ts
1511
+ // src/files.ts
374
1512
  /** The Markdown files of a folder, without dot files or dot folders, as Nitro's server assets list them. */
375
1513
  function markdownFiles(dir) {
376
1514
  if (!existsSync(dir)) return [];
@@ -414,17 +1552,22 @@ function packDocsFiles(stores, order = []) {
414
1552
  };
415
1553
  }
416
1554
  /**
417
- * The source of `#docs/files` in development. Each file is a `?raw` import, so Vite watches it, and an edit shows on the
418
- * next read. The server can run in workerd, which cannot read the folders from disk.
1555
+ * The source of `#docs/files` in development. When Nitro runs in Vite, each file is a `?raw` import, so Vite watches it,
1556
+ * and an edit shows on the next read. The server can run in workerd, which cannot read the folders from disk. When
1557
+ * Nitro builds the server with its own bundler, as on Nuxt 4.7, that bundler cannot load `?raw`, and the server reads
1558
+ * each file from disk on request.
419
1559
  */
420
- function docsDevFilesModule(stores) {
1560
+ function docsDevFilesModule(stores, { nitroInVite }) {
1561
+ const loader = (path) => nitroInVite ? `() => import(${JSON.stringify(`${path}?raw`)}).then(module => module.default)` : `() => readFile(${JSON.stringify(path)}, "utf8")`;
1562
+ const loaders = stores.map((store) => ` ${JSON.stringify(store.name)}: {\n${markdownFiles(store.dir).map((file) => ` ${JSON.stringify(file)}: ${loader(join(store.dir, file).split(sep).join("/"))},`).join("\n")}\n },`);
421
1563
  return [
422
- `const files = {\n${stores.map((store) => ` ${JSON.stringify(store.name)}: {\n${markdownFiles(store.dir).map((file) => ` ${JSON.stringify(file)}: () => import(${JSON.stringify(`${join(store.dir, file).split(sep).join("/")}?raw`)}),`).join("\n")}\n },`).join("\n")}\n}`,
1564
+ ...nitroInVite ? [] : [`import { readFile } from "node:fs/promises"`],
1565
+ `const files = {\n${loaders.join("\n")}\n}`,
423
1566
  "const has = (store, file) => Object.hasOwn(files, store) && Object.hasOwn(files[store], file)",
424
1567
  "export default {",
425
1568
  " has,",
426
1569
  " async read(store, file) {",
427
- " return has(store, file) ? (await files[store][file]()).default : null",
1570
+ " return has(store, file) ? await files[store][file]() : null",
428
1571
  " },",
429
1572
  "}",
430
1573
  ""
@@ -435,8 +1578,7 @@ function docsFilesModule(stores, order) {
435
1578
  const { index, packed } = packDocsFiles(stores, order);
436
1579
  return `export default { index: JSON.parse(${JSON.stringify(JSON.stringify(index))}), packed: ${JSON.stringify(packed)} }\n`;
437
1580
  }
438
- //#endregion
439
- //#region src/seo-audit.ts
1581
+ // src/seo-audit.ts
440
1582
  /**
441
1583
  * The search checks that every prerendered page must pass. The limits are those of common site audits, such as OpenSEO
442
1584
  * and Ahrefs: a title of 10 to 60 characters, a description of 70 to 160, one `h1`, headings that go down one level at
@@ -482,7 +1624,7 @@ function readDocsSeoPage(path, html, origin) {
482
1624
  if (property && attribute(tag, "content")?.trim()) openGraph.add(property.toLowerCase());
483
1625
  }
484
1626
  const levels = [];
485
- walkSync(parse$1(body), (node, parent) => {
1627
+ walkSync(parse$2(body), (node, parent) => {
486
1628
  if (node.type !== ELEMENT_NODE || !/^h[1-6]$/i.test(node.name)) return;
487
1629
  for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (ancestor.type === ELEMENT_NODE && ancestor.attributes.class?.split(/\s+/).includes("docs-example-preview")) return;
488
1630
  levels.push(Number(node.name[1]));
@@ -617,8 +1759,7 @@ function decode(value) {
617
1759
  return Number.isNaN(code) ? match : String.fromCodePoint(code);
618
1760
  });
619
1761
  }
620
- //#endregion
621
- //#region src/theme-css.ts
1762
+ // src/theme-css.ts
622
1763
  function readTheme(file) {
623
1764
  const css = postcss.parse(readFileSync(file, "utf8"), { from: file });
624
1765
  css.walkAtRules("import", (rule) => {
@@ -678,8 +1819,26 @@ function docsThemeCss(file) {
678
1819
  });
679
1820
  return css.toString();
680
1821
  }
681
- //#endregion
682
- //#region src/nuxt.ts
1822
+ // src/nuxt.ts
1823
+ function docsContentOf(options, rootDir) {
1824
+ const contentDir = resolve(rootDir, options.dir ?? "content");
1825
+ const sources = options.sources && resolveDocsSources(options.sources, rootDir);
1826
+ const resolveBase = () => normalizeDocsBase(options.base ?? (sources || existsSync(join(contentDir, "docs")) ? "/docs" : "/"));
1827
+ const base = resolveBase();
1828
+ return {
1829
+ contentDir,
1830
+ sources,
1831
+ resolveBase,
1832
+ base,
1833
+ manifestOptions: {
1834
+ dir: contentDir,
1835
+ base,
1836
+ sources: options.sources,
1837
+ rootDir,
1838
+ sections: options.sections
1839
+ }
1840
+ };
1841
+ }
683
1842
  const docsNuxtModule = defineNuxtModule({
684
1843
  meta: {
685
1844
  configKey: "docs",
@@ -696,9 +1855,19 @@ const docsNuxtModule = defineNuxtModule({
696
1855
  const uiFontsPath = createRequire(dependency("@nuxt/ui")).resolve("@nuxt/fonts");
697
1856
  nuxt.options.alias["@nuxt/fonts"] = fontsPath;
698
1857
  nuxt.options.alias[uiFontsPath] = fontsPath;
1858
+ const comments = await docsCommentsDependencies(nuxt, docs.comments);
1859
+ const { manifestOptions } = docsContentOf(docs, nuxt.options.rootDir);
1860
+ const webContainer = await docsWebContainerDefaults(nuxt, webContainerRoutes(docsManifestPages((await readDocsContent(manifestOptions)).manifest)));
1861
+ const vitehubDefaults = {
1862
+ ...comments["vite-hub/nuxt"]?.defaults,
1863
+ ...webContainer
1864
+ };
699
1865
  return {
700
- ...await docsCommentsDependencies(nuxt, docs.comments),
701
- "@nuxt/fonts": {},
1866
+ ...Object.keys(vitehubDefaults).length > 0 ? { "vite-hub/nuxt": {
1867
+ optional: true,
1868
+ defaults: vitehubDefaults
1869
+ } } : {},
1870
+ "@nuxt/fonts": { defaults: { throwOnError: false } },
702
1871
  "@nuxt/ui": { defaults: {
703
1872
  prose: true,
704
1873
  content: true
@@ -744,22 +1913,12 @@ const docsNuxtModule = defineNuxtModule({
744
1913
  const transform = nuxt.options.imports.transform ??= {};
745
1914
  transform.include ??= [];
746
1915
  transform.include.push(new RegExp(`^${packageRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`));
747
- const contentDir = resolve(nuxt.options.rootDir, options.dir ?? "content");
748
- const sources = options.sources && resolveDocsSources(options.sources, nuxt.options.rootDir);
1916
+ const { contentDir, sources, resolveBase, base, manifestOptions } = docsContentOf(options, nuxt.options.rootDir);
749
1917
  const sourcesDir = join(nuxt.options.buildDir, "docs/sources");
750
1918
  /** The folder that the server reads each source's pages from, by page `source` name. */
751
1919
  const sourceDirs = sources?.map((source, index) => source.dir ?? join(sourcesDir, `docs-${index}`));
752
1920
  const contentDirsToWatch = sources ? sources.flatMap((source) => source.dir ?? []) : [contentDir];
753
1921
  const agentDir = join(nuxt.options.buildDir, "docs/agent");
754
- const resolveBase = () => normalizeDocsBase(options.base ?? (sources || existsSync(join(contentDir, "docs")) ? "/docs" : "/"));
755
- const base = resolveBase();
756
- const manifestOptions = {
757
- dir: contentDir,
758
- base,
759
- sources: options.sources,
760
- rootDir: nuxt.options.rootDir,
761
- sections: options.sections
762
- };
763
1922
  const config = publicConfig(options, base, nuxt.options.app.baseURL);
764
1923
  const ownsApp = !hasAppComponent(nuxt.options._layers.map((layer) => layer.config.srcDir), nuxt.options.extensions);
765
1924
  nuxt.hook("prepare:types", ({ tsConfig, sharedTsConfig, serverTsConfig }) => {
@@ -811,6 +1970,14 @@ const docsNuxtModule = defineNuxtModule({
811
1970
  const moduleOptions = nuxt.options;
812
1971
  let read = await readDocsContent(manifestOptions);
813
1972
  let manifest = read.manifest;
1973
+ if (sources && options.base === void 0) {
1974
+ const pages = docsManifestPages(manifest);
1975
+ const firstPage = pages[0];
1976
+ if (firstPage && !pages.some((page) => isDocsPath(page.path, base))) useLogger("@vite-hub/docs").warn(formatDiagnostic(docsErrorDiagnostics.DOCS_BASE_EMPTY({
1977
+ base,
1978
+ path: firstPage.path
1979
+ })));
1980
+ }
814
1981
  /**
815
1982
  * Resolves when development has read the content after a change. Nuxt generates the app again when a file is added
816
1983
  * or removed, and the manifest templates wait for this read, so that run does not write the old pages.
@@ -827,8 +1994,9 @@ const docsNuxtModule = defineNuxtModule({
827
1994
  contentReadDone = void 0;
828
1995
  };
829
1996
  const afterContentRead = (source) => contentReadDone ? contentRead.then(source) : source();
830
- /** Copies the pages of each Content Source into the build, where the server and the agent copies read them. */
1997
+ let sourcePages = /* @__PURE__ */ new Map();
831
1998
  function writeSources(files) {
1999
+ sourcePages = new Map(files.map((file) => [`${file.source}/${file.file}`, file.markdown]));
832
2000
  rmSync(sourcesDir, {
833
2001
  force: true,
834
2002
  recursive: true
@@ -842,7 +2010,27 @@ const docsNuxtModule = defineNuxtModule({
842
2010
  writeSources(read.files);
843
2011
  /** The Markdown of a page, from the content folder or from the copy of its Content Source. */
844
2012
  const pageFile = (page) => join(page.source ? sourceDirs[Number(page.source.slice(5))] : contentDir, page.file);
845
- const readPage = (page) => readFileSync(pageFile(page), "utf8");
2013
+ const readPage = (page) => sourcePages.get(`${page.source}/${page.file}`) ?? readFileSync(pageFile(page), "utf8");
2014
+ const runnable = options.runnable || docsManifestPages(manifest).some((page) => isDocsWorkspaceLayout(page.layout)) ? await setupDocsRunnable(options.runnable ?? {}, {
2015
+ nuxt,
2016
+ content: {
2017
+ pages: () => docsManifestPages(manifest),
2018
+ read: (path) => {
2019
+ const page = docsManifestPages(manifest).find((page) => page.path === normalizeDocsPath(path));
2020
+ return page && readPage(page);
2021
+ }
2022
+ }
2023
+ }) : void 0;
2024
+ nuxt.options.alias["#docs/workspaces"] = addTemplate({
2025
+ filename: "docs/workspaces.mjs",
2026
+ write: true,
2027
+ getContents: () => runnable?.workspaces ?? "export default {}\n"
2028
+ }).dst;
2029
+ addTemplate({
2030
+ filename: "docs/workspaces.d.mts",
2031
+ write: true,
2032
+ getContents: () => `declare const workspaces: Record<string, (() => Promise<{ default: import(${JSON.stringify(ownModule(import.meta.url, "runnable"))}).DocsWorkspaceData }>) | undefined>\nexport default workspaces\n`
2033
+ });
846
2034
  /**
847
2035
  * Content renders the agent copy of each page on request. `rawMarkdown` is a function of the app's build, so it runs
848
2036
  * here, and the server reads each page that it changed from `docs/agent/<source>/<file>`. `nuxi build` empties the
@@ -986,11 +2174,21 @@ const docsNuxtModule = defineNuxtModule({
986
2174
  if (!ownDiscoveryRoutes) agentDiscoveryOptions.routes = discoveryRoutes(manifest);
987
2175
  moduleOptions.agentDiscovery = agentDiscoveryOptions;
988
2176
  /**
989
- * What the module reads from the manifest only when Nuxt starts: the mount of the docs page route, and the routes
990
- * that negotiate Markdown. A content change that moves them needs a restart. Any other change reloads the pages.
991
- * `<base>/**` already covers a new page below the base.
2177
+ * What the module reads from the manifest only when Nuxt starts: the mount of the docs page route, the routes
2178
+ * that negotiate Markdown, and the workspace pages, whose modules and isolated routes are set up then. A content
2179
+ * change that moves them needs a restart. Any other change reloads the pages. `<base>/**` already covers a new page
2180
+ * below the base.
992
2181
  */
993
- const startupShape = (pages) => JSON.stringify([docsMount(pages), ownDiscoveryRoutes ? null : discoveryRoutes(pages).filter((route) => typeof route !== "string" || route.endsWith("/**") || !isDocsPath(route, config.base))]);
2182
+ const startupShape = (pages) => JSON.stringify([
2183
+ docsMount(pages),
2184
+ ownDiscoveryRoutes ? null : discoveryRoutes(pages).filter((route) => typeof route !== "string" || route.endsWith("/**") || !isDocsPath(route, config.base)),
2185
+ workspacePages(docsManifestPages(pages)).map((page) => [
2186
+ page.path,
2187
+ page.layout,
2188
+ page.workspace
2189
+ ])
2190
+ ]);
2191
+ let packDevFiles = false;
994
2192
  const agentFile = addTemplate({
995
2193
  filename: "docs/agent.mjs",
996
2194
  write: true,
@@ -1010,20 +2208,18 @@ const docsNuxtModule = defineNuxtModule({
1010
2208
  getContents: () => `import type { DocsManifest } from "@vite-hub/docs"\ndeclare const manifest: DocsManifest\nexport default manifest\n`,
1011
2209
  write: true
1012
2210
  });
1013
- const app = () => docsAppManifest(manifest, { panels: !nuxt.options.dev });
2211
+ const builtApp = nuxt.options.dev ? void 0 : docsAppManifest(manifest, { panels: true });
2212
+ const appManifest = () => builtApp?.manifest ?? docsAppManifest(manifest, { panels: false }).manifest;
1014
2213
  nuxt.options.alias["#docs/manifest"] = addTemplate({
1015
2214
  filename: "docs/app-manifest.mjs",
1016
- getContents: () => afterContentRead(() => docsAppManifestSource(app().manifest)),
2215
+ getContents: () => afterContentRead(() => docsAppManifestSource(appManifest())),
1017
2216
  write: true
1018
2217
  }).dst;
1019
- const panelFiles = app().panels.map((panel, index) => ({
2218
+ const panelFiles = (builtApp?.panels ?? []).map((panel, index) => ({
1020
2219
  path: panel.path,
1021
2220
  file: addTemplate({
1022
2221
  filename: `docs/panels/${index}.mjs`,
1023
- getContents: () => docsAppPanelSource(app().panels.find((candidate) => candidate.path === panel.path) ?? {
1024
- ...panel,
1025
- pages: []
1026
- }),
2222
+ getContents: () => docsAppPanelSource(panel),
1027
2223
  write: true
1028
2224
  }).dst
1029
2225
  }));
@@ -1032,9 +2228,6 @@ const docsNuxtModule = defineNuxtModule({
1032
2228
  write: true,
1033
2229
  getContents: () => `export default {\n${panelFiles.map(({ path, file }) => ` ${JSON.stringify(path)}: () => import(${JSON.stringify(file)}),\n`).join("")}}\n`
1034
2230
  }).dst;
1035
- nuxt.hook("build:manifest", (chunks) => {
1036
- for (const [key, chunk] of Object.entries(chunks)) if (/docs[/\\]panels[/\\]\d+\.mjs$/.test(decodeURIComponent(key))) chunk.prefetch = false;
1037
- });
1038
2231
  addTemplate({
1039
2232
  filename: "docs/panels.d.mts",
1040
2233
  write: true,
@@ -1046,6 +2239,7 @@ const docsNuxtModule = defineNuxtModule({
1046
2239
  write: true
1047
2240
  });
1048
2241
  nuxt.options.alias["#docs/navigation"] = resolver.resolve("./navigation.js");
2242
+ nuxt.options.alias["#docs/runnable"] = resolver.resolve("./runnable.js");
1049
2243
  nuxt.options.alias["#docs/primitive-rail"] = resolver.resolve("./primitive-rail.js");
1050
2244
  nuxt.options.alias["#docs/comark-css"] = addTemplate({
1051
2245
  filename: "docs/comark-css.mjs",
@@ -1210,7 +2404,7 @@ const docsNuxtModule = defineNuxtModule({
1210
2404
  regeneration = regeneration.then(async () => {
1211
2405
  const change = await result;
1212
2406
  if (closed || !change) return;
1213
- if (change === "restart") return restart();
2407
+ if (change === "restart" || packDevFiles) return restart();
1214
2408
  if (!change.shapeChanged && await reloadPages({
1215
2409
  files: change.files,
1216
2410
  manifest: change.manifestChanged,
@@ -1347,6 +2541,9 @@ const docsNuxtModule = defineNuxtModule({
1347
2541
  visibility: false,
1348
2542
  interaction: true
1349
2543
  };
2544
+ nuxt.hook("build:manifest", (chunks) => {
2545
+ for (const chunk of Object.values(chunks)) chunk.prefetch = false;
2546
+ });
1350
2547
  addPlugin({
1351
2548
  src: join(runtime, "app/plugins/theme-color.ts"),
1352
2549
  mode: "all"
@@ -1450,6 +2647,7 @@ const docsNuxtModule = defineNuxtModule({
1450
2647
  Reflect.apply(nuxt.hook, nuxt, ["nitro:build:before", startHints]);
1451
2648
  let checkSourceLinks;
1452
2649
  Reflect.apply(nuxt.hook, nuxt, ["nitro:init", (nitro) => {
2650
+ packDevFiles = nuxt.options.dev && nuxt.options.experimental.nitroViteEnvironment !== true && (nitro.options.devServer?.runner || process.env.NITRO_DEV_RUNNER) === "miniflare";
1453
2651
  const building = !nuxt.options.dev && !Reflect.get(nuxt.options, "_prepare");
1454
2652
  const seoAudit = options.seoAudit ?? "warn";
1455
2653
  const redirects = docsRedirects(nitro.options.routeRules ?? {});
@@ -1574,7 +2772,7 @@ const docsNuxtModule = defineNuxtModule({
1574
2772
  const order = () => docsManifestPages(manifest).flatMap((page) => [[page.source ?? "docs", page.file], ["docs-agent", `${docsContentSource(page)}/${page.file}`]]);
1575
2773
  nitro.virtual = {
1576
2774
  ...nitro.virtual,
1577
- "#docs/files": nuxt.options.dev ? () => docsDevFilesModule(stores) : () => docsFilesModule(stores, order())
2775
+ "#docs/files": () => nuxt.options.dev && !packDevFiles ? docsDevFilesModule(stores, { nitroInVite: nuxt.options.experimental.nitroViteEnvironment === true }) : docsFilesModule(stores, order())
1578
2776
  };
1579
2777
  nitro.publicAssets = [...nitro.publicAssets ?? [], {
1580
2778
  baseURL: "/_docs",
@@ -1864,5 +3062,4 @@ async function githubStars(repo) {
1864
3062
  return null;
1865
3063
  }
1866
3064
  }
1867
- //#endregion
1868
3065
  export { docsNuxtModule as default };