clean-jsdoc-theme 5.1.1 → 5.2.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/publish.mjs CHANGED
@@ -1,1339 +1,1621 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.7.0_postcss@8.5.16_tsx@4.22.3_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/esm_shims.js
9
- import path from "path";
10
- import { fileURLToPath } from "url";
11
- var getFilename = () => fileURLToPath(import.meta.url);
12
- var __filename = /* @__PURE__ */ getFilename();
13
-
14
- // src/publish.ts
15
- import { mkdir as mkdir2, readFile, readdir, rm, stat, writeFile as writeFile2 } from "fs/promises";
16
- import { readFileSync } from "fs";
17
- import { createHash } from "crypto";
18
- import { basename, dirname as dirname2, extname, join as joinPath, resolve as resolvePath } from "path";
19
- import { pathToFileURL } from "url";
20
-
21
- // src/write-output-files.ts
22
- import { mkdir, writeFile } from "fs/promises";
23
- import { dirname, join } from "path";
1
+ import { createRequire } from "node:module";
2
+ import { basename, dirname, extname, join, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
+ import { readFileSync } from "node:fs";
6
+ import { createHash } from "node:crypto";
7
+ //#region \0rolldown/runtime.js
8
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
9
+ //#endregion
10
+ //#region ../../node_modules/.pnpm/tsdown@0.22.14_tsx@4.22.3_typescript@5.9.3_unrun@0.3.1/node_modules/tsdown/esm-shims.js
11
+ const getFilename = () => fileURLToPath(import.meta.url);
12
+ const __filename = /* @__PURE__ */ getFilename();
13
+ //#endregion
14
+ //#region src/write-output-files.ts
24
15
  async function writeOutputFiles(destination, files) {
25
- for (const file of files) {
26
- const target = join(destination, file.path);
27
- await mkdir(dirname(target), { recursive: true });
28
- const contents = typeof file.contents === "string" ? file.contents : Buffer.from(file.contents);
29
- await writeFile(target, contents);
30
- }
16
+ for (const file of files) {
17
+ const target = join(destination, file.path);
18
+ await mkdir(dirname(target), { recursive: true });
19
+ const contents = typeof file.contents === "string" ? file.contents : Buffer.from(file.contents);
20
+ await writeFile(target, contents);
21
+ }
31
22
  }
32
-
33
- // src/publish.ts
34
- var JSDOC_TUTORIAL_TYPE_MARKDOWN = 2;
23
+ //#endregion
24
+ //#region src/publish.ts
25
+ const JSDOC_TUTORIAL_TYPE_MARKDOWN = 2;
35
26
  function anchorPath() {
36
- if (typeof __filename === "string") return __filename;
37
- throw new Error(
38
- "clean-jsdoc-theme: could not determine the running module path (__filename is unavailable)."
39
- );
27
+ if (typeof __filename === "string") return __filename;
28
+ throw new Error("clean-jsdoc-theme: could not determine the running module path (__filename is unavailable).");
40
29
  }
41
30
  function resolvePackageDir(name) {
42
- const start = anchorPath();
43
- let dir = dirname2(start);
44
- let prev = "";
45
- while (dir !== prev) {
46
- const candidate = resolvePath(dir, "node_modules", name);
47
- try {
48
- readFileSync(resolvePath(candidate, "package.json"), "utf8");
49
- return candidate;
50
- } catch {
51
- }
52
- prev = dir;
53
- dir = dirname2(dir);
54
- }
55
- throw new Error(`clean-jsdoc-theme: could not locate '${name}' on disk starting from ${start}.`);
31
+ const start = anchorPath();
32
+ let dir = dirname(start);
33
+ let prev = "";
34
+ while (dir !== prev) {
35
+ const candidate = resolve(dir, "node_modules", name);
36
+ try {
37
+ readFileSync(resolve(candidate, "package.json"), "utf8");
38
+ return candidate;
39
+ } catch {}
40
+ prev = dir;
41
+ dir = dirname(dir);
42
+ }
43
+ throw new Error(`clean-jsdoc-theme: could not locate '${name}' on disk starting from ${start}.`);
56
44
  }
45
+ /**
46
+ * Resolve an `exports` condition subtree (a string target, or a conditions
47
+ * object like `{ import, require, default, types }`) to an absolute path,
48
+ * preferring the ESM condition (`import`, then a bare `default`). Recurses for
49
+ * nested conditions (`import: { default: "…" }`). Returns `undefined` when no
50
+ * usable target is present.
51
+ */
57
52
  function resolveExportTarget(node, pkgRoot) {
58
- if (typeof node === "string") return resolvePath(pkgRoot, node);
59
- if (!node || typeof node !== "object") return void 0;
60
- const o = node;
61
- const imp = resolveExportTarget(o.import, pkgRoot);
62
- if (imp) return imp;
63
- if (typeof o.default === "string") return resolvePath(pkgRoot, o.default);
64
- return void 0;
53
+ if (typeof node === "string") return resolve(pkgRoot, node);
54
+ if (!node || typeof node !== "object") return void 0;
55
+ const o = node;
56
+ const imp = resolveExportTarget(o.import, pkgRoot);
57
+ if (imp) return imp;
58
+ if (typeof o.default === "string") return resolve(pkgRoot, o.default);
65
59
  }
66
60
  function resolveEsmEntry(name) {
67
- const pkgRoot = resolvePackageDir(name);
68
- const pkg = JSON.parse(
69
- readFileSync(resolvePath(pkgRoot, "package.json"), "utf8")
70
- );
71
- const exp = pkg.exports;
72
- if (typeof exp === "string") return resolvePath(pkgRoot, exp);
73
- if (exp && typeof exp === "object") {
74
- const dot = exp["."];
75
- const target = resolveExportTarget(dot !== void 0 ? dot : exp, pkgRoot);
76
- if (target) return target;
77
- }
78
- if (typeof pkg.module === "string") return resolvePath(pkgRoot, pkg.module);
79
- if (typeof pkg.main === "string") return resolvePath(pkgRoot, pkg.main);
80
- throw new Error(
81
- `clean-jsdoc-theme: could not determine ESM entry file for '${name}' (no exports/module/main).`
82
- );
61
+ const pkgRoot = resolvePackageDir(name);
62
+ const pkg = JSON.parse(readFileSync(resolve(pkgRoot, "package.json"), "utf8"));
63
+ const exp = pkg.exports;
64
+ if (typeof exp === "string") return resolve(pkgRoot, exp);
65
+ if (exp && typeof exp === "object") {
66
+ const dot = exp["."];
67
+ const target = resolveExportTarget(dot !== void 0 ? dot : exp, pkgRoot);
68
+ if (target) return target;
69
+ }
70
+ if (typeof pkg.module === "string") return resolve(pkgRoot, pkg.module);
71
+ if (typeof pkg.main === "string") return resolve(pkgRoot, pkg.main);
72
+ throw new Error(`clean-jsdoc-theme: could not determine ESM entry file for '${name}' (no exports/module/main).`);
83
73
  }
84
74
  async function loadDep(name, requiredExports) {
85
- const entry = resolveEsmEntry(name);
86
- const id = pathToFileURL(entry).href;
87
- const mod = await import(id);
88
- for (const key of requiredExports) {
89
- if (typeof mod[key] !== "function") {
90
- throw new Error(
91
- `clean-jsdoc-theme: '${name}' did not export a '${key}' function (resolved from ${entry}; got keys: ${Object.keys(mod).join(", ") || "(none)"}).`
92
- );
93
- }
94
- }
95
- return mod;
75
+ const entry = resolveEsmEntry(name);
76
+ const mod = await import(pathToFileURL(entry).href);
77
+ for (const key of requiredExports) if (typeof mod[key] !== "function") throw new Error(`clean-jsdoc-theme: '${name}' did not export a '${key}' function (resolved from ${entry}; got keys: ${Object.keys(mod).join(", ") || "(none)"}).`);
78
+ return mod;
96
79
  }
97
- var loadSetu = () => loadDep("@clean-jsdoc-theme/setu", ["generateSite", "stampSite"]);
98
- var loadDwar = () => loadDep("@clean-jsdoc-theme/dwar", ["render", "runPagefindAgainstDir"]);
99
- var loadUtils = () => loadDep("@clean-jsdoc-theme/utils", [
100
- "validateThemeOpts",
101
- "createGoogleFontResolver",
102
- "formatDiagnostics",
103
- "formatBuildReport",
104
- "formatRenderError",
105
- "normalizeBasePath",
106
- "withBase",
107
- "toExtractManifest",
108
- "normalizeCollapsibleSidebarSections",
109
- "unmatchedCollapsibleSections",
110
- "topLevelSectionLabels",
111
- "normalizeScrollbar"
80
+ const loadSetu = () => loadDep("@clean-jsdoc-theme/setu", ["generateSite", "stampSite"]);
81
+ const loadDwar = () => loadDep("@clean-jsdoc-theme/dwar", ["render", "runPagefindAgainstDir"]);
82
+ const loadUtils = () => loadDep("@clean-jsdoc-theme/utils", [
83
+ "validateThemeOpts",
84
+ "createGoogleFontResolver",
85
+ "formatDiagnostics",
86
+ "warningsOnly",
87
+ "formatBuildReport",
88
+ "formatRenderError",
89
+ "normalizeBasePath",
90
+ "withBase",
91
+ "toExtractManifest",
92
+ "normalizeCollapsibleSidebarSections",
93
+ "unmatchedCollapsibleSections",
94
+ "topLevelSectionLabels",
95
+ "normalizeScrollbar"
112
96
  ]);
113
- var loadOra = async () => {
114
- try {
115
- const mod = await loadDep("ora", ["default"]);
116
- return mod.default;
117
- } catch {
118
- return null;
119
- }
97
+ /**
98
+ * Load `ora` (ESM-only) the same way as the other deps — via a resolved
99
+ * `file://` URL so the CJS bundle doesn't `require()` it. Returns `null` if
100
+ * `ora` can't be loaded, so progress degrades to silent rather than failing
101
+ * the build.
102
+ */
103
+ const loadOra = async () => {
104
+ try {
105
+ return (await loadDep("ora", ["default"])).default;
106
+ } catch {
107
+ return null;
108
+ }
120
109
  };
121
- var JSDOC_OWN_OPTS = /* @__PURE__ */ new Set([
122
- "destination",
123
- "template",
124
- "encoding",
125
- "recurse",
126
- "readme",
127
- "package",
128
- "tutorials",
129
- "query",
130
- "private",
131
- "access",
132
- "explain",
133
- "debug",
134
- "verbose",
135
- "pedantic",
136
- "match",
137
- "nocolor",
138
- "templates"
110
+ /**
111
+ * JSDoc's own standard `opts` keys (`jsdoc/lib/jsdoc/opts/argparser.js` +
112
+ * `conf` schema). These share the flat `opts` namespace with the theme's
113
+ * options, so they must never be flagged as unknown theme keys — even by a
114
+ * near-miss typo distance. Theme keys (`docs`, `docGroups`, …) live in
115
+ * `THEME_OPT_KEYS`, NOT here.
116
+ */
117
+ const JSDOC_OWN_OPTS = /* @__PURE__ */ new Set([
118
+ "destination",
119
+ "template",
120
+ "encoding",
121
+ "recurse",
122
+ "readme",
123
+ "package",
124
+ "tutorials",
125
+ "query",
126
+ "private",
127
+ "access",
128
+ "explain",
129
+ "debug",
130
+ "verbose",
131
+ "pedantic",
132
+ "match",
133
+ "nocolor",
134
+ "templates"
139
135
  ]);
140
- var defaultTheme = {
141
- tokens: {
142
- // Light palette (oklch). bg #fdfdf7 · fg #3e3e3e · border #eeeeee;
143
- // muted/accent derived to harmonize.
144
- colors: {
145
- bg: "oklch(0.9924 0.0079 106.54)",
146
- bgMuted: "oklch(0.9595 0.0079 106.55)",
147
- fg: "oklch(0.3639 0 0)",
148
- fgMuted: "oklch(0.5278 0 0)",
149
- accent: "oklch(0 0 0)",
150
- accentFg: "oklch(1 0 0)",
151
- border: "oklch(0.9561 0 0)"
152
- },
153
- // Dark palette (oklch). bg #09090b · fg #9e9e9e · border #141416;
154
- // muted/accent derived to harmonize.
155
- darkColors: {
156
- bg: "oklch(0.1408 0.0044 285.82)",
157
- bgMuted: "oklch(0.2103 0.0059 285.89)",
158
- fg: "oklch(0.6993 0 0)",
159
- fgMuted: "oklch(0.5382 0 0)",
160
- accent: "oklch(1 0 0)",
161
- accentFg: "oklch(0 0 0)",
162
- border: "oklch(0.2321 0.004 286.02)"
163
- },
164
- fonts: {
165
- heading: "Source Serif 4",
166
- body: "Roboto",
167
- mono: "ui-monospace, SFMono-Regular, Menlo, monospace"
168
- },
169
- shiki: { light: "github-light", dark: "github-dark" }
170
- },
171
- basePath: "/"
136
+ const defaultTheme = {
137
+ tokens: {
138
+ colors: {
139
+ bg: "oklch(0.9924 0.0079 106.54)",
140
+ bgMuted: "oklch(0.9595 0.0079 106.55)",
141
+ fg: "oklch(0.3639 0 0)",
142
+ fgMuted: "oklch(0.5278 0 0)",
143
+ accent: "oklch(0 0 0)",
144
+ accentFg: "oklch(1 0 0)",
145
+ border: "oklch(0.9561 0 0)"
146
+ },
147
+ darkColors: {
148
+ bg: "oklch(0.1408 0.0044 285.82)",
149
+ bgMuted: "oklch(0.2103 0.0059 285.89)",
150
+ fg: "oklch(0.6993 0 0)",
151
+ fgMuted: "oklch(0.5382 0 0)",
152
+ accent: "oklch(1 0 0)",
153
+ accentFg: "oklch(0 0 0)",
154
+ border: "oklch(0.2321 0.004 286.02)"
155
+ },
156
+ fonts: {
157
+ heading: "Source Serif 4",
158
+ body: "Roboto",
159
+ mono: "ui-monospace, SFMono-Regular, Menlo, monospace"
160
+ },
161
+ shiki: {
162
+ light: "github-light",
163
+ dark: "github-dark"
164
+ }
165
+ },
166
+ basePath: "/"
172
167
  };
168
+ /**
169
+ * Resolve the font triple for the active `locale`: a per-locale override wins,
170
+ * then the base font, then the theme default — per slot. With no locale (a
171
+ * normal, non-localized build) only the base + default apply, so the result is
172
+ * byte-identical to before per-locale fonts existed.
173
+ */
173
174
  function resolveFontSet(fonts, locale) {
174
- const base = defaultTheme.tokens.fonts;
175
- const override = locale && fonts.locales?.[locale] || {};
176
- return {
177
- heading: override.heading ?? fonts.heading ?? base.heading,
178
- body: override.body ?? fonts.body ?? base.body,
179
- mono: override.mono ?? fonts.mono ?? base.mono
180
- };
175
+ const base = defaultTheme.tokens.fonts;
176
+ const override = locale && fonts.locales?.[locale] || {};
177
+ return {
178
+ heading: override.heading ?? fonts.heading ?? base.heading,
179
+ body: override.body ?? fonts.body ?? base.body,
180
+ mono: override.mono ?? fonts.mono ?? base.mono
181
+ };
181
182
  }
183
+ /**
184
+ * Merge validated user overrides from `jsdoc.json` (`siteName`, `fonts`) over
185
+ * the defaults. Only the keys the user supplies are overridden; everything else
186
+ * keeps the default theme. `siteName` is pre-resolved/validated and its local
187
+ * logos copied by `prepareSiteName`; `fonts` is the validated subset (any
188
+ * family flagged `fonts/not-google` is dropped upstream so the default applies).
189
+ * `locale` (set in build mode) selects per-locale font overrides.
190
+ */
182
191
  function resolveTheme(opts, siteName, fonts, basePath, locale) {
183
- const aiPrompt = typeof opts.aiPrompt === "string" && opts.aiPrompt.trim() ? opts.aiPrompt.trim() : void 0;
184
- const copyPage = normalizeCopyPage(opts.copyPage);
185
- const pageNav = normalizePageNav(opts.pageNav);
186
- const playground = normalizePlayground(opts.playground);
187
- const colors = normalizeColors(opts.colors);
188
- const darkColors = normalizeColors(opts.darkColors);
189
- return {
190
- ...defaultTheme,
191
- basePath,
192
- ...aiPrompt ? { aiPrompt } : {},
193
- ...copyPage ? { copyPage } : {},
194
- ...pageNav ? { pageNav } : {},
195
- ...playground ? { playground: playground.theme } : {},
196
- tokens: {
197
- ...defaultTheme.tokens,
198
- colors: { ...defaultTheme.tokens.colors, ...colors ?? {} },
199
- darkColors: { ...defaultTheme.tokens.darkColors, ...darkColors ?? {} },
200
- fonts: resolveFontSet(fonts, locale),
201
- ...siteName ? { siteName } : {}
202
- }
203
- };
192
+ const aiPrompt = typeof opts.aiPrompt === "string" && opts.aiPrompt.trim() ? opts.aiPrompt.trim() : void 0;
193
+ const copyPage = normalizeCopyPage(opts.copyPage);
194
+ const pageNav = normalizePageNav(opts.pageNav);
195
+ const playground = normalizePlayground(opts.playground);
196
+ const colors = normalizeColors(opts.colors);
197
+ const darkColors = normalizeColors(opts.darkColors);
198
+ return {
199
+ ...defaultTheme,
200
+ basePath,
201
+ ...aiPrompt ? { aiPrompt } : {},
202
+ ...copyPage ? { copyPage } : {},
203
+ ...pageNav ? { pageNav } : {},
204
+ ...playground ? { playground: playground.theme } : {},
205
+ tokens: {
206
+ ...defaultTheme.tokens,
207
+ colors: {
208
+ ...defaultTheme.tokens.colors,
209
+ ...colors ?? {}
210
+ },
211
+ darkColors: {
212
+ ...defaultTheme.tokens.darkColors,
213
+ ...darkColors ?? {}
214
+ },
215
+ fonts: resolveFontSet(fonts, locale),
216
+ ...siteName ? { siteName } : {}
217
+ }
218
+ };
204
219
  }
220
+ /** Trim a value to a non-empty string, or `undefined`. */
205
221
  function nonEmptyString(value) {
206
- return typeof value === "string" && value.trim().length > 0 ? value : void 0;
222
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
207
223
  }
224
+ /**
225
+ * Short, deterministic content hash for cache-stable custom-asset filenames.
226
+ * Derived from the file's bytes (NOT random), so an unchanged file produces the
227
+ * same name across builds (browser cache hit) and a changed file cache-busts.
228
+ */
208
229
  function contentHash(bytes) {
209
- return createHash("sha256").update(bytes).digest("hex").slice(0, 8);
230
+ return createHash("sha256").update(bytes).digest("hex").slice(0, 8);
210
231
  }
232
+ /**
233
+ * Copy custom CSS/JS file(s) (a path or array, relative to the working dir) to
234
+ * served `_assets` files and return their hrefs. Each file is copied AS-IS (its
235
+ * own bytes — never concatenated). The asset name is `<base>.<hash>.<ext>` when
236
+ * `hash` is on (the hash is content-derived → stable URL for unchanged files),
237
+ * else the bare `<base><ext>`. A file that can't be read is skipped with a
238
+ * warning (resilient, like `prepareSiteName`); an identical served name is
239
+ * emitted once.
240
+ */
211
241
  async function copyCustomFiles(raw, ext, hash, label, hrefForServed) {
212
- const paths = (Array.isArray(raw) ? raw : [raw]).filter(
213
- (p) => typeof p === "string" && p.trim().length > 0
214
- );
215
- const links = [];
216
- const files = [];
217
- const seen = /* @__PURE__ */ new Set();
218
- for (const p of paths) {
219
- const trimmed = p.trim();
220
- let bytes;
221
- try {
222
- bytes = await readFile(resolvePath(trimmed));
223
- } catch {
224
- console.warn(`clean-jsdoc-theme: could not read ${label} ('${trimmed}'); skipping it.`);
225
- continue;
226
- }
227
- const base = basename(trimmed, extname(trimmed)) || "custom";
228
- const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;
229
- const servedPath = `_assets/${name}`;
230
- if (seen.has(servedPath)) continue;
231
- seen.add(servedPath);
232
- files.push({ path: servedPath, contents: bytes });
233
- links.push(hrefForServed(servedPath));
234
- }
235
- return { links, files };
242
+ const paths = (Array.isArray(raw) ? raw : [raw]).filter((p) => typeof p === "string" && p.trim().length > 0);
243
+ const links = [];
244
+ const files = [];
245
+ const seen = /* @__PURE__ */ new Set();
246
+ for (const p of paths) {
247
+ const trimmed = p.trim();
248
+ let bytes;
249
+ try {
250
+ bytes = await readFile(resolve(trimmed));
251
+ } catch {
252
+ console.warn(`clean-jsdoc-theme: could not read ${label} ('${trimmed}'); skipping it.`);
253
+ continue;
254
+ }
255
+ const base = basename(trimmed, extname(trimmed)) || "custom";
256
+ const servedPath = `_assets/${hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`}`;
257
+ if (seen.has(servedPath)) continue;
258
+ seen.add(servedPath);
259
+ files.push({
260
+ path: servedPath,
261
+ contents: bytes
262
+ });
263
+ links.push(hrefForServed(servedPath));
264
+ }
265
+ return {
266
+ links,
267
+ files
268
+ };
236
269
  }
270
+ /**
271
+ * Resolve the custom CSS/JS injection options into render-ready `ThemeConfig`
272
+ * fields plus the asset files to write. Inline strings (`customCss`/`customJs`)
273
+ * pass through; file options (`customCssFile`/`customJsFile`) are read + copied
274
+ * to content-hashed assets here — the bridge is the I/O layer, so dwar's
275
+ * `render()` stays pure and just links the resulting hrefs. `hashCustomAssets`
276
+ * (default `true`) toggles the content-hash suffix.
277
+ */
237
278
  async function resolveCustomAssets(opts, hrefForServed) {
238
- const hash = opts.hashCustomAssets !== false;
239
- const [cssAssets, jsAssets] = await Promise.all([
240
- copyCustomFiles(opts.customCssFile, ".css", hash, "customCssFile", hrefForServed),
241
- copyCustomFiles(opts.customJsFile, ".js", hash, "customJsFile", hrefForServed)
242
- ]);
243
- const customCss = nonEmptyString(opts.customCss)?.trim();
244
- const customJs = nonEmptyString(opts.customJs)?.trim();
245
- return {
246
- theme: {
247
- ...customCss ? { customCss } : {},
248
- ...cssAssets.links.length > 0 ? { customCssLinks: cssAssets.links } : {},
249
- ...customJs ? { customJs } : {},
250
- ...jsAssets.links.length > 0 ? { customJsLinks: jsAssets.links } : {}
251
- },
252
- files: [...cssAssets.files, ...jsAssets.files]
253
- };
279
+ const hash = opts.hashCustomAssets !== false;
280
+ const [cssAssets, jsAssets] = await Promise.all([copyCustomFiles(opts.customCssFile, ".css", hash, "customCssFile", hrefForServed), copyCustomFiles(opts.customJsFile, ".js", hash, "customJsFile", hrefForServed)]);
281
+ const customCss = nonEmptyString(opts.customCss)?.trim();
282
+ const customJs = nonEmptyString(opts.customJs)?.trim();
283
+ return {
284
+ theme: {
285
+ ...customCss ? { customCss } : {},
286
+ ...cssAssets.links.length > 0 ? { customCssLinks: cssAssets.links } : {},
287
+ ...customJs ? { customJs } : {},
288
+ ...jsAssets.links.length > 0 ? { customJsLinks: jsAssets.links } : {}
289
+ },
290
+ files: [...cssAssets.files, ...jsAssets.files]
291
+ };
254
292
  }
293
+ /**
294
+ * Resolve `opts.footer` (inline HTML `string` | `{ file }`) into the single
295
+ * `ThemeConfig.footer` string. The `{ file }` form is read from disk HERE — the
296
+ * bridge is the I/O layer, so dwar's `render()` only ever sees the resolved
297
+ * string. A missing/unreadable file is warned about and dropped (resilient,
298
+ * like the logo/custom-asset paths), and an empty value yields `undefined` so
299
+ * the default footer renders. Exported for testing.
300
+ */
255
301
  async function resolveFooter(raw) {
256
- if (typeof raw === "string") {
257
- const trimmed = raw.trim();
258
- return trimmed.length > 0 ? trimmed : void 0;
259
- }
260
- if (raw && typeof raw === "object" && typeof raw.file === "string") {
261
- const file = raw.file.trim();
262
- if (!file) return void 0;
263
- try {
264
- const html = await readFile(resolvePath(file), "utf8");
265
- return html.trim().length > 0 ? html : void 0;
266
- } catch {
267
- console.warn(
268
- `clean-jsdoc-theme: could not read footer file ('${file}'); omitting the custom footer.`
269
- );
270
- return void 0;
271
- }
272
- }
273
- return void 0;
302
+ if (typeof raw === "string") {
303
+ const trimmed = raw.trim();
304
+ return trimmed.length > 0 ? trimmed : void 0;
305
+ }
306
+ if (raw && typeof raw === "object" && typeof raw.file === "string") {
307
+ const file = raw.file.trim();
308
+ if (!file) return void 0;
309
+ try {
310
+ const html = await readFile(resolve(file), "utf8");
311
+ return html.trim().length > 0 ? html : void 0;
312
+ } catch {
313
+ console.warn(`clean-jsdoc-theme: could not read footer file ('${file}'); omitting the custom footer.`);
314
+ return;
315
+ }
316
+ }
274
317
  }
318
+ /**
319
+ * Resolve `opts.favicon` (a file path) into a served `_assets/` href + the file
320
+ * to write — the bridge is the I/O layer, so dwar only sees the final URL and
321
+ * `render()` stays pure. The asset name is content-hashed (cache-busted) unless
322
+ * `hash` is off, and the source extension is preserved so dwar can derive the
323
+ * `<link>` `type`. A missing/unreadable file is warned about and dropped
324
+ * (resilient, like the logo/custom-asset paths). Exported for testing.
325
+ */
275
326
  async function resolveFavicon(raw, hash, hrefForServed) {
276
- if (typeof raw !== "string" || raw.trim().length === 0) return void 0;
277
- const trimmed = raw.trim();
278
- let bytes;
279
- try {
280
- bytes = await readFile(resolvePath(trimmed));
281
- } catch {
282
- console.warn(`clean-jsdoc-theme: could not read favicon ('${trimmed}'); omitting it.`);
283
- return void 0;
284
- }
285
- const ext = extname(trimmed) || ".ico";
286
- const base = basename(trimmed, extname(trimmed)) || "favicon";
287
- const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;
288
- const servedPath = `_assets/${name}`;
289
- return { href: hrefForServed(servedPath), files: [{ path: servedPath, contents: bytes }] };
327
+ if (typeof raw !== "string" || raw.trim().length === 0) return void 0;
328
+ const trimmed = raw.trim();
329
+ let bytes;
330
+ try {
331
+ bytes = await readFile(resolve(trimmed));
332
+ } catch {
333
+ console.warn(`clean-jsdoc-theme: could not read favicon ('${trimmed}'); omitting it.`);
334
+ return;
335
+ }
336
+ const ext = extname(trimmed) || ".ico";
337
+ const base = basename(trimmed, extname(trimmed)) || "favicon";
338
+ const servedPath = `_assets/${hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`}`;
339
+ return {
340
+ href: hrefForServed(servedPath),
341
+ files: [{
342
+ path: servedPath,
343
+ contents: bytes
344
+ }]
345
+ };
290
346
  }
291
- var META_IDENTITY_ATTRS = ["name", "property", "http-equiv", "charset", "itemprop"];
347
+ /** Attributes that identify a `<meta>` tag (so an entry must carry at least one). */
348
+ const META_IDENTITY_ATTRS = [
349
+ "name",
350
+ "property",
351
+ "http-equiv",
352
+ "charset",
353
+ "itemprop"
354
+ ];
355
+ /**
356
+ * Validate `opts.meta` into a clean `MetaTag[]` (attribute maps), or `undefined`
357
+ * when there's nothing usable. Accepts only an array of objects; within each,
358
+ * keeps string→string pairs (trimming the value, coercing finite numbers to
359
+ * strings for convenience) and drops the rest. An entry with no recognized
360
+ * identifying attribute (`name`/`property`/`http-equiv`/`charset`/`itemprop`) is
361
+ * dropped with a warning — dwar does the final escaping + key validation.
362
+ */
292
363
  function normalizeMeta(raw) {
293
- if (!Array.isArray(raw)) return void 0;
294
- const out = [];
295
- for (const entry of raw) {
296
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
297
- const o = entry;
298
- const tag = {};
299
- for (const [k, v] of Object.entries(o)) {
300
- if (typeof v === "string") {
301
- const t = v.trim();
302
- if (t.length > 0) tag[k] = t;
303
- } else if (typeof v === "number" && Number.isFinite(v)) {
304
- tag[k] = String(v);
305
- }
306
- }
307
- const hasIdentity = META_IDENTITY_ATTRS.some((a) => typeof tag[a] === "string");
308
- if (!hasIdentity || Object.keys(tag).length === 0) {
309
- console.warn(
310
- `clean-jsdoc-theme: skipping a meta entry with no usable name/property/http-equiv/charset attribute (${JSON.stringify(entry)}).`
311
- );
312
- continue;
313
- }
314
- out.push(tag);
315
- }
316
- return out.length > 0 ? out : void 0;
364
+ if (!Array.isArray(raw)) return void 0;
365
+ const out = [];
366
+ for (const entry of raw) {
367
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
368
+ const o = entry;
369
+ const tag = {};
370
+ for (const [k, v] of Object.entries(o)) if (typeof v === "string") {
371
+ const t = v.trim();
372
+ if (t.length > 0) tag[k] = t;
373
+ } else if (typeof v === "number" && Number.isFinite(v)) tag[k] = String(v);
374
+ if (!META_IDENTITY_ATTRS.some((a) => typeof tag[a] === "string") || Object.keys(tag).length === 0) {
375
+ console.warn(`clean-jsdoc-theme: skipping a meta entry with no usable name/property/http-equiv/charset attribute (${JSON.stringify(entry)}).`);
376
+ continue;
377
+ }
378
+ out.push(tag);
379
+ }
380
+ return out.length > 0 ? out : void 0;
317
381
  }
382
+ /** A logo value that's already a servable URL/URI needs no copying. */
318
383
  function isServableUrl(value) {
319
- return /^(https?:)?\/\//i.test(value) || /^data:/i.test(value);
384
+ return /^(https?:)?\/\//i.test(value) || /^data:/i.test(value);
320
385
  }
386
+ /**
387
+ * Resolve `opts.siteName` into a render-ready value plus any image files to
388
+ * write. A string passes through (trimmed). For a logo set, each local image
389
+ * path is read and emitted as a content-hashed output asset
390
+ * (`_assets/logo-<key>.<hash><ext>`, cache-busted like the custom assets) with
391
+ * its value rewritten to the served path; `http(s)://` / `data:` values pass
392
+ * through untouched, and the `alt` label is preserved. A path that can't be
393
+ * read is left verbatim with a warning rather than aborting the build.
394
+ */
321
395
  async function prepareSiteName(raw, hrefForServed) {
322
- if (typeof raw === "string") {
323
- const trimmed = raw.trim();
324
- return { siteName: trimmed.length > 0 ? trimmed : void 0, files: [] };
325
- }
326
- if (!raw || typeof raw !== "object") return { siteName: void 0, files: [] };
327
- const files = [];
328
- const out = {};
329
- if (typeof raw.alt === "string" && raw.alt.trim().length > 0) out.alt = raw.alt.trim();
330
- for (const key of ["default", "dark", "light"]) {
331
- const value = raw[key];
332
- if (typeof value !== "string" || value.trim().length === 0) continue;
333
- const v = value.trim();
334
- if (isServableUrl(v)) {
335
- out[key] = v;
336
- continue;
337
- }
338
- try {
339
- const abs = resolvePath(v);
340
- const buf = await readFile(abs);
341
- const served = `_assets/logo-${key}.${contentHash(buf)}${extname(abs)}`;
342
- files.push({ path: served, contents: buf });
343
- out[key] = hrefForServed(served);
344
- } catch {
345
- console.warn(
346
- `clean-jsdoc-theme: could not read logo image for siteName.${key} ('${v}'); using it verbatim.`
347
- );
348
- out[key] = v;
349
- }
350
- }
351
- const hasContent = out.default || out.dark || out.light || out.alt;
352
- return { siteName: hasContent ? out : void 0, files };
396
+ if (typeof raw === "string") {
397
+ const trimmed = raw.trim();
398
+ return {
399
+ siteName: trimmed.length > 0 ? trimmed : void 0,
400
+ files: []
401
+ };
402
+ }
403
+ if (!raw || typeof raw !== "object") return {
404
+ siteName: void 0,
405
+ files: []
406
+ };
407
+ const files = [];
408
+ const out = {};
409
+ if (typeof raw.alt === "string" && raw.alt.trim().length > 0) out.alt = raw.alt.trim();
410
+ for (const key of [
411
+ "default",
412
+ "dark",
413
+ "light"
414
+ ]) {
415
+ const value = raw[key];
416
+ if (typeof value !== "string" || value.trim().length === 0) continue;
417
+ const v = value.trim();
418
+ if (isServableUrl(v)) {
419
+ out[key] = v;
420
+ continue;
421
+ }
422
+ try {
423
+ const abs = resolve(v);
424
+ const buf = await readFile(abs);
425
+ const served = `_assets/logo-${key}.${contentHash(buf)}${extname(abs)}`;
426
+ files.push({
427
+ path: served,
428
+ contents: buf
429
+ });
430
+ out[key] = hrefForServed(served);
431
+ } catch {
432
+ console.warn(`clean-jsdoc-theme: could not read logo image for siteName.${key} ('${v}'); using it verbatim.`);
433
+ out[key] = v;
434
+ }
435
+ }
436
+ return {
437
+ siteName: out.default || out.dark || out.light || out.alt ? out : void 0,
438
+ files
439
+ };
353
440
  }
354
441
  async function resolvePkg(data, opts) {
355
- if (typeof opts.package === "string" && opts.package.length > 0) {
356
- try {
357
- const json = await readFile(opts.package, "utf8");
358
- const parsed = JSON.parse(json);
359
- return pickPkgFields(parsed);
360
- } catch {
361
- }
362
- }
363
- if (typeof data === "function") {
364
- try {
365
- const pkgDoclets = data({ kind: "package" }).get();
366
- if (Array.isArray(pkgDoclets) && pkgDoclets.length > 0) {
367
- return pickPkgFields(pkgDoclets[0]);
368
- }
369
- } catch {
370
- }
371
- }
372
- return void 0;
442
+ if (typeof opts.package === "string" && opts.package.length > 0) try {
443
+ const json = await readFile(opts.package, "utf8");
444
+ return pickPkgFields(JSON.parse(json));
445
+ } catch {}
446
+ if (typeof data === "function") try {
447
+ const pkgDoclets = data({ kind: "package" }).get();
448
+ if (Array.isArray(pkgDoclets) && pkgDoclets.length > 0) return pickPkgFields(pkgDoclets[0]);
449
+ } catch {}
373
450
  }
374
451
  function pickPkgFields(raw) {
375
- const pkg = {};
376
- if (typeof raw.name === "string") pkg.name = raw.name;
377
- if (typeof raw.version === "string") pkg.version = raw.version;
378
- if (typeof raw.description === "string") pkg.description = raw.description;
379
- if (typeof raw.homepage === "string") pkg.homepage = raw.homepage;
380
- if (typeof raw.repository === "string") {
381
- pkg.repository = raw.repository;
382
- } else if (raw.repository && typeof raw.repository === "object" && typeof raw.repository.url === "string") {
383
- pkg.repository = raw.repository.url;
384
- }
385
- return pkg;
452
+ const pkg = {};
453
+ if (typeof raw.name === "string") pkg.name = raw.name;
454
+ if (typeof raw.version === "string") pkg.version = raw.version;
455
+ if (typeof raw.description === "string") pkg.description = raw.description;
456
+ if (typeof raw.homepage === "string") pkg.homepage = raw.homepage;
457
+ if (typeof raw.repository === "string") pkg.repository = raw.repository;
458
+ else if (raw.repository && typeof raw.repository === "object" && typeof raw.repository.url === "string") pkg.repository = raw.repository.url;
459
+ return pkg;
386
460
  }
461
+ /**
462
+ * Normalize JSDoc's tutorial resolver tree (the `tutorials` arg to `publish`)
463
+ * into setu's plain {@link TutorialInput} shape. The root's `children` are the
464
+ * top-level tutorials; each child carries its own `children`, so a depth-first
465
+ * walk preserves the resolved hierarchy. Content is taken raw (`.content`);
466
+ * `.type === 2` (MARKDOWN) is markdown, everything else is treated as HTML.
467
+ */
387
468
  function normalizeTutorials(root) {
388
- const walk = (node) => {
389
- const name = typeof node.name === "string" ? node.name : "";
390
- if (!name) return null;
391
- const title = typeof node.title === "string" && node.title.length > 0 ? node.title : name;
392
- const content = typeof node.content === "string" ? node.content : "";
393
- const type = node.type === JSDOC_TUTORIAL_TYPE_MARKDOWN ? "markdown" : "html";
394
- const children2 = Array.isArray(node.children) ? node.children.map(walk).filter((t) => t !== null) : [];
395
- return { name, title, content, type, children: children2 };
396
- };
397
- const children = root?.children;
398
- if (!Array.isArray(children)) return [];
399
- return children.map(walk).filter((t) => t !== null);
469
+ const walk = (node) => {
470
+ const name = typeof node.name === "string" ? node.name : "";
471
+ if (!name) return null;
472
+ return {
473
+ name,
474
+ title: typeof node.title === "string" && node.title.length > 0 ? node.title : name,
475
+ content: typeof node.content === "string" ? node.content : "",
476
+ type: node.type === JSDOC_TUTORIAL_TYPE_MARKDOWN ? "markdown" : "html",
477
+ children: Array.isArray(node.children) ? node.children.map(walk).filter((t) => t !== null) : []
478
+ };
479
+ };
480
+ const children = root?.children;
481
+ if (!Array.isArray(children)) return [];
482
+ return children.map(walk).filter((t) => t !== null);
400
483
  }
484
+ /**
485
+ * Resolve JSDoc's `templates.default.outputSourceFiles` flag. The `opts` arg
486
+ * `publish` receives is `env.opts` — the `opts` block — which does NOT carry the
487
+ * root-level `templates` block, so we probe in priority order and default ON:
488
+ * 1. `require('jsdoc/env').conf.templates.default.outputSourceFiles` (the
489
+ * canonical location at runtime; wrapped in try/catch so a missing
490
+ * `jsdoc/env` — e.g. in unit tests — never throws the build).
491
+ * 2. `opts.templates.default.outputSourceFiles` (in case a user nests it
492
+ * under `opts`).
493
+ * Resolves to `false` ONLY when one of those is exactly `=== false`; otherwise
494
+ * `true` (matching JSDoc's default-template default).
495
+ */
401
496
  function outputSourceFilesEnabled(opts) {
402
- try {
403
- const env = __require("jsdoc/env");
404
- if (env?.conf?.templates?.default?.outputSourceFiles === false) return false;
405
- } catch {
406
- }
407
- if (opts?.templates?.default?.outputSourceFiles === false) return false;
408
- return true;
497
+ try {
498
+ if (__require("jsdoc/env")?.conf?.templates?.default?.outputSourceFiles === false) return false;
499
+ } catch {}
500
+ if (opts?.templates?.default?.outputSourceFiles === false) return false;
501
+ return true;
409
502
  }
503
+ /**
504
+ * Resolve `templates.default.sourceLinkToComment`. Probed in the same priority
505
+ * order as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a
506
+ * nested `opts.templates` fallback). Resolves to `true` ONLY when one of those
507
+ * is exactly `=== true`; otherwise `false` (the default: links jump to code).
508
+ */
410
509
  function sourceLinkToCommentEnabled(opts) {
411
- try {
412
- const env = __require("jsdoc/env");
413
- if (env?.conf?.templates?.default?.sourceLinkToComment === true) return true;
414
- } catch {
415
- }
416
- if (opts?.templates?.default?.sourceLinkToComment === true) return true;
417
- return false;
510
+ try {
511
+ if (__require("jsdoc/env")?.conf?.templates?.default?.sourceLinkToComment === true) return true;
512
+ } catch {}
513
+ if (opts?.templates?.default?.sourceLinkToComment === true) return true;
514
+ return false;
418
515
  }
516
+ /**
517
+ * Resolve `templates.default.cleanOutputDir`. Probed in the same priority order
518
+ * as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a nested
519
+ * `opts.templates` fallback). Defaults to `true` — the build empties its
520
+ * destination first so a page removed or renamed between runs (e.g. a deleted
521
+ * class, or a stale content-hashed `styles.<hash>.css`) doesn't linger in the
522
+ * served site. Resolves to `false` ONLY when one is exactly `=== false`.
523
+ */
419
524
  function cleanOutputDirEnabled(opts) {
420
- try {
421
- const env = __require("jsdoc/env");
422
- if (env?.conf?.templates?.default?.cleanOutputDir === false) return false;
423
- } catch {
424
- }
425
- if (opts?.templates?.default?.cleanOutputDir === false) return false;
426
- return true;
525
+ try {
526
+ if (__require("jsdoc/env")?.conf?.templates?.default?.cleanOutputDir === false) return false;
527
+ } catch {}
528
+ if (opts?.templates?.default?.cleanOutputDir === false) return false;
529
+ return true;
427
530
  }
531
+ /**
532
+ * Whether a JSDoc `conf.plugins` list enables the bundled `plugins/markdown`
533
+ * plugin. The theme relies on it: JSDoc runs `plugins/markdown` to convert the
534
+ * Markdown in doclet descriptions/tags to HTML *before* `publish` ever sees the
535
+ * doclets, so without it descriptions arrive as raw Markdown and render wrong.
536
+ * Pure + exported for testing — accepts the `plugins` array (module specifiers,
537
+ * e.g. `"plugins/markdown"`; tolerant of a `.js` suffix or path separators).
538
+ */
428
539
  function hasMarkdownPlugin(plugins) {
429
- if (!Array.isArray(plugins)) return false;
430
- return plugins.some((p) => typeof p === "string" && /(^|[\\/])markdown(\.js)?$/i.test(p.trim()));
540
+ if (!Array.isArray(plugins)) return false;
541
+ return plugins.some((p) => typeof p === "string" && /(^|[\\/])markdown(\.js)?$/i.test(p.trim()));
431
542
  }
543
+ /**
544
+ * Hard-require JSDoc's `plugins/markdown` plugin (see {@link hasMarkdownPlugin}).
545
+ * Reads the merged config from `require('jsdoc/env').conf.plugins` — the
546
+ * canonical location at runtime — and throws if the plugin is absent so the
547
+ * build stops early with an actionable message. When `jsdoc/env` can't be
548
+ * resolved (e.g. unit tests, or a non-JSDoc caller) the check is skipped: the
549
+ * plugin list is unknowable there, so it can't be enforced.
550
+ */
432
551
  function assertMarkdownPlugin() {
433
- let conf;
434
- try {
435
- conf = __require("jsdoc/env").conf;
436
- } catch {
437
- return;
438
- }
439
- if (!conf) return;
440
- if (!hasMarkdownPlugin(conf.plugins)) {
441
- throw new Error(
442
- `clean-jsdoc-theme requires JSDoc's "plugins/markdown" plugin, which renders Markdown in doclet descriptions to HTML. Add it to your jsdoc.json:
443
-
444
- "plugins": ["plugins/markdown"]
445
- `
446
- );
447
- }
552
+ let conf;
553
+ try {
554
+ conf = __require("jsdoc/env").conf;
555
+ } catch {
556
+ return;
557
+ }
558
+ if (!conf) return;
559
+ if (!hasMarkdownPlugin(conf.plugins)) throw new Error("clean-jsdoc-theme requires JSDoc's \"plugins/markdown\" plugin, which renders Markdown in doclet descriptions to HTML. Add it to your jsdoc.json:\n\n \"plugins\": [\"plugins/markdown\"]\n");
448
560
  }
561
+ /**
562
+ * Validate `opts.sectionOrder` into a clean `string[]`, or `undefined` to fall
563
+ * back to setu's default order. Accepts only an array; trims string entries and
564
+ * drops non-strings/empties. An array that yields no usable labels → `undefined`.
565
+ */
449
566
  function normalizeSectionOrder(raw) {
450
- if (!Array.isArray(raw)) return void 0;
451
- const out = raw.filter((s) => typeof s === "string").map((s) => s.trim()).filter((s) => s.length > 0);
452
- return out.length > 0 ? out : void 0;
567
+ if (!Array.isArray(raw)) return void 0;
568
+ const out = raw.filter((s) => typeof s === "string").map((s) => s.trim()).filter((s) => s.length > 0);
569
+ return out.length > 0 ? out : void 0;
453
570
  }
571
+ /**
572
+ * Validate `opts.menu` into a clean `MenuItem[]`, or `undefined` when there's no
573
+ * usable menu. Accepts only an array of objects; trims string fields. The link
574
+ * URL is read from `link` (preferred) or `href`. Keeps only actionable entries —
575
+ * a built-in (`id`) or an external link (`link`/`href`).
576
+ */
454
577
  function normalizeMenu(raw) {
455
- if (!Array.isArray(raw)) return void 0;
456
- const out = [];
457
- for (const entry of raw) {
458
- if (!entry || typeof entry !== "object") continue;
459
- const o = entry;
460
- const item = {};
461
- if (typeof o.id === "string" && o.id.trim()) item.id = o.id.trim();
462
- if (typeof o.title === "string" && o.title.trim()) item.title = o.title.trim();
463
- const link = typeof o.link === "string" && o.link.trim() ? o.link.trim() : typeof o.href === "string" && o.href.trim() ? o.href.trim() : void 0;
464
- if (link) item.link = link;
465
- if (typeof o.icon === "string" && o.icon.trim()) item.icon = o.icon.trim();
466
- if (typeof o.target === "string" && o.target.trim()) item.target = o.target.trim();
467
- if (typeof o.class === "string" && o.class.trim()) item.class = o.class.trim();
468
- if (item.id || item.link) out.push(item);
469
- }
470
- return out.length > 0 ? out : void 0;
578
+ if (!Array.isArray(raw)) return void 0;
579
+ const out = [];
580
+ for (const entry of raw) {
581
+ if (!entry || typeof entry !== "object") continue;
582
+ const o = entry;
583
+ const item = {};
584
+ if (typeof o.id === "string" && o.id.trim()) item.id = o.id.trim();
585
+ if (typeof o.title === "string" && o.title.trim()) item.title = o.title.trim();
586
+ const link = typeof o.link === "string" && o.link.trim() ? o.link.trim() : typeof o.href === "string" && o.href.trim() ? o.href.trim() : void 0;
587
+ if (link) item.link = link;
588
+ if (typeof o.icon === "string" && o.icon.trim()) item.icon = o.icon.trim();
589
+ if (typeof o.target === "string" && o.target.trim()) item.target = o.target.trim();
590
+ if (typeof o.class === "string" && o.class.trim()) item.class = o.class.trim();
591
+ if (item.id || item.link) out.push(item);
592
+ }
593
+ return out.length > 0 ? out : void 0;
471
594
  }
472
- var COPY_PAGE_ACTIONS = [
473
- "copy",
474
- "view",
475
- "claude",
476
- "chatgpt",
477
- "perplexity"
595
+ /** Valid copy-page dropdown actions (mirrors setu/dwar's `CopyPageAction`). */
596
+ const COPY_PAGE_ACTIONS = [
597
+ "copy",
598
+ "view",
599
+ "claude",
600
+ "chatgpt",
601
+ "perplexity"
478
602
  ];
603
+ /**
604
+ * Validate `opts.copyPage` into a {@link CopyPageConfig}, or `undefined` to use
605
+ * the defaults (enabled, all actions). Accepts a boolean shorthand (`false`
606
+ * hides the button) or an object: `enabled` is read if boolean; `actions`, if an
607
+ * array, is filtered to the known action ids (preserving order, dropping
608
+ * unknowns/dupes) — an empty/all-invalid array still yields `[]` (primary button
609
+ * only), which is meaningful and kept.
610
+ */
479
611
  function normalizeCopyPage(raw) {
480
- if (raw === false) return { enabled: false };
481
- if (raw === true || raw == null) return void 0;
482
- if (typeof raw !== "object") return void 0;
483
- const o = raw;
484
- const config = {};
485
- if (typeof o.enabled === "boolean") config.enabled = o.enabled;
486
- if (Array.isArray(o.actions)) {
487
- const seen = /* @__PURE__ */ new Set();
488
- for (const a of o.actions) {
489
- if (typeof a === "string" && COPY_PAGE_ACTIONS.includes(a)) {
490
- seen.add(a);
491
- }
492
- }
493
- config.actions = COPY_PAGE_ACTIONS.filter((a) => seen.has(a));
494
- }
495
- return Object.keys(config).length > 0 ? config : void 0;
612
+ if (raw === false) return { enabled: false };
613
+ if (raw === true || raw == null) return void 0;
614
+ if (typeof raw !== "object") return void 0;
615
+ const o = raw;
616
+ const config = {};
617
+ if (typeof o.enabled === "boolean") config.enabled = o.enabled;
618
+ if (Array.isArray(o.actions)) {
619
+ const seen = /* @__PURE__ */ new Set();
620
+ for (const a of o.actions) if (typeof a === "string" && COPY_PAGE_ACTIONS.includes(a)) seen.add(a);
621
+ config.actions = COPY_PAGE_ACTIONS.filter((a) => seen.has(a));
622
+ }
623
+ return Object.keys(config).length > 0 ? config : void 0;
496
624
  }
625
+ /**
626
+ * Validate `opts.pageNav` into a {@link PageNavConfig}, or `undefined` to use the
627
+ * default (enabled). Accepts a boolean shorthand (`false` hides the pager) or an
628
+ * object whose `enabled` is read when boolean.
629
+ */
497
630
  function normalizePageNav(raw) {
498
- if (raw === false) return { enabled: false };
499
- if (raw === true || raw == null) return void 0;
500
- if (typeof raw !== "object") return void 0;
501
- const enabled = raw.enabled;
502
- return typeof enabled === "boolean" ? { enabled } : void 0;
631
+ if (raw === false) return { enabled: false };
632
+ if (raw === true || raw == null) return void 0;
633
+ if (typeof raw !== "object") return void 0;
634
+ const enabled = raw.enabled;
635
+ return typeof enabled === "boolean" ? { enabled } : void 0;
503
636
  }
504
- var PLAYGROUND_PROVIDERS = ["codepen", "jsfiddle", "codesandbox"];
637
+ /** Valid code-playground providers (mirrors utils' `PlaygroundProvider`). */
638
+ const PLAYGROUND_PROVIDERS = [
639
+ "codepen",
640
+ "jsfiddle",
641
+ "codesandbox"
642
+ ];
643
+ /** A site-wide per-provider options record, or `undefined` for a non-object. */
505
644
  function playgroundOptionRecord(raw) {
506
- return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
645
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
507
646
  }
647
+ /**
648
+ * Validate `opts.playground` into its two consumer slices, or `undefined` when
649
+ * the feature is off (absent or `false`). `playground: true` / `{}` turns it on
650
+ * with defaults — every provider available, opt-in per `@playground`. The
651
+ * **`site`** slice feeds setu's `@playground` resolver (enablement + provider
652
+ * selection); the **`theme`** slice becomes `ThemeConfig.playground` (the
653
+ * site-wide per-provider runtime options dwar hands the browser island). Unknown
654
+ * providers/keys are dropped (lenient, like {@link normalizeCopyPage}). setu
655
+ * gates on the `site` slice's presence, so returning `undefined` keeps output
656
+ * byte-identical.
657
+ */
508
658
  function normalizePlayground(raw) {
509
- if (raw == null || raw === false) return void 0;
510
- const o = raw === true ? {} : raw;
511
- if (typeof o !== "object" || Array.isArray(o)) return void 0;
512
- const obj = o;
513
- const site = {};
514
- if (obj.enableForAllExamples === true) site.enableForAllExamples = true;
515
- if (Array.isArray(obj.providers)) {
516
- const providers = [];
517
- for (const p of obj.providers) {
518
- if (typeof p === "string" && PLAYGROUND_PROVIDERS.includes(p) && !providers.includes(p)) {
519
- providers.push(p);
520
- }
521
- }
522
- if (providers.length > 0) site.providers = providers;
523
- }
524
- const theme = { enabled: true };
525
- const codepen = playgroundOptionRecord(obj.codepen);
526
- const jsfiddle = playgroundOptionRecord(obj.jsfiddle);
527
- const codesandbox = playgroundOptionRecord(obj.codesandbox);
528
- if (codepen) theme.codepen = codepen;
529
- if (jsfiddle) theme.jsfiddle = jsfiddle;
530
- if (codesandbox) theme.codesandbox = codesandbox;
531
- return { site, theme };
659
+ if (raw == null || raw === false) return void 0;
660
+ const o = raw === true ? {} : raw;
661
+ if (typeof o !== "object" || Array.isArray(o)) return void 0;
662
+ const obj = o;
663
+ const site = {};
664
+ if (obj.enableForAllExamples === true) site.enableForAllExamples = true;
665
+ if (Array.isArray(obj.providers)) {
666
+ const providers = [];
667
+ for (const p of obj.providers) if (typeof p === "string" && PLAYGROUND_PROVIDERS.includes(p) && !providers.includes(p)) providers.push(p);
668
+ if (providers.length > 0) site.providers = providers;
669
+ }
670
+ const theme = { enabled: true };
671
+ const codepen = playgroundOptionRecord(obj.codepen);
672
+ const jsfiddle = playgroundOptionRecord(obj.jsfiddle);
673
+ const codesandbox = playgroundOptionRecord(obj.codesandbox);
674
+ if (codepen) theme.codepen = codepen;
675
+ if (jsfiddle) theme.jsfiddle = jsfiddle;
676
+ if (codesandbox) theme.codesandbox = codesandbox;
677
+ return {
678
+ site,
679
+ theme
680
+ };
532
681
  }
533
- var COLOR_KEYS = [
534
- "bg",
535
- "bgMuted",
536
- "fg",
537
- "fgMuted",
538
- "accent",
539
- "accentFg",
540
- "border",
541
- "codeHeaderBg",
542
- "codeHeaderFg",
543
- "codeHighlightBg"
682
+ /** The palette keys a user may override under `opts.colors` / `opts.darkColors`. */
683
+ const COLOR_KEYS = [
684
+ "bg",
685
+ "bgMuted",
686
+ "fg",
687
+ "fgMuted",
688
+ "accent",
689
+ "accentFg",
690
+ "border",
691
+ "codeHeaderBg",
692
+ "codeHeaderFg",
693
+ "codeHighlightBg"
544
694
  ];
695
+ /**
696
+ * Validate a user `colors`/`darkColors` object from `jsdoc.json` into a clean
697
+ * `Partial<ThemeColors>`: keeps only the known palette keys whose value is a
698
+ * non-empty string, dropping everything else. Returns `undefined` when the input
699
+ * is not an object or yields no usable keys, so callers can fall back cleanly.
700
+ * Values are passed through verbatim (any CSS color is valid).
701
+ */
545
702
  function normalizeColors(raw) {
546
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
547
- const src = raw;
548
- const out = {};
549
- for (const key of COLOR_KEYS) {
550
- const v = src[key];
551
- if (typeof v === "string" && v.trim().length > 0) out[key] = v.trim();
552
- }
553
- return Object.keys(out).length > 0 ? out : void 0;
703
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
704
+ const src = raw;
705
+ const out = {};
706
+ for (const key of COLOR_KEYS) {
707
+ const v = src[key];
708
+ if (typeof v === "string" && v.trim().length > 0) out[key] = v.trim();
709
+ }
710
+ return Object.keys(out).length > 0 ? out : void 0;
554
711
  }
555
- var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"]);
712
+ /** Extensions we treat as "source" worth emitting a viewer page for. */
713
+ const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
714
+ ".js",
715
+ ".mjs",
716
+ ".cjs",
717
+ ".jsx",
718
+ ".ts",
719
+ ".mts",
720
+ ".cts",
721
+ ".tsx"
722
+ ]);
723
+ /**
724
+ * Compute project-relative paths for a set of absolute source paths by stripping
725
+ * their longest common directory prefix. Returns a `Map<absPath, relPath>` with
726
+ * `relPath` normalized to forward slashes. Pure + exported for testing.
727
+ *
728
+ * Windows-aware: paths are split on both `/` and `\\`, and segment comparison is
729
+ * case-insensitive (NTFS is case-insensitive, and JSDoc's `meta.path` casing can
730
+ * differ from disk). The single-file case yields just its basename. If the paths
731
+ * share no common leading segment (e.g. different drives / UNC vs. drive), each
732
+ * file falls back to its basename so the index stays sane.
733
+ */
556
734
  function computeRelPaths(absPaths) {
557
- const out = /* @__PURE__ */ new Map();
558
- if (absPaths.length === 0) return out;
559
- const split = (p) => p.split(/[\\/]+/).filter((s) => s.length > 0);
560
- const segLists = absPaths.map(split);
561
- let common = segLists[0].slice(0, -1);
562
- for (let i = 1; i < segLists.length && common.length > 0; i++) {
563
- const segs = segLists[i];
564
- let j = 0;
565
- const max = Math.min(common.length, segs.length - 1);
566
- while (j < max && common[j].toLowerCase() === segs[j].toLowerCase()) j++;
567
- common = common.slice(0, j);
568
- }
569
- for (let i = 0; i < absPaths.length; i++) {
570
- const segs = segLists[i];
571
- const rel = common.length > 0 && segs.length > common.length ? segs.slice(common.length).join("/") : segs[segs.length - 1] ?? absPaths[i];
572
- out.set(absPaths[i], rel);
573
- }
574
- return out;
735
+ const out = /* @__PURE__ */ new Map();
736
+ if (absPaths.length === 0) return out;
737
+ const split = (p) => p.split(/[\\/]+/).filter((s) => s.length > 0);
738
+ const segLists = absPaths.map(split);
739
+ let common = segLists[0].slice(0, -1);
740
+ for (let i = 1; i < segLists.length && common.length > 0; i++) {
741
+ const segs = segLists[i];
742
+ let j = 0;
743
+ const max = Math.min(common.length, segs.length - 1);
744
+ while (j < max && common[j].toLowerCase() === segs[j].toLowerCase()) j++;
745
+ common = common.slice(0, j);
746
+ }
747
+ for (let i = 0; i < absPaths.length; i++) {
748
+ const segs = segLists[i];
749
+ const rel = common.length > 0 && segs.length > common.length ? segs.slice(common.length).join("/") : segs[segs.length - 1] ?? absPaths[i];
750
+ out.set(absPaths[i], rel);
751
+ }
752
+ return out;
575
753
  }
754
+ /**
755
+ * Collect every source file referenced by a doclet's `meta` and read its
756
+ * contents, ready to hand to setu as {@link SourceFileInput}s. `absPath` is the
757
+ * exact `resolve(meta.path, meta.filename)` so setu's `Source: file:line`
758
+ * matching (which joins the same fields) lines up. Files that can't be read are
759
+ * warned about and skipped — never fatal. Returns sorted-by-`relPath` for
760
+ * stable output.
761
+ */
576
762
  async function collectSourceFiles(data) {
577
- let doclets = [];
578
- if (typeof data === "function") {
579
- try {
580
- doclets = data({}).get();
581
- } catch {
582
- try {
583
- doclets = data().get();
584
- } catch {
585
- doclets = [];
586
- }
587
- }
588
- }
589
- if (!Array.isArray(doclets) || doclets.length === 0) return [];
590
- const absSet = /* @__PURE__ */ new Set();
591
- for (const d of doclets) {
592
- const meta = d?.meta;
593
- if (!meta || typeof meta.path !== "string" || typeof meta.filename !== "string") continue;
594
- const filename = meta.filename;
595
- const ext = extname(filename).toLowerCase();
596
- if (ext.length > 0 && !SOURCE_EXTENSIONS.has(ext)) continue;
597
- absSet.add(resolvePath(meta.path, filename));
598
- }
599
- if (absSet.size === 0) return [];
600
- const absPaths = [...absSet];
601
- const relPaths = computeRelPaths(absPaths);
602
- const inputs = [];
603
- for (const abs of absPaths) {
604
- try {
605
- const content = await readFile(abs, "utf8");
606
- inputs.push({ absPath: abs, relPath: relPaths.get(abs) ?? abs, content });
607
- } catch (err) {
608
- console.warn(
609
- `clean-jsdoc-theme: could not read source file '${abs}' \u2014 ${err.message}; skipping.`
610
- );
611
- }
612
- }
613
- inputs.sort((a, b) => a.relPath.localeCompare(b.relPath));
614
- return inputs;
763
+ let doclets = [];
764
+ if (typeof data === "function") try {
765
+ doclets = data({}).get();
766
+ } catch {
767
+ try {
768
+ doclets = data().get();
769
+ } catch {
770
+ doclets = [];
771
+ }
772
+ }
773
+ if (!Array.isArray(doclets) || doclets.length === 0) return [];
774
+ const absSet = /* @__PURE__ */ new Set();
775
+ for (const d of doclets) {
776
+ const meta = d?.meta;
777
+ if (!meta || typeof meta.path !== "string" || typeof meta.filename !== "string") continue;
778
+ const filename = meta.filename;
779
+ const ext = extname(filename).toLowerCase();
780
+ if (ext.length > 0 && !SOURCE_EXTENSIONS.has(ext)) continue;
781
+ absSet.add(resolve(meta.path, filename));
782
+ }
783
+ if (absSet.size === 0) return [];
784
+ const absPaths = [...absSet];
785
+ const relPaths = computeRelPaths(absPaths);
786
+ const inputs = [];
787
+ for (const abs of absPaths) try {
788
+ const content = await readFile(abs, "utf8");
789
+ inputs.push({
790
+ absPath: abs,
791
+ relPath: relPaths.get(abs) ?? abs,
792
+ content
793
+ });
794
+ } catch (err) {
795
+ console.warn(`clean-jsdoc-theme: could not read source file '${abs}' — ${err.message}; skipping.`);
796
+ }
797
+ inputs.sort((a, b) => a.relPath.localeCompare(b.relPath));
798
+ return inputs;
615
799
  }
616
- var DOC_EXTENSIONS = /* @__PURE__ */ new Map([
617
- [".md", "markdown"],
618
- [".markdown", "markdown"],
619
- [".html", "html"],
620
- [".htm", "html"]
800
+ /** Doc-file extensions → `DocInput.type`. Markdown is the priority; html maps to 'html'. */
801
+ const DOC_EXTENSIONS = /* @__PURE__ */ new Map([
802
+ [".md", "markdown"],
803
+ [".markdown", "markdown"],
804
+ [".html", "html"],
805
+ [".htm", "html"]
806
+ ]);
807
+ /** Directory names skipped while walking a docs tree (build/vcs noise). */
808
+ const DOC_DIR_SKIP = /* @__PURE__ */ new Set([
809
+ "node_modules",
810
+ ".git",
811
+ ".svn",
812
+ ".hg"
621
813
  ]);
622
- var DOC_DIR_SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", ".svn", ".hg"]);
814
+ /**
815
+ * Recursively walk a docs directory and read each Markdown/HTML file into a
816
+ * {@link DocInput} for setu's docs front-end. Mirrors {@link collectSourceFiles}'s
817
+ * safe-probe style:
818
+ *
819
+ * - `path` is the file path relative to `dir`, POSIX-normalized (forward slashes)
820
+ * with the extension stripped (`<dir>/guides/advanced.md` → `'guides/advanced'`,
821
+ * `<dir>/index.md` → `'index'`).
822
+ * - `content` is the raw UTF-8 text (frontmatter stays embedded — setu parses it).
823
+ * - `type` is `'markdown'` for `.md`/`.markdown`, `'html'` for `.html`/`.htm`.
824
+ *
825
+ * Resilient by design: a missing/unreadable directory yields `[]` (never throws);
826
+ * dotfiles/dot-dirs and `node_modules`-like noise are skipped; a single
827
+ * unreadable file is warned about and skipped. Results are sorted by `path` so
828
+ * the output is stable build-to-build. Setu does no I/O — this is the only place
829
+ * the docs tree is read.
830
+ */
623
831
  async function collectDocs(dir) {
624
- if (typeof dir !== "string" || dir.trim().length === 0) return [];
625
- const root = resolvePath(dir);
626
- const docs = [];
627
- const walk = async (absDir, relPrefix) => {
628
- let entries;
629
- try {
630
- entries = await readdir(absDir, { withFileTypes: true });
631
- } catch {
632
- return;
633
- }
634
- for (const entry of entries) {
635
- const name = entry.name;
636
- if (name.startsWith(".")) continue;
637
- if (entry.isDirectory()) {
638
- if (DOC_DIR_SKIP.has(name)) continue;
639
- await walk(joinPath(absDir, name), relPrefix ? `${relPrefix}/${name}` : name);
640
- continue;
641
- }
642
- if (!entry.isFile()) continue;
643
- const ext = extname(name).toLowerCase();
644
- const type = DOC_EXTENSIONS.get(ext);
645
- if (!type) continue;
646
- const abs = joinPath(absDir, name);
647
- const stem = name.slice(0, name.length - ext.length);
648
- const relPath = relPrefix ? `${relPrefix}/${stem}` : stem;
649
- try {
650
- const content = await readFile(abs, "utf8");
651
- docs.push({ path: relPath, content, type });
652
- } catch (err) {
653
- console.warn(
654
- `clean-jsdoc-theme: could not read doc file '${abs}' \u2014 ${err.message}; skipping.`
655
- );
656
- }
657
- }
658
- };
659
- await walk(root, "");
660
- docs.sort((a, b) => a.path.localeCompare(b.path));
661
- return docs;
832
+ if (typeof dir !== "string" || dir.trim().length === 0) return [];
833
+ const root = resolve(dir);
834
+ const docs = [];
835
+ const walk = async (absDir, relPrefix) => {
836
+ let entries;
837
+ try {
838
+ entries = await readdir(absDir, { withFileTypes: true });
839
+ } catch {
840
+ return;
841
+ }
842
+ for (const entry of entries) {
843
+ const name = entry.name;
844
+ if (name.startsWith(".")) continue;
845
+ if (entry.isDirectory()) {
846
+ if (DOC_DIR_SKIP.has(name)) continue;
847
+ await walk(join(absDir, name), relPrefix ? `${relPrefix}/${name}` : name);
848
+ continue;
849
+ }
850
+ if (!entry.isFile()) continue;
851
+ const ext = extname(name).toLowerCase();
852
+ const type = DOC_EXTENSIONS.get(ext);
853
+ if (!type) continue;
854
+ const abs = join(absDir, name);
855
+ const stem = name.slice(0, name.length - ext.length);
856
+ const relPath = relPrefix ? `${relPrefix}/${stem}` : stem;
857
+ try {
858
+ const content = await readFile(abs, "utf8");
859
+ docs.push({
860
+ path: relPath,
861
+ content,
862
+ type
863
+ });
864
+ } catch (err) {
865
+ console.warn(`clean-jsdoc-theme: could not read doc file '${abs}' — ${err.message}; skipping.`);
866
+ }
867
+ }
868
+ };
869
+ await walk(root, "");
870
+ docs.sort((a, b) => a.path.localeCompare(b.path));
871
+ return docs;
662
872
  }
663
- var DOC_IMAGE_RE = /(!\[[^\]]*\]\()([^)\s]+)((?:\s+"[^"]*")?\))/g;
664
- var HTML_IMAGE_RE = /(<img\b[^>]*?\bsrc\s*=\s*(["']))([^"']*)(\2)/gi;
873
+ /** Markdown image: captures `![alt](`, the src, an optional `"title"`, and `)`. */
874
+ const DOC_IMAGE_RE = /(!\[[^\]]*\]\()([^)\s]+)((?:\s+"[^"]*")?\))/g;
875
+ /**
876
+ * HTML image: captures the `<img …src=` prefix (through the opening quote), the
877
+ * quote char, the src value, and the closing quote (a backreference to the
878
+ * opener). JSDoc's `plugins/markdown` renders a comment's `![alt](src)` to
879
+ * `<img src="…" alt="…">`, and prose can embed raw `<img>`; this matches both
880
+ * quote styles wherever `src` sits in the tag.
881
+ */
882
+ const HTML_IMAGE_RE = /(<img\b[^>]*?\bsrc\s*=\s*(["']))([^"']*)(\2)/gi;
665
883
  function createImageCollector(staticDirs = []) {
666
- const files = [];
667
- const inlineSvgs = {};
668
- const consumed = /* @__PURE__ */ new Set();
669
- const seenServed = /* @__PURE__ */ new Set();
670
- const cache = /* @__PURE__ */ new Map();
671
- const warnedMisses = /* @__PURE__ */ new Set();
672
- const resolve = async (rawSrc, baseDir) => {
673
- const src = rawSrc.trim();
674
- if (!src || isServableUrl(src) || src.startsWith("#") || src.startsWith("data:")) return null;
675
- const primary = src.startsWith("/") ? resolvePath(src.slice(1)) : resolvePath(baseDir, src);
676
- const candidates = [primary];
677
- if (staticDirs.length > 0) {
678
- const outName = src.replace(/^\/+/, "");
679
- if (outName) for (const dir of staticDirs) candidates.push(resolvePath(dir, outName));
680
- }
681
- for (const abs of candidates) {
682
- const cached = cache.get(abs);
683
- if (cached !== void 0) {
684
- if (cached) return cached;
685
- continue;
686
- }
687
- let bytes;
688
- try {
689
- bytes = await readFile(abs);
690
- } catch {
691
- cache.set(abs, null);
692
- continue;
693
- }
694
- const ext = extname(abs);
695
- const served = `_assets/${basename(abs, ext) || "asset"}.${contentHash(bytes)}${ext}`;
696
- if (!seenServed.has(served)) {
697
- seenServed.add(served);
698
- files.push({ path: served, contents: bytes });
699
- }
700
- const href = "/" + served;
701
- if (ext.toLowerCase() === ".svg") {
702
- inlineSvgs[href] = bytes.toString("utf8").replace(/<svg\b/, '<svg style="max-width:100%;height:auto;display:block"');
703
- }
704
- cache.set(abs, href);
705
- consumed.add(abs);
706
- return href;
707
- }
708
- if (!warnedMisses.has(src)) {
709
- warnedMisses.add(src);
710
- console.warn(
711
- `clean-jsdoc-theme: could not read image '${src}' (looked in: ${candidates.join(", ")}); leaving it as-is.`
712
- );
713
- }
714
- return null;
715
- };
716
- return { resolve, files, inlineSvgs, consumed };
884
+ const files = [];
885
+ const inlineSvgs = {};
886
+ const consumed = /* @__PURE__ */ new Set();
887
+ const seenServed = /* @__PURE__ */ new Set();
888
+ const cache = /* @__PURE__ */ new Map();
889
+ const warnedMisses = /* @__PURE__ */ new Set();
890
+ const resolve$1 = async (rawSrc, baseDir) => {
891
+ const src = rawSrc.trim();
892
+ if (!src || isServableUrl(src) || src.startsWith("#") || src.startsWith("data:")) return null;
893
+ const candidates = [src.startsWith("/") ? resolve(src.slice(1)) : resolve(baseDir, src)];
894
+ if (staticDirs.length > 0) {
895
+ const outName = src.replace(/^\/+/, "");
896
+ if (outName) for (const dir of staticDirs) candidates.push(resolve(dir, outName));
897
+ }
898
+ for (const abs of candidates) {
899
+ const cached = cache.get(abs);
900
+ if (cached !== void 0) {
901
+ if (cached) return cached;
902
+ continue;
903
+ }
904
+ let bytes;
905
+ try {
906
+ bytes = await readFile(abs);
907
+ } catch {
908
+ cache.set(abs, null);
909
+ continue;
910
+ }
911
+ const ext = extname(abs);
912
+ const served = `_assets/${basename(abs, ext) || "asset"}.${contentHash(bytes)}${ext}`;
913
+ if (!seenServed.has(served)) {
914
+ seenServed.add(served);
915
+ files.push({
916
+ path: served,
917
+ contents: bytes
918
+ });
919
+ }
920
+ const href = "/" + served;
921
+ if (ext.toLowerCase() === ".svg") inlineSvgs[href] = bytes.toString("utf8").replace(/<svg\b/, "<svg style=\"max-width:100%;height:auto;display:block\"");
922
+ cache.set(abs, href);
923
+ consumed.add(abs);
924
+ return href;
925
+ }
926
+ if (!warnedMisses.has(src)) {
927
+ warnedMisses.add(src);
928
+ console.warn(`clean-jsdoc-theme: could not read image '${src}' (looked in: ${candidates.join(", ")}); leaving it as-is.`);
929
+ }
930
+ return null;
931
+ };
932
+ return {
933
+ resolve: resolve$1,
934
+ files,
935
+ inlineSvgs,
936
+ consumed
937
+ };
717
938
  }
718
- var CODE_REGION_RE = /```[\s\S]*?```|~~~[\s\S]*?~~~|<pre[\s\S]*?<\/pre>|<code[^>]*>[\s\S]*?<\/code>|`[^`\n]+`/gi;
939
+ /**
940
+ * Rewrite the local image references in `content` to their content-hashed
941
+ * `/_assets/…` paths, routing each through `collector`. Handles BOTH Markdown
942
+ * `![alt](src)` and raw HTML `<img src="…">` (JSDoc renders comment/tutorial
943
+ * images to the latter), so prose in either form is covered. Relative srcs
944
+ * resolve against `baseDir`, `/`-rooted srcs against the project root, and
945
+ * external/`data:`/anchor srcs are left untouched. Returns the original string
946
+ * unchanged when nothing was rewritten.
947
+ */
948
+ /**
949
+ * Char ranges of Markdown/HTML **code** regions — fenced blocks (` ``` `/`~~~`),
950
+ * HTML `<pre>`/`<code>`, and inline backtick spans. Image references inside these
951
+ * are literal example syntax an author is *documenting*, not real images, so the
952
+ * rewriter skips them (no spurious copy/rewrite, no "could not read" warning).
953
+ * Order matters: the multi-line block forms come before the inline span so a
954
+ * fence isn't chopped at its first inner backtick.
955
+ */
956
+ const CODE_REGION_RE = /```[\s\S]*?```|~~~[\s\S]*?~~~|<pre[\s\S]*?<\/pre>|<code[^>]*>[\s\S]*?<\/code>|`[^`\n]+`/gi;
957
+ /** Collect the [start, end) char ranges of code regions in `content`. */
719
958
  function codeRanges(content) {
720
- const ranges = [];
721
- for (const m of content.matchAll(CODE_REGION_RE)) {
722
- if (m.index !== void 0) ranges.push([m.index, m.index + m[0].length]);
723
- }
724
- return ranges;
959
+ const ranges = [];
960
+ for (const m of content.matchAll(CODE_REGION_RE)) if (m.index !== void 0) ranges.push([m.index, m.index + m[0].length]);
961
+ return ranges;
725
962
  }
963
+ /** Whether char offset `idx` falls inside any of the (sorted-ish) code ranges. */
726
964
  function indexInCode(idx, ranges) {
727
- for (const [s, e] of ranges) if (idx >= s && idx < e) return true;
728
- return false;
965
+ for (const [s, e] of ranges) if (idx >= s && idx < e) return true;
966
+ return false;
729
967
  }
730
968
  async function rewriteImageRefs(content, baseDir, collector) {
731
- if (!content) return content;
732
- const ranges = codeRanges(content);
733
- const map = /* @__PURE__ */ new Map();
734
- const collect = async (re, srcGroup) => {
735
- for (const m of content.matchAll(re)) {
736
- if (m.index !== void 0 && indexInCode(m.index, ranges)) continue;
737
- const src = m[srcGroup];
738
- if (map.has(src)) continue;
739
- const href = await collector.resolve(src, baseDir);
740
- if (href) map.set(src, href);
741
- }
742
- };
743
- await collect(DOC_IMAGE_RE, 2);
744
- await collect(HTML_IMAGE_RE, 3);
745
- if (map.size === 0) return content;
746
- return content.replace(
747
- DOC_IMAGE_RE,
748
- (full, pre, src, post, offset) => !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${post}` : full
749
- ).replace(
750
- HTML_IMAGE_RE,
751
- (full, pre, _quote, src, close, offset) => !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${close}` : full
752
- );
969
+ if (!content) return content;
970
+ const ranges = codeRanges(content);
971
+ const map = /* @__PURE__ */ new Map();
972
+ const collect = async (re, srcGroup) => {
973
+ for (const m of content.matchAll(re)) {
974
+ if (m.index !== void 0 && indexInCode(m.index, ranges)) continue;
975
+ const src = m[srcGroup];
976
+ if (map.has(src)) continue;
977
+ const href = await collector.resolve(src, baseDir);
978
+ if (href) map.set(src, href);
979
+ }
980
+ };
981
+ await collect(DOC_IMAGE_RE, 2);
982
+ await collect(HTML_IMAGE_RE, 3);
983
+ if (map.size === 0) return content;
984
+ return content.replace(DOC_IMAGE_RE, (full, pre, src, post, offset) => !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${post}` : full).replace(HTML_IMAGE_RE, (full, pre, _quote, src, close, offset) => !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${close}` : full);
753
985
  }
986
+ /**
987
+ * Resolve the local images a doc references and route them through the shared
988
+ * content-hashed `_assets/` pipeline (see {@link createImageCollector}). Each
989
+ * `![alt](src)` / `<img src>` whose `src` points to a file on disk is copied and
990
+ * its `src` rewritten to the root-relative `/_assets/<base>.<hash><ext>` (rang's
991
+ * `MdxImg` adds the base path, like it does for links), resolved relative to the
992
+ * project root when it starts with `/`, else relative to the doc's own directory.
993
+ * Returns the docs with rewritten content plus the asset files to write. The
994
+ * bridge is the I/O layer here, so setu/dwar only ever see the final `_assets/`
995
+ * paths.
996
+ */
754
997
  async function resolveDocImages(docs, docsDir, collector = createImageCollector()) {
755
- if (docs.length === 0) return { docs, files: collector.files, inlineSvgs: collector.inlineSvgs };
756
- const root = resolvePath(docsDir);
757
- const out = [];
758
- for (const doc of docs) {
759
- const docDir = dirname2(resolvePath(root, doc.path));
760
- const content = await rewriteImageRefs(doc.content, docDir, collector);
761
- out.push(content === doc.content ? doc : { ...doc, content });
762
- }
763
- return { docs: out, files: collector.files, inlineSvgs: collector.inlineSvgs };
998
+ if (docs.length === 0) return {
999
+ docs,
1000
+ files: collector.files,
1001
+ inlineSvgs: collector.inlineSvgs
1002
+ };
1003
+ const root = resolve(docsDir);
1004
+ const out = [];
1005
+ for (const doc of docs) {
1006
+ const docDir = dirname(resolve(root, doc.path));
1007
+ const content = await rewriteImageRefs(doc.content, docDir, collector);
1008
+ out.push(content === doc.content ? doc : {
1009
+ ...doc,
1010
+ content
1011
+ });
1012
+ }
1013
+ return {
1014
+ docs: out,
1015
+ files: collector.files,
1016
+ inlineSvgs: collector.inlineSvgs
1017
+ };
764
1018
  }
1019
+ /**
1020
+ * Resolve the local images referenced by tutorial content, routing them through
1021
+ * the shared `collector` (the same content-hashed `_assets/` pipeline as docs).
1022
+ * JSDoc reads every tutorial from a single directory, so each tutorial's relative
1023
+ * srcs (`![x](../img/x.png)`, `<img src>`) resolve against `tutorialsDir`. Walks
1024
+ * the resolved tree (sub-tutorials included), rewriting each node's content —
1025
+ * Markdown or HTML; the tree shape is preserved. Returns a new tree (the input is
1026
+ * left untouched). Exported for testing.
1027
+ */
765
1028
  async function resolveTutorialImages(tree, tutorialsDir, collector) {
766
- const base = resolvePath(tutorialsDir);
767
- const walk = async (node) => {
768
- const content = await rewriteImageRefs(node.content, base, collector);
769
- const children = [];
770
- for (const child of node.children ?? []) children.push(await walk(child));
771
- return { ...node, content, children };
772
- };
773
- const out = [];
774
- for (const node of tree) out.push(await walk(node));
775
- return out;
1029
+ const base = resolve(tutorialsDir);
1030
+ const walk = async (node) => {
1031
+ const content = await rewriteImageRefs(node.content, base, collector);
1032
+ const children = [];
1033
+ for (const child of node.children ?? []) children.push(await walk(child));
1034
+ return {
1035
+ ...node,
1036
+ content,
1037
+ children
1038
+ };
1039
+ };
1040
+ const out = [];
1041
+ for (const node of tree) out.push(await walk(node));
1042
+ return out;
776
1043
  }
777
- var DOCLET_IMAGE_SKIP_KEYS = /* @__PURE__ */ new Set([
778
- "meta",
779
- "comment",
780
- "examples",
781
- "tags",
782
- "___id",
783
- "___s"
1044
+ /**
1045
+ * Doclet keys whose string values are raw source/code/meta, NOT rendered prose —
1046
+ * never scanned for images (a stray `<img`/`![` there must not be rewritten).
1047
+ */
1048
+ const DOCLET_IMAGE_SKIP_KEYS = /* @__PURE__ */ new Set([
1049
+ "meta",
1050
+ "comment",
1051
+ "examples",
1052
+ "tags",
1053
+ "___id",
1054
+ "___s"
784
1055
  ]);
1056
+ /**
1057
+ * Recursively rewrite the `<img>`/`![]()` image srcs in every prose string
1058
+ * reachable from a doclet object, resolving against `baseDir`. Only strings that
1059
+ * actually carry an image marker (`<img` or `![`) are touched — a cheap guard so
1060
+ * names/identifiers/code are never scanned — and raw/code keys
1061
+ * ({@link DOCLET_IMAGE_SKIP_KEYS}) are skipped entirely. Recurses into nested
1062
+ * objects/arrays (e.g. `params[].description`). Mutates `node` in place.
1063
+ */
785
1064
  async function rewriteDocletStrings(node, baseDir, collector) {
786
- for (const [key, value] of Object.entries(node)) {
787
- if (DOCLET_IMAGE_SKIP_KEYS.has(key)) continue;
788
- if (typeof value === "string") {
789
- if (value.includes("<img") || value.includes("![")) {
790
- const rewritten = await rewriteImageRefs(value, baseDir, collector);
791
- if (rewritten !== value) node[key] = rewritten;
792
- }
793
- } else if (Array.isArray(value)) {
794
- for (let i = 0; i < value.length; i++) {
795
- const item = value[i];
796
- if (typeof item === "string") {
797
- if (item.includes("<img") || item.includes("![")) {
798
- const rewritten = await rewriteImageRefs(item, baseDir, collector);
799
- if (rewritten !== item) value[i] = rewritten;
800
- }
801
- } else if (item && typeof item === "object") {
802
- await rewriteDocletStrings(item, baseDir, collector);
803
- }
804
- }
805
- } else if (value && typeof value === "object") {
806
- await rewriteDocletStrings(value, baseDir, collector);
807
- }
808
- }
1065
+ for (const [key, value] of Object.entries(node)) {
1066
+ if (DOCLET_IMAGE_SKIP_KEYS.has(key)) continue;
1067
+ if (typeof value === "string") {
1068
+ if (value.includes("<img") || value.includes("![")) {
1069
+ const rewritten = await rewriteImageRefs(value, baseDir, collector);
1070
+ if (rewritten !== value) node[key] = rewritten;
1071
+ }
1072
+ } else if (Array.isArray(value)) for (let i = 0; i < value.length; i++) {
1073
+ const item = value[i];
1074
+ if (typeof item === "string") {
1075
+ if (item.includes("<img") || item.includes("![")) {
1076
+ const rewritten = await rewriteImageRefs(item, baseDir, collector);
1077
+ if (rewritten !== item) value[i] = rewritten;
1078
+ }
1079
+ } else if (item && typeof item === "object") await rewriteDocletStrings(item, baseDir, collector);
1080
+ }
1081
+ else if (value && typeof value === "object") await rewriteDocletStrings(value, baseDir, collector);
1082
+ }
809
1083
  }
1084
+ /**
1085
+ * Resolve the local images referenced inside JSDoc-comment prose (doclet
1086
+ * descriptions, `@classdesc`, nested `@param`/`@property`/`@returns`
1087
+ * descriptions, …) and route them through the shared `collector`. JSDoc's
1088
+ * `plugins/markdown` has already turned a comment's `![alt](../img/x.png)` into
1089
+ * an HTML `<img src="../img/x.png">` by the time `publish` runs, so each src is
1090
+ * resolved **relative to that doclet's own source file** (`meta.path` — the
1091
+ * directory of the file the comment lives in). Doclets are mutated IN PLACE:
1092
+ * salty's `get()` hands out live object references, so the rewrite is visible
1093
+ * when setu later reads the same collection. Resilient — a non-collection `data`
1094
+ * or unreadable image is skipped (the latter warned), never fatal.
1095
+ */
810
1096
  async function resolveDocletImages(data, collector) {
811
- if (typeof data !== "function") return;
812
- let doclets = [];
813
- try {
814
- doclets = data({}).get();
815
- } catch {
816
- try {
817
- doclets = data().get();
818
- } catch {
819
- return;
820
- }
821
- }
822
- if (!Array.isArray(doclets)) return;
823
- for (const d of doclets) {
824
- if (!d || typeof d !== "object") continue;
825
- const meta = d.meta;
826
- if (!meta || typeof meta.path !== "string" || meta.path.length === 0) continue;
827
- await rewriteDocletStrings(d, meta.path, collector);
828
- }
1097
+ if (typeof data !== "function") return;
1098
+ let doclets = [];
1099
+ try {
1100
+ doclets = data({}).get();
1101
+ } catch {
1102
+ try {
1103
+ doclets = data().get();
1104
+ } catch {
1105
+ return;
1106
+ }
1107
+ }
1108
+ if (!Array.isArray(doclets)) return;
1109
+ for (const d of doclets) {
1110
+ if (!d || typeof d !== "object") continue;
1111
+ const meta = d.meta;
1112
+ if (!meta || typeof meta.path !== "string" || meta.path.length === 0) continue;
1113
+ await rewriteDocletStrings(d, meta.path, collector);
1114
+ }
829
1115
  }
1116
+ /**
1117
+ * Normalize a raw `staticFiles` block into a {@link StaticFilesConfig}, or
1118
+ * `undefined` when there's nothing to include. `include`/`exclude` accept a
1119
+ * string or string[]; patterns are kept as source strings (compiled later, so a
1120
+ * bad pattern fails open rather than throwing). Pure + exported for testing.
1121
+ */
830
1122
  function normalizeStaticFilesConfig(raw) {
831
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
832
- const o = raw;
833
- const toStrArr = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).filter((s) => typeof s === "string" && s.trim().length > 0).map((s) => s.trim());
834
- const include = toStrArr(o.include);
835
- if (include.length === 0) return void 0;
836
- const includePattern = typeof o.includePattern === "string" && o.includePattern.trim().length > 0 ? o.includePattern : void 0;
837
- const excludePattern = typeof o.excludePattern === "string" && o.excludePattern.trim().length > 0 ? o.excludePattern : void 0;
838
- return {
839
- include,
840
- exclude: toStrArr(o.exclude),
841
- ...includePattern ? { includePattern } : {},
842
- ...excludePattern ? { excludePattern } : {}
843
- };
1123
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
1124
+ const o = raw;
1125
+ const toStrArr = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).filter((s) => typeof s === "string" && s.trim().length > 0).map((s) => s.trim());
1126
+ const include = toStrArr(o.include);
1127
+ if (include.length === 0) return void 0;
1128
+ const includePattern = typeof o.includePattern === "string" && o.includePattern.trim().length > 0 ? o.includePattern : void 0;
1129
+ const excludePattern = typeof o.excludePattern === "string" && o.excludePattern.trim().length > 0 ? o.excludePattern : void 0;
1130
+ return {
1131
+ include,
1132
+ exclude: toStrArr(o.exclude),
1133
+ ...includePattern ? { includePattern } : {},
1134
+ ...excludePattern ? { excludePattern } : {}
1135
+ };
844
1136
  }
1137
+ /**
1138
+ * Read `templates.default.staticFiles` from JSDoc's canonical `jsdoc/env` conf
1139
+ * (the only place the root-level `templates` block lives at runtime), falling
1140
+ * back to a nested `opts.templates.default.staticFiles`. Mirrors the probe order
1141
+ * of {@link outputSourceFilesEnabled}. Returns `undefined` when unset/unusable.
1142
+ */
845
1143
  function readStaticFilesConfig(opts) {
846
- try {
847
- const env = __require("jsdoc/env");
848
- const fromEnv = normalizeStaticFilesConfig(env?.conf?.templates?.default?.staticFiles);
849
- if (fromEnv) return fromEnv;
850
- } catch {
851
- }
852
- return normalizeStaticFilesConfig(opts?.templates?.default?.staticFiles);
1144
+ try {
1145
+ const fromEnv = normalizeStaticFilesConfig(__require("jsdoc/env")?.conf?.templates?.default?.staticFiles);
1146
+ if (fromEnv) return fromEnv;
1147
+ } catch {}
1148
+ return normalizeStaticFilesConfig(opts?.templates?.default?.staticFiles);
853
1149
  }
1150
+ /**
1151
+ * Output-relative path (POSIX) for a static file under an include root: strip the
1152
+ * resolved-root prefix so `<root>/img/sub/x.png` under root `<root>/img` →
1153
+ * `sub/x.png` (JSDoc maps an include dir's contents to the output ROOT). When the
1154
+ * include was a single FILE (`absFile === includeRootAbs`), the output name is its
1155
+ * basename. Windows-aware: separators are normalized and the prefix match is
1156
+ * case-insensitive (NTFS). Pure + exported for testing.
1157
+ */
854
1158
  function staticFileOutputName(absFile, includeRootAbs) {
855
- const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "");
856
- const f = norm(absFile);
857
- const root = norm(includeRootAbs);
858
- const baseOf = (p) => p.slice(p.lastIndexOf("/") + 1);
859
- if (f === root) return baseOf(f);
860
- const prefix = root + "/";
861
- return f.toLowerCase().startsWith(prefix.toLowerCase()) ? f.slice(prefix.length) : baseOf(f);
1159
+ const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "");
1160
+ const f = norm(absFile);
1161
+ const root = norm(includeRootAbs);
1162
+ const baseOf = (p) => p.slice(p.lastIndexOf("/") + 1);
1163
+ if (f === root) return baseOf(f);
1164
+ const prefix = root + "/";
1165
+ return f.toLowerCase().startsWith(prefix.toLowerCase()) ? f.slice(prefix.length) : baseOf(f);
862
1166
  }
1167
+ /**
1168
+ * Whether a static file passes a config's filter — `includePattern` (must match),
1169
+ * `excludePattern` (must not match), and `exclude` (file equal to, or nested
1170
+ * under, an excluded path is dropped). Patterns are tested against the file's
1171
+ * POSIX-normalized absolute path; a malformed pattern fails open (ignored). Pure
1172
+ * + exported for testing.
1173
+ */
863
1174
  function staticFileIncluded(absFile, config) {
864
- const norm = (p) => resolvePath(p).replace(/\\/g, "/");
865
- const fn = norm(absFile);
866
- if (config.includePattern) {
867
- try {
868
- if (!new RegExp(config.includePattern).test(fn)) return false;
869
- } catch {
870
- }
871
- }
872
- if (config.excludePattern) {
873
- try {
874
- if (new RegExp(config.excludePattern).test(fn)) return false;
875
- } catch {
876
- }
877
- }
878
- for (const ex of config.exclude) {
879
- const exAbs = norm(ex);
880
- if (fn === exAbs || fn.toLowerCase().startsWith(exAbs.toLowerCase() + "/")) return false;
881
- }
882
- return true;
1175
+ const norm = (p) => resolve(p).replace(/\\/g, "/");
1176
+ const fn = norm(absFile);
1177
+ if (config.includePattern) try {
1178
+ if (!new RegExp(config.includePattern).test(fn)) return false;
1179
+ } catch {}
1180
+ if (config.excludePattern) try {
1181
+ if (new RegExp(config.excludePattern).test(fn)) return false;
1182
+ } catch {}
1183
+ for (const ex of config.exclude) {
1184
+ const exAbs = norm(ex);
1185
+ if (fn === exAbs || fn.toLowerCase().startsWith(exAbs.toLowerCase() + "/")) return false;
1186
+ }
1187
+ return true;
883
1188
  }
884
- var STATIC_DIR_SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", ".svn", ".hg"]);
1189
+ /** Directory names skipped while walking a staticFiles tree (build/vcs noise). */
1190
+ const STATIC_DIR_SKIP = /* @__PURE__ */ new Set([
1191
+ "node_modules",
1192
+ ".git",
1193
+ ".svn",
1194
+ ".hg"
1195
+ ]);
1196
+ /**
1197
+ * Collect the files matched by a {@link StaticFilesConfig}: walk each include
1198
+ * path (a directory recursively, or a single file), apply
1199
+ * {@link staticFileIncluded}, and read each match. Returns the verbatim copy
1200
+ * entries (output path = include-root-stripped, JSDoc's "contents → output root"
1201
+ * mapping) plus the resolved `searchDirs` the image resolver uses as fallback
1202
+ * roots (an include dir as-is; a file include's parent dir). Resilient: a missing
1203
+ * include path / unreadable file is warned + skipped, never fatal. Exported for
1204
+ * testing.
1205
+ */
885
1206
  async function collectStaticFiles(config, warn = (m) => console.warn(m)) {
886
- const files = [];
887
- const searchDirs = /* @__PURE__ */ new Set();
888
- const seenOutput = /* @__PURE__ */ new Set();
889
- for (const inc of config.include) {
890
- const root = resolvePath(inc);
891
- let st;
892
- try {
893
- st = await stat(root);
894
- } catch {
895
- warn(
896
- `clean-jsdoc-theme: staticFiles include '${inc}' (resolved '${root}') was not found; skipping it.`
897
- );
898
- continue;
899
- }
900
- if (st.isDirectory()) {
901
- searchDirs.add(root);
902
- const walk = async (absDir) => {
903
- let entries;
904
- try {
905
- entries = await readdir(absDir, { withFileTypes: true });
906
- } catch {
907
- return;
908
- }
909
- for (const entry of entries) {
910
- if (entry.name.startsWith(".")) continue;
911
- const abs = joinPath(absDir, entry.name);
912
- if (entry.isDirectory()) {
913
- if (!STATIC_DIR_SKIP.has(entry.name)) await walk(abs);
914
- continue;
915
- }
916
- if (!entry.isFile()) continue;
917
- if (!staticFileIncluded(abs, config)) continue;
918
- const outputPath = staticFileOutputName(abs, root);
919
- if (seenOutput.has(outputPath)) continue;
920
- let contents;
921
- try {
922
- contents = await readFile(abs);
923
- } catch (err) {
924
- warn(
925
- `clean-jsdoc-theme: could not read static file '${abs}' \u2014 ${err.message}; skipping.`
926
- );
927
- continue;
928
- }
929
- seenOutput.add(outputPath);
930
- files.push({ outputPath, absSource: resolvePath(abs), contents });
931
- }
932
- };
933
- await walk(root);
934
- } else if (st.isFile()) {
935
- searchDirs.add(dirname2(root));
936
- if (!staticFileIncluded(root, config)) continue;
937
- const outputPath = staticFileOutputName(root, root);
938
- if (!seenOutput.has(outputPath)) {
939
- try {
940
- const contents = await readFile(root);
941
- seenOutput.add(outputPath);
942
- files.push({ outputPath, absSource: resolvePath(root), contents });
943
- } catch (err) {
944
- warn(
945
- `clean-jsdoc-theme: could not read static file '${root}' \u2014 ${err.message}; skipping.`
946
- );
947
- }
948
- }
949
- }
950
- }
951
- files.sort((a, b) => a.outputPath.localeCompare(b.outputPath));
952
- return { files, searchDirs: [...searchDirs] };
1207
+ const files = [];
1208
+ const searchDirs = /* @__PURE__ */ new Set();
1209
+ const seenOutput = /* @__PURE__ */ new Set();
1210
+ for (const inc of config.include) {
1211
+ const root = resolve(inc);
1212
+ let st;
1213
+ try {
1214
+ st = await stat(root);
1215
+ } catch {
1216
+ warn(`clean-jsdoc-theme: staticFiles include '${inc}' (resolved '${root}') was not found; skipping it.`);
1217
+ continue;
1218
+ }
1219
+ if (st.isDirectory()) {
1220
+ searchDirs.add(root);
1221
+ const walk = async (absDir) => {
1222
+ let entries;
1223
+ try {
1224
+ entries = await readdir(absDir, { withFileTypes: true });
1225
+ } catch {
1226
+ return;
1227
+ }
1228
+ for (const entry of entries) {
1229
+ if (entry.name.startsWith(".")) continue;
1230
+ const abs = join(absDir, entry.name);
1231
+ if (entry.isDirectory()) {
1232
+ if (!STATIC_DIR_SKIP.has(entry.name)) await walk(abs);
1233
+ continue;
1234
+ }
1235
+ if (!entry.isFile()) continue;
1236
+ if (!staticFileIncluded(abs, config)) continue;
1237
+ const outputPath = staticFileOutputName(abs, root);
1238
+ if (seenOutput.has(outputPath)) continue;
1239
+ let contents;
1240
+ try {
1241
+ contents = await readFile(abs);
1242
+ } catch (err) {
1243
+ warn(`clean-jsdoc-theme: could not read static file '${abs}' — ${err.message}; skipping.`);
1244
+ continue;
1245
+ }
1246
+ seenOutput.add(outputPath);
1247
+ files.push({
1248
+ outputPath,
1249
+ absSource: resolve(abs),
1250
+ contents
1251
+ });
1252
+ }
1253
+ };
1254
+ await walk(root);
1255
+ } else if (st.isFile()) {
1256
+ searchDirs.add(dirname(root));
1257
+ if (!staticFileIncluded(root, config)) continue;
1258
+ const outputPath = staticFileOutputName(root, root);
1259
+ if (!seenOutput.has(outputPath)) try {
1260
+ const contents = await readFile(root);
1261
+ seenOutput.add(outputPath);
1262
+ files.push({
1263
+ outputPath,
1264
+ absSource: resolve(root),
1265
+ contents
1266
+ });
1267
+ } catch (err) {
1268
+ warn(`clean-jsdoc-theme: could not read static file '${root}' — ${err.message}; skipping.`);
1269
+ }
1270
+ }
1271
+ }
1272
+ files.sort((a, b) => a.outputPath.localeCompare(b.outputPath));
1273
+ return {
1274
+ files,
1275
+ searchDirs: [...searchDirs]
1276
+ };
953
1277
  }
1278
+ /**
1279
+ * Overlay a locale's resolved docs over the default set (the per-locale docs
1280
+ * track). A locale page WINS over the default page with the same `path`; a
1281
+ * default page absent from the locale falls back (stays). Image asset files are
1282
+ * deduped by served path (same content-hashed name → one copy), and inline SVGs
1283
+ * merge locale-over-default. Output docs are re-sorted by `path` so the manifest
1284
+ * stays stable regardless of merge order. Pure — the I/O already happened in the
1285
+ * two {@link resolveDocImages} calls that produced `base`/`locale`.
1286
+ */
954
1287
  function overlayDocs(base, locale) {
955
- const byPath = new Map(base.docs.map((d) => [d.path, d]));
956
- for (const d of locale.docs) byPath.set(d.path, d);
957
- const filesByPath = /* @__PURE__ */ new Map();
958
- for (const f of [...base.files, ...locale.files]) filesByPath.set(f.path, f);
959
- return {
960
- docs: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)),
961
- files: [...filesByPath.values()],
962
- inlineSvgs: { ...base.inlineSvgs, ...locale.inlineSvgs }
963
- };
1288
+ const byPath = new Map(base.docs.map((d) => [d.path, d]));
1289
+ for (const d of locale.docs) byPath.set(d.path, d);
1290
+ const filesByPath = /* @__PURE__ */ new Map();
1291
+ for (const f of [...base.files, ...locale.files]) filesByPath.set(f.path, f);
1292
+ return {
1293
+ docs: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)),
1294
+ files: [...filesByPath.values()],
1295
+ inlineSvgs: {
1296
+ ...base.inlineSvgs,
1297
+ ...locale.inlineSvgs
1298
+ }
1299
+ };
964
1300
  }
1301
+ /**
1302
+ * Validate `opts.docGroups` into a clean `string[]`, or `undefined` to fall back
1303
+ * to setu's default doc-group order. Mirrors {@link normalizeSectionOrder}:
1304
+ * accepts only an array; trims string entries and drops non-strings/empties.
1305
+ */
965
1306
  function normalizeDocGroups(raw) {
966
- return normalizeSectionOrder(raw);
1307
+ return normalizeSectionOrder(raw);
967
1308
  }
1309
+ /** Format an elapsed-ms span compactly: `840ms` under a second, else `5.2s`. */
968
1310
  function formatElapsed(ms) {
969
- return ms < 1e3 ? `${ms}ms` : `${(ms / 1e3).toFixed(1)}s`;
1311
+ return ms < 1e3 ? `${ms}ms` : `${(ms / 1e3).toFixed(1)}s`;
970
1312
  }
1313
+ /**
1314
+ * Build-stage narrator backed by `ora`. The setu→dwar pipeline does much more
1315
+ * than a bare jsdoc run (per-page MDX compile, per-island esbuild bundling, the
1316
+ * Pagefind index), so a 7–8s build can otherwise look hung. `stage(label, fn)`
1317
+ * starts an ora spinner, runs `fn`, then resolves it to `✔ <label> (<elapsed>)`
1318
+ * on success or `✖ <label>` on failure. ora handles the spinner animation, TTY
1319
+ * detection (no animation when piped/CI), and the success/fail symbols.
1320
+ *
1321
+ * The catch: ora animates its frame on a `setInterval`, but each stage does
1322
+ * heavy *synchronous* work (module evaluation during the dynamic `import()`,
1323
+ * per-page MDX compile/SSR) that blocks the event loop — so the interval can't
1324
+ * fire and the spinner freezes on one frame, looking hung. Two things keep it
1325
+ * visibly alive: an elapsed-seconds **heartbeat** appended to the label (so it
1326
+ * advances whenever the loop breathes — module-graph I/O gaps, esbuild/Pagefind
1327
+ * subprocess waits), and the `setText` handle, which long stages use to report
1328
+ * their current sub-step (e.g. the renderer load steps setu → dwar → utils).
1329
+ *
1330
+ * `ora` is `null` when progress is disabled (`opts.progress === false`) or the
1331
+ * package couldn't be loaded — then `stage` just runs `fn` with no output.
1332
+ */
971
1333
  function createBuildProgress(ora) {
972
- async function stage(label, fn) {
973
- const noop = { setText: () => {
974
- } };
975
- if (!ora) return await fn(noop);
976
- const spinner = ora(label).start();
977
- const begin = Date.now();
978
- let current = label;
979
- const refresh = () => {
980
- const secs = Math.floor((Date.now() - begin) / 1e3);
981
- spinner.text = secs > 0 ? `${current} (${secs}s)` : current;
982
- };
983
- const heartbeat = setInterval(refresh, 1e3);
984
- if (typeof heartbeat.unref === "function") heartbeat.unref();
985
- const handle = {
986
- setText(text) {
987
- current = text;
988
- refresh();
989
- }
990
- };
991
- try {
992
- const result = await fn(handle);
993
- clearInterval(heartbeat);
994
- spinner.succeed(`${label} (${formatElapsed(Date.now() - begin)})`);
995
- return result;
996
- } catch (err) {
997
- clearInterval(heartbeat);
998
- spinner.fail(label);
999
- throw err;
1000
- }
1001
- }
1002
- return { stage };
1334
+ async function stage(label, fn) {
1335
+ const noop = { setText: () => {} };
1336
+ if (!ora) return await fn(noop);
1337
+ const spinner = ora(label).start();
1338
+ const begin = Date.now();
1339
+ let current = label;
1340
+ const refresh = () => {
1341
+ const secs = Math.floor((Date.now() - begin) / 1e3);
1342
+ spinner.text = secs > 0 ? `${current} (${secs}s)` : current;
1343
+ };
1344
+ const heartbeat = setInterval(refresh, 1e3);
1345
+ if (typeof heartbeat.unref === "function") heartbeat.unref();
1346
+ const handle = { setText(text) {
1347
+ current = text;
1348
+ refresh();
1349
+ } };
1350
+ try {
1351
+ const result = await fn(handle);
1352
+ clearInterval(heartbeat);
1353
+ spinner.succeed(`${label} (${formatElapsed(Date.now() - begin)})`);
1354
+ return result;
1355
+ } catch (err) {
1356
+ clearInterval(heartbeat);
1357
+ spinner.fail(label);
1358
+ throw err;
1359
+ }
1360
+ }
1361
+ return { stage };
1003
1362
  }
1363
+ /**
1364
+ * Read the localization build spec when `CLEAN_JSDOC_THEME_BUILD` points at one
1365
+ * (set by `aadesh build` per locale). When present, the theme stamps the API
1366
+ * translations and renders to the spec's `destination`/`basePath` instead of the
1367
+ * jsdoc.json values. Returns `null` for a normal (single-locale) build.
1368
+ */
1004
1369
  function readBuildSpec() {
1005
- const path2 = process.env.CLEAN_JSDOC_THEME_BUILD?.trim();
1006
- if (!path2) return null;
1007
- const spec = JSON.parse(readFileSync(path2, "utf8"));
1008
- if (typeof spec.version === "number" && spec.version !== 1) {
1009
- throw new Error(
1010
- `clean-jsdoc-theme: build spec version ${spec.version} unsupported (expected 1) \u2014 update clean-jsdoc-theme and aadesh together.`
1011
- );
1012
- }
1013
- if (typeof spec.destination !== "string" || typeof spec.basePath !== "string") {
1014
- throw new Error(`clean-jsdoc-theme: malformed build spec at "${path2}".`);
1015
- }
1016
- return {
1017
- locale: typeof spec.locale === "string" ? spec.locale : "",
1018
- defaultLocale: typeof spec.defaultLocale === "string" ? spec.defaultLocale : "en",
1019
- apiMessages: spec.apiMessages ?? {},
1020
- chromeMessages: spec.chromeMessages ?? {},
1021
- destination: spec.destination,
1022
- basePath: spec.basePath,
1023
- siteBasePath: typeof spec.siteBasePath === "string" ? spec.siteBasePath : "/",
1024
- locales: Array.isArray(spec.locales) ? spec.locales : [],
1025
- ...typeof spec.docsDir === "string" && spec.docsDir ? { docsDir: spec.docsDir } : {}
1026
- };
1370
+ const path = process.env.CLEAN_JSDOC_THEME_BUILD?.trim();
1371
+ if (!path) return null;
1372
+ const spec = JSON.parse(readFileSync(path, "utf8"));
1373
+ if (typeof spec.version === "number" && spec.version !== 1) throw new Error(`clean-jsdoc-theme: build spec version ${spec.version} unsupported (expected 1) — update clean-jsdoc-theme and aadesh together.`);
1374
+ if (typeof spec.destination !== "string" || typeof spec.basePath !== "string") throw new Error(`clean-jsdoc-theme: malformed build spec at "${path}".`);
1375
+ return {
1376
+ locale: typeof spec.locale === "string" ? spec.locale : "",
1377
+ defaultLocale: typeof spec.defaultLocale === "string" ? spec.defaultLocale : "en",
1378
+ apiMessages: spec.apiMessages ?? {},
1379
+ chromeMessages: spec.chromeMessages ?? {},
1380
+ destination: spec.destination,
1381
+ basePath: spec.basePath,
1382
+ siteBasePath: typeof spec.siteBasePath === "string" ? spec.siteBasePath : "/",
1383
+ locales: Array.isArray(spec.locales) ? spec.locales : [],
1384
+ ...typeof spec.docsDir === "string" && spec.docsDir ? { docsDir: spec.docsDir } : {}
1385
+ };
1027
1386
  }
1028
1387
  async function publish(data, opts, tutorials) {
1029
- const buildSpec = readBuildSpec();
1030
- const destination = buildSpec?.destination ?? opts.destination;
1031
- if (!destination || typeof destination !== "string") {
1032
- throw new Error(
1033
- 'clean-jsdoc-theme publish: opts.destination is required (set "opts.destination" in your jsdoc.json).'
1034
- );
1035
- }
1036
- assertMarkdownPlugin();
1037
- const color = Boolean(process.stdout.isTTY) && opts.nocolor !== true;
1038
- const docsDir = typeof opts.docs === "string" && opts.docs.trim().length > 0 ? opts.docs.trim() : void 0;
1039
- const tutorialsDir = typeof opts.tutorials === "string" && opts.tutorials.trim().length > 0 ? opts.tutorials.trim() : void 0;
1040
- const staticCfg = readStaticFilesConfig(opts);
1041
- const pkgPromise = resolvePkg(data, opts);
1042
- const sourcesPromise = outputSourceFilesEnabled(opts) ? collectSourceFiles(data) : Promise.resolve([]);
1043
- const docsPromise = docsDir ? collectDocs(docsDir) : Promise.resolve([]);
1044
- const ora = opts.progress === false ? null : await loadOra();
1045
- const progress = createBuildProgress(ora);
1046
- const [
1047
- { generateSite, stampSite },
1048
- { render, runPagefindAgainstDir },
1049
- {
1050
- validateThemeOpts,
1051
- createGoogleFontResolver,
1052
- formatDiagnostics,
1053
- formatBuildReport,
1054
- formatRenderError,
1055
- normalizeBasePath,
1056
- withBase,
1057
- toExtractManifest,
1058
- normalizeCollapsibleSidebarSections,
1059
- unmatchedCollapsibleSections,
1060
- topLevelSectionLabels,
1061
- normalizeScrollbar
1062
- }
1063
- // Loaded sequentially (not Promise.all) so the spinner can step its label
1064
- // through each module — the evaluation of these large ESM bundles is the
1065
- // single longest, most event-loop-blocking stage, so visibly naming the
1066
- // module in flight is what stops it from reading as a hang.
1067
- ] = await progress.stage("Loading renderer", async ({ setText }) => {
1068
- setText("Loading renderer (setu)");
1069
- const setu = await loadSetu();
1070
- setText("Loading renderer (dwar)");
1071
- const dwar = await loadDwar();
1072
- setText("Loading renderer (utils)");
1073
- const utils = await loadUtils();
1074
- return [setu, dwar, utils];
1075
- });
1076
- const basePath = normalizeBasePath(buildSpec?.basePath ?? opts.basePath);
1077
- const hrefForServed = (servedPath) => withBase(basePath, "/" + servedPath);
1078
- const fontResolver = createGoogleFontResolver();
1079
- const { value, diagnostics } = await progress.stage(
1080
- "Validating options",
1081
- () => validateThemeOpts({
1082
- opts,
1083
- fontResolver,
1084
- unknownKeyPolicy: "suggest-typos",
1085
- knownNonThemeKeys: JSDOC_OWN_OPTS
1086
- })
1087
- );
1088
- const strict = opts.strict === true || opts.templates?.default?.strict === true;
1089
- if (diagnostics.list.length > 0) {
1090
- const formatted = formatDiagnostics(diagnostics, { color });
1091
- if (strict && diagnostics.hasErrors()) {
1092
- console.error(formatted);
1093
- throw new Error(
1094
- "clean-jsdoc-theme: opts validation failed in strict mode (see the diagnostics above). Fix the errors or unset `strict`."
1095
- );
1096
- }
1097
- console.log(formatted);
1098
- }
1099
- const pkg = await pkgPromise;
1100
- const readme = typeof opts.readme === "string" && opts.readme.length > 0 ? opts.readme : void 0;
1101
- const tutorialTree = normalizeTutorials(tutorials);
1102
- const sourceLinkToComment = sourceLinkToCommentEnabled(opts);
1103
- const staticFiles = staticCfg ? await progress.stage(
1104
- "Reading static files",
1105
- () => collectStaticFiles(staticCfg, (m) => console.warn(m))
1106
- ) : void 0;
1107
- const images = createImageCollector(staticFiles?.searchDirs ?? []);
1108
- const { sources, docs } = await progress.stage("Reading sources & docs", async () => {
1109
- const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);
1110
- const base = docsDir ? await resolveDocImages(rawDocs, docsDir, images) : { docs: rawDocs };
1111
- if (!buildSpec?.docsDir) return { sources: srcs, docs: base.docs };
1112
- const localeRaw = await collectDocs(buildSpec.docsDir);
1113
- const locale = await resolveDocImages(localeRaw, buildSpec.docsDir, images);
1114
- const merged = overlayDocs(
1115
- { docs: base.docs, files: [], inlineSvgs: {} },
1116
- { docs: locale.docs, files: [], inlineSvgs: {} }
1117
- );
1118
- return { sources: srcs, docs: merged.docs };
1119
- });
1120
- const { tutorialTree: resolvedTutorials, readme: resolvedReadme } = await progress.stage(
1121
- "Resolving prose images",
1122
- async () => {
1123
- const tree = tutorialsDir && tutorialTree.length > 0 ? await resolveTutorialImages(tutorialTree, tutorialsDir, images) : tutorialTree;
1124
- const md = readme ? await rewriteImageRefs(readme, process.cwd(), images) : readme;
1125
- await resolveDocletImages(data, images);
1126
- return { tutorialTree: tree, readme: md };
1127
- }
1128
- );
1129
- const imageFiles = images.files;
1130
- const allInlineSvgs = images.inlineSvgs;
1131
- const docGroups = normalizeDocGroups(opts.docGroups);
1132
- const defaultDocGroup = typeof opts.defaultDocGroup === "string" && opts.defaultDocGroup.trim().length > 0 ? opts.defaultDocGroup.trim() : void 0;
1133
- const sectionOrder = normalizeSectionOrder(opts.sectionOrder);
1134
- const menu = normalizeMenu(opts.menu);
1135
- const clubSidebarItems = opts.clubSidebarItems === true;
1136
- const { value: collapsibleSidebarSections, warnings: collapsibleWarnings } = normalizeCollapsibleSidebarSections(opts.collapsibleSidebarSections);
1137
- collapsibleWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));
1138
- const { value: scrollbar, warnings: scrollbarWarnings } = normalizeScrollbar(opts.scrollbar);
1139
- scrollbarWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));
1140
- const playground = normalizePlayground(opts.playground);
1141
- const siteOptions = {
1142
- ...pkg ? { pkg } : {},
1143
- ...resolvedReadme ? { readme: resolvedReadme } : {},
1144
- ...resolvedTutorials.length > 0 ? { tutorials: resolvedTutorials } : {},
1145
- ...sources.length > 0 ? { sources } : {},
1146
- ...sources.length > 0 && sourceLinkToComment ? { sourceLinkToComment } : {},
1147
- ...docs.length > 0 ? { docs } : {},
1148
- ...docGroups ? { docGroups } : {},
1149
- ...defaultDocGroup ? { defaultDocGroup } : {},
1150
- ...sectionOrder ? { sectionOrder } : {},
1151
- ...menu ? { menu } : {},
1152
- ...clubSidebarItems ? { clubSidebarItems } : {},
1153
- ...collapsibleSidebarSections !== void 0 ? { collapsibleSidebarSections } : {},
1154
- ...playground ? { playground: playground.site } : {}
1155
- };
1156
- const manifest = await progress.stage(
1157
- "Generating pages",
1158
- () => buildSpec ? stampSite(data, buildSpec.apiMessages, siteOptions) : generateSite(data, siteOptions)
1159
- );
1160
- if (Array.isArray(collapsibleSidebarSections)) {
1161
- const present = topLevelSectionLabels(manifest.nav);
1162
- const unmatched = unmatchedCollapsibleSections(collapsibleSidebarSections, present);
1163
- if (unmatched.length > 0) {
1164
- console.warn(
1165
- `clean-jsdoc-theme: collapsibleSidebarSections \u2014 no sidebar section matches ${unmatched.map((l) => `'${l}'`).join(", ")}. Available sections: ${present.join(", ")}.`
1166
- );
1167
- }
1168
- }
1169
- const extractPath = process.env.CLEAN_JSDOC_THEME_EXTRACT?.trim();
1170
- if (extractPath) {
1171
- const target = resolvePath(extractPath);
1172
- await progress.stage("Writing extract manifest", async () => {
1173
- await mkdir2(dirname2(target), { recursive: true });
1174
- await writeFile2(target, JSON.stringify(toExtractManifest(manifest), null, 2) + "\n", "utf8");
1175
- });
1176
- console.log(
1177
- `clean-jsdoc-theme: extract mode \u2014 wrote ${manifest.slots?.length ?? 0} slot(s) to ${target}`
1178
- );
1179
- return;
1180
- }
1181
- const { siteName, files: logoFiles } = await prepareSiteName(value.siteName, hrefForServed);
1182
- const notGoogle = new Set(
1183
- diagnostics.list.filter((d) => d.code === "fonts/not-google" && d.path).map((d) => d.path)
1184
- );
1185
- const fonts = { ...value.fonts };
1186
- if (notGoogle.has("fonts.heading")) delete fonts.heading;
1187
- if (notGoogle.has("fonts.body")) delete fonts.body;
1188
- if (fonts.locales) {
1189
- const cleaned = {};
1190
- for (const [loc, set] of Object.entries(fonts.locales)) {
1191
- const s = { ...set };
1192
- if (notGoogle.has(`fonts.${loc}:heading`)) delete s.heading;
1193
- if (notGoogle.has(`fonts.${loc}:body`)) delete s.body;
1194
- cleaned[loc] = s;
1195
- }
1196
- fonts.locales = cleaned;
1197
- }
1198
- const customAssets = await resolveCustomAssets(opts, hrefForServed);
1199
- const footer = await resolveFooter(opts.footer);
1200
- const favicon = await resolveFavicon(opts.favicon, opts.hashCustomAssets !== false, hrefForServed);
1201
- const meta = normalizeMeta(opts.meta);
1202
- const absoluteDestination = resolvePath(destination);
1203
- const islandCacheDir = resolvePath(process.cwd(), "node_modules", ".cache", "clean-jsdoc-theme");
1204
- const result = await progress.stage(
1205
- "Rendering site",
1206
- () => render(manifest, {
1207
- theme: {
1208
- ...resolveTheme(opts, siteName, fonts, basePath, buildSpec?.locale),
1209
- ...customAssets.theme,
1210
- ...footer ? { footer } : {},
1211
- ...favicon ? { favicon: favicon.href } : {},
1212
- ...meta ? { meta } : {},
1213
- ...scrollbar ? { scrollbar } : {}
1214
- },
1215
- destination: absoluteDestination,
1216
- islandCacheDir,
1217
- inlineSvgs: allInlineSvgs,
1218
- // Emit sitemap.xml when a public site URL is configured (the protocol needs
1219
- // absolute URLs). In a localized build each locale's basePath yields that
1220
- // locale's URLs, so each locale dir gets its own sitemap.
1221
- ...nonEmptyString(opts.siteUrl) ? { siteUrl: opts.siteUrl.trim() } : {},
1222
- // Build mode: render chrome in the locale (SSR provider + island seeding)
1223
- // and, with >1 locale, mount the language switcher.
1224
- ...buildSpec ? {
1225
- locale: {
1226
- code: buildSpec.locale,
1227
- defaultLocale: buildSpec.defaultLocale,
1228
- messages: buildSpec.chromeMessages,
1229
- siteBasePath: buildSpec.siteBasePath,
1230
- locales: buildSpec.locales.map((l) => ({ code: l.code, label: l.name ?? l.code }))
1231
- }
1232
- } : {}
1233
- })
1234
- );
1235
- const generatedFiles = [
1236
- ...result.files,
1237
- ...logoFiles,
1238
- ...customAssets.files,
1239
- ...imageFiles,
1240
- ...favicon?.files ?? []
1241
- ];
1242
- const staticOutputFiles = [];
1243
- if (staticFiles) {
1244
- const generatedPaths = new Set(generatedFiles.map((f) => f.path));
1245
- const RESERVED_PREFIXES = ["_assets/", "_islands/", "pagefind/"];
1246
- let skippedConsumed = 0;
1247
- for (const f of staticFiles.files) {
1248
- if (images.consumed.has(f.absSource)) {
1249
- skippedConsumed++;
1250
- continue;
1251
- }
1252
- if (generatedPaths.has(f.outputPath) || RESERVED_PREFIXES.some((p) => f.outputPath.startsWith(p))) {
1253
- console.warn(
1254
- `clean-jsdoc-theme: static file '${f.outputPath}' would clobber generated output; skipping it.`
1255
- );
1256
- continue;
1257
- }
1258
- staticOutputFiles.push({ path: f.outputPath, contents: f.contents });
1259
- }
1260
- if (staticFiles.files.length > 0) {
1261
- console.log(
1262
- `clean-jsdoc-theme: staticFiles \u2014 copied ${staticOutputFiles.length} file(s) verbatim` + (skippedConsumed > 0 ? ` (${skippedConsumed} served hashed via _assets/)` : "") + "."
1263
- );
1264
- }
1265
- }
1266
- const outputFiles = [...generatedFiles, ...staticOutputFiles];
1267
- if (!buildSpec && cleanOutputDirEnabled(opts)) {
1268
- await progress.stage(
1269
- "Cleaning output",
1270
- () => rm(absoluteDestination, { recursive: true, force: true })
1271
- );
1272
- }
1273
- await progress.stage("Writing files", () => writeOutputFiles(absoluteDestination, outputFiles));
1274
- const zlib = await import("zlib");
1275
- const gzipSizer = (b) => zlib.gzipSync(b).length;
1276
- console.log(
1277
- formatBuildReport({
1278
- files: outputFiles,
1279
- stats: result.stats,
1280
- destination,
1281
- gzipSizer,
1282
- color
1283
- })
1284
- );
1285
- if (result.errors && result.errors.length > 0) {
1286
- console.warn(
1287
- `clean-jsdoc-theme: ${result.errors.length} page(s) failed to render and were skipped:`
1288
- );
1289
- for (const e of result.errors) {
1290
- console.warn(formatRenderError(e));
1291
- }
1292
- }
1293
- if (result.warnings && result.warnings.length > 0) {
1294
- console.warn(
1295
- `clean-jsdoc-theme: ${result.warnings.length} content warning(s) (non-fatal):`
1296
- );
1297
- for (const w of result.warnings) {
1298
- console.warn(formatRenderError(w));
1299
- }
1300
- }
1301
- try {
1302
- await progress.stage(
1303
- "Indexing search (pagefind)",
1304
- () => runPagefindAgainstDir(absoluteDestination)
1305
- );
1306
- } catch (err) {
1307
- console.warn(`clean-jsdoc-theme: pagefind step skipped (optional) \u2014 ${err.message}`);
1308
- }
1388
+ const buildSpec = readBuildSpec();
1389
+ const destination = buildSpec?.destination ?? opts.destination;
1390
+ if (!destination || typeof destination !== "string") throw new Error("clean-jsdoc-theme publish: opts.destination is required (set \"opts.destination\" in your jsdoc.json).");
1391
+ assertMarkdownPlugin();
1392
+ const color = Boolean(process.stdout.isTTY) && opts.nocolor !== true;
1393
+ const docsDir = typeof opts.docs === "string" && opts.docs.trim().length > 0 ? opts.docs.trim() : void 0;
1394
+ const tutorialsDir = typeof opts.tutorials === "string" && opts.tutorials.trim().length > 0 ? opts.tutorials.trim() : void 0;
1395
+ const staticCfg = readStaticFilesConfig(opts);
1396
+ const pkgPromise = resolvePkg(data, opts);
1397
+ const sourcesPromise = outputSourceFilesEnabled(opts) ? collectSourceFiles(data) : Promise.resolve([]);
1398
+ const docsPromise = docsDir ? collectDocs(docsDir) : Promise.resolve([]);
1399
+ const progress = createBuildProgress(opts.progress === false ? null : await loadOra());
1400
+ const [{ generateSite, stampSite }, { render, runPagefindAgainstDir }, { validateThemeOpts, createGoogleFontResolver, formatDiagnostics, warningsOnly, formatBuildReport, formatRenderError, normalizeBasePath, withBase, toExtractManifest, normalizeCollapsibleSidebarSections, unmatchedCollapsibleSections, topLevelSectionLabels, normalizeScrollbar }] = await progress.stage("Loading renderer", async ({ setText }) => {
1401
+ setText("Loading renderer (setu)");
1402
+ const setu = await loadSetu();
1403
+ setText("Loading renderer (dwar)");
1404
+ const dwar = await loadDwar();
1405
+ setText("Loading renderer (utils)");
1406
+ return [
1407
+ setu,
1408
+ dwar,
1409
+ await loadUtils()
1410
+ ];
1411
+ });
1412
+ const basePath = normalizeBasePath(buildSpec?.basePath ?? opts.basePath);
1413
+ const hrefForServed = (servedPath) => withBase(basePath, "/" + servedPath);
1414
+ const fontResolver = createGoogleFontResolver();
1415
+ const { value, diagnostics } = await progress.stage("Validating options", () => validateThemeOpts({
1416
+ opts,
1417
+ fontResolver,
1418
+ unknownKeyPolicy: "suggest-typos",
1419
+ knownNonThemeKeys: JSDOC_OWN_OPTS
1420
+ }));
1421
+ const strict = opts.strict === true || opts.templates?.default?.strict === true;
1422
+ if (diagnostics.list.length > 0) {
1423
+ const formatted = formatDiagnostics(diagnostics, { color });
1424
+ if (strict && diagnostics.hasErrors()) {
1425
+ console.error(formatted);
1426
+ throw new Error("clean-jsdoc-theme: opts validation failed in strict mode (see the diagnostics above). Fix the errors or unset `strict`.");
1427
+ }
1428
+ console.log(formatted);
1429
+ }
1430
+ const pkg = await pkgPromise;
1431
+ const readme = typeof opts.readme === "string" && opts.readme.length > 0 ? opts.readme : void 0;
1432
+ const tutorialTree = normalizeTutorials(tutorials);
1433
+ const sourceLinkToComment = sourceLinkToCommentEnabled(opts);
1434
+ const staticFiles = staticCfg ? await progress.stage("Reading static files", () => collectStaticFiles(staticCfg, (m) => console.warn(m))) : void 0;
1435
+ const images = createImageCollector(staticFiles?.searchDirs ?? []);
1436
+ const { sources, docs } = await progress.stage("Reading sources & docs", async () => {
1437
+ const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);
1438
+ const base = docsDir ? await resolveDocImages(rawDocs, docsDir, images) : { docs: rawDocs };
1439
+ if (!buildSpec?.docsDir) return {
1440
+ sources: srcs,
1441
+ docs: base.docs
1442
+ };
1443
+ const locale = await resolveDocImages(await collectDocs(buildSpec.docsDir), buildSpec.docsDir, images);
1444
+ return {
1445
+ sources: srcs,
1446
+ docs: overlayDocs({
1447
+ docs: base.docs,
1448
+ files: [],
1449
+ inlineSvgs: {}
1450
+ }, {
1451
+ docs: locale.docs,
1452
+ files: [],
1453
+ inlineSvgs: {}
1454
+ }).docs
1455
+ };
1456
+ });
1457
+ const { tutorialTree: resolvedTutorials, readme: resolvedReadme } = await progress.stage("Resolving prose images", async () => {
1458
+ const tree = tutorialsDir && tutorialTree.length > 0 ? await resolveTutorialImages(tutorialTree, tutorialsDir, images) : tutorialTree;
1459
+ const md = readme ? await rewriteImageRefs(readme, process.cwd(), images) : readme;
1460
+ await resolveDocletImages(data, images);
1461
+ return {
1462
+ tutorialTree: tree,
1463
+ readme: md
1464
+ };
1465
+ });
1466
+ const imageFiles = images.files;
1467
+ const allInlineSvgs = images.inlineSvgs;
1468
+ const docGroups = normalizeDocGroups(opts.docGroups);
1469
+ const defaultDocGroup = typeof opts.defaultDocGroup === "string" && opts.defaultDocGroup.trim().length > 0 ? opts.defaultDocGroup.trim() : void 0;
1470
+ const sectionOrder = normalizeSectionOrder(opts.sectionOrder);
1471
+ const menu = normalizeMenu(opts.menu);
1472
+ const clubSidebarItems = opts.clubSidebarItems === true;
1473
+ const { value: collapsibleSidebarSections, warnings: collapsibleWarnings } = normalizeCollapsibleSidebarSections(opts.collapsibleSidebarSections);
1474
+ collapsibleWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));
1475
+ const { value: scrollbar, warnings: scrollbarWarnings } = normalizeScrollbar(opts.scrollbar);
1476
+ scrollbarWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));
1477
+ const playground = normalizePlayground(opts.playground);
1478
+ const siteOptions = {
1479
+ ...pkg ? { pkg } : {},
1480
+ ...resolvedReadme ? { readme: resolvedReadme } : {},
1481
+ ...resolvedTutorials.length > 0 ? { tutorials: resolvedTutorials } : {},
1482
+ ...sources.length > 0 ? { sources } : {},
1483
+ ...sources.length > 0 && sourceLinkToComment ? { sourceLinkToComment } : {},
1484
+ ...docs.length > 0 ? { docs } : {},
1485
+ ...docGroups ? { docGroups } : {},
1486
+ ...defaultDocGroup ? { defaultDocGroup } : {},
1487
+ ...sectionOrder ? { sectionOrder } : {},
1488
+ ...menu ? { menu } : {},
1489
+ ...clubSidebarItems ? { clubSidebarItems } : {},
1490
+ ...collapsibleSidebarSections !== void 0 ? { collapsibleSidebarSections } : {},
1491
+ ...playground ? { playground: playground.site } : {}
1492
+ };
1493
+ const manifest = await progress.stage("Generating pages", () => buildSpec ? stampSite(data, buildSpec.apiMessages, siteOptions) : generateSite(data, siteOptions));
1494
+ if (Array.isArray(collapsibleSidebarSections)) {
1495
+ const present = topLevelSectionLabels(manifest.nav);
1496
+ const unmatched = unmatchedCollapsibleSections(collapsibleSidebarSections, present);
1497
+ if (unmatched.length > 0) console.warn(`clean-jsdoc-theme: collapsibleSidebarSections — no sidebar section matches ${unmatched.map((l) => `'${l}'`).join(", ")}. Available sections: ${present.join(", ")}.`);
1498
+ }
1499
+ const extractPath = process.env.CLEAN_JSDOC_THEME_EXTRACT?.trim();
1500
+ if (extractPath) {
1501
+ const target = resolve(extractPath);
1502
+ await progress.stage("Writing extract manifest", async () => {
1503
+ await mkdir(dirname(target), { recursive: true });
1504
+ await writeFile(target, JSON.stringify(toExtractManifest(manifest), null, 2) + "\n", "utf8");
1505
+ });
1506
+ console.log(`clean-jsdoc-theme: extract mode — wrote ${manifest.slots?.length ?? 0} slot(s) to ${target}`);
1507
+ return;
1508
+ }
1509
+ const { siteName, files: logoFiles } = await prepareSiteName(value.siteName, hrefForServed);
1510
+ const notGoogle = new Set(diagnostics.list.filter((d) => d.code === "fonts/not-google" && d.path).map((d) => d.path));
1511
+ const fonts = { ...value.fonts };
1512
+ if (notGoogle.has("fonts.heading")) delete fonts.heading;
1513
+ if (notGoogle.has("fonts.body")) delete fonts.body;
1514
+ if (fonts.locales) {
1515
+ const cleaned = {};
1516
+ for (const [loc, set] of Object.entries(fonts.locales)) {
1517
+ const s = { ...set };
1518
+ if (notGoogle.has(`fonts.${loc}:heading`)) delete s.heading;
1519
+ if (notGoogle.has(`fonts.${loc}:body`)) delete s.body;
1520
+ cleaned[loc] = s;
1521
+ }
1522
+ fonts.locales = cleaned;
1523
+ }
1524
+ const customAssets = await resolveCustomAssets(opts, hrefForServed);
1525
+ const footer = await resolveFooter(opts.footer);
1526
+ const favicon = await resolveFavicon(opts.favicon, opts.hashCustomAssets !== false, hrefForServed);
1527
+ const meta = normalizeMeta(opts.meta);
1528
+ const absoluteDestination = resolve(destination);
1529
+ const islandCacheDir = resolve(process.cwd(), "node_modules", ".cache", "clean-jsdoc-theme");
1530
+ const result = await progress.stage("Rendering site", () => render(manifest, {
1531
+ theme: {
1532
+ ...resolveTheme(opts, siteName, fonts, basePath, buildSpec?.locale),
1533
+ ...customAssets.theme,
1534
+ ...footer ? { footer } : {},
1535
+ ...favicon ? { favicon: favicon.href } : {},
1536
+ ...meta ? { meta } : {},
1537
+ ...scrollbar ? { scrollbar } : {}
1538
+ },
1539
+ destination: absoluteDestination,
1540
+ islandCacheDir,
1541
+ inlineSvgs: allInlineSvgs,
1542
+ ...value.siteUrl ? { siteUrl: value.siteUrl } : {},
1543
+ ...value.llmsTxt ? { llmsTxt: value.llmsTxt } : {},
1544
+ ...buildSpec ? { locale: {
1545
+ code: buildSpec.locale,
1546
+ defaultLocale: buildSpec.defaultLocale,
1547
+ messages: buildSpec.chromeMessages,
1548
+ siteBasePath: buildSpec.siteBasePath,
1549
+ locales: buildSpec.locales.map((l) => ({
1550
+ code: l.code,
1551
+ label: l.name ?? l.code
1552
+ }))
1553
+ } } : {}
1554
+ }));
1555
+ const generatedFiles = [
1556
+ ...result.files,
1557
+ ...logoFiles,
1558
+ ...customAssets.files,
1559
+ ...imageFiles,
1560
+ ...favicon?.files ?? []
1561
+ ];
1562
+ const staticOutputFiles = [];
1563
+ if (staticFiles) {
1564
+ const generatedPaths = new Set(generatedFiles.map((f) => f.path));
1565
+ const RESERVED_PREFIXES = [
1566
+ "_assets/",
1567
+ "_islands/",
1568
+ "pagefind/"
1569
+ ];
1570
+ let skippedConsumed = 0;
1571
+ for (const f of staticFiles.files) {
1572
+ if (images.consumed.has(f.absSource)) {
1573
+ skippedConsumed++;
1574
+ continue;
1575
+ }
1576
+ if (generatedPaths.has(f.outputPath) || RESERVED_PREFIXES.some((p) => f.outputPath.startsWith(p))) {
1577
+ console.warn(`clean-jsdoc-theme: static file '${f.outputPath}' would clobber generated output; skipping it.`);
1578
+ continue;
1579
+ }
1580
+ staticOutputFiles.push({
1581
+ path: f.outputPath,
1582
+ contents: f.contents
1583
+ });
1584
+ }
1585
+ if (staticFiles.files.length > 0) console.log(`clean-jsdoc-theme: staticFiles — copied ${staticOutputFiles.length} file(s) verbatim` + (skippedConsumed > 0 ? ` (${skippedConsumed} served hashed via _assets/)` : "") + ".");
1586
+ }
1587
+ const outputFiles = [...generatedFiles, ...staticOutputFiles];
1588
+ if (!buildSpec && cleanOutputDirEnabled(opts)) await progress.stage("Cleaning output", () => rm(absoluteDestination, {
1589
+ recursive: true,
1590
+ force: true
1591
+ }));
1592
+ await progress.stage("Writing files", () => writeOutputFiles(absoluteDestination, outputFiles));
1593
+ const zlib = await import("node:zlib");
1594
+ const gzipSizer = (b) => zlib.gzipSync(b).length;
1595
+ console.log(formatBuildReport({
1596
+ files: outputFiles,
1597
+ stats: result.stats,
1598
+ destination,
1599
+ gzipSizer,
1600
+ color
1601
+ }));
1602
+ const optsWarnings = warningsOnly(diagnostics);
1603
+ if (optsWarnings.list.length > 0) console.warn(formatDiagnostics(optsWarnings, { color }));
1604
+ if (result.errors && result.errors.length > 0) {
1605
+ console.warn(`clean-jsdoc-theme: ${result.errors.length} page(s) failed to render and were skipped:`);
1606
+ for (const e of result.errors) console.warn(formatRenderError(e));
1607
+ }
1608
+ if (result.warnings && result.warnings.length > 0) {
1609
+ console.warn(`clean-jsdoc-theme: ${result.warnings.length} content warning(s) (non-fatal):`);
1610
+ for (const w of result.warnings) console.warn(formatRenderError(w));
1611
+ }
1612
+ try {
1613
+ await progress.stage("Indexing search (pagefind)", () => runPagefindAgainstDir(absoluteDestination));
1614
+ } catch (err) {
1615
+ console.warn(`clean-jsdoc-theme: pagefind step skipped (optional) — ${err.message}`);
1616
+ }
1309
1617
  }
1310
- export {
1311
- cleanOutputDirEnabled,
1312
- collectDocs,
1313
- collectStaticFiles,
1314
- computeRelPaths,
1315
- createImageCollector,
1316
- hasMarkdownPlugin,
1317
- normalizeColors,
1318
- normalizeCopyPage,
1319
- normalizeDocGroups,
1320
- normalizeMenu,
1321
- normalizeMeta,
1322
- normalizePageNav,
1323
- normalizePlayground,
1324
- normalizeSectionOrder,
1325
- normalizeStaticFilesConfig,
1326
- outputSourceFilesEnabled,
1327
- overlayDocs,
1328
- publish,
1329
- readStaticFilesConfig,
1330
- resolveDocImages,
1331
- resolveDocletImages,
1332
- resolveFavicon,
1333
- resolveFooter,
1334
- resolveTutorialImages,
1335
- sourceLinkToCommentEnabled,
1336
- staticFileIncluded,
1337
- staticFileOutputName
1338
- };
1618
+ //#endregion
1619
+ export { cleanOutputDirEnabled, collectDocs, collectStaticFiles, computeRelPaths, createImageCollector, hasMarkdownPlugin, normalizeColors, normalizeCopyPage, normalizeDocGroups, normalizeMenu, normalizeMeta, normalizePageNav, normalizePlayground, normalizeSectionOrder, normalizeStaticFilesConfig, outputSourceFilesEnabled, overlayDocs, publish, readStaticFilesConfig, resolveDocImages, resolveDocletImages, resolveFavicon, resolveFooter, resolveTutorialImages, sourceLinkToCommentEnabled, staticFileIncluded, staticFileOutputName };
1620
+
1339
1621
  //# sourceMappingURL=publish.mjs.map