@dogsbay/ssg-cli 0.2.0-beta.186 → 0.2.0-beta.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/AGENTS.md +168 -0
  2. package/README.md +3 -1
  3. package/THIRD-PARTY-NOTICES.txt +23 -17
  4. package/chunks/{build-command-X76EICE4.mjs → build-command-NJATVOUY.mjs} +34 -25
  5. package/chunks/check-command-FL5O3AXB.mjs +577 -0
  6. package/chunks/chunk-2EM7IEQT.mjs +95 -0
  7. package/chunks/{chunk-JABACD5T.mjs → chunk-5A2QPRCV.mjs} +1 -30
  8. package/chunks/chunk-5NQOUB5I.mjs +4534 -0
  9. package/chunks/{chunk-YQ2K646L.mjs → chunk-CYJ6GFVM.mjs} +32 -3
  10. package/chunks/{chunk-XQORVEL6.mjs → chunk-FFIXBXHD.mjs} +60 -233
  11. package/chunks/chunk-GFG5I7WI.mjs +807 -0
  12. package/chunks/{chunk-AOHGXC4D.mjs → chunk-GZ3E45TE.mjs} +518 -240
  13. package/chunks/chunk-IAAKV7V2.mjs +37 -0
  14. package/chunks/{chunk-YA6TJOAM.mjs → chunk-VJ6AESSJ.mjs} +216 -24
  15. package/chunks/chunk-X3UPCLX5.mjs +503 -0
  16. package/chunks/{chunk-TRECVC6H.mjs → chunk-ZDH4JRVX.mjs} +1041 -4051
  17. package/chunks/{chunk-FNP5PNJW.mjs → chunk-ZRGJHNES.mjs} +6 -0
  18. package/chunks/compare-W4DJYVHT.mjs +239 -0
  19. package/chunks/compare-command-U36H55IE.mjs +144 -0
  20. package/chunks/{css-build-VKKTSP6P.mjs → css-build-MKIHYHCX.mjs} +2 -1
  21. package/chunks/{dev-DXMZPST7.mjs → dev-X3PKN4G3.mjs} +77 -26
  22. package/chunks/{menu-W7ZXME4A.mjs → menu-J3CLVADF.mjs} +5 -3
  23. package/chunks/{publish-command-AVMRM4UZ.mjs → publish-command-SAPICGGM.mjs} +15 -8
  24. package/chunks/{release-diff-3OZOYBXR.mjs → release-diff-Y7X63MT3.mjs} +13 -7
  25. package/chunks/{serve-U2YV7AQH.mjs → serve-7DR4WSYA.mjs} +2 -2
  26. package/cli.mjs +17 -10
  27. package/package.json +4 -3
  28. package/chunks/check-command-SXDUKSAZ.mjs +0 -256
