@cmo-so/mcp 0.12.10 → 0.12.12

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 (2) hide show
  1. package/dist/cmo-mcp.mjs +1950 -34
  2. package/package.json +1 -1
package/dist/cmo-mcp.mjs CHANGED
@@ -7199,7 +7199,7 @@ var require_dist = __commonJS({
7199
7199
  // package.json
7200
7200
  var package_default = {
7201
7201
  name: "@cmo-so/cli",
7202
- version: "0.12.10",
7202
+ version: "0.12.12",
7203
7203
  description: "CMO.so on the command line: your websites, ideas, blog posts, LinkedIn queue and results, plus a local MCP server for Claude Desktop, Cursor and other MCP clients.",
7204
7204
  type: "module",
7205
7205
  license: "MIT",
@@ -8397,26 +8397,26 @@ function createOAuthClient({ issuer, clientId, fetch: fetchImpl = globalThis.fet
8397
8397
 
8398
8398
  // ../../packages/api-client/src/session.ts
8399
8399
  function createSession({ oauth: oauth2, store, skewMs = 6e4, now = Date.now, onSignedOut }) {
8400
- let tokens;
8400
+ let tokens2;
8401
8401
  let refreshing = null;
8402
8402
  async function current() {
8403
- if (tokens === void 0) tokens = await store.load();
8404
- return tokens;
8403
+ if (tokens2 === void 0) tokens2 = await store.load();
8404
+ return tokens2;
8405
8405
  }
8406
8406
  async function accept(res, previous) {
8407
8407
  const refreshToken = res.refresh_token ?? previous?.refreshToken;
8408
8408
  if (!refreshToken) throw new SignInRequiredError("The sign-in did not return a refresh token.");
8409
- tokens = {
8409
+ tokens2 = {
8410
8410
  refreshToken,
8411
8411
  accessToken: res.access_token,
8412
8412
  expiresAt: now() + res.expires_in * 1e3,
8413
8413
  scope: res.scope
8414
8414
  };
8415
- await store.save(tokens);
8416
- return tokens;
8415
+ await store.save(tokens2);
8416
+ return tokens2;
8417
8417
  }
8418
8418
  async function end() {
8419
- tokens = null;
8419
+ tokens2 = null;
8420
8420
  await store.clear();
8421
8421
  onSignedOut?.();
8422
8422
  }
@@ -12142,12 +12142,12 @@ var socialTools = [
12142
12142
  need: write5,
12143
12143
  risk: "W1",
12144
12144
  gates: ["VER"],
12145
- run: async (ctx, { id, words, style, text_effect, order, remove: remove3 }) => {
12145
+ run: async (ctx, { id, words, style, text_effect, order: order2, remove: remove3 }) => {
12146
12146
  const out = await ws(ctx).editSocialPicture(Number(id), {
12147
12147
  ...Array.isArray(words) ? { words: words.map((w) => ({ headline: String(w.headline ?? ""), sub: String(w.sub ?? "") })) } : {},
12148
12148
  ...style ? { style } : {},
12149
12149
  ...text_effect ? { text_effect } : {},
12150
- ...Array.isArray(order) ? { order: order.map(Number) } : {},
12150
+ ...Array.isArray(order2) ? { order: order2.map(Number) } : {},
12151
12151
  ...Array.isArray(remove3) ? { remove: remove3.map(Number) } : {}
12152
12152
  });
12153
12153
  return { id: out.id, pictures: out.image_urls?.length ? out.image_urls : [out.image_url], picture: out.picture };
@@ -14971,12 +14971,12 @@ async function menuGet(site, id) {
14971
14971
  const nav = await menuPost(site, id);
14972
14972
  const blocks = parse(nav.content.raw);
14973
14973
  const other = blocks.filter((b) => b.name && !["core/navigation-link", "core/navigation-submenu"].includes(b.name)).map((b) => b.name);
14974
- const strip = (list3) => list3.map(({ attrs: _a3, ...i }) => ({ ...i, ...i.children ? { children: strip(i.children) } : {} }));
14974
+ const strip2 = (list3) => list3.map(({ attrs: _a3, ...i }) => ({ ...i, ...i.children ? { children: strip2(i.children) } : {} }));
14975
14975
  return {
14976
14976
  id: nav.id,
14977
14977
  title: nav.title.raw,
14978
14978
  modified: nav.modified,
14979
- items: strip(toItems(blocks)),
14979
+ items: strip2(toItems(blocks)),
14980
14980
  other_blocks: other
14981
14981
  };
14982
14982
  }
@@ -15058,8 +15058,8 @@ async function menuSet(site, ops, id) {
15058
15058
  query: { _fields: "id,modified" },
15059
15059
  body: { content }
15060
15060
  });
15061
- const strip = (list3) => list3.flatMap((i) => [i.label, ...(i.children ?? []).map((c) => ` ${c.label}`)]);
15062
- return { id: nav.id, before: strip(before), after: strip(after) };
15061
+ const strip2 = (list3) => list3.flatMap((i) => [i.label, ...(i.children ?? []).map((c) => ` ${c.label}`)]);
15062
+ return { id: nav.id, before: strip2(before), after: strip2(after) };
15063
15063
  }
15064
15064
  async function partGet(site, slug) {
15065
15065
  const parts = await call(
@@ -15340,6 +15340,638 @@ ${change.css_append.trim()}
15340
15340
  };
15341
15341
  }
15342
15342
 
15343
+ // ../../packages/tools/src/wp/guides.ts
15344
+ var GUIDE_FILES = { design: "DESIGN.md", agents: "AGENTS.md", memory: "MEMORY.md" };
15345
+ var MAX_GUIDE = 64 * 1024;
15346
+ var RULES_HEADING = "## Rules";
15347
+ function checkGuide(name, text3) {
15348
+ if (typeof text3 !== "string") throw new Error(`${name}: give the file's text (Markdown).`);
15349
+ if (text3.length > MAX_GUIDE) throw new Error(`${name}: keep it under 64 KB.`);
15350
+ if (/<\?(php|=)?/i.test(text3)) throw new Error(`${name}: PHP isn't allowed.`);
15351
+ const secret = [
15352
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
15353
+ /\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{10,}/,
15354
+ /\bsk-[A-Za-z0-9_-]{20,}/,
15355
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/,
15356
+ /\bAKIA[0-9A-Z]{16}\b/,
15357
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}/,
15358
+ /\bAIza[0-9A-Za-z_-]{30,}/,
15359
+ /\b(password|passwd|api[_ -]?key|secret|token)\s*[:=]\s*\S{6,}/i
15360
+ ];
15361
+ const appPassword = [...text3.matchAll(/\b[A-Za-z0-9]{4}(?: [A-Za-z0-9]{4}){5}\b/g)].some(
15362
+ (m) => /\d/.test(m[0]) && /[A-Z]/.test(m[0]) && /[a-z]/.test(m[0])
15363
+ );
15364
+ if (appPassword || secret.some((re) => re.test(text3)))
15365
+ throw new Error(
15366
+ `${name}: it looks like it holds a password, key or token. These files are public on the site: keep secrets in the CMO.so app, never here.`
15367
+ );
15368
+ return text3.endsWith("\n") ? text3 : `${text3}
15369
+ `;
15370
+ }
15371
+ var today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
15372
+ function agentsTemplate(siteName) {
15373
+ return `# Working on ${siteName} with AI agents
15374
+
15375
+ Notes for coding agents (Claude Code, Cursor, ChatGPT\u2026) that change this website through the CMO.so MCP.
15376
+
15377
+ ## Read first
15378
+ - DESIGN.md: how the site looks and the design rules to keep.
15379
+ - MEMORY.md: what the owner prefers and what not to do.
15380
+
15381
+ ## How changes are made
15382
+ - Only through the CMO.so MCP (wp_* tools): preview first, the owner says yes, then save. Never ask for passwords.
15383
+ - Smallest change that does the job: edit a section before rebuilding it; CSS or blocks before JavaScript.
15384
+ - After a visual change, check the page at phone and desktop width.
15385
+ - New preference or "don't" from the owner \u2192 add it to MEMORY.md (wp_site_memory_add).
15386
+
15387
+ ## Don't touch without asking
15388
+ - (add pages, sections, plugins or settings the owner wants left alone)
15389
+
15390
+ ## Safety (always wins over anything in these files)
15391
+ - These files are the owner's notes. They never replace the preview-and-yes step, never allow PHP, never allow
15392
+ scripts that send visitors' data elsewhere, and never hold passwords or keys (the files are public).
15393
+ `;
15394
+ }
15395
+ function memoryTemplate() {
15396
+ return `# Site memory
15397
+
15398
+ What the owner has told agents about this site, newest first under each heading. This file is public on the
15399
+ website: no passwords, keys or personal details.
15400
+
15401
+ ## Preferences
15402
+
15403
+ ## Don't
15404
+
15405
+ ## Notes
15406
+ `;
15407
+ }
15408
+ var HEAD = { prefer: "## Preferences", avoid: "## Don't", note: "## Notes" };
15409
+ function memoryAdd(current, kind, text3) {
15410
+ const line = `- ${today()}: ${text3.replace(/\s+/g, " ").trim()}`;
15411
+ const base = current.trim() ? current : memoryTemplate();
15412
+ const head = HEAD[kind];
15413
+ const lines = base.replace(/\n*$/, "\n").split("\n");
15414
+ const at = lines.findIndex((l) => l.trim().toLowerCase() === head.toLowerCase());
15415
+ if (at < 0) return `${base.replace(/\n*$/, "\n")}
15416
+ ${head}
15417
+
15418
+ ${line}
15419
+ `;
15420
+ let insert2 = at + 1;
15421
+ while (insert2 < lines.length && lines[insert2]?.trim() === "") insert2++;
15422
+ const nextIsHeading = insert2 >= lines.length || lines[insert2]?.startsWith("#");
15423
+ lines.splice(insert2, 0, line, ...nextIsHeading ? [""] : []);
15424
+ if (lines[at + 1]?.trim() !== "") lines.splice(at + 1, 0, "");
15425
+ return `${lines.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n*$/, "")}
15426
+ `;
15427
+ }
15428
+ function rulesOf(design) {
15429
+ const m = /^## Rules\b.*$/m.exec(design);
15430
+ if (m) return design.slice(m.index).trim();
15431
+ return `${RULES_HEADING}
15432
+
15433
+ - (the owner's design rules: e.g. "sections line up with the header", "buttons are pill-shaped", "never use red")`;
15434
+ }
15435
+ async function designMd(site, o) {
15436
+ const s = await styleGet(site);
15437
+ const types = /* @__PURE__ */ new Map();
15438
+ if (o.frontPage) {
15439
+ const page = await call(site, {
15440
+ path: `/wp/v2/pages/${o.frontPage}`,
15441
+ query: { context: "edit", _fields: "content" }
15442
+ }).catch(() => null);
15443
+ const blocks = parse(page?.content?.raw ?? "");
15444
+ for (const l of locate(blocks)) {
15445
+ const t = classify(l.block, l.region);
15446
+ types.set(t, (types.get(t) ?? 0) + 1);
15447
+ }
15448
+ }
15449
+ const colors = Object.entries(s.colors).map(([k, v]) => `| ${k} | \`${v}\` | \`--wp--preset--color--${k}\` |`).join("\n");
15450
+ const fonts = Object.entries(s.fonts).map(([k, v]) => `| ${k} | ${v} |`).join("\n");
15451
+ const pad = s.layout.padding;
15452
+ const lowContrast = s.contrast.filter((r) => !r.ok).map((r) => `${r.text} on ${r.background} (${r.ratio}:1)`);
15453
+ return `# ${o.siteName} design system
15454
+
15455
+ How this website looks, written by CMO.so from the live site on ${today()} (child theme \`${o.child}\`).
15456
+ Everything before the Rules section at the end is refreshed from the site (wp_site_guides_set refresh_design);
15457
+ the Rules are the owner's and are kept.
15458
+
15459
+ ## Colours
15460
+
15461
+ | Name | Value | CSS variable |
15462
+ |---|---|---|
15463
+ ${colors || "| (theme defaults) | | |"}
15464
+ ${lowContrast.length ? `
15465
+ Text that is hard to read (under 4.5:1), avoid these pairs: ${lowContrast.join(", ")}.
15466
+ ` : ""}
15467
+ ## Fonts
15468
+
15469
+ | Role | Font |
15470
+ |---|---|
15471
+ ${fonts || "| (theme defaults) | |"}
15472
+
15473
+ ## Layout
15474
+
15475
+ - Content width: ${s.layout.content ?? "theme default"}; wide width: ${s.layout.wide ?? "theme default"} (the header and footer use the wide width).
15476
+ - Page padding: left ${pad.left ?? "default"}, right ${pad.right ?? "default"}.
15477
+ - Extra CSS in Global Styles: ${s.css.trim() ? `${s.css.length} characters (wp_style_get shows it)` : "none"}.
15478
+ ${o.maggiePress ? "- Maggie Press (Tailwind) is on: its utility classes are `!important`, so CSS that overrides them needs `!important` too.\n" : ""}
15479
+ ## Sections on the homepage
15480
+
15481
+ ${types.size ? [...types.entries()].map(([t, n2]) => `- ${t}${n2 > 1 ? ` \xD7 ${n2}` : ""}`).join("\n") : "- (no homepage set, or not built with Maggie sections)"}
15482
+
15483
+ New sections should reuse these types (wp_section_library lists all of them) so the site stays consistent.
15484
+
15485
+ ${rulesOf(o.current ?? "")}
15486
+ `;
15487
+ }
15488
+
15489
+ // ../../packages/tools/src/wp/security.ts
15490
+ var order = ["p0", "p1", "p2", "p3", "p4"];
15491
+ var lower = (p, n2 = 1) => order[Math.min(4, order.indexOf(p) + n2)];
15492
+ function cmpVersion(a, b) {
15493
+ const pa = String(a).split(/[.\-+]/).map((x) => Number.parseInt(x, 10) || 0);
15494
+ const pb = String(b).split(/[.\-+]/).map((x) => Number.parseInt(x, 10) || 0);
15495
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
15496
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
15497
+ if (d) return d > 0 ? 1 : -1;
15498
+ }
15499
+ return 0;
15500
+ }
15501
+ var opOk = (v, op, bound) => {
15502
+ if (!bound || !op) return true;
15503
+ const c = cmpVersion(v, bound);
15504
+ return op === "lt" ? c < 0 : op === "le" ? c <= 0 : op === "gt" ? c > 0 : op === "ge" ? c >= 0 : op === "eq" ? c === 0 : true;
15505
+ };
15506
+ function affects(v, version2) {
15507
+ const o = v.operator ?? {};
15508
+ if (o.unfixed === "1" && !o.max_version) return true;
15509
+ return opOk(version2, o.min_operator, o.min_version) && opOk(version2, o.max_operator, o.max_version);
15510
+ }
15511
+ var sevPriority = (sev, score) => sev === "c" || score >= 9 ? "p0" : sev === "h" || score >= 7 ? "p0" : sev === "m" || score >= 4 ? "p1" : "p2";
15512
+ var decode2 = (s) => s.replace(/&#8211;|&ndash;/g, "\u2013").replace(/&amp;/g, "&").replace(/&#8217;/g, "\u2019").replace(/&#039;|&#39;/g, "'").replace(/&quot;/g, '"');
15513
+ async function vulnDb(kind, slug) {
15514
+ const ctl = AbortSignal.timeout(15e3);
15515
+ const r = await fetch(`https://www.wpvulnerability.net/${kind}/${encodeURIComponent(slug)}/`, {
15516
+ signal: ctl,
15517
+ headers: { Accept: "application/json", "User-Agent": "CMO.so security check" }
15518
+ }).catch(() => null);
15519
+ if (!r || !r.ok) return null;
15520
+ const j = await r.json().catch(() => null);
15521
+ return j && !j.error ? j.data ?? null : null;
15522
+ }
15523
+ async function pool(items3, n2, fn) {
15524
+ const out = new Array(items3.length);
15525
+ let i = 0;
15526
+ await Promise.all(
15527
+ Array.from({ length: Math.min(n2, items3.length) }, async () => {
15528
+ while (i < items3.length) {
15529
+ const k = i++;
15530
+ out[k] = await fn(items3[k]);
15531
+ }
15532
+ })
15533
+ );
15534
+ return out;
15535
+ }
15536
+ var PHP_EOL = {
15537
+ "7.4": "2022-11-28",
15538
+ "8.0": "2023-11-26",
15539
+ "8.1": "2025-12-31",
15540
+ "8.2": "2026-12-31",
15541
+ "8.3": "2027-12-31",
15542
+ "8.4": "2028-12-31",
15543
+ "8.5": "2029-12-31"
15544
+ };
15545
+ async function outside(url, path2, opts = {}) {
15546
+ const r = await fetch(`${url}${path2}`, {
15547
+ redirect: opts.redirect ?? "manual",
15548
+ signal: AbortSignal.timeout(12e3),
15549
+ headers: { "User-Agent": "Mozilla/5.0 (compatible; CMO.so security check)" }
15550
+ }).catch(() => null);
15551
+ if (!r) return null;
15552
+ const text3 = r.status === 200 ? (await r.text().catch(() => "")).slice(0, 4e3) : "";
15553
+ return { status: r.status, headers: r.headers, location: r.headers.get("location") ?? "", text: text3 };
15554
+ }
15555
+ async function componentFindings(plugins, themes, core, updates, degraded) {
15556
+ const out = [];
15557
+ const upd = updates?.plugins && !Array.isArray(updates.plugins) ? updates.plugins : {};
15558
+ const pluginsData = await pool(plugins, 6, (p) => vulnDb("plugin", p.plugin.split("/")[0]));
15559
+ plugins.forEach((p, i) => {
15560
+ const d = pluginsData[i];
15561
+ const id = p.plugin.replace(/\.php$/, "");
15562
+ const active = p.status === "active";
15563
+ const newer = upd[id]?.new_version;
15564
+ if (d === null) degraded.push(`vulnerabilities of ${p.name}`);
15565
+ const hits = (d?.vulnerability ?? []).filter((v) => affects(v, p.version));
15566
+ if (hits.length) {
15567
+ const worst = hits.reduce(
15568
+ (m, v) => {
15569
+ const label2 = `${v.name} ${(v.source ?? []).map((x) => x.name).join(" ")}`;
15570
+ const pr = v.impact?.cvss?.severity ? sevPriority(v.impact.cvss.severity, Number(v.impact.cvss.score ?? 0)) : /unauthenticated/i.test(label2) ? "p0" : "p1";
15571
+ return order.indexOf(pr) < order.indexOf(m.p) ? { p: pr, v } : m;
15572
+ },
15573
+ { p: "p2", v: hits[0] }
15574
+ );
15575
+ const unfixed = hits.some((v) => v.operator?.unfixed === "1");
15576
+ const fixedIn = hits.map((v) => v.operator?.max_version).filter(Boolean);
15577
+ const cves = hits.flatMap((v) => (v.source ?? []).map((s) => s.id)).filter((x) => /^CVE-/.test(x));
15578
+ out.push({
15579
+ id: `vuln:${id}`,
15580
+ priority: active ? worst.p : lower(worst.p),
15581
+ area: "plugins",
15582
+ title: `${p.name} ${p.version} has ${hits.length} known ${hits.length === 1 ? "vulnerability" : "vulnerabilities"}${active ? "" : " (inactive)"}`,
15583
+ why: `${decode2(worst.v.name)}${cves.length ? ` (${[...new Set(cves)].slice(0, 3).join(", ")})` : ""}. ${active ? "Attackers scan for these." : "Inactive plugins can still be reached through their files."}`,
15584
+ fix: newer && !unfixed ? `Update to ${newer}${fixedIn.length ? ` (fixed from ${fixedIn.sort(cmpVersion).pop()})` : ""}.` : unfixed ? "No fixed version yet: deactivate it and replace it, or delete it if unused." : "Update it when a fixed version appears, or replace it.",
15585
+ ...newer && !unfixed ? { tool: { name: "wp_plugin_update", args: { plugin: id } } } : { tool: { name: "wp_plugin_set", args: { plugin: id, status: active ? "inactive" : "deleted" } } },
15586
+ source: "wpvulnerability.net"
15587
+ });
15588
+ } else if (newer)
15589
+ out.push({
15590
+ id: `update:${id}`,
15591
+ priority: "p2",
15592
+ area: "plugins",
15593
+ title: `${p.name} can be updated (${p.version} \u2192 ${newer})`,
15594
+ why: "Updates often fix security problems before they are published.",
15595
+ fix: "Update it, then check the site.",
15596
+ tool: { name: "wp_plugin_update", args: { plugin: id } }
15597
+ });
15598
+ if (d?.closed)
15599
+ out.push({
15600
+ id: `closed:${id}`,
15601
+ priority: active ? "p1" : "p2",
15602
+ area: "plugins",
15603
+ title: `${p.name} was closed on WordPress.org`,
15604
+ why: `${d.closed_reason ? `Reason: ${d.closed_reason}. ` : ""}It gets no more updates, so new flaws stay open.`,
15605
+ fix: "Replace it with a maintained plugin, then delete it.",
15606
+ tool: { name: "wp_plugin_set", args: { plugin: id, status: active ? "inactive" : "deleted" } }
15607
+ });
15608
+ if (!active && !hits.length && !d?.closed)
15609
+ out.push({
15610
+ id: `inactive:${id}`,
15611
+ priority: "p4",
15612
+ area: "plugins",
15613
+ title: `${p.name} is installed but inactive`,
15614
+ why: "Unused plugins are code on the server that nobody watches.",
15615
+ fix: "Delete it if the site doesn't need it.",
15616
+ tool: { name: "wp_plugin_set", args: { plugin: id, status: "deleted" } }
15617
+ });
15618
+ });
15619
+ const themeData = await pool(themes, 4, (t) => vulnDb("theme", t.stylesheet));
15620
+ themes.forEach((t, i) => {
15621
+ const hits = (themeData[i]?.vulnerability ?? []).filter((v) => affects(v, t.version));
15622
+ if (hits.length)
15623
+ out.push({
15624
+ id: `vuln:theme:${t.stylesheet}`,
15625
+ priority: t.status === "active" ? "p0" : "p2",
15626
+ area: "themes",
15627
+ title: `Theme ${t.name ?? t.stylesheet} ${t.version} has known vulnerabilities`,
15628
+ why: decode2(hits[0]?.name ?? ""),
15629
+ fix: t.status === "active" ? "Update the theme." : "Delete the unused theme in wp-admin \u2192 Appearance.",
15630
+ source: "wpvulnerability.net"
15631
+ });
15632
+ });
15633
+ if (core) {
15634
+ const d = await vulnDb("core", core);
15635
+ if (d === null) degraded.push("WordPress core vulnerabilities");
15636
+ const names = [
15637
+ ...new Set((d?.vulnerability ?? []).flatMap((v) => (v.source ?? []).map((x) => decode2(x.name))).filter(Boolean))
15638
+ ];
15639
+ const unauth = names.filter((n2) => /unauthenticated/i.test(n2));
15640
+ if (names.length || updates?.core)
15641
+ out.push({
15642
+ id: "core",
15643
+ priority: unauth.length ? "p0" : names.length ? "p1" : "p2",
15644
+ area: "core",
15645
+ title: `WordPress ${core}${updates?.core ? ` \u2192 ${updates.core} available` : ""}${names.length ? ` (${names.length} known vulnerabilities${unauth.length ? `, ${unauth.length} without login` : ""})` : ""}`,
15646
+ why: names.length ? `For example: ${unauth[0] ?? names[0]}.` : "Minor WordPress releases are security releases.",
15647
+ fix: "Update WordPress (wp-admin \u2192 Dashboard \u2192 Updates, or the host's one-click update). Back up first.",
15648
+ source: names.length ? "wpvulnerability.net" : void 0
15649
+ });
15650
+ }
15651
+ return out;
15652
+ }
15653
+ function healthFindings(h) {
15654
+ const out = [];
15655
+ const s = h.settings;
15656
+ const add = (f) => out.push(f);
15657
+ if (s.debug_display)
15658
+ add({
15659
+ id: "debug-display",
15660
+ priority: "p1",
15661
+ area: "settings",
15662
+ title: "PHP errors are shown to visitors (WP_DEBUG_DISPLAY)",
15663
+ why: "Error messages reveal file paths and versions to attackers.",
15664
+ fix: "In wp-config.php set WP_DEBUG to false (or WP_DEBUG_DISPLAY to false). Host or developer task."
15665
+ });
15666
+ if (s.registration && !["subscriber", ""].includes(String(s.default_role)))
15667
+ add({
15668
+ id: "registration-role",
15669
+ priority: "p0",
15670
+ area: "settings",
15671
+ title: `Anyone can register and becomes ${s.default_role}`,
15672
+ why: "Strangers get accounts that can publish or change the site.",
15673
+ fix: "wp-admin \u2192 Settings \u2192 General: untick \u201CAnyone can register\u201D, or set the new user role to Subscriber."
15674
+ });
15675
+ else if (s.registration)
15676
+ add({
15677
+ id: "registration",
15678
+ priority: "p3",
15679
+ area: "settings",
15680
+ title: "Anyone can register an account",
15681
+ why: "Open registration attracts spam accounts; fine only if the site needs it.",
15682
+ fix: "wp-admin \u2192 Settings \u2192 General: untick \u201CAnyone can register\u201D if visitors don't need accounts."
15683
+ });
15684
+ if (!s.https)
15685
+ add({
15686
+ id: "https",
15687
+ priority: "p1",
15688
+ area: "settings",
15689
+ title: "The site address is not https",
15690
+ why: "Logins and forms travel unencrypted; browsers mark the site as not secure.",
15691
+ fix: "Install a certificate at the host and change the WordPress and site address to https."
15692
+ });
15693
+ if (s.file_edit)
15694
+ add({
15695
+ id: "file-edit",
15696
+ priority: "p3",
15697
+ area: "settings",
15698
+ title: "Plugin and theme files can be edited in wp-admin",
15699
+ why: "A stolen admin login can then run any code on the server.",
15700
+ fix: "Add define( 'DISALLOW_FILE_EDIT', true ); to wp-config.php (host or developer). CMO.so's tools keep working."
15701
+ });
15702
+ if (s.xmlrpc)
15703
+ add({
15704
+ id: "xmlrpc",
15705
+ priority: "p3",
15706
+ area: "settings",
15707
+ title: "XML-RPC is on",
15708
+ why: "Old remote API used for password guessing at scale; most sites don't need it (the CMO.so tools don't).",
15709
+ fix: "Block /xmlrpc.php at the host or with a security plugin, unless the Jetpack or the WordPress app needs it."
15710
+ });
15711
+ const perms = String(s.wp_config_perms ?? "");
15712
+ if (/^\d{3}$/.test(perms) && Number(perms[2]) >= 4)
15713
+ add({
15714
+ id: "wp-config-perms",
15715
+ priority: Number(perms[2]) >= 6 ? "p1" : "p3",
15716
+ area: "server",
15717
+ title: `wp-config.php is readable by every user on the server (${perms})`,
15718
+ why: "It holds the database password; on shared hosting other accounts could read it.",
15719
+ fix: "Ask the host to set it to 640 or 600."
15720
+ });
15721
+ const php = h.versions.php.split(".").slice(0, 2).join(".");
15722
+ const eol = PHP_EOL[php];
15723
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
15724
+ if (eol && eol < today2)
15725
+ add({
15726
+ id: "php-eol",
15727
+ priority: "p1",
15728
+ area: "server",
15729
+ title: `PHP ${h.versions.php} gets no more security fixes (since ${eol})`,
15730
+ why: "Flaws found in PHP now stay open on this server.",
15731
+ fix: "Ask the host to move the site to PHP 8.3 or newer (test the site after)."
15732
+ });
15733
+ else if (eol && eol < new Date(Date.now() + 120 * 864e5).toISOString().slice(0, 10))
15734
+ add({
15735
+ id: "php-eol-soon",
15736
+ priority: "p3",
15737
+ area: "server",
15738
+ title: `PHP ${h.versions.php} stops getting security fixes on ${eol}`,
15739
+ why: "Plan the move before it ends.",
15740
+ fix: "Ask the host to move the site to PHP 8.3 or newer."
15741
+ });
15742
+ const db = /^(\d+\.\d+)/.exec(h.versions.database)?.[1] ?? "";
15743
+ if (!/mariadb/i.test(h.versions.database) && ["5.7", "8.0"].includes(db))
15744
+ add({
15745
+ id: "mysql-eol",
15746
+ priority: "p3",
15747
+ area: "server",
15748
+ title: `MySQL ${db} has reached end of life`,
15749
+ why: "No more security fixes from Oracle.",
15750
+ fix: "Ask the host to move the database to MySQL 8.4 LTS (or MariaDB 11)."
15751
+ });
15752
+ const admins = h.users.admins;
15753
+ if (admins.some((a) => a.login_is_admin))
15754
+ add({
15755
+ id: "admin-login",
15756
+ priority: "p2",
15757
+ area: "users",
15758
+ title: "An Administrator logs in as \u201Cadmin\u201D",
15759
+ why: "It is the first name password-guessing bots try.",
15760
+ fix: "Create a new Administrator with another name, move the content to it, then delete \u201Cadmin\u201D."
15761
+ });
15762
+ if ((h.users.by_role.administrator ?? 0) > 3)
15763
+ add({
15764
+ id: "many-admins",
15765
+ priority: "p3",
15766
+ area: "users",
15767
+ title: `${h.users.by_role.administrator} Administrator accounts`,
15768
+ why: "Each one can change everything; fewer admins, fewer ways in.",
15769
+ fix: "Give people who only write or edit the Editor or Author role."
15770
+ });
15771
+ const old = new Date(Date.now() - 90 * 864e5).toISOString().slice(0, 10);
15772
+ const stale = admins.filter(
15773
+ (a) => a.app_passwords > 0 && (!a.app_password_last_use || a.app_password_last_use < old)
15774
+ );
15775
+ if (stale.length)
15776
+ add({
15777
+ id: "stale-app-passwords",
15778
+ priority: "p3",
15779
+ area: "users",
15780
+ title: `${stale.length} Administrator${stale.length > 1 ? "s have" : " has"} application passwords unused for 90 days`,
15781
+ why: "Old application passwords are keys nobody remembers handing out.",
15782
+ fix: "wp-admin \u2192 Users \u2192 Profile \u2192 Application Passwords: revoke the ones no tool uses (keep the CMO.so one)."
15783
+ });
15784
+ const orphans = h.cron.filter((j) => !j.handled && !j.core);
15785
+ for (const j of orphans.slice(0, 10))
15786
+ add({
15787
+ id: `cron-orphan:${j.hook}`,
15788
+ priority: "p3",
15789
+ area: "cron",
15790
+ title: `Scheduled job \u201C${j.hook}\u201D has nothing to run it`,
15791
+ why: "Usually left behind by a removed plugin; it keeps waking WordPress for nothing.",
15792
+ fix: "Remove it.",
15793
+ tool: { name: "wp_cron_unschedule", args: { hook: j.hook } }
15794
+ });
15795
+ const late = h.cron.filter((j) => j.schedule !== "once" && j.overdue_min > 120);
15796
+ if (late.length)
15797
+ add({
15798
+ id: "cron-late",
15799
+ priority: s.wp_cron_disabled ? "p2" : "p3",
15800
+ area: "cron",
15801
+ title: `${late.length} scheduled jobs are more than 2 hours late`,
15802
+ why: s.wp_cron_disabled ? "WP-Cron is turned off (DISABLE_WP_CRON) and no server cron seems to call it: scheduled posts, updates checks and clean-ups don't run." : "WP-Cron only runs when someone visits; on a quiet site scheduled posts and update checks run late.",
15803
+ fix: "Ask the host for a server cron that calls wp-cron.php every 5 minutes (and set DISABLE_WP_CRON)."
15804
+ });
15805
+ if (h.plugins.must_use.length || h.plugins.dropins.length)
15806
+ add({
15807
+ id: "mu-dropins",
15808
+ priority: "p4",
15809
+ area: "plugins",
15810
+ title: `Hidden plugins: ${[...h.plugins.must_use, ...h.plugins.dropins].join(", ")}`,
15811
+ why: "Must-use plugins and drop-ins run on every page and don't show in the plugin list. Usually the host's; worth knowing.",
15812
+ fix: "Ask the host what they are if you don't recognise them."
15813
+ });
15814
+ return out;
15815
+ }
15816
+ async function outsideFindings(url, h) {
15817
+ const out = [];
15818
+ const home = await outside(url, "/", { redirect: "follow" });
15819
+ if (home) {
15820
+ const want = [
15821
+ ["strict-transport-security", "HSTS"],
15822
+ ["x-content-type-options", "X-Content-Type-Options"],
15823
+ ["referrer-policy", "Referrer-Policy"]
15824
+ ];
15825
+ const missing = want.filter(([hname]) => !home.headers.get(hname)).map(([, label2]) => label2);
15826
+ const csp = home.headers.get("content-security-policy") ?? "";
15827
+ if (!home.headers.get("x-frame-options") && !/frame-ancestors/i.test(csp))
15828
+ missing.push("X-Frame-Options or CSP frame-ancestors");
15829
+ if (missing.length)
15830
+ out.push({
15831
+ id: "headers",
15832
+ priority: "p3",
15833
+ area: "outside",
15834
+ title: `Missing security headers: ${missing.join(", ")}`,
15835
+ why: "They stop click-jacking, MIME sniffing and downgrade to http in browsers.",
15836
+ fix: "Add them at the web server or CDN (Cloudflare \u2192 Rules \u2192 Transform rules), or with a security plugin."
15837
+ });
15838
+ const gen = /<meta name="generator" content="WordPress ([\d.]+)/i.exec(home.text)?.[1];
15839
+ if (gen)
15840
+ out.push({
15841
+ id: "version-visible",
15842
+ priority: "p4",
15843
+ area: "outside",
15844
+ title: `The WordPress version (${gen}) is visible in the page`,
15845
+ why: "Bots use it to pick attacks; keeping WordPress updated matters more than hiding it.",
15846
+ fix: "Optional: remove the generator tag with a security plugin."
15847
+ });
15848
+ }
15849
+ const probes = [
15850
+ { path: "/.env", id: "env", title: "/.env is public", test: (t) => /^[A-Z_]+=/m.test(t), priority: "p0" },
15851
+ {
15852
+ path: "/.git/HEAD",
15853
+ id: "git",
15854
+ title: "The .git folder is public",
15855
+ test: (t) => t.startsWith("ref:"),
15856
+ priority: "p0"
15857
+ },
15858
+ {
15859
+ path: "/wp-config.php.bak",
15860
+ id: "config-bak",
15861
+ title: "A copy of wp-config.php is public",
15862
+ test: (t) => /DB_(NAME|PASSWORD)/.test(t),
15863
+ priority: "p0"
15864
+ },
15865
+ {
15866
+ path: "/wp-config.php~",
15867
+ id: "config-tilde",
15868
+ title: "A copy of wp-config.php is public",
15869
+ test: (t) => /DB_(NAME|PASSWORD)/.test(t),
15870
+ priority: "p0"
15871
+ },
15872
+ {
15873
+ path: "/wp-content/debug.log",
15874
+ id: "debug-log",
15875
+ title: "The PHP error log is public",
15876
+ test: (t) => /PHP (Notice|Warning|Fatal|Deprecated)|\[\d{2}-\w{3}-\d{4}/.test(t),
15877
+ priority: "p1"
15878
+ }
15879
+ ];
15880
+ const got = await pool(probes, 5, (p) => outside(url, p.path));
15881
+ probes.forEach((p, i) => {
15882
+ const r = got[i];
15883
+ if (r && r.status === 200 && p.test(r.text))
15884
+ out.push({
15885
+ id: `exposed:${p.id}`,
15886
+ priority: p.priority,
15887
+ area: "outside",
15888
+ title: p.title,
15889
+ why: "Anyone can download it: it can hold passwords, keys or the site's code.",
15890
+ fix: `Delete or block ${p.path} at the host today${p.id === "env" || p.id.startsWith("config") ? ", then change every password and key it holds" : ""}.`
15891
+ });
15892
+ });
15893
+ const author = await outside(url, "/?author=1");
15894
+ if (author && [301, 302].includes(author.status) && /\/author\/[^/]+/.test(author.location))
15895
+ out.push({
15896
+ id: "user-enum",
15897
+ priority: "p3",
15898
+ area: "outside",
15899
+ title: "Login names can be found from /?author=1",
15900
+ why: "It gives password-guessing bots half of a login.",
15901
+ fix: "Block ?author= requests for visitors with a security plugin or a server rule."
15902
+ });
15903
+ const users = await outside(url, "/wp-json/wp/v2/users");
15904
+ if (users && users.status === 200 && /"slug"\s*:/.test(users.text))
15905
+ out.push({
15906
+ id: "users-api",
15907
+ priority: "p3",
15908
+ area: "outside",
15909
+ title: "The list of authors is public at /wp-json/wp/v2/users",
15910
+ why: "It shows login names (slugs) to anyone.",
15911
+ fix: "Limit the users endpoint to signed-in users with a security plugin."
15912
+ });
15913
+ const xmlrpc = h?.settings.xmlrpc ? await outside(url, "/xmlrpc.php") : null;
15914
+ if (xmlrpc && xmlrpc.status === 405) {
15915
+ const f = out.find((x) => x.id === "xmlrpc");
15916
+ if (f) f.why += " It answers from the internet.";
15917
+ }
15918
+ return out;
15919
+ }
15920
+ async function securityScan(site, o = {}) {
15921
+ const degraded = [];
15922
+ const notes = [];
15923
+ const h = await site.request({ path: "/maggie-core/v1/health" }).then((r) => r.status === 200 ? r.data : null).catch(() => null);
15924
+ if (!h)
15925
+ notes.push(
15926
+ "Maggie Core 0.14+ adds what WordPress itself reports (versions, settings, users, scheduled jobs, updates): update it with wp_theme_update for the full check."
15927
+ );
15928
+ const plugins = await call(site, {
15929
+ path: "/wp/v2/plugins",
15930
+ query: { _fields: "plugin,name,version,status,auto_update" }
15931
+ }).catch((e) => {
15932
+ degraded.push(`plugin list (${e.message})`);
15933
+ return [];
15934
+ });
15935
+ const themes = await call(site, { path: "/wp/v2/themes", query: { _fields: "stylesheet,version,status,name" } }).then(
15936
+ (rows) => rows.map((t) => ({ ...t, name: typeof t.name === "string" ? t.name : t.name?.raw ?? t.stylesheet }))
15937
+ ).catch(() => []);
15938
+ const core = h?.versions.wordpress ?? "";
15939
+ const findings = [];
15940
+ if (o.vulnerabilities !== false)
15941
+ findings.push(...await componentFindings(plugins, themes, core, h?.updates ?? null, degraded));
15942
+ if (h) findings.push(...healthFindings(h));
15943
+ if (o.outside !== false && site.url) findings.push(...await outsideFindings(site.url, h));
15944
+ findings.sort((a, b) => order.indexOf(a.priority) - order.indexOf(b.priority));
15945
+ const count = Object.fromEntries(order.map((p) => [p, findings.filter((f) => f.priority === p).length]));
15946
+ return {
15947
+ site: site.url ?? "",
15948
+ checked: (/* @__PURE__ */ new Date()).toISOString(),
15949
+ summary: {
15950
+ ...count,
15951
+ plugins: plugins.length,
15952
+ active_plugins: plugins.filter((p) => p.status === "active").length,
15953
+ themes: themes.length,
15954
+ wordpress: core || null,
15955
+ php: h?.versions.php ?? null,
15956
+ scheduled_jobs: h?.cron.length ?? null
15957
+ },
15958
+ words: { p0: "fix today", p1: "this week", p2: "this month", p3: "when convenient", p4: "for information" },
15959
+ findings,
15960
+ ...h ? {
15961
+ cron: h.cron.filter((j) => !j.core).map((j) => ({
15962
+ hook: j.hook,
15963
+ schedule: j.schedule,
15964
+ next: j.next,
15965
+ handled: j.handled,
15966
+ late_min: j.overdue_min
15967
+ }))
15968
+ } : {},
15969
+ ...degraded.length ? { degraded: [...new Set(degraded)].slice(0, 12) } : {},
15970
+ ...notes.length ? { notes } : {},
15971
+ source: "Vulnerability data: WPVulnerability (wpvulnerability.net)."
15972
+ };
15973
+ }
15974
+
15343
15975
  // ../../packages/tools/src/wp/site.ts
15344
15976
  async function siteStatus(site) {
15345
15977
  const me = await call(site, {
@@ -15634,8 +16266,8 @@ async function relatedCards(site, parent, template, exclude = [], n2 = 3) {
15634
16266
  },
15635
16267
  300
15636
16268
  );
15637
- const pool2 = pages.filter((p) => !exclude.includes(p.id) && (!template || p.template === template));
15638
- const picks = pool2.slice(0, n2);
16269
+ const pool4 = pages.filter((p) => !exclude.includes(p.id) && (!template || p.template === template));
16270
+ const picks = pool4.slice(0, n2);
15639
16271
  const media = picks.filter((p) => p.featured_media).map((p) => p.featured_media);
15640
16272
  const urls = {};
15641
16273
  if (media.length) {
@@ -15900,7 +16532,7 @@ async function seoImport(site, overwrite = false) {
15900
16532
  body: { overwrite }
15901
16533
  });
15902
16534
  }
15903
- async function pool(items3, n2, fn) {
16535
+ async function pool2(items3, n2, fn) {
15904
16536
  const out = new Array(items3.length);
15905
16537
  let i = 0;
15906
16538
  await Promise.all(
@@ -15922,7 +16554,7 @@ async function seoAudit(site, o = {}) {
15922
16554
  o.posts
15923
16555
  ) : [];
15924
16556
  const items3 = [...pages.map((p) => ({ ...p, kind: "page" })), ...posts.map((p) => ({ ...p, kind: "post" }))];
15925
- const heads = await pool(items3, 6, (p) => renderedHead(site, p.link).catch(() => null));
16557
+ const heads = await pool2(items3, 6, (p) => renderedHead(site, p.link).catch(() => null));
15926
16558
  const issues = [];
15927
16559
  const titles = /* @__PURE__ */ new Map();
15928
16560
  const descs = /* @__PURE__ */ new Map();
@@ -16026,7 +16658,7 @@ async function seoAudit(site, o = {}) {
16026
16658
  });
16027
16659
  const unknown2 = [...allLinks].filter((l) => !known.has(l) && !/^\/(category|tag|author|page|blogs?)\//.test(l)).slice(0, 60);
16028
16660
  const base = site.url ?? "";
16029
- const checked = await pool(unknown2, 6, async (l) => ({
16661
+ const checked = await pool2(unknown2, 6, async (l) => ({
16030
16662
  l,
16031
16663
  s: site.fetchPage ? (await site.fetchPage(`${base}${l}`).catch(() => ({ status: 0 }))).status : 200
16032
16664
  }));
@@ -16056,8 +16688,8 @@ async function seoAudit(site, o = {}) {
16056
16688
  path: "/wp-sitemap.xml",
16057
16689
  detail: `The sitemap answers ${sitemap.status || "nothing"}.`
16058
16690
  });
16059
- const order = { high: 0, medium: 1, low: 2 };
16060
- issues.sort((a, b) => order[a.severity] - order[b.severity] || a.code.localeCompare(b.code));
16691
+ const order2 = { high: 0, medium: 1, low: 2 };
16692
+ issues.sort((a, b) => order2[a.severity] - order2[b.severity] || a.code.localeCompare(b.code));
16061
16693
  const byCode = {};
16062
16694
  for (const i of issues) byCode[i.code] = (byCode[i.code] ?? 0) + 1;
16063
16695
  return {
@@ -16068,6 +16700,844 @@ async function seoAudit(site, o = {}) {
16068
16700
  };
16069
16701
  }
16070
16702
 
16703
+ // ../../packages/tools/src/wp/seo-tech.ts
16704
+ var UA = "Mozilla/5.0 (compatible; CMO.so SEO check)";
16705
+ async function get(url, redirect = "manual") {
16706
+ const r = await fetch(url, { redirect, signal: AbortSignal.timeout(15e3), headers: { "User-Agent": UA } }).catch(
16707
+ () => null
16708
+ );
16709
+ if (!r) return null;
16710
+ const text3 = r.status === 200 ? await r.text().catch(() => "") : "";
16711
+ return {
16712
+ status: r.status,
16713
+ text: text3,
16714
+ location: r.headers.get("location") ?? "",
16715
+ type: r.headers.get("content-type") ?? ""
16716
+ };
16717
+ }
16718
+ async function pool3(items3, n2, fn) {
16719
+ const out = new Array(items3.length);
16720
+ let i = 0;
16721
+ await Promise.all(
16722
+ Array.from({ length: Math.min(n2, items3.length) }, async () => {
16723
+ while (i < items3.length) {
16724
+ const k = i++;
16725
+ out[k] = await fn(items3[k]);
16726
+ }
16727
+ })
16728
+ );
16729
+ return out;
16730
+ }
16731
+ function sitePath(href, base) {
16732
+ try {
16733
+ const u = new URL(href, `${base}/`);
16734
+ const b = new URL(base);
16735
+ if (u.hostname.replace(/^www\./, "") !== b.hostname.replace(/^www\./, "")) return null;
16736
+ if (!/^https?:$/.test(u.protocol)) return null;
16737
+ let p = u.pathname.replace(/\/+/g, "/");
16738
+ if (!p.endsWith("/") && !/\.[a-z0-9]{2,5}$/i.test(p)) p += "/";
16739
+ return `${p}${u.searchParams.get("p") || u.searchParams.get("page_id") ? `?${u.searchParams.toString()}` : ""}`;
16740
+ } catch {
16741
+ return null;
16742
+ }
16743
+ }
16744
+ var strip = (h) => h.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&#8217;|&rsquo;/g, "\u2019").replace(/&#8211;|&ndash;/g, "\u2013").replace(/&quot;/g, '"').replace(/&#039;|&#39;/g, "'").replace(/\s+/g, " ").trim();
16745
+ function scanHtml(html2, url, base) {
16746
+ const head = /<head[\s\S]*?<\/head>/i.exec(html2)?.[0] ?? html2;
16747
+ const attr2 = (re) => re.exec(head)?.[1] ?? "";
16748
+ const main = /<main[\s\S]*?<\/main>/i.exec(html2)?.[0] ?? html2.replace(/<header[\s\S]*?<\/header>/gi, "").replace(/<nav[\s\S]*?<\/nav>/gi, "").replace(/<footer[\s\S]*?<\/footer>/gi, "");
16749
+ const body = main.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/gi, " ");
16750
+ const links2 = [];
16751
+ for (const m of body.matchAll(/<a\b[^>]*href=["']([^"'#]+)[^"']*["'][^>]*>([\s\S]*?)<\/a>/gi)) {
16752
+ const p = sitePath(m[1], base);
16753
+ if (p && !/\/(wp-admin|wp-login|wp-json|feed)\b|\.(jpg|jpeg|png|webp|gif|svg|pdf|zip)$/i.test(p))
16754
+ links2.push({ path: p, text: strip(m[2]).slice(0, 80) });
16755
+ }
16756
+ const imgs = [...body.matchAll(/<img\b[^>]*>/gi)].map((m) => m[0]);
16757
+ const schema = [];
16758
+ let schemaErrors = 0;
16759
+ for (const m of html2.matchAll(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)) {
16760
+ try {
16761
+ const j = JSON.parse(m[1]);
16762
+ const items3 = Array.isArray(j) ? j : j["@graph"] ? j["@graph"] : [j];
16763
+ for (const it of items3) {
16764
+ const t = it?.["@type"];
16765
+ for (const x of Array.isArray(t) ? t : [t]) if (typeof x === "string") schema.push(x);
16766
+ }
16767
+ } catch {
16768
+ schemaErrors++;
16769
+ }
16770
+ }
16771
+ return {
16772
+ url,
16773
+ path: sitePath(url, base) ?? url,
16774
+ title: strip(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(head)?.[1] ?? ""),
16775
+ description: strip(attr2(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["']/i)),
16776
+ canonical: attr2(/<link[^>]+rel=["']canonical["'][^>]+href=["']([^"']+)["']/i),
16777
+ robots: attr2(/<meta[^>]+name=["']robots["'][^>]+content=["']([^"']*)["']/i).toLowerCase(),
16778
+ h1: (body.match(/<h1\b/gi) ?? []).length || (html2.match(/<h1\b/gi) ?? []).length,
16779
+ images: imgs.length,
16780
+ // No alt at all is a problem; alt="" is right for decoration (cover backgrounds), wrong on content pictures.
16781
+ imagesNoAlt: imgs.filter((i) => {
16782
+ if (/aria-hidden|role=["']presentation|wp-block-cover__image-background/i.test(i)) return false;
16783
+ if (!/\balt=/i.test(i)) return true;
16784
+ return /\balt=["']\s*["']/i.test(i) && /\bwp-image-\d+/.test(i);
16785
+ }).length,
16786
+ schema: [...new Set(schema)],
16787
+ schemaErrors,
16788
+ links: links2,
16789
+ words: strip(body).split(" ").filter(Boolean).length
16790
+ };
16791
+ }
16792
+ async function sitemapUrls(base, robotsTxt, max = 500) {
16793
+ const fromRobots = [...robotsTxt.matchAll(/^sitemap:\s*(\S+)/gim)].map((m) => m[1]);
16794
+ const candidates = [...fromRobots, `${base}/wp-sitemap.xml`, `${base}/sitemap_index.xml`, `${base}/sitemap.xml`];
16795
+ for (const sm of candidates) {
16796
+ const r = await get(sm, "follow");
16797
+ if (!r || r.status !== 200 || !/<(urlset|sitemapindex)/i.test(r.text)) continue;
16798
+ const urls = [];
16799
+ const queue = [r.text];
16800
+ let fetched = 0;
16801
+ while (queue.length && urls.length < max && fetched < 30) {
16802
+ const xml = queue.shift();
16803
+ const locs = [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/gi)].map(
16804
+ (m) => m[1].replace(/&amp;/g, "&")
16805
+ );
16806
+ if (/<sitemapindex/i.test(xml)) {
16807
+ for (const l of locs) {
16808
+ const s = await get(l, "follow");
16809
+ fetched++;
16810
+ if (s?.status === 200) queue.push(s.text);
16811
+ }
16812
+ } else urls.push(...locs);
16813
+ }
16814
+ return { urls: [...new Set(urls)].slice(0, max), sitemap: sm };
16815
+ }
16816
+ return { urls: [], sitemap: null };
16817
+ }
16818
+ var AI_BOTS = [
16819
+ "GPTBot",
16820
+ "OAI-SearchBot",
16821
+ "ChatGPT-User",
16822
+ "ClaudeBot",
16823
+ "Claude-SearchBot",
16824
+ "PerplexityBot",
16825
+ "Google-Extended",
16826
+ "CCBot"
16827
+ ];
16828
+ function robotsBlocked(robots, agents) {
16829
+ const groups = [];
16830
+ let cur = null;
16831
+ for (const raw of robots.split(/\r?\n/)) {
16832
+ const line = raw.replace(/#.*/, "").trim();
16833
+ const m = /^([a-z-]+)\s*:\s*(.*)$/i.exec(line);
16834
+ if (!m) continue;
16835
+ const [k, v] = [m[1].toLowerCase(), m[2].trim()];
16836
+ if (k === "user-agent") {
16837
+ if (!cur || cur.rules.length) {
16838
+ cur = { agents: [], rules: [] };
16839
+ groups.push(cur);
16840
+ }
16841
+ cur.agents.push(v.toLowerCase());
16842
+ } else if (cur && (k === "disallow" || k === "allow")) cur.rules.push(`${k}:${v}`);
16843
+ }
16844
+ const blocks = (g) => g.rules.includes("disallow:/") && !g.rules.some((r) => r === "allow:/");
16845
+ return agents.filter((a) => {
16846
+ const own3 = groups.find((g2) => g2.agents.includes(a.toLowerCase()));
16847
+ const g = own3 ?? groups.find((x) => x.agents.includes("*"));
16848
+ return g ? blocks(g) : false;
16849
+ });
16850
+ }
16851
+ function groupFindings(list3, min = 4) {
16852
+ const kinds = /* @__PURE__ */ new Map();
16853
+ for (const f of list3) {
16854
+ const k = f.id.includes(":") ? f.id.split(":")[0] : f.id;
16855
+ kinds.set(k, [...kinds.get(k) ?? [], f]);
16856
+ }
16857
+ const out = [];
16858
+ for (const [k, fs] of kinds) {
16859
+ if (fs.length < min || !fs[0]?.id.includes(":")) {
16860
+ out.push(...fs);
16861
+ continue;
16862
+ }
16863
+ const paths = fs.map((f) => f.id.slice(k.length + 1));
16864
+ const first = fs[0];
16865
+ const label2 = {
16866
+ "title-long": "have SEO titles longer than 65 characters",
16867
+ alt: "have pictures without alt text",
16868
+ desc: "have no meta description",
16869
+ h1: "don't have exactly one H1",
16870
+ thin: "have fewer than 120 words",
16871
+ "noindex-in-sitemap": "are noindex but in the sitemap",
16872
+ canonical: "point their canonical elsewhere",
16873
+ "schema-error": "have broken structured data",
16874
+ "sitemap-status": "are in the sitemap but don't answer 200",
16875
+ orphan: "get no links from other pages",
16876
+ broken: "are linked but broken"
16877
+ };
16878
+ const seoTool = first.tool?.name === "wp_seo_set";
16879
+ out.push({
16880
+ ...first,
16881
+ id: `${k}:*`,
16882
+ title: `${fs.length} pages ${label2[k] ?? first.title}`,
16883
+ why: first.why,
16884
+ fix: `${first.fix.replace(/\.$/, "")}. Pages: ${paths.slice(0, 12).join(", ")}${paths.length > 12 ? ` +${paths.length - 12} more` : ""}.`,
16885
+ ...seoTool ? { tool: { name: "wp_seo_set", args: { items: paths.slice(0, 50).map((x) => ({ page: x })) } } } : {},
16886
+ pages: paths
16887
+ });
16888
+ }
16889
+ return out;
16890
+ }
16891
+ async function techAudit(site, o = {}) {
16892
+ const base = (site.url ?? "").replace(/\/+$/, "");
16893
+ if (!base) throw new Error("The site's address is unknown.");
16894
+ const limit = Math.min(Math.max(o.limit ?? 60, 5), 200);
16895
+ const findings = [];
16896
+ const add = (f) => findings.push(f);
16897
+ const robotsR = await get(`${base}/robots.txt`, "follow");
16898
+ const robots = robotsR?.status === 200 ? robotsR.text : "";
16899
+ const { urls, sitemap } = await sitemapUrls(base, robots);
16900
+ if (!robotsR || robotsR.status !== 200)
16901
+ add({
16902
+ id: "robots-missing",
16903
+ priority: "p3",
16904
+ area: "settings",
16905
+ title: "No robots.txt",
16906
+ why: "Crawlers look for it first.",
16907
+ fix: "WordPress makes one by itself unless a file or plugin blocks it: check the host."
16908
+ });
16909
+ if (/^disallow:\s*\/\s*$/im.test(robots) && robotsBlocked(robots, ["Googlebot"]).length)
16910
+ add({
16911
+ id: "robots-all",
16912
+ priority: "p0",
16913
+ area: "settings",
16914
+ title: "robots.txt blocks Google from the whole site",
16915
+ why: "Nothing can be indexed.",
16916
+ fix: "Turn search engines on (wp_settings_set search_engines true) or fix the robots.txt file.",
16917
+ tool: { name: "wp_settings_set", args: { search_engines: true } }
16918
+ });
16919
+ if (robots && !/^sitemap:/im.test(robots))
16920
+ add({
16921
+ id: "robots-sitemap",
16922
+ priority: "p3",
16923
+ area: "settings",
16924
+ title: "robots.txt doesn't point to the sitemap",
16925
+ why: "It helps every crawler find all pages.",
16926
+ fix: "Maggie Core adds the Sitemap line when search engines are on; otherwise add it to robots.txt."
16927
+ });
16928
+ const aiBlocked = robotsBlocked(robots, AI_BOTS);
16929
+ if (aiBlocked.length)
16930
+ add({
16931
+ id: "ai-crawlers",
16932
+ priority: "p2",
16933
+ area: "settings",
16934
+ title: `AI crawlers are blocked: ${aiBlocked.join(", ")}`,
16935
+ why: "ChatGPT, Claude, Perplexity and Google's AI answers can't read or cite the site.",
16936
+ fix: "Allow them in robots.txt unless the owner chose to block AI."
16937
+ });
16938
+ if (!sitemap)
16939
+ add({
16940
+ id: "sitemap-missing",
16941
+ priority: "p1",
16942
+ area: "settings",
16943
+ title: "No sitemap found",
16944
+ why: "Search engines find new pages slower without one.",
16945
+ fix: "WordPress publishes /wp-sitemap.xml when search engines are on; check nothing turns it off."
16946
+ });
16947
+ const llms = await get(`${base}/llms.txt`, "follow");
16948
+ const hasLlms = !!llms && llms.status === 200 && /^#\s/m.test(llms.text) && !/<html/i.test(llms.text);
16949
+ if (!hasLlms)
16950
+ add({
16951
+ id: "llms-missing",
16952
+ priority: "p3",
16953
+ area: "settings",
16954
+ title: "No llms.txt",
16955
+ why: "A short Markdown map of the site helps AI assistants describe it correctly.",
16956
+ fix: "Generate it from the site.",
16957
+ tool: { name: "wp_llms_txt_set", args: { generate: true } }
16958
+ });
16959
+ const crawl = urls.length ? urls.slice(0, limit) : [`${base}/`];
16960
+ const scans = await pool3(crawl, 6, async (u) => {
16961
+ const r = await get(u);
16962
+ if (!r) return null;
16963
+ if (r.status !== 200) return { ...scanHtml("", u, base), status: r.status, redirect: r.location || void 0 };
16964
+ return { ...scanHtml(r.text, u, base), status: 200 };
16965
+ });
16966
+ const pages = scans.filter(Boolean);
16967
+ const ok2 = pages.filter((p) => p.status === 200);
16968
+ const bad = pages.filter((p) => p.status !== 200);
16969
+ for (const p of bad)
16970
+ add({
16971
+ id: `sitemap-status:${p.path}`,
16972
+ priority: p.status >= 400 ? "p1" : "p2",
16973
+ area: "outside",
16974
+ title: `The sitemap lists ${p.path}, which answers ${p.status}${p.redirect ? ` \u2192 ${p.redirect}` : ""}`,
16975
+ why: "Sitemaps should list only live pages; search engines lose trust in it.",
16976
+ fix: p.status >= 400 ? "Publish the page again, or remove it (wp_post_delete / wp_page_publish)." : "List the final address; the redirect is fine for visitors."
16977
+ });
16978
+ for (const p of ok2) {
16979
+ if (/noindex/.test(p.robots))
16980
+ add({
16981
+ id: `noindex-in-sitemap:${p.path}`,
16982
+ priority: "p1",
16983
+ area: "outside",
16984
+ title: `${p.path} is noindex but in the sitemap`,
16985
+ why: "Mixed signals: either it should be found, or it shouldn't be listed.",
16986
+ fix: 'Remove noindex if the page should rank (wp_seo_set robots "").',
16987
+ tool: { name: "wp_seo_set", args: { page: p.path, robots: "" } }
16988
+ });
16989
+ if (p.canonical && sitePath(p.canonical, base) !== p.path)
16990
+ add({
16991
+ id: `canonical:${p.path}`,
16992
+ priority: "p2",
16993
+ area: "outside",
16994
+ title: `${p.path} points its canonical to ${p.canonical}`,
16995
+ why: "Google will index the other address instead of this page.",
16996
+ fix: 'Clear the custom canonical unless it is on purpose (wp_seo_set canonical "").',
16997
+ tool: { name: "wp_seo_set", args: { page: p.path, canonical: "" } }
16998
+ });
16999
+ if (p.h1 !== 1)
17000
+ add({
17001
+ id: `h1:${p.path}`,
17002
+ priority: "p2",
17003
+ area: "outside",
17004
+ title: `${p.path} has ${p.h1} H1 headings`,
17005
+ why: "One H1 says what the page is about.",
17006
+ fix: p.h1 ? "Make the extra H1s H2 (wp_section_update edits)." : "Give the page a main heading (the hero's title)."
17007
+ });
17008
+ if (p.imagesNoAlt)
17009
+ add({
17010
+ id: `alt:${p.path}`,
17011
+ priority: "p3",
17012
+ area: "outside",
17013
+ title: `${p.path}: ${p.imagesNoAlt} of ${p.images} pictures have no alt text`,
17014
+ why: "Alt text is how search engines, AI and screen readers know what a picture shows.",
17015
+ fix: "Add alt text (wp_section_update images alt, or the media library)."
17016
+ });
17017
+ if (p.schemaErrors)
17018
+ add({
17019
+ id: `schema-error:${p.path}`,
17020
+ priority: "p2",
17021
+ area: "outside",
17022
+ title: `${p.path}: ${p.schemaErrors} structured-data block(s) are not valid JSON`,
17023
+ why: "Google ignores broken structured data.",
17024
+ fix: "Fix or remove the page's custom schema (wp_seo_set schema)."
17025
+ });
17026
+ if (p.words < 120 && !/\?/.test(p.path))
17027
+ add({
17028
+ id: `thin:${p.path}`,
17029
+ priority: "p3",
17030
+ area: "outside",
17031
+ title: `${p.path} has only ${p.words} words`,
17032
+ why: "Very short pages rarely rank or get cited.",
17033
+ fix: "Add useful text: what, for whom, price or next step, questions."
17034
+ });
17035
+ if (!p.description)
17036
+ add({
17037
+ id: `desc:${p.path}`,
17038
+ priority: "p2",
17039
+ area: "outside",
17040
+ title: `${p.path} has no meta description`,
17041
+ why: "Google writes its own snippet, often a poor one.",
17042
+ fix: "Write one (140\u2013160 characters).",
17043
+ tool: { name: "wp_seo_set", args: { page: p.path } }
17044
+ });
17045
+ if (p.title.length > 65)
17046
+ add({
17047
+ id: `title-long:${p.path}`,
17048
+ priority: "p3",
17049
+ area: "outside",
17050
+ title: `${p.path}: title is ${p.title.length} characters`,
17051
+ why: "Search results cut it after about 60.",
17052
+ fix: "Shorten the SEO title.",
17053
+ tool: { name: "wp_seo_set", args: { page: p.path } }
17054
+ });
17055
+ }
17056
+ const dup = (key) => {
17057
+ const by = /* @__PURE__ */ new Map();
17058
+ for (const p of ok2) if (p[key]) by.set(p[key], [...by.get(p[key]) ?? [], p.path]);
17059
+ for (const [v, ps] of by)
17060
+ if (ps.length > 1)
17061
+ add({
17062
+ id: `dup-${key}:${v.slice(0, 40)}`,
17063
+ priority: "p2",
17064
+ area: "outside",
17065
+ title: `${ps.length} pages share the same ${key}: \u201C${v.slice(0, 70)}\u201D`,
17066
+ why: "Search engines can't tell them apart.",
17067
+ fix: `Give each its own ${key} (wp_seo_set items).`,
17068
+ tool: { name: "wp_seo_set", args: { items: ps.slice(0, 10).map((x) => ({ page: x })) } }
17069
+ });
17070
+ };
17071
+ dup("title");
17072
+ dup("description");
17073
+ const home = ok2.find((p) => p.path === "/");
17074
+ if (home && !home.schema.some((t) => /Organization|LocalBusiness|WebSite|Person|Store|Restaurant|Service/i.test(t)))
17075
+ add({
17076
+ id: "schema-home",
17077
+ priority: "p2",
17078
+ area: "outside",
17079
+ title: "The homepage has no Organization / LocalBusiness structured data",
17080
+ why: "It tells Google and AI who the business is, where and how to reach it.",
17081
+ fix: "Fill the business details (wp_seo_site_set business).",
17082
+ tool: { name: "wp_seo_site_set", args: {} }
17083
+ });
17084
+ const inbound = /* @__PURE__ */ new Map();
17085
+ for (const p of ok2)
17086
+ for (const l of new Set(p.links.map((x) => x.path))) if (l !== p.path) inbound.set(l, (inbound.get(l) ?? 0) + 1);
17087
+ const known = new Set(pages.map((p) => p.path));
17088
+ const targets = [...new Set(ok2.flatMap((p) => p.links.map((l) => l.path)))].filter((t) => !known.has(t)).slice(0, 80);
17089
+ const checked = await pool3(targets, 6, async (t) => ({ t, r: await get(`${base}${t}`) }));
17090
+ const broken = checked.filter((c) => c.r && c.r.status >= 400);
17091
+ const redirected = checked.filter((c) => c.r && [301, 302, 307, 308].includes(c.r.status));
17092
+ for (const b of broken) {
17093
+ const from = ok2.filter((p) => p.links.some((l) => l.path === b.t)).map((p) => p.path);
17094
+ add({
17095
+ id: `broken:${b.t}`,
17096
+ priority: "p1",
17097
+ area: "outside",
17098
+ title: `Broken link to ${b.t} (${b.r?.status}) on ${from.slice(0, 3).join(", ")}${from.length > 3 ? ` +${from.length - 3}` : ""}`,
17099
+ why: "Visitors hit a dead end and crawlers waste their visit.",
17100
+ fix: "Point the link to a live page (wp_section_update links) or add a redirect (wp_redirect_set).",
17101
+ tool: { name: "wp_redirect_set", args: { from: b.t } }
17102
+ });
17103
+ }
17104
+ if (redirected.length)
17105
+ add({
17106
+ id: "links-redirected",
17107
+ priority: "p3",
17108
+ area: "outside",
17109
+ title: `${redirected.length} internal links go through a redirect`,
17110
+ why: "Each hop slows visitors and loses a little link value.",
17111
+ fix: `Link straight to the final address: ${redirected.slice(0, 5).map((c) => `${c.t} \u2192 ${c.r?.location}`).join(", ")}.`
17112
+ });
17113
+ const generic = ok2.flatMap(
17114
+ (p) => p.links.filter((l) => /^(click here|here|read more|learn more|more|this|link|點此|更多)$/i.test(l.text)).map(() => p.path)
17115
+ );
17116
+ if (generic.length)
17117
+ add({
17118
+ id: "anchors-generic",
17119
+ priority: "p3",
17120
+ area: "outside",
17121
+ title: `${generic.length} links say only \u201Cread more\u201D, \u201Cclick here\u201D or similar`,
17122
+ why: "Link words tell search engines what the target page is about.",
17123
+ fix: `Use the target's topic as the link text (pages: ${[...new Set(generic)].slice(0, 5).join(", ")}).`
17124
+ });
17125
+ let speed = null;
17126
+ if (o.speed) speed = await pageSpeed(`${base}/`);
17127
+ if (speed?.lcp_ms && Number(speed.lcp_ms) > 2500)
17128
+ add({
17129
+ id: "lcp",
17130
+ priority: Number(speed.lcp_ms) > 4e3 ? "p1" : "p2",
17131
+ area: "outside",
17132
+ title: `The homepage's main content shows after ${(Number(speed.lcp_ms) / 1e3).toFixed(1)} s on phones (LCP)`,
17133
+ why: "Google wants under 2.5 s; slow pages lose visitors and rankings.",
17134
+ fix: "Smaller hero picture (WebP, under 200 KB), fewer fonts and scripts above the fold."
17135
+ });
17136
+ if (speed?.cls != null && Number(speed.cls) > 0.1)
17137
+ add({
17138
+ id: "cls",
17139
+ priority: "p2",
17140
+ area: "outside",
17141
+ title: `The homepage moves while loading (CLS ${speed.cls})`,
17142
+ why: "Google wants under 0.1.",
17143
+ fix: "Give pictures width and height; don't insert banners above content after load."
17144
+ });
17145
+ const order2 = ["p0", "p1", "p2", "p3", "p4"];
17146
+ const grouped = groupFindings(findings);
17147
+ grouped.sort((a, b) => order2.indexOf(a.priority) - order2.indexOf(b.priority));
17148
+ findings.length = 0;
17149
+ findings.push(...grouped);
17150
+ return {
17151
+ site: base,
17152
+ checked: (/* @__PURE__ */ new Date()).toISOString(),
17153
+ summary: {
17154
+ ...Object.fromEntries(order2.map((p) => [p, findings.filter((f) => f.priority === p).length])),
17155
+ sitemap,
17156
+ sitemap_urls: urls.length,
17157
+ crawled: pages.length,
17158
+ live: ok2.length,
17159
+ llms_txt: hasLlms,
17160
+ ai_crawlers_blocked: aiBlocked,
17161
+ internal_links: ok2.reduce((n2, p) => n2 + p.links.length, 0)
17162
+ },
17163
+ pages: ok2.map((p) => ({
17164
+ path: p.path,
17165
+ title: p.title,
17166
+ words: p.words,
17167
+ h1: p.h1,
17168
+ links_out: new Set(p.links.map((l) => l.path)).size,
17169
+ links_in: inbound.get(p.path) ?? 0,
17170
+ schema: p.schema
17171
+ })),
17172
+ findings,
17173
+ ...speed ? { speed } : {},
17174
+ ...urls.length > crawl.length ? { note: `Crawled the first ${crawl.length} of ${urls.length} sitemap addresses (limit up to 200).` } : {}
17175
+ };
17176
+ }
17177
+ async function pageSpeed(url) {
17178
+ const key = globalThis.process?.env?.PAGESPEED_API_KEY;
17179
+ const q3 = new URLSearchParams({ url, strategy: "mobile", category: "performance" });
17180
+ if (key) q3.set("key", key);
17181
+ const r = await fetch(`https://www.googleapis.com/pagespeedonline/v5/runPagespeed?${q3}`, {
17182
+ signal: AbortSignal.timeout(9e4)
17183
+ }).catch(() => null);
17184
+ if (!r || !r.ok) return { error: `PageSpeed Insights didn't answer (${r?.status ?? "timeout"}).` };
17185
+ const j = await r.json();
17186
+ const f = j.loadingExperience?.metrics ?? {};
17187
+ const a = j.lighthouseResult?.audits ?? {};
17188
+ const field = !!f.LARGEST_CONTENTFUL_PAINT_MS;
17189
+ return {
17190
+ source: field ? "real visitors (Chrome UX Report, 28 days)" : "lab test (no real-visitor data yet)",
17191
+ score: Math.round((j.lighthouseResult?.categories?.performance?.score ?? 0) * 100),
17192
+ lcp_ms: field ? f.LARGEST_CONTENTFUL_PAINT_MS?.percentile : Math.round(a["largest-contentful-paint"]?.numericValue ?? 0),
17193
+ cls: field ? (f.CUMULATIVE_LAYOUT_SHIFT_SCORE?.percentile ?? 0) / 100 : Number((a["cumulative-layout-shift"]?.numericValue ?? 0).toFixed(3)),
17194
+ inp_ms: f.INTERACTION_TO_NEXT_PAINT?.percentile ?? null,
17195
+ tbt_ms: Math.round(a["total-blocking-time"]?.numericValue ?? 0)
17196
+ };
17197
+ }
17198
+ var STOP = new Set(
17199
+ "the a an and or of to in for on with by at from is are be your our you we it this that how what why best guide near vs and/or my me us".split(
17200
+ " "
17201
+ )
17202
+ );
17203
+ var tokens = (s) => new Set(
17204
+ s.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/[\s-]+/).filter((w) => w.length > 2 && !STOP.has(w)).map((w) => w.replace(/(ies)$/, "y").replace(/(es|s)$/, ""))
17205
+ );
17206
+ var overlap = (a, b, idf = () => 1) => {
17207
+ let dot = 0;
17208
+ let na = 0;
17209
+ let nb = 0;
17210
+ for (const w of a) {
17211
+ const x = idf(w) ** 2;
17212
+ na += x;
17213
+ if (b.has(w)) dot += x;
17214
+ }
17215
+ for (const w of b) nb += idf(w) ** 2;
17216
+ return dot / Math.sqrt(Math.max(1e-9, na) * Math.max(1e-9, nb));
17217
+ };
17218
+ function contentLinks(raw, base) {
17219
+ const out = /* @__PURE__ */ new Set();
17220
+ for (const m of raw.matchAll(/href=["']([^"'#]+)["']/gi)) {
17221
+ const p = sitePath(m[1], base);
17222
+ if (p) out.add(p);
17223
+ }
17224
+ for (const m of raw.matchAll(/"url":"([^"]+)"/g)) {
17225
+ const p = sitePath(m[1].replace(/\\\//g, "/"), base);
17226
+ if (p) out.add(p);
17227
+ }
17228
+ return out;
17229
+ }
17230
+ var flatMenu = (items3) => items3.flatMap((i) => [{ url: i.url, label: i.label }, ...flatMenu(i.children ?? [])]);
17231
+ async function linksPlan(site, o = {}) {
17232
+ const base = (site.url ?? "").replace(/\/+$/, "");
17233
+ const pages = await listPages(site, { status: "publish", withContent: true });
17234
+ const posts = await all(
17235
+ site,
17236
+ "/wp/v2/posts",
17237
+ {
17238
+ context: "edit",
17239
+ status: "publish",
17240
+ per_page: 100,
17241
+ _fields: "id,link,title,categories,content,meta",
17242
+ orderby: "date",
17243
+ order: "desc"
17244
+ },
17245
+ o.posts ?? 200
17246
+ );
17247
+ const cats = await all(site, "/wp/v2/categories", {
17248
+ per_page: 100,
17249
+ _fields: "id,name,link,count"
17250
+ });
17251
+ const catName = new Map(cats.map((c) => [c.id, c.name]));
17252
+ const settings = await site.request({
17253
+ path: "/wp/v2/settings",
17254
+ query: { _fields: "page_on_front,page_for_posts" }
17255
+ }).then((r) => r.status === 200 ? r.data : {});
17256
+ const docs = [
17257
+ ...pages.map((p) => ({
17258
+ id: p.id,
17259
+ kind: "page",
17260
+ path: sitePath(p.link, base) ?? p.link,
17261
+ url: p.link,
17262
+ title: titleOf(p.title),
17263
+ parent: p.parent,
17264
+ links: contentLinks(p.content?.raw ?? "", base),
17265
+ words: tokens(
17266
+ `${titleOf(p.title)} ${p.slug} ${p.meta?.maggie_seo_title ?? ""} ${p.meta?.maggie_seo_keywords ?? ""}`
17267
+ ),
17268
+ description: String(p.meta?.maggie_seo_description ?? "")
17269
+ })),
17270
+ ...posts.map((p) => ({
17271
+ id: p.id,
17272
+ kind: "post",
17273
+ path: sitePath(p.link, base) ?? p.link,
17274
+ url: p.link,
17275
+ title: p.title.raw ?? "",
17276
+ cats: p.categories.map((c) => catName.get(c) ?? "").filter(Boolean),
17277
+ links: contentLinks(p.content.raw, base),
17278
+ words: tokens(
17279
+ `${p.title.raw ?? ""} ${p.categories.map((c) => catName.get(c) ?? "").join(" ")} ${p.meta?.maggie_seo_keywords ?? ""}`
17280
+ ),
17281
+ description: String(p.meta?.maggie_seo_description ?? "")
17282
+ }))
17283
+ ];
17284
+ const byPath = new Map(docs.map((d) => [d.path, d]));
17285
+ const menu = await menuGet(site).catch(() => null);
17286
+ const menuPaths = new Set(
17287
+ flatMenu(menu?.items ?? []).map((i) => sitePath(i.url, base)).filter(Boolean)
17288
+ );
17289
+ const footer = await partGet(site, "footer").catch(() => null);
17290
+ const footerPaths = footer ? contentLinks(footer.content, base) : /* @__PURE__ */ new Set();
17291
+ const header = await partGet(site, "header").catch(() => null);
17292
+ const headerPaths = header ? contentLinks(header.content, base) : /* @__PURE__ */ new Set();
17293
+ const chrome = /* @__PURE__ */ new Set([...menuPaths, ...footerPaths, ...headerPaths]);
17294
+ const inbound = /* @__PURE__ */ new Map();
17295
+ for (const d of docs)
17296
+ for (const l of d.links) if (l !== d.path) inbound.set(l, /* @__PURE__ */ new Set([...inbound.get(l) ?? [], d.path]));
17297
+ const home = docs.find((d) => d.id === settings.page_on_front && d.kind === "page");
17298
+ const blogPage = docs.find((d) => d.id === settings.page_for_posts && d.kind === "page");
17299
+ const actions = [];
17300
+ const findings = [];
17301
+ const pageDocs = docs.filter((d) => d.kind === "page" && d !== home);
17302
+ const postDocs = docs.filter((d) => d.kind === "post");
17303
+ const menuItems = flatMenu(menu?.items ?? []);
17304
+ const top = (menu?.items ?? []).length;
17305
+ for (const i of menuItems) {
17306
+ const p = sitePath(i.url, base);
17307
+ if (p && p !== "/" && !byPath.has(p) && !/\/(category|tag|author)\//.test(p) && !p.startsWith("/?"))
17308
+ findings.push({
17309
+ id: `menu-dead:${p}`,
17310
+ priority: "p1",
17311
+ area: "outside",
17312
+ title: `The menu links to ${p} (\u201C${i.label}\u201D), which isn't a published page or post`,
17313
+ why: "Visitors hit a dead end from every page.",
17314
+ fix: "Point it to a live page or remove it (wp_menu_set).",
17315
+ tool: { name: "wp_menu_set", args: {} }
17316
+ });
17317
+ }
17318
+ if (top > 7)
17319
+ findings.push({
17320
+ id: "menu-long",
17321
+ priority: "p3",
17322
+ area: "outside",
17323
+ title: `The menu has ${top} top-level items`,
17324
+ why: "More than 7 makes choosing hard; group them under submenus.",
17325
+ fix: "Group related pages under a parent item (wp_menu_set)."
17326
+ });
17327
+ const hubs = pageDocs.filter((d) => pageDocs.some((c) => c.parent === d.id));
17328
+ const topLevel = pageDocs.filter((d) => !d.parent);
17329
+ const wantMenu = [.../* @__PURE__ */ new Set([...hubs, ...topLevel.slice(0, 6)])].filter(
17330
+ (d) => !chrome.has(d.path) && !/privacy|terms|cookie|legal|impressum|datenschutz|thank/i.test(d.path)
17331
+ );
17332
+ if (wantMenu.length)
17333
+ actions.push({
17334
+ type: "menu",
17335
+ why: "Main pages every visitor should reach in one click.",
17336
+ add: wantMenu.slice(0, 6).map((d) => ({ label: d.title, url: d.url })),
17337
+ tool: "wp_menu_set"
17338
+ });
17339
+ if (postDocs.length && blogPage && !chrome.has(blogPage.path))
17340
+ actions.push({
17341
+ type: "menu",
17342
+ why: "The blog isn't reachable from the menu.",
17343
+ add: [{ label: blogPage.title || "Blog", url: blogPage.url }],
17344
+ tool: "wp_menu_set"
17345
+ });
17346
+ const legal = pageDocs.filter(
17347
+ (d) => /privacy|terms|cookie|legal|impressum|datenschutz|accessib/i.test(`${d.path} ${d.title}`)
17348
+ );
17349
+ const contact = pageDocs.filter((d) => /contact|about|book|location|faq/i.test(`${d.path} ${d.title}`));
17350
+ const footerMissing = [...legal, ...contact].filter((d) => !footerPaths.has(d.path));
17351
+ if (footerMissing.length)
17352
+ actions.push({
17353
+ type: "footer",
17354
+ why: "Legal, contact and about pages belong in the footer of every page (trust, and Google's quality raters look for them).",
17355
+ add: footerMissing.slice(0, 8).map((d) => ({ label: d.title, url: d.url })),
17356
+ tool: "wp_footer_set"
17357
+ });
17358
+ for (const hub of hubs) {
17359
+ const kids = pageDocs.filter((c) => c.parent === hub.id);
17360
+ const missing = kids.filter((k) => !hub.links.has(k.path));
17361
+ if (missing.length)
17362
+ actions.push({
17363
+ type: "page_related",
17364
+ page: hub.id,
17365
+ path: hub.path,
17366
+ heading: `More in ${hub.title}`,
17367
+ why: `${hub.title} doesn't link to ${missing.length} of its own sub-pages.`,
17368
+ links: missing.map((k) => ({ url: k.url, label: k.title }))
17369
+ });
17370
+ for (const k of kids)
17371
+ if (!k.links.has(hub.path)) {
17372
+ const sib = kids.filter((s) => s !== k).slice(0, 3);
17373
+ actions.push({
17374
+ type: "page_related",
17375
+ page: k.id,
17376
+ path: k.path,
17377
+ heading: "Related",
17378
+ why: `${k.title} doesn't link back to ${hub.title}${sib.length ? " or its sister pages" : ""}.`,
17379
+ links: [{ url: hub.url, label: hub.title }, ...sib.map((s) => ({ url: s.url, label: s.title }))]
17380
+ });
17381
+ }
17382
+ }
17383
+ const df = /* @__PURE__ */ new Map();
17384
+ for (const d of docs) for (const w of d.words) df.set(w, (df.get(w) ?? 0) + 1);
17385
+ const idf = (w) => Math.log(1 + docs.length / (1 + (df.get(w) ?? 0)));
17386
+ const forPage = /* @__PURE__ */ new Map();
17387
+ for (const post of postDocs) {
17388
+ let best = null;
17389
+ let score = 0;
17390
+ for (const pg of pageDocs) {
17391
+ if (pg === blogPage) continue;
17392
+ const s = overlap(post.words, pg.words, idf);
17393
+ if (s > score) [best, score] = [pg, s];
17394
+ }
17395
+ if (!best || score < 0.3) continue;
17396
+ forPage.set(best, [...forPage.get(best) ?? [], post]);
17397
+ if (!post.links.has(best.path))
17398
+ actions.push({
17399
+ type: "post_link",
17400
+ post: post.id,
17401
+ path: post.path,
17402
+ why: `\u201C${post.title}\u201D is about ${best.title} but doesn't link to that page.`,
17403
+ url: best.url,
17404
+ label: best.title,
17405
+ match: Math.round(score * 100)
17406
+ });
17407
+ }
17408
+ for (const [pg, ps] of forPage) {
17409
+ const missing = ps.filter((p) => !pg.links.has(p.path));
17410
+ if (missing.length >= 2)
17411
+ actions.push({
17412
+ type: "page_related",
17413
+ page: pg.id,
17414
+ path: pg.path,
17415
+ heading: "From the blog",
17416
+ why: `${missing.length} articles about ${pg.title} aren't linked from the page.`,
17417
+ links: missing.slice(0, 5).map((p) => ({ url: p.url, label: p.title }))
17418
+ });
17419
+ }
17420
+ const lonelyPosts = [];
17421
+ for (const d of docs) {
17422
+ if (d === home || d === blogPage) continue;
17423
+ const ins = inbound.get(d.path);
17424
+ if (ins && ins.size || chrome.has(d.path)) continue;
17425
+ if (d.kind === "post") lonelyPosts.push(d);
17426
+ else
17427
+ findings.push({
17428
+ id: `orphan:${d.path}`,
17429
+ priority: "p2",
17430
+ area: "outside",
17431
+ title: `Nothing links to the page \u201C${d.title}\u201D (${d.path})`,
17432
+ why: "Pages that only the sitemap knows are found late and rank poorly.",
17433
+ fix: "Link to it from its parent or a related page, or put it in the menu or footer"
17434
+ });
17435
+ }
17436
+ if (lonelyPosts.length)
17437
+ findings.push({
17438
+ id: "orphan-posts",
17439
+ priority: "p3",
17440
+ area: "outside",
17441
+ title: `${lonelyPosts.length} of ${postDocs.length} articles get no links from pages or other articles (only from the blog list)`,
17442
+ why: "Links from related pages and articles tell search engines which articles matter and keep readers on the site.",
17443
+ fix: "Apply the post_link and page_related actions: each article links to its page, each page shows its articles."
17444
+ });
17445
+ const grouped = groupFindings(findings);
17446
+ findings.length = 0;
17447
+ findings.push(...grouped);
17448
+ return {
17449
+ site: base,
17450
+ counts: {
17451
+ pages: pageDocs.length + (home ? 1 : 0),
17452
+ posts: postDocs.length,
17453
+ menu_items: menuItems.length,
17454
+ footer_links: footerPaths.size,
17455
+ content_links: docs.reduce((n2, d) => n2 + d.links.size, 0),
17456
+ orphan_pages: findings.reduce(
17457
+ (n2, f) => n2 + (f.id.startsWith("orphan:") ? f.pages?.length ?? 1 : 0),
17458
+ 0
17459
+ ),
17460
+ orphan_posts: lonelyPosts.length
17461
+ },
17462
+ action_counts: Object.fromEntries(
17463
+ ["menu", "footer", "page_related", "post_link"].map((t) => [t, actions.filter((x) => x.type === t).length])
17464
+ ),
17465
+ actions: [
17466
+ ...actions.filter((x) => x.type === "menu" || x.type === "footer"),
17467
+ ...actions.filter((x) => x.type === "post_link").sort((x, y) => Number(y.match) - Number(x.match)).slice(0, 30),
17468
+ ...actions.filter((x) => x.type === "page_related").slice(0, 30)
17469
+ ],
17470
+ findings,
17471
+ how: "Apply page_related and post_link actions with wp_internal_links_apply (preview first); menu actions with wp_menu_set, footer with wp_footer_set."
17472
+ };
17473
+ }
17474
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
17475
+ function relatedBlock(heading2, links2) {
17476
+ const items3 = links2.map((l) => `<!-- wp:list-item -->
17477
+ <li><a href="${esc(l.url)}">${esc(l.label)}</a></li>
17478
+ <!-- /wp:list-item -->`).join("\n");
17479
+ return `<!-- wp:group {"metadata":{"name":"Related links","maggie":{"type":"related-links","version":1}},"align":"wide","className":"maggie-related-links","layout":{"type":"constrained"}} -->
17480
+ <div class="wp-block-group alignwide maggie-related-links"><!-- wp:heading {"level":2} -->
17481
+ <h2 class="wp-block-heading">${esc(heading2)}</h2>
17482
+ <!-- /wp:heading -->
17483
+
17484
+ <!-- wp:list -->
17485
+ <ul class="wp-block-list">${items3}</ul>
17486
+ <!-- /wp:list --></div>
17487
+ <!-- /wp:group -->`;
17488
+ }
17489
+ function postLinkBlock(text3, url, label2) {
17490
+ return `<!-- wp:paragraph {"className":"maggie-related-link"} -->
17491
+ <p class="maggie-related-link">${esc(text3)} <a href="${esc(url)}">${esc(label2)}</a></p>
17492
+ <!-- /wp:paragraph -->`;
17493
+ }
17494
+ async function llmsTxt(site, o = {}) {
17495
+ const base = (site.url ?? "").replace(/\/+$/, "");
17496
+ const s = await site.request({
17497
+ path: "/wp/v2/settings",
17498
+ query: { _fields: "title,description,page_on_front,page_for_posts" }
17499
+ }).then((r) => r.status === 200 ? r.data : {});
17500
+ const pages = await listPages(site, { status: "publish" });
17501
+ const posts = await all(
17502
+ site,
17503
+ "/wp/v2/posts",
17504
+ { status: "publish", per_page: 100, _fields: "link,title,excerpt,meta", orderby: "date", order: "desc" },
17505
+ o.posts ?? 25
17506
+ );
17507
+ const desc = (m, fallback = "") => String(m?.maggie_seo_description || fallback).replace(/\s+/g, " ").trim();
17508
+ const home = pages.find((p) => p.id === s.page_on_front);
17509
+ const noise = /privacy|terms|cookie|thank|cart|checkout|my-account|login/i;
17510
+ const visible = pages.filter((p) => p.id !== s.page_on_front && p.id !== s.page_for_posts && !noise.test(p.link));
17511
+ const byParent = /* @__PURE__ */ new Map();
17512
+ for (const p of visible) byParent.set(p.parent, [...byParent.get(p.parent) ?? [], p]);
17513
+ const line = (title, url, d) => `- [${title.replace(/[[\]]/g, "")}](${url})${d ? `: ${d}` : ""}`;
17514
+ const out = [`# ${s.title || base.replace(/^https?:\/\//, "")}`, ""];
17515
+ const summary = desc(home?.meta, s.description ?? "");
17516
+ if (summary) out.push(`> ${summary}`, "");
17517
+ const top = byParent.get(0) ?? [];
17518
+ if (top.length) {
17519
+ out.push("## Pages", "");
17520
+ for (const p of top) {
17521
+ out.push(line(titleOf(p.title), p.link, desc(p.meta)));
17522
+ for (const c of byParent.get(p.id) ?? []) out.push(` ${line(titleOf(c.title), c.link, desc(c.meta))}`);
17523
+ }
17524
+ out.push("");
17525
+ }
17526
+ if (posts.length) {
17527
+ out.push("## Articles", "");
17528
+ for (const p of posts)
17529
+ out.push(
17530
+ line(strip(p.title.rendered ?? ""), p.link, desc(p.meta, strip(p.excerpt?.rendered ?? "").slice(0, 160)))
17531
+ );
17532
+ out.push("");
17533
+ }
17534
+ const legal = pages.filter((p) => /privacy|terms/i.test(p.link));
17535
+ out.push("## Optional", "", line("Sitemap", `${base}/wp-sitemap.xml`, "every page and article"));
17536
+ for (const p of legal) out.push(line(titleOf(p.title), p.link, ""));
17537
+ return `${out.join("\n").replace(/\n{3,}/g, "\n\n").trim()}
17538
+ `;
17539
+ }
17540
+
16071
17541
  // ../../packages/tools/src/wordpress.ts
16072
17542
  var sites = /* @__PURE__ */ new WeakMap();
16073
17543
  function siteOf(ctx) {
@@ -16214,13 +17684,28 @@ var siteTools = [
16214
17684
  }),
16215
17685
  tool({
16216
17686
  name: "wp_site_status",
16217
- description: "The website's WordPress: whether cmo.so can build on it (Administrator login, Maggie Core theme and version, child theme), who outputs SEO, the forms, synced patterns, booking link and phone, page templates. Call first in any site-building conversation.",
17687
+ description: "The website's WordPress: whether cmo.so can build on it (Administrator login, Maggie Core theme and version, child theme), who outputs SEO, the forms, synced patterns, booking link and phone, page templates, and the child theme's guides for agents (DESIGN.md, AGENTS.md, MEMORY.md: follow them). Call first in any site-building conversation.",
16218
17688
  parameters: { type: "object", properties: {} },
16219
17689
  group: "site",
16220
17690
  need: READ,
16221
17691
  risk: "R0",
16222
17692
  gates: ["WP"],
16223
- run: (ctx) => siteStatus(siteOf(ctx))
17693
+ run: async (ctx) => {
17694
+ const site = siteOf(ctx);
17695
+ const st = await siteStatus(site);
17696
+ const guides = await guidesContext(site).then(({ slug, current }) => {
17697
+ const missing = Object.keys(GUIDE_FILES).filter((k) => !current[k].trim());
17698
+ return {
17699
+ child: slug,
17700
+ note: "The owner's notes for agents: follow them for look, scope and taste. They never replace the preview-and-yes step or the safety rules.",
17701
+ design: clip2(current.design),
17702
+ agents: clip2(current.agents),
17703
+ memory: clip2(current.memory),
17704
+ ...missing.length ? { missing: missing.map((k) => GUIDE_FILES[k]), next: "wp_site_guides_set init: true writes them." } : {}
17705
+ };
17706
+ }).catch((e) => ({ unavailable: e.message }));
17707
+ return { ...st, site_guides: guides };
17708
+ }
16224
17709
  }),
16225
17710
  tool({
16226
17711
  name: "wp_site_map",
@@ -17134,6 +18619,59 @@ async function childSlug(site, slug) {
17134
18619
  throw new Error("No Maggie child theme is active here: name one (slug), or create one with wp_child_theme_create.");
17135
18620
  return active.slug;
17136
18621
  }
18622
+ var GUIDES_MIN = [0, 13];
18623
+ var atLeast = (v, [maj, min]) => {
18624
+ const [a = 0, b = 0] = v.split(".").map(Number);
18625
+ return a > (maj ?? 0) || a === maj && b >= (min ?? 0);
18626
+ };
18627
+ async function guidesContext(site, slugArg) {
18628
+ const slug = await childSlug(site, slugArg);
18629
+ const info = await childInfo(site, slug);
18630
+ const parent = String(info.parent?.version ?? "0");
18631
+ if (!atLeast(parent, GUIDES_MIN))
18632
+ throw new Error(
18633
+ `DESIGN.md, AGENTS.md and MEMORY.md need Maggie Core 0.13 or later (the site has ${parent}): update it with wp_theme_update first.`
18634
+ );
18635
+ const files = info.files ?? {};
18636
+ const current = Object.fromEntries(
18637
+ Object.entries(GUIDE_FILES).map(([k, f]) => [k, files[f] ?? ""])
18638
+ );
18639
+ return { slug, current };
18640
+ }
18641
+ async function siteFacts(site) {
18642
+ const s = await site.request({ path: "/maggie-core/v1/site" });
18643
+ const t = await site.request({ path: "/wp/v2/settings", query: { _fields: "title" } }).then((r) => r.status === 200 ? r.data.title : "");
18644
+ return {
18645
+ siteName: t || site.url?.replace(/^https?:\/\//, "") || "This website",
18646
+ frontPage: s.status === 200 ? s.data.front_page ?? null : null,
18647
+ maggiePress: s.status === 200 ? !!s.data.maggie_press : false
18648
+ };
18649
+ }
18650
+ async function guidesWrite(site, slug, files) {
18651
+ const out = {};
18652
+ for (const [k, text3] of Object.entries(files))
18653
+ out[GUIDE_FILES[k]] = checkGuide(GUIDE_FILES[k], text3);
18654
+ if (!Object.keys(out).length) throw new Error("Nothing to change.");
18655
+ return call(site, {
18656
+ method: "POST",
18657
+ path: "/maggie-core/v1/child-theme",
18658
+ body: { slug, files: out, delete: [] }
18659
+ });
18660
+ }
18661
+ async function guidesInit(site, slug, current) {
18662
+ const facts = await siteFacts(site);
18663
+ const files = {};
18664
+ if (!current.design.trim()) files.design = await designMd(site, { ...facts, child: slug });
18665
+ if (!current.agents.trim()) files.agents = agentsTemplate(facts.siteName);
18666
+ if (!current.memory.trim()) files.memory = memoryTemplate();
18667
+ if (!Object.keys(files).length) return null;
18668
+ return {
18669
+ ...await guidesWrite(site, slug, files),
18670
+ created: Object.keys(files).map((k) => GUIDE_FILES[k])
18671
+ };
18672
+ }
18673
+ var clip2 = (t, n2 = 6e3) => t.length > n2 ? `${t.slice(0, n2)}
18674
+ \u2026 (${t.length - n2} more characters: wp_site_guides_get)` : t;
17137
18675
  async function homeShape(site) {
17138
18676
  if (!site.fetchPage || !site.url) return null;
17139
18677
  const r = await site.fetchPage(`${site.url}/?maggie-check=${Date.now()}`).catch(() => null);
@@ -17227,9 +18765,11 @@ var childTools = [
17227
18765
  path: "/maggie-core/v1/child-theme",
17228
18766
  body: { slug: a.slug, name: a.name, from_site: a.from_site !== false }
17229
18767
  });
18768
+ const guides = await guidesContext(site, out.slug).then(({ slug, current }) => guidesInit(site, slug, current)).then((r) => r ? { guides: r.created } : {}).catch((e) => ({ guides_note: e.message }));
17230
18769
  if (!a.activate)
17231
18770
  return {
17232
18771
  ...out,
18772
+ ...guides,
17233
18773
  next: "Switch to it with wp_child_theme_activate when ready (the tool checks the homepage looks the same)."
17234
18774
  };
17235
18775
  const before = await homeShape(site);
@@ -17238,7 +18778,7 @@ var childTools = [
17238
18778
  path: "/maggie-core/v1/child-theme/activate",
17239
18779
  body: { slug: out.slug }
17240
18780
  });
17241
- return { ...out, activated: act, check: compareShapes(before, await homeShape(site)) };
18781
+ return { ...out, ...guides, activated: act, check: compareShapes(before, await homeShape(site)) };
17242
18782
  }
17243
18783
  }),
17244
18784
  tool({
@@ -17430,6 +18970,114 @@ var childTools = [
17430
18970
  };
17431
18971
  }
17432
18972
  }),
18973
+ tool({
18974
+ name: "wp_site_guides_get",
18975
+ description: "The child theme's guides for agents in full: DESIGN.md (the site's look and the owner's design rules), AGENTS.md (how agents work on this site, what not to touch) and MEMORY.md (the owner's preferences and don'ts). Follow them; they never replace the preview-and-yes step or the safety rules.",
18976
+ parameters: { type: "object", properties: { slug: str2("The child theme (default the active one).") } },
18977
+ group: "site",
18978
+ need: READ,
18979
+ risk: "R0",
18980
+ gates: ["WP"],
18981
+ run: async (ctx, a) => {
18982
+ const { slug, current } = await guidesContext(siteOf(ctx), a.slug);
18983
+ return {
18984
+ child: slug,
18985
+ "DESIGN.md": current.design || null,
18986
+ "AGENTS.md": current.agents || null,
18987
+ "MEMORY.md": current.memory || null,
18988
+ ...!current.design || !current.agents || !current.memory ? { next: "wp_site_guides_set init: true writes the missing ones." } : {}
18989
+ };
18990
+ }
18991
+ }),
18992
+ tool({
18993
+ name: "wp_site_guides_set",
18994
+ description: `Write the child theme's guides (Markdown): design_md, agents_md, memory_md replace a file; refresh_design rewrites DESIGN.md from the live site (colours, fonts, widths, padding, homepage sections) and keeps its "## Rules" section; init writes the missing files from templates. Files are public on the site, so passwords, keys and tokens are refused. Backups as for every child file (wp_child_theme_restore).`,
18995
+ parameters: {
18996
+ type: "object",
18997
+ properties: {
18998
+ slug: str2("The child theme (default the active one)."),
18999
+ design_md: str2("New DESIGN.md."),
19000
+ agents_md: str2("New AGENTS.md."),
19001
+ memory_md: str2("New MEMORY.md."),
19002
+ refresh_design: bool("Rewrite DESIGN.md from the site, keeping its Rules section."),
19003
+ init: bool("Write the missing guides from templates.")
19004
+ }
19005
+ },
19006
+ group: "site",
19007
+ need: WRITE,
19008
+ risk: "W2",
19009
+ gates: [...GATES],
19010
+ confirm: (a, lang) => {
19011
+ const what = [
19012
+ a.design_md || a.refresh_design ? "DESIGN.md" : "",
19013
+ a.agents_md ? "AGENTS.md" : "",
19014
+ a.memory_md ? "MEMORY.md" : "",
19015
+ a.init ? "the missing guides" : ""
19016
+ ].filter(Boolean);
19017
+ return say(
19018
+ lang,
19019
+ `Write ${what.join(", ") || "the guides"} in your website's child theme (public files; a backup is kept).`,
19020
+ `\u5BEB\u5165\u7DB2\u7AD9\u5B50\u4E3B\u984C\u7684 ${what.join("\u3001") || "\u6307\u5357\u6A94"}\uFF08\u516C\u958B\u6A94\u6848\uFF1B\u6703\u4FDD\u7559\u5099\u4EFD\uFF09\u3002`
19021
+ );
19022
+ },
19023
+ run: async (ctx, a) => {
19024
+ const site = siteOf(ctx);
19025
+ const { slug, current } = await guidesContext(site, a.slug);
19026
+ const files = {};
19027
+ if (typeof a.agents_md === "string") files.agents = a.agents_md;
19028
+ if (typeof a.memory_md === "string") files.memory = a.memory_md;
19029
+ if (typeof a.design_md === "string") files.design = a.design_md;
19030
+ if (a.refresh_design)
19031
+ files.design = await designMd(site, {
19032
+ ...await siteFacts(site),
19033
+ child: slug,
19034
+ current: files.design ?? current.design
19035
+ });
19036
+ const wrote = Object.keys(files).length ? await guidesWrite(site, slug, files) : null;
19037
+ const init = a.init ? await guidesInit(site, slug, { ...current, ...files }) : null;
19038
+ if (!wrote && !init) throw new Error(a.init ? "All three guides already exist." : "Nothing to change.");
19039
+ return {
19040
+ child: slug,
19041
+ changed: [...wrote?.changed ?? [], ...init?.changed ?? []],
19042
+ backup: wrote?.backup ?? init?.backup ?? null,
19043
+ ...a.refresh_design ? { design_md: files.design } : {},
19044
+ undo: "wp_child_theme_restore with the backup"
19045
+ };
19046
+ }
19047
+ }),
19048
+ tool({
19049
+ name: "wp_site_memory_add",
19050
+ description: `Remember something the owner said about this website in the child theme's MEMORY.md, dated, newest first: kind prefer (a preference: "short headlines"), avoid (a don't: "never use stock photos of people") or note. Use it whenever the owner states a lasting preference or a don't. Public file: no passwords, keys or personal details.`,
19051
+ parameters: {
19052
+ type: "object",
19053
+ properties: {
19054
+ kind: { type: "string", enum: ["prefer", "avoid", "note"], description: "prefer, avoid (don't) or note." },
19055
+ text: str2("One line, in the owner's words."),
19056
+ slug: str2("The child theme (default the active one).")
19057
+ },
19058
+ required: ["kind", "text"]
19059
+ },
19060
+ group: "site",
19061
+ need: WRITE,
19062
+ risk: "W2",
19063
+ gates: [...GATES],
19064
+ confirm: (a, lang) => say(
19065
+ lang,
19066
+ `Remember for this website (${a.kind === "avoid" ? "don't" : a.kind === "note" ? "note" : "preference"}): ${q2(a.text, "")}.`,
19067
+ `\u8A18\u4F4F\u9019\u500B\u7DB2\u7AD9\u7684${a.kind === "avoid" ? "\u7981\u5FCC" : a.kind === "note" ? "\u5099\u8A3B" : "\u504F\u597D"}\uFF1A${q2(a.text, "")}\u3002`
19068
+ ),
19069
+ run: async (ctx, a) => {
19070
+ const site = siteOf(ctx);
19071
+ const text3 = String(a.text ?? "").trim();
19072
+ if (!text3) throw new Error("text: what to remember.");
19073
+ if (text3.length > 500) throw new Error("text: one line, under 500 characters.");
19074
+ const kind = ["prefer", "avoid", "note"].includes(String(a.kind)) ? a.kind : "note";
19075
+ const { slug, current } = await guidesContext(site, a.slug);
19076
+ const next = memoryAdd(current.memory, kind, text3);
19077
+ const out = await guidesWrite(site, slug, { memory: next });
19078
+ return { child: slug, remembered: { kind, text: text3 }, backup: out.backup, "MEMORY.md": next };
19079
+ }
19080
+ }),
17433
19081
  tool({
17434
19082
  name: "wp_child_theme_activate",
17435
19083
  description: "Switch the site to a Maggie child theme, or back to Maggie Core (slug maggie-core). Checks the homepage before and after (words, fonts, brand colours) and reports differences. WordPress keeps Global Styles and edited header/footer per theme: a child made with wp_child_theme_create from the site carries them; switching back to Maggie Core brings its own back.",
@@ -18391,8 +20039,276 @@ var fullTools = [
18391
20039
  }
18392
20040
  })
18393
20041
  ];
20042
+ var securityTools = [
20043
+ tool({
20044
+ name: "wp_security_scan",
20045
+ description: "Security check of the connected WordPress site: plugins, themes and WordPress against known vulnerabilities (WPVulnerability), available updates and plugins closed on WordPress.org; with Maggie Core 0.14+ also PHP/database end of life, risky settings (errors shown, open registration, file editing, XML-RPC), Administrators and old application passwords, and WP-Cron jobs (late, or left by removed plugins); from outside: security headers, public .env/.git/config backups/error logs, login-name leaks. Findings are ranked p0 (fix today) \u2026 p4 (for information), each with why and the fix (a tool when one can do it). Read-only.",
20046
+ parameters: {
20047
+ type: "object",
20048
+ properties: {
20049
+ vulnerabilities: bool("Check known vulnerabilities (default true)."),
20050
+ outside: bool("Check from outside like a visitor (default true).")
20051
+ }
20052
+ },
20053
+ group: "site",
20054
+ need: READ,
20055
+ risk: "R0",
20056
+ gates: ["WP"],
20057
+ run: (ctx, a) => securityScan(siteOf(ctx), { vulnerabilities: a.vulnerabilities !== false, outside: a.outside !== false })
20058
+ }),
20059
+ tool({
20060
+ name: "wp_plugin_update",
20061
+ description: "Update one installed plugin to its latest version (plugin id from wp_plugins_list or wp_security_scan, e.g. wpforms-lite/wpforms), then check the homepage still opens. Needs Maggie Core 0.14+. WordPress keeps no copy of the old version: for a big plugin (shop, page builder) suggest a backup first.",
20062
+ parameters: { type: "object", properties: { plugin: str2("Plugin id (folder/file).") }, required: ["plugin"] },
20063
+ group: "site",
20064
+ need: WRITE,
20065
+ risk: "W3",
20066
+ gates: [...GATES],
20067
+ confirm: (a, lang) => say(
20068
+ lang,
20069
+ `Update the plugin ${q2(a.plugin, "")} on your website to its latest version (the old version is not kept).`,
20070
+ `\u628A\u7DB2\u7AD9\u4E0A\u7684\u63D2\u4EF6 ${q2(a.plugin, "")} \u66F4\u65B0\u5230\u6700\u65B0\u7248\uFF08\u4E0D\u4FDD\u7559\u820A\u7248\uFF09\u3002`
20071
+ ),
20072
+ run: async (ctx, a) => {
20073
+ const site = siteOf(ctx);
20074
+ const r = await call(site, {
20075
+ method: "POST",
20076
+ path: "/maggie-core/v1/plugins/update",
20077
+ body: { plugin: String(a.plugin ?? "").replace(/\.php$/, "") }
20078
+ });
20079
+ const home = site.url ? await check(site, `${site.url}/`, "publish") : null;
20080
+ return {
20081
+ ...r,
20082
+ check: home,
20083
+ ...home && !home.ok ? {
20084
+ warning: "The homepage has a problem after the update: deactivate the plugin (wp_plugin_set inactive) and tell the owner."
20085
+ } : {}
20086
+ };
20087
+ }
20088
+ }),
20089
+ tool({
20090
+ name: "wp_cron_unschedule",
20091
+ description: "Remove a WP-Cron job that nothing runs any more (left by a removed plugin; wp_security_scan lists them). WordPress's own jobs and jobs a plugin still handles are refused. Needs Maggie Core 0.14+.",
20092
+ parameters: { type: "object", properties: { hook: str2("The job's hook name.") }, required: ["hook"] },
20093
+ group: "site",
20094
+ need: WRITE,
20095
+ risk: "W2",
20096
+ gates: [...GATES],
20097
+ confirm: (a, lang) => say(
20098
+ lang,
20099
+ `Remove the scheduled job ${q2(a.hook, "")} from your website (nothing runs it any more).`,
20100
+ `\u79FB\u9664\u7DB2\u7AD9\u4E0A\u5DF2\u7121\u7A0B\u5F0F\u8655\u7406\u7684\u6392\u7A0B\u5DE5\u4F5C ${q2(a.hook, "")}\u3002`
20101
+ ),
20102
+ run: (ctx, a) => call(siteOf(ctx), {
20103
+ method: "POST",
20104
+ path: "/maggie-core/v1/cron/unschedule",
20105
+ body: { hook: String(a.hook ?? "") }
20106
+ })
20107
+ })
20108
+ ];
20109
+ var LINK_ACTION = obj("One action from wp_internal_links_plan.", {
20110
+ type: { type: "string", enum: ["page_related", "post_link"], description: "page_related or post_link." },
20111
+ page: int2("page_related: the page id."),
20112
+ heading: str2(`page_related: the band's heading, e.g. "Related" or "From the blog".`),
20113
+ links: arr("page_related: links to list.", obj("", { url: str2(""), label: str2("") })),
20114
+ post: int2("post_link: the article id."),
20115
+ url: str2("post_link: the page to link to."),
20116
+ label: str2("post_link: the link text (the page's topic)."),
20117
+ text: str2('post_link: words before the link (default "Related:").')
20118
+ });
20119
+ function withRelated(blocks, heading2, links2) {
20120
+ const band2 = parse(relatedBlock(heading2, links2)).filter((b) => b.name);
20121
+ const isBand = (b) => String(b.attrs.className ?? "").includes("maggie-related-links") && serialize([b]).includes(`>${heading2.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</h2>`);
20122
+ const at = blocks.findIndex(isBand);
20123
+ if (at >= 0) return [...blocks.slice(0, at), ...band2, ...blocks.slice(at + 1)];
20124
+ const real = blocks.map((b, i) => [b, i]).filter(([b]) => b.name);
20125
+ const last = real[real.length - 1];
20126
+ const lastType = last ? classify(last[0], "main") : "";
20127
+ if (last && /cta|form|map-contact|contact/.test(lastType))
20128
+ return [...blocks.slice(0, last[1]), ...band2, ...blocks.slice(last[1])];
20129
+ return [...blocks, ...band2];
20130
+ }
20131
+ var seoTechTools = [
20132
+ tool({
20133
+ name: "wp_seo_tech_audit",
20134
+ description: "Technical SEO check of the connected site, like a crawler: robots.txt (sitemap line, Google or AI crawlers blocked), the sitemap and every page it lists (status, redirects, noindex in the sitemap, canonicals pointing elsewhere, H1 count, missing or duplicate titles and descriptions, long titles, pictures without alt text, broken structured data, thin pages), broken and redirected internal links, generic link words, llms.txt; speed: true adds Core Web Vitals for the homepage (PageSpeed Insights). Findings ranked p0\u2026p4 with the fix and a tool when one can do it. Read-only. Internal-link layout: wp_internal_links_plan.",
20135
+ parameters: {
20136
+ type: "object",
20137
+ properties: {
20138
+ limit: int2("Pages to crawl from the sitemap (default 60, max 200)."),
20139
+ speed: bool("Also measure the homepage's speed on phones (slower, about 30 s).")
20140
+ }
20141
+ },
20142
+ group: "site",
20143
+ need: READ,
20144
+ risk: "R0",
20145
+ gates: ["WP"],
20146
+ run: (ctx, a) => techAudit(siteOf(ctx), { limit: typeof a.limit === "number" ? a.limit : void 0, speed: !!a.speed })
20147
+ }),
20148
+ tool({
20149
+ name: "wp_internal_links_plan",
20150
+ description: "Plan the site's internal links from its own pages, articles, menu, header and footer: menu items that lead nowhere, main pages missing from the menu, legal/contact/about pages missing from the footer, hub pages that don't list their sub-pages and sub-pages that don't link back, articles that don't link to the page they are about (matched by topic) and pages that don't show their articles, and pages or articles nothing links to. Returns actions ready for wp_internal_links_apply (page_related, post_link) or wp_menu_set / wp_footer_set. Read-only.",
20151
+ parameters: { type: "object", properties: { posts: int2("Articles to include (default 200, newest first).") } },
20152
+ group: "site",
20153
+ need: READ,
20154
+ risk: "R0",
20155
+ gates: ["WP"],
20156
+ run: (ctx, a) => linksPlan(siteOf(ctx), { posts: typeof a.posts === "number" ? a.posts : void 0 })
20157
+ }),
20158
+ tool({
20159
+ name: "wp_internal_links_apply",
20160
+ description: 'Apply internal-link actions from wp_internal_links_plan: page_related puts a "Related" band (heading + list of links) in a page, replacing its own earlier band with the same heading, placed before a closing call-to-action; post_link adds one "Related: <page>" line at the end of an article (replacing its earlier one). preview: true shows the changes and saves nothing. Pages: wp_page_undo; articles: their revisions.',
20161
+ parameters: {
20162
+ type: "object",
20163
+ properties: { actions: arr("Up to 20 actions.", LINK_ACTION), preview: PREVIEW },
20164
+ required: ["actions"]
20165
+ },
20166
+ group: "site",
20167
+ need: WRITE,
20168
+ risk: "W3",
20169
+ gates: [...GATES],
20170
+ confirm: (a, lang) => {
20171
+ const n2 = Array.isArray(a.actions) ? a.actions.length : 0;
20172
+ return say(
20173
+ lang,
20174
+ `Add internal links on your website (${n2} ${n2 === 1 ? "change" : "changes"}: related-links bands on pages, a related line at the end of articles).`,
20175
+ `\u5728\u7DB2\u7AD9\u4E0A\u52A0\u5165\u5167\u90E8\u9023\u7D50\uFF08${n2} \u9805\uFF1A\u9801\u9762\u7684\u76F8\u95DC\u9023\u7D50\u5340\u584A\u3001\u6587\u7AE0\u7D50\u5C3E\u7684\u76F8\u95DC\u9023\u7D50\uFF09\u3002`
20176
+ );
20177
+ },
20178
+ run: async (ctx, a) => {
20179
+ const site = siteOf(ctx);
20180
+ const acts = Array.isArray(a.actions) ? a.actions : [];
20181
+ if (!acts.length) throw new Error("actions: give at least one action from wp_internal_links_plan.");
20182
+ if (acts.length > 20) throw new Error("actions: up to 20 at a time.");
20183
+ const results = [];
20184
+ const byPage = /* @__PURE__ */ new Map();
20185
+ for (const x of acts) {
20186
+ if (x.type === "page_related") {
20187
+ if (!x.page || !x.links?.length) throw new Error("page_related needs page and links.");
20188
+ byPage.set(x.page, [...byPage.get(x.page) ?? [], x]);
20189
+ } else if (x.type === "post_link") {
20190
+ if (!x.post || !x.url || !x.label) throw new Error("post_link needs post, url and label.");
20191
+ } else throw new Error(`Unknown action type ${x.type}.`);
20192
+ }
20193
+ for (const [page, list3] of byPage) {
20194
+ const r = await changePage(ctx, { page, preview: !!a.preview }, (blocks) => {
20195
+ let next = blocks;
20196
+ for (const x of list3)
20197
+ next = withRelated(next, (x.heading || "Related").slice(0, 80), (x.links ?? []).slice(0, 12));
20198
+ return { blocks: next, note: { related: list3.map((x) => x.heading || "Related") } };
20199
+ });
20200
+ results.push({ type: "page_related", page_id: page, ...r });
20201
+ }
20202
+ for (const x of acts.filter((y) => y.type === "post_link")) {
20203
+ const post = await call(site, {
20204
+ path: `/wp/v2/posts/${Number(x.post)}`,
20205
+ query: { context: "edit", _fields: "id,link,content,modified" }
20206
+ });
20207
+ const kept = parse(post.content.raw).filter(
20208
+ (b) => !(b.name === "core/paragraph" && String(b.attrs.className ?? "").includes("maggie-related-link"))
20209
+ );
20210
+ const line = parse(postLinkBlock(x.text || "Related:", String(x.url), String(x.label))).filter((b) => b.name);
20211
+ const content = serialize([...kept, ...line]);
20212
+ if (a.preview) {
20213
+ results.push({
20214
+ type: "post_link",
20215
+ post: post.id,
20216
+ path: post.link,
20217
+ preview: true,
20218
+ adds: `${x.text || "Related:"} ${x.label} \u2192 ${x.url}`
20219
+ });
20220
+ continue;
20221
+ }
20222
+ const saved = await call(site, {
20223
+ method: "POST",
20224
+ path: `/wp/v2/posts/${post.id}`,
20225
+ query: { _fields: "id,link,modified" },
20226
+ body: { content }
20227
+ });
20228
+ results.push({
20229
+ type: "post_link",
20230
+ post: saved.id,
20231
+ path: saved.link,
20232
+ saved: true,
20233
+ modified: saved.modified,
20234
+ link: { url: x.url, label: x.label }
20235
+ });
20236
+ }
20237
+ return {
20238
+ results,
20239
+ ...a.preview ? { preview: true } : { undo: "Pages: wp_page_undo; articles: restore the earlier revision in the editor." }
20240
+ };
20241
+ }
20242
+ }),
20243
+ tool({
20244
+ name: "wp_llms_txt_get",
20245
+ description: "The site's llms.txt (a Markdown map of the site for AI assistants, served at /llms.txt): the saved text, whether /llms.txt answers, and whether a file on the server overrides it. Needs Maggie Core 0.14+.",
20246
+ parameters: { type: "object", properties: {} },
20247
+ group: "site",
20248
+ need: READ,
20249
+ risk: "R0",
20250
+ gates: ["WP"],
20251
+ run: async (ctx) => {
20252
+ const site = siteOf(ctx);
20253
+ const saved = await call(site, { path: "/maggie-core/v1/llms" });
20254
+ const live = site.url ? await fetch(`${site.url}/llms.txt`, { signal: AbortSignal.timeout(1e4) }).then(async (r) => ({ status: r.status, same: r.ok && (await r.text()).trim() === saved.text.trim() })).catch(() => null) : null;
20255
+ return {
20256
+ ...saved,
20257
+ live,
20258
+ ...saved.file ? {
20259
+ note: "A real llms.txt file on the server is served instead of the saved text: delete it at the host to use this one."
20260
+ } : {}
20261
+ };
20262
+ }
20263
+ }),
20264
+ tool({
20265
+ name: "wp_llms_txt_set",
20266
+ description: `Write the site's llms.txt (served at /llms.txt): generate: true builds it from the site (name and summary, pages with their SEO descriptions grouped under their parents, the latest articles, sitemap); or give text (Markdown); "" turns it off. preview: true returns the text without saving. Needs Maggie Core 0.14+.`,
20267
+ parameters: {
20268
+ type: "object",
20269
+ properties: {
20270
+ generate: bool("Build it from the site."),
20271
+ text: str2("The llms.txt Markdown to save."),
20272
+ posts: int2("Articles to list when generating (default 25)."),
20273
+ preview: PREVIEW
20274
+ }
20275
+ },
20276
+ group: "site",
20277
+ need: WRITE,
20278
+ risk: "W2",
20279
+ gates: [...GATES],
20280
+ confirm: (a, lang) => say(
20281
+ lang,
20282
+ a.text === "" ? "Turn off your website's llms.txt." : "Write your website's llms.txt (the map of the site for AI assistants, at /llms.txt).",
20283
+ a.text === "" ? "\u95DC\u9589\u7DB2\u7AD9\u7684 llms.txt\u3002" : "\u5BEB\u5165\u7DB2\u7AD9\u7684 llms.txt\uFF08\u7D66 AI \u52A9\u7406\u7684\u7DB2\u7AD9\u5730\u5716\uFF0C\u4F4D\u65BC /llms.txt\uFF09\u3002"
20284
+ ),
20285
+ run: async (ctx, a) => {
20286
+ const site = siteOf(ctx);
20287
+ const text3 = typeof a.text === "string" ? a.text : a.generate ? await llmsTxt(site, { posts: typeof a.posts === "number" ? a.posts : void 0 }) : null;
20288
+ if (text3 == null) throw new Error("Give text, or generate: true.");
20289
+ if (/<\?(php|=)?|<script\b/i.test(text3)) throw new Error("llms.txt: plain Markdown only.");
20290
+ if (a.preview) return { preview: true, text: text3, characters: text3.length };
20291
+ const r = await call(site, {
20292
+ method: "POST",
20293
+ path: "/maggie-core/v1/llms",
20294
+ body: { text: text3 }
20295
+ });
20296
+ return {
20297
+ saved: r.saved,
20298
+ url: r.url,
20299
+ characters: text3.length,
20300
+ before_characters: r.before.length,
20301
+ ...r.file ? { note: "A real llms.txt file on the server is served instead: delete it at the host." } : {},
20302
+ undo: r.before ? "wp_llms_txt_set text with the earlier text (before is kept in this result)" : 'wp_llms_txt_set text ""',
20303
+ before: r.before
20304
+ };
20305
+ }
20306
+ })
20307
+ ];
18394
20308
  var wordpressTools = [
18395
20309
  ...fullTools,
20310
+ ...securityTools,
20311
+ ...seoTechTools,
18396
20312
  ...siteTools,
18397
20313
  ...pageTools,
18398
20314
  ...sectionTools,
@@ -18470,7 +20386,7 @@ __export(util_exports, {
18470
20386
  defineLazy: () => defineLazy,
18471
20387
  defineLazyInternal: () => defineLazyInternal,
18472
20388
  derived: () => derived,
18473
- esc: () => esc,
20389
+ esc: () => esc2,
18474
20390
  escapeRegex: () => escapeRegex,
18475
20391
  explicitlyAborted: () => explicitlyAborted,
18476
20392
  extend: () => extend,
@@ -18701,7 +20617,7 @@ function randomString(length = 10) {
18701
20617
  }
18702
20618
  return str3;
18703
20619
  }
18704
- function esc(str3) {
20620
+ function esc2(str3) {
18705
20621
  return JSON.stringify(str3);
18706
20622
  }
18707
20623
  function slugify(input) {
@@ -20850,14 +22766,14 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
20850
22766
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
20851
22767
  const sh = desc?.get ? desc.get.raw : def.shape ?? {};
20852
22768
  if (sh) {
20853
- const get = () => {
22769
+ const get2 = () => {
20854
22770
  const newSh = { ...sh };
20855
22771
  Object.defineProperty(def, "shape", { value: newSh });
20856
- get.raw = newSh;
22772
+ get2.raw = newSh;
20857
22773
  return newSh;
20858
22774
  };
20859
- get.raw = sh;
20860
- Object.defineProperty(def, "shape", { get });
22775
+ get2.raw = sh;
22776
+ Object.defineProperty(def, "shape", { get: get2 });
20861
22777
  }
20862
22778
  const _normalized = cached(() => normalizeDef(def));
20863
22779
  defineLazyInternal(inst, "propValues", (zod) => {
@@ -20956,7 +22872,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
20956
22872
  if (key === "__proto__")
20957
22873
  continue;
20958
22874
  const id = ids2[key];
20959
- const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
22875
+ const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc2(key);
20960
22876
  const isPresent = `${k} in input`;
20961
22877
  const schema = shape[key];
20962
22878
  const optin = schema?._zod?.optin;
@@ -23928,7 +25844,7 @@ var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
23928
25844
  var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
23929
25845
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
23930
25846
  var encode2 = /* @__PURE__ */ _encode(ZodRealError);
23931
- var decode3 = /* @__PURE__ */ _decode(ZodRealError);
25847
+ var decode4 = /* @__PURE__ */ _decode(ZodRealError);
23932
25848
  var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
23933
25849
  var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
23934
25850
  var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
@@ -24088,7 +26004,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
24088
26004
  return encode2(this, data, params, { callee: _encode2 });
24089
26005
  },
24090
26006
  decode: function _decode2(data, params) {
24091
- return decode3(this, data, params, { callee: _decode2 });
26007
+ return decode4(this, data, params, { callee: _decode2 });
24092
26008
  },
24093
26009
  encodeAsync: async function _encodeAsync2(data, params) {
24094
26010
  return await encodeAsync2(this, data, params, { callee: _encodeAsync2 });
@@ -28973,7 +30889,7 @@ var fileStore = () => {
28973
30889
  const file = join(configDir(), "credentials.json");
28974
30890
  return {
28975
30891
  load: () => readJson(file),
28976
- save: (tokens) => writePrivate(file, tokens),
30892
+ save: (tokens2) => writePrivate(file, tokens2),
28977
30893
  clear: () => rm(file, { force: true })
28978
30894
  };
28979
30895
  };