@@ -0,0 +1,577 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
+ import {
4
+ createAuditSession,
5
+ filterRules,
6
+ formatJson,
7
+ formatText,
8
+ getRule,
9
+ registerRule,
10
+ registerSharedRules,
11
+ releaseCollector,
12
+ reportExitCode,
13
+ toReport
14
+ } from "./chunk-FFIXBXHD.mjs";
15
+ import {
16
+ cliMemorySettings,
17
+ diagramRenderers,
18
+ iconResolver
19
+ } from "./chunk-OBUK53NJ.mjs";
20
+ import {
21
+ build,
22
+ siteBase
23
+ } from "./chunk-ZDH4JRVX.mjs";
24
+ import {
25
+ INLINE_SCRIPTS
26
+ } from "./chunk-CYJ6GFVM.mjs";
27
+ import "./chunk-2EM7IEQT.mjs";
28
+ import {
29
+ readBuildFiles
30
+ } from "./chunk-X3UPCLX5.mjs";
31
+ import "./chunk-GFG5I7WI.mjs";
32
+ import {
33
+ ConfigError,
34
+ htmlIsText,
35
+ loadYaml,
36
+ parseConfig
37
+ } from "./chunk-5NQOUB5I.mjs";
38
+ import "./chunk-GZ3E45TE.mjs";
39
+ import {
40
+ DATA_DIRECTIVES,
41
+ frontmatterPolicyFromConfig
42
+ } from "./chunk-VJ6AESSJ.mjs";
43
+ import {
44
+ FAILING_CODES,
45
+ UsageError,
46
+ dataProblemLines,
47
+ flag,
48
+ option,
49
+ positional
50
+ } from "./chunk-ZRGJHNES.mjs";
51
+ import "./chunk-YVSP26OS.mjs";
52
+ import "./chunk-O3R3MASP.mjs";
53
+ import "./chunk-IAAKV7V2.mjs";
54
+ import {
55
+ isRef,
56
+ isStream
57
+ } from "./chunk-5A2QPRCV.mjs";
58
+ import "./chunk-G6OTOD3B.mjs";
59
+ import "./chunk-STRHO6SY.mjs";
60
+
61
+ // src/node/check-command.ts
62
+ import { existsSync, readFileSync, statSync } from "node:fs";
63
+ import { join, resolve } from "node:path";
64
+
65
+ // src/core/check.ts
66
+ var KEPT = /(^|\/)(robots\.txt|sitemap[^/]*\.xml)$/;
67
+ var BUILD_DIAGNOSTICS = /* @__PURE__ */ new Set(["front-matter", "template", "template-tag", "data", "example", "choice", "parse"]);
68
+ var DATA_NODES = new Set(DATA_DIRECTIVES);
69
+ function withoutDataNodes(tree) {
70
+ let changed = false;
71
+ const out = [];
72
+ for (const n of tree) {
73
+ if (DATA_NODES.has(n.type)) {
74
+ changed = true;
75
+ continue;
76
+ }
77
+ const children = n.children && withoutDataNodes(n.children);
78
+ if (children !== n.children) changed = true;
79
+ out.push(children === n.children ? n : { ...n, children });
80
+ }
81
+ return changed ? out : tree;
82
+ }
83
+ function refsOf(tree, visit) {
84
+ const inline = (nodes) => {
85
+ if (!Array.isArray(nodes)) return;
86
+ for (const n of nodes) {
87
+ if (n.type === "link" && typeof n.href === "string") visit(`l ${n.href}`, { type: "paragraph", inline: [{ type: "link", href: n.href, children: [] }] });
88
+ else if (n.type === "image" && typeof n.src === "string") visit(`i ${n.src}`, { type: "paragraph", inline: [{ type: "image", src: n.src, alt: "" }] });
89
+ inline(n.children);
90
+ }
91
+ };
92
+ const blocks = (nodes) => {
93
+ for (const n of nodes ?? []) {
94
+ const o = n;
95
+ inline(o.inline);
96
+ if (typeof o.html === "string" && !htmlIsText(n)) visit(`h ${o.html}`, { type: "html", html: o.html });
97
+ for (const k of ["href", "src"]) {
98
+ const v = n.props?.[k];
99
+ if (typeof v === "string") visit(`${k} ${v}`, { type: "div", props: { [k]: v }, children: [] });
100
+ }
101
+ blocks(n.children);
102
+ }
103
+ };
104
+ blocks(tree);
105
+ }
106
+ function withAgentsRefs(tree, agents) {
107
+ if (!agents) return tree;
108
+ const seen = /* @__PURE__ */ new Set();
109
+ refsOf(tree, (k) => seen.add(k));
110
+ const extra = [];
111
+ refsOf(agents, (k, n) => {
112
+ if (seen.has(k)) return;
113
+ seen.add(k);
114
+ extra.push(n);
115
+ });
116
+ return extra.length ? [...tree, ...extra] : tree;
117
+ }
118
+ var markdownSyntax = {
119
+ id: "markdown/syntax",
120
+ category: "markdown",
121
+ stage: "source-corpus",
122
+ severity: "warning",
123
+ description: "Dogsbay Markdown the parser recovers from silently: an unclosed or stray `:::`, an unknown `:::name` or `:name[]`, a prop a directive does not take, an unreadable `{\u2026}` attribute block.",
124
+ run: () => []
125
+ };
126
+ async function check(input) {
127
+ const { configText, filter, releaseFrom, ...rest } = input;
128
+ const parsed = input.config ?? parseConfig(configText);
129
+ const raw = parseRaw(configText);
130
+ const site = raw.site ?? {};
131
+ const policy = frontmatterPolicyFromConfig(raw, parsed.sources.map((s) => s.path === "." ? "" : s.path.replace(/\/+$/, "")));
132
+ if (policy.invalid) throw new ConfigError(policy.invalid);
133
+ registerSharedRules();
134
+ if (!getRule(markdownSyntax.id)) registerRule(markdownSyntax);
135
+ const rules = filterRules(filter ?? {});
136
+ const releaseRule = rules.find((r) => r.id === "structure/release-moves");
137
+ const corpusRules = rules.filter((r) => r.stage === "source-corpus" && r !== releaseRule && r.id !== markdownSyntax.id);
138
+ const otherRules = rules.filter((r) => r.stage !== "source-corpus");
139
+ const wantDist = rules.some((r) => r.stage === "dist");
140
+ const cfg = { ...parsed, search: false, llmsTxt: false };
141
+ const auditConfig = {
142
+ siteName: cfg.name,
143
+ // The sitemap lists URLs under url + basePath; the sitemap rules strip siteUrl's path.
144
+ siteUrl: siteBase(cfg) ?? cfg.url,
145
+ brandKeywords: Array.isArray(site.brandKeywords) ? site.brandKeywords.filter((k) => typeof k === "string") : void 0
146
+ };
147
+ const session = createAuditSession({ rules: otherRules, nav: [], config: auditConfig, frontmatterPolicy: policy });
148
+ const release = releaseRule ? releaseCollector(cfg, releaseFrom) : void 0;
149
+ const units = /* @__PURE__ */ new Map();
150
+ const unitOf = (prefix) => {
151
+ let u = units.get(prefix);
152
+ if (!u) {
153
+ const assets = /* @__PURE__ */ new Set();
154
+ u = { assets, session: createAuditSession({ rules: corpusRules, nav: [], config: auditConfig, basePath: cfg.basePath ? `/${cfg.basePath}` : "", knownAssets: assets }) };
155
+ units.set(prefix, u);
156
+ }
157
+ return u;
158
+ };
159
+ const named = (slug) => slug || "index";
160
+ const kept = /* @__PURE__ */ new Map();
161
+ const decoder = new TextDecoder();
162
+ const syntax = [];
163
+ const hooks = rules.some((r) => r.id === markdownSyntax.id) ? {
164
+ diagnostics: (file, list) => {
165
+ for (const d of list) if (!BUILD_DIAGNOSTICS.has(d.code)) syntax.push({ ruleId: markdownSyntax.id, severity: markdownSyntax.severity, file, ...d.line ? { line: d.line } : {}, message: d.message, context: d.code });
166
+ }
167
+ } : {};
168
+ const result = await build({
169
+ ...rest,
170
+ config: cfg,
171
+ onRedirects: (r) => release?.onRedirects(r),
172
+ onPageBuilt: (p) => {
173
+ release?.onPage(p);
174
+ const local = p.unit && p.slug.startsWith(p.unit) ? p.slug.slice(p.unit.length).replace(/^\//, "") : p.slug;
175
+ const page = { slug: p.slug, title: p.title, tree: withAgentsRefs(withoutDataNodes(p.tree), p.agentsTree && withoutDataNodes(p.agentsTree)), headings: [], frontmatter: p.frontmatter };
176
+ session.page({ ...page, slug: [p.unit, named(local)].filter(Boolean).join("/") }, { path: p.source, text: p.text });
177
+ if (corpusRules.length) unitOf(p.unit).session.page({ ...page, slug: named(local), sourcePath: p.contentPath });
178
+ },
179
+ onUnitAssets: (prefix, assets) => {
180
+ if (!corpusRules.length) return;
181
+ const u = unitOf(prefix);
182
+ for (const a of assets) u.assets.add(`/${a}`);
183
+ },
184
+ sink: async (path, content) => {
185
+ if (!wantDist || isStream(content)) return;
186
+ const html = path.endsWith(".html");
187
+ if (!html && !KEPT.test(path)) return;
188
+ const text = typeof content === "string" ? content : content instanceof Uint8Array ? decoder.decode(content) : decoder.decode(await content.read());
189
+ if (html) session.dist(path, text);
190
+ else kept.set(path, text);
191
+ }
192
+ }, hooks);
193
+ const issues = session.finish((p) => kept.get(p.replace(/^\/+/, ""))).issues;
194
+ issues.push(...syntax);
195
+ for (const p of result.problems) {
196
+ if (p.code === "data") issues.push({ ruleId: "data/files", severity: "error", file: p.file ?? "dogsbay.config.yml", ...p.line ? { line: p.line } : {}, message: p.message });
197
+ if (p.code === "example") issues.push({ ruleId: "examples/files", severity: "error", file: p.file ?? "dogsbay.config.yml", ...p.line ? { line: p.line } : {}, message: p.message });
198
+ if (p.code === "choice") issues.push({ ruleId: "choices/valid", severity: "error", file: p.file ?? "dogsbay.config.yml", ...p.line ? { line: p.line } : {}, message: p.message });
199
+ if (p.code === "menu") issues.push({ ruleId: "structure/menu-valid", severity: "warning", file: p.file ?? "dogsbay.config.yml", ...p.line ? { line: p.line } : {}, message: p.message });
200
+ }
201
+ if (releaseRule && release) issues.push(...releaseRule.run({ pages: [], nav: [], config: auditConfig, release: release.finish() }));
202
+ for (const [prefix, u] of units) {
203
+ for (const i of u.session.finish().issues) issues.push(prefix ? { ...i, file: `${prefix}/${i.file}` } : i);
204
+ }
205
+ return { report: toReport(issues, rules.length), build: result };
206
+ }
207
+ function parseRaw(text) {
208
+ if (!text) return {};
209
+ try {
210
+ const v = loadYaml(text);
211
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
212
+ } catch {
213
+ return {};
214
+ }
215
+ }
216
+
217
+ // src/core/artifact.ts
218
+ var ARTIFACT_LIMITS = { files: 511, textBytes: 16 * 1024 * 1024, binaryBytes: 15 * 1024 * 1024 };
219
+ var SERVED = /* @__PURE__ */ new Set([
220
+ "html",
221
+ "htm",
222
+ "css",
223
+ "js",
224
+ "mjs",
225
+ "json",
226
+ "map",
227
+ "webmanifest",
228
+ "txt",
229
+ "md",
230
+ "xml",
231
+ "csv",
232
+ "svg",
233
+ "png",
234
+ "jpg",
235
+ "jpeg",
236
+ "gif",
237
+ "webp",
238
+ "avif",
239
+ "ico",
240
+ "bmp",
241
+ "woff",
242
+ "woff2",
243
+ "ttf",
244
+ "otf",
245
+ "pdf",
246
+ "mp4",
247
+ "webm",
248
+ "ogg",
249
+ "ogv",
250
+ "mp3",
251
+ "wav",
252
+ "m4a",
253
+ "vtt"
254
+ ]);
255
+ var TEXT = /* @__PURE__ */ new Set(["html", "htm", "css", "js", "mjs", "json", "map", "webmanifest", "txt", "md", "xml", "csv", "svg", "vtt"]);
256
+ var ext = (path) => {
257
+ const name = path.slice(path.lastIndexOf("/") + 1);
258
+ const dot = name.lastIndexOf(".");
259
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
260
+ };
261
+ var ABSOLUTE = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
262
+ var rootAbsolute = (v) => v.startsWith("/") && !v.startsWith("//");
263
+ var originOf = (v) => {
264
+ try {
265
+ return new URL(v.startsWith("//") ? `https:${v}` : v).origin;
266
+ } catch {
267
+ return v;
268
+ }
269
+ };
270
+ var decode = (v) => v.replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
271
+ function attrsOf(text) {
272
+ const out = /* @__PURE__ */ new Map();
273
+ for (const m of text.matchAll(/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g)) out.set(m[1].toLowerCase(), decode(m[2] ?? m[3] ?? m[4] ?? ""));
274
+ return out;
275
+ }
276
+ function scan(html) {
277
+ const scripts = [];
278
+ const styles = [];
279
+ const rest = html.replace(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi, (m, a, body, at) => {
280
+ scripts.push({ attrs: attrsOf(a), body, at });
281
+ return " ".repeat(m.length);
282
+ }).replace(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi, (m, css) => {
283
+ styles.push(css);
284
+ return " ".repeat(m.length);
285
+ }).replace(/<!--[\s\S]*?-->/g, (m) => " ".repeat(m.length));
286
+ const tags = [];
287
+ for (const m of rest.matchAll(/<([a-zA-Z][\w:-]*)\b([^>]*)>/g)) tags.push({ name: m[1].toLowerCase(), attrs: attrsOf(m[2]), at: m.index });
288
+ return { scripts, tags, styles };
289
+ }
290
+ var runs = (attrs) => {
291
+ const t = (attrs.get("type") ?? "").trim().toLowerCase();
292
+ return t === "" || t === "module" || /^(?:text|application)\/(?:x-)?(?:javascript|ecmascript)$/.test(t);
293
+ };
294
+ function loads(t) {
295
+ const out = [];
296
+ const add = (kind, v) => v && out.push([kind, v.trim()]);
297
+ const srcset = (kind, v) => v?.split(",").forEach((c) => add(kind, c.trim().split(/\s+/)[0]));
298
+ switch (t.name) {
299
+ case "script":
300
+ add("script", t.attrs.get("src"));
301
+ break;
302
+ case "link": {
303
+ const rel = (t.attrs.get("rel") ?? "").toLowerCase();
304
+ if (/\b(stylesheet|preload|modulepreload|icon|apple-touch-icon|manifest|prefetch)\b/.test(rel)) add(/stylesheet/.test(rel) ? "stylesheet" : rel.split(/\s+/)[0], t.attrs.get("href"));
305
+ break;
306
+ }
307
+ case "img":
308
+ add("image", t.attrs.get("src"));
309
+ srcset("image", t.attrs.get("srcset"));
310
+ break;
311
+ case "source":
312
+ add("media", t.attrs.get("src"));
313
+ srcset("image", t.attrs.get("srcset"));
314
+ break;
315
+ case "video":
316
+ add("media", t.attrs.get("src"));
317
+ add("image", t.attrs.get("poster"));
318
+ break;
319
+ case "audio":
320
+ case "track":
321
+ add("media", t.attrs.get("src"));
322
+ break;
323
+ case "iframe":
324
+ case "frame":
325
+ add("frame", t.attrs.get("src"));
326
+ break;
327
+ case "embed":
328
+ add("embed", t.attrs.get("src"));
329
+ break;
330
+ case "object":
331
+ add("object", t.attrs.get("data"));
332
+ break;
333
+ case "image":
334
+ case "use":
335
+ add("image", t.attrs.get("href") ?? t.attrs.get("xlink:href"));
336
+ break;
337
+ }
338
+ return out;
339
+ }
340
+ function cssUrls(css) {
341
+ const out = [];
342
+ for (const m of css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi)) out.push((m[1] ?? m[2] ?? m[3] ?? "").trim());
343
+ for (const m of css.matchAll(/@import\s+(?:"([^"]*)"|'([^']*)')/gi)) out.push((m[1] ?? m[2] ?? "").trim());
344
+ return out;
345
+ }
346
+ var LINK_ATTRS = ["href", "src", "poster", "action", "formaction", "data"];
347
+ var DANGEROUS = /* @__PURE__ */ new Set(["iframe", "frame", "object", "embed"]);
348
+ var SCRIPTISH = /&lt;\s*(?:script|iframe)\b|\bjavascript:|\\u003c\s*(?:script|iframe)\b/i;
349
+ var ArtifactAudit = class {
350
+ /** `assetsFolder`: the build's own folder (ssg.assetsFolder), whose scripts are the build's. */
351
+ constructor(assetsFolder = "_dogsbay") {
352
+ this.assetsFolder = assetsFolder;
353
+ this.ours = new Set(INLINE_SCRIPTS.map((s) => s.trim()));
354
+ }
355
+ files = 0;
356
+ bytes = 0;
357
+ findings = [];
358
+ underscore = /* @__PURE__ */ new Map();
359
+ external = /* @__PURE__ */ new Map();
360
+ content = [];
361
+ chrome = [];
362
+ textOnly = 0;
363
+ ours;
364
+ encoder = new TextEncoder();
365
+ decoder = new TextDecoder();
366
+ async add(path, content) {
367
+ this.files++;
368
+ const e = ext(path);
369
+ let text;
370
+ let size;
371
+ if (typeof content === "string") {
372
+ text = content;
373
+ size = this.encoder.encode(content).length;
374
+ } else if (content instanceof Uint8Array) {
375
+ size = content.byteLength;
376
+ if (TEXT.has(e)) text = this.decoder.decode(content);
377
+ } else if (isStream(content)) {
378
+ let s = "";
379
+ for await (const c of content.chunks()) s += c;
380
+ text = s;
381
+ size = this.encoder.encode(s).length;
382
+ } else if (isRef(content)) {
383
+ const needText = e === "html" || e === "htm" || e === "css";
384
+ if (content.size !== void 0 && !needText) size = content.size;
385
+ else {
386
+ const b = await content.read();
387
+ size = b.byteLength;
388
+ if (needText) text = this.decoder.decode(b);
389
+ }
390
+ } else size = 0;
391
+ this.bytes += size;
392
+ const top = path.split("/")[0];
393
+ if (top.startsWith("_")) this.underscore.set(top, (this.underscore.get(top) ?? 0) + 1);
394
+ if (!SERVED.has(e) && !(path === "_headers" || path === "_redirects")) this.findings.push({ rule: "artifact/file-type", severity: "warning", file: path, message: `${e ? `.${e}` : "a file without an extension"} is not a standard web media type; the host may refuse it` });
395
+ const limit = TEXT.has(e) ? ARTIFACT_LIMITS.textBytes : ARTIFACT_LIMITS.binaryBytes;
396
+ if (size > limit) this.findings.push({ rule: "artifact/file-size", severity: "error", file: path, message: `${mb(size)} is over the ${mb(limit)} limit for a ${TEXT.has(e) ? "text" : "binary"} file` });
397
+ if (text === void 0) return;
398
+ if (e === "html" || e === "htm") this.page(path, text);
399
+ else if (e === "css") this.rootLinks(path, cssUrls(text));
400
+ }
401
+ rootLinks(file, urls) {
402
+ const found = [...new Set(urls.filter(rootAbsolute))];
403
+ if (found.length) this.findings.push({ rule: "artifact/root-link", severity: "error", file, message: `${found.length === 1 ? "a link" : `${found.length} links`} from the host's root, which an artifact does not serve the site at: ${found.slice(0, 3).join(", ")}${found.length > 3 ? ", \u2026" : ""}` });
404
+ }
405
+ page(file, html) {
406
+ const { scripts, tags, styles } = scan(html);
407
+ const start = html.indexOf('<article class="docs-prose">');
408
+ const end = html.lastIndexOf("</article>");
409
+ const inContent = (at) => start >= 0 && at > start && at < end;
410
+ const urls = [];
411
+ const loaded = [];
412
+ for (const t of tags) {
413
+ for (const a of LINK_ATTRS) {
414
+ const v = t.attrs.get(a);
415
+ if (v !== void 0) urls.push(v.trim());
416
+ }
417
+ const srcset = t.attrs.get("srcset");
418
+ if (srcset) for (const c of srcset.split(",")) urls.push(c.trim().split(/\s+/)[0]);
419
+ const style = t.attrs.get("style");
420
+ if (style) urls.push(...cssUrls(style));
421
+ loaded.push(...loads(t));
422
+ const where = inContent(t.at) ? this.content : this.chrome;
423
+ for (const [k, v] of t.attrs) {
424
+ if (/^on[a-z]+$/.test(k)) where.push({ file, what: `${k} handler on <${t.name}>` });
425
+ else if (LINK_ATTRS.includes(k) && /^\s*javascript:/i.test(v)) where.push({ file, what: `javascript: ${k} on <${t.name}>` });
426
+ }
427
+ if (DANGEROUS.has(t.name)) where.push({ file, what: `<${t.name}>` });
428
+ }
429
+ for (const css of styles) urls.push(...cssUrls(css));
430
+ for (const s of scripts) {
431
+ const src = s.attrs.get("src");
432
+ if (src !== void 0) {
433
+ urls.push(src.trim());
434
+ loaded.push(["script", src.trim()]);
435
+ }
436
+ if (!runs(s.attrs)) continue;
437
+ if (inContent(s.at)) this.content.push({ file, what: src ? `<script src="${src}">` : "inline <script>" });
438
+ else if (src === void 0 ? !this.ours.has(s.body.trim()) : !ABSOLUTE.test(src) && !new RegExp(`(^|/)${this.assetsFolder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`).test(src))
439
+ this.chrome.push({ file, what: src ? `<script src="${src}">` : "inline <script>" });
440
+ }
441
+ this.rootLinks(file, urls);
442
+ const pages = /* @__PURE__ */ new Set();
443
+ for (const [kind, v] of loaded) {
444
+ if (!ABSOLUTE.test(v)) continue;
445
+ const o = originOf(v);
446
+ const x = this.external.get(o) ?? { what: /* @__PURE__ */ new Set(), pages: /* @__PURE__ */ new Set() };
447
+ x.what.add(kind);
448
+ x.pages.add(file);
449
+ this.external.set(o, x);
450
+ pages.add(o);
451
+ }
452
+ const contentHtml = start >= 0 ? html.slice(start, end) : "";
453
+ const embedded = scripts.find((s) => s.attrs.get("id") === "db-page-markdown")?.body ?? "";
454
+ if (SCRIPTISH.test(contentHtml) || SCRIPTISH.test(embedded)) this.textOnly++;
455
+ }
456
+ finish() {
457
+ const findings = [...this.findings];
458
+ if (this.files > ARTIFACT_LIMITS.files) findings.unshift({ rule: "artifact/file-count", severity: "error", file: ".", message: `${this.files} files, over the ${ARTIFACT_LIMITS.files} an artifact version holds` });
459
+ for (const [top, n] of this.underscore) {
460
+ const host = top === "_headers" || top === "_redirects";
461
+ const fix = top === "_dogsbay" ? "set ssg.assetsFolder (such as dogsbay)" : top === "_headers" ? "a host file for Cloudflare and Netlify; agent.llmsTxt: false leaves it out" : host ? "a host file for Cloudflare and Netlify, from the redirects; leave it out of the publish" : "rename it";
462
+ findings.push({ rule: "artifact/underscore-path", severity: "error", file: top, message: `the host refuses top-level paths that start with "_"${n > 1 ? ` (${n} files)` : ""}: ${fix}` });
463
+ }
464
+ return {
465
+ files: this.files,
466
+ bytes: this.bytes,
467
+ limits: ARTIFACT_LIMITS,
468
+ findings,
469
+ safety: {
470
+ external: [...this.external].map(([origin, x]) => ({ origin, what: [...x.what].sort(), pages: x.pages.size })).sort((a, b) => b.pages - a.pages || a.origin.localeCompare(b.origin)),
471
+ content: this.content,
472
+ chrome: this.chrome,
473
+ textOnly: this.textOnly
474
+ }
475
+ };
476
+ }
477
+ };
478
+ var mb = (n) => `${(n / 1048576).toFixed(1)} MB`;
479
+ async function artifactCheck(input) {
480
+ const audit = new ArtifactAudit(input.config.assetsFolder);
481
+ const result = await build({ ...input, sink: (path, content) => audit.add(path, content) });
482
+ const report = audit.finish();
483
+ if (input.config.search && input.config.searchEngine !== "builtin")
484
+ report.findings.push({ rule: "artifact/pagefind", severity: "warning", file: "pagefind/", message: `ssg.search: ${input.config.searchEngine} writes each unit's pagefind/ folder after the build, which this check does not see: its files count toward the ${ARTIFACT_LIMITS.files}, its .pf_* files may be refused, and its search loads over HTTP; ssg.search: builtin keeps search in the checked files` });
485
+ return { report, build: result };
486
+ }
487
+ function formatArtifactReport(r) {
488
+ const lines = [];
489
+ lines.push(`Artifact check: ${r.files} files (limit ${r.limits.files}), ${mb(r.bytes)}`);
490
+ const errors = r.findings.filter((f) => f.severity === "error").length;
491
+ const warnings = r.findings.length - errors;
492
+ if (!r.findings.length) lines.push(" Nothing stops a publish.");
493
+ for (const f of r.findings.slice(0, 50)) lines.push(` ${f.severity === "error" ? "error" : "warn "} ${f.rule} ${f.file}: ${f.message}`);
494
+ if (r.findings.length > 50) lines.push(` \u2026 and ${r.findings.length - 50} more (--json lists them all)`);
495
+ const s = r.safety;
496
+ lines.push("", "Safety");
497
+ lines.push(s.external.length ? ` Loaded from outside the site: ${s.external.map((x) => `${x.origin} (${x.what.join(", ")}; ${x.pages} page${x.pages === 1 ? "" : "s"})`).join("; ")}` : " Loaded from outside the site: nothing");
498
+ const list = (xs) => {
499
+ const by = /* @__PURE__ */ new Map();
500
+ for (const x of xs) by.set(x.what, (by.get(x.what) ?? 0) + 1);
501
+ const pages = new Set(xs.map((x) => x.file)).size;
502
+ return `${[...by].map(([w, n]) => `${w}${n > 1 ? ` \xD7${n}` : ""}`).join(", ")} on ${pages} page${pages === 1 ? "" : "s"} (first: ${xs[0].file})`;
503
+ };
504
+ lines.push(s.content.length ? ` From the content: ${list(s.content)}` : " From the content: no raw <script>, <iframe>, <object>, <embed>, event handlers or javascript: links");
505
+ if (s.chrome.length) lines.push(` In the page layout, not the build's own: ${list(s.chrome)}`);
506
+ else lines.push(" Page layout: only the build's own scripts");
507
+ if (s.textOnly) lines.push(` Script-like text on ${s.textOnly} page${s.textOnly === 1 ? "" : "s"}, as text only: inside code, prose or the embedded Markdown`);
508
+ lines.push("", `${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}`);
509
+ return lines.join("\n") + "\n";
510
+ }
511
+
512
+ // src/node/check-command.ts
513
+ async function runCheck(args) {
514
+ const json = flag(args, "--json");
515
+ const strict = flag(args, "--strict");
516
+ const sourceOnly = flag(args, "--source");
517
+ const distOnly = flag(args, "--dist");
518
+ const noDiagrams = flag(args, "--no-diagrams");
519
+ const quiet = flag(args, "--quiet", "-q");
520
+ const categories = option(args, "--category");
521
+ const rules = option(args, "--rule");
522
+ const skip = option(args, "--skip");
523
+ const includeDraftsCheck = flag(args, "--include-drafts");
524
+ const untrusted = flag(args, "--untrusted");
525
+ const artifact = flag(args, "--artifact");
526
+ const memory = cliMemorySettings(flag(args, "--low-memory"));
527
+ if (sourceOnly && distOnly) throw new UsageError("--source and --dist cannot be used together");
528
+ if (artifact && (sourceOnly || distOnly || categories.length || rules.length || skip.length)) throw new UsageError("--artifact checks the built files on their own; it takes no --source, --dist, --category, --rule or --skip");
529
+ const project = resolve(positional(args, "."));
530
+ if (!(existsSync(project) && statSync(project).isDirectory())) throw new UsageError(`${project} is not a folder`);
531
+ const cfgPath = ["dogsbay.config.yml", "dogsbay.config.yaml"].map((f) => join(project, f)).find(existsSync);
532
+ const cfgText = cfgPath ? readFileSync(cfgPath, "utf8") : void 0;
533
+ const cfg = parseConfig(cfgText);
534
+ if (!cfgPath && !existsSync(join(project, "content"))) cfg.sources = [{ path: "." }];
535
+ const { files } = await readBuildFiles(project, cfg, [join(project, "out")], untrusted);
536
+ if (artifact) {
537
+ const { report: report2, build: result2 } = await artifactCheck({ ...memory, files, config: cfg, includeDrafts: includeDraftsCheck, untrusted, diagrams: noDiagrams ? void 0 : diagramRenderers(), icons: await iconResolver() });
538
+ const failing = dataProblemLines(result2.problems);
539
+ const warnings2 = result2.warnings.filter((_, i) => !FAILING_CODES.has(result2.problems[i].code));
540
+ if (!quiet && !json) for (const w of warnings2.slice(0, 20)) console.warn(`warn ${w}`);
541
+ if (!json) for (const e of failing) console.error(`error ${e}`);
542
+ process.stdout.write(json ? `${JSON.stringify({ ...report2, buildErrors: failing }, null, 2)}
543
+ ` : formatArtifactReport(report2));
544
+ const errors = report2.findings.some((f) => f.severity === "error");
545
+ process.exitCode = errors || failing.length || strict && report2.findings.length ? 1 : 0;
546
+ return;
547
+ }
548
+ const stages = sourceOnly ? ["source", "source-corpus"] : distOnly ? ["dist"] : [];
549
+ const { report, build: result } = await check({
550
+ ...memory,
551
+ files,
552
+ config: cfg,
553
+ configText: cfgText,
554
+ includeDrafts: includeDraftsCheck,
555
+ untrusted,
556
+ diagrams: noDiagrams ? void 0 : diagramRenderers(),
557
+ icons: await iconResolver(),
558
+ filter: {
559
+ categories: categories.length ? categories : void 0,
560
+ stages: stages.length ? stages : void 0,
561
+ rules: rules.length ? rules : void 0,
562
+ skip: skip.length ? skip : void 0
563
+ }
564
+ });
565
+ if (report.summary.rulesRun === 0) {
566
+ console.error("no rules matched --category/--rule/--skip; nothing was checked");
567
+ process.exitCode = 1;
568
+ return;
569
+ }
570
+ const warnings = result.warnings.filter((_, i) => !FAILING_CODES.has(result.problems[i].code));
571
+ if (!quiet && !json) for (const w of warnings.slice(0, 20)) console.warn(`warn ${w}`);
572
+ process.stdout.write(json ? formatJson(report) : formatText(report));
573
+ process.exitCode = reportExitCode(report, strict);
574
+ }
575
+ export {
576
+ runCheck
577
+ };
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
+ import {
4
+ dirname,
5
+ isExternal,
6
+ normalize,
7
+ scriptUrl
8
+ } from "./chunk-GZ3E45TE.mjs";
9
+
10
+ // src/core/nav.ts
11
+ function slugFromPath(p) {
12
+ let s = normalize(p).replace(/^\/+/, "").replace(/\.(md|markdown)$/i, "");
13
+ if (s === "index") return "";
14
+ if (s.endsWith("/index")) s = s.slice(0, -"/index".length);
15
+ return s;
16
+ }
17
+ function navFromMenu(items) {
18
+ const walk = (it) => {
19
+ const target = it.file ?? it.href;
20
+ const node = { label: it.label, children: (it.children ?? []).map(walk) };
21
+ if (target) {
22
+ if (isExternal(target)) {
23
+ if (scriptUrl(target, "link")) node.refused = target;
24
+ else node.href = target;
25
+ } else {
26
+ const hash = target.indexOf("#");
27
+ const path = (hash < 0 ? target : target.slice(0, hash)).replace(/\?.*$/, "");
28
+ node.slug = slugFromPath(path.replace(/\.html$/, ".md"));
29
+ if (hash >= 0 && hash < target.length - 1) node.fragment = target.slice(hash);
30
+ }
31
+ }
32
+ if (it.unlisted) node.unlisted = true;
33
+ if (it.singlePage) node.singlePage = it.singlePage;
34
+ return node;
35
+ };
36
+ return items.map(walk);
37
+ }
38
+ function navFromPages(pages) {
39
+ const root = { label: "", children: [] };
40
+ const dirs = /* @__PURE__ */ new Map([["", root]]);
41
+ const sorted = [...pages].sort((a, b) => (a.order ?? 1e9) - (b.order ?? 1e9) || a.slug.localeCompare(b.slug));
42
+ const ensureDir = (dir) => {
43
+ const hit = dirs.get(dir);
44
+ if (hit) return hit;
45
+ const parent = ensureDir(dirname(dir));
46
+ const node = { label: humanize(dir.split("/").pop()), children: [] };
47
+ parent.children.push(node);
48
+ dirs.set(dir, node);
49
+ return node;
50
+ };
51
+ for (const p of sorted) {
52
+ if (p.slug === "") continue;
53
+ const existing = dirs.get(p.slug);
54
+ if (existing) {
55
+ existing.slug = p.slug;
56
+ existing.label = p.title;
57
+ continue;
58
+ }
59
+ if (pages.some((q) => q.slug.startsWith(p.slug + "/"))) {
60
+ const sec = ensureDir(p.slug);
61
+ sec.slug = p.slug;
62
+ sec.label = p.title;
63
+ continue;
64
+ }
65
+ ensureDir(dirname(p.slug)).children.push({ label: p.title, slug: p.slug, children: [] });
66
+ }
67
+ return root.children;
68
+ }
69
+ function humanize(s) {
70
+ const t = s.replace(/[-_]+/g, " ").trim();
71
+ return t.charAt(0).toUpperCase() + t.slice(1);
72
+ }
73
+ function indexNav(nav, o = {}) {
74
+ const order = [];
75
+ const trail = /* @__PURE__ */ new Map();
76
+ const walk = (nodes, chain) => {
77
+ for (const n of nodes) {
78
+ const here = [...chain, n];
79
+ if (n.slug != null && !n.fragment && !(o.skipAliases && n.alias) && !trail.has(n.slug)) {
80
+ trail.set(n.slug, here);
81
+ order.push(n.slug);
82
+ }
83
+ walk(n.children, here);
84
+ }
85
+ };
86
+ walk(nav, []);
87
+ return { order, trail };
88
+ }
89
+
90
+ export {
91
+ slugFromPath,
92
+ navFromMenu,
93
+ navFromPages,
94
+ indexNav
95
+ };